runmat-plot 0.4.0

GPU-accelerated and static plotting for RunMat with WGPU and Plotters
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
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
//! Unified plot rendering pipeline for both interactive GUI and static export
//!
//! This module provides the core rendering logic that is shared between
//! interactive plotting windows and static file exports, ensuring consistent
//! high-quality output across all use cases.

use crate::core::renderer::Vertex;
use crate::core::{Camera, ClipPolicy, DepthMode, Scene, WgpuRenderer};
use crate::plots::figure::{LegendEntry, TextStyle};
use crate::plots::surface::ColorMap;
use crate::plots::Figure;
use glam::{Mat4, Vec3, Vec4};
use runmat_time::Instant;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Arc;

#[derive(Clone, Debug)]
struct CachedSceneBuffers {
    vertex_signature: (usize, usize),
    vertex_buffer: Arc<wgpu::Buffer>,
    index_signature: Option<(usize, usize)>,
    index_buffer: Option<Arc<wgpu::Buffer>>,
}

/// Unified plot renderer that handles both interactive and static rendering
pub struct PlotRenderer {
    /// WGPU renderer for GPU-accelerated rendering
    pub wgpu_renderer: WgpuRenderer,

    /// Current scene being rendered
    pub scene: Scene,

    /// Current theme configuration  
    pub theme: crate::styling::PlotThemeConfig,

    /// Cached rendering state
    data_bounds: Option<(f64, f64, f64, f64)>,
    needs_update: bool,

    // Cached figure metadata for overlay
    figure_title: Option<String>,
    figure_x_label: Option<String>,
    figure_y_label: Option<String>,
    figure_z_label: Option<String>,
    figure_show_grid: bool,
    figure_show_legend: bool,
    figure_show_box: bool,
    figure_x_limits: Option<(f64, f64)>,
    figure_y_limits: Option<(f64, f64)>,
    legend_entries: Vec<LegendEntry>,
    figure_x_log: bool,
    figure_y_log: bool,
    figure_axis_equal: bool,
    figure_colormap: ColorMap,
    figure_colorbar_enabled: bool,
    // Categorical axis cache
    figure_categorical_is_x: Option<bool>,
    figure_categorical_labels: Option<Vec<String>>,
    /// Per-axes cameras (for subplots and single-axes figures).
    axes_cameras: Vec<Camera>,
    /// Keep a clone of the last figure set for export/UX operations
    pub(crate) last_figure: Option<crate::plots::Figure>,

    /// Last surface extent (in pixels) that was used to build viewport-dependent geometry.
    /// Used so we can rebuild the scene after the canvas is resized (common on wasm).
    last_scene_viewport_px: Option<(u32, u32)>,
    /// Last per-axes plot viewport sizes used to build viewport-dependent geometry.
    last_axes_plot_sizes_px: Option<Vec<(u32, u32)>>,

    /// If false, do not auto-fit camera when the figure updates (user has interacted).
    camera_auto_fit: bool,
    /// Per-axes 2D camera ownership. True means the user has interacted and automatic 2D refits
    /// should not overwrite the camera during ordinary figure updates.
    axes_2d_camera_user_controlled: Vec<bool>,
    /// Per-node GPU buffer cache for stable interactive redraws.
    scene_buffer_cache: RefCell<HashMap<u64, CachedSceneBuffers>>,
}

/// Configuration for plot rendering
#[derive(Debug, Clone)]
pub struct PlotRenderConfig {
    /// Output dimensions
    pub width: u32,
    pub height: u32,

    /// Background color
    pub background_color: Vec4,

    /// Whether to draw grid
    pub show_grid: bool,

    /// Whether to draw axes
    pub show_axes: bool,

    /// Whether to draw title
    pub show_title: bool,

    /// Anti-aliasing samples
    pub msaa_samples: u32,

    /// Depth mode for 3D rendering (standard vs reversed-Z).
    pub depth_mode: DepthMode,

    /// Clip plane policy for 3D rendering.
    pub clip_policy: ClipPolicy,

    /// Theme to use
    pub theme: crate::styling::PlotThemeConfig,
}

impl Default for PlotRenderConfig {
    fn default() -> Self {
        Self {
            width: 800,
            height: 600,
            background_color: Vec4::new(0.08, 0.09, 0.11, 1.0), // Dark theme background
            show_grid: true,
            show_axes: true,
            show_title: true,
            msaa_samples: 4,
            depth_mode: DepthMode::default(),
            clip_policy: ClipPolicy::default(),
            theme: crate::styling::PlotThemeConfig::default(),
        }
    }
}

/// Target surface information for rendering with optional MSAA resolve.
pub struct RenderTarget<'a> {
    pub view: &'a wgpu::TextureView,
    pub resolve_target: Option<&'a wgpu::TextureView>,
}

/// Result of rendering operation
#[derive(Debug)]
pub struct RenderResult {
    /// Whether rendering was successful
    pub success: bool,

    /// Rendered data bounds
    pub data_bounds: Option<(f64, f64, f64, f64)>,

    /// Performance metrics
    pub vertex_count: usize,
    pub triangle_count: usize,
    pub render_time_ms: f64,
}

impl PlotRenderer {
    /// Notify the renderer that the underlying surface configuration has changed (e.g. resize).
    /// On wasm the canvas is often created at a tiny size and resized shortly after; some
    /// CPU-generated geometry (like thick 2D lines) depends on viewport pixels, so we rebuild
    /// the scene when the surface extent changes.
    pub fn on_surface_config_updated(&mut self) {
        let current = (
            self.wgpu_renderer.surface_config.width.max(1),
            self.wgpu_renderer.surface_config.height.max(1),
        );
        if self.last_scene_viewport_px == Some(current) {
            return;
        }
        let Some(figure) = self.last_figure.clone() else {
            self.last_scene_viewport_px = Some(current);
            return;
        };
        // Rebuild scene using the updated surface extent.
        self.set_figure(figure);
    }

    fn prepare_buffers_for_render_data(
        &self,
        node_id: u64,
        render_data: &crate::core::RenderData,
    ) -> Option<(Arc<wgpu::Buffer>, Option<Arc<wgpu::Buffer>>)> {
        let mut cache = self.scene_buffer_cache.borrow_mut();
        let vertex_signature = (
            render_data.vertices.as_ptr() as usize,
            render_data.vertices.len(),
        );
        let index_signature = render_data
            .indices
            .as_ref()
            .map(|indices| (indices.as_ptr() as usize, indices.len()));

        if let Some(cached) = cache.get(&node_id) {
            if cached.vertex_signature == vertex_signature
                && cached.index_signature == index_signature
            {
                return Some((cached.vertex_buffer.clone(), cached.index_buffer.clone()));
            }
        }

        let vertex_buffer = self
            .wgpu_renderer
            .vertex_buffer_from_sources(render_data.gpu_vertices.as_ref(), &render_data.vertices)?;
        let index_buffer = render_data
            .indices
            .as_ref()
            .map(|indices| Arc::new(self.wgpu_renderer.create_index_buffer(indices)));

        cache.insert(
            node_id,
            CachedSceneBuffers {
                vertex_signature,
                vertex_buffer: vertex_buffer.clone(),
                index_signature,
                index_buffer: index_buffer.clone(),
            },
        );

        Some((vertex_buffer, index_buffer))
    }

    fn gpu_indirect_args(render_data: &crate::core::RenderData) -> Option<(&wgpu::Buffer, u64)> {
        render_data
            .gpu_vertices
            .as_ref()
            .and_then(|buf| buf.indirect.as_ref())
            .map(|indirect| (indirect.args.as_ref(), indirect.offset))
    }

    /// Create a new plot renderer
    pub async fn new(
        device: Arc<wgpu::Device>,
        queue: Arc<wgpu::Queue>,
        surface_config: wgpu::SurfaceConfiguration,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let wgpu_renderer = WgpuRenderer::new(device, queue, surface_config).await;
        let scene = Scene::new();
        let theme = crate::styling::PlotThemeConfig::default();

        Ok(Self {
            wgpu_renderer,
            scene,
            theme,
            data_bounds: None,
            needs_update: true,
            figure_title: None,
            figure_x_label: None,
            figure_y_label: None,
            figure_z_label: None,
            figure_show_grid: true,
            figure_show_legend: true,
            figure_show_box: true,
            figure_x_limits: None,
            figure_y_limits: None,
            legend_entries: Vec::new(),
            figure_x_log: false,
            figure_y_log: false,
            figure_axis_equal: false,
            figure_colormap: ColorMap::Parula,
            figure_colorbar_enabled: false,
            figure_categorical_is_x: None,
            figure_categorical_labels: None,
            axes_cameras: vec![Self::create_default_camera()],
            last_figure: None,
            last_scene_viewport_px: None,
            last_axes_plot_sizes_px: None,
            camera_auto_fit: true,
            axes_2d_camera_user_controlled: vec![false],
            scene_buffer_cache: RefCell::new(HashMap::new()),
        })
    }

    fn plot_element_is_3d(plot: &crate::plots::figure::PlotElement) -> bool {
        match plot {
            crate::plots::figure::PlotElement::Surface(surface) => !surface.image_mode,
            crate::plots::figure::PlotElement::Line3(_) => true,
            crate::plots::figure::PlotElement::Scatter3(_) => true,
            _ => false,
        }
    }

    pub fn axes_has_3d_content(&self, axes_index: usize) -> bool {
        self.last_figure
            .as_ref()
            .map(|figure| {
                figure
                    .plots()
                    .zip(figure.plot_axes_indices().iter().copied())
                    .any(|(plot, plot_axes_index)| {
                        plot_axes_index == axes_index && Self::plot_element_is_3d(plot)
                    })
            })
            .unwrap_or(false)
    }

    /// Mark that the user has interacted with the camera (disable auto-fit-on-update).
    pub fn note_camera_interaction(&mut self) {
        if self.camera_auto_fit {
            log::debug!(target: "runmat_plot", "camera_auto_fit disabled (user interaction)");
        }
        self.camera_auto_fit = false;
    }

    pub fn note_axes_camera_interaction(&mut self, axes_index: usize) {
        self.note_camera_interaction();
        if self.axes_has_3d_content(axes_index) {
            return;
        }
        if let Some(flag) = self.axes_2d_camera_user_controlled.get_mut(axes_index) {
            *flag = true;
        }
    }

    fn clear_axes_camera_interaction(&mut self, axes_index: usize) {
        if let Some(flag) = self.axes_2d_camera_user_controlled.get_mut(axes_index) {
            *flag = false;
        }
    }

    fn clear_all_axes_camera_interaction(&mut self) {
        for flag in &mut self.axes_2d_camera_user_controlled {
            *flag = false;
        }
    }

    /// Set the figure to render
    pub fn set_figure(&mut self, figure: Figure) {
        // Clear existing scene
        self.scene.clear();
        self.scene_buffer_cache.borrow_mut().clear();

        // Convert figure to scene nodes
        self.cache_figure_meta(&figure);
        self.last_figure = Some(figure.clone());
        self.last_axes_plot_sizes_px = None;
        // Initialize axes cameras for subplot grid
        let (rows, cols) = figure.axes_grid();
        let num_axes = rows.max(1) * cols.max(1);

        if self.axes_cameras.len() != num_axes {
            self.axes_cameras
                .resize_with(num_axes, Self::create_default_camera);
            self.axes_2d_camera_user_controlled.resize(num_axes, false);
            self.camera_auto_fit = true;
        }

        for axes_index in 0..num_axes {
            let wants_3d = self.axes_has_3d_content(axes_index);
            let has_3d_camera = self
                .axes_cameras
                .get(axes_index)
                .map(|cam| {
                    matches!(
                        cam.projection,
                        crate::core::camera::ProjectionType::Perspective { .. }
                    )
                })
                .unwrap_or(false);
            if wants_3d != has_3d_camera {
                self.axes_cameras[axes_index] = if wants_3d {
                    Camera::new()
                } else {
                    Self::create_default_camera()
                };
                self.clear_axes_camera_interaction(axes_index);
                self.camera_auto_fit = true;
            }
        }

        self.add_figure_to_scene(figure);

        // Mark for update
        self.needs_update = true;

        // Recompute bounds and fit camera immediately (only once per initial dataset).
        let fit_applied = if self.camera_auto_fit {
            if num_axes > 1 {
                self.fit_cameras_to_axes_data()
            } else {
                self.fit_camera_to_data()
            }
        } else {
            false
        };
        if self.camera_auto_fit && fit_applied {
            // Freeze the initial fit (CAD-like): don't re-fit as data updates (e.g. animations)
            // unless the user explicitly asks (Fit Extents / Reset View) or we change plot mode.
            self.camera_auto_fit = false;
        }
        self.apply_stored_axes_views();
    }

    /// Add a figure to the current scene
    fn add_figure_to_scene(&mut self, figure: Figure) {
        self.add_figure_to_scene_with_axes_plot_sizes(figure, None);
    }

    fn add_figure_to_scene_with_axes_plot_sizes(
        &mut self,
        mut figure: Figure,
        axes_plot_sizes_px: Option<&[(u32, u32)]>,
    ) {
        use crate::core::SceneNode;

        // Convert figure to render data first, then create scene nodes
        let viewport_px = (
            self.wgpu_renderer.surface_config.width.max(1),
            self.wgpu_renderer.surface_config.height.max(1),
        );
        self.last_scene_viewport_px = Some(viewport_px);
        let gpu = crate::core::GpuPackContext {
            device: &self.wgpu_renderer.device,
            queue: &self.wgpu_renderer.queue,
        };
        let render_data_list = figure.render_data_with_axes_with_viewport_and_gpu(
            Some(viewport_px),
            axes_plot_sizes_px,
            Some(&gpu),
        );
        let (rows, cols) = figure.axes_grid();

        for (node_id_counter, (axes_index, render_data)) in render_data_list.into_iter().enumerate()
        {
            let axes_index = axes_index.min(rows * cols - 1);
            // Create scene node for this plot element
            let node = SceneNode {
                id: node_id_counter as u64,
                name: format!("Plot {node_id_counter} @axes {axes_index}"),
                transform: Mat4::IDENTITY,
                visible: true,
                cast_shadows: false,
                receive_shadows: false,
                axes_index,
                parent: None,
                children: Vec::new(),
                render_data: Some(render_data),
                bounds: crate::core::BoundingBox::default(),
                lod_levels: Vec::new(),
                current_lod: 0,
            };

            let nid = self.scene.add_node(node);
            // Tag node with axes index via a no-op mechanism for now (could extend SceneNode in future)
            let _ = nid;
            let _ = axes_index;
            let _ = rows;
            let _ = cols;
        }
    }

    pub fn ensure_scene_viewport_dependent_geometry_for_axes(
        &mut self,
        axes_plot_sizes_px: &[(u32, u32)],
    ) {
        let normalized: Vec<(u32, u32)> = axes_plot_sizes_px
            .iter()
            .map(|&(w, h)| (w.max(1), h.max(1)))
            .collect();
        if self.last_axes_plot_sizes_px.as_ref() == Some(&normalized) {
            return;
        }
        let Some(figure) = self.last_figure.clone() else {
            self.last_axes_plot_sizes_px = Some(normalized);
            return;
        };
        self.scene.clear();
        self.scene_buffer_cache.borrow_mut().clear();
        self.add_figure_to_scene_with_axes_plot_sizes(figure, Some(&normalized));
        log::debug!(
            target: "runmat_plot.viewport_rebuild",
            "rebuilt viewport-dependent scene geometry axes_count={} viewport_sizes={:?}",
            normalized.len(),
            normalized
        );
        self.refit_2d_cameras_to_scene_bounds();
        self.last_axes_plot_sizes_px = Some(normalized);
        self.needs_update = true;
    }

    fn refit_2d_cameras_to_scene_bounds(&mut self) {
        for idx in 0..self.axes_cameras.len() {
            if self.axes_has_3d_content(idx) {
                continue;
            }
            if self
                .axes_2d_camera_user_controlled
                .get(idx)
                .copied()
                .unwrap_or(false)
            {
                continue;
            }
            let Some((x_min, x_max, y_min, y_max)) = self.display_bounds_for_axes(idx) else {
                continue;
            };
            let geometry_bounds = self.axes_bounds(idx);
            let Some(cam) = self.axes_cameras.get_mut(idx) else {
                continue;
            };
            if let crate::core::camera::ProjectionType::Orthographic {
                ref mut left,
                ref mut right,
                ref mut bottom,
                ref mut top,
                ..
            } = cam.projection
            {
                *left = x_min as f32;
                *right = x_max as f32;
                *bottom = y_min as f32;
                *top = y_max as f32;
                let camera_left = *left;
                let camera_right = *right;
                let camera_bottom = *bottom;
                let camera_top = *top;
                cam.position.z = 1.0;
                cam.target.z = 0.0;
                cam.mark_dirty();
                if let Some(bounds) = geometry_bounds {
                    log::debug!(
                        target: "runmat_plot.camera_refit",
                        "refit 2d camera to rebuilt scene bounds axes_index={} geometry=({}, {})..({}, {}) camera=({}, {})..({}, {}) margins=top:{} bottom:{} left:{} right:{}",
                        idx,
                        bounds.min.x,
                        bounds.min.y,
                        bounds.max.x,
                        bounds.max.y,
                        camera_left,
                        camera_bottom,
                        camera_right,
                        camera_top,
                        camera_top - bounds.max.y,
                        bounds.min.y - camera_bottom,
                        bounds.min.x - camera_left,
                        camera_right - bounds.max.x
                    );
                } else {
                    log::debug!(
                        target: "runmat_plot.camera_refit",
                        "refit 2d camera without geometry bounds axes_index={} camera=({}, {})..({}, {})",
                        idx,
                        camera_left,
                        camera_bottom,
                        camera_right,
                        camera_top
                    );
                }
                if let Some(display_bounds) = self.display_bounds_for_axes(idx) {
                    log::debug!(
                        target: "runmat_plot.bounds_chain",
                        "bounds chain axes_index={} axes_bounds=({}, {})..({}, {}) display_bounds=({}, {})..({}, {}) camera_bounds=({}, {})..({}, {})",
                        idx,
                        geometry_bounds.map(|b| b.min.x as f64).unwrap_or(f64::NAN),
                        geometry_bounds.map(|b| b.min.y as f64).unwrap_or(f64::NAN),
                        geometry_bounds.map(|b| b.max.x as f64).unwrap_or(f64::NAN),
                        geometry_bounds.map(|b| b.max.y as f64).unwrap_or(f64::NAN),
                        display_bounds.0,
                        display_bounds.2,
                        display_bounds.1,
                        display_bounds.3,
                        camera_left,
                        camera_bottom,
                        camera_right,
                        camera_top
                    );
                }
            }
        }
    }

    /// Cache figure metadata for overlay consumption
    fn cache_figure_meta(&mut self, figure: &Figure) {
        self.figure_title = figure.title.clone();
        self.figure_x_label = figure.x_label.clone();
        self.figure_y_label = figure.y_label.clone();
        self.figure_z_label = figure.z_label.clone();
        self.figure_show_grid = figure.grid_enabled;
        self.figure_show_legend = figure.legend_enabled;
        self.figure_show_box = figure.box_enabled;
        self.figure_x_limits = figure.x_limits;
        self.figure_y_limits = figure.y_limits;
        self.legend_entries = figure.legend_entries();
        self.figure_x_log = figure.x_log;
        self.figure_y_log = figure.y_log;
        self.figure_axis_equal = figure.axis_equal;
        self.figure_colormap = figure.colormap;
        self.figure_colorbar_enabled = figure.colorbar_enabled;
        // Cache categorical labels for overlay
        if let Some((is_x, labels)) = figure.categorical_axis_labels() {
            self.figure_categorical_is_x = Some(is_x);
            self.figure_categorical_labels = Some(labels);
        } else {
            self.figure_categorical_is_x = None;
            self.figure_categorical_labels = None;
        }
    }

    fn apply_stored_axes_views(&mut self) {
        let Some(fig) = self.last_figure.as_ref() else {
            return;
        };
        for (idx, cam) in self.axes_cameras.iter_mut().enumerate() {
            if !matches!(
                cam.projection,
                crate::core::camera::ProjectionType::Perspective { .. }
            ) {
                continue;
            }
            if let Some(meta) = fig.axes_metadata(idx) {
                if let (Some(az), Some(el)) = (meta.view_azimuth_deg, meta.view_elevation_deg) {
                    cam.set_view_angles_deg(az, el);
                }
            }
        }
    }

    fn display_bounds_for_axes(&self, axes_index: usize) -> Option<(f64, f64, f64, f64)> {
        let base = self.axes_bounds(axes_index)?;
        let mut x_min = base.min.x as f64;
        let mut x_max = base.max.x as f64;
        let mut y_min = base.min.y as f64;
        let mut y_max = base.max.y as f64;

        if let Some(fig) = self.last_figure.as_ref() {
            if let Some(meta) = fig.axes_metadata(axes_index) {
                if let Some((xl, xr)) = meta.x_limits {
                    x_min = xl;
                    x_max = xr;
                }
                if let Some((yl, yr)) = meta.y_limits {
                    y_min = yl;
                    y_max = yr;
                }
                if meta.axis_equal {
                    let cx = (x_min + x_max) * 0.5;
                    let cy = (y_min + y_max) * 0.5;
                    let size = (x_max - x_min).abs().max((y_max - y_min).abs()).max(0.1);
                    x_min = cx - size * 0.5;
                    x_max = cx + size * 0.5;
                    y_min = cy - size * 0.5;
                    y_max = cy + size * 0.5;
                }
            }
        }

        Some((x_min, x_max, y_min, y_max))
    }

    fn fit_cameras_to_axes_data(&mut self) -> bool {
        let mut applied = false;
        for idx in 0..self.axes_cameras.len() {
            if self.axes_has_3d_content(idx) {
                let Some(bounds) = self.axes_bounds(idx) else {
                    continue;
                };
                let center = (bounds.min + bounds.max) * 0.5;
                let mut cam = Camera::new();
                cam.target = center;
                cam.up = Vec3::Z;
                cam.position = center + Vec3::new(1.0, -1.0, 1.0);
                cam.fit_bounds(bounds.min, bounds.max);
                self.axes_cameras[idx] = cam;
                applied = true;
                continue;
            }

            let Some((x_min, x_max, y_min, y_max)) = self.display_bounds_for_axes(idx) else {
                continue;
            };
            let mut cam = Self::create_default_camera();
            if let crate::core::camera::ProjectionType::Orthographic {
                ref mut left,
                ref mut right,
                ref mut bottom,
                ref mut top,
                ..
            } = cam.projection
            {
                *left = x_min as f32;
                *right = x_max as f32;
                *bottom = y_min as f32;
                *top = y_max as f32;
            }
            cam.position.z = 1.0;
            cam.target.z = 0.0;
            cam.mark_dirty();
            self.axes_cameras[idx] = cam;
            applied = true;
        }
        applied
    }

    /// Calculate data bounds from scene
    pub fn calculate_data_bounds(&mut self) -> Option<(f64, f64, f64, f64)> {
        let mut min_x = f64::INFINITY;
        let mut max_x = f64::NEG_INFINITY;
        let mut min_y = f64::INFINITY;
        let mut max_y = f64::NEG_INFINITY;

        for node in self.scene.get_visible_nodes() {
            if let Some(render_data) = &node.render_data {
                if let Some(bounds) = render_data.bounds {
                    min_x = min_x.min(bounds.min.x as f64);
                    max_x = max_x.max(bounds.max.x as f64);
                    min_y = min_y.min(bounds.min.y as f64);
                    max_y = max_y.max(bounds.max.y as f64);
                    continue;
                }
                for vertex in &render_data.vertices {
                    let x = vertex.position[0] as f64;
                    let y = vertex.position[1] as f64;
                    min_x = min_x.min(x);
                    max_x = max_x.max(x);
                    min_y = min_y.min(y);
                    max_y = max_y.max(y);
                }
            }
        }

        if min_x != f64::INFINITY && max_x != f64::NEG_INFINITY {
            // Add a small margin around data for readability without making
            // the plotted curve appear to exceed the labeled axis range.
            let x_range = (max_x - min_x).max(0.1);
            let y_range = (max_y - min_y).max(0.1);
            let x_margin = x_range * 0.04;
            let y_margin = y_range * 0.04;

            let bounds = (
                min_x - x_margin,
                max_x + x_margin,
                min_y - y_margin,
                max_y + y_margin,
            );

            // println!("Calculated data bounds: {:?}", bounds); // Too noisy
            self.data_bounds = Some(bounds);
            Some(bounds)
        } else {
            self.data_bounds = None;
            None
        }
    }

    /// Fit camera to show all data.
    ///
    /// Returns `true` if a fit was applied (i.e. bounds existed).
    pub fn fit_camera_to_data(&mut self) -> bool {
        if self.axes_cameras.len() > 1 {
            return self.fit_cameras_to_axes_data();
        }

        if self.axes_has_3d_content(0) {
            let Some(bounds) = self.axes_bounds(0) else {
                return false;
            };
            let center = (bounds.min + bounds.max) * 0.5;
            let mut cam = Camera::new();
            cam.target = center;
            cam.up = Vec3::Z;
            cam.position = center + Vec3::new(1.0, -1.0, 1.0);
            cam.fit_bounds(bounds.min, bounds.max);
            if let Some(axis_cam) = self.axes_cameras.get_mut(0) {
                *axis_cam = cam;
            }
            return true;
        }

        if let Some((x_min, x_max, y_min, y_max)) = self.display_bounds_for_axes(0) {
            // Match the camera bounds exactly to data bounds to align with overlay grid
            let mut cam = Self::create_default_camera();
            let l = x_min as f32;
            let r = x_max as f32;
            let b = y_min as f32;
            let t = y_max as f32;
            if let crate::core::camera::ProjectionType::Orthographic {
                ref mut left,
                ref mut right,
                ref mut bottom,
                ref mut top,
                ..
            } = cam.projection
            {
                *left = l;
                *right = r;
                *bottom = b;
                *top = t;
            }
            cam.position.z = 1.0;
            cam.target.z = 0.0;
            cam.mark_dirty();

            if let Some(axis_cam) = self.axes_cameras.get_mut(0) {
                *axis_cam = cam;
            }
            return true;
        }
        false
    }

    /// Explicit "Fit Extents" action (CAD-like). Fits the camera to current data once.
    pub fn fit_extents(&mut self) {
        let _ = if self.figure_axes_grid().0 * self.figure_axes_grid().1 > 1 {
            self.fit_cameras_to_axes_data()
        } else {
            self.fit_camera_to_data()
        };
        self.clear_all_axes_camera_interaction();
        self.camera_auto_fit = false;
        self.needs_update = true;
    }

    /// Explicit "Reset Camera" action. Restores the default orientation without re-framing.
    ///
    /// For 3D, this resets the view direction around the current data center (or current target)
    /// while preserving the current zoom distance.
    /// For 2D, this is equivalent to Fit Extents (since "home" without data bounds is rarely useful).
    pub fn reset_camera_position(&mut self) {
        let dir = Vec3::new(1.0, -1.0, 1.0).normalize_or_zero();
        let data_centers: Vec<Vec3> = (0..self.axes_cameras.len())
            .map(|idx| {
                self.axes_bounds(idx)
                    .map(|b| (b.min + b.max) * 0.5)
                    .unwrap_or_else(|| self.axes_cameras[idx].target)
            })
            .collect();
        let display_bounds: Vec<Option<(f64, f64, f64, f64)>> = (0..self.axes_cameras.len())
            .map(|idx| self.display_bounds_for_axes(idx))
            .collect();
        for (idx, c) in self.axes_cameras.iter_mut().enumerate() {
            if matches!(
                c.projection,
                crate::core::camera::ProjectionType::Perspective { .. }
            ) {
                let data_center = data_centers.get(idx).copied().unwrap_or(c.target);
                let dist = (c.position - c.target).length().max(0.1);
                c.target = data_center;
                c.up = Vec3::Z;
                c.position = data_center + dir * dist;
                c.mark_dirty();
            } else if let Some((x_min, x_max, y_min, y_max)) = display_bounds[idx] {
                let mut cam = Self::create_default_camera();
                if let crate::core::camera::ProjectionType::Orthographic {
                    ref mut left,
                    ref mut right,
                    ref mut bottom,
                    ref mut top,
                    ..
                } = cam.projection
                {
                    *left = x_min as f32;
                    *right = x_max as f32;
                    *bottom = y_min as f32;
                    *top = y_max as f32;
                }
                cam.position.z = 1.0;
                cam.target.z = 0.0;
                cam.mark_dirty();
                *c = cam;
            }
        }
        self.clear_all_axes_camera_interaction();
        self.camera_auto_fit = false;
        self.needs_update = true;
    }

    /// Render the current scene to a specific viewport within a texture/surface
    pub fn render_to_viewport(
        &mut self,
        encoder: &mut wgpu::CommandEncoder,
        target_view: &wgpu::TextureView,
        _viewport: (f32, f32, f32, f32), // (x, y, width, height) in framebuffer coordinates
        clear_background: bool,
        background_color: Option<glam::Vec4>,
    ) -> Result<RenderResult, Box<dyn std::error::Error>> {
        let start_time = Instant::now();

        // Collect render data and create buffers first
        let mut render_items = Vec::new();
        let mut total_vertices = 0;
        let mut total_triangles = 0;

        for node in self.scene.get_visible_nodes() {
            if let Some(render_data) = &node.render_data {
                if let Some(vertex_buffer) = self.wgpu_renderer.vertex_buffer_from_sources(
                    render_data.gpu_vertices.as_ref(),
                    &render_data.vertices,
                ) {
                    self.wgpu_renderer
                        .ensure_pipeline(render_data.pipeline_type);

                    log::trace!(
                        target: "runmat_plot",
                        "upload vertices={}, draw_calls={}",
                        render_data.vertex_count(),
                        render_data.draw_calls.len()
                    );

                    render_items.push((render_data, vertex_buffer));
                    total_vertices += render_data.vertex_count();

                    if render_data.pipeline_type == crate::core::PipelineType::Triangles {
                        total_triangles += render_data.vertex_count() / 3;
                    }
                }
            }
        }

        // Update uniforms
        let mut cam = self.camera().clone();
        let view_proj_matrix = cam.view_proj_matrix();

        self.wgpu_renderer
            .update_uniforms(view_proj_matrix, Mat4::IDENTITY);

        // Create render pass (respect MSAA)
        let use_msaa = self.wgpu_renderer.msaa_sample_count > 1;
        let msaa_view_opt = if use_msaa {
            let tex = self
                .wgpu_renderer
                .device
                .create_texture(&wgpu::TextureDescriptor {
                    label: Some("runmat_msaa_color_camera"),
                    size: wgpu::Extent3d {
                        width: self.wgpu_renderer.surface_config.width,
                        height: self.wgpu_renderer.surface_config.height,
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: self.wgpu_renderer.msaa_sample_count,
                    dimension: wgpu::TextureDimension::D2,
                    format: self.wgpu_renderer.surface_config.format,
                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                    view_formats: &[],
                });
            Some(tex.create_view(&wgpu::TextureViewDescriptor::default()))
        } else {
            None
        };

        let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("Viewport Plot Render Pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: msaa_view_opt.as_ref().unwrap_or(target_view),
                resolve_target: if use_msaa { Some(target_view) } else { None },
                ops: wgpu::Operations {
                    load: if clear_background {
                        wgpu::LoadOp::Clear(wgpu::Color {
                            r: background_color.map_or(0.08, |c| c.x as f64),
                            g: background_color.map_or(0.09, |c| c.y as f64),
                            b: background_color.map_or(0.11, |c| c.z as f64),
                            a: background_color.map_or(1.0, |c| c.w as f64),
                        })
                    } else {
                        wgpu::LoadOp::Load
                    },
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            occlusion_query_set: None,
            timestamp_writes: None,
        });

        // Apply viewport scissor to match overlay plot rect
        let (vx, vy, vw, vh) = _viewport;
        render_pass.set_viewport(vx, vy, vw, vh, 0.0, 1.0);

        // Configure direct-uniforms for precise data-to-NDC mapping within this viewport
        let sw = self.wgpu_renderer.surface_config.width as f32;
        let sh = self.wgpu_renderer.surface_config.height as f32;
        let ndc_left = (vx / sw) * 2.0 - 1.0;
        let ndc_right = ((vx + vw) / sw) * 2.0 - 1.0;
        let ndc_top = 1.0 - (vy / sh) * 2.0;
        let ndc_bottom = 1.0 - ((vy + vh) / sh) * 2.0;

        // data_bounds passed in from caller: (x_min, y_min, x_max, y_max)
        let (x_min, y_min, x_max, y_max) = (0.0_f64, 0.0_f64, 1.0_f64, 1.0_f64);
        self.wgpu_renderer.update_direct_uniforms(
            [x_min as f32, y_min as f32],
            [x_max as f32, y_max as f32],
            [ndc_left, ndc_bottom],
            [ndc_right, ndc_top],
            [sw, sh],
        );

        // Continue with specific pipelines below (implementation omitted here)
        drop(render_pass);

        let render_time = start_time.elapsed().as_secs_f64() * 1000.0;

        Ok(RenderResult {
            success: true,
            data_bounds: self.data_bounds,
            vertex_count: total_vertices,
            triangle_count: total_triangles,
            render_time_ms: render_time,
        })
    }

    /// Render the current scene to a texture/surface
    pub fn render(
        &mut self,
        encoder: &mut wgpu::CommandEncoder,
        target: RenderTarget<'_>,
        config: &PlotRenderConfig,
    ) -> Result<RenderResult, Box<dyn std::error::Error>> {
        let start_time = Instant::now();

        self.wgpu_renderer.ensure_msaa(config.msaa_samples);

        // Update WGPU uniforms from primary axes camera
        let aspect_ratio = config.width as f32 / config.height as f32;
        let mut cam = self.camera().clone();
        cam.update_aspect_ratio(aspect_ratio);
        let view_proj_matrix = cam.view_proj_matrix();
        let model_matrix = Mat4::IDENTITY;
        self.wgpu_renderer
            .update_uniforms(view_proj_matrix, model_matrix);

        // Collect all render data and create vertex buffers first (outside render pass)
        let mut render_items = Vec::new();
        let mut total_vertices = 0;
        let mut total_triangles = 0;

        for node in self.scene.get_visible_nodes() {
            if let Some(render_data) = &node.render_data {
                if let Some((vertex_buffer, index_buffer)) =
                    self.prepare_buffers_for_render_data(node.id, render_data)
                {
                    self.wgpu_renderer
                        .ensure_pipeline(render_data.pipeline_type);
                    render_items.push((render_data, vertex_buffer, index_buffer));

                    total_vertices += render_data.vertex_count();
                    if let Some(indices) = &render_data.indices {
                        total_triangles += indices.len() / 3;
                    }
                }
            }
        }

        // Pre-create image bind groups and set direct uniforms once (for textured items)
        let mut image_bind_groups: Vec<Option<wgpu::BindGroup>> =
            Vec::with_capacity(render_items.len());
        let has_textured_items = render_items.iter().any(|(render_data, _, _)| {
            render_data.pipeline_type == crate::core::PipelineType::Textured
        });
        if has_textured_items {
            // Ensure image pipeline once to avoid mutable borrow during pass.
            self.wgpu_renderer.ensure_image_pipeline();
            let mut inferred_bounds: Option<(f64, f64, f64, f64)> = None;
            for (render_data, _, _) in &render_items {
                let Some(bounds) = render_data.bounds.as_ref() else {
                    continue;
                };
                let min_x = bounds.min.x as f64;
                let max_x = bounds.max.x as f64;
                let min_y = bounds.min.y as f64;
                let max_y = bounds.max.y as f64;
                inferred_bounds = Some(match inferred_bounds {
                    Some((x0, x1, y0, y1)) => {
                        (x0.min(min_x), x1.max(max_x), y0.min(min_y), y1.max(max_y))
                    }
                    None => (min_x, max_x, min_y, max_y),
                });
            }

            let (mut x_min, mut x_max, mut y_min, mut y_max) = self
                .data_bounds
                .or(inferred_bounds)
                .unwrap_or((-1.0, 1.0, -1.0, 1.0));
            // Avoid zero ranges in the direct image shader (division by data_range).
            if (x_max - x_min).abs() < f64::EPSILON {
                x_min -= 0.5;
                x_max += 0.5;
            }
            if (y_max - y_min).abs() < f64::EPSILON {
                y_min -= 0.5;
                y_max += 0.5;
            }
            log::trace!(
                target: "runmat_plot",
                "direct uniforms bounds x=({}, {}) y=({}, {}) size=({}, {})",
                x_min,
                x_max,
                y_min,
                y_max,
                config.width,
                config.height
            );
            self.wgpu_renderer.update_direct_uniforms(
                [x_min as f32, y_min as f32],
                [x_max as f32, y_max as f32],
                [-1.0, -1.0],
                [1.0, 1.0],
                [config.width as f32, config.height as f32],
            );
        }
        for (render_data, _vb, _ib) in &render_items {
            if render_data.pipeline_type == crate::core::PipelineType::Textured {
                if let Some(crate::core::scene::ImageData::Rgba8 {
                    width,
                    height,
                    data,
                }) = &render_data.image
                {
                    let (_tex, _view, img_bg) = self
                        .wgpu_renderer
                        .create_image_texture_and_bind_group(*width, *height, data);
                    image_bind_groups.push(Some(img_bg));
                } else {
                    image_bind_groups.push(None);
                }
            } else {
                image_bind_groups.push(None);
            }
        }
        let mut point_style_bind_groups: Vec<Option<wgpu::BindGroup>> =
            Vec::with_capacity(render_items.len());
        for (render_data, _vb, _ib) in &render_items {
            if render_data.pipeline_type == crate::core::PipelineType::Points {
                let style = crate::core::renderer::PointStyleUniforms {
                    face_color: render_data.material.albedo.to_array(),
                    edge_color: render_data.material.emissive.to_array(),
                    edge_thickness_px: render_data.material.roughness,
                    marker_shape: render_data.material.metallic as u32,
                    _pad: [0.0, 0.0],
                };
                let (_buf, bg) = self.wgpu_renderer.create_point_style_bind_group(style);
                point_style_bind_groups.push(Some(bg));
            } else {
                point_style_bind_groups.push(None);
            }
        }

        // Create render pass
        {
            let depth_view = self.wgpu_renderer.ensure_depth_view();
            let use_msaa = self.wgpu_renderer.msaa_sample_count > 1;
            let mut cached_msaa_view: Option<Arc<wgpu::TextureView>> = None;

            let (color_view, resolve_target) = if use_msaa {
                if let Some(explicit_resolve_target) = target.resolve_target {
                    (target.view, Some(explicit_resolve_target))
                } else {
                    cached_msaa_view = Some(self.wgpu_renderer.ensure_msaa_color_view());
                    (
                        cached_msaa_view
                            .as_ref()
                            .expect("msaa color view should exist")
                            .as_ref(),
                        Some(target.view),
                    )
                }
            } else {
                (target.view, target.resolve_target)
            };

            let depth_clear = match self.wgpu_renderer.depth_mode {
                crate::core::DepthMode::Standard => 1.0,
                crate::core::DepthMode::ReversedZ => 0.0,
            };
            let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Plot Render Pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: color_view,
                    resolve_target,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color {
                            r: config.background_color.x as f64,
                            g: config.background_color.y as f64,
                            b: config.background_color.z as f64,
                            a: config.background_color.w as f64,
                        }),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                    view: &depth_view,
                    depth_ops: Some(wgpu::Operations {
                        load: wgpu::LoadOp::Clear(depth_clear),
                        store: wgpu::StoreOp::Discard,
                    }),
                    stencil_ops: None,
                }),
                occlusion_query_set: None,
                timestamp_writes: None,
            });
            let _keep_msaa_view_alive = &cached_msaa_view;

            // Now render all items with proper bind group setup
            for (i, (render_data, vertex_buffer, index_buffer)) in render_items.iter().enumerate() {
                #[cfg(target_arch = "wasm32")]
                {
                    // On wasm, "blank but drawing" is often caused by bad vertex data (NaNs/alpha=0)
                    // or using the wrong pipeline. Emit a single summary per item.
                    if log::log_enabled!(log::Level::Debug) {
                        if let Some(v0) = render_data.vertices.first() {
                            log::debug!(
                                target: "runmat_plot",
                                "wasm draw item: pipeline={:?} verts={} v0.pos=({:.3},{:.3},{:.3}) v0.color=({:.3},{:.3},{:.3},{:.3})",
                                render_data.pipeline_type,
                                render_data.vertices.len(),
                                v0.position[0],
                                v0.position[1],
                                v0.position[2],
                                v0.color[0],
                                v0.color[1],
                                v0.color[2],
                                v0.color[3],
                            );
                        } else if render_data.gpu_vertices.is_some() {
                            log::debug!(
                                target: "runmat_plot",
                                "wasm draw item: pipeline={:?} using gpu_vertices vertex_count={}",
                                render_data.pipeline_type,
                                render_data.vertex_count(),
                            );
                        } else {
                            log::debug!(
                                target: "runmat_plot",
                                "wasm draw item: pipeline={:?} has no vertices",
                                render_data.pipeline_type
                            );
                        }
                    }
                }

                // Get the appropriate pipeline for this render data (pipeline ensured above)
                if render_data.pipeline_type == crate::core::PipelineType::Textured {
                    // Ensure image pipeline
                    let pipeline = self.wgpu_renderer.get_pipeline(render_data.pipeline_type);
                    render_pass.set_pipeline(pipeline);
                    // Bind direct uniforms at set(0)
                    // Use data bounds for image mapping
                    render_pass.set_bind_group(
                        0,
                        &self.wgpu_renderer.direct_uniform_bind_group,
                        &[],
                    );
                    if let Some(ref img_bg) = image_bind_groups[i] {
                        render_pass.set_bind_group(1, img_bg, &[]);
                    }
                } else {
                    let pipeline = self.wgpu_renderer.get_pipeline(render_data.pipeline_type);
                    render_pass.set_pipeline(pipeline);
                    // Set the uniform bind group (required by shaders)
                    render_pass.set_bind_group(0, self.wgpu_renderer.get_uniform_bind_group(), &[]);
                }

                render_pass.set_vertex_buffer(0, vertex_buffer.slice(..));

                if let Some(index_buffer) = index_buffer {
                    render_pass.set_index_buffer(index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                    if let Some(indices) = &render_data.indices {
                        log::trace!(target: "runmat_plot", "draw indexed count={}", indices.len());
                        render_pass.draw_indexed(0..indices.len() as u32, 0, 0..1);
                    }
                } else {
                    log::trace!(target: "runmat_plot", "draw direct vertices");
                    if let Some((args, offset)) = Self::gpu_indirect_args(render_data) {
                        render_pass.draw_indirect(args, offset);
                        continue;
                    }
                    // Use draw_calls from render_data for proper vertex range handling
                    for draw_call in &render_data.draw_calls {
                        log::trace!(
                            target: "runmat_plot",
                            "draw vertices offset={} count={} instances={}",
                            draw_call.vertex_offset,
                            draw_call.vertex_count,
                            draw_call.instance_count
                        );
                        render_pass.draw(
                            draw_call.vertex_offset as u32
                                ..(draw_call.vertex_offset + draw_call.vertex_count) as u32,
                            0..draw_call.instance_count as u32,
                        );
                    }
                }
            }
            // drop render_pass at end of scope
        }

        let render_time = start_time.elapsed().as_secs_f64() * 1000.0;

        Ok(RenderResult {
            success: true,
            data_bounds: self.data_bounds,
            vertex_count: total_vertices,
            triangle_count: total_triangles,
            render_time_ms: render_time,
        })
    }

    /// Shared scene orchestration for non-overlay render targets.
    ///
    /// For single-axes figures this follows the direct full-target render path.
    /// For subplot grids, it renders each axes into a deterministic tiled viewport layout.
    pub fn render_scene_to_target(
        &mut self,
        encoder: &mut wgpu::CommandEncoder,
        target_view: &wgpu::TextureView,
        config: &PlotRenderConfig,
    ) -> Result<RenderResult, Box<dyn std::error::Error>> {
        let start_time = Instant::now();
        let (rows, cols) = self.figure_axes_grid();
        let axes_count = rows.saturating_mul(cols);
        log::debug!(
            "runmat-plot: renderer.scene_to_target.start rows={} cols={} axes_count={} width={} height={}",
            rows,
            cols,
            axes_count,
            config.width,
            config.height
        );
        if axes_count <= 1 {
            log::debug!("runmat-plot: renderer.scene_to_target.branch_single_axes");
            return self.render(
                encoder,
                RenderTarget {
                    view: target_view,
                    resolve_target: None,
                },
                config,
            );
        }

        let viewports =
            Self::compute_tiled_viewports(config.width.max(1), config.height.max(1), rows, cols);
        log::debug!(
            "runmat-plot: renderer.scene_to_target.branch_subplot_axes viewports={}",
            viewports.len()
        );
        self.render_axes_to_viewports(
            encoder,
            target_view,
            &viewports,
            config.msaa_samples.max(1),
            config,
        )?;
        let stats = self.scene.statistics();
        Ok(RenderResult {
            success: true,
            data_bounds: self.data_bounds,
            vertex_count: stats.total_vertices,
            triangle_count: stats.total_triangles,
            render_time_ms: start_time.elapsed().as_secs_f64() * 1000.0,
        })
    }

    fn compute_tiled_viewports(
        total_width: u32,
        total_height: u32,
        rows: usize,
        cols: usize,
    ) -> Vec<(u32, u32, u32, u32)> {
        if rows == 0 || cols == 0 {
            return vec![(0, 0, total_width.max(1), total_height.max(1))];
        }
        let rows_u32 = rows as u32;
        let cols_u32 = cols as u32;
        let cell_w = (total_width / cols_u32).max(1);
        let cell_h = (total_height / rows_u32).max(1);
        let mut out = Vec::with_capacity(rows * cols);
        for r in 0..rows_u32 {
            for c in 0..cols_u32 {
                let x = c * cell_w;
                let y = r * cell_h;
                let mut w = cell_w;
                let mut h = cell_h;
                if c + 1 == cols_u32 {
                    w = total_width.saturating_sub(x).max(1);
                }
                if r + 1 == rows_u32 {
                    h = total_height.saturating_sub(y).max(1);
                }
                out.push((x, y, w, h));
            }
        }
        out
    }

    /// Render using the camera-based pipeline into a viewport region with a scissor rectangle.
    /// This preserves existing contents (Load) and draws only inside the viewport rectangle.
    #[allow(clippy::too_many_arguments)]
    pub fn render_camera_to_viewport(
        &mut self,
        encoder: &mut wgpu::CommandEncoder,
        target_view: &wgpu::TextureView,
        viewport_scissor: (u32, u32, u32, u32),
        config: &PlotRenderConfig,
        camera: &Camera,
        axes_index: usize,
        clear_background: bool,
    ) -> Result<RenderResult, Box<dyn std::error::Error>> {
        log::debug!(
            "runmat-plot: renderer.camera_to_viewport.start axes_index={} viewport=({}, {}, {}, {}) clear_background={}",
            axes_index,
            viewport_scissor.0,
            viewport_scissor.1,
            viewport_scissor.2,
            viewport_scissor.3,
            clear_background
        );
        let use_msaa = config.msaa_samples.max(1) > 1;
        self.wgpu_renderer.ensure_msaa(config.msaa_samples);
        let msaa_view_keepalive = if use_msaa {
            Some(self.wgpu_renderer.ensure_msaa_color_view())
        } else {
            None
        };
        let render_target = if let Some(msaa_view) = msaa_view_keepalive.as_ref() {
            RenderTarget {
                view: msaa_view.as_ref(),
                resolve_target: Some(target_view),
            }
        } else {
            RenderTarget {
                view: target_view,
                resolve_target: None,
            }
        };
        self.render_camera_to_target_viewport(
            encoder,
            render_target,
            viewport_scissor,
            config,
            camera,
            axes_index,
            clear_background,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn render_camera_to_target_viewport(
        &mut self,
        encoder: &mut wgpu::CommandEncoder,
        target: RenderTarget<'_>,
        viewport_scissor: (u32, u32, u32, u32),
        config: &PlotRenderConfig,
        camera: &Camera,
        axes_index: usize,
        clear_background: bool,
    ) -> Result<RenderResult, Box<dyn std::error::Error>> {
        let start_time = Instant::now();

        // Apply MSAA preference into pipelines
        self.wgpu_renderer.ensure_msaa(config.msaa_samples);
        self.wgpu_renderer.set_depth_mode(config.depth_mode);

        // Ensure a depth attachment exists for camera-based 3D rendering.
        // This is a no-op for pure 2D direct-mapped pipelines, but is required for correct
        // occlusion in 3D plots (surf/mesh/scatter3).
        let depth_view = self.wgpu_renderer.ensure_depth_view();

        // Update standard uniforms from the provided camera
        let aspect_ratio = (config.width.max(1)) as f32 / (config.height.max(1)) as f32;
        let mut cam = camera.clone();
        cam.update_aspect_ratio(aspect_ratio);
        cam.depth_mode = config.depth_mode;
        log::debug!(
            "runmat-plot: renderer.camera_to_target_viewport.camera_ready axes_index={} aspect_ratio={} msaa_samples={}",
            axes_index,
            aspect_ratio,
            config.msaa_samples
        );

        // Dynamic clip planes (CAD-like): keep near/far tight to visible bounds to avoid
        // clipping surprises and depth precision collapse on huge datasets.
        if config.clip_policy.dynamic {
            let mut bounds: Option<crate::core::scene::BoundingBox> = None;
            for node in self.scene.get_visible_nodes() {
                if let Some(rd) = &node.render_data {
                    if let Some(b) = rd.bounds {
                        bounds = Some(bounds.map_or(b, |acc| acc.union(&b)));
                    }
                }
            }
            if let Some(b) = bounds {
                cam.update_clip_planes_from_world_aabb(b.min, b.max, &config.clip_policy);
            }
        }
        let view_proj_matrix = cam.view_proj_matrix();
        self.wgpu_renderer
            .update_uniforms_for_axes(axes_index, view_proj_matrix, Mat4::IDENTITY);
        log::debug!(
            "runmat-plot: renderer.camera_to_target_viewport.uniforms_updated axes_index={}",
            axes_index
        );

        let (mut sx, mut sy, mut sw, mut sh) = viewport_scissor;
        let target_w = self.wgpu_renderer.surface_config.width.max(1);
        let target_h = self.wgpu_renderer.surface_config.height.max(1);
        if sx >= target_w || sy >= target_h {
            return Ok(RenderResult {
                success: true,
                data_bounds: self.data_bounds,
                vertex_count: 0,
                triangle_count: 0,
                render_time_ms: 0.0,
            });
        }
        sx = sx.min(target_w.saturating_sub(1));
        sy = sy.min(target_h.saturating_sub(1));
        sw = sw.max(1).min(target_w.saturating_sub(sx).max(1));
        sh = sh.max(1).min(target_h.saturating_sub(sy).max(1));
        let is_2d = matches!(
            cam.projection,
            crate::core::camera::ProjectionType::Orthographic { .. }
        );
        log::debug!(
            "runmat-plot: renderer.camera_to_target_viewport.viewport_normalized axes_index={} viewport=({}, {}, {}, {}) is_2d={}",
            axes_index,
            sx,
            sy,
            sw,
            sh,
            is_2d
        );
        match cam.projection {
            crate::core::camera::ProjectionType::Orthographic {
                left,
                right,
                bottom,
                top,
                ..
            } => {
                log::debug!(
                    target: "runmat_plot.draw_camera",
                    "draw camera axes_index={} is_2d=true viewport=({}, {}, {}, {}) bounds=({}, {})..({}, {}) cfg_wh=({}, {})",
                    axes_index,
                    sx,
                    sy,
                    sw,
                    sh,
                    left,
                    bottom,
                    right,
                    top,
                    config.width,
                    config.height
                );
            }
            crate::core::camera::ProjectionType::Perspective { .. } => {
                log::debug!(
                    target: "runmat_plot.draw_camera",
                    "draw camera axes_index={} is_2d=false viewport=({}, {}, {}, {}) cfg_wh=({}, {})",
                    axes_index,
                    sx,
                    sy,
                    sw,
                    sh,
                    config.width,
                    config.height
                );
            }
        }

        // Prepare render items outside the pass
        let mut owned_render_data: Vec<Box<crate::core::RenderData>> = Vec::new();
        let mut render_items = Vec::new();
        let mut grid_plane_buffers: Option<(wgpu::Buffer, wgpu::Buffer)> = None;
        let mut total_vertices = 0usize;
        let mut total_triangles = 0usize;
        log::debug!(
            "runmat-plot: renderer.camera_to_target_viewport.collect_render_items.start axes_index={}",
            axes_index
        );
        for node in self.scene.get_visible_nodes() {
            if let Some(render_data) = &node.render_data {
                if node.axes_index == axes_index {
                    log::debug!(
                        target: "runmat_plot.draw_item",
                        "draw item axes_index={} node_axes_index={} pipeline={:?} vertex_count={} has_indices={} has_bounds={} gpu_vertices={}",
                        axes_index,
                        node.axes_index,
                        render_data.pipeline_type,
                        render_data.vertex_count(),
                        render_data.indices.is_some(),
                        render_data.bounds.is_some(),
                        render_data.gpu_vertices.is_some()
                    );
                }
                if let Some((vb, ib)) = self.prepare_buffers_for_render_data(node.id, render_data) {
                    self.wgpu_renderer
                        .ensure_pipeline(render_data.pipeline_type);
                    total_vertices += render_data.vertex_count();
                    if let Some(indices) = &render_data.indices {
                        total_triangles += indices.len() / 3;
                    }
                    render_items.push((render_data, vb, ib));
                }
            }
        }
        log::debug!(
            "runmat-plot: renderer.camera_to_target_viewport.collect_render_items.ok axes_index={} items={} total_vertices={} total_triangles={}",
            axes_index,
            render_items.len(),
            total_vertices,
            total_triangles
        );

        // 3D helpers: CAD-style XY grid at Z=0 (grid on/off) + origin triad (always).
        // These are generated per-frame so they can adapt to zoom level.
        if !is_2d {
            let view_proj = view_proj_matrix;
            let inv_view_proj = view_proj.inverse();

            let unproject = |ndc_x: f32, ndc_y: f32, ndc_z: f32| -> Option<Vec3> {
                let clip = Vec4::new(ndc_x, ndc_y, ndc_z, 1.0);
                let world = inv_view_proj * clip;
                if !world.w.is_finite() || world.w.abs() < 1e-6 {
                    return None;
                }
                let p = world.truncate() / world.w;
                if p.x.is_finite() && p.y.is_finite() && p.z.is_finite() {
                    Some(p)
                } else {
                    None
                }
            };

            let ray_intersect_z0 = |ndc_x: f32, ndc_y: f32| -> Option<Vec3> {
                // Use a near/far pair in clip space to form a ray.
                let p0 = unproject(ndc_x, ndc_y, -1.0)?;
                let p1 = unproject(ndc_x, ndc_y, 1.0)?;
                let dir = p1 - p0;
                if !dir.z.is_finite() || dir.z.abs() < 1e-8 {
                    return None;
                }
                let t = (-p0.z) / dir.z;
                if !t.is_finite() || t <= 0.0 {
                    return None;
                }
                Some(p0 + dir * t)
            };

            let mut plane_pts: Vec<Vec3> = Vec::new();
            for (nx, ny) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] {
                if let Some(p) = ray_intersect_z0(nx, ny) {
                    plane_pts.push(p);
                }
            }

            // Fallback region if we couldn't intersect enough rays (camera nearly parallel to plane).
            let mut min_x = 0.0_f32;
            let mut max_x = 1.0_f32;
            let mut min_y = 0.0_f32;
            let mut max_y = 1.0_f32;

            if plane_pts.len() >= 2 {
                min_x = plane_pts.iter().map(|p| p.x).fold(f32::INFINITY, f32::min);
                max_x = plane_pts
                    .iter()
                    .map(|p| p.x)
                    .fold(f32::NEG_INFINITY, f32::max);
                min_y = plane_pts.iter().map(|p| p.y).fold(f32::INFINITY, f32::min);
                max_y = plane_pts
                    .iter()
                    .map(|p| p.y)
                    .fold(f32::NEG_INFINITY, f32::max);
            } else if let crate::core::camera::ProjectionType::Perspective { fov, .. } =
                cam.projection
            {
                let dist = (cam.position - cam.target).length().max(1e-3);
                let extent = (dist * (0.5 * fov).tan() * 1.25).max(0.5);
                let center = Vec3::new(cam.target.x, cam.target.y, 0.0);
                min_x = center.x - extent;
                max_x = center.x + extent;
                min_y = center.y - extent;
                max_y = center.y + extent;
            }

            // Expand a bit so grid lines don't pop at edges.
            let dx = (max_x - min_x).abs().max(1e-3);
            let dy = (max_y - min_y).abs().max(1e-3);
            let margin_x = dx * 0.04;
            let margin_y = dy * 0.04;
            min_x -= margin_x;
            max_x += margin_x;
            min_y -= margin_y;
            max_y += margin_y;

            let project_to_px = |p: Vec3| -> Option<(f32, f32)> {
                let clip = view_proj * Vec4::new(p.x, p.y, p.z, 1.0);
                if !clip.w.is_finite() || clip.w.abs() < 1e-6 {
                    return None;
                }
                let ndc = clip.truncate() / clip.w;
                if !(ndc.x.is_finite() && ndc.y.is_finite()) {
                    return None;
                }
                let px = ((ndc.x + 1.0) * 0.5) * (sw.max(1) as f32);
                let py = ((1.0 - ndc.y) * 0.5) * (sh.max(1) as f32);
                Some((px, py))
            };

            let nice_step = |raw: f64| -> f64 {
                if !raw.is_finite() || raw <= 0.0 {
                    return 1.0;
                }
                let pow10 = 10.0_f64.powf(raw.log10().floor());
                let norm = raw / pow10;
                let mult = if norm <= 1.0 {
                    1.0
                } else if norm <= 2.0 {
                    2.0
                } else if norm <= 5.0 {
                    5.0
                } else {
                    10.0
                };
                mult * pow10
            };

            // Determine grid scale from projection at the plane center.
            let cx = (min_x + max_x) * 0.5;
            let cy = (min_y + max_y) * 0.5;
            let center = Vec3::new(cx, cy, 0.0);
            let px_per_world = {
                let a = project_to_px(center);
                let b = project_to_px(center + Vec3::new(1.0, 0.0, 0.0));
                match (a, b) {
                    (Some((ax, ay)), Some((bx, by))) => ((bx - ax).hypot(by - ay)).max(1e-3),
                    _ => 1.0,
                }
            };
            let desired_major_px = 120.0_f64;
            let major_step = nice_step((desired_major_px / (px_per_world as f64)).max(1e-6));
            let mut minor_step = major_step / 10.0;
            if !minor_step.is_finite() || minor_step <= 0.0 {
                minor_step = major_step.max(1.0);
            }

            // Cap minor line density to avoid noisy/perf-heavy grids.
            let max_minor_lines = 180.0;
            let minor_count_x = (dx as f64 / minor_step).abs();
            let minor_count_y = (dy as f64 / minor_step).abs();
            if minor_count_x > max_minor_lines || minor_count_y > max_minor_lines {
                minor_step = (major_step / 5.0).max(major_step); // effectively disable minors
            }

            let mut helper_vertices: Vec<Vertex> = Vec::new();
            let mut push_line = |a: Vec3, b: Vec3, color: Vec4| {
                helper_vertices.push(Vertex::new(a, color));
                helper_vertices.push(Vertex::new(b, color));
            };

            // Slightly offset the grid plane to reduce z-fighting with geometry on z=0.
            let z_grid = -1e-4_f32;

            // Procedural XY grid plane (depth-tested, no depth writes). This avoids far-plane
            // popping and keeps line density stable via shader derivatives.
            if self.overlay_show_grid_for_axes(axes_index) {
                let theme = self.theme.build_theme();
                let bg = theme.get_background_color();
                let grid = theme.get_grid_color();
                let bg_luma = 0.2126 * bg.x + 0.7152 * bg.y + 0.0722 * bg.z;
                let mut major_rgb = [grid.x, grid.y, grid.z];
                let mut minor_rgb = [grid.x, grid.y, grid.z];
                let mut major_alpha = grid.w.clamp(0.08, 0.22);
                let mut minor_alpha = (grid.w * 0.45).clamp(0.04, 0.14);
                if bg_luma <= 0.62 {
                    major_rgb = [grid.x * 0.80, grid.y * 0.80, grid.z * 0.80];
                    minor_rgb = [grid.x * 0.68, grid.y * 0.68, grid.z * 0.68];
                }
                if bg_luma > 0.62 {
                    major_rgb = [grid.x * 0.45, grid.y * 0.45, grid.z * 0.45];
                    minor_rgb = [grid.x * 0.33, grid.y * 0.33, grid.z * 0.33];
                    major_alpha = major_alpha.max(0.24);
                    minor_alpha = minor_alpha.max(0.12);
                }
                self.wgpu_renderer.ensure_grid_plane_pipeline();
                self.wgpu_renderer.update_grid_uniforms_for_axes(
                    axes_index,
                    crate::core::renderer::GridUniforms {
                        major_step: major_step as f32,
                        minor_step: minor_step as f32,
                        fade_start: (0.60 * dx.max(dy)).max(major_step as f32),
                        fade_end: (0.95 * dx.max(dy)).max((major_step as f32) * 2.0),
                        camera_pos: cam.position.to_array(),
                        _pad0: 0.0,
                        target_pos: Vec3::new(cam.target.x, cam.target.y, 0.0).to_array(),
                        _pad1: 0.0,
                        major_color: [major_rgb[0], major_rgb[1], major_rgb[2], major_alpha],
                        minor_color: [minor_rgb[0], minor_rgb[1], minor_rgb[2], minor_alpha],
                    },
                );

                let quad_vertices = [
                    Vertex::new(Vec3::new(min_x, min_y, z_grid), Vec4::ONE),
                    Vertex::new(Vec3::new(max_x, min_y, z_grid), Vec4::ONE),
                    Vertex::new(Vec3::new(max_x, max_y, z_grid), Vec4::ONE),
                    Vertex::new(Vec3::new(min_x, max_y, z_grid), Vec4::ONE),
                ];
                let quad_indices: [u32; 6] = [0, 1, 2, 0, 2, 3];
                let vb = self.wgpu_renderer.create_vertex_buffer(&quad_vertices);
                let ib = self.wgpu_renderer.create_index_buffer(&quad_indices);
                grid_plane_buffers = Some((vb, ib));
            }

            // Origin triad (always, for spatial awareness).
            let axis_len = (major_step as f32 * 5.0).clamp(0.5, (dx.max(dy) * 0.6).max(0.5));
            let origin = Vec3::new(0.0, 0.0, 0.0);
            let col_x = Vec4::new(0.92, 0.25, 0.25, 0.85);
            let col_y = Vec4::new(0.35, 0.90, 0.45, 0.85);
            let col_z = Vec4::new(0.35, 0.62, 0.98, 0.85);
            push_line(origin, origin + Vec3::new(axis_len, 0.0, 0.0), col_x);
            push_line(origin, origin + Vec3::new(0.0, axis_len, 0.0), col_y);
            push_line(origin, origin + Vec3::new(0.0, 0.0, axis_len), col_z);

            // Dynamic tick marks on the origin triad (major step only). Labels are drawn in the
            // overlay so they stay crisp; these marks provide a depth-correct anchor in the scene.
            // NOTE: `f32::clamp` panics if min > max. When zoomed very far in, `major_step` can
            // be tiny, making `major_step * 0.25` smaller than a fixed minimum like 0.01.
            // Keep the min <= max by adapting the minimum to the current step size.
            let tick_max = (major_step as f32 * 0.25).max(1.0e-6);
            let tick_min = 0.01_f32.min(tick_max);
            let tick_len = (axis_len * 0.04).clamp(tick_min, tick_max);
            let max_ticks = 6usize;
            let mut add_ticks = |axis: Vec3, perp: Vec3, col: Vec4| {
                if major_step <= 0.0 {
                    return;
                }
                for i in 1..=max_ticks {
                    let t = (i as f32) * (major_step as f32);
                    if t >= axis_len * 0.999 {
                        break;
                    }
                    let p = origin + axis * t;
                    push_line(
                        p - perp * tick_len,
                        p + perp * tick_len,
                        Vec4::new(col.x, col.y, col.z, col.w * 0.85),
                    );
                }
            };
            add_ticks(Vec3::X, Vec3::Y, col_x);
            add_ticks(Vec3::Y, Vec3::X, col_y);
            add_ticks(Vec3::Z, Vec3::X, col_z);

            if !helper_vertices.is_empty() {
                let rd = Box::new(crate::core::RenderData {
                    pipeline_type: crate::core::PipelineType::Lines,
                    vertices: helper_vertices,
                    indices: None,
                    gpu_vertices: None,
                    bounds: None,
                    material: crate::core::Material::default(),
                    draw_calls: vec![crate::core::DrawCall {
                        vertex_offset: 0,
                        vertex_count: 0, // filled below
                        index_offset: None,
                        index_count: None,
                        instance_count: 1,
                    }],
                    image: None,
                });
                owned_render_data.push(rd);
                let idx = owned_render_data.len() - 1;
                // Fill vertex_count now that vertices are owned.
                let vcount = owned_render_data[idx].vertices.len();
                if let Some(dc) = owned_render_data[idx].draw_calls.get_mut(0) {
                    dc.vertex_count = vcount;
                }
                let vb = Arc::new(
                    self.wgpu_renderer
                        .create_vertex_buffer(&owned_render_data[idx].vertices),
                );
                // Draw helpers first (under data, depth-tested).
                let rd_ref: &crate::core::RenderData = &owned_render_data[idx];
                render_items.insert(0, (rd_ref, vb, None));
                total_vertices += vcount;
            }
        }

        // Precompute expanded point buffers to keep them alive across the render pass
        let mut point_buffers: Vec<Option<(wgpu::Buffer, usize)>> =
            Vec::with_capacity(render_items.len());
        for (render_data, _vb, _ib) in render_items.iter() {
            if matches!(render_data.pipeline_type, crate::core::PipelineType::Points) {
                let expanded = self
                    .wgpu_renderer
                    // size_px=0.0 => use per-vertex normal.z sizes
                    .create_direct_point_vertices(&render_data.vertices, 0.0);
                let buf = self.wgpu_renderer.create_vertex_buffer(&expanded);
                point_buffers.push(Some((buf, expanded.len())));
            } else {
                point_buffers.push(None);
            }
        }
        // Precreate image bind groups for textured items to avoid lifetime issues
        let has_textured_items = render_items.iter().any(|(render_data, _vb, _ib)| {
            render_data.pipeline_type == crate::core::PipelineType::Textured
        });
        if has_textured_items {
            self.wgpu_renderer.ensure_image_pipeline();
        }
        let mut image_bind_groups: Vec<Option<wgpu::BindGroup>> =
            Vec::with_capacity(render_items.len());

        for (render_data, _vb, _ib) in render_items.iter() {
            if render_data.pipeline_type == crate::core::PipelineType::Textured {
                if let Some(crate::core::scene::ImageData::Rgba8 {
                    width,
                    height,
                    data,
                }) = &render_data.image
                {
                    let (_t, _v, bg) = self
                        .wgpu_renderer
                        .create_image_texture_and_bind_group(*width, *height, data);
                    image_bind_groups.push(Some(bg));
                } else {
                    image_bind_groups.push(None);
                }
            } else {
                image_bind_groups.push(None);
            }
        }
        // Precreate point style bind groups for points to match pipeline layout [direct uniforms, point style]
        let mut point_style_bind_groups: Vec<Option<wgpu::BindGroup>> =
            Vec::with_capacity(render_items.len());
        for (render_data, _vb, _ib) in render_items.iter() {
            if matches!(render_data.pipeline_type, crate::core::PipelineType::Points) {
                let style = crate::core::renderer::PointStyleUniforms {
                    face_color: render_data.material.albedo.to_array(),
                    edge_color: render_data.material.emissive.to_array(),
                    edge_thickness_px: render_data.material.roughness,
                    marker_shape: render_data.material.metallic as u32,
                    _pad: [0.0, 0.0],
                };
                let (_buf, bg) = self.wgpu_renderer.create_point_style_bind_group(style);
                point_style_bind_groups.push(Some(bg));
            } else {
                point_style_bind_groups.push(None);
            }
        }

        // Precompute optional grid geometry and uniforms so we can draw it under data
        // Grid is drawn only when enabled and in 2D orthographic
        let mut grid_vb_opt: Option<wgpu::Buffer> = None;
        if is_2d && self.overlay_show_grid_for_axes(axes_index) {
            if let Some((l, r, b, t)) = self.view_bounds_for_axes(axes_index) {
                // Update direct uniforms mapping for viewport
                self.wgpu_renderer.update_direct_uniforms_for_axes(
                    axes_index,
                    [l as f32, b as f32],
                    [r as f32, t as f32],
                    [-1.0, -1.0],
                    [1.0, 1.0],
                    [sw.max(1) as f32, sh.max(1) as f32],
                );
                self.wgpu_renderer.ensure_direct_line_pipeline();

                let x_range = (r - l).max(1e-6);
                let y_range = (t - b).max(1e-6);
                let x_step = plot_utils::calculate_tick_interval(x_range);
                let y_step = plot_utils::calculate_tick_interval(y_range);
                let mut grid_vertices: Vec<Vertex> = Vec::new();
                let g = 80.0_f32 / 255.0_f32;
                let col = Vec4::new(g, g, g, 1.0);
                if x_step.is_finite() && x_step > 0.0 {
                    let mut x = ((l / x_step).ceil() * x_step) as f32;
                    let b_f = b as f32;
                    let t_f = t as f32;
                    while (x as f64) <= r {
                        grid_vertices.push(Vertex::new(Vec3::new(x, b_f, 0.0), col));
                        grid_vertices.push(Vertex::new(Vec3::new(x, t_f, 0.0), col));
                        x += x_step as f32;
                    }
                }
                if y_step.is_finite() && y_step > 0.0 {
                    let mut y = ((b / y_step).ceil() * y_step) as f32;
                    let l_f = l as f32;
                    let r_f = r as f32;
                    while (y as f64) <= t {
                        grid_vertices.push(Vertex::new(Vec3::new(l_f, y, 0.0), col));
                        grid_vertices.push(Vertex::new(Vec3::new(r_f, y, 0.0), col));
                        y += y_step as f32;
                    }
                }
                if !grid_vertices.is_empty() {
                    grid_vb_opt = Some(self.wgpu_renderer.create_vertex_buffer(&grid_vertices));
                }
            }
        }

        // Before the pass: configure direct uniforms and ensure pipelines
        let bounds_opt = if is_2d {
            match cam.projection {
                crate::core::camera::ProjectionType::Orthographic {
                    left,
                    right,
                    bottom,
                    top,
                    ..
                } => Some((left as f64, right as f64, bottom as f64, top as f64)),
                _ => self.data_bounds,
            }
        } else {
            None
        };
        if is_2d {
            if let Some((l, r, b, t)) = bounds_opt {
                self.wgpu_renderer.update_direct_uniforms_for_axes(
                    axes_index,
                    [l as f32, b as f32],
                    [r as f32, t as f32],
                    [-1.0, -1.0],
                    [1.0, 1.0],
                    [sw.max(1) as f32, sh.max(1) as f32],
                );
            }
            self.wgpu_renderer.ensure_direct_triangle_pipeline();
            self.wgpu_renderer.ensure_direct_line_pipeline();
            self.wgpu_renderer.ensure_direct_point_pipeline();
        } else {
            // 3D: ensure camera-based pipelines exist so surfaces rotate with the camera.
            self.wgpu_renderer
                .ensure_pipeline(crate::core::PipelineType::Triangles);
            self.wgpu_renderer
                .ensure_pipeline(crate::core::PipelineType::Lines);
            self.wgpu_renderer
                .ensure_pipeline(crate::core::PipelineType::Points);
        }

        // Begin pass with Load (preserve egui)
        {
            // Prepare MSAA render target if enabled
            let use_msaa = self.wgpu_renderer.msaa_sample_count > 1;
            log::debug!(
                "runmat-plot: renderer.camera_to_target_viewport.render_pass_start axes_index={} use_msaa={} clear_background={}",
                axes_index,
                use_msaa,
                clear_background
            );

            let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Plot Camera Viewport Pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: target.view,
                    resolve_target: if use_msaa {
                        target.resolve_target
                    } else {
                        None
                    },
                    ops: wgpu::Operations {
                        load: if clear_background {
                            wgpu::LoadOp::Clear(wgpu::Color {
                                r: config.background_color.x as f64,
                                g: config.background_color.y as f64,
                                b: config.background_color.z as f64,
                                a: config.background_color.w as f64,
                            })
                        } else {
                            wgpu::LoadOp::Load
                        },
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                    view: depth_view.as_ref(),
                    depth_ops: Some(wgpu::Operations {
                        load: wgpu::LoadOp::Clear(match config.depth_mode {
                            DepthMode::Standard => 1.0,
                            DepthMode::ReversedZ => 0.0,
                        }),
                        store: wgpu::StoreOp::Store,
                    }),
                    stencil_ops: None,
                }),
                timestamp_writes: None,
                occlusion_query_set: None,
            });

            // Apply viewport and scissor rectangle to draw into the plot rect
            render_pass.set_viewport(
                sx as f32,
                sy as f32,
                sw.max(1) as f32,
                sh.max(1) as f32,
                0.0,
                1.0,
            );
            render_pass.set_scissor_rect(sx, sy, sw.max(1), sh.max(1));
            log::debug!(
                "runmat-plot: renderer.camera_to_target_viewport.render_pass_ready axes_index={} viewport=({}, {}, {}, {})",
                axes_index,
                sx,
                sy,
                sw.max(1),
                sh.max(1)
            );
            if let Some(ref vb_grid) = grid_vb_opt {
                if let Some(ref pipeline) = self.wgpu_renderer.direct_line_pipeline {
                    log::debug!(
                        "runmat-plot: renderer.camera_to_target_viewport.draw_grid_start axes_index={} vertex_buffer_size={}",
                        axes_index,
                        vb_grid.size()
                    );
                    render_pass.set_pipeline(pipeline);
                    render_pass.set_bind_group(
                        0,
                        self.wgpu_renderer
                            .get_direct_uniform_bind_group_for_axes(axes_index),
                        &[],
                    );
                    render_pass.set_vertex_buffer(0, vb_grid.slice(..));
                    // Each grid line is two vertices (LineList)
                    // Draw full buffer
                    // Note: vertex count equals number of vertices
                    // wgpu will interpret as lines via pipeline topology
                    render_pass.draw(
                        0..(vb_grid.size() / std::mem::size_of::<Vertex>() as u64) as u32,
                        0..1,
                    );
                    log::debug!(
                        "runmat-plot: renderer.camera_to_target_viewport.draw_grid_ok axes_index={}",
                        axes_index
                    );
                }
            }

            // Use direct pipelines for precise 2D mapping inside the viewport
            let use_direct_for_triangles = is_2d;
            let use_direct_for_lines = is_2d;
            let direct_tri_pipeline = if use_direct_for_triangles && bounds_opt.is_some() {
                self.wgpu_renderer
                    .direct_triangle_pipeline
                    .as_ref()
                    .map(|p| p as *const wgpu::RenderPipeline)
            } else {
                None
            };
            let direct_line_pipeline = if use_direct_for_lines && bounds_opt.is_some() {
                self.wgpu_renderer
                    .direct_line_pipeline
                    .as_ref()
                    .map(|p| p as *const wgpu::RenderPipeline)
            } else {
                None
            };
            let direct_point_pipeline = if is_2d && bounds_opt.is_some() {
                self.wgpu_renderer
                    .direct_point_pipeline
                    .as_ref()
                    .map(|p| p as *const wgpu::RenderPipeline)
            } else {
                None
            };

            // Keep transient point buffers alive during this pass
            let mut __temp_point_buffers_cam: Vec<wgpu::Buffer> = Vec::new();
            for (idx, (render_data, vertex_buffer, index_buffer)) in render_items.iter().enumerate()
            {
                let is_triangles = matches!(
                    render_data.pipeline_type,
                    crate::core::PipelineType::Triangles
                );
                let is_lines =
                    matches!(render_data.pipeline_type, crate::core::PipelineType::Lines);
                let is_points =
                    matches!(render_data.pipeline_type, crate::core::PipelineType::Points);
                let is_textured = matches!(
                    render_data.pipeline_type,
                    crate::core::PipelineType::Textured
                );
                // Use direct mapping for lines/triangles/points for correct pixel-sized markers in GUI
                let use_direct = is_2d
                    && ((use_direct_for_triangles && is_triangles)
                        || (use_direct_for_lines && is_lines)
                        || is_points)
                    && bounds_opt.is_some();
                log::debug!(
                    "runmat-plot: renderer.camera_to_target_viewport.draw_item_start axes_index={} item_index={} pipeline={:?} use_direct={} textured={} indexed={} draw_calls={} point_buffer={} ",
                    axes_index,
                    idx,
                    render_data.pipeline_type,
                    use_direct,
                    is_textured,
                    index_buffer.is_some(),
                    render_data.draw_calls.len(),
                    point_buffers[idx].is_some()
                );

                if use_direct {
                    // Safe because we only read pointers here within pass
                    let pipeline_ref: &wgpu::RenderPipeline = unsafe {
                        if is_triangles {
                            direct_tri_pipeline.unwrap().as_ref().unwrap()
                        } else if is_lines {
                            direct_line_pipeline.unwrap().as_ref().unwrap()
                        } else {
                            direct_point_pipeline.unwrap().as_ref().unwrap()
                        }
                    };
                    let uniform_bg = self
                        .wgpu_renderer
                        .get_direct_uniform_bind_group_for_axes(axes_index);
                    render_pass.set_pipeline(pipeline_ref);
                    render_pass.set_bind_group(0, uniform_bg, &[]);
                    log::debug!(
                        "runmat-plot: renderer.camera_to_target_viewport.draw_item_pipeline_ready axes_index={} item_index={} branch=direct",
                        axes_index,
                        idx
                    );
                } else if is_textured {
                    let pipeline = self
                        .wgpu_renderer
                        .get_pipeline(crate::core::PipelineType::Textured);
                    render_pass.set_pipeline(pipeline);
                    render_pass.set_bind_group(
                        0,
                        self.wgpu_renderer
                            .get_direct_uniform_bind_group_for_axes(axes_index),
                        &[],
                    );
                    if let Some(ref bg) = image_bind_groups[idx] {
                        render_pass.set_bind_group(1, bg, &[]);
                    }
                    log::debug!(
                        "runmat-plot: renderer.camera_to_target_viewport.draw_item_pipeline_ready axes_index={} item_index={} branch=textured",
                        axes_index,
                        idx
                    );
                } else {
                    let pipeline = self.wgpu_renderer.get_pipeline(render_data.pipeline_type);
                    render_pass.set_pipeline(pipeline);
                    render_pass.set_bind_group(
                        0,
                        self.wgpu_renderer
                            .get_uniform_bind_group_for_axes(axes_index),
                        &[],
                    );
                    log::debug!(
                        "runmat-plot: renderer.camera_to_target_viewport.draw_item_pipeline_ready axes_index={} item_index={} branch=standard",
                        axes_index,
                        idx
                    );
                }

                if is_points && use_direct {
                    if let Some((ref buf, len)) = point_buffers[idx] {
                        if let Some(ref bg) = point_style_bind_groups[idx] {
                            render_pass.set_bind_group(1, bg, &[]);
                        }
                        render_pass.set_vertex_buffer(0, buf.slice(..));
                        render_pass.draw(0..len as u32, 0..1);
                        log::debug!(
                            "runmat-plot: renderer.camera_to_target_viewport.draw_item_ok axes_index={} item_index={} mode=direct_points vertices={}",
                            axes_index,
                            idx,
                            len
                        );
                        continue;
                    }
                } else {
                    render_pass.set_vertex_buffer(0, vertex_buffer.slice(..));
                }
                if let Some(index_buffer_ref) = index_buffer {
                    render_pass
                        .set_index_buffer(index_buffer_ref.slice(..), wgpu::IndexFormat::Uint32);
                    if let Some(indices) = &render_data.indices {
                        render_pass.draw_indexed(0..indices.len() as u32, 0, 0..1);
                        log::debug!(
                            "runmat-plot: renderer.camera_to_target_viewport.draw_item_ok axes_index={} item_index={} mode=indexed indices={}",
                            axes_index,
                            idx,
                            indices.len()
                        );
                    }
                } else {
                    for dc in &render_data.draw_calls {
                        render_pass.draw(
                            dc.vertex_offset as u32..(dc.vertex_offset + dc.vertex_count) as u32,
                            0..dc.instance_count as u32,
                        );
                        log::debug!(
                            "runmat-plot: renderer.camera_to_target_viewport.draw_call_ok axes_index={} item_index={} mode=draw vertex_offset={} vertex_count={} instances={}",
                            axes_index,
                            idx,
                            dc.vertex_offset,
                            dc.vertex_count,
                            dc.instance_count
                        );
                    }
                }
            }

            // Draw procedural 3D grid plane after data, depth-tested (no depth writes).
            if let Some((ref vb, ref ib)) = grid_plane_buffers {
                if let Some(pipeline) = self.wgpu_renderer.grid_plane_pipeline() {
                    log::debug!(
                        "runmat-plot: renderer.camera_to_target_viewport.draw_grid_plane_start axes_index={}",
                        axes_index
                    );
                    render_pass.set_pipeline(pipeline);
                    render_pass.set_bind_group(
                        0,
                        self.wgpu_renderer
                            .get_uniform_bind_group_for_axes(axes_index),
                        &[],
                    );
                    render_pass.set_bind_group(
                        1,
                        self.wgpu_renderer
                            .get_grid_uniform_bind_group_for_axes(axes_index),
                        &[],
                    );
                    render_pass.set_vertex_buffer(0, vb.slice(..));
                    render_pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
                    render_pass.draw_indexed(0..6, 0, 0..1);
                    log::debug!(
                        "runmat-plot: renderer.camera_to_target_viewport.draw_grid_plane_ok axes_index={}",
                        axes_index
                    );
                }
            }
        }

        log::debug!(
            "runmat-plot: renderer.camera_to_target_viewport.ok axes_index={} total_vertices={} total_triangles={}",
            axes_index,
            total_vertices,
            total_triangles
        );

        Ok(RenderResult {
            success: true,
            data_bounds: self.data_bounds,
            vertex_count: total_vertices,
            triangle_count: total_triangles,
            render_time_ms: start_time.elapsed().as_secs_f64() * 1000.0,
        })
    }

    /// Render all axes of a subplot grid into their respective viewport rectangles.
    /// `axes_viewports` is a vector of (x, y, w, h) in physical pixels, length equals rows*cols.
    pub fn render_axes_to_viewports(
        &mut self,
        encoder: &mut wgpu::CommandEncoder,
        target_view: &wgpu::TextureView,
        axes_viewports: &[(u32, u32, u32, u32)],
        msaa_samples: u32,
        base_config: &PlotRenderConfig,
    ) -> Result<(), Box<dyn std::error::Error>> {
        log::debug!(
            "runmat-plot: renderer.axes_to_viewports.start viewport_count={} msaa_samples={} width={} height={}",
            axes_viewports.len(),
            msaa_samples,
            base_config.width,
            base_config.height
        );
        // Build map axes_index -> node ids
        let mut axes_to_nodes: std::collections::HashMap<usize, Vec<crate::core::scene::NodeId>> =
            std::collections::HashMap::new();
        for node in self.scene.get_visible_nodes() {
            axes_to_nodes
                .entry(node.axes_index)
                .or_default()
                .push(node.id);
        }

        if self.axes_cameras.is_empty() {
            self.axes_cameras.push(Self::create_default_camera());
        }
        self.wgpu_renderer
            .ensure_axes_uniform_capacity(axes_viewports.len().max(1));

        // Pre-collect all node ids
        let all_ids: Vec<crate::core::scene::NodeId> = self
            .scene
            .get_visible_nodes()
            .into_iter()
            .map(|n| n.id)
            .collect();
        let active_axes: Vec<usize> = axes_viewports
            .iter()
            .enumerate()
            .filter_map(|(ax_idx, _)| {
                axes_to_nodes
                    .get(&ax_idx)
                    .filter(|ids| !ids.is_empty())
                    .map(|_| ax_idx)
            })
            .collect();
        if active_axes.is_empty() {
            log::debug!("runmat-plot: renderer.axes_to_viewports.no_active_axes");
            return Ok(());
        }

        self.wgpu_renderer.ensure_msaa(msaa_samples.max(1));
        let shared_msaa_view = if self.wgpu_renderer.msaa_sample_count > 1 {
            Some(self.wgpu_renderer.ensure_msaa_color_view())
        } else {
            None
        };

        for (ax_idx, viewport) in axes_viewports.iter().enumerate() {
            log::debug!(
                "runmat-plot: renderer.axes_to_viewports.viewport axes_index={} viewport=({}, {}, {}, {})",
                ax_idx,
                viewport.0,
                viewport.1,
                viewport.2,
                viewport.3
            );
            let ids_for_axes = axes_to_nodes.get(&ax_idx).cloned().unwrap_or_default();
            if ids_for_axes.is_empty() {
                log::debug!(
                    "runmat-plot: renderer.axes_to_viewports.skip_empty_axes axes_index={}",
                    ax_idx
                );
                continue;
            }

            // Hide nodes not belonging to this axes
            let mut hidden_ids: Vec<crate::core::scene::NodeId> = Vec::new();
            for id in &all_ids {
                if !ids_for_axes.contains(id) {
                    if let Some(node) = self.scene.get_node_mut(*id) {
                        if node.visible {
                            node.visible = false;
                            hidden_ids.push(*id);
                        }
                    }
                }
            }
            // Update camera and bounds
            let cam = self
                .axes_cameras
                .get(ax_idx)
                .cloned()
                .unwrap_or_else(Self::create_default_camera);
            let _ = self.calculate_data_bounds();

            // Render this axes into its viewport
            let mut cfg = base_config.clone();
            cfg.width = viewport.2;
            cfg.height = viewport.3;
            cfg.msaa_samples = msaa_samples.max(1);
            let is_first_axes = Some(&ax_idx) == active_axes.first();
            let is_last_axes = Some(&ax_idx) == active_axes.last();
            log::debug!(
                "runmat-plot: renderer.axes_to_viewports.axes_ready axes_index={} node_count={} first_axes={} last_axes={}",
                ax_idx,
                ids_for_axes.len(),
                is_first_axes,
                is_last_axes
            );
            let render_target = if let Some(ref msaa_view) = shared_msaa_view {
                RenderTarget {
                    view: msaa_view.as_ref(),
                    resolve_target: if is_last_axes {
                        Some(target_view)
                    } else {
                        None
                    },
                }
            } else {
                RenderTarget {
                    view: target_view,
                    resolve_target: None,
                }
            };
            let _ = self.render_camera_to_target_viewport(
                encoder,
                render_target,
                *viewport,
                &cfg,
                &cam,
                ax_idx,
                is_first_axes,
            )?;
            log::debug!(
                "runmat-plot: renderer.axes_to_viewports.axes_render_ok axes_index={}",
                ax_idx
            );

            // Restore hidden nodes visibility
            for id in hidden_ids {
                if let Some(node) = self.scene.get_node_mut(id) {
                    node.visible = true;
                }
            }
        }
        log::debug!("runmat-plot: renderer.axes_to_viewports.ok");
        Ok(())
    }

    /// Create default 2D camera for plotting
    fn create_default_camera() -> Camera {
        let mut camera = Camera::new();
        camera.projection = crate::core::camera::ProjectionType::Orthographic {
            left: -5.0,
            right: 5.0,
            bottom: -5.0,
            top: 5.0,
            // Use a deeper z range so the default camera position doesn't clip z=0 geometry.
            near: -10.0,
            far: 10.0,
        };
        camera.depth_mode = DepthMode::default();
        // For 2D plotting we keep the camera close to the z=0 plane.
        camera.position = Vec3::new(0.0, 0.0, 1.0);
        camera.target = Vec3::new(0.0, 0.0, 0.0);
        camera.up = Vec3::new(0.0, 1.0, 0.0);
        camera
    }

    // Removed simple data_bounds getter in favor of overlay-aware bounds below

    /// Get the primary (axes 0) camera.
    pub fn camera(&self) -> &Camera {
        self.axes_cameras
            .first()
            .expect("axes_cameras must contain at least one camera")
    }

    /// Get mutable reference to the primary (axes 0) camera.
    pub fn camera_mut(&mut self) -> &mut Camera {
        self.axes_cameras
            .first_mut()
            .expect("axes_cameras must contain at least one camera")
    }

    pub fn axes_camera(&self, axes_index: usize) -> Option<&Camera> {
        self.axes_cameras.get(axes_index)
    }

    /// Get scene reference
    pub fn scene(&self) -> &Scene {
        &self.scene
    }

    /// Get scene statistics
    pub fn scene_statistics(&self) -> crate::core::SceneStatistics {
        self.scene.statistics()
    }

    /// Get current view bounds (camera frustum) in world/data space for 2D
    pub fn view_bounds(&self) -> Option<(f64, f64, f64, f64)> {
        match self.camera().projection {
            crate::core::camera::ProjectionType::Orthographic {
                left,
                right,
                bottom,
                top,
                ..
            } => Some((left as f64, right as f64, bottom as f64, top as f64)),
            _ => None,
        }
    }

    /// Overlay configuration getters
    pub fn overlay_show_grid(&self) -> bool {
        self.figure_show_grid
    }
    pub fn overlay_show_grid_for_axes(&self, axes_index: usize) -> bool {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .map(|m| m.grid_enabled)
            .unwrap_or(self.figure_show_grid)
    }
    pub fn overlay_show_box(&self) -> bool {
        self.figure_show_box
    }
    pub fn overlay_show_box_for_axes(&self, axes_index: usize) -> bool {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .map(|m| m.box_enabled)
            .unwrap_or(self.figure_show_box)
    }
    pub fn overlay_title(&self) -> Option<&String> {
        self.figure_title.as_ref()
    }
    pub fn overlay_title_for_axes(&self, axes_index: usize) -> Option<&String> {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .and_then(|m| m.title.as_ref())
    }
    pub fn overlay_x_label(&self) -> Option<&String> {
        self.figure_x_label.as_ref()
    }
    pub fn overlay_x_label_for_axes(&self, axes_index: usize) -> Option<&String> {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .and_then(|m| m.x_label.as_ref())
    }
    pub fn overlay_x_label_style_for_axes(&self, axes_index: usize) -> Option<&TextStyle> {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .map(|m| &m.x_label_style)
    }
    pub fn overlay_y_label(&self) -> Option<&String> {
        self.figure_y_label.as_ref()
    }
    pub fn overlay_y_label_for_axes(&self, axes_index: usize) -> Option<&String> {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .and_then(|m| m.y_label.as_ref())
    }
    pub fn overlay_y_label_style_for_axes(&self, axes_index: usize) -> Option<&TextStyle> {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .map(|m| &m.y_label_style)
    }
    pub fn overlay_z_label(&self) -> Option<&String> {
        self.figure_z_label.as_ref()
    }
    pub fn overlay_z_label_for_axes(&self, axes_index: usize) -> Option<&String> {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .and_then(|m| m.z_label.as_ref())
    }
    pub fn overlay_z_label_style_for_axes(&self, axes_index: usize) -> Option<&TextStyle> {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .map(|m| &m.z_label_style)
    }
    pub fn active_axes_pie_labels(&self) -> Vec<(String, glam::Vec2)> {
        let Some(fig) = self.last_figure.as_ref() else {
            return Vec::new();
        };
        fig.pie_labels_for_axes(fig.active_axes_index)
            .into_iter()
            .map(|entry| (entry.label, entry.position))
            .collect()
    }
    pub fn pie_labels_for_axes(&self, axes_index: usize) -> Vec<(String, glam::Vec2)> {
        let Some(fig) = self.last_figure.as_ref() else {
            return Vec::new();
        };
        fig.pie_labels_for_axes(axes_index)
            .into_iter()
            .map(|entry| (entry.label, entry.position))
            .collect()
    }

    pub fn world_text_annotations_for_axes(
        &self,
        axes_index: usize,
    ) -> Vec<(glam::Vec3, String, TextStyle)> {
        self.last_figure
            .as_ref()
            .map(|f| {
                f.axes_text_annotations(axes_index)
                    .iter()
                    .map(|annotation| {
                        (
                            annotation.position,
                            annotation.text.clone(),
                            annotation.style.clone(),
                        )
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    pub fn world_axis_label_annotations_for_axes(
        &self,
        axes_index: usize,
    ) -> Vec<(glam::Vec3, String, TextStyle)> {
        let Some(fig) = self.last_figure.as_ref() else {
            return Vec::new();
        };
        let Some(meta) = fig.axes_metadata(axes_index) else {
            return Vec::new();
        };
        let Some(bounds) = self.axes_bounds(axes_index) else {
            return Vec::new();
        };
        let dx = (bounds.max.x - bounds.min.x).abs().max(1.0e-3);
        let dy = (bounds.max.y - bounds.min.y).abs().max(1.0e-3);
        let dz = (bounds.max.z - bounds.min.z).abs().max(1.0e-3);
        let camera = self
            .axes_camera(axes_index)
            .or_else(|| Some(self.camera()))
            .expect("plot renderer must always have a camera");
        let center = (bounds.min + bounds.max) * 0.5;
        let cam_delta = camera.position - center;
        let sx = if cam_delta.x >= 0.0 { 1.0 } else { -1.0 };
        let sy = if cam_delta.y >= 0.0 { 1.0 } else { -1.0 };
        let sz = if cam_delta.z >= 0.0 { 1.0 } else { -1.0 };
        let x_anchor = glam::Vec3::new(bounds.min.x + dx * 0.82, bounds.min.y, bounds.min.z)
            + glam::Vec3::new(0.0, -sy * dy * 0.10, -sz * dz * 0.08);
        let y_anchor = glam::Vec3::new(bounds.min.x, bounds.min.y + dy * 0.82, bounds.min.z)
            + glam::Vec3::new(-sx * dx * 0.10, 0.0, -sz * dz * 0.08);
        let z_anchor = glam::Vec3::new(bounds.min.x, bounds.min.y, bounds.min.z + dz * 0.82)
            + glam::Vec3::new(-sx * dx * 0.08, -sy * dy * 0.08, 0.0);
        let mut out = Vec::new();
        if let Some(label) = meta.x_label.clone().filter(|s| !s.is_empty()) {
            out.push((x_anchor, label, meta.x_label_style.clone()));
        }
        if let Some(label) = meta.y_label.clone().filter(|s| !s.is_empty()) {
            out.push((y_anchor, label, meta.y_label_style.clone()));
        }
        if let Some(label) = meta.z_label.clone().filter(|s| !s.is_empty()) {
            out.push((z_anchor, label, meta.z_label_style.clone()));
        }
        out
    }
    pub fn overlay_show_legend(&self) -> bool {
        self.figure_show_legend
    }
    pub fn overlay_show_legend_for_axes(&self, axes_index: usize) -> bool {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .map(|m| m.legend_enabled)
            .unwrap_or(self.figure_show_legend)
    }
    pub fn overlay_legend_entries(&self) -> &Vec<LegendEntry> {
        &self.legend_entries
    }
    pub fn overlay_legend_entries_for_axes(&self, axes_index: usize) -> Vec<LegendEntry> {
        self.last_figure
            .as_ref()
            .map(|f| f.legend_entries_for_axes(axes_index))
            .unwrap_or_default()
    }
    pub fn overlay_x_log(&self) -> bool {
        self.figure_x_log
    }
    pub fn overlay_x_log_for_axes(&self, axes_index: usize) -> bool {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .map(|m| m.x_log)
            .unwrap_or(self.figure_x_log)
    }
    pub fn overlay_y_log(&self) -> bool {
        self.figure_y_log
    }
    pub fn overlay_y_log_for_axes(&self, axes_index: usize) -> bool {
        self.last_figure
            .as_ref()
            .and_then(|f| f.axes_metadata(axes_index))
            .map(|m| m.y_log)
            .unwrap_or(self.figure_y_log)
    }
    pub fn overlay_colormap(&self) -> ColorMap {
        self.figure_colormap
    }
    pub fn overlay_colorbar_enabled(&self) -> bool {
        self.figure_colorbar_enabled
    }
    /// Subplot grid
    pub fn figure_axes_grid(&self) -> (usize, usize) {
        self.last_figure
            .as_ref()
            .map(|f| f.axes_grid())
            .unwrap_or((1, 1))
    }
    /// Return categorical labels if any (is_x_axis, &labels)
    pub fn overlay_categorical_labels(&self) -> Option<(bool, &Vec<String>)> {
        if let (Some(is_x), Some(labels)) = (
            &self.figure_categorical_is_x,
            &self.figure_categorical_labels,
        ) {
            Some((*is_x, labels))
        } else {
            None
        }
    }

    pub fn overlay_categorical_labels_for_axes(
        &self,
        axes_index: usize,
    ) -> Option<(bool, Vec<String>)> {
        self.last_figure
            .as_ref()
            .and_then(|f| f.categorical_axis_labels_for_axes(axes_index))
    }

    pub fn overlay_histogram_edges_for_axes(&self, axes_index: usize) -> Option<(bool, Vec<f64>)> {
        self.last_figure
            .as_ref()
            .and_then(|f| f.histogram_axis_edges_for_axes(axes_index))
    }

    /// Get stable display bounds for an axes (data/explicit limits), excluding transient pan/zoom.
    pub fn overlay_display_bounds_for_axes(
        &self,
        axes_index: usize,
    ) -> Option<(f64, f64, f64, f64)> {
        self.display_bounds_for_axes(axes_index)
    }

    /// Get bounds used for display (manual axis limits override data bounds when provided)
    pub fn data_bounds(&self) -> Option<(f64, f64, f64, f64)> {
        let base = self.data_bounds;
        base.map(|(bx_min, bx_max, by_min, by_max)| {
            let (mut x_min, mut x_max) = (bx_min, bx_max);
            let (mut y_min, mut y_max) = (by_min, by_max);
            if let Some((xl, xr)) = self.figure_x_limits {
                x_min = xl;
                x_max = xr;
            }
            if let Some((yl, yr)) = self.figure_y_limits {
                y_min = yl;
                y_max = yr;
            }
            (x_min, x_max, y_min, y_max)
        })
    }

    /// Get mutable reference to a specific axes camera when using subplots
    pub fn axes_camera_mut(&mut self, idx: usize) -> Option<&mut Camera> {
        self.axes_cameras.get_mut(idx)
    }

    /// Get view bounds for a specific axes camera (l, r, b, t)
    pub fn view_bounds_for_axes(&self, idx: usize) -> Option<(f64, f64, f64, f64)> {
        if let Some(cam) = self.axes_cameras.get(idx) {
            if let crate::core::camera::ProjectionType::Orthographic {
                left,
                right,
                bottom,
                top,
                ..
            } = cam.projection
            {
                return Some((left as f64, right as f64, bottom as f64, top as f64));
            }
        }
        None
    }

    pub fn axes_bounds(&self, axes_index: usize) -> Option<crate::core::BoundingBox> {
        let mut min = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
        let mut max = Vec3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY);
        let mut saw_any = false;

        for node in self.scene.get_visible_nodes() {
            if node.axes_index != axes_index {
                continue;
            }
            let Some(render_data) = &node.render_data else {
                continue;
            };
            if let Some(bounds) = render_data.bounds {
                min = min.min(bounds.min);
                max = max.max(bounds.max);
                saw_any = true;
                continue;
            }
            for v in &render_data.vertices {
                let p = Vec3::new(v.position[0], v.position[1], v.position[2]);
                min = min.min(p);
                max = max.max(p);
                saw_any = true;
            }
        }

        if !saw_any {
            return None;
        }
        Some(crate::core::BoundingBox { min, max })
    }

    /// Prefer exporting the original figure if available
    pub fn export_figure_clone(&self) -> crate::plots::Figure {
        if let Some(f) = &self.last_figure {
            return f.clone();
        }
        // As a strict fallback, produce an empty figure with current metadata only
        let mut fig = crate::plots::Figure::new();
        fig.title = self.figure_title.clone();
        fig.x_label = self.figure_x_label.clone();
        fig.y_label = self.figure_y_label.clone();
        fig.legend_enabled = self.figure_show_legend;
        fig.grid_enabled = self.figure_show_grid;
        fig.box_enabled = self.figure_show_box;
        fig.x_limits = self.figure_x_limits;
        fig.y_limits = self.figure_y_limits;
        fig.x_log = self.figure_x_log;
        fig.y_log = self.figure_y_log;
        fig.axis_equal = self.figure_axis_equal;
        fig.colormap = self.figure_colormap;
        fig.colorbar_enabled = self.figure_colorbar_enabled;
        let (rows, cols) = self.figure_axes_grid();
        fig.set_subplot_grid(rows, cols);
        fig
    }
}

/// High-level plotting utilities that use the unified renderer
pub mod plot_utils {
    pub fn generate_major_ticks(min: f64, max: f64) -> Vec<f64> {
        if !(min.is_finite() && max.is_finite()) || max <= min {
            return Vec::new();
        }
        let range = (max - min).max(1e-9);
        let step = calculate_tick_interval(range);
        if !(step.is_finite() && step > 0.0) {
            return Vec::new();
        }

        let mut ticks = Vec::new();
        let mut value = (min / step).ceil() * step;
        let epsilon = range * 1e-6 + step * 1e-6;
        while value <= max + epsilon {
            let snapped = if value.abs() < epsilon { 0.0 } else { value };
            ticks.push(snapped);
            value += step;
            if ticks.len() > 64 {
                break;
            }
        }

        let endpoint_tol = step * 0.18;
        let near_min = ticks.iter().any(|t| (*t - min).abs() <= endpoint_tol);
        let near_max = ticks.iter().any(|t| (*t - max).abs() <= endpoint_tol);
        if !near_min {
            ticks.insert(0, min);
        }
        if !near_max {
            ticks.push(max);
        }

        ticks.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        ticks.dedup_by(|a, b| (*a - *b).abs() <= endpoint_tol * 0.5);
        ticks
    }

    /// Calculate nice tick intervals for axis labeling
    pub fn calculate_tick_interval(range: f64) -> f64 {
        let magnitude = 10.0_f64.powf(range.log10().floor());
        let normalized = range / magnitude;

        let nice_interval = if normalized <= 1.0 {
            0.2
        } else if normalized <= 2.0 {
            0.5
        } else if normalized <= 5.0 {
            1.0
        } else {
            2.0
        };

        nice_interval * magnitude
    }

    /// Format a tick label value for display
    pub fn format_tick_label(value: f64) -> String {
        fn trim_fixed(mut s: String) -> String {
            if s.contains('.') {
                while s.ends_with('0') {
                    s.pop();
                }
                if s.ends_with('.') {
                    s.pop();
                }
            }
            if s == "-0" {
                "0".to_string()
            } else {
                s
            }
        }

        if value.abs() < 0.001 {
            "0".to_string()
        } else if value.abs() >= 1000.0 || value.fract().abs() < 0.0005 {
            format!("{value:.0}")
        } else if value.abs() < 0.1 {
            trim_fixed(format!("{value:.3}"))
        } else if value.abs() < 10.0 {
            trim_fixed(format!("{value:.2}"))
        } else {
            trim_fixed(format!("{value:.1}"))
        }
    }

    /// Generate grid lines for plotting
    pub fn generate_grid_lines(
        bounds: (f64, f64, f64, f64),
        plot_rect: (f32, f32, f32, f32), // (left, right, bottom, top)
    ) -> Vec<(f32, f32, f32, f32)> {
        // Vector of (x1, y1, x2, y2) line segments
        let (x_min, x_max, y_min, y_max) = bounds;
        let (left, right, bottom, top) = plot_rect;

        let mut lines = Vec::new();

        // X-axis grid lines
        let x_range = x_max - x_min;
        let x_interval = calculate_tick_interval(x_range);
        let mut x_val = (x_min / x_interval).ceil() * x_interval;

        while x_val <= x_max {
            let x_screen = left + ((x_val - x_min) / x_range) as f32 * (right - left);
            lines.push((x_screen, bottom, x_screen, top));
            x_val += x_interval;
        }

        // Y-axis grid lines
        let y_range = y_max - y_min;
        let y_interval = calculate_tick_interval(y_range);
        let mut y_val = (y_min / y_interval).ceil() * y_interval;

        while y_val <= y_max {
            let y_screen = bottom + ((y_val - y_min) / y_range) as f32 * (top - bottom);
            lines.push((left, y_screen, right, y_screen));
            y_val += y_interval;
        }

        lines
    }
}