euv-core 0.52.1

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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
use super::*;

/// Shared font, glyph atlas, and text shaping constructors for `FontAtlasService`.
impl FontAtlasService {
    /// Creates a shared font and glyph service bound to `font_provider` with zero eager glyph allocation.
    ///
    /// # Arguments
    ///
    /// - `NativeSystemFont` - Native OS or deterministic font provider.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized shared font service.
    #[must_use]
    pub fn with_font_provider(font_provider: NativeSystemFont) -> Self {
        Self {
            font_provider,
            glyph_atlas: GlyphAtlas::default(),
            text_shaping_cache: TextShapingCache::default(),
        }
    }
}

/// Fluent builder helpers for `FrameRenderParams`.
impl FrameRenderParams {
    /// Creates frame render parameters for `viewport` with `1.0` scale, white clear color, and full damage.
    ///
    /// # Arguments
    ///
    /// - `Size` - Logical viewport size.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready render parameters.
    #[must_use]
    pub fn new(viewport: Size) -> Self {
        Self {
            viewport,
            scale_factor: 1.0,
            clear_color: COLOR_WHITE,
            layout_stats: LayoutStats::default(),
            damage: DamageRegion::full(),
            physical_width: 0,
            physical_height: 0,
        }
    }

    /// Sets the active DPI scale factor clamped to `[0.25, 16.0]`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base parameters.
    /// - `f32` - Scale factor.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated parameters.
    #[must_use]
    pub fn with_scale(mut self, scale_factor: f32) -> Self {
        self.set_scale_factor(scale_factor.clamp(0.25, 16.0));
        self
    }

    /// Attaches exact authoritative physical backing dimensions `(physical_width, physical_height)` preventing fractional-DPI round-trip drift.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base parameters.
    /// - `u32` - Authoritative physical width in pixels.
    /// - `u32` - Authoritative physical height in pixels.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated parameters.
    #[must_use]
    pub fn with_physical_size(mut self, physical_width: u32, physical_height: u32) -> Self {
        self.set_physical_width(physical_width);
        self.set_physical_height(physical_height);
        self
    }

    /// Sets the surface clear color.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base parameters.
    /// - `Color` - Clear color.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated parameters.
    #[must_use]
    pub fn with_clear(mut self, clear_color: Color) -> Self {
        self.set_clear_color(clear_color);
        self
    }

    /// Attaches layout telemetry from the current frame.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base parameters.
    /// - `LayoutStats` - Layout pass statistics.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated parameters.
    #[must_use]
    pub fn with_layout_stats(mut self, layout_stats: LayoutStats) -> Self {
        self.set_layout_stats(layout_stats);
        self
    }

    /// Sets the active dirty damage region.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base parameters.
    /// - `DamageRegion` - Damage region.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated parameters.
    #[must_use]
    pub fn with_damage(mut self, damage: DamageRegion) -> Self {
        self.set_damage(damage);
        self
    }
}

/// Single-backend pipeline construction, live mode switching, and frame rendering for `Renderer`.
impl Renderer {
    /// Creates a `Renderer` instantiating strictly ONE active backend for `platform` and `config`.
    ///
    /// # Arguments
    ///
    /// - `PlatformKind` - Active execution platform.
    /// - `PlatformCapabilities` - Hardware capabilities reported by the platform backend.
    /// - `u32` - Initial physical width.
    /// - `u32` - Initial physical height.
    /// - `RenderConfig` - Requested rendering configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized single-backend renderer facade with zero eager fallback allocation.
    #[must_use]
    pub fn new(
        platform: PlatformKind,
        capabilities: PlatformCapabilities,
        width: u32,
        height: u32,
        config: RenderConfig,
    ) -> Self {
        Self::with_display_hz(
            platform,
            capabilities,
            width,
            height,
            config,
            platform.default_refresh_rate_hz(),
        )
    }

    /// Creates a `Renderer` bound to live `display_refresh_hz` and instantiating strictly ONE active backend.
    ///
    /// # Arguments
    ///
    /// - `PlatformKind` - Active execution platform.
    /// - `PlatformCapabilities` - Hardware capabilities reported by the platform backend.
    /// - `u32` - Initial physical width.
    /// - `u32` - Initial physical height.
    /// - `RenderConfig` - Requested rendering configuration.
    /// - `f32` - Live native display refresh rate in Hertz.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized single-backend renderer facade.
    #[must_use]
    pub fn with_display_hz(
        platform: PlatformKind,
        capabilities: PlatformCapabilities,
        width: u32,
        height: u32,
        config: RenderConfig,
        display_refresh_hz: f32,
    ) -> Self {
        let (active_mode, active_backend): (RenderMode, GraphicsBackend) =
            Self::resolve_mode_and_backend(platform, capabilities, config);
        let readback_mirror: bool = !config.get_direct_gpu_present();
        let compute_pixel_hash: bool =
            platform == PlatformKind::Headless || active_backend == GraphicsBackend::Headless;
        let font_provider: NativeSystemFont = if platform == PlatformKind::Headless {
            NativeSystemFont::deterministic()
        } else {
            NativeSystemFont::system()
        };
        let font_service: FontAtlasService =
            FontAtlasService::with_font_provider(font_provider.clone());
        let mut display_list: DisplayList = DisplayList::default();
        display_list.reserve_steady_state();
        let active_backend_impl: ActiveRenderBackend = match active_mode {
            RenderMode::Software => ActiveRenderBackend::Software(Box::new(
                SoftwareRenderer::with_font_provider(width, height, config, font_provider),
            )),
            RenderMode::Hybrid => {
                ActiveRenderBackend::Hybrid(Box::new(HybridRenderer::with_backend_and_font(
                    active_backend,
                    width,
                    height,
                    config,
                    font_provider,
                )))
            }
            RenderMode::Hardware | RenderMode::Auto => {
                let (hw_w, hw_h): (u32, u32) = if readback_mirror {
                    (width, height)
                } else {
                    (0, 0)
                };
                ActiveRenderBackend::Hardware(Box::new(HardwareRenderer::with_backend_and_font(
                    active_backend,
                    hw_w,
                    hw_h,
                    config,
                    readback_mirror,
                    font_provider,
                )))
            }
        };
        let semantics: RenderSemanticsContract =
            RenderSemanticsContract::from_render_config(config, 1.0);
        let host_profile: HostCapabilityProfile =
            HostCapabilityProfile::from_platform(platform, capabilities);
        let mut router_cfg: AdaptiveRouterConfig = AdaptiveRouterConfig::default();
        router_cfg.set_switch_mode(config.get_adaptive_switch_mode());
        let mut adaptive_router: AdaptiveRenderRouter =
            AdaptiveRenderRouter::new(router_cfg, host_profile, display_refresh_hz as f64);
        let active_candidate: RenderBackendCandidate = match active_mode {
            RenderMode::Software => {
                if platform == PlatformKind::Terminal {
                    RenderBackendCandidate::Terminal
                } else {
                    RenderBackendCandidate::Software
                }
            }
            RenderMode::Hybrid => RenderBackendCandidate::Hybrid,
            RenderMode::Hardware | RenderMode::Auto => {
                if config.get_direct_gpu_present() {
                    RenderBackendCandidate::GpuDirect
                } else {
                    RenderBackendCandidate::GpuUpload
                }
            }
        };
        adaptive_router.set_active_candidate(active_candidate);
        adaptive_router.set_recommended_candidate(active_candidate);
        let initial_metrics: AdaptiveFrameMetrics = AdaptiveFrameMetrics::with_context(
            ObservableMetric::Measured(display_refresh_hz as f64),
            PresentTimingSource::Unobservable,
            adaptive_router.snapshot(),
        );
        Self {
            config,
            active_mode,
            active_backend,
            active_platform: platform,
            active_backend_impl,
            fallback_software: None,
            font_service,
            surface_width: width,
            surface_height: height,
            paint_pass: PaintPass,
            paint_fragment_cache: PaintFragmentCache::default(),
            display_list,
            frame_index: 0,
            compute_pixel_hash,
            telemetry_enabled: false,
            last_hashed_mode: None,
            last_hashed_dims: (0, 0),
            last_stats: FrameStats::default(),
            fallback_policy: FallbackPolicyEngine::with_display_hz(display_refresh_hz, semantics),
            composite_fast_path_frames: 0,
            cpu_fallback_frames: 0,
            adaptive_router,
            last_adaptive_metrics: initial_metrics,
            execution_router: AdaptiveExecutionRouter::default(),
            render_graph: RenderGraph::default(),
            last_scale_bits: 0,
            direct_submission_scratch: Box::new(GpuFrameSubmission::default()),
            direct_batch_tail_pool: Vec::new(),
        }
    }

    /// Returns an immutable reference to the single active rendering backend enum.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `&ActiveRenderBackend` - Active backend variant.
    #[must_use]
    pub fn active_backend_ref(&self) -> &ActiveRenderBackend {
        let Self {
            active_backend_impl,
            ..
        } = self;
        active_backend_impl
    }

    /// Returns a reference to the active or lazily-instantiated `SoftwareRenderer`, if one exists.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `Option<&SoftwareRenderer>` - Software renderer reference when active or lazily allocated.
    #[must_use]
    pub fn software(&self) -> Option<&SoftwareRenderer> {
        let Self {
            active_backend_impl,
            fallback_software,
            ..
        } = self;
        match active_backend_impl {
            ActiveRenderBackend::Software(stroke_width) => Some(stroke_width.as_ref()),
            ActiveRenderBackend::Hybrid(hy) => Some(hy.get_software()),
            ActiveRenderBackend::Hardware(_) => fallback_software.as_deref(),
        }
    }

    /// Returns a reference to the active `HardwareRenderer` when hardware mode is active.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `Option<&HardwareRenderer>` - Active hardware renderer, or `None` when inactive.
    #[must_use]
    pub fn hardware(&self) -> Option<&HardwareRenderer> {
        let Self {
            active_backend_impl,
            ..
        } = self;
        match active_backend_impl {
            ActiveRenderBackend::Hardware(hw) => Some(hw.as_ref()),
            ActiveRenderBackend::Software(_) | ActiveRenderBackend::Hybrid(_) => None,
        }
    }

    /// Returns a reference to the active `HybridRenderer` when hybrid mode is active.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `Option<&HybridRenderer>` - Active hybrid renderer, or `None` when inactive.
    #[must_use]
    pub fn hybrid(&self) -> Option<&HybridRenderer> {
        let Self {
            active_backend_impl,
            ..
        } = self;
        match active_backend_impl {
            ActiveRenderBackend::Hybrid(hy) => Some(hy.as_ref()),
            ActiveRenderBackend::Software(_) | ActiveRenderBackend::Hardware(_) => None,
        }
    }

    /// Returns `true` when the lazy CPU fallback `SoftwareRenderer` has been instantiated.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether `fallback_software` is currently allocated.
    #[must_use]
    pub fn has_fallback_software(&self) -> bool {
        let Self {
            fallback_software, ..
        } = self;
        fallback_software.is_some()
    }

    /// Returns total CPU RGBA8 framebuffer bytes currently allocated across active and fallback renderers (`0` in GPU direct-draw mode).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `usize` - Total allocated CPU framebuffer pixel bytes.
    #[must_use]
    pub fn allocated_cpu_framebuffer_bytes(&self) -> usize {
        let Self {
            active_backend_impl,
            fallback_software,
            ..
        } = self;
        let active_bytes: usize = match active_backend_impl {
            ActiveRenderBackend::Software(stroke_width) => {
                stroke_width.allocated_framebuffer_bytes()
            }
            ActiveRenderBackend::Hybrid(hy) => hy.get_software().allocated_framebuffer_bytes(),
            ActiveRenderBackend::Hardware(hw) => hw.get_readback().allocated_framebuffer_bytes(),
        };
        let fallback_bytes: usize = fallback_software
            .as_deref()
            .map_or(0, SoftwareRenderer::allocated_framebuffer_bytes);
        active_bytes.saturating_add(fallback_bytes)
    }

    /// Lazily allocates `fallback_software` if unset and returns a mutable reference to it, reusing `font_service`.
    ///
    /// # Arguments
    ///
    /// - `&'a mut Option<Box<SoftwareRenderer>>` - Fallback slot to populate lazily.
    /// - `&mut FontAtlasService` - Shared font and glyph atlas service.
    /// - `(RenderConfig, u32, u32, bool)` - Tuple `(config, width, height, telemetry_enabled)`.
    ///
    /// # Returns
    ///
    /// - `&'a mut SoftwareRenderer` - Mutable reference to the lazy CPU reference renderer.
    fn ensure_fallback_software<'a>(
        fallback_slot: &'a mut Option<Box<SoftwareRenderer>>,
        font_service: &mut FontAtlasService,
        opts: (RenderConfig, u32, u32, bool),
    ) -> &'a mut SoftwareRenderer {
        let (config, width, height, telemetry_enabled): (RenderConfig, u32, u32, bool) = opts;
        let sw_box: &mut Box<SoftwareRenderer> = fallback_slot.get_or_insert_with(|| {
            let mut sw_cfg: RenderConfig = config;
            sw_cfg.set_mode(RenderMode::Software);
            sw_cfg.set_direct_gpu_present(false);
            let mut stroke_width: SoftwareRenderer = SoftwareRenderer::with_font_provider(
                width,
                height,
                sw_cfg,
                font_service.get_font_provider().clone(),
            );
            swap(
                stroke_width.get_mut_glyph_atlas(),
                font_service.get_mut_glyph_atlas(),
            );
            stroke_width.set_telemetry_enabled(telemetry_enabled);
            Box::new(stroke_width)
        });
        sw_box.as_mut()
    }

    /// Returns a mutable reference to the active software renderer, lazily instantiating `fallback_software` only when in hardware mode.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    ///
    /// # Returns
    ///
    /// - `&mut SoftwareRenderer` - Mutable software renderer reference.
    pub fn get_mut_software(&mut self) -> &mut SoftwareRenderer {
        let Self {
            active_backend_impl,
            fallback_software,
            font_service,
            config,
            surface_width,
            surface_height,
            telemetry_enabled,
            ..
        } = self;
        match active_backend_impl {
            ActiveRenderBackend::Software(stroke_width) => stroke_width.as_mut(),
            ActiveRenderBackend::Hybrid(hy) => hy.get_mut_software(),
            ActiveRenderBackend::Hardware(_) => Self::ensure_fallback_software(
                fallback_software,
                font_service,
                (*config, *surface_width, *surface_height, *telemetry_enabled),
            ),
        }
    }

    /// Updates whether timing instrumentation (`Instant::now`) is active inside software band scheduling.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    /// - `bool` - `true` to enable per-dispatch microsecond timing instrumentation.
    pub fn set_timing_telemetry_enabled(&mut self, enabled: bool) {
        self.set_telemetry_enabled(enabled);
        let Self {
            active_backend_impl,
            fallback_software,
            ..
        } = self;
        match active_backend_impl {
            ActiveRenderBackend::Software(stroke_width) => {
                stroke_width.set_telemetry_enabled(enabled);
            }
            ActiveRenderBackend::Hybrid(hy) => {
                hy.get_mut_software().set_telemetry_enabled(enabled);
            }
            ActiveRenderBackend::Hardware(hw) => {
                hw.get_mut_readback().set_telemetry_enabled(enabled);
            }
        }
        if let Some(source_width) = fallback_software.as_deref_mut() {
            source_width.set_telemetry_enabled(enabled);
        }
    }

    /// Updates adaptive worker-pool spin behavior for active animation/scroll vs idle periods.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    /// - `bool` - `true` during active animation or scrolling; `false` when idle to drop worker spin to `0`.
    pub fn set_high_frequency_active(&mut self, active: bool) {
        let Self {
            active_backend_impl,
            fallback_software,
            ..
        } = self;
        match active_backend_impl {
            ActiveRenderBackend::Software(stroke_width) => {
                stroke_width.set_high_frequency_active(active)
            }
            ActiveRenderBackend::Hybrid(hy) => {
                hy.get_mut_software().set_high_frequency_active(active);
            }
            ActiveRenderBackend::Hardware(hw) => {
                hw.get_mut_readback().set_high_frequency_active(active);
            }
        }
        if let Some(source_width) = fallback_software.as_deref_mut() {
            source_width.set_high_frequency_active(active);
        }
    }

    /// Enables or disables direct GPU rendering without steady-state CPU RGBA readback mirroring.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    /// - `bool` - `true` for GPU direct-draw (zero CPU RGBA mirror); `false` to enable software readback mirror.
    pub fn set_direct_gpu_present(&mut self, enabled: bool) {
        let mut config_spec: RenderConfig = self.get_config();
        config_spec.set_direct_gpu_present(enabled);
        self.set_config(config_spec);
        let Self {
            active_backend_impl,
            last_hashed_mode,
            ..
        } = self;
        if let ActiveRenderBackend::Hardware(hw) = active_backend_impl {
            hw.set_enable_readback(!enabled);
            hw.set_per_glyph_atlas(enabled);
            if enabled {
                hw.get_mut_readback().release_framebuffer();
                hw.get_mut_gpu_glyph_atlas()
                    .set_submission_needs_full_upload(true);
            }
        }
        *last_hashed_mode = None;
    }

    /// Synchronizes the fallback policy engine with the active native display refresh rate in Hertz.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    /// - `f32` - Active display refresh rate in Hertz.
    pub fn set_display_refresh_rate_hz(&mut self, display_refresh_hz: f32) {
        self.get_mut_fallback_policy()
            .update_display_refresh_hz(display_refresh_hz);
        if display_refresh_hz.is_finite() && display_refresh_hz > 0.0 {
            self.get_mut_adaptive_router()
                .set_display_mode_hz(display_refresh_hz as f64);
        }
    }

    /// Returns a compact serializable telemetry snapshot of the active `AdaptiveRenderRouter`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `AdaptiveRouterSnapshot` - Current adaptive router and handoff snapshot.
    #[must_use]
    pub fn adaptive_router_snapshot(&self) -> AdaptiveRouterSnapshot {
        self.get_adaptive_router().snapshot()
    }

    /// Returns the active rollout switch mode (`RecommendOnly` vs `AutoSwitch`) on `AdaptiveRenderRouter`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `AdaptiveSwitchMode` - Active rollout switch policy.
    #[must_use]
    pub fn adaptive_switch_mode(&self) -> AdaptiveSwitchMode {
        self.get_adaptive_router().get_config().get_switch_mode()
    }

    /// Updates the rollout switch mode (`RecommendOnly` vs `AutoSwitch`) on both `RenderConfig` and the live `AdaptiveRenderRouter`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer reference.
    /// - `AdaptiveSwitchMode` - Requested rollout switch policy.
    pub fn set_adaptive_switch_mode(&mut self, mode: AdaptiveSwitchMode) {
        let mut config_spec: RenderConfig = self.get_config();
        config_spec.set_adaptive_switch_mode(mode);
        self.set_config(config_spec);
        let mut router_cfg: AdaptiveRouterConfig = self.get_adaptive_router().get_config();
        router_cfg.set_switch_mode(mode);
        self.get_mut_adaptive_router().set_config(router_cfg);
        let snap: AdaptiveRouterSnapshot = self.get_adaptive_router().snapshot();
        self.get_mut_last_adaptive_metrics()
            .set_adaptive_router(snap);
    }

    /// Returns the most recent truthful `AdaptiveFrameMetrics` snapshot synchronized with the live router state.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `AdaptiveFrameMetrics` - Truthful per-frame adaptive observability snapshot.
    #[must_use]
    pub fn adaptive_frame_metrics(&self) -> AdaptiveFrameMetrics {
        let mut metrics: AdaptiveFrameMetrics = self.get_last_adaptive_metrics();
        metrics.set_adaptive_router(self.get_adaptive_router().snapshot());
        metrics
    }

    /// Applies an adaptive candidate selection to the active pipeline, aligning `direct_gpu_present` strictly with GPU-first selection.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer reference.
    /// - `PlatformKind` - Active platform kind.
    /// - `PlatformCapabilities` - Host hardware capabilities.
    /// - `RenderBackendCandidate` - Candidate backend to activate.
    pub fn apply_adaptive_candidate(
        &mut self,
        platform: PlatformKind,
        capabilities: PlatformCapabilities,
        candidate: RenderBackendCandidate,
    ) {
        let direct_gpu: bool = self.get_config().resolve_direct_gpu_present(candidate);
        let mut config_spec: RenderConfig = self.get_config();
        config_spec.set_direct_gpu_present(direct_gpu);
        self.set_config(config_spec);
        self.switch_mode(platform, capabilities, candidate.to_render_mode());
        self.set_direct_gpu_present(direct_gpu);
        self.get_mut_adaptive_router()
            .set_active_candidate(candidate);
        self.get_mut_adaptive_router()
            .set_recommended_candidate(candidate);
    }

    /// Captures the active visual semantics contract verifying zero quality degradation across fallback transitions.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    /// - `f32` - Active display scale factor.
    ///
    /// # Returns
    ///
    /// - `RenderSemanticsContract` - Immutable visual fidelity snapshot.
    #[must_use]
    pub fn semantics_contract(&self, scale_factor: f32) -> RenderSemanticsContract {
        RenderSemanticsContract::from_render_config(self.get_config(), scale_factor)
    }

    /// Captures an on-demand CPU reference framebuffer for pixel-parity verification even while direct GPU draw is enabled.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    /// - `DamageRegion` - Damage region to rasterize into the reference framebuffer.
    ///
    /// # Returns
    ///
    /// - `&Framebuffer` - Rendered full-fidelity CPU reference RGBA8 framebuffer.
    pub fn capture_reference_framebuffer(&mut self, damage: DamageRegion) -> &Framebuffer {
        let Self {
            active_backend_impl,
            fallback_software,
            font_service,
            config,
            surface_width,
            surface_height,
            telemetry_enabled,
            display_list,
            ..
        } = self;
        match active_backend_impl {
            ActiveRenderBackend::Software(stroke_width) => {
                let (_, _): (usize, usize) = stroke_width.render(display_list, damage);
                stroke_width.get_framebuffer()
            }
            ActiveRenderBackend::Hybrid(hy) => hy.get_software().get_framebuffer(),
            ActiveRenderBackend::Hardware(hw) => {
                if hw.get_enable_readback() {
                    hw.capture_reference_readback(display_list, damage)
                } else {
                    let source_width: &mut SoftwareRenderer = Self::ensure_fallback_software(
                        fallback_software,
                        font_service,
                        (*config, *surface_width, *surface_height, *telemetry_enabled),
                    );
                    let (_, _): (usize, usize) = source_width.render(display_list, damage);
                    source_width.get_framebuffer()
                }
            }
        }
    }

    /// Evaluates `trigger` through `FallbackPolicyEngine` and applies strictly non-degrading cache trimming or CPU reference switching.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    /// - `FallbackTrigger` - Runtime pressure, frame overrun, or GPU fault trigger.
    /// - `u64` - Monotonic clock timestamp in milliseconds.
    ///
    /// # Returns
    ///
    /// - `FallbackAction` - Strictly non-degrading action applied.
    pub fn apply_fallback_trigger(
        &mut self,
        trigger: FallbackTrigger,
        now_ms: u64,
    ) -> FallbackAction {
        let action: FallbackAction = self
            .get_mut_fallback_policy()
            .evaluate_trigger(trigger, now_ms);
        match action {
            FallbackAction::TrimPrefetchAndColdCache { retain_ratio } => {
                let Self {
                    active_backend_impl,
                    fallback_software,
                    font_service,
                    paint_fragment_cache,
                    ..
                } = self;
                let budget: usize =
                    ((GLYPH_ATLAS_DEFAULT_BUDGET_BYTES as f32) * retain_ratio.clamp(0.1, 1.0))
                        .round()
                        .max(GLYPH_ATLAS_MIN_BUDGET_BYTES as f32) as usize;
                font_service.get_mut_glyph_atlas().set_memory_budget(budget);
                match active_backend_impl {
                    ActiveRenderBackend::Software(stroke_width) => {
                        stroke_width.get_mut_glyph_atlas().set_memory_budget(budget);
                    }
                    ActiveRenderBackend::Hybrid(hy) => {
                        hy.get_mut_software()
                            .get_mut_glyph_atlas()
                            .set_memory_budget(budget);
                    }
                    ActiveRenderBackend::Hardware(hw) => {
                        let _: usize = hw.trim_gpu_caches(retain_ratio);
                        hw.get_mut_readback()
                            .get_mut_glyph_atlas()
                            .set_memory_budget(budget);
                    }
                }
                if let Some(source_width) = fallback_software.as_deref_mut() {
                    source_width.get_mut_glyph_atlas().set_memory_budget(budget);
                }
                if retain_ratio <= FALLBACK_CRITICAL_RETAIN_RATIO + 0.01 {
                    paint_fragment_cache.clear();
                }
            }
            FallbackAction::SwitchToCpuReference { .. } => {
                let mut next_cfg: RenderConfig = self.get_config();
                next_cfg.set_mode(RenderMode::Software);
                next_cfg.set_direct_gpu_present(false);
                self.set_config(next_cfg);
                self.set_active_mode(RenderMode::Software);
                self.set_active_backend(GraphicsBackend::SoftwareCpu);
                let Self {
                    active_backend_impl,
                    fallback_software,
                    font_service,
                    surface_width,
                    surface_height,
                    telemetry_enabled,
                    last_hashed_mode,
                    ..
                } = self;
                if !matches!(active_backend_impl, ActiveRenderBackend::Software(_)) {
                    let next_sw: Box<SoftwareRenderer> = match fallback_software.take() {
                        Some(existing) => existing,
                        None => {
                            let mut span_width: SoftwareRenderer =
                                SoftwareRenderer::with_font_provider(
                                    *surface_width,
                                    *surface_height,
                                    next_cfg,
                                    font_service.get_font_provider().clone(),
                                );
                            swap(
                                span_width.get_mut_glyph_atlas(),
                                font_service.get_mut_glyph_atlas(),
                            );
                            span_width.set_telemetry_enabled(*telemetry_enabled);
                            Box::new(span_width)
                        }
                    };
                    *active_backend_impl = ActiveRenderBackend::Software(next_sw);
                }
                *last_hashed_mode = None;
            }
            FallbackAction::None
            | FallbackAction::AdjustPresentCadence { .. }
            | FallbackAction::RouteLayerToCpuReference => {}
        }
        action
    }

    /// Resolves `(RenderMode, GraphicsBackend)` deterministically from platform capabilities and user preference.
    ///
    /// # Arguments
    ///
    /// - `PlatformKind` - Target platform.
    /// - `PlatformCapabilities` - Hardware support flags.
    /// - `RenderConfig` - User configuration.
    ///
    /// # Returns
    ///
    /// - `(RenderMode, GraphicsBackend)` - Concrete resolved mode and backend.
    #[must_use]
    pub fn resolve_mode_and_backend(
        platform: PlatformKind,
        capabilities: PlatformCapabilities,
        config: RenderConfig,
    ) -> (RenderMode, GraphicsBackend) {
        let default_gpu: GraphicsBackend = platform.default_graphics_backend();
        let mode: RenderMode = match config.get_mode() {
            RenderMode::Auto => {
                if capabilities.get_hardware_gpu() {
                    RenderMode::Hardware
                } else {
                    RenderMode::Software
                }
            }
            explicit => explicit,
        };
        let backend: GraphicsBackend = match mode {
            RenderMode::Software => match platform {
                PlatformKind::Web | PlatformKind::MiniApp | PlatformKind::QuickApp => {
                    GraphicsBackend::Canvas2d
                }
                _ => GraphicsBackend::SoftwareCpu,
            },
            RenderMode::Hardware | RenderMode::Hybrid => {
                config.preferred_backend_value().unwrap_or(default_gpu)
            }
            RenderMode::Auto => default_gpu,
        };
        (mode, backend)
    }

    /// Dynamically switches the active rendering mode at runtime, instantiating only the target backend and transferring the shared glyph atlas.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    /// - `PlatformKind` - Active platform kind.
    /// - `PlatformCapabilities` - Platform hardware capabilities.
    /// - `RenderMode` - Target render mode.
    pub fn switch_mode(
        &mut self,
        platform: PlatformKind,
        capabilities: PlatformCapabilities,
        mode: RenderMode,
    ) {
        let mut next_cfg: RenderConfig = self.get_config();
        next_cfg.set_mode(mode);
        let (resolved_mode, resolved_backend): (RenderMode, GraphicsBackend) =
            Self::resolve_mode_and_backend(platform, capabilities, next_cfg);
        self.set_config(next_cfg);
        self.set_active_mode(resolved_mode);
        self.set_active_backend(resolved_backend);
        let Self {
            active_backend_impl,
            fallback_software,
            font_service,
            surface_width,
            surface_height,
            telemetry_enabled,
            last_hashed_mode,
            ..
        } = self;
        *last_hashed_mode = None;
        let same_variant: bool = matches!(
            (&*active_backend_impl, resolved_mode),
            (ActiveRenderBackend::Software(_), RenderMode::Software)
                | (
                    ActiveRenderBackend::Hardware(_),
                    RenderMode::Hardware | RenderMode::Auto
                )
                | (ActiveRenderBackend::Hybrid(_), RenderMode::Hybrid)
        );
        if same_variant {
            match active_backend_impl {
                ActiveRenderBackend::Hardware(hw) => {
                    hw.get_mut_driver().switch_backend(resolved_backend);
                }
                ActiveRenderBackend::Hybrid(hy) => {
                    hy.get_mut_driver().switch_backend(resolved_backend);
                }
                ActiveRenderBackend::Software(_) => {}
            }
            return;
        }
        let mut carried_atlas: GlyphAtlas = take(font_service.get_mut_glyph_atlas());
        match active_backend_impl {
            ActiveRenderBackend::Software(stroke_width) => {
                if !stroke_width.get_glyph_atlas().is_empty() {
                    carried_atlas = take(stroke_width.get_mut_glyph_atlas());
                }
            }
            ActiveRenderBackend::Hybrid(hy) => {
                if !hy.get_software().get_glyph_atlas().is_empty() {
                    carried_atlas = take(hy.get_mut_software().get_mut_glyph_atlas());
                }
            }
            ActiveRenderBackend::Hardware(hw) => {
                if !hw.get_readback().get_glyph_atlas().is_empty() {
                    carried_atlas = take(hw.get_mut_readback().get_mut_glyph_atlas());
                }
            }
        }
        let font_provider: NativeSystemFont = font_service.get_font_provider().clone();
        let next_backend: ActiveRenderBackend = match resolved_mode {
            RenderMode::Software => {
                let mut source_width: Box<SoftwareRenderer> = match fallback_software.take() {
                    Some(existing) => existing,
                    None => {
                        let mut sw_cfg: RenderConfig = next_cfg;
                        sw_cfg.set_direct_gpu_present(false);
                        Box::new(SoftwareRenderer::with_font_provider(
                            *surface_width,
                            *surface_height,
                            sw_cfg,
                            font_provider,
                        ))
                    }
                };
                if !carried_atlas.is_empty() {
                    source_width.set_glyph_atlas(carried_atlas);
                }
                source_width.set_telemetry_enabled(*telemetry_enabled);
                ActiveRenderBackend::Software(source_width)
            }
            RenderMode::Hybrid => {
                let mut hy_cfg: RenderConfig = next_cfg;
                hy_cfg.set_direct_gpu_present(false);
                let mut hy: HybridRenderer = HybridRenderer::with_backend_and_font(
                    resolved_backend,
                    *surface_width,
                    *surface_height,
                    hy_cfg,
                    font_provider,
                );
                if !carried_atlas.is_empty() {
                    hy.get_mut_software().set_glyph_atlas(carried_atlas);
                }
                hy.get_mut_software()
                    .set_telemetry_enabled(*telemetry_enabled);
                ActiveRenderBackend::Hybrid(Box::new(hy))
            }
            RenderMode::Hardware | RenderMode::Auto => {
                let readback_mirror: bool = !next_cfg.get_direct_gpu_present();
                let (hw_w, hw_h): (u32, u32) = if readback_mirror {
                    (*surface_width, *surface_height)
                } else {
                    (0, 0)
                };
                let mut hw: HardwareRenderer = HardwareRenderer::with_backend_and_font(
                    resolved_backend,
                    hw_w,
                    hw_h,
                    next_cfg,
                    readback_mirror,
                    font_provider,
                );
                if !carried_atlas.is_empty() {
                    hw.get_mut_readback().set_glyph_atlas(carried_atlas);
                }
                hw.get_mut_readback()
                    .set_telemetry_enabled(*telemetry_enabled);
                ActiveRenderBackend::Hardware(Box::new(hw))
            }
        };
        *active_backend_impl = next_backend;
    }

    /// Compiles `tree` into a `DisplayList`, executes the active render backend, and returns `FrameStats`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    /// - `&SceneTree` - Laid-out scene tree.
    /// - `Size` - Logical viewport dimensions.
    /// - `f32` - Active DPI scale factor.
    /// - `Color` - Surface clear color.
    /// - `LayoutStats` - Telemetry from the layout pass.
    /// - `DamageRegion` - Damaged screen region.
    ///
    /// # Returns
    ///
    /// - `Result<FrameStats, PlatformError>` - Frame performance and pixel-hash telemetry.
    pub fn render_frame(
        &mut self,
        tree: &SceneTree,
        viewport: Size,
        scale_factor: f32,
        clear_color: Color,
        layout_stats: LayoutStats,
        damage: DamageRegion,
    ) -> Result<FrameStats, PlatformError> {
        let params: FrameRenderParams = FrameRenderParams::new(viewport)
            .with_scale(scale_factor)
            .with_clear(clear_color)
            .with_layout_stats(layout_stats)
            .with_damage(damage);
        self.render_frame_composite_aware(tree, &params, false)
    }

    /// Compiles `tree` into a `DisplayList`, honoring composite-only fast paths and non-degrading CPU reference fallback on unsupported GPU effects.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    /// - `&SceneTree` - Laid-out scene tree.
    /// - `&FrameRenderParams` - Viewport, DPI, clear color, layout stats, and damage bundle.
    /// - `bool` - Whether only composite/scroll properties changed with zero layout or paint mutations.
    ///
    /// # Returns
    ///
    /// - `Result<FrameStats, PlatformError>` - Frame performance, direct-draw, fallback, and pixel-hash telemetry.
    pub fn render_frame_composite_aware(
        &mut self,
        tree: &SceneTree,
        params: &FrameRenderParams,
        composite_only: bool,
    ) -> Result<FrameStats, PlatformError> {
        let viewport: Size = params.get_viewport();
        let scale: f32 = params.get_scale_factor().clamp(0.25, 16.0);
        let clear_color: Color = params.get_clear_color();
        let layout_stats: LayoutStats = params.get_layout_stats();
        let damage: DamageRegion = params.get_damage();
        let phys_w: u32 = if params.get_physical_width() > 0 {
            params.get_physical_width()
        } else {
            ((viewport.get_width() * scale).round() as u32).max(1)
        };
        let phys_h: u32 = if params.get_physical_height() > 0 {
            params.get_physical_height()
        } else {
            ((viewport.get_height() * scale).round() as u32).max(1)
        };
        let phys_dims: (u32, u32) = (phys_w, phys_h);
        let scale_bits: u32 = scale.to_bits();
        let Self {
            config,
            active_mode,
            active_backend,
            active_platform,
            active_backend_impl,
            fallback_software,
            font_service,
            surface_width,
            surface_height,
            paint_pass,
            paint_fragment_cache,
            display_list,
            frame_index,
            compute_pixel_hash,
            telemetry_enabled,
            last_hashed_mode,
            last_hashed_dims,
            last_stats,
            fallback_policy,
            composite_fast_path_frames,
            cpu_fallback_frames,
            adaptive_router,
            last_adaptive_metrics,
            execution_router,
            render_graph: _,
            last_scale_bits,
            direct_submission_scratch: _,
            direct_batch_tail_pool: _,
        } = self;
        *surface_width = phys_w;
        *surface_height = phys_h;
        if *last_scale_bits != scale_bits {
            let aa_mode: AntialiasingMode = config.get_antialiasing();
            let _: bool = font_service
                .get_mut_glyph_atlas()
                .invalidate_for_render_params(scale, aa_mode, 0);
            match active_backend_impl {
                ActiveRenderBackend::Software(sw) => {
                    let _: bool = sw
                        .get_mut_glyph_atlas()
                        .invalidate_for_render_params(scale, aa_mode, 0);
                }
                ActiveRenderBackend::Hybrid(hy) => {
                    let _: bool = hy
                        .get_mut_software()
                        .get_mut_glyph_atlas()
                        .invalidate_for_render_params(scale, aa_mode, 0);
                }
                ActiveRenderBackend::Hardware(hw) => {
                    let _: bool = hw
                        .get_mut_readback()
                        .get_mut_glyph_atlas()
                        .invalidate_for_render_params(scale, aa_mode, 0);
                }
            }
            if let Some(fb_sw) = fallback_software.as_mut() {
                let _: bool = fb_sw
                    .get_mut_glyph_atlas()
                    .invalidate_for_render_params(scale, aa_mode, 0);
            }
            *last_scale_bits = scale_bits;
        }
        let mode: RenderMode = *active_mode;
        let backend: GraphicsBackend = *active_backend;
        let do_pixel_hash: bool = *compute_pixel_hash;
        let hash_reusable: bool = *last_hashed_mode == Some(mode) && *last_hashed_dims == phys_dims;
        if !damage.get_full_damage() && damage.bounds_rect().is_none() && hash_reusable {
            *frame_index = frame_index.wrapping_add(1);
            let stats: FrameStats = FrameStats {
                frame_index: *frame_index,
                active_mode: mode,
                active_backend: backend,
                layout_nodes: layout_stats.get_nodes_computed(),
                layout_skipped: layout_stats.get_subtrees_skipped(),
                draw_commands: 0,
                draw_batches: 0,
                pixels_shaded: 0,
                frame_hash: last_stats.get_frame_hash(),
                composite_only: false,
                gpu_direct_draw: false,
                cpu_rgba_upload_bytes: 0,
                submit_outcome: FrameSubmitOutcome::SkippedNoDamage,
                wait_in_flight: false,
            };
            *last_stats = stats;
            let hz: f64 = adaptive_router.get_display_mode_hz();
            let mut skipped_metrics: AdaptiveFrameMetrics = AdaptiveFrameMetrics::with_context(
                ObservableMetric::Measured(hz),
                PresentTimingSource::Unobservable,
                adaptive_router.snapshot(),
            );
            skipped_metrics.set_present_outcome(SurfacePresentOutcome::SkippedUnchanged);
            skipped_metrics.set_upload_strategy(UploadStrategy::None);
            skipped_metrics.set_texture_upload_bytes(0);
            skipped_metrics.set_cpu_mirror_active(false);
            *last_adaptive_metrics = skipped_metrics;
            return Ok(stats);
        }
        let _: &PaintPass = paint_pass;
        let layout_changed: bool = layout_stats.get_nodes_computed() > 0;
        let took_composite_fast_path: bool = composite_only && !layout_changed;
        if took_composite_fast_path {
            *composite_fast_path_frames = composite_fast_path_frames.saturating_add(1);
        }
        let direct_scene_ok: bool = matches!(
            active_backend_impl,
            ActiveRenderBackend::Hardware(hw) if !hw.get_enable_readback()
        ) && active_platform.supports_direct_gpu_scene_pass(backend);
        display_list.set_direct_gpu_scene_enabled(direct_scene_ok);
        {
            let DisplayList { gpu_scene_pass, .. } = display_list;
            recycle_gpu_scene_pass(gpu_scene_pass.take());
        }
        PaintPass::build_retained(
            tree,
            viewport,
            scale,
            clear_color,
            layout_changed,
            display_list,
            paint_fragment_cache,
        );
        if *frame_index == 0 && tree.has_scroll_nodes() {
            display_list.prewarm_scroll_string_pool(24);
        }
        let cmd_count: usize = display_list.len();
        let mut gpu_direct_draw: bool = false;
        let cpu_mirror_active: bool;
        let upload_strategy: UploadStrategy;
        let cpu_rgba_upload_bytes: usize;
        let mut effective_mode: RenderMode = mode;
        let mut effective_backend: GraphicsBackend = backend;
        let (batches, pixels, hash): (usize, usize, u64) = match active_backend_impl {
            ActiveRenderBackend::Software(stroke_width) => {
                let (blue_val, point_val): (usize, usize) =
                    stroke_width.render(display_list, damage);
                cpu_mirror_active = true;
                upload_strategy = UploadStrategy::FullFrame;
                cpu_rgba_upload_bytes = (phys_w as usize)
                    .saturating_mul(phys_h as usize)
                    .saturating_mul(4);
                let height_val: u64 = if point_val == 0 && hash_reusable {
                    last_stats.get_frame_hash()
                } else if do_pixel_hash {
                    stroke_width.incremental_framebuffer_hash()
                } else {
                    display_list.fast_hash()
                };
                (blue_val, point_val, height_val)
            }
            ActiveRenderBackend::Hybrid(hy) => {
                let (byte_val, palette_val): (usize, usize) =
                    hy.render_with_physical_size(display_list, damage, Some(phys_dims))?;
                cpu_rgba_upload_bytes = hy.get_last_cpu_upload_bytes();
                let sparse_active: bool = hy.get_last_cpu_tile_count() > 0;
                cpu_mirror_active = sparse_active;
                upload_strategy = if sparse_active {
                    UploadStrategy::MultiRect
                } else {
                    UploadStrategy::DirectGpu
                };
                let span_height: u64 = if palette_val == 0 && hash_reusable {
                    last_stats.get_frame_hash()
                } else if do_pixel_hash && sparse_active {
                    hy.get_mut_software().incremental_framebuffer_hash()
                } else {
                    display_list.fast_hash()
                };
                (byte_val, palette_val, span_height)
            }
            ActiveRenderBackend::Hardware(hw) => {
                match hw.render_with_physical_size(display_list, damage, Some(phys_dims)) {
                    Ok((bounds_val, pixel_slice)) => {
                        if hw.get_has_unsupported_effect() {
                            let _: FallbackAction = fallback_policy.evaluate_trigger(
                                FallbackTrigger::MissingGpuEffectPath { isolatable: false },
                                0,
                            );
                            *cpu_fallback_frames = cpu_fallback_frames.saturating_add(1);
                            let source_width: &mut SoftwareRenderer =
                                Self::ensure_fallback_software(
                                    fallback_software,
                                    font_service,
                                    (*config, phys_w, phys_h, *telemetry_enabled),
                                );
                            let (sb, sp): (usize, usize) =
                                source_width.render(display_list, damage);
                            effective_mode = RenderMode::Software;
                            effective_backend = GraphicsBackend::SoftwareCpu;
                            cpu_mirror_active = true;
                            upload_strategy = UploadStrategy::FullFrame;
                            cpu_rgba_upload_bytes = (phys_w as usize)
                                .saturating_mul(phys_h as usize)
                                .saturating_mul(4);
                            let half_extent: u64 = if do_pixel_hash {
                                source_width.incremental_framebuffer_hash()
                            } else {
                                display_list.fast_hash()
                            };
                            (sb, sp, half_extent)
                        } else {
                            gpu_direct_draw = !hw.get_enable_readback();
                            cpu_mirror_active = hw.get_enable_readback();
                            upload_strategy = if gpu_direct_draw {
                                UploadStrategy::DirectGpu
                            } else {
                                UploadStrategy::FullFrame
                            };
                            cpu_rgba_upload_bytes = hw.get_last_cpu_rgba_upload_bytes();
                            let height_val_primary: u64 = if pixel_slice == 0 && hash_reusable {
                                last_stats.get_frame_hash()
                            } else if hw.get_enable_readback() {
                                if do_pixel_hash {
                                    hw.get_mut_readback().incremental_framebuffer_hash()
                                } else {
                                    display_list.fast_hash()
                                }
                            } else {
                                hw.batch_hash()
                            };
                            (bounds_val, pixel_slice, height_val_primary)
                        }
                    }
                    Err(_) => {
                        let _: FallbackAction =
                            fallback_policy.evaluate_trigger(FallbackTrigger::DeviceLost, 0);
                        let _: AdaptiveDecision =
                            adaptive_router.handle_fault(FaultEventKind::DeviceLost, true, 0);
                        *cpu_fallback_frames = cpu_fallback_frames.saturating_add(1);
                        let span_width: &mut SoftwareRenderer = Self::ensure_fallback_software(
                            fallback_software,
                            font_service,
                            (*config, phys_w, phys_h, *telemetry_enabled),
                        );
                        let (sb, sp): (usize, usize) = span_width.render(display_list, damage);
                        effective_mode = RenderMode::Software;
                        effective_backend = GraphicsBackend::SoftwareCpu;
                        cpu_mirror_active = true;
                        upload_strategy = UploadStrategy::FullFrame;
                        cpu_rgba_upload_bytes = (phys_w as usize)
                            .saturating_mul(phys_h as usize)
                            .saturating_mul(4);
                        let height_val_secondary: u64 = if do_pixel_hash {
                            span_width.incremental_framebuffer_hash()
                        } else {
                            display_list.fast_hash()
                        };
                        (sb, sp, height_val_secondary)
                    }
                }
            }
        };
        *last_hashed_mode = Some(effective_mode);
        *last_hashed_dims = phys_dims;
        *frame_index = frame_index.wrapping_add(1);
        let stats: FrameStats = FrameStats {
            frame_index: *frame_index,
            active_mode: effective_mode,
            active_backend: effective_backend,
            layout_nodes: layout_stats.get_nodes_computed(),
            layout_skipped: layout_stats.get_subtrees_skipped(),
            draw_commands: cmd_count,
            draw_batches: batches,
            pixels_shaded: pixels,
            frame_hash: hash,
            composite_only: took_composite_fast_path,
            gpu_direct_draw,
            cpu_rgba_upload_bytes,
            submit_outcome: FrameSubmitOutcome::Submitted,
            wait_in_flight: false,
        };
        *last_stats = stats;
        let hz: f64 = adaptive_router.get_display_mode_hz();
        let mut frame_metrics: AdaptiveFrameMetrics = AdaptiveFrameMetrics::with_context(
            ObservableMetric::Measured(hz),
            PresentTimingSource::SubmissionProxy,
            adaptive_router.snapshot(),
        );
        frame_metrics.set_frame_callback_count(*frame_index);
        frame_metrics.set_present_outcome(SurfacePresentOutcome::Submitted);
        frame_metrics.set_cpu_mirror_active(cpu_mirror_active);
        frame_metrics.set_texture_upload_bytes(cpu_rgba_upload_bytes as u64);
        frame_metrics.set_upload_strategy(upload_strategy);
        *last_adaptive_metrics = frame_metrics;
        let exec_workload: ExecutionWorkloadFeatures = ExecutionWorkloadFeatures {
            dirty_nodes: layout_stats.get_nodes_computed(),
            visible_nodes: cmd_count,
            tree_depth: 4,
            gpu_eligible_nodes: if gpu_direct_draw { cmd_count } else { 0 },
            cpu_chrome_nodes: if gpu_direct_draw { 0 } else { cmd_count },
            dirty_upload_bytes: cmd_count.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES),
            wrapping_text_ratio: 0.0,
            worker_threads: 1,
            gpu_compute_available: gpu_direct_draw,
            thermal_throttled: false,
        };
        let _: ExecutionRouterDecision = execution_router.evaluate(exec_workload, *frame_index);
        execution_router.observe_frame(
            0.0,
            last_gpu_compute_ns(),
            last_gpu_render_ns(),
            exec_workload,
            false,
            *frame_index,
        );
        Ok(stats)
    }

    /// Executes `callback` with a borrowed `GpuFrameSubmission` built via O(1) pointer swaps, eliminating per-frame `GpuBatch`, `DirectGpuScenePass`, and multi-MB atlas `Vec<u8>` clones while restoring all buffers intact immediately after presentation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer reference.
    /// - `Color` - Surface clear color for the active frame.
    /// - `F` - Synchronous presentation closure borrowing `&GpuFrameSubmission`.
    ///
    /// # Returns
    ///
    /// - `Option<R>` - Presentation callback result when hardware or hybrid batches are ready.
    pub fn with_direct_gpu_submission<R, F>(&mut self, clear_color: Color, callback: F) -> Option<R>
    where
        F: FnOnce(&GpuFrameSubmission) -> R,
    {
        let width: u32 = self.get_surface_width().max(1);
        let height: u32 = self.get_surface_height().max(1);
        let scale_factor: f32 = self.get_display_list().get_scale_factor().clamp(0.25, 16.0);
        let Self {
            active_backend_impl,
            display_list,
            direct_submission_scratch,
            direct_batch_tail_pool,
            ..
        } = self;
        let DisplayList { gpu_scene_pass, .. } = display_list;
        match active_backend_impl {
            ActiveRenderBackend::Hardware(hw) => {
                let active_len: usize = hw.get_active_batches().min(hw.get_batches().len());
                direct_batch_tail_pool.clear();
                direct_batch_tail_pool.extend(hw.get_mut_batches().drain(active_len..));
                swap(&mut direct_submission_scratch.batches, hw.get_mut_batches());
                swap(
                    &mut direct_submission_scratch.blur_passes,
                    hw.get_mut_blur_passes(),
                );
                direct_submission_scratch.width = width;
                direct_submission_scratch.height = height;
                direct_submission_scratch.scale_factor = scale_factor;
                direct_submission_scratch.clear_color = clear_color;
                direct_submission_scratch.external_texture_handle =
                    hw.get_driver().get_external_texture_handle();
                direct_submission_scratch.gpu_scene_pass = gpu_scene_pass.take();
                let mut dirty_rects: Vec<PixelDirtyRect> =
                    hw.get_mut_gpu_glyph_atlas().take_submission_dirty_rects();
                dirty_rects
                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
                if !dirty_rects.is_empty() {
                    let atlas: &mut IncrementalGpuGlyphAtlas = hw.get_mut_gpu_glyph_atlas();
                    let atlas_w: u32 = atlas.get_width();
                    let atlas_h: u32 = atlas.get_height();
                    let atlas_rev: u64 = atlas.get_synced_revision();
                    let moved_pixels: Vec<u8> = take(atlas.get_mut_pixels());
                    direct_submission_scratch.set_glyph_atlas_payload(
                        Some(DirectGpuAtlasUpload {
                            width: atlas_w,
                            height: atlas_h,
                            revision: atlas_rev,
                            pixels: moved_pixels,
                        }),
                        dirty_rects,
                    );
                } else {
                    direct_submission_scratch.set_glyph_atlas_payload(None, Vec::new());
                }
                let mut img_dirty_rects: Vec<PixelDirtyRect> =
                    hw.get_mut_gpu_image_atlas().take_submission_dirty_rects();
                img_dirty_rects
                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
                if !img_dirty_rects.is_empty() {
                    let img_atlas: &mut IncrementalGpuImageAtlas = hw.get_mut_gpu_image_atlas();
                    let img_w: u32 = img_atlas.get_width();
                    let img_h: u32 = img_atlas.get_height();
                    let img_rev: u64 = img_atlas.get_revision();
                    let moved_pixels: Vec<u8> = take(img_atlas.get_mut_pixels());
                    direct_submission_scratch.set_image_atlas_payload(
                        Some(DirectGpuAtlasUpload {
                            width: img_w,
                            height: img_h,
                            revision: img_rev,
                            pixels: moved_pixels,
                        }),
                        img_dirty_rects,
                    );
                } else {
                    direct_submission_scratch.set_image_atlas_payload(None, Vec::new());
                }
                let outcome: R = callback(direct_submission_scratch);
                if let Some(upload) = direct_submission_scratch.glyph_atlas_r8.take() {
                    hw.get_mut_gpu_glyph_atlas().set_pixels(upload.pixels);
                }
                direct_submission_scratch.glyph_dirty_rects.clear();
                if let Some(upload) = direct_submission_scratch.image_atlas_rgba8.take() {
                    hw.get_mut_gpu_image_atlas().set_pixels(upload.pixels);
                }
                direct_submission_scratch.image_dirty_rects.clear();
                *gpu_scene_pass = direct_submission_scratch.gpu_scene_pass.take();
                swap(
                    &mut direct_submission_scratch.blur_passes,
                    hw.get_mut_blur_passes(),
                );
                swap(&mut direct_submission_scratch.batches, hw.get_mut_batches());
                hw.get_mut_batches().append(direct_batch_tail_pool);
                Some(outcome)
            }
            ActiveRenderBackend::Hybrid(hy) => {
                swap(
                    &mut direct_submission_scratch.batches,
                    hy.get_mut_last_batches(),
                );
                direct_submission_scratch.blur_passes.clear();
                direct_submission_scratch.width = width;
                direct_submission_scratch.height = height;
                direct_submission_scratch.scale_factor = scale_factor;
                direct_submission_scratch.clear_color = clear_color;
                direct_submission_scratch.external_texture_handle =
                    hy.get_driver().get_external_texture_handle();
                direct_submission_scratch.gpu_scene_pass = gpu_scene_pass.take();
                let mut dirty_rects: Vec<PixelDirtyRect> =
                    hy.get_mut_gpu_glyph_atlas().take_submission_dirty_rects();
                dirty_rects
                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
                if !dirty_rects.is_empty() {
                    let atlas: &mut IncrementalGpuGlyphAtlas = hy.get_mut_gpu_glyph_atlas();
                    let atlas_w: u32 = atlas.get_width();
                    let atlas_h: u32 = atlas.get_height();
                    let atlas_rev: u64 = atlas.get_synced_revision();
                    let moved_pixels: Vec<u8> = take(atlas.get_mut_pixels());
                    direct_submission_scratch.set_glyph_atlas_payload(
                        Some(DirectGpuAtlasUpload {
                            width: atlas_w,
                            height: atlas_h,
                            revision: atlas_rev,
                            pixels: moved_pixels,
                        }),
                        dirty_rects,
                    );
                } else {
                    direct_submission_scratch.set_glyph_atlas_payload(None, Vec::new());
                }
                direct_submission_scratch.set_image_atlas_payload(None, Vec::new());
                let outcome: R = callback(direct_submission_scratch);
                if let Some(upload) = direct_submission_scratch.glyph_atlas_r8.take() {
                    hy.get_mut_gpu_glyph_atlas().set_pixels(upload.pixels);
                }
                direct_submission_scratch.glyph_dirty_rects.clear();
                *gpu_scene_pass = direct_submission_scratch.gpu_scene_pass.take();
                swap(
                    &mut direct_submission_scratch.batches,
                    hy.get_mut_last_batches(),
                );
                Some(outcome)
            }
            ActiveRenderBackend::Software(_) => None,
        }
    }

    /// Builds a direct-GPU `GpuFrameSubmission` payload from the active `HardwareRenderer` or `HybridRenderer` for `PlatformBackend::present_gpu_frame`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer reference.
    /// - `Color` - Surface clear color for the active frame.
    ///
    /// # Returns
    ///
    /// - `Option<GpuFrameSubmission>` - Direct-GPU frame submission when hardware or hybrid batches are ready.
    #[must_use]
    pub fn build_direct_gpu_submission(
        &mut self,
        clear_color: Color,
    ) -> Option<GpuFrameSubmission> {
        let width: u32 = self.get_surface_width().max(1);
        let height: u32 = self.get_surface_height().max(1);
        let scale_factor: f32 = self.get_display_list().get_scale_factor().clamp(0.25, 16.0);
        let gpu_scene_pass: Option<DirectGpuScenePass> =
            self.get_display_list().gpu_scene_pass_clone();
        let Self {
            active_backend_impl,
            ..
        } = self;
        match active_backend_impl {
            ActiveRenderBackend::Hardware(hw) => {
                let batches: Vec<GpuBatch> = hw.active_batches_slice().to_vec();
                let blur_passes: Vec<GpuBackdropBlurPass> = hw.get_blur_passes().clone();
                let external_tex: usize = hw.get_driver().get_external_texture_handle();
                let mut submission: GpuFrameSubmission = GpuFrameSubmission {
                    width,
                    height,
                    scale_factor,
                    clear_color,
                    batches,
                    blur_passes,
                    external_texture_handle: external_tex,
                    gpu_scene_pass,
                    glyph_atlas_r8: None,
                    glyph_dirty_rects: Vec::new(),
                    image_atlas_rgba8: None,
                    image_dirty_rects: Vec::new(),
                };
                let mut dirty_rects: Vec<PixelDirtyRect> =
                    hw.get_mut_gpu_glyph_atlas().take_submission_dirty_rects();
                dirty_rects
                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
                if !dirty_rects.is_empty() {
                    let atlas: &IncrementalGpuGlyphAtlas = hw.get_gpu_glyph_atlas();
                    submission.set_glyph_atlas_payload(
                        Some(DirectGpuAtlasUpload {
                            width: atlas.get_width(),
                            height: atlas.get_height(),
                            revision: atlas.get_synced_revision(),
                            pixels: atlas.get_pixels().clone(),
                        }),
                        dirty_rects,
                    );
                }
                let mut img_dirty_rects: Vec<PixelDirtyRect> =
                    hw.get_mut_gpu_image_atlas().take_submission_dirty_rects();
                img_dirty_rects
                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
                if !img_dirty_rects.is_empty() {
                    let img_atlas: &IncrementalGpuImageAtlas = hw.get_gpu_image_atlas();
                    submission.set_image_atlas_payload(
                        Some(DirectGpuAtlasUpload {
                            width: img_atlas.get_width(),
                            height: img_atlas.get_height(),
                            revision: img_atlas.get_revision(),
                            pixels: img_atlas.get_pixels().clone(),
                        }),
                        img_dirty_rects,
                    );
                }
                Some(submission)
            }
            ActiveRenderBackend::Hybrid(hy) => {
                let batches: Vec<GpuBatch> = hy.get_last_batches().clone();
                let external_tex: usize = hy.get_driver().get_external_texture_handle();
                let mut submission: GpuFrameSubmission = GpuFrameSubmission {
                    width,
                    height,
                    scale_factor,
                    clear_color,
                    batches,
                    blur_passes: Vec::new(),
                    external_texture_handle: external_tex,
                    gpu_scene_pass,
                    glyph_atlas_r8: None,
                    glyph_dirty_rects: Vec::new(),
                    image_atlas_rgba8: None,
                    image_dirty_rects: Vec::new(),
                };
                let mut dirty_rects: Vec<PixelDirtyRect> =
                    hy.get_mut_gpu_glyph_atlas().take_submission_dirty_rects();
                dirty_rects
                    .retain(|rect: &PixelDirtyRect| rect.get_width() > 0 && rect.get_height() > 0);
                if !dirty_rects.is_empty() {
                    let atlas: &IncrementalGpuGlyphAtlas = hy.get_gpu_glyph_atlas();
                    submission.set_glyph_atlas_payload(
                        Some(DirectGpuAtlasUpload {
                            width: atlas.get_width(),
                            height: atlas.get_height(),
                            revision: atlas.get_synced_revision(),
                            pixels: atlas.get_pixels().clone(),
                        }),
                        dirty_rects,
                    );
                }
                Some(submission)
            }
            ActiveRenderBackend::Software(_) => None,
        }
    }

    /// Handles a GPU presentation `DeviceLost` or `SurfaceError` by invoking `FallbackPolicyEngine`, `AdaptiveExecutionRouter` fault failover, and rendering a non-degrading CPU software fallback framebuffer.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer reference.
    /// - `DamageRegion` - Frame damage region for software fallback recovery.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the CPU software fallback framebuffer is ready for immediate presentation.
    pub fn recover_gpu_present_fault(&mut self, damage: DamageRegion) -> bool {
        let phys_w: u32 = self.get_surface_width().max(1);
        let phys_h: u32 = self.get_surface_height().max(1);
        let Self {
            config,
            fallback_software,
            font_service,
            display_list,
            telemetry_enabled,
            fallback_policy,
            cpu_fallback_frames,
            adaptive_router,
            execution_router,
            frame_index,
            last_stats,
            ..
        } = self;
        let _: FallbackAction = fallback_policy.evaluate_trigger(FallbackTrigger::DeviceLost, 0);
        let _: AdaptiveDecision = adaptive_router.handle_fault(FaultEventKind::DeviceLost, true, 0);
        let _: ExecutionLane = execution_router.trigger_gpu_fault_failover(1, *frame_index);
        *cpu_fallback_frames = cpu_fallback_frames.saturating_add(1);
        let sw: &mut SoftwareRenderer = Self::ensure_fallback_software(
            fallback_software,
            font_service,
            (*config, phys_w, phys_h, *telemetry_enabled),
        );
        let _: (usize, usize) = sw.render(display_list, damage);
        last_stats.set_active_mode(RenderMode::Software);
        last_stats.set_gpu_direct_draw(false);
        true
    }

    /// Renders `tree` using a compact `FrameRenderParams` descriptor and returns `FrameStats`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    /// - `&SceneTree` - Laid-out scene tree.
    /// - `&FrameRenderParams` - Viewport, DPI, clear color, layout stats, and damage bundle.
    ///
    /// # Returns
    ///
    /// - `Result<FrameStats, PlatformError>` - Frame performance and pixel-hash telemetry.
    #[inline(always)]
    pub fn render_with(
        &mut self,
        tree: &SceneTree,
        params: &FrameRenderParams,
    ) -> Result<FrameStats, PlatformError> {
        self.render_frame(
            tree,
            params.get_viewport(),
            params.get_scale_factor(),
            params.get_clear_color(),
            params.get_layout_stats(),
            params.get_damage(),
        )
    }

    /// Advances the frame counter for an undamaged idle frame without rasterizing or hashing pixels and drops worker spin to `0`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable renderer.
    ///
    /// # Returns
    ///
    /// - `FrameStats` - Lightweight telemetry preserving the last rendered `frame_hash` with zero shaded pixels.
    pub fn record_skipped_frame(&mut self) -> FrameStats {
        self.set_high_frequency_active(false);
        let next_idx: u64 = self.get_frame_index().wrapping_add(1);
        self.set_frame_index(next_idx);
        let mut stats: FrameStats = self.get_last_stats();
        stats.set_frame_index(next_idx);
        stats.set_layout_nodes(0);
        stats.set_draw_commands(0);
        stats.set_draw_batches(0);
        stats.set_pixels_shaded(0);
        stats.set_composite_only(false);
        stats.set_gpu_direct_draw(false);
        stats.set_cpu_rgba_upload_bytes(0);
        stats.record_present_outcome(PresentOutcome::SkippedNoDamage);
        self.set_last_stats(stats);
        stats
    }

    /// Returns cumulative cross-frame `PaintFragmentCache` telemetry `(whole_list_hits, fragment_hits, fragment_misses, fragment_evictions)`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `(u64, u64, u64, u64)` - Tuple of whole-list hits, fragment hits, misses, and evictions.
    #[must_use]
    pub fn paint_fragment_cache_stats(&self) -> (u64, u64, u64, u64) {
        self.get_paint_fragment_cache().stats()
    }

    /// Returns a reference to the latest CPU-accessible `Framebuffer` for software/hybrid/readback presentation (`None` when GPU direct-draw is active with 0 CPU FB bytes).
    ///
    /// # Arguments
    ///
    /// - `&Self` - Renderer reference.
    ///
    /// # Returns
    ///
    /// - `Option<&Framebuffer>` - Active RGBA8 framebuffer if resident in host memory.
    #[must_use]
    pub fn framebuffer(&self) -> Option<&Framebuffer> {
        let Self {
            active_backend_impl,
            fallback_software,
            last_stats,
            ..
        } = self;
        match active_backend_impl {
            ActiveRenderBackend::Software(stroke_width) => stroke_width.framebuffer_opt(),
            ActiveRenderBackend::Hybrid(hy) => hy.get_software().framebuffer_opt(),
            ActiveRenderBackend::Hardware(hw) => {
                if last_stats.get_active_mode() == RenderMode::Software {
                    fallback_software
                        .as_deref()
                        .and_then(SoftwareRenderer::framebuffer_opt)
                } else if hw.get_enable_readback() {
                    hw.get_readback().framebuffer_opt()
                } else {
                    None
                }
            }
        }
    }
}