All files workerBlob.js

99.26% Statements 4298/4330
80.33% Branches 1205/1500
96.61% Functions 343/355
99.42% Lines 4179/4203

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 10156 10157 10158 10159 10160 10161 10162 10163 10164 10165 10166 10167 10168 10169 10170 10171 10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183 10184 10185 10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208 10209 10210 10211 10212 10213 10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224 10225 10226 10227 10228 10229 10230 10231 10232 10233 10234 10235 10236 10237 10238 10239 10240 10241 10242 10243 10244 10245 10246 10247 10248 10249 10250 10251 10252 10253 10254 10255 10256 10257 10258 10259 10260 10261 10262 10263 10264 10265 10266 10267 10268 10269 10270 10271 10272 10273 10274 10275 10276 10277 10278 10279 10280 10281 10282 10283 10284 10285 10286 10287 10288 10289 10290 10291 10292 10293 10294 10295 10296 10297 10298 10299 10300 10301 10302 10303 10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325      13446x     13446x 13446x 13446x 1132x 1132x             13446x     72x 72x 72x   72x   72x 2x 2x 2x 2x 2x 2x     72x 72x 72x 72x 72x 72x 72x 72x   72x 72x 584x 584x             72x     72x 72x       72x 72x     72x 72x 72x     72x 72x 2x   2x     2x 2x 2x 2x 2x 2x   2x 2x 2x   2x 2x 2x     2x 2x       2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x     2x 2x 2x   2x 2x 2x     2x 2x   2x       13446x 13446x   13446x       31812848x 31812848x   2x       76x 76x   2x         26914x 26914x 35840x   26914x         438x 438x 58x 541088x       438x 438x 410x 5278852x 5278852x 5278852x 10557702x   5278852x             438x           13446x 13446x   13446x       13446x             13446x 13446x     13446x 13446x   13446x 13446x     13446x             438x 438x   438x 438x       438x         13446x 13446x 13446x         13446x 13446x   13446x 13446x 13446x 13446x   13446x 13446x   13446x   13446x             5816x       5816x 2x           13444x         13446x 13446x   13446x 13446x 13446x   13446x 13446x   13446x 13446x                 13446x         13446x     13446x         13446x   250x   250x 250x 250x   250x 250x 250x 250x 250x   250x 250x 250x   250x 250x 250x     250x 250x 250x 250x 250x     250x         32382x 19462x 19462x     1226x     13446x                                         81830382x 81529490x 81529490x 81529490x   81330888x 81330888x   198602x 198602x   81529476x         13446x                       13446x 13446x           90096312x             214030x 214030x         13446x   10x 10x 10x 10x   10x 930x 930x 930x 470594x 470594x 470594x 470594x 204x       10x 10x   10x 10x 470594x 470594x               13446x                   13446x     13446x 13446x 13446x 13446x         13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x       13446x 13446x     13446x         13446x 13446x 13446x 13446x 13446x 13446x     13446x                         24256x 301416x 301416x 301416x   301416x 134x 1709824x 1709824x 1577626x 1577626x 1577626x     301416x 11200752x 11200752x 11200752x 470594x 1572x   470594x 64990x           405606x       301416x 1572x 1572x   301416x 170x 170x   2x 2x 2x 2x 2x 2x 2x 2x 2x         2x 2x 2x         2x 2x 2x         2x 2x   2x         301416x 2x     301416x 301416x         170x       11200752x 10138992x 10138992x 10138992x 10138992x 10138992x 10138992x 11200752x 405606x 405606x     9733388x 9733388x 11200752x 2x 2x 2x   9733388x 9733388x 9733388x 9733388x   9733388x 9733388x 9733388x 9733388x 9733388x 11200752x 3748420x 3748420x 64990x 64990x 204x   64990x     9668400x             13446x   13446x         13446x 13446x 13446x       13446x 13446x     13446x 13446x     13446x 13446x 13446x         13446x 13446x     13446x 13446x   13446x 13446x     13446x 13446x 13446x     13446x 13446x 13446x 13446x 13446x       13446x 13446x   13446x 13446x 13446x 13446x               13446x                   13446x     13446x 13446x 13446x 13446x         13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x   13446x       13446x 13446x     13446x         13446x 13446x 13446x 13446x 13446x 13446x     13446x       13444x 13444x       13444x 13444x                     13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x 13446x   13446x     13446x 13446x 13446x 13446x 13446x 13446x   13446x 13446x   13446x             13446x       13446x 13446x 13446x   13446x 13446x       13446x 13446x     13446x 13446x         13444x       13446x 13446x   13446x 13446x       13446x 13446x 13446x             13446x 13446x   13446x       13446x 13446x 13446x     13446x 13446x     13446x 13446x 13446x 13446x     13446x 13446x 13446x 13446x           13446x 13446x 13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x   13446x     13446x             13446x               40x   40x 40x 40x       13446x       13446x     4210682x 4210682x 4210682x       10526698x             2105340x 2105340x 2105340x 2105340x 2105340x 2104954x   2105340x                   2105344x 2105344x   2105344x         2105344x 2105344x 2105344x 2105344x   2105344x             2105344x 2105344x 8421360x 8421360x 8421360x   1774364x 1776534x 1801638x     1801638x 1801638x 1773650x 1773650x       1778050x 1773650x   1778050x 1773622x       2105340x             2085504x 336443920x 336681874x 326434x     336443920x 325418x                   13446x   24x 24x       2869280x 2869280x 2869280x       1104940x 1104940x 1104940x     1104940x 1104940x     1104940x 1104940x     1104940x 1104866x   74x               13446x   18x 18x       1341404x 1341404x 1341404x             696970x 696970x 696970x     696970x       696970x           696970x 696970x     696970x 668984x   27986x         13446x           40x   40x   40x   40x                     2105344x     2105344x         2105344x 1773650x               2105340x     2105344x 2084204x               4954824x             13446x               13444x                       13446x       24x     24x 24x 24x     24x 24x 24x     24x     24x         24x 24x 24x 24x   24x 46x         2x 2x 2x 2x 2x 2x           8008x 8008x 8008x 8008x         1434866x 1434866x 1434866x   1434866x 1434866x 1434866x 1434866x     1434866x 1434866x 1434866x   1434866x 10x 10x       1434858x 1434858x   1434864x 390x 390x 390x 390x 390x 390x 390x       1434858x 1434858x 1434858x   1434858x 1434858x     1434858x     1434866x 46x               13446x       18x     18x           18x 18x 18x     18x     18x         18x 18x 18x 18x   18x 34x         8932398x 8932398x 8932398x 8912582x 4x 4x           2698x 2698x 2698x 2698x         670680x 670680x 670680x 670680x     670680x 670680x 670680x 670680x 6x 6x         670676x 670676x 670676x   670676x     670680x 2x   2x   2x   2x   2x   2x   2x       670674x 670674x 670674x   670674x     670674x   670674x     670674x     670678x 22x             13446x   6x     6x 6x 6x     6x 6x 6x     6x 6x 6x 6x 6x   6x           13444x     13444x     13444x     13446x     13444x     13446x     13446x             6x 6x 6x 6x       6x 6x   6x 170x 170x   170x 8994x 8994x   8994x 8994x 8994x   8994x 8994x   8994x     8994x 8994x       8994x 8994x 8994x 2x                 27588x 27588x 1664x       27588x 1158x   1158x 1158x 2976324x 2976324x 2976324x 8194x 110x   8194x   8194x 8194x 8194x 8194x     2x 2x 2x 2x 2x 2x         2x 2x 2x       2x       2968132x     1158x   1158x 2x       1158x 2x     1158x 1158x           2976324x 2976324x     2976324x 2976324x 2976324x 2976324x 2976324x 2976324x 2976324x 2976324x 2976324x 2976324x 8194x         2976324x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x   2x         2976324x 19816x 19816x 19816x 19816x 19816x 19816x 19816x 19816x 19816x       2968132x 2976324x 2x   2968132x 2968132x     2968132x 2968132x   2976324x     2976324x 2976324x 2976324x     2976324x 2976324x     2976324x   2968132x 2968132x 2968132x 2968132x     2968132x 2968132x 2968132x     2968132x 2968132x 2968132x     2968132x       2968132x 2968132x 2968132x 2968132x     2968132x 2976324x 98414x 98414x 98414x 98414x 98414x 98414x     2869720x 2869720x 2869720x 2x 2x 2x 2x       2869720x 220x 220x 220x 220x 220x 220x 220x   220x 220x 220x 2x 2x   2x 2x             2968132x 2976324x 1156x   2968132x         2968132x 2968132x 2968132x 2968132x   2968132x 2968132x   2968132x 2968132x   2968132x 2968132x   2968132x 2968132x 2968132x 2968132x   2968132x         13446x 13446x 13446x 13446x 13446x 13446x     13446x                                               13446x 13446x 13446x 13446x         13446x 13446x 13446x 13446x 13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x   13446x     13446x 13446x 13446x     13446x 13446x 13446x 13446x           13446x   13446x 13446x     13446x 13446x 13446x   13446x       13446x                   13446x     13446x 13446x     13446x   13446x       13444x               13446x 13446x 13446x   13446x             13446x   6x 6x     6x 6x 6x   6x       13446x               13446x                   13446x     13446x 13446x     13446x   13446x               13446x       232x         232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x 232x         232x 232x 232x 232x         248x 248x 248x 248x 248x     248x   248x 132402x 132402x   132402x 89551740x 89551740x 89551740x   89551740x   19294x 152x   19294x 19294x             258x 258x   258x 2x 2x       258x 258x 2x 2x   258x     258x 258x   258x   258x 258x     258x     258x 2x 2x   258x     258x 256x 256x 252x 252x 252x   252x 2x     252x 252x     2x   2x 2x         2x         13446x 13446x 13446x   13446x       100080x 12406x     99036x 542x 542x   87136x 93780x 87136x   87012x         13446x 13446x           13446x 13446x 13446x   13446x 13446x 13446x 13446x   13446x       186x       170x 2x   170x   170x 170x 2x 2x 2x     170x     170x 170x   2x 2x 2x                           226x 226x 226x 226x     226x 226x 226x 226x 226x 226x 226x       272x 272x 272x 272x   272x             272x 272x 272x 272x     272x     272x     272x   272x 2x   272x 2x 2x       272x           272x 272x                         272x 272x 272x 272x 272x 272x 272x 272x 272x     272x 272x 272x 272x 272x   272x         272x 2x   272x           272x 272x     272x 272x     272x       272x 272x 272x           272x                                                                       272x         272x                   272x                       272x 272x     272x                                             272x                                                                                                                                                                                                                   272x         272x                   272x                           272x 542x                   542x         272x                                                   20590x 20590x 20590x 20590x 20590x             20634x 20634x 20634x   20634x 20634x     20634x                   21812x 21812x 21808x     21808x 21808x 21808x 21808x 21808x     21808x 21812x 20802x 20802x 20802x 20802x     21806x 21806x       20366x 20366x     20364x         20358x 20364x 2x       2x 2x     20358x           20358x   20358x           20358x       20366x 19756x 604x   604x     20316x 20316x 20316x 20316x 20316x                           19864x 19864x 19864x 19864x     19864x 19864x 19864x   19864x     19864x 32558x     32558x 12038x       32558x 81711804x 81711804x 81711804x 81711804x 81711804x 81711804x 81711804x     81711804x 2x 2x 2x   2x 2x       81711804x 2x 2x   2x 2x       81711804x 2x 2x   2x 2x         81711804x 49844378x 49844378x 49844378x 49844378x 31867428x 31867428x 31867428x 31867428x       81711804x     81711804x   81711804x 81711804x 81711804x       32554x   19210x           32170x 2x         26272x 5598x         32170x 75594212x 2x   75594212x 2x   75594212x 2x       75594212x       13302x 13302x 13302x           19864x 19864x 19864x               12446x 5816x 5816x               6432x       6432x       6432x 436x 436x     436x 541086x 541086x 541086x       436x 5278850x 5278850x                           204796x       202x               988x   988x       988x 854x         988x 2973738x     988x 988x 988x       988x 988x         13446x       13446x       13446x       13446x                     13446x 13446x       13446x 13446x       13446x 13444x 13444x 13444x     13444x             13444x 13444x 13444x 13444x     13444x 13444x 13444x 13444x 13444x     13444x   13444x     13446x 13446x 13446x   13446x                 13446x 13446x   13446x 13446x 13446x           13446x         202x 202x   202x 202x 202x 202x     202x   202x         240x                                                                                                                                                                                                                                                                                                                                                                                                                                                                             240x         240x                     238x 238x   238x           238x 238x       238x   238x 2x   238x 238x 2x       238x                 238x 238x           238x           238x   238x 238x   64x 28696112x 24660750x 24660750x         176x 67151292x   176x   236x 236x 236x 236x 2x     236x     236x 236x       246x                             92146x 92146x 92146x   92146x 92146x   92146x   92146x     72700x 4x         4x   72700x   72700x 42x   72698x         19448x 19448x 19448x   19448x 92146x 19448x   2x 2x         19448x 19448x 18818x 18588x 18358x 18130x   19448x 19448x 19448x   19448x 19448x 92146x 115791616x   19390x   19390x 19390x 19390x   19390x 19390x 19390x 19390x 19390x 19390x 19390x 19390x 19390x 19390x 19390x 19390x 19390x 19390x   19390x 19390x 19390x   92146x 620418x     19390x   19390x     19390x     19390x 19390x 19390x 19390x 19390x         19390x   19390x         19390x 19390x 19390x 19390x       92146x 19148x       19332x 19332x 19332x 19332x 19332x   19332x 19332x     2x   92028x           13446x 13446x         13446x 13446x       13446x 13446x     13446x 13446x 13446x 13446x 13446x 13446x       13446x                             58x     58x 58x         56x 56x   56x 56x 56x 56x 56x     56x   56x 56x 2x 2x     56x               13446x   13446x 13446x   13446x         13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x   13446x       13446x                   13446x   13444x 13444x 13444x 13444x     13444x 13444x   13444x 13444x             13444x 13444x 13444x         13444x   13444x     13444x 13444x 13444x 13444x 13444x     13444x 13444x 13444x 13444x         13444x 13444x       13446x               13446x       4x 4x   4x     4x 4x 4x 4x 4x         4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x     4x     4x 4x 4x 4x 4x 4x     4x 4x     4x 4x     4x     4x 4x 4x       4x 4x 4x 4x     4x 4x 4x 4x     4x           13446x 13446x 13446x     13446x 13446x 13446x 13446x 13446x 13446x   13446x         4x 4x                 4x 2x     4x     4x 4x 2x       4x     4x 4x     4x     4x       4x     4x                       4x                                                                                                                                                                                                                                                       4x                                                                                 4x                                                                     4x 4x 4x     4x 4x       8x   8x 8x 8x 8x 2x     8x 8x 8x 8x 2x     8x 8x 8x 8x 8x 2x     8x 8x   8x       4x 4x 4x                                   4x   4x 4x             4x 4x             16x 16x   16x 16x 16x 16x 16x 16x 16x 16x       8x 8x 8x 8x   8x 8x 2x     8x       4x     4x 4x 4x 4x     4x 4x     4x       6x 6x 6x     6x   6x     6x   6x 6x 2x     6x         4x 4x 4x 4x     4x 4x     4x 4x 4x 4x 4x 4x       4x     4x         4x 4x   4x 4x 4x   4x 4x 4x   4x       4x 4x 4x 4x     4x 4x 4x 4x 4x 4x         4x   4x 42x 802x   802x 802x       802x       4x 4x               4x   4x   4x 4x       4x 4x 20x 20x 20x         4x 2x 2x 2x   2x   2x 2x   2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x                   4x 4x   4x 4x       4x 4x         2x         8x             4x           27088x       27088x   27088x     27088x 2x 2x 2x       4x     4x     4x             4x     4x     4x 4x     4x 4x 4x 4x 4x       4x 4x 4x 4x     4x 4x     4x         27088x 27088x   27088x   4x 27088x   2x 2x 2x 2x     4x 4x 4x     4x 4x 4x       4x 4x 4x 4x     4x       27088x 2x           4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x           4x 4x 4x 4x     4x   2x 2x       4x 4x 4x       2x             4x 2x 2x     4x 4x 4x                   4x 4x 4x 4x       4x   4x 4x     4x 4x 4x 4x 4x 4x 4x     4x 2x       4x 4x 4x 4x 4x     4x 4x 4x 4x     4x     4x 4x 4x     4x 4x 4x     4x 4x   4x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x           4x       4x 4x 4x     4x 2x   4x         4x 4x     4x 4x   4x 4x 4x   4x 4x 4x   4x 4x   4x 4x 4x     4x   4x 4x 4x   4x   4x 4x 4x   4x           4x 4x 4x     4x 4x 4x     4x 4x 6x 10x 10x 10x     10x 10x 10x     10x 10x   2x 2x         4x 4x           13444x     13444x     13444x 13444x 13444x     13444x 13444x 13444x 13444x 13444x 13444x 13444x 13444x 13444x           13444x 13444x 13444x 13444x 13444x     13444x   13444x 13444x       13444x 13444x       13444x         6x 6x 6x 6x 6x       13446x     13446x 13446x     13446x 13446x   13446x 13446x 13446x 13446x 13446x   13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x             13446x     13446x 13446x       13446x 13446x 13446x 13446x 13446x     13446x 13446x 13446x     13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x   13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x   13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x   13446x 13446x 13446x   13446x 13446x   13446x                     13446x 13446x     13446x     13446x     13446x 13446x   13446x 13446x 13446x 13446x     13446x       4x     4x 4x     4x     4x 4x       4x 4x 4x   4x 4x 4x   4x 802x 802x   802x 802x   802x 662x 662x 662x 662x 662x   662x 36x   662x 142x 142x 142x 142x 142x   142x 142x 142x   142x 50x   142x                 4x 4x     4x     4x     4x 4x   4x 66x 66x 66x     4x       4x 4x         13446x   13446x                       13446x                 13446x 13444x 13444x 13444x 13444x   13444x 13444x     13444x 13444x 13444x 13444x     13444x 13444x 13444x 13444x         13446x         12x 12x 12x 12x 12x 12x 12x   2x             13446x       6x 6x 6x     6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x     6x     6x 6x 6x 6x     6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x     6x     6x 6x 6x 6x 6x 6x     6x 6x     6x 6x     6x     6x 6x 6x     6x 6x 6x 6x     6x 6x     6x 6x       6x 6x             6x 6x 6x   6x 6x 6x 6x 6x         6x                       6x                                                                       6x                                                                 13446x       6x 6x 6x 6x 6x   6x 6x 6x     6x 6x                                               6x 6x             6x 6x             14x 14x 14x 14x 14x 2x     14x 14x 14x 14x 2x     14x 14x 14x 14x 14x 2x     14x       4x     4x 4x 4x 4x 4x 4x     4x     4x       4x 4x     4x 4x 4x 4x 4x 4x     4x 4x 4x 4x       50x 50x 50x 50x 50x 50x 50x 50x 50x       14x 14x 14x 14x 14x       6x 6x 6x 6x 6x 6x 6x 6x       6x 6x 6x   6x 6x 6x   6x 6x 6x         13446x       6x 6x 6x 6x   6x 6x 1602x 1602x 1602x 1602x     6x 6x         13446x       13446x 13446x 13446x 13446x 13446x       6x 6x   6x     6x 6x 104x   2x   2x 2x 2x 2x     2x 2x 2x       13446x     13446x 13446x 13446x   13446x 13446x 13446x 13446x     13446x   13446x 13446x 13446x   13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x     13446x 13446x 13446x 13446x 13446x     13446x 13446x 13446x   13446x   13446x 13446x 13446x   13446x 13446x 13446x   13446x 13446x 13446x     13446x 13446x 13446x 13446x   13446x 13446x       13446x 13446x   13446x 13446x   13446x 13446x 13446x 13446x 13446x     13446x 13446x 13446x 13446x     13446x 13446x   13446x       13446x 13446x     13446x 13446x     13446x 13446x 13446x   13446x 13446x 13446x   13446x 13446x 13446x   13446x 13446x   13446x 13446x     13446x 13446x 13446x   13446x 13446x 13446x 13446x   13446x       6x 6x   6x   2x 2x 2x 2x 2x 2x     2x 2x 2x     2x 2x 2x     2x 2x 2x 2x   2x       13446x 13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x         13446x     13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x           13446x     13446x 13446x   13446x 13446x     13446x 13446x 13446x 13446x   13446x 13446x 13446x     13446x 13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x   13446x 13446x   13446x 13446x 13446x 13446x 13446x   13446x                     13446x 13446x     13446x 13446x 13446x 13446x 13446x   13446x 13446x 13446x   13446x 13446x 13446x   13446x       13446x 13446x 13446x 13446x                   13446x 13446x 13446x 13446x 13446x 13446x 13446x     13446x                         6x 6x 6x 6x 6x 6x 6x   2x             13446x   4x     4x 4x 4x     4x     4x       4x 4x 4x   4x 4x 4x 4x 4x   4x 4x 4x 4x 4x   4x 42x 42x 42x 42x   42x 802x 802x 802x 802x   802x 802x 802x 802x 802x 802x           4x                                                                                                                                                                                                                                                                                                                                                                                                                                                     4x 4x 4x 4x   4x 4x 4x   4x 802x 802x 802x 802x   802x 802x 802x 802x   802x 802x 802x 802x     4x 4x 4x 4x 4x 4x       13446x 13446x   13446x   13446x 13446x 13446x   13446x 13446x 13446x     13446x       13446x 13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x     13446x     13446x 13446x   13446x 13446x 13446x 13446x     13446x       13444x 13444x               13446x                 13446x 13444x 13444x 13444x 13444x   13444x 13444x     13444x 13444x 13444x 13444x   13444x 13444x   13444x 13444x 13444x     13444x 13444x 13444x 13444x         13446x         13446x   4x     4x 4x 4x     4x     4x           4x 4x 4x     4x 4x     4x 4x     4x     4x     4x 42x   42x 802x   802x 802x     802x 802x     802x 802x     802x             4x     4x 4x 4x 4x 4x 4x 4x 4x     4x     4x     4x 4x     4x 4x 4x 4x 4x 4x     4x 4x 4x 4x       6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x   6x         4x     4x 4x 4x 4x         4x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   4x 4x 4x 4x   4x 4x 4x 4x   4x 802x 802x 802x 802x   802x 802x 802x 802x   802x 802x 802x 802x     802x 802x 802x 802x     4x 4x 4x 4x 4x 4x 4x 4x       13446x     13446x 13446x 13446x   13446x 13446x 13446x 13446x     13446x   13446x 13446x 13446x   13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x 13446x     13446x 13446x 13446x 13446x 13446x     13446x     13446x 13446x 13446x 13446x   13446x   13446x 13446x 13446x   13446x 13446x 13446x   13446x 13446x 13446x     13446x 13446x 13446x     13446x 13446x 13446x 13446x   13446x 13446x       13446x 13446x   13446x   13446x 13446x 13446x   13446x 13446x 13446x     13446x       13446x 13446x 13446x 13446x   13446x   13446x 13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x     13446x     13446x 13446x   13446x 13446x 13446x 13446x     13446x       13446x 13446x                   13446x                 13446x 13444x 13444x 13444x 13444x   13444x 13444x     13444x 13444x 13444x 13444x   13444x 13444x   13444x 13444x 13444x   13444x 13444x   13444x 13444x     13444x 13444x 13444x 13444x         13446x           13446x           34x 34x 34x 34x       34x 34x 34x 34x 34x 34x 34x         53888x       32x         6x   6x 6x         6x 6x 6x 6x 6x 6x 6x     6x   6x 6x         6x           13446x 13446x     13446x 13446x     13446x             13446x 13446x 13446x 13446x     13446x 13446x 13446x 13446x 13446x     13446x   13446x             13446x         22x 22x     22x 22x 22x     22x     22x     22x       22x 22x 22x     22x 22x   22x 22x 22x     22x   22x   22x       22x 22x 22x 22x 22x     22x   2832x     2832x 2832x     2832x   2832x   1311106x     1311106x 1311106x     1311106x   1311106x 1311106x     1311106x 1311106x     1311106x 1311106x     1311106x       22x       24x 24x 24x     24x         24x 24x 24x   24x 2x           24x 24x 2x               24x                 24x             24x     24x                     24x 24x 24x   24x 24x 1319298x 1282x   1318018x   1318018x 1318018x 1318018x 1318018x 1318018x 1318018x 1318018x   1318018x 1318018x 1318018x 1318018x 1318018x 1318018x 1318018x 1318018x 1318018x         24x   24x 24x 24x 24x 24x   24x 24x 24x 24x 24x   24x 24x     24x   24x 24x 24x 24x 24x         34x                                     792x 792x 792x 792x   792x 792x 792x   792x 792x   792x     792x 1564x     1564x 398x       1564x 1316644x 1316644x 1316644x 1316644x   1316644x     1316644x                   1316644x         1316644x   1308638x 1308638x 1308638x 1308638x     1308638x 8006x   8006x 8006x 8006x     8006x 8006x 8006x 8006x   8006x     8006x             1316644x 1316644x 1316644x       1564x   772x           1366x 200x       1564x 1317174x       792x 792x 792x           792x 792x 792x             13446x 13446x   13446x 13446x       13446x 13446x 13446x     13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x 13446x   13446x 13446x 13446x         13446x 13446x 13446x 13446x     13446x               13446x     13446x 13446x 13446x       13446x 13446x 13446x 13446x       13446x 13446x   13446x 13446x   13446x 13446x 13446x   13446x   13446x 13446x             24x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     24x         24x                       19448x 19448x 19448x 19448x 19448x 19448x 19448x   19448x       19448x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x   2x 2x         2x 2x 2x   2x   19448x 18626x 8x   18626x           824x 824x 19448x 824x   2x     824x 824x 19448x 547224x       19448x 2x           818x     818x 818x 818x 19448x   14x 14x 14x         14x 14x       13462x 490x 490x 490x 490x   490x 490x   490x 2085106x 2085106x 2085106x   2085106x 2085106x 2085106x 2085106x 2x 2x 2x   2085106x 2085106x 2085106x       490x 490x     490x           818x 818x 818x 19448x 2362926x   816x   816x 816x 816x 816x   816x 816x 816x 816x   816x 816x 816x 816x 816x 19448x 19448x 19448x 19448x 19448x   19448x 26050x     816x 19448x 19448x 19448x 19448x 19448x 19448x 19448x 19448x   19448x   19448x     19448x     19448x 19448x 19448x 19448x 19448x       19448x   19448x 19448x   19448x 19448x 19448x 19448x           19448x 798x           816x 816x 816x 816x         19448x     887544x           816x 816x 816x 816x 816x   816x 816x     2x   19440x               13446x 13446x       13446x 13446x       13446x     13446x     13446x 13446x 13446x 13446x 13446x 13446x       13446x                                               13446x                   13446x 13446x 13446x 13446x 13446x 13446x   13446x 13446x 13446x           13446x 13446x       13446x 13446x 13446x       13446x 13446x 13446x 13446x 13446x 13446x     13446x     13446x 13446x 13446x 13446x 13446x   13446x 13446x       13446x 13446x 13446x 13446x         13446x                                         13446x         12x 12x     12x 12x 12x     12x     12x     12x                 13446x 13446x   13446x 13446x       13446x     13446x 13446x 13446x   13446x 13446x   13446x   13446x       13446x 13446x 13446x   13446x 13446x 13446x         13446x 13446x   13446x       13446x 13446x   13446x                   13446x     13446x 13446x 13446x       13446x 13446x 13446x 13446x       13446x 13446x   13446x 13446x   13446x 13446x 13446x   13446x   13446x 13446x               394x 394x 394x     394x 394x 18x 18x 18x       18x 18x       394x 76x 76x     76x 76x 1238560x 1238560x 1238560x   1238560x   1238560x 1238560x 1238560x 1238560x 1238560x     76x 76x         12x 12x 12x     12x 12x     12x 12x     12x     12x 12x 12x 12x           12x 376x   376x 24706x   24706x 24706x     24706x 24706x     24706x 24706x     24706x     24706x       12x               10x 10x           10x 10x   10x 10x 10x 10x 10x       10x 2x   10x 2x       10x                                   10x 10x 10x   10x 10x 23906x 752x   23156x   23156x 23156x 23156x 23156x 23156x 23156x 23156x   23156x 23156x 23156x 23156x 23156x 23156x 23156x 23156x   23156x 23156x   10x   10x 10x 10x 10x 10x 10x       24x                                     376x 376x 376x 376x   376x 376x 376x   376x 376x   376x     376x 736x     736x 2x       736x 94034x 94034x 94034x 94034x   94034x     94034x 2x 2x 2x   2x 2x       94034x 2x 2x     94034x   91338x 91338x 91338x 91338x     91338x 2698x   2698x 2698x 2698x     2698x 2698x 2698x 2698x   2698x     2698x             94034x 94034x 94034x       736x   362x           736x 2x       736x 94034x       376x 376x 376x           376x 376x 376x                 12x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               12x           12x 10x 2x 2x       10x                       108x 108x 108x     108x     108x 2x 2x 2x     108x 108x 108x 108x         108x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x   2x 2x         2x 2x 2x   2x   108x 2x 2x   2x           108x 108x 108x 108x   2x     108x 108x 108x 355180x       108x 2x           106x         106x 106x 108x 1390960x 1390960x 154x     104x   104x 104x   104x 104x 104x 104x   104x 104x 104x 104x 104x   104x 104x 104x 104x 104x 108x 108x 108x 108x 108x   108x 3266x     104x 108x 108x 108x 108x 108x 108x 108x 108x 108x 108x   108x   108x       108x     108x   108x 108x 108x 108x       108x   108x 108x   108x 108x 108x 108x           108x 98x           104x 104x 104x 104x         108x     313838x           104x 104x 104x 104x 104x   104x 104x     2x     104x               13446x 13446x       13446x 13446x       13446x     13446x     13446x 13446x 13446x 13446x 13446x 13446x       13446x                                                   13446x                   13446x 13446x 13446x 13446x 13446x 13446x   13446x 13446x 13446x         13446x 13446x       13446x 13446x 13446x       13446x 13446x 13446x 13446x 13446x 13446x     13446x 13446x       13446x     13446x 13446x 13446x 13446x 13446x   13446x 13446x       13446x 13446x 13446x 13446x         13446x         13446x                           13446x 22x 22x 12x     22x     250x 250x 50x   50x 50x 6x     46x   2x           202x             192x       192x 192x 192x   2x 2x 2x               12x   8x 4x     8x 4x     4x 4x         250x       250x             13446x   114x 114x 114x 114x 114x 114x 114x 114x 114x 114x 114x     114x 114x   114x   114x 114x 114x   114x       114x 114x 114x 178262x 178262x           178858x 178272x 178272x             13446x 13446x 13446x   13446x   13446x 13446x 13446x   13446x           13444x         13444x 13444x   13444x         1168x   194x   194x 194x 194x     194x 160x     194x 8x       194x 154x 18x 8x 12x 12x   2x   138x 2x 2x   2x           194x 194x 194x 194x 194x     194x 194x     194x 4x     4x       190x 2x     190x 2x     190x 2x 2x       190x     190x 190x 190x 190x 190x 190x               194x 2x   2x   2x 2x         190x             190x   34x 34x   232x 232x   690x 690x   2x 2x 2x 2x 2x 2x 2x 2x       2x       2x     2x 2x 2x   26x 26x       1168x 590x   576x     576x                   179180x 179180x 12x   179170x     179180x   179010x 286x 286x   179010x   89438x     89574x   89574x 9324x       179010x 179010x 179010x 179010x         179010x 179010x 179010x 179010x   2x 179010x     2x         179010x 179010x 179010x 179010x 179010x       179010x     179010x 179010x 179010x 179010x 179010x 179004x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x       179004x 2x   2x 2x       178880x 178880x 178880x 179010x   179010x     179010x 2322x 2322x 2322x         2322x   2322x                                             2322x 2322x 2322x 2322x 2322x   104x         162x 126x   162x   178860x           13444x             13446x 13446x 13446x     13446x 13446x 13446x 13446x 13446x     13446x   13446x 13446x     13446x 13446x         13446x     13446x   13446x 13446x       13446x             13444x 13444x 13444x           13444x 13444x         13444x     13444x   13444x 13446x   13446x 13446x 13446x         13446x 13446x 13446x 13446x     13446x 13446x 13446x 13446x     13446x 13446x   13446x 13446x   13446x     13446x 13446x 13446x 13446x 13446x     13446x 13444x 13444x     13444x 13446x 13446x 13446x 13444x     13444x 13444x 13446x     13446x 13446x 13446x 13446x 13446x     13446x 13446x 13446x 13446x 13446x 13446x   13446x     13446x 13446x 13446x 13446x 13446x     13446x 13446x             13446x 13446x 13446x 13446x 13446x   13446x 13446x 13446x 13446x 13446x 13446x 13446x       13446x 13446x 13446x 13446x     13446x 13446x               13446x 13446x 13446x 13446x 13446x     13446x 13446x 13446x 13446x     13446x 13446x 13446x   2x 13446x 13446x     13446x 13446x 13446x 13446x 13446x 2x 2x 13446x 13446x 13446x   2x 13446x 13446x 2x 13446x 13446x 13446x 13446x 13446x 13446x 2x 13446x 13446x 13446x 2x 2x 2x 13446x 13446x 2x 2x     2x   13446x 2x   13446x 13446x 13446x 13446x 13446x       13446x 13446x 13446x         2x 2x 13446x
// Linefeeds to align line numbers with HTML.
// <script id="workerCode">
// Constants
const MAX_CHAOTIC_ITERATIONS = 100000;
 
// Helper function to check debug flags
function hasDebugFlag(config, flag) {
  const debug = config?.debug;
  if (!debug) return false;
  const parts = debug.split(',').map(f => f.trim());
  return parts.some(p => p === flag || p.startsWith(flag + '='));
}
 
 
// Utility class for managing precomputed pixel data inherited from parent views.
// Used by all board types to skip computation for pixels known from parent.
// Uses TypedArrays for efficient storage of pending data.
class PrecomputedPoints {
  constructor(inheritedData) {
    // Track which pixels are pre-known (for excluding from compute)
    this.knownPixels = new Set();
    this.knownMask = null;
    this.knownCount = 0;
    // Map<iter, {dStart, dCount, cStart, cCount}>
    this.rangeMap = new Map();
 
    if (!inheritedData) {
      this.dIndices = new Uint32Array(0);
      this.cIndices = new Uint32Array(0);
      this.cP = new Uint32Array(0);
      this.cZ = new Float64Array(0);
      this.zStride = 2;
      return;
    }
 
    if (inheritedData.packed) {
      this.dIndices = inheritedData.dIndices || new Uint32Array(0);
      this.cIndices = inheritedData.cIndices || new Uint32Array(0);
      this.cP = inheritedData.cP || new Uint32Array(0);
      this.cZ = inheritedData.cZ || new Float64Array(0);
      this.zStride = inheritedData.zStride || 2;
      this.knownMask = inheritedData.knownMask || null;
      this.knownCount = this.dIndices.length + this.cIndices.length;
 
      const ranges = inheritedData.ranges || new Uint32Array(0);
      for (let i = 0; i + 4 < ranges.length; i += 5) {
        const iter = ranges[i];
        this.rangeMap.set(iter, {
          dStart: ranges[i + 1],
          dCount: ranges[i + 2],
          cStart: ranges[i + 3],
          cCount: ranges[i + 4]
        });
      }
      return;
    }
 
    const diverged = inheritedData.diverged || [];
    const converged = inheritedData.converged || [];
 
    // Sort to ensure contiguous storage per iteration
    // (Use stable sort if preserving index order matters, but here it doesn't)
    diverged.sort((a, b) => a.iter - b.iter);
    converged.sort((a, b) => a.iter - b.iter);
 
    // Allocate storage
    this.dIndices = new Uint32Array(diverged.length);
    this.cIndices = new Uint32Array(converged.length);
    this.cP = new Uint32Array(converged.length);
 
    // Determine Z stride
    this.zStride = 2;
    if (converged.length > 0 && converged[0].z && converged[0].z.length > 2) {
      this.zStride = converged[0].z.length;
    }
    this.cZ = new Float64Array(converged.length * this.zStride);
 
    // Fill Diverged
    let currentIter = -1;
    let start = 0;
    for (let i = 0; i < diverged.length; i++) {
      const item = diverged[i];
      this.knownPixels.add(item.index);
      this.dIndices[i] = item.index;
 
      if (item.iter !== currentIter) {
        if (currentIter !== -1) {
          this.getRange(currentIter).dCount = i - start;
        }
        currentIter = item.iter;
        start = i;
        this.getRange(currentIter).dStart = start;
      }
    }
    if (currentIter !== -1) {
      this.getRange(currentIter).dCount = diverged.length - start;
    }
 
    // Fill Converged
    currentIter = -1;
    start = 0;
    for (let i = 0; i < converged.length; i++) {
      const item = converged[i];
      this.knownPixels.add(item.index);
      this.cIndices[i] = item.index;
      this.cP[i] = item.p;
      
      const zOffset = i * this.zStride;
      const zLen = Math.min(this.zStride, item.z ? item.z.length : 0);
      for (let k = 0; k < zLen; k++) {
        this.cZ[zOffset + k] = item.z[k];
      }
 
      if (item.iter !== currentIter) {
        if (currentIter !== -1) {
          this.getRange(currentIter).cCount = i - start;
        }
        currentIter = item.iter;
        start = i;
        this.getRange(currentIter).cStart = start;
      }
    }
    if (currentIter !== -1) {
      this.getRange(currentIter).cCount = converged.length - start;
    }
    this.knownCount = this.knownPixels.size;
  }
 
  getRange(iter) {
    if (!this.rangeMap.has(iter)) {
      this.rangeMap.set(iter, { dStart: 0, dCount: 0, cStart: 0, cCount: 0 });
    }
    return this.rangeMap.get(iter);
  }
 
  isPrecomputed(index) {
    if (this.knownMask) {
      return this.knownMask[index] === 1;
    }
    return this.knownPixels.has(index);
  }
 
  getPrecomputedCount() {
    if (this.knownMask) {
      return this.knownCount;
    }
    return this.knownPixels.size;
  }
 
  // Get count of pending (not yet reported) precomputed points
  getPendingCount() {
    let count = 0;
    for (const range of this.rangeMap.values()) {
      count += range.dCount + range.cCount;
    }
    return count;
  }
 
  // Helper to reconstruct objects from TypedArrays
  extractData(range) {
    const diverged = [];
    if (range.dCount > 0) {
      for (let i = 0; i < range.dCount; i++) {
        diverged.push(this.dIndices[range.dStart + i]);
      }
    }
 
    const converged = [];
    if (range.cCount > 0) {
      for (let i = 0; i < range.cCount; i++) {
        const idx = range.cStart + i;
        const z = new Array(this.zStride);
        for (let k = 0; k < this.zStride; k++) {
          z[k] = this.cZ[idx * this.zStride + k];
        }
        converged.push({
          index: this.cIndices[idx],
          z: z,
          p: this.cP[idx]
        });
      }
    }
    return { diverged, converged };
  }
 
  // Called each iteration to inject pending reports into changeList.
  // Reports pixels that completed at this iteration count.
  flushAtIteration(iter, board) {
    const range = this.rangeMap.get(iter);
    if (!range) return;
 
    const { diverged, converged } = this.extractData(range);
 
    // Queue the changes for reporting to main thread
    // Note: diverged is just indices (nn), converged is objects (vv)
    board.queueChanges({
      iter,
      nn: diverged,
      vv: converged
    });
 
    // Update board's internal counters
    board.di += diverged.length;
    board.un -= diverged.length + converged.length;
 
    // Mark pixels as done in nn[]
    for (const idx of diverged) {
      board.nn[idx] = iter;
    }
    for (const c of converged) {
      board.nn[c.index] = -iter;
    }
 
    this.rangeMap.delete(iter);
  }
 
  // Get and remove pending reports for a specific iteration.
  // Returns {diverged: [...], converged: [...]} or null if none.
  // Does NOT update board counters - caller is responsible for that.
  extractAtIteration(iter) {
    const range = this.rangeMap.get(iter);
    if (!range) return null;
    
    const data = this.extractData(range);
    this.rangeMap.delete(iter);
    
    // Consumers expect {diverged: [indices], converged: [objects]}
    // extractData provides exactly this.
    return data;
  }
 
  // Get all iterations that have pending reports, optionally below maxIter.
  getPendingIterations(maxIter = null) {
    const keys = Array.from(this.rangeMap.keys());
    const filtered = maxIter === null ? keys : keys.filter(iter => iter < maxIter);
    return filtered.sort((a, b) => a - b);
  }
 
  // Extract and remove ALL pending reports below maxIter.
  extractBelowIteration(maxIter) {
    const iters = this.getPendingIterations(maxIter);
    if (iters.length === 0) return null;
 
    const combined = { diverged: [], converged: [] };
    for (const iter of iters) {
      const range = this.rangeMap.get(iter);
      const data = this.extractData(range);
      
      for (const item of data.diverged) combined.diverged.push(item);
      for (const item of data.converged) combined.converged.push(item);
      
      this.rangeMap.delete(iter);
    }
    return combined.diverged.length > 0 || combined.converged.length > 0 ? combined : null;
  }
 
  // Flush all pending reports up to and including maxIter.
  // Used by GPU boards that compute in batches.
  flushUpToIteration(maxIter, board) {
    // Get iterations in sorted order to maintain proper changeList ordering
    const iterations = Array.from(this.rangeMap.keys())
      .filter(iter => iter <= maxIter)
      .sort((a, b) => a - b);
 
    for (const iter of iterations) {
      this.flushAtIteration(iter, board);
    }
  }
 
  // Check if all pending reports have been flushed
  isEmpty() {
    return this.rangeMap.size === 0;
  }
 
  // Serialize for board transfer between workers
  serialize() {
    const diverged = [];
    const converged = [];
    
    for (const iter of this.rangeMap.keys()) {
      const range = this.rangeMap.get(iter);
      const data = this.extractData(range);
      
      for (const idx of data.diverged) {
        diverged.push({ index: idx, iter });
      }
      for (const item of data.converged) {
        converged.push({ 
          index: item.index, 
          iter, 
          z: item.z, 
          p: item.p 
        });
      }
    }
    // knownPixels is redundant as it can be rebuilt from diverged/converged
    return { diverged, converged };
  }
 
  // Restore from serialized state
  static fromSerialized(data) {
    if (!data) return null;
    // Constructor rebuilds everything (TypedArrays, knownPixels, rangeMap)
    // from the diverged/converged arrays
    return new PrecomputedPoints(data);
  }
}
 
// Abstract base class for Mandelbrot computation backends.
class Board {
  constructor(k, size, re, im, config, id, inheritedData = null) {
    this.k = k;    // Number in explorer
    // Store size as double (sufficient for scaling), coordinates as QD
    this.sizesQD = [typeof size === 'number' ? size : qdToNumber(size), toQD(re), toQD(im)];
    this.id = id;  // Random ID
    this.config = config;  // Global config
 
    this.it = 1;            // Current iteration
    this.un = config.dimsArea; // Unfinished pixels
    this.di = 0;            // Diverged pixels
    this.ch = 0;            // Chaotic pixels
    this.effort = 100;      // Benchmarked: 4.4 ns/px-iter (baseline)
 
    this.pix = this.pixelSize;
    this.epsilon = this.pix / 10;
    this.epsilon2 = this.pix * 10;
 
    this.lastTime = 0;      // Time last message sent out
    this.changeList = [];   // List of new data to send
    this.updateSize = 0;    // Amount of data to send
 
    // Initialize arrays
    this.nn = new Array(this.config.dimsArea).fill(0);
    this.pp = new Array(this.config.dimsArea).fill(0);
    this.cc = [];
    this.zz = [];
    this.bb = [];
 
    // Initialize precomputed points from parent view (if provided)
    this.precomputed = inheritedData ? new PrecomputedPoints(inheritedData) : null;
  }
 
  // Getter properties that derive from sizesQD (the authoritative source)
  // sizesQD format: [sizeDouble, reQD, imQD]
  get size() { return this.sizesQD[0]; }
  get re() { return this.sizesQD[1]; }
  get im() { return this.sizesQD[2]; }
 
  // Derived scalar property
  get pixelSize() { return this.size / this.config.dimsWidth; }
 
  async serialize() {
    return {
      type: this.constructor.name,
      k: this.k,
      sizesQD: this.sizesQD,
      id: this.id,
      config: this.config,
      it: this.it,
      un: this.un,
      di: this.di,
      ch: this.ch,
      lastTime: this.lastTime,
      changeList: this.changeList,
      updateSize: this.updateSize,
      precomputed: this.precomputed ? this.precomputed.serialize() : null
    };
  }
 
  compact() {
  }
 
  queueChanges(changes) {
    if (changes !== null) {
      if (!this.changeMap) this.changeMap = new Map();
      const existing = this.changeMap.get(changes.iter);
      if (existing) {
        // Use loop instead of spread to avoid stack overflow with large arrays
        for (const item of changes.nn) existing.nn.push(item);
        for (const item of changes.vv) existing.vv.push(item);
      } else {
        this.changeList.push(changes);
        this.changeMap.set(changes.iter, changes);
      }
      this.updateSize += changes.nn.length + changes.vv.length;
    }
  }
 
  static fromSerialized(serialized) {
    const subclasses = new Map([
      ['CpuBoard', CpuBoard],
      ['QDCpuBoard', QDCpuBoard],
      ['DDZhuoranBoard', DDZhuoranBoard],
      ['QDZhuoranBoard', QDZhuoranBoard],
      ['GpuBoard', GpuBoard],
      ['GlBoard', GlBoard],
      ['GlZhuoranBoard', GlZhuoranBoard],
      ['GpuZhuoranBoard', GpuZhuoranBoard],
      ['GpuAdaptiveBoard', GpuAdaptiveBoard],
      ['GlAdaptiveBoard', GlAdaptiveBoard]
    ]);
    const board = subclasses.get(serialized.type).fromSerialized(serialized);
    return board;
  }
 
  inspike(re, im) {
    // We do not iterate infinitely for chaotic points in the spike.
    // -1.401155 is the Feigenbaum point boundary
    return (im == 0.0 && re > -2.0 && re < -1.401155 &&
            this.config.exponent == 2);
  }
 
 
  unfinished() {
    // Chaotic points in the spike counted as finished after max iterations.
    const result = Math.max(0, this.un + (this.it < MAX_CHAOTIC_ITERATIONS ? 0 : -this.ch));
    return result;
  }
}
 
// CPU board using double precision arithmetic for shallow zoom depths.
class CpuBoard extends Board {
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
    const sizeScalar = this.size;
    const reDD = qdToDD(this.re);
    const imDD = qdToDD(this.im);
    // Initialize board: cc = c values, zz = current z, bb = checkpoint z, ss = active pixel indices
    for (let y = 0; y < this.config.dimsHeight; y++) {
      const jFrac = (0.5 - (y / this.config.dimsHeight));
      const j = jFrac * (sizeScalar / this.config.aspectRatio) + imDD[0];  // Scale by height
      for (let x = 0; x < this.config.dimsWidth; x++) {
        const rFrac = ((x / this.config.dimsWidth) - 0.5);
        const r = rFrac * sizeScalar + reDD[0];  // Scale by width
        this.cc.push(r, j);
        if (this.inspike(r, j)) {
          this.ch += 1;
        }
      }
    }
    this.zz = this.cc.slice();  // Start with z = c
    this.bb = this.cc.slice();  // Initial checkpoint = c
    // Initialize active pixel list, excluding precomputed pixels
    this.ss = [];
    for (let i = 0; i < this.config.dimsArea; i++) {
      if (!this.precomputed || !this.precomputed.isPrecomputed(i)) {
        this.ss.push(i);
      }
    }
    // Note: don't adjust this.un here - it will be decremented by flushAtIteration
    // when precomputed points are flushed, which properly updates di/un together
  }
 
  static fromSerialized(serialized) {
    const board = new CpuBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    // Override initialized values with serialized data
    Object.assign(board, serialized);
 
    // Restore nn values for completed pixels
    board.nn = new Array(serialized.config.dimsArea).fill(0);
    if (serialized.completedIndexes) {
      for (let i = 0; i < serialized.completedIndexes.length; i++) {
        board.nn[serialized.completedIndexes[i]] = serialized.completedNn[i];
      }
    }
 
    // Reconstruct sparse arrays from serialized data
    const cc = board.cc;
    board.cc = [];
    board.zz = [];
    board.bb = [];
    board.pp = [];
    for (let i = 0; i < serialized.ss.length; i++) {
      const index = serialized.ss[i];
      board.cc[index * 2] = cc[index * 2];
      board.cc[index * 2 + 1] = cc[index * 2 + 1];
      board.zz[index * 2] = serialized.zz[i * 2];
      board.zz[index * 2 + 1] = serialized.zz[i * 2 + 1];
      board.bb[index * 2] = serialized.bb[i * 2];
      board.bb[index * 2 + 1] = serialized.bb[i * 2 + 1];
      board.pp[index] = serialized.pp[i];
    }
 
    // Restore precomputed points state
    if (serialized.precomputed) {
      board.precomputed = PrecomputedPoints.fromSerialized(serialized.precomputed);
    }
 
    return board;
  }
 
  async serialize() {
    // Build sparse nn array for completed pixels (non-zero nn values)
    const completedIndexes = [];
    const completedNn = [];
    for (let i = 0; i < this.nn.length; i++) {
      if (this.nn[i] !== 0) {
        completedIndexes.push(i);
        completedNn.push(this.nn[i]);
      }
    }
    return {
      ...(await super.serialize()),
      ss: this.ss,
      zz: this.ss.flatMap(i => [this.zz[i*2], this.zz[i*2+1]]),
      bb: this.ss.flatMap(i => [this.bb[i*2], this.bb[i*2+1]]),
      pp: this.ss.map(index => this.pp[index]),
      completedIndexes,
      completedNn,
    }
  }
 
  iterate(targetIters = 1) {
    // Batch multiple iterations internally
    for (let batch = 0; batch < targetIters && this.un > 0; batch++) {
      let changes = null;
      const results = [0, 0, 0];
      let s = this.ss;    // speedy list of active pixel indices to compute
      // Update checkpoints at fibonacciPeriod intervals (returns 1 at Fibonacci points)
      if (fibonacciPeriod(this.it) == 1) {
        for (let t = 0; t < s.length; ++t) {
          let m = s[t];
          if (this.nn[m]) continue;
          this.bb[m * 2] = this.zz[m * 2];      // bb = checkpoint z position
          this.bb[m * 2 + 1] = this.zz[m * 2 + 1];
          this.pp[m] = 0;  // Reset pp (period = iter when convergence first detected)
        }
      }
      for (let t = 0; t < s.length; ++t) {
        const index = s[t];
        const computeResult = this.compute(index);
        if (computeResult !== 0) {
          if (!changes) {
            changes = { iter: this.it, nn: [], vv: [] };
          }
          if (computeResult < 0) {
            changes.vv.push({
              index: index,
              z: [this.zz[index * 2], this.zz[index * 2 + 1]],  // float64 pair
              p: this.pp[index]  // period
            });
          } else {
            changes.nn.push(index);
          }
        }
      }
      if (changes) {
        this.un -= changes.nn.length + changes.vv.length; // newly finished
        this.di += changes.nn.length; // diverged
      }
      if (s.length > this.un * 1.25) {
        this.compact();
        if (this.ss.length > this.un + this.ch) {
          // Debug: Check for overlap between ss and changes
          if (changes) {
            const ssSet = new Set(this.ss);
            const changedIndexes = new Set([...changes.nn, ...changes.vv.map(v => v.index)]);
            const overlap = [...ssSet].filter(x => changedIndexes.has(x));
            if (overlap.length > 0) {
              console.warn(`Overlap detected between ss and changes: ${overlap.length} items`);
              console.warn(`Overlap indexes: ${overlap}`);
              console.warn(`ss length: ${this.ss.length}, un: ${this.un}`);
              console.warn(`changes: nn ${changes.nn.length}, vv ${changes.vv.length}`);
            }
          }
 
          // Additional checks
          const uniqueSS = new Set(this.ss);
          if (uniqueSS.size !== this.ss.length) {
            console.warn(
              `Duplicate entries in ss detected. ss length: ${this.ss.length}, ` +
              `unique entries: ${uniqueSS.size}`);
          }
 
          const invalidIndexes = this.ss.filter(i => this.nn[i]);
          if (invalidIndexes.length > 0) {
            console.warn(
              `Found ${invalidIndexes.length} indexes in ss that are ` +
              `already marked as finished in nn`);
          }
 
          if (this.ss.length !== this.un + this.ch) {
            console.warn(`Mismatch between ss length (${this.ss.length}) and un (${this.un})`);
          }
          throw new Error(`excess ss ${s.length}, ${this.ss.length}, ${this.un}`);
        }
      }
 
      // Flush precomputed points at this iteration
      if (this.precomputed) {
        this.precomputed.flushAtIteration(this.it, this);
      }
 
      this.queueChanges(changes);
      this.it++;
    }
  }
 
  compact() {
    this.ss = this.ss.filter(i => !this.nn[i]);
  }
 
  compute(m) {
    if (this.nn[m]) return 0;
    const m2 = m * 2;
    const m2i = m2 + 1;
    const r = this.zz[m2];
    const j = this.zz[m2i];
    const r2 = r * r;
    const j2 = j * j;
    if (r2 + j2 > 4.0) {
      this.nn[m] = this.it;
      return 1;  // Diverged
    }
    // Mandelbrot iteration: z = z^exponent + c
    let ra = r2 - j2;
    let ja = 2 * r * j;
    for (let ord = 2; ord < this.config.exponent; ord++) {
      let rt = r * ra - j * ja;
      ja = r * ja + j * ra;
      ra = rt;
    }
    ra += this.cc[m2];
    ja += this.cc[m2i];
    this.zz[m2] = ra;
    this.zz[m2i] = ja;
    // Check convergence: compare current z to checkpoint
    const rb = this.bb[m2];
    const jb = this.bb[m2i];
    const db = Math.abs(rb - ra) + Math.abs(jb - ja);  // distance from checkpoint
    const epsilon = this.epsilon;
    const epsilon2 = this.epsilon2;
    if (db <= epsilon2) {
      if (!this.pp[m]) { this.pp[m] = this.it; }  // Record iter when first detected
      if (db <= epsilon) {
        this.nn[m] = -this.it;
        if (this.inspike(this.cc[m2], this.cc[m2i]) && this.ch > 0) {
          this.ch -= 1;
        }
        return -1;  // Converged
      }
    }
    return 0;  // Continue iterating
  }
 
}
 
// CPU board using direct QD-precision iteration (no perturbation).
// Very slow but maximally accurate - serves as ground truth for verification.
class QDCpuBoard extends Board {
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
    // Override epsilon for QD precision - need much tighter thresholds
    // to avoid false convergence detection at deep zoom.
    // Base Board uses pix/10 and pix*10, but for direct QD iteration
    // we need thresholds much smaller than pixel size.
    this.epsilon = this.pix * 1e-20;   // Final convergence threshold
    this.epsilon2 = this.pix * 1e-15;  // Getting close threshold
    this.effort = 11200;  // Benchmarked: 493 ns/px-iter, 112× slower than CPU
    // Use QD-precision values from getters
    // IMPORTANT: At deep zoom (z > 1e30), double precision cannot represent
    // the pixel size or offset accurately. Must use QD precision throughout.
    const reQD = this.re;
    const imQD = this.im;
    // Pre-compute size/aspectRatio in QD precision for y offsets
    // Use toQDMul instead of toQDScale to capture error terms at deep zoom
    const aspectRecipQD = toQD(1 / this.config.aspectRatio);
    const sizeOverAspect = toQDMul(this.size, aspectRecipQD);
    
    // Temps for loop to avoid allocation
    const tempQD = new Array(4);
    const jQD = new Array(4);
    const rQD = new Array(4);
 
    // Initialize board: cc = c values (8 floats per pixel), zz = current z (8 floats per pixel)
    // bb = checkpoint z, ss = active pixel indices
    // Format: [r0, r1, r2, r3, i0, i1, i2, i3] for each complex number
    for (let y = 0; y < this.config.dimsHeight; y++) {
      const jFrac = (0.5 - (y / this.config.dimsHeight));
      // Use arQdMul instead of toQDScale to capture error terms
      // jFrac is treated as QD [jFrac, 0, 0, 0]
      arQdMul(tempQD, 0, sizeOverAspect[0], sizeOverAspect[1], sizeOverAspect[2], sizeOverAspect[3], jFrac, 0, 0, 0);
      arQdAdd(jQD, 0, imQD[0], imQD[1], imQD[2], imQD[3], tempQD[0], tempQD[1], tempQD[2], tempQD[3]);
      
      for (let x = 0; x < this.config.dimsWidth; x++) {
        const rFrac = ((x / this.config.dimsWidth) - 0.5);
        // Use arQdMul instead of toQDScale to capture error terms
        // size (if double) is [size, 0, 0, 0] as QD
        const sz = this.size;
        arQdMul(tempQD, 0, sz, 0, 0, 0, rFrac, 0, 0, 0);
        arQdAdd(rQD, 0, reQD[0], reQD[1], reQD[2], reQD[3], tempQD[0], tempQD[1], tempQD[2], tempQD[3]);
 
        // Store c as 8 floats: [r0, r1, r2, r3, i0, i1, i2, i3]
        this.cc.push(rQD[0], rQD[1], rQD[2], rQD[3], jQD[0], jQD[1], jQD[2], jQD[3]);
        const r = rQD[0] + rQD[1] + rQD[2] + rQD[3];
        const j = jQD[0] + jQD[1] + jQD[2] + jQD[3];
        if (this.inspike(r, j)) {
          this.ch += 1;
        }
      }
    }
    this.zz = this.cc.slice();  // Start with z = c
    this.bb = this.cc.slice();  // Initial checkpoint = c
    // Initialize active pixel list, excluding precomputed pixels
    this.ss = [];
    for (let i = 0; i < this.config.dimsArea; i++) {
      if (!this.precomputed || !this.precomputed.isPrecomputed(i)) {
        this.ss.push(i);
      }
    }
    // Note: don't adjust this.un here - it will be decremented by flushAtIteration
    // when precomputed points are flushed, which properly updates di/un together
  }
 
  static fromSerialized(serialized) {
    const board = new QDCpuBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    // Override initialized values with serialized data
    Object.assign(board, serialized);
 
    // Restore nn values for completed pixels
    board.nn = new Array(serialized.config.dimsArea).fill(0);
    if (serialized.completedIndexes) {
      for (let i = 0; i < serialized.completedIndexes.length; i++) {
        board.nn[serialized.completedIndexes[i]] = serialized.completedNn[i];
      }
    }
 
    // Reconstruct sparse arrays from serialized data (8 floats per pixel)
    const cc = board.cc;
    board.cc = [];
    board.zz = [];
    board.bb = [];
    board.pp = [];
    for (let i = 0; i < serialized.ss.length; i++) {
      const index = serialized.ss[i];
      const i8 = index * 8;
      for (let j = 0; j < 8; j++) {
        board.cc[i8 + j] = cc[i8 + j];
        board.zz[i8 + j] = serialized.zz[i * 8 + j];
        board.bb[i8 + j] = serialized.bb[i * 8 + j];
      }
      board.pp[index] = serialized.pp[i];
    }
 
    // Restore precomputed points state
    if (serialized.precomputed) {
      board.precomputed = PrecomputedPoints.fromSerialized(serialized.precomputed);
    }
 
    return board;
  }
 
  async serialize() {
    // Build sparse nn array for completed pixels (non-zero nn values)
    const completedIndexes = [];
    const completedNn = [];
    for (let i = 0; i < this.nn.length; i++) {
      if (this.nn[i] !== 0) {
        completedIndexes.push(i);
        completedNn.push(this.nn[i]);
      }
    }
    return {
      ...(await super.serialize()),
      ss: this.ss,
      zz: this.ss.flatMap(i => {
        const i8 = i * 8;
        return [this.zz[i8], this.zz[i8+1], this.zz[i8+2], this.zz[i8+3],
                this.zz[i8+4], this.zz[i8+5], this.zz[i8+6], this.zz[i8+7]];
      }),
      bb: this.ss.flatMap(i => {
        const i8 = i * 8;
        return [this.bb[i8], this.bb[i8+1], this.bb[i8+2], this.bb[i8+3],
                this.bb[i8+4], this.bb[i8+5], this.bb[i8+6], this.bb[i8+7]];
      }),
      pp: this.ss.map(index => this.pp[index]),
      completedIndexes,
      completedNn,
    }
  }
 
  iterate(targetIters = 1) {
    // Batch multiple iterations internally
    for (let batch = 0; batch < targetIters && this.un > 0; batch++) {
      let changes = null;
      let s = this.ss;    // speedy list of active pixel indices to compute
      // Update checkpoints at fibonacciPeriod intervals (returns 1 at Fibonacci points)
      if (fibonacciPeriod(this.it) == 1) {
        for (let t = 0; t < s.length; ++t) {
          let m = s[t];
          if (this.nn[m]) continue;
          const m8 = m * 8;
          for (let i = 0; i < 8; i++) {
            this.bb[m8 + i] = this.zz[m8 + i];
          }
          this.pp[m] = 0;  // Reset pp (period = iter when convergence first detected)
        }
      }
      for (let t = 0; t < s.length; ++t) {
        const index = s[t];
        const computeResult = this.compute(index);
        if (computeResult !== 0) {
          if (!changes) {
            changes = { iter: this.it, nn: [], vv: [] };
          }
          if (computeResult < 0) {
            const m8 = index * 8;
            // Preserve full QD precision (8 elements: 4 real + 4 imag)
            changes.vv.push({
              index: index,
              z: [this.zz[m8], this.zz[m8+1], this.zz[m8+2], this.zz[m8+3],
                  this.zz[m8+4], this.zz[m8+5], this.zz[m8+6], this.zz[m8+7]],
              p: this.pp[index]  // period
            });
          } else {
            changes.nn.push(index);
          }
        }
      }
      if (changes) {
        this.un -= changes.nn.length + changes.vv.length; // newly finished
        this.di += changes.nn.length; // diverged
      }
      if (s.length > this.un * 1.25) {
        this.compact();
      }
 
      // Flush precomputed points at this iteration
      if (this.precomputed) {
        this.precomputed.flushAtIteration(this.it, this);
      }
 
      this.queueChanges(changes);
      this.it++;
    }
  }
 
  compact() {
    this.ss = this.ss.filter(i => !this.nn[i]);
  }
 
  compute(m) {
    if (this.nn[m]) return 0;
    const m8 = m * 8;
    // Extract z as QD complex: [r0, r1, r2, r3] and [i0, i1, i2, i3]
    const zr = [this.zz[m8], this.zz[m8+1], this.zz[m8+2], this.zz[m8+3]];
    const zi = [this.zz[m8+4], this.zz[m8+5], this.zz[m8+6], this.zz[m8+7]];
 
    // Mandelbrot iteration: z = z² + c using QD precision
    // z² = (zr + zi*i)² = zr² - zi² + 2*zr*zi*i
    const zr2 = toQDSquare(zr);      // zr²
    const zi2 = toQDSquare(zi);      // zi²
    const zri = toQDMul(zr, zi);     // zr * zi
 
    // Check escape: |z|² > 4 using FULL QD precision comparison
    // IMPORTANT: Cannot sum components to double and compare - this loses precision
    // when |z|² ≈ 4 and differences are at 1e-34 scale. Adjacent pixels would escape
    // at the same iteration, creating vertical stripes in the output.
    // Instead, compute |z|² - 4 in QD precision and check if positive.
    const mag2QD = toQDAdd(zr2, zi2);  // |z|² in QD precision
    const diffQD = toQDSub(mag2QD, [4, 0, 0, 0]);  // |z|² - 4
    // Check if diff > 0: find first non-zero component and check its sign
    const escaped = diffQD[0] > 0 ||
      (diffQD[0] === 0 && (diffQD[1] > 0 ||
        (diffQD[1] === 0 && (diffQD[2] > 0 ||
          (diffQD[2] === 0 && diffQD[3] > 0)))));
    if (escaped) {
      this.nn[m] = this.it;
      return 1;  // Diverged
    }
 
    const newZr = toQDSub(zr2, zi2); // zr² - zi²
    const newZi = toQDDouble(zri);   // 2 * zr * zi
 
    // Add c
    const cr = [this.cc[m8], this.cc[m8+1], this.cc[m8+2], this.cc[m8+3]];
    const ci = [this.cc[m8+4], this.cc[m8+5], this.cc[m8+6], this.cc[m8+7]];
    const finalZr = toQDAdd(newZr, cr);
    const finalZi = toQDAdd(newZi, ci);
 
    // Store back
    this.zz[m8] = finalZr[0]; this.zz[m8+1] = finalZr[1];
    this.zz[m8+2] = finalZr[2]; this.zz[m8+3] = finalZr[3];
    this.zz[m8+4] = finalZi[0]; this.zz[m8+5] = finalZi[1];
    this.zz[m8+6] = finalZi[2]; this.zz[m8+7] = finalZi[3];
 
    // Check convergence: compare current z to checkpoint
    // IMPORTANT: Must compute difference in QD precision FIRST, then convert to double.
    // If we sum to double first and then subtract, we lose precision due to catastrophic
    // cancellation when z ≈ 2 (fixed point) and differences are at 1e-35 scale.
    const bbR = [this.bb[m8], this.bb[m8+1], this.bb[m8+2], this.bb[m8+3]];
    const bbI = [this.bb[m8+4], this.bb[m8+5], this.bb[m8+6], this.bb[m8+7]];
    const diffR = toQDSub(finalZr, bbR);
    const diffI = toQDSub(finalZi, bbI);
    const db = Math.abs(diffR[0] + diffR[1] + diffR[2] + diffR[3]) +
               Math.abs(diffI[0] + diffI[1] + diffI[2] + diffI[3]);
    const epsilon = this.epsilon;
    const epsilon2 = this.epsilon2;
    if (db <= epsilon2) {
      if (!this.pp[m]) { this.pp[m] = this.it; }  // Record iter when first detected
      if (db <= epsilon) {
        this.nn[m] = -this.it;
        const cR = this.cc[m8] + this.cc[m8+1] + this.cc[m8+2] + this.cc[m8+3];
        const cI = this.cc[m8+4] + this.cc[m8+5] + this.cc[m8+6] + this.cc[m8+7];
        if (this.inspike(cR, cI) && this.ch > 0) {
          this.ch -= 1;
        }
        return -1;  // Converged
      }
    }
    return 0;  // Continue iterating
  }
}
 
// Spatial bucket for O(1) lookup of nearby points in 2D
// Uses a grid with cell size = 2*bucketRadius to guarantee 4-bucket coverage
// Base class - subclasses implement precision-specific getF64Point and verifyAndGetDelta
class SpatialBucket {
  // Minimum bucket size to avoid f64 precision issues
  static MIN_BUCKET_SIZE = 1e-12;
 
  /**
   * @param {number} threadingEpsilon - L∞ distance threshold for "nearby"
   */
  constructor(threadingEpsilon) {
    this.threadingEpsilon = threadingEpsilon;
    // Clamp bucket radius to avoid f64 precision problems
    this.bucketRadius = Math.max(threadingEpsilon, SpatialBucket.MIN_BUCKET_SIZE);
    this.gridSize = 2 * this.bucketRadius;  // Grid cells are 2× radius for 4-bucket guarantee
    this.buckets = new Map();  // "bx,by" -> Set of indices
  }
 
  // Subclasses must override: return {re, im} as f64 for coarse bucketing
  getF64Point(i) { throw new Error("subclass must implement getF64Point"); }
 
  // Subclasses must override: return {deltaRe, deltaIm} if within threadingEpsilon, else null
  // Uses precision-aware subtraction to avoid catastrophic cancellation
  verifyAndGetDelta(i, j) { throw new Error("subclass must implement verifyAndGetDelta"); }
 
  getBucket(re, im) {
    const bx = Math.floor(re / this.gridSize);
    const by = Math.floor(im / this.gridSize);
    return { bx, by };
  }
 
  getKey(bx, by) {
    return `${bx},${by}`;
  }
 
  /**
   * Add point at index i to the spatial structure
   */
  add(i) {
    const pt = this.getF64Point(i);
    if (!pt) return;
    const { bx, by } = this.getBucket(pt.re, pt.im);
    const key = this.getKey(bx, by);
    if (!this.buckets.has(key)) {
      this.buckets.set(key, new Set());
    }
    this.buckets.get(key).add(i);
  }
 
  /**
   * Find all points within threadingEpsilon L∞ distance of point i,
   * remove them from the structure, and return [{index, deltaRe, deltaIm}, ...].
   * Uses precision-aware verification via verifyAndGetDelta.
   * Does NOT remove point i itself (it may not even be in the structure).
   */
  findAndRemoveNear(i) {
    const pt = this.getF64Point(i);
    if (!pt) return [];
 
    const { bx, by } = this.getBucket(pt.re, pt.im);
 
    // Determine which 4 buckets to check based on position within bucket
    // Since gridSize = 2*bucketRadius, checking 4 adjacent buckets guarantees
    // we find all points within bucketRadius distance
    const fracX = (pt.re / this.gridSize) - bx;
    const fracY = (pt.im / this.gridSize) - by;
    const dx = fracX < 0.5 ? -1 : 1;
    const dy = fracY < 0.5 ? -1 : 1;
 
    const bucketsToCheck = [
      [bx, by],
      [bx + dx, by],
      [bx, by + dy],
      [bx + dx, by + dy]
    ];
 
    const found = [];
    for (const [checkBx, checkBy] of bucketsToCheck) {
      const key = this.getKey(checkBx, checkBy);
      const bucket = this.buckets.get(key);
      if (!bucket) continue;
 
      const toRemove = [];
      for (const j of bucket) {
        if (j === i) continue;  // Don't return the query point itself
 
        // Use precision-aware verification
        const delta = this.verifyAndGetDelta(i, j);
        if (delta !== null) {
          found.push({ index: j, deltaRe: delta.deltaRe, deltaIm: delta.deltaIm });
          toRemove.push(j);
        }
      }
 
      for (const j of toRemove) {
        bucket.delete(j);
      }
      if (bucket.size === 0) {
        this.buckets.delete(key);
      }
    }
 
    return found;
  }
 
  /**
   * Remove all indices older than (less than) minIndex
   */
  removeOlderThan(minIndex) {
    for (const [key, bucket] of this.buckets) {
      for (const j of bucket) {
        if (j < minIndex) {
          bucket.delete(j);
        }
      }
      if (bucket.size === 0) {
        this.buckets.delete(key);
      }
    }
  }
}
 
/**
 * DDSpatialBucket - for quad-double precision points
 * Point format: [re_hi, re_lo, im_hi, im_lo]
 */
class DDSpatialBucket extends SpatialBucket {
  constructor(threadingEpsilon, getDDPoint) {
    super(threadingEpsilon);
    this.getDDPoint = getDDPoint;
  }
 
  getF64Point(i) {
    const p = this.getDDPoint(i);
    if (!p) return null;
    return { re: p[0] + p[1], im: p[2] + p[3] };
  }
 
  verifyAndGetDelta(i, j) {
    const pi = this.getDDPoint(i);
    const pj = this.getDDPoint(j);
    if (!pi || !pj) return null;
 
    // Proper qd subtraction to avoid catastrophic cancellation
    const deltaReQd = ddSub([pi[0], pi[1]], [pj[0], pj[1]]);
    const deltaImQd = ddSub([pi[2], pi[3]], [pj[2], pj[3]]);
 
    // Sum qd result to f64
    const deltaRe = deltaReQd[0] + deltaReQd[1];
    const deltaIm = deltaImQd[0] + deltaImQd[1];
 
    // Check L∞ distance against actual threadingEpsilon
    if (Math.max(Math.abs(deltaRe), Math.abs(deltaIm)) <= this.threadingEpsilon) {
      return { deltaRe, deltaIm };
    }
    return null;
  }
}
 
/**
 * QDSpatialBucket - for quad-double precision points
 * Point format: [re0, re1, re2, re3, im0, im1, im2, im3]
 */
class QDSpatialBucket extends SpatialBucket {
  constructor(threadingEpsilon, getQDPoint) {
    super(threadingEpsilon);
    this.getQDPoint = getQDPoint;
  }
 
  getF64Point(i) {
    const p = this.getQDPoint(i);
    if (!p) return null;
    return {
      re: p[0] + p[1] + p[2] + p[3],
      im: p[4] + p[5] + p[6] + p[7]
    };
  }
 
  verifyAndGetDelta(i, j) {
    const pi = this.getQDPoint(i);
    const pj = this.getQDPoint(j);
    if (!pi || !pj) return null;
 
    // Proper QD subtraction to avoid catastrophic cancellation
    const deltaReQD = toQDSub(
      [pi[0], pi[1], pi[2], pi[3]],
      [pj[0], pj[1], pj[2], pj[3]]
    );
    const deltaImQD = toQDSub(
      [pi[4], pi[5], pi[6], pi[7]],
      [pj[4], pj[5], pj[6], pj[7]]
    );
 
    // Sum QD result to f64
    const deltaRe = qdToNumber(deltaReQD);
    const deltaIm = qdToNumber(deltaImQD);
 
    // Check L∞ distance against actual threadingEpsilon
    if (Math.max(Math.abs(deltaRe), Math.abs(deltaIm)) <= this.threadingEpsilon) {
      return { deltaRe, deltaIm };
    }
    return null;
  }
}
 
// Reference Orbit Threading - enables robust cycle detection despite rebasing
class ReferenceOrbitThreading {
  /**
   * @param {SpatialBucket} spatialBucket - A precision-aware spatial bucket
   *   (DDSpatialBucket or QDSpatialBucket)
   */
  constructor(spatialBucket) {
    const maxCycleLength = 1e5;
    // Window size limits bucket growth
    this.windowSize = Math.min(1024, Math.floor(maxCycleLength));
    // Threading links: {next: index, deltaRe: f32, deltaIm: f32}
    this.threads = [];
    // Spatial index for finding nearby points (precision-aware)
    this.spatialBucket = spatialBucket;
  }
 
  /**
   * Add a new orbit point and create threading links.
   * All nearby past points are threaded to point at this new point.
   * The spatial bucket handles precision-aware distance checking and delta computation.
   */
  addPoint(currentIndex) {
    // Find and remove all nearby past points from the bucket
    // Returns [{index, deltaRe, deltaIm}, ...] with precision-aware deltas
    const nearbyPast = this.spatialBucket.findAndRemoveNear(currentIndex);
 
    // Add placeholder for this point's thread
    this.threads.push({next: -1, deltaRe: 0, deltaIm: 0});
 
    // Thread all nearby past points to this new point
    // Note: deltaRe/deltaIm are (current - past), but we want (past -> current) delta
    // So we negate the deltas returned by the bucket
    for (const match of nearbyPast) {
      this.threads[match.index] = {
        next: currentIndex,
        deltaRe: Math.fround(-match.deltaRe),  // Negate: bucket returns (query - candidate)
        deltaIm: Math.fround(-match.deltaIm)
      };
    }
 
    // Add this point to the bucket for future lookups
    this.spatialBucket.add(currentIndex);
 
    // Cleanup old entries outside the window
    if (currentIndex >= this.windowSize) {
      this.spatialBucket.removeOlderThan(currentIndex - this.windowSize);
    }
  }
 
  /**
   * Get thread info for iteration i
   */
  getThread(i) {
    return this.threads[i] || null;
  }
 
  /**
   * Manually set a thread (used for loop configuration)
   */
  setThread(i, next, deltaRe, deltaIm) {
    this.threads[i] = {
      next,
      deltaRe: Math.fround(deltaRe),
      deltaIm: Math.fround(deltaIm)
    };
  }
 
  get length() {
    return this.threads.length;
  }
}
 
// Single reference orbit perturbation method.
// Based on Zhuoran Li's 2021 approach:
// https://mathr.co.uk/blog/2021-05-14_stretching_deep_zoom.html
// Rebasing implementation follows Imagina: https://github.com/ImaginaFractal/Imagina
 
// Mixin that adds DD-precision reference orbit methods to any board class.
// Used by both DDZhuoranBoard (CPU) and GpuZhuoranBoard (GPU) to share
// the reference orbit computation logic.
const DDReferenceOrbitMixin = (Base) => class extends Base {
  // Initialize DD reference orbit state. Call from constructor after super().
  initDDReferenceOrbit(refC) {
    // Reference point in DD precision [r_hi, r_lo, i_hi, i_lo]
    this.refC = refC;
 
    // Reference orbit array - each entry is [r_hi, r_lo, i_hi, i_lo]
    this.refOrbit = [];
    this.refOrbit.push([0, 0, 0, 0]);      // Iteration 0: z = 0
    this.refOrbit.push(this.refC.slice()); // Iteration 1: z = c
 
    // Reference orbit state
    this.refOrbitEscaped = false;
    this.refIterations = 1;
    this.maxRefIterations = 10000;
 
    // Working array for DD precision operations
    this.tt = new Array(16);
 
    // Build threading structure
    this.rebuildDDThreading();
  }
 
  // Rebuild threading structure from reference orbit (for serialization restore)
  rebuildDDThreading() {
    const threadingEpsilon = 10000 * this.epsilon;
    const getDDPoint = (i) => this.refOrbit[i] || null;
    const spatialBucket = new DDSpatialBucket(threadingEpsilon, getDDPoint);
    this.threading = new ReferenceOrbitThreading(spatialBucket);
    // Add all points from reference orbit
    for (let i = 0; i <= this.refIterations; i++) {
      this.threading.addPoint(i);
    }
  }
 
  // DD accessor methods
  getRefReal(ref) { return ref[0] + ref[1]; }
  getRefImag(ref) { return ref[2] + ref[3]; }
  getRefOrbit(iter) { return this.refOrbit[iter]; }
  getRefOrbitLength() { return this.refOrbit.length; }
  getRefCReal() { return this.refC[0] + this.refC[1]; }
  getRefCImag() { return this.refC[2] + this.refC[3]; }
 
  // Compute z = ref + dz in native DDc format (4 elements)
  refDzNative(ref, dzr, dzi) {
    // ref is DD: [r_hi, r_lo, i_hi, i_lo], returns DDc with proper DD addition
    // Optimized to avoid allocations
    const out = new Array(4);
    arDdAdd(out, 0, ref[0], ref[1], dzr, 0);
    arDdAdd(out, 2, ref[2], ref[3], dzi, 0);
    return out;
  }
 
  // Extend reference orbit by one iteration in DD precision
  extendReferenceOrbit() {
    const lastIndex = this.refIterations;
    const last = this.refOrbit[lastIndex];
    const tt = this.tt;
 
    const r1 = last[0];
    const r2 = last[1];
    const j1 = last[2];
    const j2 = last[3];
 
    // Check for escape
    arDdSquare(tt, 0, r1, r2);                    // rsq = r**2
    arDdSquare(tt, 2, j1, j2);                    // jsq = j**2
    arDdAdd(tt, 4, tt[0], tt[1], tt[2], tt[3]);   // d = rsq + jsq
 
    if (tt[4] > 1e10) {
      this.refOrbitEscaped = true;
      return;
    }
 
    // Compute z^n for general exponent
    arDdMul(tt, 6, 2 * r1, 2 * r2, j1, j2);       // ja = 2*r*j
    arDdAdd(tt, 8, tt[0], tt[1], -tt[2], -tt[3]); // ra = rsq - jsq
 
    for (let ord = 2; ord < this.config.exponent; ord++) {
      arDdMul(tt, 0, j1, j2, tt[6], tt[7]);         // j * ja
      arDdMul(tt, 2, r1, r2, tt[8], tt[9]);         // r * ra
      arDdAdd(tt, 4, -tt[0], -tt[1], tt[2], tt[3]); // rt = r*ra - j*ja
      arDdMul(tt, 0, r1, r2, tt[6], tt[7]);         // r * ja
      arDdMul(tt, 2, j1, j2, tt[8], tt[9]);         // j * ra
      arDdAdd(tt, 6, tt[0], tt[1], tt[2], tt[3]);   // ja = r*ja + j*ra
      arDdSet(tt, 8, tt[4], tt[5]);                // ra = rt
    }
 
    // Add c to get next z
    const newZ = [0, 0, 0, 0];
    arDdAdd(newZ, 0, tt[8], tt[9], this.refC[0], this.refC[1]);      // real part
    arDdAdd(newZ, 2, tt[6], tt[7], this.refC[2], this.refC[3]);      // imag part
 
    this.refOrbit.push(newZ);
    this.refIterations++;
 
    // Build thread-following map
    this.threading.addPoint(this.refIterations);
 
    // Grow array if needed
    if (this.refIterations >= this.maxRefIterations) {
      this.maxRefIterations *= 2;
    }
  }
};
 
// Mixin that adds QD-precision reference orbit methods to any board class.
// Used by both QDZhuoranBoard (CPU) and GpuAdaptiveBoard (GPU) to share
// the reference orbit computation logic.
const QDReferenceOrbitMixin = (Base) => class extends Base {
  // Initialize QD reference orbit state. Call from constructor after super().
  initQDReferenceOrbit(refC_qd) {
    // Reference point in QD precision [re0, re1, re2, re3, im0, im1, im2, im3]
    this.refC_qd = refC_qd;
 
    // QD reference orbit array - each entry is [re0, re1, re2, re3, im0, im1, im2, im3]
    this.qdRefOrbit = [
      [0, 0, 0, 0, 0, 0, 0, 0],  // Iteration 0: z = 0
      [...refC_qd]               // Iteration 1: z = c
    ];
 
    // Reference orbit state
    this.refOrbitEscaped = false;
    this.refIterations = 1;
    this.maxRefIterations = 10000;
 
    // Working array for QD precision operations
    this.tt = new Array(32);
 
    // Build threading structure
    this.rebuildQDThreading();
  }
 
  // Rebuild threading structure from reference orbit (for serialization restore)
  rebuildQDThreading() {
    const threadingEpsilon = 10000 * this.epsilon;
    const getQDPoint = (i) => this.qdRefOrbit[i] || null;
    const spatialBucket = new QDSpatialBucket(threadingEpsilon, getQDPoint);
    this.threading = new ReferenceOrbitThreading(spatialBucket);
    // Add all points from reference orbit
    for (let i = 0; i <= this.refIterations; i++) {
      this.threading.addPoint(i);
    }
  }
 
  // QD accessor methods
  getRefReal(ref) { return ref[0] + ref[1] + ref[2] + ref[3]; }
  getRefImag(ref) { return ref[4] + ref[5] + ref[6] + ref[7]; }
  getRefOrbit(iter) { return this.qdRefOrbit[iter]; }
  getRefOrbitLength() { return this.qdRefOrbit.length; }
  getRefCReal() { return this.refC_qd[0] + this.refC_qd[1] + this.refC_qd[2] + this.refC_qd[3]; }
  getRefCImag() { return this.refC_qd[4] + this.refC_qd[5] + this.refC_qd[6] + this.refC_qd[7]; }
 
  // Compute z = ref + dz in native QDc format (8 elements)
  refDzNative(ref, dzr, dzi) {
    // ref is QD: [r0,r1,r2,r3, i0,i1,i2,i3], returns QDc
    // Optimized to avoid allocations
    const out = new Array(8);
    arQdAdd(out, 0, ref[0], ref[1], ref[2], ref[3], dzr, 0, 0, 0);
    arQdAdd(out, 4, ref[4], ref[5], ref[6], ref[7], dzi, 0, 0, 0);
    return out;
  }
 
  // Extend reference orbit by one iteration in QD precision
  extendReferenceOrbit() {
    const last = this.qdRefOrbit[this.refIterations];
    const rr = [last[0], last[1], last[2], last[3]];
    const ri = [last[4], last[5], last[6], last[7]];
    const tt = this.tt;
 
    // Check for escape using sum of QD components
    const rSum = rr[0] + rr[1] + rr[2] + rr[3];
    const iSum = ri[0] + ri[1] + ri[2] + ri[3];
    const mag = rSum * rSum + iSum * iSum;
    if (mag > 1e10) {
      this.refOrbitEscaped = true;
      return;
    }
 
    // Compute z^n for general exponent
    // z^2 = (zr + zi*i)^2 = zr^2 - zi^2 + 2*zr*zi*i
    arQdSquare(tt, 0, rr[0], rr[1], rr[2], rr[3]);   // rsq = r^2
    arQdSquare(tt, 4, ri[0], ri[1], ri[2], ri[3]);   // jsq = j^2
    arQdMul(tt, 8, 2*rr[0], 2*rr[1], 2*rr[2], 2*rr[3],
      ri[0], ri[1], ri[2], ri[3]);  // ja = 2*r*j
    arQdAdd(tt, 16, tt[0], tt[1], tt[2], tt[3],
      -tt[4], -tt[5], -tt[6], -tt[7]);     // ra = rsq - jsq
 
    for (let ord = 2; ord < this.config.exponent; ord++) {
      arQdMul(tt, 0, ri[0], ri[1], ri[2], ri[3],
        tt[8], tt[9], tt[10], tt[11]);         // j * ja
      arQdMul(tt, 4, rr[0], rr[1], rr[2], rr[3],
        tt[16], tt[17], tt[18], tt[19]);       // r * ra
      arQdAdd(tt, 12, -tt[0], -tt[1], -tt[2], -tt[3],
        tt[4], tt[5], tt[6], tt[7]);      // rt = r*ra - j*ja
      arQdMul(tt, 0, rr[0], rr[1], rr[2], rr[3],
        tt[8], tt[9], tt[10], tt[11]);         // r * ja
      arQdMul(tt, 4, ri[0], ri[1], ri[2], ri[3],
        tt[16], tt[17], tt[18], tt[19]);       // j * ra
      arQdAdd(tt, 8, tt[0], tt[1], tt[2], tt[3],
        tt[4], tt[5], tt[6], tt[7]);           // ja = r*ja + j*ra
      arQdSet(tt, 16, tt[12], tt[13], tt[14], tt[15]);  // ra = rt
    }
 
    // Add c to get next z
    const nzrQD = new Array(4);
    const nziQD = new Array(4);
    arQdAdd(nzrQD, 0, tt[16], tt[17], tt[18], tt[19],
      this.refC_qd[0], this.refC_qd[1], this.refC_qd[2], this.refC_qd[3]);
    arQdAdd(nziQD, 0, tt[8], tt[9], tt[10], tt[11],
      this.refC_qd[4], this.refC_qd[5], this.refC_qd[6], this.refC_qd[7]);
 
    this.qdRefOrbit.push([nzrQD[0], nzrQD[1], nzrQD[2], nzrQD[3],
                          nziQD[0], nziQD[1], nziQD[2], nziQD[3]]);
    this.refIterations++;
 
    // Build thread-following map
    this.threading.addPoint(this.refIterations);
 
    // Grow array if needed
    if (this.refIterations >= this.maxRefIterations) {
      this.maxRefIterations *= 2;
    }
  }
};
 
// Base class for CPU-based Zhuoran perturbation boards (DD and QD precision)
// Subclasses implement precision-specific reference orbit computation
class CpuZhuoranBaseBoard extends Board {
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
 
    // Per-pixel thread tracking for convergence detection
    this.currentThreadIter = new Array(this.config.dimsArea).fill(0);
    this.threadDeltaRe = new Array(this.config.dimsArea).fill(0);
    this.threadDeltaIm = new Array(this.config.dimsArea).fill(0);
 
    // Reference orbit management
    this.maxRefIterations = 10000;  // Will grow dynamically
    this.refOrbitEscaped = false;
    this.refIterations = 1;  // Start with iterations 0 and 1
 
    // Per-pixel data (double precision) - shared by all subclasses
    this.dc = [];  // Delta c from reference point [real, imag] pairs
    this.dz = [];  // Current perturbation delta [real, imag] pairs
    this.refIter = [];  // Which iteration of reference each pixel is following
    this.pixelIndexes = [];  // Active pixel indices
    this.maxRefIter = 1;  // Track maximum refIter to avoid scanning all pixels
 
    this.effort = 100;  // Default for CPU Zhuoran boards, overridden by subclasses
  }
 
  // Abstract methods - subclasses must implement these
 
  // Get the double value of the real part from a ref orbit entry
  getRefReal(refEntry) { throw new Error('Abstract method'); }
 
  // Get the double value of the imaginary part from a ref orbit entry
  getRefImag(refEntry) { throw new Error('Abstract method'); }
 
  // Get the reference orbit entry at the given iteration
  getRefOrbit(iter) { throw new Error('Abstract method'); }
 
  // Get the current length of the reference orbit
  getRefOrbitLength() { throw new Error('Abstract method'); }
 
  // Get reference C real part as double
  getRefCReal() { throw new Error('Abstract method'); }
 
  // Get reference C imaginary part as double
  getRefCImag() { throw new Error('Abstract method'); }
 
  // Extend reference orbit by one iteration (precision-specific)
  extendReferenceOrbit() { throw new Error('Abstract method'); }
 
  // Initialize pixels (shared by DD and QD subclasses)
  initPixels() {
    // Compute delta c directly without precision loss.
    // At deep zoom, computing cr = center + offset loses precision.
    // Since the reference point IS the view center, dc is just the pixel offset from center.
    const sizeScalar = this.size;
    const dimsWidth = this.config.dimsWidth;
    const dimsHeight = this.config.dimsHeight;
    const aspectRatio = this.config.aspectRatio;
 
    // Convert reference point to double for spike detection
    // Subclasses implement these accessors via mixins
    const refRe = this.getRefCReal();
    const refIm = this.getRefCImag();
 
    for (let y = 0; y < dimsHeight; y++) {
      const yFrac = (0.5 - y / dimsHeight);
      const dci = yFrac * (sizeScalar / aspectRatio);
 
      for (let x = 0; x < dimsWidth; x++) {
        const xFrac = (x / dimsWidth - 0.5);
        const dcr = xFrac * sizeScalar;
 
        const index = y * dimsWidth + x;
        this.dc[index * 2] = dcr;
        this.dc[index * 2 + 1] = dci;
        // Start with z = c, so dz = dc
        this.dz[index * 2] = dcr;
        this.dz[index * 2 + 1] = dci;
        // Start at iteration 1 (z = c)
        this.refIter[index] = 1;
 
        // Skip precomputed pixels - they'll be flushed at their iteration
        if (!this.precomputed || !this.precomputed.isPrecomputed(index)) {
          this.pixelIndexes.push(index);
        }
 
        // Count spike pixels
        const cr = refRe + dcr;
        const ci = refIm + dci;
        if (this.inspike(cr, ci)) {
          this.ch += 1;
        }
      }
    }
  }
 
  // Shared iterate() method - works for both DD and QD
  iterate(targetIters = 1) {
    // Step 1: Extend reference orbit for entire batch upfront (not ahead)
    const targetRefIterations = Math.max(this.it + targetIters, this.maxRefIter + targetIters);
    while (!this.refOrbitEscaped && this.refIterations < targetRefIterations) {
      this.extendReferenceOrbit();
    }
 
    // Batch multiple iterations internally
    for (let batch = 0; batch < targetIters && this.un > 0; batch++) {
      let changes = null;
      // Step 2: Iterate all active pixels using perturbation
      const newPixelIndexes = [];
      for (const index of this.pixelIndexes) {
        if (this.nn[index]) continue;  // Skip finished pixels
        const result = this.iteratePixel(index);
        if (result !== 0) {
          if (!changes) {
            changes = { iter: this.it, nn: [], vv: [] };
          }
          if (result > 0) {
            // Diverged
            changes.nn.push(index);
            this.nn[index] = this.it;
            this.di += 1;
            this.un -= 1;
          } else {
            // Converged
            const index2 = index * 2;
            const nextRefIter = this.refIter[index] + 1;
            const ref = this.getRefOrbit(Math.min(nextRefIter, this.getRefOrbitLength() - 1));
            const dzr = this.dz[index2];
            const dzi = this.dz[index2 + 1];
            changes.vv.push({
              index: index,
              z: this.refDzNative(ref, dzr, dzi),  // Native format (DDc or QDc)
              p: this.pp[index]
            });
            this.nn[index] = -this.it;
            this.un -= 1;
            if (this.inspike(
              this.dc[index2] + this.getRefCReal(),
              this.dc[index2 + 1] + this.getRefCImag()
            ) && this.ch > 0) {
              this.ch -= 1;
            }
          }
        } else {
          newPixelIndexes.push(index);
        }
      }
      this.pixelIndexes = newPixelIndexes;
      // Compact if needed
      if (this.pixelIndexes.length > this.un * 1.25) {
        this.pixelIndexes = this.pixelIndexes.filter(i => !this.nn[i]);
      }
 
      // Flush precomputed points at this iteration
      if (this.precomputed) {
        this.precomputed.flushAtIteration(this.it, this);
      }
 
      this.it++;
      this.queueChanges(changes);
    }
  }
 
  // Shared iteratePixel() method - works for both DD and QD
  iteratePixel(index) {
    const index2 = index * 2;
    let refIter = this.refIter[index];
 
    // Check if current z has escaped BEFORE doing iteration
    if (refIter < this.getRefOrbitLength()) {
      const ref = this.getRefOrbit(refIter);
      const refR = this.getRefReal(ref);
      const refI = this.getRefImag(ref);
      const dr = this.dz[index2];
      const di = this.dz[index2 + 1];
      const currentZR = refR + dr;
      const currentZI = refI + di;
      const currentMag2 = currentZR * currentZR + currentZI * currentZI;
      if (currentMag2 > 4) {
        return 1;  // Diverged
      }
    }
 
    // Ensure reference orbit exists
    if (refIter >= this.getRefOrbitLength()) {
      if (this.refOrbitEscaped) {
        // Rebase to beginning
        const lastRef = this.getRefOrbit(this.getRefOrbitLength() - 1);
        const lastRefR = this.getRefReal(lastRef);
        const lastRefI = this.getRefImag(lastRef);
        const dr = this.dz[index2];
        const di = this.dz[index2 + 1];
        this.dz[index2] = lastRefR + dr;
        this.dz[index2 + 1] = lastRefI + di;
        this.refIter[index] = 0;
        refIter = 0;
      } else {
        return 1;  // Mark as diverged if unexpected
      }
    }
 
    // Check if we need to rebase (Zhuoran's key innovation)
    if (this.shouldRebase(index)) {
      const ref = this.getRefOrbit(refIter);
      const refR = this.getRefReal(ref);
      const refI = this.getRefImag(ref);
      const dr = this.dz[index2];
      const di = this.dz[index2 + 1];
      this.dz[index2] = refR + dr;
      this.dz[index2 + 1] = refI + di;
      this.refIter[index] = 0;
      refIter = 0;
    }
 
    // Get reference orbit value
    const ref = this.getRefOrbit(refIter);
    if (!ref) {
      return 0;
    }
    const refR = this.getRefReal(ref);
    const refI = this.getRefImag(ref);
 
    // Perturbation iteration using binomial expansion (Horner's method)
    const dr = this.dz[index2];
    const di = this.dz[index2 + 1];
 
    const exponent = this.config.exponent || 2;
 
    // Build binomial powers: coeff * z_ref^power for each term
    let zPowR = refR;
    let zPowI = refI;
    let coeff = exponent;
 
    // Start Horner's method with innermost term (just dz)
    let resultR = dr;
    let resultI = di;
 
    // Horner's method: accumulate terms from highest to lowest power of z_ref
    for (let k = 1; k < exponent; k++) {
      // Add coeff * z_ref^power term
      const termR = coeff * zPowR;
      const termI = coeff * zPowI;
      resultR = resultR + termR;
      resultI = resultI + termI;
 
      // Multiply by dz (complex multiplication)
      const tempR = resultR * dr - resultI * di;
      resultI = resultR * di + resultI * dr;
      resultR = tempR;
 
      // Update z_ref power: z_pow = z_pow * z_ref
      const newZPowR = zPowR * refR - zPowI * refI;
      zPowI = zPowR * refI + zPowI * refR;
      zPowR = newZPowR;
 
      // Update coefficient: coeff *= (n-k) / (k+1)
      coeff *= (exponent - k) / (k + 1);
    }
 
    // Add perturbation in c
    const newDr = resultR + this.dc[index2];
    const newDi = resultI + this.dc[index2 + 1];
    this.dz[index2] = newDr;
    this.dz[index2 + 1] = newDi;
 
    // CONVERGENCE DETECTION: fibonacciPeriod returns 1 at Fibonacci checkpoints
    const justUpdatedCheckpoint = (fibonacciPeriod(this.it) == 1);
    if (justUpdatedCheckpoint) {
      this.bb[index2] = dr;
      this.bb[index2 + 1] = di;
      this.pp[index] = 0;
      this.currentThreadIter[index] = refIter;
      this.threadDeltaRe[index] = 0;
      this.threadDeltaIm[index] = 0;
    } else {
      // Incrementally advance threads when thread.next == refIter
      let currentThread = this.currentThreadIter[index];
      const thread = this.threading.getThread(currentThread);
      if (thread.next == refIter) {
        this.threadDeltaRe[index] += thread.deltaRe;
        this.threadDeltaIm[index] += thread.deltaIm;
        currentThread = thread.next;
        this.currentThreadIter[index] = currentThread;
      }
 
      // Check convergence when currentThreadIter matches refIter
      if (this.currentThreadIter[index] === refIter) {
        const checkpoint_dr = this.bb[index2];
        const checkpoint_di = this.bb[index2 + 1];
        const dzDiffR = dr - checkpoint_dr;
        const dzDiffI = di - checkpoint_di;
        const totalDiffR = this.threadDeltaRe[index] + dzDiffR;
        const totalDiffI = this.threadDeltaIm[index] + dzDiffI;
        const db = Math.max(Math.abs(totalDiffR), Math.abs(totalDiffI));
 
        const epsilon = this.epsilon;
        const epsilon2 = this.epsilon2;
        if (db <= epsilon2) {
          if (!this.pp[index]) {
            this.pp[index] = this.it - 1;
          }
          if (db <= epsilon) {
            return -1;  // Converged via threading!
          }
        }
      }
    }
 
    // Update reference iteration counter
    this.refIter[index]++;
    if (this.refIter[index] > this.maxRefIter) {
      this.maxRefIter = this.refIter[index];
    }
    return 0;  // Continue iterating
  }
 
  // Shared shouldRebase() method - works for both DD and QD
  shouldRebase(index) {
    const index2 = index * 2;
    const dr = this.dz[index2];
    const di = this.dz[index2 + 1];
    const refIter = this.refIter[index];
 
    if (refIter === 0) return false;
    if (refIter >= this.getRefOrbitLength()) return false;
 
    const ref = this.getRefOrbit(refIter);
    if (!ref) return false;
 
    const refR = this.getRefReal(ref);
    const refI = this.getRefImag(ref);
 
    const dzNorm = Math.max(Math.abs(dr), Math.abs(di));
    const totalR = refR + dr;
    const totalI = refI + di;
    const totalNorm = Math.max(Math.abs(totalR), Math.abs(totalI));
 
    return totalNorm < dzNorm * 2.0;
  }
 
  async serialize() {
    // Build sparse nn array for completed pixels (non-zero nn values)
    const completedIndexes = [];
    const completedNn = [];
    for (let i = 0; i < this.nn.length; i++) {
      if (this.nn[i] !== 0) {
        completedIndexes.push(i);
        completedNn.push(this.nn[i]);
      }
    }
    return {
      ...(await super.serialize()),
      // Per-pixel state (sparse - only for active pixels)
      pixelIndexes: this.pixelIndexes,
      dc: this.pixelIndexes.flatMap(i => [this.dc[i*2], this.dc[i*2+1]]),
      dz: this.pixelIndexes.flatMap(i => [this.dz[i*2], this.dz[i*2+1]]),
      refIter: this.pixelIndexes.map(i => this.refIter[i]),
      pp: this.pixelIndexes.map(i => this.pp[i]),
      // Convergence detection state
      currentThreadIter: this.pixelIndexes.map(i => this.currentThreadIter[i]),
      threadDeltaRe: this.pixelIndexes.map(i => this.threadDeltaRe[i]),
      threadDeltaIm: this.pixelIndexes.map(i => this.threadDeltaIm[i]),
      // Reference orbit state
      refOrbitEscaped: this.refOrbitEscaped,
      refIterations: this.refIterations,
      maxRefIter: this.maxRefIter,
      // Completed pixels
      completedIndexes,
      completedNn,
    };
  }
 
  static restoreBaseState(board, serialized) {
    // Restore nn values for completed pixels
    board.nn = new Array(serialized.config.dimsArea).fill(0);
    if (serialized.completedIndexes) {
      for (let i = 0; i < serialized.completedIndexes.length; i++) {
        board.nn[serialized.completedIndexes[i]] = serialized.completedNn[i];
      }
    }
 
    // Restore per-pixel state from sparse serialized data
    board.dc = new Array(serialized.config.dimsArea * 2).fill(0);
    board.dz = new Array(serialized.config.dimsArea * 2).fill(0);
    board.refIter = new Array(serialized.config.dimsArea).fill(0);
    board.pp = new Array(serialized.config.dimsArea).fill(0);
    board.currentThreadIter = new Array(serialized.config.dimsArea).fill(0);
    board.threadDeltaRe = new Array(serialized.config.dimsArea).fill(0);
    board.threadDeltaIm = new Array(serialized.config.dimsArea).fill(0);
 
    const pixelIndexes = serialized.pixelIndexes || [];
    for (let i = 0; i < pixelIndexes.length; i++) {
      const index = pixelIndexes[i];
      board.dc[index * 2] = serialized.dc[i * 2];
      board.dc[index * 2 + 1] = serialized.dc[i * 2 + 1];
      board.dz[index * 2] = serialized.dz[i * 2];
      board.dz[index * 2 + 1] = serialized.dz[i * 2 + 1];
      board.refIter[index] = serialized.refIter[i];
      board.pp[index] = serialized.pp[i];
      board.currentThreadIter[index] = serialized.currentThreadIter[i];
      board.threadDeltaRe[index] = serialized.threadDeltaRe[i];
      board.threadDeltaIm[index] = serialized.threadDeltaIm[i];
    }
    board.pixelIndexes = pixelIndexes.slice();
 
    // Restore reference orbit state
    board.refOrbitEscaped = serialized.refOrbitEscaped || false;
    board.refIterations = serialized.refIterations || 1;
    board.maxRefIter = serialized.maxRefIter || 1;
 
    // Restore scalar values
    board.it = serialized.it;
    board.un = serialized.un;
    board.di = serialized.di;
    board.ch = serialized.ch || 0;
  }
}
 
// DD-precision implementation of CpuZhuoranBaseBoard
// Uses DDReferenceOrbitMixin for reference orbit computation
class DDZhuoranBoard extends DDReferenceOrbitMixin(CpuZhuoranBaseBoard) {
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
    this.effort = 450;  // Benchmarked: 19.6 ns/px-iter, 4.5× slower than CPU
 
    // Initialize DD reference orbit (refC, refOrbit, threading, etc.)
    const refRe = qdToDD(this.re);
    const refIm = qdToDD(this.im);
    this.initDDReferenceOrbit([refRe[0], refRe[1], refIm[0], refIm[1]]);
 
    this.initPixels();
  }
 
  static fromSerialized(serialized) {
    const board = new DDZhuoranBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    // Restore base Zhuoran state (nn, dc, dz, refIter, etc.)
    CpuZhuoranBaseBoard.restoreBaseState(board, serialized);
 
    // Restore DD reference orbit
    board.refOrbit = serialized.refOrbit || [];
    board.refC = serialized.refC || [0, 0, 0, 0];
 
    // Rebuild threading structure from restored reference orbit
    board.rebuildDDThreading();
 
    return board;
  }
 
  async serialize() {
    return {
      ...(await super.serialize()),
      refOrbit: this.refOrbit,
      refC: this.refC,
    };
  }
 
  getCurrentRefZ(index) {
    const refIter = this.refIter[index];
    if (refIter <= this.refIterations && this.refOrbit[refIter]) {
      return this.refOrbit[refIter];
    }
    return [0, 0, 0, 0];
  }
}
 
// QD-precision implementation of CpuZhuoranBaseBoard
// Provides higher precision (~212 bits) reference for very deep zooms
// Uses QDReferenceOrbitMixin for reference orbit computation
class QDZhuoranBoard extends QDReferenceOrbitMixin(CpuZhuoranBaseBoard) {
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
    this.effort = 480;  // Benchmarked: 21.0 ns/px-iter, 4.8× slower than CPU
 
    // Initialize QD reference orbit (refC_qd, qdRefOrbit, threading, etc.)
    const refReQD = this.re.slice();
    const refImQD = this.im.slice();
    this.initQDReferenceOrbit([...refReQD, ...refImQD]);
 
    this.initPixels();
  }
 
  async serialize() {
    return {
      ...(await super.serialize()),
      refC_qd: this.refC_qd,
      qdRefOrbit: this.qdRefOrbit,
    };
  }
 
  static fromSerialized(serialized) {
    const board = new QDZhuoranBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    // Restore base Zhuoran state (nn, dc, dz, refIter, etc.)
    CpuZhuoranBaseBoard.restoreBaseState(board, serialized);
 
    // Restore QD reference orbit
    board.refC_qd = serialized.refC_qd || new Array(8).fill(0);
    board.qdRefOrbit = serialized.qdRefOrbit || [];
 
    // Rebuild threading structure from restored reference orbit
    board.rebuildQDThreading();
 
    return board;
  }
}
 
// WebGPU-accelerated Mandelbrot computation using single-precision float32
// GPU computes all pixels in parallel using standard Mandelbrot iteration
// Base class for WebGPU-accelerated boards
// Provides shared GPU infrastructure for different computation strategies
class GpuBaseBoard extends Board {
  static GPU_DEFAULT_MAX_BUFFER = 200 * 1024 * 1024;  // 200MB
 
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
 
    // Note: size, re, im are available via inherited getters from Board (computed from sizesQD)
 
    // WebGPU state (shared by all GPU board implementations)
    this.device = null;
    this.pipeline = null;
    this.buffers = {};
    this.isGPUReady = false;
    this.gpuInitPromise = null;
    this.isComputing = false;
    this.computePromise = null;  // Track current async computation
    this.lastReportedIters = null;
    this.cpuStatus = null;
    this.readPixelBufferPromise = null;  // Lock for readPixelBuffer
    this.effort = 20;  // Default for GPU boards, overridden by subclasses
    this.minBatchIters = 17;  // GPU boards need minimum iterations per batch to amortize overhead
    this.maxBatchIters = 134567;  // Cap to avoid very long batches with few pixels
 
    // Initialize batch tracking state (will be fully setup in initResultsReadback)
    // This ensures batchesToReadback is defined for precomputed points processed before GPU init.
    // When empty, queueChanges() uses the fallback path that adds directly to changeList.
    this.batchesToReadback = [];
    this.batchResultsRead = [];
    this.previousBatchEndIter = 1;  // First batch starts at iter=1
    this.lastFlushedPrecomputedIter = 0;
  }
 
  checkSpike(size, re, im) {
    // Count chaotic pixels in spike region and track which pixels are in spike
    const dimsWidth = this.config.dimsWidth;
    const dimsHeight = this.config.dimsHeight;
    const size_double = Array.isArray(size) ? size.reduce((a, b) => a + (b || 0), 0) : size;
    const re_double = Array.isArray(re) ? (re[0] + re[1]) : re;
    const im_double = Array.isArray(im) ? (im[0] + im[1]) : im;
 
    // Only allocate inSpike array if we find spike pixels (common case: none)
    this.inSpike = null;
 
    for (let y = 0; y < dimsHeight; y++) {
      const yFrac = (0.5 - y / dimsHeight);
      const ci = im_double + yFrac * (size_double / this.config.aspectRatio);
 
      for (let x = 0; x < dimsWidth; x++) {
        const index = y * dimsWidth + x;
        const xFrac = (x / dimsWidth - 0.5);
        const cr = re_double + xFrac * size_double;
 
        if (this.inspike(cr, ci)) {
          // Lazily allocate array only when we find the first spike pixel
          if (!this.inSpike) {
            this.inSpike = new Uint8Array(this.config.dimsArea);
          }
          this.ch += 1;
          this.inSpike[index] = 1;
        }
      }
    }
  }
 
  async initGPU() {
    try {
      const t0 = performance.now();
      // Check WebGPU availability
      if (!navigator.gpu) {
        console.warn('WebGPU not supported');
        return false;
      }
 
      // Request adapter (note: adapters are consumed after creating a device, so can't cache)
      const adapter = await navigator.gpu.requestAdapter();
      if (!adapter) {
        console.warn('No WebGPU adapter found');
        return false;
      }
      const t1 = performance.now();
 
      // Request device with higher buffer limits if supported
      const requiredLimits = {};
      if (adapter.limits.maxStorageBufferBindingSize > 134217728) {
        // Request higher limit if adapter supports it (default is 128MB)
        requiredLimits.maxStorageBufferBindingSize = adapter.limits.maxStorageBufferBindingSize;
      }
      if (adapter.limits.maxBufferSize > 134217728) {
        requiredLimits.maxBufferSize = adapter.limits.maxBufferSize;
      }
 
      this.device = await adapter.requestDevice({
        requiredLimits: Object.keys(requiredLimits).length > 0 ? requiredLimits : undefined
      });
      if (!this.device) {
        console.warn('Failed to get WebGPU device');
        return false;
      }
      const t2 = performance.now();
 
      // Subclass-specific initialization
      await this.createComputePipeline();
      const t3 = performance.now();
      await this.createBuffers();
      const t4 = performance.now();
      this.createBindGroup();
      const t5 = performance.now();
 
      if (hasDebugFlag(this.config, 't')) {
        console.log(`[gpu-init] adapter=${(t1-t0).toFixed(0)}ms device=${(t2-t1).toFixed(0)}ms pipeline=${(t3-t2).toFixed(0)}ms buffers=${(t4-t3).toFixed(0)}ms bindgroup=${(t5-t4).toFixed(0)}ms total=${(t5-t0).toFixed(0)}ms`);
      }
 
      this.isGPUReady = true;
      return true;
 
    } catch (error) {
      console.error(`Board ${this.id}: WebGPU initialization failed:`, error.message || error);
      // Check if this is a buffer size error
      if (error.message && error.message.includes('exceeds WebGPU safe limit')) {
        console.warn(
          `Board ${this.id}: Dimensions too large for GPU ` +
          `(${this.config.dimsWidth}x${this.config.dimsHeight}). ` +
          `This board will NOT compute any pixels!`);
      }
      return false;
    }
  }
 
  async ensureGPUReady() {
    if (this.gpuInitPromise) {
      await this.gpuInitPromise;
      this.gpuInitPromise = null;
    }
    return this.isGPUReady;
  }
 
  async iterate(targetIters = null) {
    if (!this.isGPUReady) {
      return;
    }
    // Block if already computing (prevents scheduler spin on GPU boards)
    if (this.computePromise) {
      await this.computePromise;
      return;
    }
    this.computePromise = this.compute(targetIters);
    try {
      await this.computePromise;
    } finally {
      this.computePromise = null;
    }
  }
 
  async readBuffer(buffer, TypedArrayConstructor) {
    const size = buffer.size;
    const stagingBuffer = this.device.createBuffer({
      size,
      usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
      label: 'Staging buffer'
    });
 
    const commandEncoder = this.device.createCommandEncoder();
    commandEncoder.copyBufferToBuffer(buffer, 0, stagingBuffer, 0, size);
    this.device.queue.submit([commandEncoder.finish()]);
 
    await stagingBuffer.mapAsync(GPUMapMode.READ);
    const data = new TypedArrayConstructor(stagingBuffer.getMappedRange()).slice();
    stagingBuffer.unmap();
    stagingBuffer.destroy();
 
    return data;
  }
 
  static isAvailable() {
    return typeof navigator !== 'undefined' && 'gpu' in navigator;
  }
 
  static async queryMaxBufferSize() {
    if (GpuBaseBoard.cachedMaxBufferSize !== undefined) {
      return GpuBaseBoard.cachedMaxBufferSize;
    }
    try {
      // Query adapter limits directly - no need to create a device
      const adapter = await navigator.gpu.requestAdapter();
      if (!adapter) {
        console.warn('WebGPU adapter not available, falling back to CPU/WebGL2');
        GpuBaseBoard.cachedMaxBufferSize = null;
        return null;
      }
 
      const limit = Math.min(
        adapter.limits.maxBufferSize,
        adapter.limits.maxStorageBufferBindingSize);
      GpuBaseBoard.cachedMaxBufferSize = Math.floor(limit * 0.9);  // 90% for safety
      return GpuBaseBoard.cachedMaxBufferSize;
    } catch (e) {
      console.warn('WebGPU query failed, falling back to CPU/WebGL2:', e.message || e);
      GpuBaseBoard.cachedMaxBufferSize = null;
      return null;
    }
  }
 
  // ================================================================
  // Double-buffering and compaction infrastructure
  // Subclasses must define: static BYTES_PER_PIXEL, static STRIDE
  // ================================================================
 
  /**
   * Initialize double-buffering and compaction state.
   * Call from subclass constructor after super().
   */
  initDoubleBuffering() {
    this.stagingBufferIndex = 0;
    this.hasPendingResults = false;
    this.pendingIterationsPerBatch = 0;
    this.baseIt = 1;  // Committed iteration count
 
    // Compaction state - uses bandwidth cost model
    this.activeCount = this.config.dimsArea;
    this.deadSinceCompaction = 0;
    this.wastedBandwidth = 0;
    this.compactionCount = 0;
    this.pendingActiveCount = this.config.dimsArea;
    this.lastBatchCompacted = false;
    this.cumulativeWastedReads = 0;
  }
 
  initResultsReadback(recordBytes, maxCount) {
    const safeMax = Math.max(1, maxCount);
    this.resultsRecordBytes = recordBytes;
    this.resultsHeaderBytes = 32;  // 8 u32 fields: count, lastStaged, active_count, start_iter, iterations_per_batch, pad x3
    this.resultsMaxCount = safeMax;
    // Chunk size for incremental readback
    this.resultsReadbackMaxRecords = Math.max(256, Math.floor(safeMax * 0.01));
 
    // Pre-staging area layout (written by staging shader, copied to staging buffer):
    // - Header: 16 bytes (firstEmpty, countInChunk, chunkStartIndex, reserved)
    // - Records: chunkSize * recordBytes
    // Two pre-staging areas (one per staging buffer) to prevent race conditions
    // when command buffers overlap in execution.
    this.preStagingHeaderBytes = 16;
    this.preStagingSize = this.preStagingHeaderBytes + (recordBytes * this.resultsReadbackMaxRecords);
    const preStagingBase = this.resultsHeaderBytes + (recordBytes * safeMax);
    this.preStagingOffsets = [preStagingBase, preStagingBase + this.preStagingSize];
 
    // Total results buffer: header + main records + TWO pre-staging areas
    this.resultsBufferSize = preStagingBase + (this.preStagingSize * 2);
 
    // Staging buffer matches pre-staging area size
    this.resultsReadbackBufferSize = this.preStagingSize;
 
    // Reset buffer: 8 u32s for header (count=0, lastStaged=0, others don't matter)
    this.resultsCounterReset = new Uint32Array([0, 0, 0, 0, 0, 0, 0, 0]);
 
    if (this.buffers.results?.destroy) {
      this.buffers.results.destroy();
    }
    if (this.buffers.resultsStaging) {
      for (const buf of this.buffers.resultsStaging) {
        if (buf?.destroy) buf.destroy();
      }
    }
 
    this.buffers.results = this.device.createBuffer({
      size: this.resultsBufferSize,
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
      label: 'Results buffer'
    });
 
    const stagingSize = this.resultsReadbackBufferSize;
    this.buffers.resultsStaging = [
      this.device.createBuffer({
        size: stagingSize,
        usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
        label: 'Results staging 0'
      }),
      this.device.createBuffer({
        size: stagingSize,
        usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
        label: 'Results staging 1'
      })
    ];
 
    this.resultsReadIndex = 0;
    this.resultsTotalCount = 0;
    this.readbackBufferIndex = 0;
    this.pendingReadbackIndex = null;
    this.pendingReadbackPromise = null;
    this.hasPendingResults = false;
    this.resultsReadbackBytes = 0;
    this.resultsReadbackBatches = 0;
    this.lastResultsCount = 0;
 
    // Batch tracking for ordered results (see docs/gpu-results-readback-design.md)
    this.batchesToReadback = [];  // Queue of {startIter, endIter, remainingPixelCount}
    this.batchResultsRead = [];   // Accumulated results for current head batch
    this.previousBatchEndIter = 1;  // First batch starts at iter=1
    this.previousFirstEmpty = 0;  // Track firstEmpty for batch size computation
    this.lastFlushedPrecomputedIter = 0;
 
    this.device.queue.writeBuffer(this.buffers.results, 0, this.resultsCounterReset);
 
    // Batch locking buffer (see docs/gpu-batch-locking.md)
    // Layout: lock(u32), batch_active(u32), collision_count(u32), reserved(u32)
    // Used to prevent shader race conditions between overlapping batches
    if (this.buffers.lock?.destroy) {
      this.buffers.lock.destroy();
    }
    this.buffers.lock = this.device.createBuffer({
      size: 16,  // 4 u32s
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
      label: 'Batch lock buffer'
    });
    // Initialize: lock=0 (unlocked), batch_active=0, collision_count=0, reserved=0
    this.lockBufferReset = new Uint32Array([0, 0, 0, 0]);
    this.device.queue.writeBuffer(this.buffers.lock, 0, this.lockBufferReset);
 
    // Collision stats tracking (CPU-side)
    this.batchCollisionCount = 0;
    this.batchTotalCount = 0;
 
    // Create staging shader pipeline (see docs/gpu-results-readback-design.md)
    this.createStagingPipeline();
  }
 
  createStagingPipeline() {
    const chunkSize = this.resultsReadbackMaxRecords;
    const recordBytes = this.resultsRecordBytes;
    const recordU32s = recordBytes / 4;
 
    // Guard shader: tries to acquire batch lock (see docs/gpu-batch-locking.md)
    // Uses atomicCompareExchange to prevent race conditions between overlapping batches
    // Uses per-buffer-index batch_active to avoid race between Guard2 overwriting batch_active
    // before Compute1 reads it (see design doc for details)
    const guardShaderCode = `
      struct GuardParams {
        buffer_index: u32,  // 0 or 1, matches double-buffering index
      }
 
      // Lock buffer layout:
      // [0]=lock, [1]=batch_active[0], [2]=batch_active[1], [3]=collision_count
      struct LockBuffer {
        lock: atomic<u32>,
        batch_active_0: atomic<u32>,
        batch_active_1: atomic<u32>,
        collision_count: atomic<u32>,
      }
 
      @group(0) @binding(0) var<uniform> params: GuardParams;
      @group(0) @binding(1) var<storage, read_write> lockBuf: LockBuffer;
 
      @compute @workgroup_size(1)
      fn guard_main() {
        // Try to acquire lock: atomicCompareExchange(expected=0, desired=1)
        let prev = atomicCompareExchangeWeak(&lockBuf.lock, 0u, 1u).old_value;
        let is_active = select(0u, 1u, prev == 0u);
 
        // Write to per-buffer-index batch_active to avoid cross-batch race
        if (params.buffer_index == 0u) {
          atomicStore(&lockBuf.batch_active_0, is_active);
        } else {
          atomicStore(&lockBuf.batch_active_1, is_active);
        }
 
        if (prev != 0u) {
          atomicAdd(&lockBuf.collision_count, 1u);
        }
      }
    `;
 
    const guardModule = this.device.createShaderModule({
      code: guardShaderCode,
      label: 'Guard shader'
    });
 
    this.guardPipeline = this.device.createComputePipeline({
      layout: 'auto',
      compute: {
        module: guardModule,
        entryPoint: 'guard_main'
      },
      label: 'Guard pipeline'
    });
 
    // Create guard params buffers for each buffer index
    this.buffers.guardParams = [
      this.device.createBuffer({
        size: 4,  // 1 u32
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
        label: 'Guard params 0'
      }),
      this.device.createBuffer({
        size: 4,  // 1 u32
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
        label: 'Guard params 1'
      })
    ];
    this.device.queue.writeBuffer(this.buffers.guardParams[0], 0, new Uint32Array([0]));
    this.device.queue.writeBuffer(this.buffers.guardParams[1], 0, new Uint32Array([1]));
 
    // Create guard bind groups for each buffer index
    this.guardBindGroups = [
      this.device.createBindGroup({
        layout: this.guardPipeline.getBindGroupLayout(0),
        entries: [
          { binding: 0, resource: { buffer: this.buffers.guardParams[0] } },
          { binding: 1, resource: { buffer: this.buffers.lock } }
        ],
        label: 'Guard bind group 0'
      }),
      this.device.createBindGroup({
        layout: this.guardPipeline.getBindGroupLayout(0),
        entries: [
          { binding: 0, resource: { buffer: this.buffers.guardParams[1] } },
          { binding: 1, resource: { buffer: this.buffers.lock } }
        ],
        label: 'Guard bind group 1'
      })
    ];
 
    // Staging shader: copies results from main area to pre-staging area
    // All threads copy records in parallel, then atomicMin finds first not-ready record.
    // This handles the race where atomicAdd claims a slot before data is written.
    // Also handles batch locking: releases lock after copying, marks skipped batches.
    const stagingShaderCode = `
      struct StagingParams {
        chunkSize: u32,
        maxResults: u32,
        recordU32s: u32,
        preStagingOffset: u32,
        bufferIndex: u32,  // 0 or 1, for checking batch_active
        _pad0: u32,
        _pad1: u32,
        _pad2: u32,
      }
 
      // Lock buffer layout matches guard shader:
      // [0]=lock, [1]=batch_active[0], [2]=batch_active[1], [3]=collision_count
      struct LockBuffer {
        lock: atomic<u32>,
        batch_active_0: atomic<u32>,
        batch_active_1: atomic<u32>,
        collision_count: atomic<u32>,
      }
 
      @group(0) @binding(0) var<uniform> params: StagingParams;
      @group(0) @binding(1) var<storage, read_write> buffer: array<u32>;
      @group(0) @binding(2) var<storage, read_write> lockBuf: LockBuffer;
 
      // Buffer layout:
      // [0]: count (firstEmpty)
      // [1]: lastStaged
      // [2..7]: other header fields
      // [8..]: main records (status at offset 2 within each record)
      // [preStagingOffset/4..]: pre-staging header + records
      //   Pre-staging header: [0]=firstEmpty, [1]=countInChunk, [2]=chunkStartIndex, [3]=skipped
 
      const STATUS_OFFSET: u32 = 2u;
 
      var<workgroup> sharedFirstEmpty: u32;
      var<workgroup> sharedLastStaged: u32;
      var<workgroup> sharedMaxToCheck: u32;
      var<workgroup> sharedBatchSkipped: u32;
      var<workgroup> firstNotReady: atomic<u32>;
 
      @compute @workgroup_size(256)
      fn staging_main(@builtin(local_invocation_id) local_id: vec3<u32>) {
        let tid = local_id.x;
 
        // Thread 0 reads header and initializes shared state
        if (tid == 0u) {
          sharedFirstEmpty = buffer[0];
          sharedLastStaged = buffer[1];
          sharedMaxToCheck = min(sharedFirstEmpty - sharedLastStaged, params.chunkSize);
          atomicStore(&firstNotReady, sharedMaxToCheck);  // "all ready" sentinel
 
          // Check if batch was skipped due to collision
          var batch_active: u32;
          if (params.bufferIndex == 0u) {
            batch_active = atomicLoad(&lockBuf.batch_active_0);
          } else {
            batch_active = atomicLoad(&lockBuf.batch_active_1);
          }
          sharedBatchSkipped = select(0u, 1u, batch_active == 0u);
        }
 
        workgroupBarrier();
 
        let lastStaged = sharedLastStaged;
        let maxToCheck = sharedMaxToCheck;
 
        // Each thread copies multiple records (strided) and checks status
        for (var i = tid; i < maxToCheck; i = i + 256u) {
          let srcRecordStart = 8u + (lastStaged + i) * params.recordU32s;
          let dstRecordStart = (params.preStagingOffset / 4u) + 4u + i * params.recordU32s;
 
          // Copy the record
          for (var j = 0u; j < params.recordU32s; j++) {
            buffer[dstRecordStart + j] = buffer[srcRecordStart + j];
          }
 
          // Check status - if not ready, atomicMin to find earliest not-ready
          let status = buffer[srcRecordStart + STATUS_OFFSET];
          if (status == 0u) {
            atomicMin(&firstNotReady, i);
          }
        }
 
        workgroupBarrier();
 
        // Thread 0 writes header, updates lastStaged, and releases lock
        if (tid == 0u) {
          let actualCount = atomicLoad(&firstNotReady);
          let skipped = sharedBatchSkipped;
 
          let headerBase = params.preStagingOffset / 4u;
          buffer[headerBase + 0u] = sharedFirstEmpty;
          buffer[headerBase + 1u] = actualCount;
          buffer[headerBase + 2u] = lastStaged;
          buffer[headerBase + 3u] = skipped;  // 1 if batch was skipped due to collision
 
          // Update lastStaged (only advance by ready records)
          buffer[1] = lastStaged + actualCount;
 
          // Release the batch lock (atomic provides memory ordering)
          atomicStore(&lockBuf.lock, 0u);
        }
      }
    `;
 
    const stagingModule = this.device.createShaderModule({
      code: stagingShaderCode,
      label: 'Staging shader'
    });
 
    this.stagingPipeline = this.device.createComputePipeline({
      layout: 'auto',
      compute: {
        module: stagingModule,
        entryPoint: 'staging_main'
      },
      label: 'Staging pipeline'
    });
 
    // Create two staging params buffers (one per pre-staging area)
    this.buffers.stagingParams = [
      this.device.createBuffer({
        size: 32,  // 8 u32s (includes bufferIndex and padding)
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
        label: 'Staging params 0'
      }),
      this.device.createBuffer({
        size: 32,  // 8 u32s (includes bufferIndex and padding)
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
        label: 'Staging params 1'
      })
    ];
 
    // Write staging params for each pre-staging area
    for (let i = 0; i < 2; i++) {
      const stagingParamsData = new Uint32Array([
        chunkSize,
        this.resultsMaxCount,
        recordU32s,
        this.preStagingOffsets[i],
        i,  // bufferIndex: 0 or 1, for checking batch_active
        0,  // _pad0
        0,  // _pad1
        0   // _pad2
      ]);
      this.device.queue.writeBuffer(this.buffers.stagingParams[i], 0, stagingParamsData);
    }
 
    // Create two staging bind groups (one per pre-staging area)
    // Each includes the lock buffer for batch collision handling
    this.stagingBindGroups = [
      this.device.createBindGroup({
        layout: this.stagingPipeline.getBindGroupLayout(0),
        entries: [
          { binding: 0, resource: { buffer: this.buffers.stagingParams[0] } },
          { binding: 1, resource: { buffer: this.buffers.results } },
          { binding: 2, resource: { buffer: this.buffers.lock } }
        ],
        label: 'Staging bind group 0'
      }),
      this.device.createBindGroup({
        layout: this.stagingPipeline.getBindGroupLayout(0),
        entries: [
          { binding: 0, resource: { buffer: this.buffers.stagingParams[1] } },
          { binding: 1, resource: { buffer: this.buffers.results } },
          { binding: 2, resource: { buffer: this.buffers.lock } }
        ],
        label: 'Staging bind group 1'
      })
    ];
  }
 
  queueGuardPass(commandEncoder, bufferIndex) {
    // Guard pass: try to acquire batch lock (see docs/gpu-batch-locking.md)
    // Must run before compute pass to set batch_active[bufferIndex] flag
    // Using per-buffer-index prevents Guard2 from corrupting Compute1's batch_active
    const guardPass = commandEncoder.beginComputePass({ label: 'Guard pass' });
    guardPass.setPipeline(this.guardPipeline);
    guardPass.setBindGroup(0, this.guardBindGroups[bufferIndex]);
    guardPass.dispatchWorkgroups(1);
    guardPass.end();
  }
 
  queueResultsReadback(commandEncoder, index) {
    // Run staging shader to copy results to pre-staging area
    // Use index-specific bind group to write to the correct pre-staging area
    // Staging shader also releases the batch lock after copying
    const stagingPass = commandEncoder.beginComputePass({ label: 'Staging pass' });
    stagingPass.setPipeline(this.stagingPipeline);
    stagingPass.setBindGroup(0, this.stagingBindGroups[index]);
    // Single workgroup - each thread handles multiple records via strided loop
    stagingPass.dispatchWorkgroups(1);
    stagingPass.end();
 
    // Copy pre-staging area to staging buffer (each index uses its own pre-staging area)
    commandEncoder.copyBufferToBuffer(
      this.buffers.results, this.preStagingOffsets[index],
      this.buffers.resultsStaging[index], 0,
      this.preStagingSize
    );
  }
 
  async readResultsChunk(index) {
    // Read staging buffer which contains pre-staging header + records
    // Header: firstEmpty (u32), countInChunk (u32), chunkStartIndex (u32), skipped (u32)
    const staging = this.buffers.resultsStaging[index];
    await staging.mapAsync(GPUMapMode.READ, 0, this.preStagingSize);
    const mapped = staging.getMappedRange(0, this.preStagingSize);
 
    // Parse header
    const headerView = new Uint32Array(mapped, 0, 4);
    const firstEmpty = Math.min(headerView[0], this.resultsMaxCount);
    const countInChunk = headerView[1];
    const chunkStartIndex = headerView[2];
    const skipped = headerView[3] !== 0;  // Batch collision flag (see docs/gpu-batch-locking.md)
 
    // Copy records data (only if not skipped)
    let data = null;
    if (countInChunk > 0 && !skipped) {
      const dataBytes = countInChunk * this.resultsRecordBytes;
      data = new ArrayBuffer(dataBytes);
      const src = new Uint8Array(mapped, this.preStagingHeaderBytes, dataBytes);
      new Uint8Array(data).set(src);
    }
 
    staging.unmap();
    return { firstEmpty, countInChunk, chunkStartIndex, skipped, data };
  }
 
  async processPendingReadback() {
    if (this.pendingReadbackIndex === null) return;
    await this.pendingReadbackPromise;
 
    // Read chunk from staging buffer (see docs/gpu-results-readback-design.md)
    const { firstEmpty, countInChunk, chunkStartIndex, skipped, data } = await this.readResultsChunk(
      this.pendingReadbackIndex
    );
 
    // Track collision stats (see docs/gpu-batch-locking.md)
    this.batchTotalCount++;
    if (skipped) {
      this.batchCollisionCount++;
      // Skipped batch: no work was done, no results to process
      // Don't update previousFirstEmpty or add to batchesToReadback
      // Always log since collisions are rare and indicate GPU backpressure
      console.log(`Board ${this.id}: Batch skipped (collision #${this.batchCollisionCount}/${this.batchTotalCount})`);
      return;
    }
 
    this.resultsTotalCount = firstEmpty;
 
    // Enqueue this batch with its pixel count and iteration range [start, end)
    // Always enqueue, even with 0 GPU results - this ensures previousBatchEndIter
    // gets updated for precomputed point flushing (batches with 0 results will
    // immediately complete in flushCompleteBatches)
    const batchPixelCount = firstEmpty - this.previousFirstEmpty;
 
    this.batchesToReadback.push({
      startIter: this.pendingBatchStartIter,
      endIter: this.pendingBatchEndIter,
      remainingPixelCount: batchPixelCount,
      originalPixelCount: batchPixelCount  // For invariant checking
    });
    this.previousFirstEmpty = firstEmpty;
 
    // Process results through the batch-oriented loop
    // (see docs/gpu-results-readback-design.md "Results Processing Loop Structure")
    if (countInChunk > 0 && data) {
      this.processResultsData(data, countInChunk);
    } else if (countInChunk === 0) {
      // No GPU results in this chunk, but still need to flush complete batches
      this.flushCompleteBatches();
    }
 
    this.hasPendingResults = false;
    this.pendingReadbackIndex = null;
    this.pendingReadbackPromise = null;
    this.pendingBatchStartIter = 0;
    this.pendingBatchEndIter = 0;
  }
 
  /**
   * Process results data with clean batch-oriented loop structure.
   * See docs/gpu-results-readback-design.md "Results Processing Loop Structure" for design.
   *
   * Structure:
   *   1. Outer loop over batches in batchesToReadback
   *   2. Flush precomputed points before the head batch's start iteration
   *   3. Inner loop: parse results, accumulate into batchResultsRead
   *   4. On batch completion: merge precomputed, sort, queue to changeList
   */
  processResultsData(data, count) {
    const STRIDE = 8;  // 8 u32s per record for GpuBoard
    const pixelU32 = new Uint32Array(data);
    const pixelF32 = new Float32Array(data);
    const debugReadback = hasDebugFlag(this.config, 'rb');
 
    // Update readback stats
    this.lastResultsCount = count;
    this.resultsReadbackBatches += 1;
    this.resultsReadbackBytes += count * this.resultsRecordBytes;
 
    let dataIndex = 0;
 
    // OUTER LOOP: Process batches in order (Step 1)
    while (this.batchesToReadback.length > 0) {
      const batch = this.batchesToReadback[0];
 
      // Step 2: Flush precomputed points before this batch's iteration range
      if (this.precomputed) {
        this.flushPrecomputedUpTo(this.previousBatchEndIter - 1);
      }
 
      // Step 3: INNER LOOP - Process available data for this batch
      while (batch.remainingPixelCount > 0 && dataIndex < count) {
        const idx8 = dataIndex * STRIDE;
        const origIndex = pixelU32[idx8 + 0];
        const iters = pixelU32[idx8 + 1];
        const status = pixelU32[idx8 + 2];
        const period = pixelU32[idx8 + 3];
        const zr = pixelF32[idx8 + 4];
        const zi = pixelF32[idx8 + 5];
 
        // Skip already processed pixels (can happen with staging overlap race)
        if (this.nn[origIndex] !== 0) {
          if (debugReadback) {
            const same = this.nn[origIndex] === iters ? ' (SAME VALUE)' : ' (DIFFERENT VALUE)';
            console.error(`Duplicate result for pixel ${origIndex}, existing nn=${this.nn[origIndex]}, new iters=${iters}${same}`);
          }
          dataIndex++;
          continue;
        }
 
        // Skip non-finished pixels (status 0 = record not ready due to race)
        if (status === 0) {
          if (debugReadback) {
            console.error(`status=0 in results buffer at origIndex=${origIndex}`);
          }
          dataIndex++;
          continue;
        }
 
        // INVARIANT checks (gated by debug=rb flag)
        if (debugReadback) {
          if (iters < batch.startIter) {
            console.error(`INVARIANT VIOLATION: iter=${iters} < batchStart=${batch.startIter}`);
          }
          if (iters >= batch.endIter) {
            console.error(`INVARIANT VIOLATION: Future result! iter=${iters} >= batchEnd=${batch.endIter}`);
          }
        }
 
        // Update board state
        if (status === 1) {  // Diverged
          this.nn[origIndex] = iters;
          this.pp[origIndex] = 1;
          this.di++;
          if (this.inSpike && this.inSpike[origIndex] && this.ch > 0) this.ch -= 1;
        } else if (status === 2) {  // Converged
          this.nn[origIndex] = -iters;
          this.pp[origIndex] = period;  // Use GPU period directly (matches CpuBoard convention)
          if (this.inSpike && this.inSpike[origIndex] && this.ch > 0) this.ch -= 1;
        }
 
        // Accumulate into batchResultsRead
        const change = status === 1
          ? { iter: iters, nn: [origIndex], vv: [] }
          : { iter: iters, nn: [], vv: [{ index: origIndex, z: [zr, zi], p: this.pp[origIndex] }] };
        this.batchResultsRead.push(change);
 
        this.deadSinceCompaction++;
        batch.remainingPixelCount--;
        dataIndex++;
      }
 
      // Check if batch is complete
      if (batch.remainingPixelCount > 0) {
        // Batch not complete yet - exit and wait for more data
        break;
      }
 
      // Step 4: FLUSHING LOGIC - Batch is complete
 
      // INVARIANT CHECK: batchResultsRead should have exactly originalPixelCount GPU results
      if (this.batchResultsRead.length !== batch.originalPixelCount) {
        console.error(`INVARIANT VIOLATION: batchResultsRead.length=${this.batchResultsRead.length} but originalPixelCount=${batch.originalPixelCount}`);
      }
 
      // Flush precomputed points up to this batch's end iteration
      // With half-open [startIter, endIter), max iter in batch is endIter - 1
      if (this.precomputed) {
        this.flushPrecomputedIntoResults(batch.endIter - 1);
      }
 
      // INVARIANT CHECK: All results must be in half-open interval [startIter, endIter)
      // AND iter >= previousBatchEndIter (no late results from earlier batches)
      for (const change of this.batchResultsRead) {
        if (change.iter < this.previousBatchEndIter) {
          console.error(`INVARIANT VIOLATION at flush: iter=${change.iter} < previousEnd=${this.previousBatchEndIter}`);
        }
        if (change.iter < batch.startIter) {
          console.error(`INVARIANT VIOLATION at flush: iter=${change.iter} < batchStart=${batch.startIter}`);
        }
        if (change.iter >= batch.endIter) {
          console.error(`INVARIANT VIOLATION at flush: iter=${change.iter} >= batchEnd=${batch.endIter}`);
        }
        
        // Queue to changeList
        this.queueChanges(change);
      }
 
      // Clear for next batch
      this.batchResultsRead.length = 0;
      this.previousBatchEndIter = batch.endIter;
      this.batchesToReadback.shift();
    }
 
    // Update un count
    // deadSinceCompaction includes results in batchResultsRead that aren't flushed yet
    // Add them back since they're not in changeList yet (view won't see them)
    const pendingPrecomputed = this.precomputed ? this.precomputed.getPendingCount() : 0;
    const pendingInBatchResults = this.batchResultsRead.length;
    this.un = (this.activeCount - this.deadSinceCompaction) + pendingPrecomputed + pendingInBatchResults;
  }
 
  /**
   * Flush precomputed points with iterations <= maxIter directly to changeList.
   * Called before processing a batch's iteration range.
   */
  flushPrecomputedUpTo(maxIter) {
    if (!this.precomputed || maxIter <= this.lastFlushedPrecomputedIter) return;
    this.lastFlushedPrecomputedIter = maxIter;
    this.precomputed.flushUpToIteration(maxIter, this);
  }
 
  /**
   * Flush precomputed points with iterations <= maxIter into batchResultsRead.
   * Called when a batch is complete to merge precomputed with GPU results.
   */
  flushPrecomputedIntoResults(maxIter) {
    if (!this.precomputed) return;
 
    // With half-open intervals: flush precomputed with iter in [previousBatchEndIter, maxIter]
    // (maxIter is inclusive because it's the last iter of the current batch)
    const iterations = Array.from(this.precomputed.rangeMap.keys())
      .filter(iter => iter >= this.previousBatchEndIter && iter <= maxIter)
      .sort((a, b) => a - b);
 
    for (const iter of iterations) {
      const data = this.precomputed.extractAtIteration(iter);
      if (!data) continue;
 
      // Add diverged pixels
      for (const idx of data.diverged) {
        this.nn[idx] = iter;
        this.di++;
        this.batchResultsRead.push({ iter, nn: [idx], vv: [] });
      }
 
      // Add converged pixels
      for (const c of data.converged) {
        this.nn[c.index] = -iter;
        this.batchResultsRead.push({ iter, nn: [], vv: [c] });
      }
    }
  }
 
 
  // Note: drainResultsBacklog is no longer needed.
  // The staging shader automatically handles backlog via the lastStaged counter,
  // ensuring each batch reads the next chunk of unprocessed results.
 
  /**
   * Return iteration count for submitted GPU batches.
   */
  get it() {
    return this.baseIt;
  }
 
  set it(value) {
    this.baseIt = value;
  }
 
  /**
   * Flush complete batches that have no remaining GPU results expected.
   * Called when no GPU data in chunk but batches may be complete.
   */
  flushCompleteBatches() {
    while (this.batchesToReadback.length > 0 &&
           this.batchesToReadback[0].remainingPixelCount <= 0) {
      const batch = this.batchesToReadback[0];
 
      // Flush precomputed points for this batch's range
      // With half-open [startIter, endIter), max iter in batch is endIter - 1
      if (this.precomputed) {
        this.flushPrecomputedIntoResults(batch.endIter - 1);
      }
 
      // Queue results to changeList
      // FractalWorker sorts changeList by iteration before sending, so we don't need to sort here
      for (const change of this.batchResultsRead) {
        this.queueChanges(change);
      }
 
      this.batchResultsRead.length = 0;
      this.previousBatchEndIter = batch.endIter;
      this.batchesToReadback.shift();
    }
 
    // Update un count
    const pendingPrecomputed = this.precomputed ? this.precomputed.getPendingCount() : 0;
    this.un = (this.activeCount - this.deadSinceCompaction) + pendingPrecomputed;
  }
 
  // Abstract methods - subclasses must implement these
  async createComputePipeline() {
    throw new Error('createComputePipeline() must be implemented by subclass');
  }
 
  async createBuffers() {
    throw new Error('createBuffers() must be implemented by subclass');
  }
 
  createBindGroup() {
    throw new Error('createBindGroup() must be implemented by subclass');
  }
 
  async compute() {
    throw new Error('compute() must be implemented by subclass');
  }
 
  /**
   * Read the pixels buffer from GPU and return as ArrayBuffer.
   * Creates a temporary staging buffer on-demand to avoid persistent memory use.
   * Uses a lock to prevent concurrent mapAsync calls.
   * @returns {Promise<ArrayBuffer>} The pixel buffer data
   */
  async readPixelBuffer() {
    // Read GPU pixel buffer for serialization - creates temporary staging buffer on-demand
    if (!this.isGPUReady || !this.buffers.pixels) {
      return null;
    }
 
    // Wait for any pending read to complete before starting a new one
    if (this.readPixelBufferPromise) {
      await this.readPixelBufferPromise;
    }
 
    // Create the actual read operation as a promise we can track
    const doRead = async () => {
      const bytesPerPixel = this.constructor.BYTES_PER_PIXEL;
      const dimsArea = this.config.dimsWidth * this.config.dimsHeight;
      const bufferSize = dimsArea * bytesPerPixel;
 
      // Create temporary staging buffer (only needed during serialization)
      const stagingBuffer = this.device.createBuffer({
        size: bufferSize,
        usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
        label: 'Temp staging for serialization'
      });
 
      // Copy pixels buffer to staging
      const commandEncoder = this.device.createCommandEncoder();
      commandEncoder.copyBufferToBuffer(this.buffers.pixels, 0, stagingBuffer, 0, bufferSize);
      this.device.queue.submit([commandEncoder.finish()]);
      await this.device.queue.onSubmittedWorkDone();
 
      // Read back the data
      await stagingBuffer.mapAsync(GPUMapMode.READ);
      const pixelData = new ArrayBuffer(bufferSize);
      const srcData = stagingBuffer.getMappedRange();
      new Uint8Array(pixelData).set(new Uint8Array(srcData));
      stagingBuffer.unmap();
 
      // Destroy temporary buffer immediately
      stagingBuffer.destroy();
 
      return pixelData;
    };
 
    this.readPixelBufferPromise = doRead();
    try {
      return await this.readPixelBufferPromise;
    } finally {
      this.readPixelBufferPromise = null;
    }
  }
 
  /**
   * Write ArrayBuffer data back to the GPU pixels buffer.
   * @param {ArrayBuffer} data - The pixel buffer data to write
   */
  async writePixelBuffer(data) {
    if (!this.isGPUReady || !this.buffers.pixels) {
      return false;
    }
    this.device.queue.writeBuffer(this.buffers.pixels, 0, data);
    await this.device.queue.onSubmittedWorkDone();
    return true;
  }
}
 
// WebGPU board using float32 arithmetic for shallow zoom depths.
// Uses sparse buffer compaction to improve performance as pixels complete.
class GpuBoard extends GpuBaseBoard {
  static BYTES_PER_PIXEL = 32;  // 8 fields: orig_index + iter/status/period + zr/zi/base_r/base_i
  static STRIDE = 8;            // 8 u32/f32 fields per pixel
 
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
    this.effort = 10;  // Doubled to reduce batch sizes after GPU readback improvements
 
    const pix = this.pixelSize;
    this.epsilon = pix / 10;
    this.epsilon2 = pix * 10;
    this.checkSpike(size, re, im);
 
    // Initialize double-buffering (from GpuBaseBoard)
    this.initDoubleBuffering();
 
    this.gpuInitPromise = this.initGPU();
  }
 
  async createComputePipeline() {
    // Same shader as GpuBoard but adapted for compacted buffers
    const shaderCode = `
      struct Params {
        center_re: f32,
        center_im: f32,
        pixel_size: f32,
        aspect_ratio: f32,
        dims_width: u32,
        dims_height: u32,
        iterations_per_batch: u32,
        active_count: u32,
        epsilon: f32,
        epsilon2: f32,
        exponent: u32,
        workgroups_x: u32,
        start_iter: u32,
        checkpoint_count: u32,
        buffer_index: u32,  // 0 or 1, for per-buffer batch_active
        _pad_bi: u32,       // padding to maintain alignment
        ckpt0: u32, ckpt1: u32, ckpt2: u32, ckpt3: u32,
        ckpt4: u32, ckpt5: u32, ckpt6: u32, ckpt7: u32,
        ckpt8: u32, ckpt9: u32, ckpt10: u32, ckpt11: u32,
        ckpt12: u32, ckpt13: u32, ckpt14: u32, ckpt15: u32,
        ckpt16: u32, ckpt17: u32, ckpt18: u32, ckpt19: u32,
        ckpt20: u32, ckpt21: u32, ckpt22: u32, ckpt23: u32,
        ckpt24: u32, ckpt25: u32, ckpt26: u32, ckpt27: u32,
        ckpt28: u32, ckpt29: u32, ckpt30: u32, ckpt31: u32,
      }
 
      struct PixelState {
        orig_index: u32,  // Original pixel index (for coordinate computation)
        iter: u32,
        status: u32,
        period: u32,
        zr: f32,
        zi: f32,
        base_r: f32,
        base_i: f32,
      }
 
      // Results buffer header: 32 bytes (8 u32 fields)
      // Offset 0:  count (atomic) - firstEmpty, next write slot
      // Offset 4:  lastStaged (atomic) - last staged index
      // Offset 8:  active_count
      // Offset 12: start_iter
      // Offset 16: iterations_per_batch
      // Offset 20-28: padding
      // Offset 32: records[0..N]
      struct Results {
        count: atomic<u32>,
        lastStaged: atomic<u32>,
        active_count: u32,
        start_iter: u32,
        iterations_per_batch: u32,
        _pad0: u32,
        _pad1: u32,
        _pad2: u32,
        records: array<PixelState>,
      }
 
      // Lock buffer for batch collision prevention (see docs/gpu-batch-locking.md)
      // Uses per-buffer-index batch_active to avoid cross-batch race conditions
      struct LockBuffer {
        lock: atomic<u32>,
        batch_active_0: atomic<u32>,
        batch_active_1: atomic<u32>,
        collision_count: atomic<u32>,
      }
 
      @group(0) @binding(0) var<uniform> params: Params;
      @group(0) @binding(1) var<storage, read_write> pixels: array<PixelState>;
      @group(0) @binding(2) var<storage, read_write> results: Results;
      @group(0) @binding(3) var<storage, read_write> lockBuf: LockBuffer;
 
      @compute @workgroup_size(64)
      fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
        // Check per-buffer-index batch_active - skip if guard didn't acquire lock
        // Using buffer_index avoids race where Guard2 overwrites before Compute1 reads
        var batch_active: u32;
        if (params.buffer_index == 0u) {
          batch_active = atomicLoad(&lockBuf.batch_active_0);
        } else {
          batch_active = atomicLoad(&lockBuf.batch_active_1);
        }
        if (batch_active == 0u) {
          return;  // Batch skipped due to collision
        }
 
        if (global_id.x == 0u && global_id.y == 0u && global_id.z == 0u) {
          results.active_count = params.active_count;
          results.start_iter = params.start_iter;
          results.iterations_per_batch = params.iterations_per_batch;
        }
        let active_idx = global_id.y * params.workgroups_x + global_id.x;
        if (active_idx >= params.active_count) {
          return;
        }
 
        // Skip already-finished pixels (simple check in compacted buffer)
        if (pixels[active_idx].status != 0u) {
          return;
        }
 
        let orig_index = pixels[active_idx].orig_index;
        let x = orig_index % params.dims_width;
        let y = orig_index / params.dims_width;
 
        let xFrac = f32(i32(x) - i32(params.dims_width / 2u)) / f32(params.dims_width);
        let yFrac = f32(i32(params.dims_height / 2u) - i32(y)) / f32(params.dims_height);
        let cr = params.center_re + xFrac * params.pixel_size;
        let ci = params.center_im + yFrac * (params.pixel_size / params.aspect_ratio);
 
        var zr = pixels[active_idx].zr;
        var zi = pixels[active_idx].zi;
        var iter = pixels[active_idx].iter;
        var base_r = pixels[active_idx].base_r;
        var base_i = pixels[active_idx].base_i;
        var p = pixels[active_idx].period;
        var finished = false;
 
        // Initialize fresh pixels: iter=0 means uninitialized
        // Set z=c (first iteration z₀=0 → z₁=c) and iter=1
        if (iter == 0u) {
          zr = cr;
          zi = ci;
          base_r = cr;
          base_i = ci;
          iter = 1u;
        }
 
        var next_checkpoint_idx = 0u;
 
        // Fixed epsilon derived from pixel size (no iteration-based escalation)
        let epsilon = params.epsilon;
        let epsilon2 = params.epsilon2;
 
        for (var i = 0u; i < params.iterations_per_batch; i++) {
          if (next_checkpoint_idx < params.checkpoint_count) {
            var checkpoint_offset = 0u;
            switch (next_checkpoint_idx) {
              case 0u: { checkpoint_offset = params.ckpt0; }
              case 1u: { checkpoint_offset = params.ckpt1; }
              case 2u: { checkpoint_offset = params.ckpt2; }
              case 3u: { checkpoint_offset = params.ckpt3; }
              case 4u: { checkpoint_offset = params.ckpt4; }
              case 5u: { checkpoint_offset = params.ckpt5; }
              case 6u: { checkpoint_offset = params.ckpt6; }
              case 7u: { checkpoint_offset = params.ckpt7; }
              case 8u: { checkpoint_offset = params.ckpt8; }
              case 9u: { checkpoint_offset = params.ckpt9; }
              case 10u: { checkpoint_offset = params.ckpt10; }
              case 11u: { checkpoint_offset = params.ckpt11; }
              case 12u: { checkpoint_offset = params.ckpt12; }
              case 13u: { checkpoint_offset = params.ckpt13; }
              case 14u: { checkpoint_offset = params.ckpt14; }
              case 15u: { checkpoint_offset = params.ckpt15; }
              case 16u: { checkpoint_offset = params.ckpt16; }
              case 17u: { checkpoint_offset = params.ckpt17; }
              case 18u: { checkpoint_offset = params.ckpt18; }
              case 19u: { checkpoint_offset = params.ckpt19; }
              case 20u: { checkpoint_offset = params.ckpt20; }
              case 21u: { checkpoint_offset = params.ckpt21; }
              case 22u: { checkpoint_offset = params.ckpt22; }
              case 23u: { checkpoint_offset = params.ckpt23; }
              case 24u: { checkpoint_offset = params.ckpt24; }
              case 25u: { checkpoint_offset = params.ckpt25; }
              case 26u: { checkpoint_offset = params.ckpt26; }
              case 27u: { checkpoint_offset = params.ckpt27; }
              case 28u: { checkpoint_offset = params.ckpt28; }
              case 29u: { checkpoint_offset = params.ckpt29; }
              case 30u: { checkpoint_offset = params.ckpt30; }
              case 31u: { checkpoint_offset = params.ckpt31; }
              default: {}
            }
            if (i == checkpoint_offset) {
              base_r = zr;
              base_i = zi;
              p = 0u;
              next_checkpoint_idx++;
            }
          }
 
          let zr2 = zr * zr;
          let zi2 = zi * zi;
          let mag_sq = zr2 + zi2;
 
          if (mag_sq > 4.0 || !(mag_sq <= 1e38)) {
            pixels[active_idx].status = 1u;
            finished = true;
            break;
          }
 
          var ra = zr2 - zi2;
          var ja = 2.0 * zr * zi;
          for (var ord = 2u; ord < params.exponent; ord++) {
            let rt = zr * ra - zi * ja;
            ja = zr * ja + zi * ra;
            ra = rt;
          }
          zr = ra + cr;
          zi = ja + ci;
 
          let dr = zr - base_r;
          let di = zi - base_i;
          let db = abs(dr) + abs(di);
          if (db <= epsilon2) {
            if (p == 0u) {
              p = iter;
            }
            if (db <= epsilon) {
              pixels[active_idx].status = 2u;
              finished = true;
              break;
            }
          }
          iter++;
        }
 
        pixels[active_idx].zr = zr;
        pixels[active_idx].zi = zi;
        pixels[active_idx].base_r = base_r;
        pixels[active_idx].base_i = base_i;
        pixels[active_idx].iter = iter;
        pixels[active_idx].period = p;
 
        if (finished) {
          let outIndex = atomicAdd(&results.count, 1u);
          results.records[outIndex] = pixels[active_idx];
        }
      }
    `;
 
    const shaderModule = this.device.createShaderModule({
      code: shaderCode,
      label: 'SparseGpu compute shader'
    });
 
    this.pipeline = this.device.createComputePipeline({
      layout: 'auto',
      compute: {
        module: shaderModule,
        entryPoint: 'main'
      },
      label: 'SparseGpu compute pipeline'
    });
  }
 
  async createBuffers() {
    const dimsArea = this.config.dimsWidth * this.config.dimsHeight;
    const BYTES_PER_PIXEL = 32;  // 8 fields × 4 bytes
 
    const maxBufferSize = Math.min(
      this.device.limits.maxBufferSize,
      this.device.limits.maxStorageBufferBindingSize
    );
 
    // Count active pixels (excluding precomputed)
    const precomputedCount = this.precomputed ? this.precomputed.getPrecomputedCount() : 0;
    const activePixelCount = dimsArea - precomputedCount;
 
    // Allocate buffer for active pixels only
    // WebGPU requires non-zero buffer size, so use at least 1 pixel worth
    const pixelBufferSize = Math.max(BYTES_PER_PIXEL, activePixelCount * BYTES_PER_PIXEL);
 
    if (pixelBufferSize > maxBufferSize) {
      throw new Error(`Buffer size exceeds WebGPU limit`);
    }
    const resultsBufferSize = 16 + (activePixelCount * BYTES_PER_PIXEL);
    if (resultsBufferSize > maxBufferSize) {
      throw new Error(`Results buffer size exceeds WebGPU limit`);
    }
 
    // Uniform buffer for parameters
    this.buffers.params = this.device.createBuffer({
      size: 256,  // 14 fields + 32 checkpoints = 184 bytes, rounded to 256
      usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
      label: 'Parameters buffer'
    });
 
    // Pixel state buffer (compacted - excludes precomputed pixels)
    // Each pixel carries its orig_index, so no separate mapping buffer needed
    // Use mappedAtCreation to avoid separate writeBuffer call
    const tb0 = performance.now();
    this.buffers.pixels = this.device.createBuffer({
      size: pixelBufferSize,
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
      label: 'Pixel state buffer',
      mappedAtCreation: true
    });
    const tb1 = performance.now();
 
    // Note: stagingPixels buffers are created on-demand in readPixelBuffer() for serialization
    // This saves ~2x pixel buffer size in GPU memory during normal operation
 
    // Initialize directly into the mapped buffer (avoids separate CPU buffer + writeBuffer)
    const pixelU32 = new Uint32Array(this.buffers.pixels.getMappedRange());
 
    let activeIdx = 0;
    if (this.precomputed) {
      // With precomputed pixels, need to skip them
      for (let i = 0; i < dimsArea; i++) {
        if (!this.precomputed.isPrecomputed(i)) {
          pixelU32[activeIdx * 8] = i;  // orig_index only, rest is already 0
          activeIdx++;
        }
      }
    } else {
      // No precomputed pixels - fast path: orig_index = sequential index
      for (let i = 0; i < dimsArea; i++) {
        pixelU32[i * 8] = i;
      }
      activeIdx = dimsArea;
    }
    const tb2 = performance.now();
    this.buffers.pixels.unmap();
    const tb3 = performance.now();
    if (hasDebugFlag(this.config, 't')) {
      console.log(`[buffer-init] create=${(tb1-tb0).toFixed(0)}ms loop=${(tb2-tb1).toFixed(0)}ms unmap=${(tb3-tb2).toFixed(0)}ms total=${(tb3-tb0).toFixed(0)}ms`);
    }
 
    this.activeCount = activePixelCount;
    // Note: don't adjust this.un here - it will be decremented by flushUpToIteration
    // when precomputed points are flushed, which properly updates di/un together
    this.deadSinceCompaction = 0;
    this.initResultsReadback(BYTES_PER_PIXEL, activePixelCount);
  }
 
  createBindGroup() {
    this.bindGroup = this.device.createBindGroup({
      layout: this.pipeline.getBindGroupLayout(0),
      entries: [
        { binding: 0, resource: { buffer: this.buffers.params } },
        { binding: 1, resource: { buffer: this.buffers.pixels } },
        { binding: 2, resource: { buffer: this.buffers.results } },
        { binding: 3, resource: { buffer: this.buffers.lock } }
      ],
      label: 'SparseGpu bind group'
    });
  }
 
  // processResultsData inherited from GpuBaseBoard - uses batch tracking
 
  async compute(targetIters = null) {
    if (this.isComputing) return;
    this.isComputing = true;
    this.lastBatchCompacted = false;
 
    const BYTES_PER_PIXEL = 32;  // 8 fields × 4 bytes
    const workgroupSize = 64;
 
    try {
      // STEP 1: Check if done (before submitting new work)
      if (this.activeCount === 0 || this.un === 0) {
        // Push sentinel batch to flush any remaining precomputed points
        // (see docs/gpu-results-readback-design.md "Step 5: Sentinel Batch")
        if (this.precomputed && this.precomputed.getPendingCount() > 0) {
          this.batchesToReadback.push({
            startIter: this.previousBatchEndIter,
            endIter: Infinity,  // Signals "all done" - flush all remaining precomputed
            remainingPixelCount: 0  // No GPU results expected
          });
          this.flushCompleteBatches();
        }
        this.un = 0;
        // Flush any pending results before returning
        if (this.hasPendingResults) {
          await this.flushPendingResults();
        }
        return;
      }
 
      // STEP 2: Submit new GPU batch FIRST (non-blocking)
      // This starts the GPU working while we process previous results
      const re_double = qdToNumber(this.re);
      const im_double = qdToNumber(this.im);
      const pixel_size = this.size;
 
      let iterationsPerBatch;
      if (targetIters !== null) {
        iterationsPerBatch = targetIters;
      } else {
        const targetWork = 333337;
        iterationsPerBatch = Math.max(17, Math.floor(targetWork / Math.max(this.un, 1)));
      }
      // Accelerating batch sizes for fast first paint at shallow zoom:
      // - Batch 1: 1 iter, Batch 2: 2 iters, Batch 3: 4 iters, Batch 4: 8 iters
      // - Only applies at zoom < 30 (size > 0.1) where early escapes are visible
      const baseIt = this.baseIt;
      if (this.size > 0.1) {
        if (baseIt === 1) iterationsPerBatch = 1;
        else if (baseIt <= 3) iterationsPerBatch = Math.min(iterationsPerBatch, 3 - baseIt + 1);
        else if (baseIt <= 7) iterationsPerBatch = Math.min(iterationsPerBatch, 7 - baseIt + 1);
        else if (baseIt <= 15) iterationsPerBatch = Math.min(iterationsPerBatch, 15 - baseIt + 1);
      }
      const numWorkgroups = Math.ceil(this.activeCount / workgroupSize);
      const workgroupsX = Math.ceil(Math.sqrt(numWorkgroups));
      const workgroupsY = Math.ceil(numWorkgroups / workgroupsX);
 
      const checkpointOffsets = [];
      const bufferIter = this.it;
      for (let i = 0; i < iterationsPerBatch; i++) {
        if (fibonacciPeriod(bufferIter + i) === 1) checkpointOffsets.push(i);
      }
      const checkpointCount = Math.min(checkpointOffsets.length, 32);
 
      const paramsBuffer = new ArrayBuffer(256);
      const paramsF32 = new Float32Array(paramsBuffer);
      const paramsU32 = new Uint32Array(paramsBuffer);
 
      paramsF32[0] = re_double;
      paramsF32[1] = im_double;
      paramsF32[2] = pixel_size;
      paramsF32[3] = this.config.aspectRatio;
      paramsU32[4] = this.config.dimsWidth;
      paramsU32[5] = this.config.dimsHeight;
      paramsU32[6] = iterationsPerBatch;
      paramsU32[7] = this.activeCount;
      paramsF32[8] = this.epsilon;
      paramsF32[9] = this.epsilon2;
      paramsU32[10] = this.config.exponent;
      paramsU32[11] = workgroupsX * workgroupSize;
      paramsU32[12] = bufferIter;
      paramsU32[13] = checkpointCount;
 
      const bufferIndex = this.readbackBufferIndex;
      paramsU32[14] = bufferIndex;  // buffer_index for per-buffer batch_active
      paramsU32[15] = 0;  // _pad_bi
 
      for (let i = 0; i < 32; i++) {
        paramsU32[16 + i] = i < checkpointCount ? checkpointOffsets[i] : 0;
      }
 
      this.device.queue.writeBuffer(this.buffers.params, 0, paramsBuffer);
 
      const commandEncoder = this.device.createCommandEncoder({ label: 'GpuBoard compute' });
 
      // Guard pass: try to acquire batch lock (see docs/gpu-batch-locking.md)
      this.queueGuardPass(commandEncoder, bufferIndex);
 
      // Compute pass: iterate pixels (will skip if lock not acquired)
      const passEncoder = commandEncoder.beginComputePass({ label: 'GpuBoard pass' });
      passEncoder.setPipeline(this.pipeline);
      passEncoder.setBindGroup(0, this.bindGroup);
      passEncoder.dispatchWorkgroups(workgroupsX, workgroupsY);
      passEncoder.end();
 
      // Queue staging shader pass and copy to staging buffer
      // (see docs/gpu-results-readback-design.md)
      // Staging shader releases the lock after copying
      this.queueResultsReadback(commandEncoder, bufferIndex);
 
      this.device.queue.submit([commandEncoder.finish()]);
      // Save batch iter range using half-open interval [start, end)
      // - start = first iter processed in this batch
      // - end = first iter of the next batch (one past the last iter of this batch)
      // Results from this batch have iter in [start, end)
      const batchStartIter = this.baseIt;
      this.baseIt += iterationsPerBatch;
      const batchEndIter = this.baseIt;  // = start + iterationsPerBatch
      const currentPromise = this.device.queue.onSubmittedWorkDone();
      // GPU is now computing in parallel!
 
      // STEP 3: Process pending results from PREVIOUS batch (overlaps with GPU work)
      if (this.pendingReadbackIndex !== null) {
        await this.processPendingReadback();
      }
 
      // Set up state for THIS batch (to be processed next frame)
      this.pendingReadbackIndex = bufferIndex;
      this.pendingReadbackPromise = currentPromise;
      this.readbackBufferIndex = 1 - bufferIndex;
      this.pendingIterationsPerBatch = iterationsPerBatch;
      this.hasPendingResults = true;
      // Batch tracking: half-open interval [start, end) for proper invariant checking
      this.pendingBatchStartIter = batchStartIter;
      this.pendingBatchEndIter = batchEndIter;
 
    } catch (error) {
      console.error(`GpuBoard.compute() ERROR:`, error);
    } finally {
      this.isComputing = false;
    }
  }
 
  async serialize() {
    // Wait for any in-progress compute() to finish to avoid mapAsync race condition
    while (this.isComputing) {
      await new Promise(resolve => setTimeout(resolve, 10));
    }
 
    // CRITICAL: Flush pending results before serializing
    // The double-buffered staging has results that haven't been processed yet
    if (this.hasPendingResults) {
      await this.flushPendingResults();
    }
 
    // Read the compacted GPU pixel buffer
    await this.ensureGPUReady();
    const gpuPixelData = await this.readCompactedPixelBuffer();
 
    // Build sparse nn array for completed pixels
    const completedIndexes = [];
    const completedNn = [];
    for (let i = 0; i < this.nn.length; i++) {
      if (this.nn[i] !== 0) {
        completedIndexes.push(i);
        completedNn.push(this.nn[i]);
      }
    }
 
    return {
      ...(await super.serialize()),
      gpuPixelData: gpuPixelData ? Array.from(new Uint8Array(gpuPixelData)) : null,
      effort: this.effort,
      completedIndexes,
      completedNn,
      // Compaction state (orig_index is embedded in pixel data, no separate mapping needed)
      activeCount: this.activeCount,
      deadSinceCompaction: this.deadSinceCompaction,
      cumulativeWastedReads: this.cumulativeWastedReads,
    };
  }
 
  async flushPendingResults() {
    // Process pending results from the staging buffer without starting a new batch
    if (!this.hasPendingResults) return;
 
    // Process the pending batch if there is one
    if (this.pendingReadbackIndex !== null) {
      await this.processPendingReadback();
    }
 
    // Continue draining results until all are read
    // The staging shader reads from lastStaged which advances each time we read a chunk
    let moreData = true;
    while (moreData) {
      // Run another staging shader pass and copy to staging buffer
      const readbackIndex = this.readbackBufferIndex;
      const commandEncoder = this.device.createCommandEncoder({ label: 'Drain readback' });
      this.queueResultsReadback(commandEncoder, readbackIndex);
      this.device.queue.submit([commandEncoder.finish()]);
      await this.device.queue.onSubmittedWorkDone();
 
      // Read and process the chunk
      const { firstEmpty, countInChunk, chunkStartIndex, data } = await this.readResultsChunk(readbackIndex);
 
      if (countInChunk === 0) {
        moreData = false;  // No more results to read
      } else if (data) {
        this.processResultsData(data, countInChunk);
      }
 
      this.readbackBufferIndex = 1 - readbackIndex;
    }
 
    // Batches should complete naturally as results are processed.
    // If batches remain incomplete after draining all results, that's a bug.
  }
 
  async readCompactedPixelBuffer() {
    if (!this.isGPUReady || !this.buffers?.pixels) return null;
 
    const BYTES_PER_PIXEL = 32;  // 8 fields × 4 bytes
    const bufferSize = this.activeCount * BYTES_PER_PIXEL;
 
    const readBuffer = this.device.createBuffer({
      size: bufferSize,
      usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
    });
 
    const commandEncoder = this.device.createCommandEncoder();
    commandEncoder.copyBufferToBuffer(this.buffers.pixels, 0, readBuffer, 0, bufferSize);
    this.device.queue.submit([commandEncoder.finish()]);
 
    await readBuffer.mapAsync(GPUMapMode.READ);
    const data = new ArrayBuffer(bufferSize);
    new Uint8Array(data).set(new Uint8Array(readBuffer.getMappedRange()));
    readBuffer.unmap();
    readBuffer.destroy();
 
    return data;
  }
 
  static fromSerialized(serialized) {
    const board = new GpuBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    // Schedule async restoration after GPU init
    board.gpuInitPromise = board.gpuInitPromise.then(async () => {
      // Restore compaction state
      if (serialized.activeCount !== undefined) {
        board.activeCount = serialized.activeCount;
        board.deadSinceCompaction = serialized.deadSinceCompaction || 0;
        board.cumulativeWastedReads = serialized.cumulativeWastedReads || 0;
 
        // Recreate buffers at the compacted size
        const BYTES_PER_PIXEL = 32;  // 8 fields × 4 bytes
        const bufferSize = board.activeCount * BYTES_PER_PIXEL;
 
        board.buffers.pixels?.destroy();
        board.buffers.pixels = board.device.createBuffer({
          size: bufferSize,
          usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
          label: 'Pixel state buffer (restored)'
        });
 
        // Restore GPU pixel buffer (includes orig_index for each pixel)
        if (serialized.gpuPixelData) {
          const pixelData = new Uint8Array(serialized.gpuPixelData).buffer;
          board.device.queue.writeBuffer(board.buffers.pixels, 0, new Uint8Array(pixelData));
        }
 
        // Note: stagingPixels are created on-demand in readPixelBuffer() for serialization
 
        board.initResultsReadback(BYTES_PER_PIXEL, board.activeCount);
        // Recreate bind group with restored buffer
        board.createBindGroup();
      }
 
      board.effort = serialized.effort || 5;
      board.it = serialized.it;
      board.un = serialized.un;
      board.di = serialized.di;
      board.ch = serialized.ch || 0;
 
      // Restore nn array
      board.nn = new Array(serialized.config.dimsArea).fill(0);
      if (serialized.completedIndexes) {
        for (let i = 0; i < serialized.completedIndexes.length; i++) {
          board.nn[serialized.completedIndexes[i]] = serialized.completedNn[i];
        }
      }
 
      // Restore precomputed points state
      if (serialized.precomputed) {
        board.precomputed = PrecomputedPoints.fromSerialized(serialized.precomputed);
      }
    });
 
    return board;
  }
}
 
// WebGL2 board using fragment shaders for gap-free GPU iteration.
// Unlike WebGPU, WebGL's driver manages cross-command synchronization,
// allowing continuous GPU pipelining without CPU round-trips between batches.
// See docs/webgl-pingpong-design.md for detailed design rationale.
class GlBoard extends Board {
  static TILE_SIZE = 16;  // Tile size for hierarchical reduction
 
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
    this.effort = 10;  // Similar to GpuBoard
    // Cap iterations per batch - can do up to 327680 in a single draw call
    this.maxBatchIters = 327680;
 
    // WebGL state
    this.gl = null;
    this.canvas = null;
    this.iterProgram = null;
    this.reduction1Program = null;
    this.reduction2Program = null;
 
    // Ping-pong state textures (MRT: state + checkpoint)
    // State texture: (zr, zi, iter, status)
    // Checkpoint texture: (checkpoint_zr, checkpoint_zi, period, reserved)
    this.pingStateTex = null;
    this.pingCheckpointTex = null;
    this.pongStateTex = null;
    this.pongCheckpointTex = null;
    this.pingFB = null;
    this.pongFB = null;
    this.isPingRead = true;
 
    // Hierarchy textures for sparse readback
    this.level1Tex = null;
    this.level1FB = null;
    this.prevLevel1Tex = null;
    this.prevLevel1FB = null;
    this.level2Tex = null;
    this.level2FB = null;
 
    // Dimensions
    this.texWidth = config.dimsWidth;
    this.texHeight = config.dimsHeight;
    this.level1Width = Math.ceil(this.texWidth / GlBoard.TILE_SIZE);
    this.level1Height = Math.ceil(this.texHeight / GlBoard.TILE_SIZE);
    this.level2Width = Math.ceil(this.level1Width / GlBoard.TILE_SIZE);
    this.level2Height = Math.ceil(this.level1Height / GlBoard.TILE_SIZE);
 
    // Track reported pixels to avoid duplicates
    this.reported = new Uint8Array(config.dimsArea);
 
    // Tile-based dispatch optimization
    const totalTiles = this.level1Width * this.level1Height;
    this.activeTileMask = new Uint8Array(totalTiles);  // 1 = active, 0 = inactive
    this.activeTileMask.fill(1);  // All tiles start active
    this.activeTileCount = totalTiles;
    this.useTileDispatch = false;  // Enable after first reduction
    this.escapedSinceUpdate = 0;  // Track escapes since last tile mask update
 
    // Convergence detection thresholds (like CpuBoard)
    this.epsilon = this.pix / 10;    // Final convergence threshold
    this.epsilon2 = this.pix * 10;   // "Getting close" threshold
 
    // Fibonacci sequence for checkpoint updates
    this.fibCache = [1, 2];
    this.nextFibIndex = 2;
 
    // Full-screen quad VAO
    this.quadVAO = null;
 
    // Uniform locations (cached after shader compilation)
    this.iterUniforms = {};
    this.reduction1Uniforms = {};
    this.reduction2Uniforms = {};
 
    // Async readback state (PBO-based to avoid blocking)
    // Double-buffered PBOs to avoid write-before-read warnings
    this.pendingReadback = null;  // { sync, pboIndex }
    this.pendingBatchEndIter = null;  // End iteration for pending batch (for precomputed flushing)
    this.level2PBOs = [null, null];  // Ping-pong PBOs
    this.currentPBOIndex = 0;
 
    // Complex plane bounds (set in start())
    this.cMinRe = 0;
    this.cMinIm = 0;
    this.cMaxRe = 0;
    this.cMaxIm = 0;
 
    // Initialize WebGL
    this.glInitPromise = this.initWebGL();
  }
 
  // Check if iteration is a Fibonacci number (checkpoint point)
  isFibonacci(n) {
    // Extend cache if needed
    while (this.fibCache[this.fibCache.length - 1] < n) {
      const len = this.fibCache.length;
      this.fibCache.push(this.fibCache[len - 1] + this.fibCache[len - 2]);
    }
    // Binary search
    let lo = 0, hi = this.fibCache.length - 1;
    while (lo <= hi) {
      const mid = (lo + hi) >> 1;
      if (this.fibCache[mid] === n) return true;
      if (this.fibCache[mid] < n) lo = mid + 1;
      else hi = mid - 1;
    }
    return false;
  }
 
  async initWebGL() {
    // Create offscreen canvas for WebGL context
    this.canvas = new OffscreenCanvas(this.texWidth, this.texHeight);
    this.gl = this.canvas.getContext('webgl2', {
      alpha: false,
      antialias: false,
      depth: false,
      stencil: false,
      powerPreference: 'high-performance',
      preserveDrawingBuffer: true
    });
 
    if (!this.gl) {
      throw new Error('WebGL2 not available');
    }
 
    const gl = this.gl;
 
    // Required extension for float textures as render targets
    const ext = gl.getExtension('EXT_color_buffer_float');
    if (!ext) {
      throw new Error('EXT_color_buffer_float not available');
    }
 
    // Initialize shaders
    this.initShaders();
 
    // Initialize textures and framebuffers
    this.initPingPongBuffers();
    this.initHierarchyBuffers();
 
    // Initialize full-screen quad
    this.initQuad();
 
    // Initialize state texture with starting values
    this.initStateTexture();
  }
 
  initShaders() {
    const gl = this.gl;
 
    // Vertex shader (shared by all passes)
    const vsSource = `#version 300 es
      in vec2 a_position;
      out vec2 v_texCoord;
      void main() {
        gl_Position = vec4(a_position, 0.0, 1.0);
        v_texCoord = (a_position + 1.0) * 0.5;
      }
    `;
 
    // Fragment shader for Mandelbrot iteration with convergence detection
    // Uses MRT: output 0 = state (zr, zi, iter, status)
    //           output 1 = checkpoint (checkpoint_zr, checkpoint_zi, period, reserved)
    const fsIterSource = `#version 300 es
      precision highp float;
 
      uniform sampler2D u_state;
      uniform sampler2D u_checkpoint;
      uniform vec2 u_resolution;
      uniform vec2 u_cMin;
      uniform vec2 u_cMax;
      uniform int u_iterations;
      uniform float u_escapeRadius;
      uniform int u_exponent;
      uniform float u_epsilon;      // Final convergence threshold
      uniform float u_epsilon2;     // "Getting close" threshold
      uniform int u_startIter;      // Global iteration at batch start
      // Fibonacci info for checkpoint updates
      uniform int u_fibPrev;        // Previous Fibonacci number <= startIter
      uniform int u_fibCurr;        // Current Fibonacci number > startIter
 
      in vec2 v_texCoord;
      layout(location = 0) out vec4 outState;
      layout(location = 1) out vec4 outCheckpoint;
 
      void main() {
        vec4 state = texture(u_state, v_texCoord);
        vec4 checkpoint = texture(u_checkpoint, v_texCoord);
 
        float zr = state.r;
        float zi = state.g;
        float iter = state.b;
        float pixelIndex = state.a;  // Grid index (static)
 
        float cp_zr = checkpoint.r;
        float cp_zi = checkpoint.g;
        float period = checkpoint.b;
        float status = checkpoint.a;  // 0=active, 1=escaped, 2=converged, 4=precomputed (skip)
 
        // c from pixel position
        vec2 c = mix(u_cMin, u_cMax, v_texCoord);
 
        // Track Fibonacci for checkpoint updates
        int fibPrev = u_fibPrev;
        int fibCurr = u_fibCurr;
 
        if (status == 0.0) {  // Active pixel
          for (int i = 0; i < 327680; i++) {  // Max iterations per draw call
            if (i >= u_iterations) break;
 
            int globalIter = u_startIter + i + 1;
 
            // z = z^n + c (support exponent 2-5)
            float zr2, zi2;
            if (u_exponent == 2) {
              zr2 = zr * zr - zi * zi + c.x;
              zi2 = 2.0 * zr * zi + c.y;
            } else if (u_exponent == 3) {
              float zr_sq = zr * zr;
              float zi_sq = zi * zi;
              zr2 = zr * (zr_sq - 3.0 * zi_sq) + c.x;
              zi2 = zi * (3.0 * zr_sq - zi_sq) + c.y;
            } else if (u_exponent == 4) {
              float zr_sq = zr * zr;
              float zi_sq = zi * zi;
              float zr_4 = zr_sq * zr_sq;
              float zi_4 = zi_sq * zi_sq;
              zr2 = zr_4 - 6.0 * zr_sq * zi_sq + zi_4 + c.x;
              zi2 = 4.0 * zr * zi * (zr_sq - zi_sq) + c.y;
            } else {
              // Fallback for exponent 5+
              float r = sqrt(zr * zr + zi * zi);
              float theta = atan(zi, zr);
              float rn = pow(r, float(u_exponent));
              float ntheta = float(u_exponent) * theta;
              zr2 = rn * cos(ntheta) + c.x;
              zi2 = rn * sin(ntheta) + c.y;
            }
 
            zr = zr2;
            zi = zi2;
            iter += 1.0;
 
            // Check for escape
            if (zr * zr + zi * zi > u_escapeRadius) {
              status = 1.0;  // Escaped
              break;
            }
 
            // Check for Fibonacci checkpoint update
            if (globalIter == fibCurr) {
              // Update checkpoint: save current z, reset period
              cp_zr = zr;
              cp_zi = zi;
              period = 0.0;
              // Advance Fibonacci sequence
              int nextFib = fibPrev + fibCurr;
              fibPrev = fibCurr;
              fibCurr = nextFib;
              // Skip convergence check this iteration - checkpoint was just set
              // (z == checkpoint trivially when we just set checkpoint = z)
            } else {
              // Check for convergence (compare to checkpoint)
              float dist = abs(zr - cp_zr) + abs(zi - cp_zi);
              if (dist <= u_epsilon2) {
                // Getting close - record period if not already set
                if (period == 0.0) {
                  period = iter;
                }
                if (dist <= u_epsilon) {
                  // Converged!
                  status = 2.0;
                  break;
                }
              }
            }
          }
        }
 
        outState = vec4(zr, zi, iter, pixelIndex);
        outCheckpoint = vec4(cp_zr, cp_zi, period, status);
      }
    `;
 
    // Fragment shader for Level 0 → Level 1 reduction (tile summary)
    // Tracks both escaped (status=1) and converged (status=2) pixels
    // Status is now in checkpoint.a (not state.a)
    const fsReduction1Source = `#version 300 es
      precision highp float;
 
      uniform sampler2D u_checkpoint;
      uniform sampler2D u_prevTiles;
      uniform vec2 u_stateSize;
      uniform vec2 u_tileSize;
 
      in vec2 v_texCoord;
      out vec4 tileInfo;
 
      void main() {
        ivec2 tileCoord = ivec2(gl_FragCoord.xy);
        ivec2 basePixel = tileCoord * 16;
 
        float finishedCount = 0.0;  // Both escaped and converged
        float hasFinished = 0.0;
 
        // Sample all 256 pixels in this 16x16 tile
        for (int dy = 0; dy < 16; dy++) {
          for (int dx = 0; dx < 16; dx++) {
            ivec2 pixel = basePixel + ivec2(dx, dy);
            if (pixel.x < int(u_stateSize.x) && pixel.y < int(u_stateSize.y)) {
              vec4 checkpoint = texelFetch(u_checkpoint, pixel, 0);
              if (checkpoint.a > 0.0) {  // Escaped (1.0) or Converged (2.0)
                finishedCount += 1.0;
                hasFinished = 1.0;
              }
            }
          }
        }
 
        // Compare with previous count to find newly finished
        vec4 prev = texelFetch(u_prevTiles, tileCoord, 0);
        float newlyFinished = finishedCount - prev.r;
 
        tileInfo = vec4(finishedCount, newlyFinished, 0.0, hasFinished);
      }
    `;
 
    // Fragment shader for Level 1 → Level 2 reduction (super-tile summary)
    const fsReduction2Source = `#version 300 es
      precision highp float;
 
      uniform sampler2D u_tiles;
      uniform vec2 u_tilesSize;
 
      in vec2 v_texCoord;
      out vec4 superTileInfo;
 
      void main() {
        ivec2 superCoord = ivec2(gl_FragCoord.xy);
        ivec2 baseTile = superCoord * 16;
 
        float totalFinished = 0.0;
        float totalNew = 0.0;
        float hasFinished = 0.0;
 
        // Sample all 256 tiles in this 16x16 super-tile
        for (int dy = 0; dy < 16; dy++) {
          for (int dx = 0; dx < 16; dx++) {
            ivec2 tile = baseTile + ivec2(dx, dy);
            if (tile.x < int(u_tilesSize.x) && tile.y < int(u_tilesSize.y)) {
              vec4 tileData = texelFetch(u_tiles, tile, 0);
              totalFinished += tileData.r;
              totalNew += tileData.g;
              if (tileData.a > 0.0) hasFinished = 1.0;
            }
          }
        }
 
        superTileInfo = vec4(totalFinished, totalNew, 0.0, hasFinished);
      }
    `;
 
    // Compile shaders
    this.iterProgram = this.compileProgram(vsSource, fsIterSource);
    this.reduction1Program = this.compileProgram(vsSource, fsReduction1Source);
    this.reduction2Program = this.compileProgram(vsSource, fsReduction2Source);
 
    // Cache uniform locations
    this.cacheIterUniforms();
    this.cacheReductionUniforms();
  }
 
  compileProgram(vsSource, fsSource) {
    const gl = this.gl;
 
    const vs = gl.createShader(gl.VERTEX_SHADER);
    gl.shaderSource(vs, vsSource);
    gl.compileShader(vs);
    if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) {
      throw new Error('Vertex shader compile error: ' + gl.getShaderInfoLog(vs));
    }
 
    const fs = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(fs, fsSource);
    gl.compileShader(fs);
    if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
      throw new Error('Fragment shader compile error: ' + gl.getShaderInfoLog(fs));
    }
 
    const program = gl.createProgram();
    gl.attachShader(program, vs);
    gl.attachShader(program, fs);
    gl.linkProgram(program);
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
      throw new Error('Program link error: ' + gl.getProgramInfoLog(program));
    }
 
    gl.deleteShader(vs);
    gl.deleteShader(fs);
 
    return program;
  }
 
  cacheIterUniforms() {
    const gl = this.gl;
    gl.useProgram(this.iterProgram);
    this.iterUniforms = {
      u_state: gl.getUniformLocation(this.iterProgram, 'u_state'),
      u_checkpoint: gl.getUniformLocation(this.iterProgram, 'u_checkpoint'),
      u_resolution: gl.getUniformLocation(this.iterProgram, 'u_resolution'),
      u_cMin: gl.getUniformLocation(this.iterProgram, 'u_cMin'),
      u_cMax: gl.getUniformLocation(this.iterProgram, 'u_cMax'),
      u_iterations: gl.getUniformLocation(this.iterProgram, 'u_iterations'),
      u_escapeRadius: gl.getUniformLocation(this.iterProgram, 'u_escapeRadius'),
      u_exponent: gl.getUniformLocation(this.iterProgram, 'u_exponent'),
      u_epsilon: gl.getUniformLocation(this.iterProgram, 'u_epsilon'),
      u_epsilon2: gl.getUniformLocation(this.iterProgram, 'u_epsilon2'),
      u_startIter: gl.getUniformLocation(this.iterProgram, 'u_startIter'),
      u_fibPrev: gl.getUniformLocation(this.iterProgram, 'u_fibPrev'),
      u_fibCurr: gl.getUniformLocation(this.iterProgram, 'u_fibCurr')
    };
  }
 
  cacheReductionUniforms() {
    const gl = this.gl;
 
    gl.useProgram(this.reduction1Program);
    this.reduction1Uniforms = {
      u_checkpoint: gl.getUniformLocation(this.reduction1Program, 'u_checkpoint'),
      u_prevTiles: gl.getUniformLocation(this.reduction1Program, 'u_prevTiles'),
      u_stateSize: gl.getUniformLocation(this.reduction1Program, 'u_stateSize'),
      u_tileSize: gl.getUniformLocation(this.reduction1Program, 'u_tileSize')
    };
 
    gl.useProgram(this.reduction2Program);
    this.reduction2Uniforms = {
      u_tiles: gl.getUniformLocation(this.reduction2Program, 'u_tiles'),
      u_tilesSize: gl.getUniformLocation(this.reduction2Program, 'u_tilesSize')
    };
  }
 
  createTexture(width, height, internalFormat = null) {
    const gl = this.gl;
    internalFormat = internalFormat || gl.RGBA32F;
 
    const tex = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, tex);
    gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, width, height, 0, gl.RGBA, gl.FLOAT, null);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    return tex;
  }
 
  createFramebuffer(texture) {
    const gl = this.gl;
    const fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
 
    const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
    if (status !== gl.FRAMEBUFFER_COMPLETE) {
      throw new Error('Framebuffer incomplete: ' + status);
    }
 
    return fb;
  }
 
  initPingPongBuffers() {
    const gl = this.gl;
 
    // Create state and checkpoint textures for ping-pong
    this.pingStateTex = this.createTexture(this.texWidth, this.texHeight);
    this.pingCheckpointTex = this.createTexture(this.texWidth, this.texHeight);
    this.pongStateTex = this.createTexture(this.texWidth, this.texHeight);
    this.pongCheckpointTex = this.createTexture(this.texWidth, this.texHeight);
 
    // Create MRT framebuffers (2 color attachments each)
    this.pingFB = this.createMRTFramebuffer(this.pingStateTex, this.pingCheckpointTex);
    this.pongFB = this.createMRTFramebuffer(this.pongStateTex, this.pongCheckpointTex);
 
    // Start with ping as read, pong as write
    this.isPingRead = true;
  }
 
  createMRTFramebuffer(stateTex, checkpointTex) {
    const gl = this.gl;
    const fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
 
    // Attach state texture to COLOR_ATTACHMENT0
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, stateTex, 0);
    // Attach checkpoint texture to COLOR_ATTACHMENT1
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.TEXTURE_2D, checkpointTex, 0);
 
    // Enable both attachments for MRT
    gl.drawBuffers([gl.COLOR_ATTACHMENT0, gl.COLOR_ATTACHMENT1]);
 
    const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
    if (status !== gl.FRAMEBUFFER_COMPLETE) {
      throw new Error('MRT Framebuffer incomplete: ' + status);
    }
 
    return fb;
  }
 
  initHierarchyBuffers() {
    // Level 1: tile summaries
    this.level1Tex = this.createTexture(this.level1Width, this.level1Height);
    this.prevLevel1Tex = this.createTexture(this.level1Width, this.level1Height);
    this.level1FB = this.createFramebuffer(this.level1Tex);
    this.prevLevel1FB = this.createFramebuffer(this.prevLevel1Tex);
 
    // Level 2: super-tile summaries
    this.level2Tex = this.createTexture(this.level2Width, this.level2Height);
    this.level2FB = this.createFramebuffer(this.level2Tex);
 
    // Clear BOTH level1 textures to avoid garbage values after swap
    const gl = this.gl;
    gl.clearColor(0, 0, 0, 0);
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level1FB);
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.prevLevel1FB);
    gl.clear(gl.COLOR_BUFFER_BIT);
  }
 
  initQuad() {
    const gl = this.gl;
 
    // Full-screen quad vertices
    const positions = new Float32Array([
      -1, -1,  1, -1,  -1, 1,
      -1,  1,  1, -1,   1, 1
    ]);
 
    this.quadVAO = gl.createVertexArray();
    gl.bindVertexArray(this.quadVAO);
 
    const posBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, posBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
 
    const posLoc = gl.getAttribLocation(this.iterProgram, 'a_position');
    gl.enableVertexAttribArray(posLoc);
    gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
 
    gl.bindVertexArray(null);
  }
 
  initStateTexture() {
    const gl = this.gl;
    const sizeScalar = this.size;
    const reDD = qdToDD(this.re);
    const imDD = qdToDD(this.im);
 
    // Calculate complex plane bounds
    const halfWidth = sizeScalar / 2;
    const halfHeight = halfWidth / this.config.aspectRatio;
    this.cMinRe = reDD[0] - halfWidth;
    this.cMaxRe = reDD[0] + halfWidth;
    this.cMinIm = imDD[0] - halfHeight;
    this.cMaxIm = imDD[0] + halfHeight;
 
    // Initialize state texture: z=0, iter=0, index=gridIndex
    // State layout: (zr, zi, iter, index) - index is the View's grid index
    // WebGL y=0 is at bottom, but View y=0 is at top, so flip Y
    const stateData = new Float32Array(this.texWidth * this.texHeight * 4);
    // Set grid index in state.a for each pixel
    for (let texY = 0; texY < this.texHeight; texY++) {
      for (let x = 0; x < this.texWidth; x++) {
        const texOffset = (texY * this.texWidth + x) * 4;
        // Flip Y: texture y=0 (bottom) -> grid y=height-1, texture y=height-1 (top) -> grid y=0
        const gridY = this.texHeight - 1 - texY;
        const gridIndex = gridY * this.texWidth + x;
        // stateData[texOffset + 0] = 0;  // zr = 0
        // stateData[texOffset + 1] = 0;  // zi = 0
        // stateData[texOffset + 2] = 0;  // iter = 0
        stateData[texOffset + 3] = gridIndex;  // index = View's grid index
      }
    }
 
    gl.bindTexture(gl.TEXTURE_2D, this.pingStateTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.texWidth, this.texHeight,
                     gl.RGBA, gl.FLOAT, stateData);
 
    // Initialize checkpoint texture with sentinel values
    // Checkpoint layout: (checkpoint_zr, checkpoint_zi, period, status)
    // checkpoint_z must be far from any valid z value to prevent false convergence
    // on the first iterations (before the first Fibonacci checkpoint is set)
    // status: 0=active, 1=escaped, 2=converged, 4=precomputed
    const checkpointData = new Float32Array(this.texWidth * this.texHeight * 4);
    // Fast initialization: build pattern then copy with doubling
    const sentinel = 1e30;
    // Start with one pixel pattern
    checkpointData[0] = sentinel;  // checkpoint_zr
    checkpointData[1] = sentinel;  // checkpoint_zi
    // checkpointData[2] = 0;      // period = 0
    // checkpointData[3] = 0;      // status = 0 (active)
    // Copy doubling: 1->2->4->8->... pixels at a time
    let filled = 4;  // 1 pixel = 4 floats
    while (filled < checkpointData.length) {
      const copyLen = Math.min(filled, checkpointData.length - filled);
      checkpointData.copyWithin(filled, 0, copyLen);
      filled += copyLen;
    }
 
    // Mark precomputed pixels with status=4 (and mark them as reported)
    // These pixels won't be computed by the GPU and will be flushed separately
    if (this.precomputed) {
      const precomputedCount = this.precomputed.getPrecomputedCount();
      if (precomputedCount > 0) {
        const pp = this.precomputed;
        // Iterate through all precomputed pixels
        for (const [iter, range] of pp.rangeMap) {
          // Mark diverged pixels
          for (let i = 0; i < range.dCount; i++) {
            const gridIndex = pp.dIndices[range.dStart + i];
            // Convert grid index to texture offset (flip Y)
            const gridY = Math.floor(gridIndex / this.texWidth);
            const gridX = gridIndex % this.texWidth;
            const texY = this.texHeight - 1 - gridY;
            const texOffset = (texY * this.texWidth + gridX) * 4;
            checkpointData[texOffset + 3] = 4.0;  // status = precomputed
            this.reported[gridIndex] = 1;  // Mark as reported so we don't read it back
          }
          // Mark converged pixels
          for (let i = 0; i < range.cCount; i++) {
            const gridIndex = pp.cIndices[range.cStart + i];
            const gridY = Math.floor(gridIndex / this.texWidth);
            const gridX = gridIndex % this.texWidth;
            const texY = this.texHeight - 1 - gridY;
            const texOffset = (texY * this.texWidth + gridX) * 4;
            checkpointData[texOffset + 3] = 4.0;  // status = precomputed
            this.reported[gridIndex] = 1;  // Mark as reported
          }
        }
        // Note: don't adjust un here - it will be decremented by flushUpToIteration
        // when precomputed points are flushed, which properly updates di/un together
      }
    }
 
    // Initialize BOTH ping and pong checkpoint textures with the same data
    // This ensures precomputed pixels have status=4 regardless of which buffer is read first
    gl.bindTexture(gl.TEXTURE_2D, this.pingCheckpointTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.texWidth, this.texHeight,
                     gl.RGBA, gl.FLOAT, checkpointData);
    gl.bindTexture(gl.TEXTURE_2D, this.pongCheckpointTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.texWidth, this.texHeight,
                     gl.RGBA, gl.FLOAT, checkpointData);
 
    // Also initialize both state textures with pixel indices
    gl.bindTexture(gl.TEXTURE_2D, this.pongStateTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.texWidth, this.texHeight,
                     gl.RGBA, gl.FLOAT, stateData);
  }
 
  swapPingPong() {
    this.isPingRead = !this.isPingRead;
  }
 
  // Helper to get current read textures
  getReadTextures() {
    return this.isPingRead
      ? { state: this.pingStateTex, checkpoint: this.pingCheckpointTex }
      : { state: this.pongStateTex, checkpoint: this.pongCheckpointTex };
  }
 
  // Helper to get current write framebuffer
  getWriteFB() {
    return this.isPingRead ? this.pongFB : this.pingFB;
  }
 
  // Main entry point for scheduler - matches GpuBoard interface
  async iterate(targetIters = null) {
    // Wait for WebGL initialization
    await this.glInitPromise;
 
    // Process any pending readback from previous iteration
    // This blocks until complete, but allows OTHER boards to work in parallel
    this.waitForPendingReadback();
 
    if (this.un <= 0) return;
 
    // Calculate iterations based on effort if not specified
    if (targetIters === null) {
      const pixels = this.texWidth * this.texHeight;
      const effort = Math.max(this.effort, 1);
      targetIters = Math.max(1, Math.floor(100000 / (pixels * effort)));
    }
 
    // Run GPU iterations
    this.doGpuIterations(targetIters);
 
    // Store end iteration for precomputed flushing when readback completes
    this.pendingBatchEndIter = this.it;
 
    // Start async readback - results processed at start of next iterate()
    this.startAsyncReadback();
  }
 
  // Start async readback using PBO
  // The PBO read is async - GPU copies data in background
  // getBufferSubData() will block until complete
  startAsyncReadback() {
    const gl = this.gl;
 
    // Run reduction passes
    this.runReductionPasses();
 
    // Use ping-pong PBOs
    const pboIndex = this.currentPBOIndex;
    this.currentPBOIndex = 1 - this.currentPBOIndex;
 
    // Create PBO if not exists
    if (!this.level2PBOs[pboIndex]) {
      this.level2PBOs[pboIndex] = gl.createBuffer();
      this.level2Size = this.level2Width * this.level2Height * 4 * 4; // RGBA float
      gl.bindBuffer(gl.PIXEL_PACK_BUFFER, this.level2PBOs[pboIndex]);
      gl.bufferData(gl.PIXEL_PACK_BUFFER, this.level2Size, gl.STREAM_READ);
    }
 
    // Async read level2 into PBO
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level2FB);
    gl.bindBuffer(gl.PIXEL_PACK_BUFFER, this.level2PBOs[pboIndex]);
    gl.readPixels(0, 0, this.level2Width, this.level2Height, gl.RGBA, gl.FLOAT, 0);
    gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
 
    // Create fence sync to wait for GPU completion before reading
    const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
    gl.flush();
 
    // Store pending PBO index and sync object
    this.pendingReadback = { pboIndex, sync };
  }
 
  // Wait for pending readback to complete
  waitForPendingReadback() {
    const gl = this.gl;
    const pending = this.pendingReadback;
 
    if (!pending) return;
 
    const pbo = this.level2PBOs[pending.pboIndex];
    if (!pbo) {
      // PBO was never created or was lost - skip this readback
      if (pending.sync) gl.deleteSync(pending.sync);
      this.pendingReadback = null;
      this.pendingBatchEndIter = null;
      return;
    }
 
    const batchEndIter = this.pendingBatchEndIter;
    this.pendingReadback = null;
    this.pendingBatchEndIter = null;
 
    // Wait for fence sync to complete before reading (avoids pipeline stall warning)
    if (pending.sync) {
      gl.clientWaitSync(pending.sync, 0, 0);  // Don't actually wait, just signal intent
      gl.deleteSync(pending.sync);
    }
 
    // getBufferSubData() reads data after sync is signaled
    const level2Data = new Float32Array(this.level2Width * this.level2Height * 4);
    gl.bindBuffer(gl.PIXEL_PACK_BUFFER, pbo);
    gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, level2Data);
    gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
 
    // Process level2 data (queues GPU results)
    this.processLevel2Results(level2Data);
 
    // Flush precomputed points for this batch's iteration range
    // This ensures precomputed and GPU results go in the same message
    if (this.precomputed && batchEndIter) {
      this.precomputed.flushUpToIteration(batchEndIter, this);
    }
  }
 
  // Process level2 results and trigger hierarchical readback if needed
  processLevel2Results(superTiles) {
    const gl = this.gl;
    const totalPixels = this.texWidth * this.texHeight;
 
    // Find super-tiles with new escapes
    const activeSuperTiles = [];
    let totalNew = 0;
    for (let sy = 0; sy < this.level2Height; sy++) {
      for (let sx = 0; sx < this.level2Width; sx++) {
        const idx = (sy * this.level2Width + sx) * 4;
        const newlyEscaped = superTiles[idx + 1];
        if (newlyEscaped > 0) {
          activeSuperTiles.push({ x: sx, y: sy, count: newlyEscaped });
          totalNew += newlyEscaped;
        }
      }
    }
 
    // Track cumulative escapes and update tile mask when >10% since last update
    this.escapedSinceUpdate += totalNew;
    if (this.escapedSinceUpdate > totalPixels * 0.10) {
      this.updateActiveTileMask();
      this.escapedSinceUpdate = 0;
    }
 
    if (activeSuperTiles.length === 0) {
      // No new escapes - swap buffers and return
      this.swapLevel1Buffers();
      return;
    }
 
    // Adaptive: if >10% escapes, just read full texture
    if (totalNew > totalPixels * 0.1) {
      this.readFullTexture();
      return;
    }
 
    // Hierarchical read
    this.readHierarchical(activeSuperTiles);
  }
 
  // Find Fibonacci numbers around a given iteration
  // Returns { prev, curr } where prev <= iter < curr
  getFibonacciBounds(iter) {
    // Extend cache if needed
    while (this.fibCache[this.fibCache.length - 1] <= iter) {
      const len = this.fibCache.length;
      this.fibCache.push(this.fibCache[len - 1] + this.fibCache[len - 2]);
    }
    // Find the first Fibonacci > iter
    let i = 0;
    while (this.fibCache[i] <= iter) i++;
    return {
      prev: i > 0 ? this.fibCache[i - 1] : 1,
      curr: this.fibCache[i]
    };
  }
 
  // Queue n iterations (non-blocking - driver pipelines internally)
  // Batches up to 327680 iterations per draw call (shader loop limit)
  // Uses tile-based dispatch when many tiles are inactive
  doGpuIterations(n) {
    const gl = this.gl;
    const MAX_SHADER_ITERS = 327680;  // Shader's internal loop limit
    const TILE_SIZE = GlBoard.TILE_SIZE;
    const totalTiles = this.level1Width * this.level1Height;
 
    // Decide whether to use tile dispatch
    // Use tiles if <30% tiles active (overhead of many draws vs savings)
    const useTiles = this.useTileDispatch && this.activeTileCount < totalTiles * 0.3;
 
    gl.useProgram(this.iterProgram);
    gl.bindVertexArray(this.quadVAO);
 
    // Set static uniforms
    gl.uniform2f(this.iterUniforms.u_resolution, this.texWidth, this.texHeight);
    gl.uniform2f(this.iterUniforms.u_cMin, this.cMinRe, this.cMinIm);
    gl.uniform2f(this.iterUniforms.u_cMax, this.cMaxRe, this.cMaxIm);
    gl.uniform1f(this.iterUniforms.u_escapeRadius, 4.0);
    gl.uniform1i(this.iterUniforms.u_exponent, this.config.exponent);
    gl.uniform1f(this.iterUniforms.u_epsilon, this.epsilon);
    gl.uniform1f(this.iterUniforms.u_epsilon2, this.epsilon2);
 
    // Enable scissor test for tile-based dispatch
    if (useTiles) {
      gl.enable(gl.SCISSOR_TEST);
    }
 
    // Batch iterations - shader handles up to 327680 per draw call
    let remaining = n;
    while (remaining > 0) {
      const batchSize = Math.min(remaining, MAX_SHADER_ITERS);
      const startIter = this.it;
      const { prev: fibPrev, curr: fibCurr } = this.getFibonacciBounds(startIter);
 
      // Set per-batch uniforms
      gl.uniform1i(this.iterUniforms.u_startIter, startIter);
      gl.uniform1i(this.iterUniforms.u_fibPrev, fibPrev);
      gl.uniform1i(this.iterUniforms.u_fibCurr, fibCurr);
      gl.uniform1i(this.iterUniforms.u_iterations, batchSize);
 
      // Get current read textures
      const readTextures = this.getReadTextures();
 
      // Bind state texture to TEXTURE0
      gl.activeTexture(gl.TEXTURE0);
      gl.bindTexture(gl.TEXTURE_2D, readTextures.state);
      gl.uniform1i(this.iterUniforms.u_state, 0);
 
      // Bind checkpoint texture to TEXTURE1
      gl.activeTexture(gl.TEXTURE1);
      gl.bindTexture(gl.TEXTURE_2D, readTextures.checkpoint);
      gl.uniform1i(this.iterUniforms.u_checkpoint, 1);
 
      // Bind write framebuffer (MRT with both state and checkpoint attachments)
      gl.bindFramebuffer(gl.FRAMEBUFFER, this.getWriteFB());
      gl.viewport(0, 0, this.texWidth, this.texHeight);
 
      if (useTiles) {
        // Tile-based dispatch: only render active tiles using scissor
        for (let ty = 0; ty < this.level1Height; ty++) {
          for (let tx = 0; tx < this.level1Width; tx++) {
            const tileIdx = ty * this.level1Width + tx;
            if (this.activeTileMask[tileIdx]) {
              const x = tx * TILE_SIZE;
              const y = ty * TILE_SIZE;
              const w = Math.min(TILE_SIZE, this.texWidth - x);
              const h = Math.min(TILE_SIZE, this.texHeight - y);
              gl.scissor(x, y, w, h);
              gl.drawArrays(gl.TRIANGLES, 0, 6);
            }
          }
        }
      } else {
        // Full-screen dispatch
        gl.drawArrays(gl.TRIANGLES, 0, 6);
      }
 
      // Swap and advance
      this.swapPingPong();
      this.it += batchSize;
      remaining -= batchSize;
    }
 
    if (useTiles) {
      gl.disable(gl.SCISSOR_TEST);
    }
    gl.bindVertexArray(null);
  }
 
  // Run reduction passes (GPU-side, pipelined)
  runReductionPasses() {
    const gl = this.gl;
    const readTextures = this.getReadTextures();
 
    // Pass 1: State → Level 1
    gl.useProgram(this.reduction1Program);
    gl.bindVertexArray(this.quadVAO);
 
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, readTextures.checkpoint);
    gl.uniform1i(this.reduction1Uniforms.u_checkpoint, 0);
 
    gl.activeTexture(gl.TEXTURE1);
    gl.bindTexture(gl.TEXTURE_2D, this.prevLevel1Tex);
    gl.uniform1i(this.reduction1Uniforms.u_prevTiles, 1);
 
    gl.uniform2f(this.reduction1Uniforms.u_stateSize, this.texWidth, this.texHeight);
    gl.uniform2f(this.reduction1Uniforms.u_tileSize, GlBoard.TILE_SIZE, GlBoard.TILE_SIZE);
 
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level1FB);
    gl.viewport(0, 0, this.level1Width, this.level1Height);
    gl.drawArrays(gl.TRIANGLES, 0, 6);
 
    // Pass 2: Level 1 → Level 2
    gl.useProgram(this.reduction2Program);
 
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, this.level1Tex);
    gl.uniform1i(this.reduction2Uniforms.u_tiles, 0);
 
    gl.uniform2f(this.reduction2Uniforms.u_tilesSize, this.level1Width, this.level1Height);
 
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level2FB);
    gl.viewport(0, 0, this.level2Width, this.level2Height);
    gl.drawArrays(gl.TRIANGLES, 0, 6);
 
    gl.bindVertexArray(null);
  }
 
  // Update active tile mask based on level1 reduction data
  // Called periodically to track which tiles are fully finished
  updateActiveTileMask() {
    const gl = this.gl;
    const TILE_SIZE = GlBoard.TILE_SIZE;
    const PIXELS_PER_TILE = TILE_SIZE * TILE_SIZE;  // 256
 
    // Read level1 texture to get per-tile finished counts
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level1FB);
    const level1Data = new Float32Array(this.level1Width * this.level1Height * 4);
    gl.readPixels(0, 0, this.level1Width, this.level1Height, gl.RGBA, gl.FLOAT, level1Data);
 
    // Update active tile mask
    let newActiveCount = 0;
    for (let ty = 0; ty < this.level1Height; ty++) {
      for (let tx = 0; tx < this.level1Width; tx++) {
        const tileIdx = ty * this.level1Width + tx;
        const dataIdx = tileIdx * 4;
        const finishedCount = level1Data[dataIdx];  // .r = finished count
 
        // Calculate expected pixels in this tile (edge tiles may be smaller)
        const tileW = Math.min(TILE_SIZE, this.texWidth - tx * TILE_SIZE);
        const tileH = Math.min(TILE_SIZE, this.texHeight - ty * TILE_SIZE);
        const tilePixels = tileW * tileH;
 
        // Tile is inactive if all pixels are finished
        if (finishedCount >= tilePixels) {
          this.activeTileMask[tileIdx] = 0;
        } else {
          this.activeTileMask[tileIdx] = 1;
          newActiveCount++;
        }
      }
    }
 
    this.activeTileCount = newActiveCount;
    this.useTileDispatch = true;  // Enable tile dispatch after first update
  }
 
  // LEGACY: Synchronous readback (replaced by async PBO pipeline)
  // Kept for reference - use startAsyncReadback() + processPendingReadback() instead
  readResultsSync() {
    const gl = this.gl;
 
    // Run reduction passes
    this.runReductionPasses();
 
    // Read Level 2 (tiny - always read all)
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level2FB);
    const superTiles = new Float32Array(this.level2Width * this.level2Height * 4);
    gl.readPixels(0, 0, this.level2Width, this.level2Height, gl.RGBA, gl.FLOAT, superTiles);
 
    // Find super-tiles with new escapes
    const activeSuperTiles = [];
    let totalNew = 0;
    for (let sy = 0; sy < this.level2Height; sy++) {
      for (let sx = 0; sx < this.level2Width; sx++) {
        const idx = (sy * this.level2Width + sx) * 4;
        const newlyEscaped = superTiles[idx + 1];
        if (newlyEscaped > 0) {
          activeSuperTiles.push({ x: sx, y: sy, count: newlyEscaped });
          totalNew += newlyEscaped;
        }
      }
    }
 
    // Track cumulative escapes and update tile mask when >10% since last update
    const totalPixels = this.texWidth * this.texHeight;
    this.escapedSinceUpdate += totalNew;
    if (this.escapedSinceUpdate > totalPixels * 0.10) {
      this.updateActiveTileMask();
      this.escapedSinceUpdate = 0;
    }
 
    if (activeSuperTiles.length === 0) {
      // No new escapes - swap buffers and return empty
      this.swapLevel1Buffers();
      return null;
    }
 
    // Adaptive: if >10% escapes, just read full texture
    if (totalNew > totalPixels * 0.1) {
      return this.readFullTexture();
    }
 
    // Hierarchical read
    return this.readHierarchical(activeSuperTiles);
  }
 
  // Create a temporary framebuffer for reading a single texture
  createReadFB(texture) {
    const gl = this.gl;
    const fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
    return fb;
  }
 
  readHierarchical(activeSuperTiles) {
    const gl = this.gl;
 
    // Group results: escaped by iteration, converged separately
    const escapedByIter = new Map();
    const convergedByIter = new Map();
 
    // Read Level 1 for active super-tiles
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level1FB);
    const activeTiles = [];
 
    for (const st of activeSuperTiles) {
      const x0 = st.x * GlBoard.TILE_SIZE;
      const y0 = st.y * GlBoard.TILE_SIZE;
      const w = Math.min(GlBoard.TILE_SIZE, this.level1Width - x0);
      const h = Math.min(GlBoard.TILE_SIZE, this.level1Height - y0);
 
      const tileData = new Float32Array(w * h * 4);
      gl.readPixels(x0, y0, w, h, gl.RGBA, gl.FLOAT, tileData);
 
      for (let ty = 0; ty < h; ty++) {
        for (let tx = 0; tx < w; tx++) {
          const idx = (ty * w + tx) * 4;
          const newlyFinished = tileData[idx + 1];
          if (newlyFinished > 0) {
            activeTiles.push({ x: x0 + tx, y: y0 + ty, count: newlyFinished });
          }
        }
      }
    }
 
    // Get read textures
    const readTextures = this.getReadTextures();
 
    // Create temporary read framebuffers for state and checkpoint
    const stateReadFB = this.createReadFB(readTextures.state);
    const checkpointReadFB = this.createReadFB(readTextures.checkpoint);
 
    // Read both state and checkpoint textures for active tiles
    // State: (zr, zi, iter, index), Checkpoint: (cp_zr, cp_zi, period, status)
    for (const tile of activeTiles) {
      const x0 = tile.x * GlBoard.TILE_SIZE;
      const y0 = tile.y * GlBoard.TILE_SIZE;
      const w = Math.min(GlBoard.TILE_SIZE, this.texWidth - x0);
      const h = Math.min(GlBoard.TILE_SIZE, this.texHeight - y0);
 
      // Read state texture (zr, zi, iter, index)
      gl.bindFramebuffer(gl.FRAMEBUFFER, stateReadFB);
      const statePixels = new Float32Array(w * h * 4);
      gl.readPixels(x0, y0, w, h, gl.RGBA, gl.FLOAT, statePixels);
 
      // Read checkpoint texture (cp_zr, cp_zi, period, status)
      gl.bindFramebuffer(gl.FRAMEBUFFER, checkpointReadFB);
      const checkpointPixels = new Float32Array(w * h * 4);
      gl.readPixels(x0, y0, w, h, gl.RGBA, gl.FLOAT, checkpointPixels);
 
      for (let py = 0; py < h; py++) {
        for (let px = 0; px < w; px++) {
          const localIdx = (py * w + px) * 4;
          const status = checkpointPixels[localIdx + 3];  // status in checkpoint.a
          const pixelIndex = Math.round(statePixels[localIdx + 3]);  // index in state.a
 
          if (this.reported[pixelIndex]) continue;
          if (status === 4.0) continue;  // Precomputed - handled separately
 
          if (status === 1.0) {  // Escaped
            const iter = Math.round(statePixels[localIdx + 2]);
            this.nn[pixelIndex] = iter;
            this.reported[pixelIndex] = 1;
            this.un--;
            this.di++;
 
            if (!escapedByIter.has(iter)) {
              escapedByIter.set(iter, []);
            }
            escapedByIter.get(iter).push(pixelIndex);
          } else if (status === 2.0) {  // Converged
            const iter = Math.round(statePixels[localIdx + 2]);
            const zr = statePixels[localIdx];
            const zi = statePixels[localIdx + 1];
            const period = Math.round(checkpointPixels[localIdx + 2]);
 
            this.nn[pixelIndex] = -iter;  // Negative for converged
            this.reported[pixelIndex] = 1;
            this.un--;
 
            if (!convergedByIter.has(iter)) {
              convergedByIter.set(iter, []);
            }
            convergedByIter.get(iter).push({
              index: pixelIndex,
              z: [zr, zi],
              p: period
            });
          }
        }
      }
    }
 
    // Clean up temporary framebuffers
    gl.deleteFramebuffer(stateReadFB);
    gl.deleteFramebuffer(checkpointReadFB);
 
    // Swap level1 buffers for next "newly finished" tracking
    this.swapLevel1Buffers();
 
    // Queue changes grouped by iteration
    if (escapedByIter.size === 0 && convergedByIter.size === 0) return null;
 
    // Merge and sort by iteration
    const allIters = new Set([...escapedByIter.keys(), ...convergedByIter.keys()]);
    const sortedIters = Array.from(allIters).sort((a, b) => a - b);
 
    for (const iter of sortedIters) {
      const escaped = escapedByIter.get(iter) || [];
      const converged = convergedByIter.get(iter) || [];
      this.queueChanges({ iter, nn: escaped, vv: converged });
    }
 
    return { queued: true };
  }
 
  readFullTexture() {
    const gl = this.gl;
 
    // Group results: escaped by iteration, converged separately
    const escapedByIter = new Map();
    const convergedByIter = new Map();
 
    // Get read textures
    const readTextures = this.getReadTextures();
 
    // Create temporary read framebuffers
    const stateReadFB = this.createReadFB(readTextures.state);
    const checkpointReadFB = this.createReadFB(readTextures.checkpoint);
 
    // Read both full textures
    // State: (zr, zi, iter, index), Checkpoint: (cp_zr, cp_zi, period, status)
    gl.bindFramebuffer(gl.FRAMEBUFFER, stateReadFB);
    const statePixels = new Float32Array(this.texWidth * this.texHeight * 4);
    gl.readPixels(0, 0, this.texWidth, this.texHeight, gl.RGBA, gl.FLOAT, statePixels);
 
    gl.bindFramebuffer(gl.FRAMEBUFFER, checkpointReadFB);
    const checkpointPixels = new Float32Array(this.texWidth * this.texHeight * 4);
    gl.readPixels(0, 0, this.texWidth, this.texHeight, gl.RGBA, gl.FLOAT, checkpointPixels);
 
    for (let i = 0; i < this.texWidth * this.texHeight; i++) {
      const status = checkpointPixels[i * 4 + 3];  // status in checkpoint.a
      const pixelIndex = Math.round(statePixels[i * 4 + 3]);  // index in state.a
 
      if (this.reported[pixelIndex]) continue;
      if (status === 4.0) continue;  // Precomputed - handled separately
 
      if (status === 1.0) {  // Escaped
        const iter = Math.round(statePixels[i * 4 + 2]);
        this.nn[pixelIndex] = iter;
        this.reported[pixelIndex] = 1;
        this.un--;
        this.di++;
 
        if (!escapedByIter.has(iter)) {
          escapedByIter.set(iter, []);
        }
        escapedByIter.get(iter).push(pixelIndex);
      } else if (status === 2.0) {  // Converged
        const iter = Math.round(statePixels[i * 4 + 2]);
        const zr = statePixels[i * 4];
        const zi = statePixels[i * 4 + 1];
        const period = Math.round(checkpointPixels[i * 4 + 2]);
 
        this.nn[pixelIndex] = -iter;  // Negative for converged
        this.reported[pixelIndex] = 1;
        this.un--;
 
        if (!convergedByIter.has(iter)) {
          convergedByIter.set(iter, []);
        }
        convergedByIter.get(iter).push({
          index: pixelIndex,
          z: [zr, zi],
          p: period
        });
      }
    }
 
    // Clean up temporary framebuffers
    gl.deleteFramebuffer(stateReadFB);
    gl.deleteFramebuffer(checkpointReadFB);
 
    // Swap level1 buffers
    this.swapLevel1Buffers();
 
    // Queue changes grouped by iteration
    if (escapedByIter.size === 0 && convergedByIter.size === 0) return null;
 
    // Merge and sort by iteration
    const allIters = new Set([...escapedByIter.keys(), ...convergedByIter.keys()]);
    const sortedIters = Array.from(allIters).sort((a, b) => a - b);
 
    for (const iter of sortedIters) {
      const escaped = escapedByIter.get(iter) || [];
      const converged = convergedByIter.get(iter) || [];
      this.queueChanges({ iter, nn: escaped, vv: converged });
    }
 
    return { queued: true };
  }
 
  swapLevel1Buffers() {
    [this.level1FB, this.prevLevel1FB] = [this.prevLevel1FB, this.level1FB];
    [this.level1Tex, this.prevLevel1Tex] = [this.prevLevel1Tex, this.level1Tex];
  }
 
  // Serialization support
  async serialize() {
    const base = await super.serialize();
    // GlBoard-specific state
    return {
      ...base,
      type: 'GlBoard',
      reported: Array.from(this.reported),
      cMinRe: this.cMinRe,
      cMinIm: this.cMinIm,
      cMaxRe: this.cMaxRe,
      cMaxIm: this.cMaxIm
    };
  }
 
  static fromSerialized(serialized) {
    const board = new GlBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    board.glInitPromise = board.glInitPromise.then(() => {
      board.it = serialized.it;
      board.un = serialized.un;
      board.di = serialized.di;
      board.ch = serialized.ch || 0;
 
      if (serialized.reported) {
        board.reported = new Uint8Array(serialized.reported);
      }
 
      board.cMinRe = serialized.cMinRe;
      board.cMinIm = serialized.cMinIm;
      board.cMaxRe = serialized.cMaxRe;
      board.cMaxIm = serialized.cMaxIm;
 
      // Restore nn array
      board.nn = new Array(serialized.config.dimsArea).fill(0);
      if (serialized.completedIndexes) {
        for (let i = 0; i < serialized.completedIndexes.length; i++) {
          board.nn[serialized.completedIndexes[i]] = serialized.completedNn[i];
        }
      }
    });
 
    return board;
  }
 
  // Check if WebGL2 is available
  static isAvailable() {
    if (typeof OffscreenCanvas === 'undefined') return false;
    try {
      const canvas = new OffscreenCanvas(1, 1);
      const gl = canvas.getContext('webgl2');
      if (!gl) return false;
      const ext = gl.getExtension('EXT_color_buffer_float');
      return !!ext;
    } catch (e) {
      return false;
    }
  }
}
 
// Base class for WebGL2 perturbation boards
// Provides shared WebGL infrastructure for GlZhuoranBoard and GlAdaptiveBoard
class GlPerturbationBaseBoard extends Board {
  static TILE_SIZE = 16;
 
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
    this.effort = 18;
    this.maxBatchIters = 100000;
 
    // WebGL state
    this.gl = null;
    this.canvas = null;
    this.iterProgram = null;
    this.reduction1Program = null;
    this.reduction2Program = null;
 
    // Ping-pong state textures for perturbation
    this.pingStateTex = null;
    this.pingCheckpointTex = null;
    this.pingLazyTex = null;
    this.pongStateTex = null;
    this.pongCheckpointTex = null;
    this.pongLazyTex = null;
    this.pingFB = null;
    this.pongFB = null;
    this.isPingRead = true;
 
    // Delta C texture (constant per pixel)
    this.deltaCTex = null;
 
    // Reference orbit + threading texture
    this.refOrbitTex = null;
    this.refOrbitTexWidth = 2048;
    this.refOrbitTexHeight = 512;
    this.lastUploadedRefIter = 0;
 
    // Hierarchy textures for sparse readback
    this.level1Tex = null;
    this.level1FB = null;
    this.prevLevel1Tex = null;
    this.prevLevel1FB = null;
    this.level2Tex = null;
    this.level2FB = null;
 
    // Dimensions
    this.texWidth = config.dimsWidth;
    this.texHeight = config.dimsHeight;
    this.level1Width = Math.ceil(this.texWidth / GlPerturbationBaseBoard.TILE_SIZE);
    this.level1Height = Math.ceil(this.texHeight / GlPerturbationBaseBoard.TILE_SIZE);
    this.level2Width = Math.ceil(this.level1Width / GlPerturbationBaseBoard.TILE_SIZE);
    this.level2Height = Math.ceil(this.level1Height / GlPerturbationBaseBoard.TILE_SIZE);
 
    // Track reported pixels
    this.reported = new Uint8Array(config.dimsArea);
 
    // Tile-based dispatch
    const totalTiles = this.level1Width * this.level1Height;
    this.activeTileMask = new Uint8Array(totalTiles);
    this.activeTileMask.fill(1);
    this.activeTileCount = totalTiles;
    this.useTileDispatch = false;
    this.escapedSinceUpdate = 0;
 
    // Convergence thresholds
    this.epsilon = this.pix / 10;
    this.epsilon2 = this.pix * 10;
 
    // Fibonacci checkpoints
    this.fibCache = [1, 2];
    this.nextFibIndex = 2;
 
    // Full-screen quad VAO
    this.quadVAO = null;
 
    // Uniform locations
    this.iterUniforms = {};
    this.reduction1Uniforms = {};
    this.reduction2Uniforms = {};
 
    // Async readback
    this.pendingReadback = null;
    this.pendingBatchEndIter = null;
    this.level2PBOs = [null, null];
    this.currentPBOIndex = 0;
 
    // Reference orbit loop (for very deep zoom)
    this.refOrbitLoop = { enabled: false };
    this.refOrbitLoopConfigured = false;
 
    // Per-pixel perturbation data
    this.dc = new Float32Array(config.dimsArea * 2);
    this.dz = new Float32Array(config.dimsArea * 2);
  }
 
  async initGL() {
    this.canvas = new OffscreenCanvas(this.texWidth, this.texHeight);
    this.gl = this.canvas.getContext('webgl2', {
      antialias: false,
      depth: false,
      stencil: false,
      preserveDrawingBuffer: true
    });
 
    const gl = this.gl;
    gl.getExtension('EXT_color_buffer_float');
    gl.getExtension('OES_texture_float_linear');
 
    await this.createShaders();
    this.createTextures();
    this.createQuad();
    this.initializeStateTextures();
    this.uploadDeltaC();
  }
 
  // Vertex shader source (shared by all GL perturbation boards)
  getVertexShaderSource() {
    return `#version 300 es
      in vec2 a_position;
      out vec2 v_texCoord;
      void main() {
        gl_Position = vec4(a_position, 0.0, 1.0);
        v_texCoord = (a_position + 1.0) * 0.5;
      }
    `;
  }
 
  // Reduction shader sources (shared by all GL perturbation boards)
  getReduction1ShaderSource() {
    return `#version 300 es
      precision highp float;
      uniform sampler2D u_state;
      uniform sampler2D u_prevTiles;
      uniform vec2 u_stateSize;
      uniform vec2 u_tileSize;
      in vec2 v_texCoord;
      out vec4 tileInfo;
 
      void main() {
        ivec2 tileCoord = ivec2(gl_FragCoord.xy);
        ivec2 basePixel = tileCoord * 16;
        float finishedCount = 0.0;
        float hasFinished = 0.0;
 
        for (int dy = 0; dy < 16; dy++) {
          for (int dx = 0; dx < 16; dx++) {
            ivec2 pixel = basePixel + ivec2(dx, dy);
            if (pixel.x < int(u_stateSize.x) && pixel.y < int(u_stateSize.y)) {
              vec4 state = texelFetch(u_state, pixel, 0);
              if (state.a > 0.0) {
                finishedCount += 1.0;
                hasFinished = 1.0;
              }
            }
          }
        }
 
        vec4 prev = texelFetch(u_prevTiles, tileCoord, 0);
        float newlyFinished = finishedCount - prev.r;
        tileInfo = vec4(finishedCount, newlyFinished, 0.0, hasFinished);
      }
    `;
  }
 
  getReduction2ShaderSource() {
    return `#version 300 es
      precision highp float;
      uniform sampler2D u_tiles;
      uniform vec2 u_tilesSize;
      in vec2 v_texCoord;
      out vec4 superTileInfo;
 
      void main() {
        ivec2 superCoord = ivec2(gl_FragCoord.xy);
        ivec2 baseTile = superCoord * 16;
        float totalFinished = 0.0;
        float totalNew = 0.0;
        float hasFinished = 0.0;
 
        for (int dy = 0; dy < 16; dy++) {
          for (int dx = 0; dx < 16; dx++) {
            ivec2 tile = baseTile + ivec2(dx, dy);
            if (tile.x < int(u_tilesSize.x) && tile.y < int(u_tilesSize.y)) {
              vec4 tileData = texelFetch(u_tiles, tile, 0);
              totalFinished += tileData.r;
              totalNew += tileData.g;
              if (tileData.a > 0.0) hasFinished = 1.0;
            }
          }
        }
 
        superTileInfo = vec4(totalFinished, totalNew, 0.0, hasFinished);
      }
    `;
  }
 
  // Abstract method - subclasses must implement
  getIterationShaderSource() {
    throw new Error('Subclass must implement getIterationShaderSource()');
  }
 
  async createShaders() {
    const gl = this.gl;
    const vsSource = this.getVertexShaderSource();
    const fsIterSource = this.getIterationShaderSource();
    const fsReduction1Source = this.getReduction1ShaderSource();
    const fsReduction2Source = this.getReduction2ShaderSource();
 
    this.iterProgram = this.compileProgram(vsSource, fsIterSource);
    this.reduction1Program = this.compileProgram(vsSource, fsReduction1Source);
    this.reduction2Program = this.compileProgram(vsSource, fsReduction2Source);
 
    // Cache uniform locations for iteration shader
    gl.useProgram(this.iterProgram);
    this.iterUniforms = {
      u_state: gl.getUniformLocation(this.iterProgram, 'u_state'),
      u_checkpoint: gl.getUniformLocation(this.iterProgram, 'u_checkpoint'),
      u_lazy: gl.getUniformLocation(this.iterProgram, 'u_lazy'),
      u_deltaC: gl.getUniformLocation(this.iterProgram, 'u_deltaC'),
      u_refOrbit: gl.getUniformLocation(this.iterProgram, 'u_refOrbit'),
      u_resolution: gl.getUniformLocation(this.iterProgram, 'u_resolution'),
      u_iterations: gl.getUniformLocation(this.iterProgram, 'u_iterations'),
      u_exponent: gl.getUniformLocation(this.iterProgram, 'u_exponent'),
      u_epsilon: gl.getUniformLocation(this.iterProgram, 'u_epsilon'),
      u_epsilon2: gl.getUniformLocation(this.iterProgram, 'u_epsilon2'),
      u_pixelSize: gl.getUniformLocation(this.iterProgram, 'u_pixelSize'),
      u_startIter: gl.getUniformLocation(this.iterProgram, 'u_startIter'),
      u_refOrbitLength: gl.getUniformLocation(this.iterProgram, 'u_refOrbitLength'),
      u_refOrbitTexWidth: gl.getUniformLocation(this.iterProgram, 'u_refOrbitTexWidth'),
      u_fibPrev: gl.getUniformLocation(this.iterProgram, 'u_fibPrev'),
      u_fibCurr: gl.getUniformLocation(this.iterProgram, 'u_fibCurr'),
      u_loopEnabled: gl.getUniformLocation(this.iterProgram, 'u_loopEnabled'),
      u_loopThreshold: gl.getUniformLocation(this.iterProgram, 'u_loopThreshold'),
      u_loopJump: gl.getUniformLocation(this.iterProgram, 'u_loopJump'),
      u_loopDeltaR: gl.getUniformLocation(this.iterProgram, 'u_loopDeltaR'),
      u_loopDeltaI: gl.getUniformLocation(this.iterProgram, 'u_loopDeltaI'),
    };
 
    gl.useProgram(this.reduction1Program);
    this.reduction1Uniforms = {
      u_state: gl.getUniformLocation(this.reduction1Program, 'u_state'),
      u_prevTiles: gl.getUniformLocation(this.reduction1Program, 'u_prevTiles'),
      u_stateSize: gl.getUniformLocation(this.reduction1Program, 'u_stateSize'),
      u_tileSize: gl.getUniformLocation(this.reduction1Program, 'u_tileSize'),
    };
 
    gl.useProgram(this.reduction2Program);
    this.reduction2Uniforms = {
      u_tiles: gl.getUniformLocation(this.reduction2Program, 'u_tiles'),
      u_tilesSize: gl.getUniformLocation(this.reduction2Program, 'u_tilesSize'),
    };
  }
 
  compileProgram(vsSource, fsSource) {
    const gl = this.gl;
    const vs = gl.createShader(gl.VERTEX_SHADER);
    gl.shaderSource(vs, vsSource);
    gl.compileShader(vs);
    if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS)) {
      throw new Error('Vertex shader: ' + gl.getShaderInfoLog(vs));
    }
 
    const fs = gl.createShader(gl.FRAGMENT_SHADER);
    gl.shaderSource(fs, fsSource);
    gl.compileShader(fs);
    if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
      throw new Error('Fragment shader: ' + gl.getShaderInfoLog(fs));
    }
 
    const program = gl.createProgram();
    gl.attachShader(program, vs);
    gl.attachShader(program, fs);
    gl.linkProgram(program);
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
      throw new Error('Program link: ' + gl.getProgramInfoLog(program));
    }
 
    return program;
  }
 
  createTextures() {
    const gl = this.gl;
 
    // Create ping-pong state textures
    this.pingStateTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pingCheckpointTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pingLazyTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pongStateTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pongCheckpointTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pongLazyTex = this.createFloatTexture(this.texWidth, this.texHeight);
 
    // Delta C texture (constant)
    this.deltaCTex = this.createFloatTexture(this.texWidth, this.texHeight);
 
    // Reference orbit texture
    this.refOrbitTex = this.createFloatTexture(this.refOrbitTexWidth, this.refOrbitTexHeight);
 
    // Create framebuffers with MRT for ping-pong
    // pingFB writes to ping textures, pongFB writes to pong textures
    this.pingFB = this.createMRTFramebuffer(this.pingStateTex, this.pingCheckpointTex, this.pingLazyTex);
    this.pongFB = this.createMRTFramebuffer(this.pongStateTex, this.pongCheckpointTex, this.pongLazyTex);
 
    // Hierarchy textures
    this.level1Tex = this.createFloatTexture(this.level1Width, this.level1Height);
    this.level1FB = this.createFramebuffer(this.level1Tex);
    this.prevLevel1Tex = this.createFloatTexture(this.level1Width, this.level1Height);
    this.prevLevel1FB = this.createFramebuffer(this.prevLevel1Tex);
    this.level2Tex = this.createFloatTexture(this.level2Width, this.level2Height);
    this.level2FB = this.createFramebuffer(this.level2Tex);
 
    // Initialize prevLevel1 to zeros
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.prevLevel1FB);
    gl.viewport(0, 0, this.level1Width, this.level1Height);
    gl.clearColor(0, 0, 0, 0);
    gl.clear(gl.COLOR_BUFFER_BIT);
  }
 
  createFloatTexture(width, height) {
    const gl = this.gl;
    const tex = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, tex);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, width, height, 0, gl.RGBA, gl.FLOAT, null);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    return tex;
  }
 
  createFramebuffer(colorTex) {
    const gl = this.gl;
    const fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorTex, 0);
    return fb;
  }
 
  createMRTFramebuffer(stateTex, checkpointTex, lazyTex) {
    const gl = this.gl;
    const fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, stateTex, 0);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.TEXTURE_2D, checkpointTex, 0);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT2, gl.TEXTURE_2D, lazyTex, 0);
    gl.drawBuffers([gl.COLOR_ATTACHMENT0, gl.COLOR_ATTACHMENT1, gl.COLOR_ATTACHMENT2]);
    return fb;
  }
 
  createQuad() {
    const gl = this.gl;
    this.quadVAO = gl.createVertexArray();
    gl.bindVertexArray(this.quadVAO);
 
    const vbo = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 1,-1, -1,1, 1,1]), gl.STATIC_DRAW);
 
    const posLoc = gl.getAttribLocation(this.iterProgram, 'a_position');
    gl.enableVertexAttribArray(posLoc);
    gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
  }
 
  // Abstract - subclass should implement
  initializeStateTextures() {
    throw new Error('Subclass must implement initializeStateTextures()');
  }
 
  uploadDeltaC() {
    const gl = this.gl;
    const w = this.texWidth;
    const h = this.texHeight;
    const area = w * h;
 
    const dcData = new Float32Array(area * 4);
    for (let i = 0; i < area; i++) {
      dcData[i * 4 + 0] = this.dc[i * 2];
      dcData[i * 4 + 1] = this.dc[i * 2 + 1];
      dcData[i * 4 + 2] = 0.0;
      dcData[i * 4 + 3] = 0.0;
    }
 
    gl.bindTexture(gl.TEXTURE_2D, this.deltaCTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.FLOAT, dcData);
  }
 
  // Abstract - subclass should implement based on DD or QD precision
  uploadRefOrbit() {
    throw new Error('Subclass must implement uploadRefOrbit()');
  }
 
  async start() {
    await this.glInitPromise;
    this.startTime = Date.now();
    const re = qdToNumber(this.re);
    const im = qdToNumber(this.im);
    console.log(`[GL] Board ${this.config.index}: ${this.constructor.name} @ c=(${re.toFixed(4)}, ${im.toFixed(4)}), dims=${this.texWidth}x${this.texHeight}, pixel=${this.pix.toExponential(3)}`);
  }
 
  async iterate(targetIters = null) {
    await this.glInitPromise;
    this.waitForPendingReadback();
 
    if (this.un <= 0) return;
 
    // Extend reference orbit if needed
    const targetRefIter = this.it + (targetIters || 1000);
    while (this.refIterations < targetRefIter + 100 && !this.refOrbitEscaped) {
      this.extendReferenceOrbit(Math.min(10000, targetRefIter + 100 - this.refIterations));
    }
    this.uploadRefOrbit();
 
    if (targetIters === null) {
      const pixels = this.texWidth * this.texHeight;
      const effort = Math.max(this.effort, 1);
      targetIters = Math.max(1, Math.floor(100000 / (pixels * effort)));
    }
 
    this.doGpuIterations(targetIters);
    this.pendingBatchEndIter = this.it;
    this.startAsyncReadback();
  }
 
  doGpuIterations(targetIters) {
    const gl = this.gl;
 
    // Get Fibonacci checkpoints
    while (this.fibCache[this.fibCache.length - 1] < this.it + targetIters + 1000) {
      const n = this.fibCache.length;
      this.fibCache.push(this.fibCache[n - 1] + this.fibCache[n - 2]);
    }
    let fibIdx = 0;
    while (this.fibCache[fibIdx] <= this.it) fibIdx++;
    const fibPrev = fibIdx > 0 ? this.fibCache[fibIdx - 1] : 1;
    const fibCurr = this.fibCache[fibIdx];
 
    // Bind shader and set uniforms
    gl.useProgram(this.iterProgram);
 
    gl.activeTexture(gl.TEXTURE3);
    gl.bindTexture(gl.TEXTURE_2D, this.deltaCTex);
    gl.uniform1i(this.iterUniforms.u_deltaC, 3);
 
    gl.activeTexture(gl.TEXTURE4);
    gl.bindTexture(gl.TEXTURE_2D, this.refOrbitTex);
    gl.uniform1i(this.iterUniforms.u_refOrbit, 4);
 
    gl.uniform2f(this.iterUniforms.u_resolution, this.texWidth, this.texHeight);
    gl.uniform1i(this.iterUniforms.u_iterations, targetIters);
    gl.uniform1i(this.iterUniforms.u_exponent, this.config.exponent);
    gl.uniform1f(this.iterUniforms.u_epsilon, this.epsilon);
    gl.uniform1f(this.iterUniforms.u_epsilon2, this.epsilon2);
    gl.uniform1f(this.iterUniforms.u_pixelSize, this.pix);
    gl.uniform1i(this.iterUniforms.u_startIter, this.it);
    gl.uniform1i(this.iterUniforms.u_refOrbitLength, this.refIterations);
    gl.uniform1i(this.iterUniforms.u_refOrbitTexWidth, this.refOrbitTexWidth);
    gl.uniform1i(this.iterUniforms.u_fibPrev, fibPrev);
    gl.uniform1i(this.iterUniforms.u_fibCurr, fibCurr);
 
    // Loop parameters
    gl.uniform1i(this.iterUniforms.u_loopEnabled, this.refOrbitLoop.enabled ? 1 : 0);
    gl.uniform1i(this.iterUniforms.u_loopThreshold, this.refOrbitLoop.threshold || 0);
    gl.uniform1i(this.iterUniforms.u_loopJump, this.refOrbitLoop.jumpAmount || 0);
    gl.uniform1f(this.iterUniforms.u_loopDeltaR, this.refOrbitLoop.deltaR || 0);
    gl.uniform1f(this.iterUniforms.u_loopDeltaI, this.refOrbitLoop.deltaI || 0);
 
    // Bind input textures
    const readState = this.isPingRead ? this.pingStateTex : this.pongStateTex;
    const readCheckpoint = this.isPingRead ? this.pingCheckpointTex : this.pongCheckpointTex;
    const readLazy = this.isPingRead ? this.pingLazyTex : this.pongLazyTex;
    // Write to the OPPOSITE buffer (ping-pong pattern)
    const writeFB = this.isPingRead ? this.pongFB : this.pingFB;
 
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, readState);
    gl.uniform1i(this.iterUniforms.u_state, 0);
 
    gl.activeTexture(gl.TEXTURE1);
    gl.bindTexture(gl.TEXTURE_2D, readCheckpoint);
    gl.uniform1i(this.iterUniforms.u_checkpoint, 1);
 
    gl.activeTexture(gl.TEXTURE2);
    gl.bindTexture(gl.TEXTURE_2D, readLazy);
    gl.uniform1i(this.iterUniforms.u_lazy, 2);
 
    // Draw
    gl.bindFramebuffer(gl.FRAMEBUFFER, writeFB);
    gl.viewport(0, 0, this.texWidth, this.texHeight);
    gl.bindVertexArray(this.quadVAO);
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
 
    this.isPingRead = !this.isPingRead;
    this.it += targetIters;
  }
 
  startAsyncReadback() {
    const gl = this.gl;
    this.runReductionPasses();
 
    const pboIndex = this.currentPBOIndex;
    this.currentPBOIndex = 1 - this.currentPBOIndex;
 
    if (!this.level2PBOs[pboIndex]) {
      this.level2PBOs[pboIndex] = gl.createBuffer();
      this.level2Size = this.level2Width * this.level2Height * 4 * 4;
      gl.bindBuffer(gl.PIXEL_PACK_BUFFER, this.level2PBOs[pboIndex]);
      gl.bufferData(gl.PIXEL_PACK_BUFFER, this.level2Size, gl.STREAM_READ);
    }
 
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level2FB);
    gl.bindBuffer(gl.PIXEL_PACK_BUFFER, this.level2PBOs[pboIndex]);
    gl.readPixels(0, 0, this.level2Width, this.level2Height, gl.RGBA, gl.FLOAT, 0);
    gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
 
    // Create fence sync to wait for GPU completion before reading
    const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
    gl.flush();
 
    this.pendingReadback = { pboIndex, sync };
  }
 
  runReductionPasses() {
    const gl = this.gl;
    const readState = this.isPingRead ? this.pingStateTex : this.pongStateTex;
 
    // Swap level1 textures
    [this.level1Tex, this.prevLevel1Tex] = [this.prevLevel1Tex, this.level1Tex];
    [this.level1FB, this.prevLevel1FB] = [this.prevLevel1FB, this.level1FB];
 
    // Level 1 reduction
    gl.useProgram(this.reduction1Program);
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level1FB);
    gl.viewport(0, 0, this.level1Width, this.level1Height);
 
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, readState);
    gl.uniform1i(this.reduction1Uniforms.u_state, 0);
 
    gl.activeTexture(gl.TEXTURE1);
    gl.bindTexture(gl.TEXTURE_2D, this.prevLevel1Tex);
    gl.uniform1i(this.reduction1Uniforms.u_prevTiles, 1);
 
    gl.uniform2f(this.reduction1Uniforms.u_stateSize, this.texWidth, this.texHeight);
    gl.uniform2f(this.reduction1Uniforms.u_tileSize, this.level1Width, this.level1Height);
 
    gl.bindVertexArray(this.quadVAO);
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
 
    // Level 2 reduction
    gl.useProgram(this.reduction2Program);
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level2FB);
    gl.viewport(0, 0, this.level2Width, this.level2Height);
 
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, this.level1Tex);
    gl.uniform1i(this.reduction2Uniforms.u_tiles, 0);
    gl.uniform2f(this.reduction2Uniforms.u_tilesSize, this.level1Width, this.level1Height);
 
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  }
 
  waitForPendingReadback() {
    const gl = this.gl;
    const pending = this.pendingReadback;
 
    if (!pending) return;
 
    const pbo = this.level2PBOs[pending.pboIndex];
    if (!pbo) {
      if (pending.sync) gl.deleteSync(pending.sync);
      this.pendingReadback = null;
      this.pendingBatchEndIter = null;
      return;
    }
 
    this.pendingReadback = null;
    const batchEndIter = this.pendingBatchEndIter;
    this.pendingBatchEndIter = null;
 
    // Wait for fence sync to complete before reading (avoids pipeline stall warning)
    if (pending.sync) {
      gl.clientWaitSync(pending.sync, 0, 0);  // Don't actually wait, just signal intent
      gl.deleteSync(pending.sync);
    }
 
    const level2Data = new Float32Array(this.level2Width * this.level2Height * 4);
    gl.bindBuffer(gl.PIXEL_PACK_BUFFER, pbo);
    gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, level2Data);
    gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
 
    this.processLevel2Results(level2Data);
  }
 
  processLevel2Results(superTiles) {
    const gl = this.gl;
    const activeSuperTiles = [];
    let totalNew = 0;
    let totalFinished = 0;
 
    for (let sy = 0; sy < this.level2Height; sy++) {
      for (let sx = 0; sx < this.level2Width; sx++) {
        const idx = (sy * this.level2Width + sx) * 4;
        totalFinished += superTiles[idx];
        const newlyEscaped = superTiles[idx + 1];
        if (newlyEscaped > 0) {
          activeSuperTiles.push({ x: sx, y: sy, count: newlyEscaped });
          totalNew += newlyEscaped;
        }
      }
    }
 
    if (totalNew === 0) return;
 
    // Read level1 tiles for active super-tiles
    const level1Data = new Float32Array(this.level1Width * this.level1Height * 4);
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.level1FB);
    gl.readPixels(0, 0, this.level1Width, this.level1Height, gl.RGBA, gl.FLOAT, level1Data);
 
    const activeTiles = [];
    for (const st of activeSuperTiles) {
      const baseX = st.x * 16;
      const baseY = st.y * 16;
      for (let dy = 0; dy < 16; dy++) {
        for (let dx = 0; dx < 16; dx++) {
          const tx = baseX + dx;
          const ty = baseY + dy;
          if (tx >= this.level1Width || ty >= this.level1Height) continue;
          const idx = (ty * this.level1Width + tx) * 4;
          if (level1Data[idx + 1] > 0) {
            activeTiles.push({ x: tx, y: ty, count: level1Data[idx + 1] });
          }
        }
      }
    }
 
    if (activeTiles.length === 0) return;
 
    // Read pixel state for active tiles
    const readState = this.isPingRead ? this.pingStateTex : this.pongStateTex;
    const readCheckpoint = this.isPingRead ? this.pingCheckpointTex : this.pongCheckpointTex;
 
    const stateData = new Float32Array(this.texWidth * this.texHeight * 4);
    const checkpointData = new Float32Array(this.texWidth * this.texHeight * 4);
 
    // Create temp framebuffer to read from state texture
    const tempFB = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, tempFB);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, readState, 0);
    gl.readPixels(0, 0, this.texWidth, this.texHeight, gl.RGBA, gl.FLOAT, stateData);
 
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, readCheckpoint, 0);
    gl.readPixels(0, 0, this.texWidth, this.texHeight, gl.RGBA, gl.FLOAT, checkpointData);
    gl.deleteFramebuffer(tempFB);
 
    // Process active tiles
    const results = [];
    for (const tile of activeTiles) {
      const baseX = tile.x * 16;
      const baseY = tile.y * 16;
 
      for (let dy = 0; dy < 16; dy++) {
        for (let dx = 0; dx < 16; dx++) {
          const px = baseX + dx;
          const py = baseY + dy;
          if (px >= this.texWidth || py >= this.texHeight) continue;
 
          const pixelIdx = py * this.texWidth + px;
          const stateIdx = pixelIdx * 4;
 
          const status = stateData[stateIdx + 3];
          if (status > 0 && !this.reported[pixelIdx]) {
            this.reported[pixelIdx] = 1;
            const iter = Math.round(stateData[stateIdx + 2]);
            const period = Math.round(checkpointData[stateIdx + 3]);
 
            results.push({
              index: pixelIdx,
              iter: status === 2 ? -iter : iter,
              period: period
            });
          }
        }
      }
    }
 
    // Update counters
    this.di += results.length;
    this.un -= results.length;
 
    // Queue results to changeList, grouped by iteration
    if (results.length > 0) {
      const byIter = new Map();
      for (const r of results) {
        this.nn[r.index] = r.iter;
        this.pp[r.index] = r.period;
 
        const absIter = Math.abs(r.iter);
        if (!byIter.has(absIter)) {
          byIter.set(absIter, { diverged: [], converged: [] });
        }
        const group = byIter.get(absIter);
        if (r.iter > 0) {
          group.diverged.push(r.index);
        } else {
          group.converged.push({ index: r.index, z: 0, p: r.period });
        }
      }
 
      const sortedIters = Array.from(byIter.keys()).sort((a, b) => a - b);
      for (const iter of sortedIters) {
        const group = byIter.get(iter);
        this.queueChanges({
          iter,
          nn: group.diverged,
          vv: group.converged
        });
      }
    }
  }
 
  async serialize() {
    const base = await super.serialize();
    const completedIndexes = [];
    const completedNn = [];
    for (let i = 0; i < this.nn.length; i++) {
      if (this.nn[i] !== 0) {
        completedIndexes.push(i);
        completedNn.push(this.nn[i]);
      }
    }
    return {
      ...base,
      reported: Array.from(this.reported),
      completedIndexes,
      completedNn,
      cMinRe: this.cMinRe,
      cMinIm: this.cMinIm,
      cMaxRe: this.cMaxRe,
      cMaxIm: this.cMaxIm
    };
  }
 
  static isAvailable() {
    if (typeof OffscreenCanvas === 'undefined') return false;
    try {
      const canvas = new OffscreenCanvas(1, 1);
      const gl = canvas.getContext('webgl2');
      if (!gl) return false;
      const ext = gl.getExtension('EXT_color_buffer_float');
      return !!ext;
    } catch (e) {
      return false;
    }
  }
}
 
// WebGL2 perturbation board using DD precision reference orbit
// Fallback for browsers without WebGPU support at medium zoom depths
class GlZhuoranBoard extends DDReferenceOrbitMixin(GlPerturbationBaseBoard) {
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
 
    // Initialize DD reference orbit
    const refRe = Array.isArray(re) ? re : toDD(re);
    const refIm = Array.isArray(im) ? im : toDD(im);
    this.initDDReferenceOrbit([refRe[0], refRe[1], refIm[0], refIm[1]]);
 
    // Initialize per-pixel perturbation data
    this.initPixels(size, re, im);
 
    // Start GL initialization
    this.glInitPromise = this.initGL();
  }
 
  initPixels(size, re, im) {
    const dimsWidth = this.config.dimsWidth;
    const dimsHeight = this.config.dimsHeight;
    const dimsArea = this.config.dimsArea;
 
    const re_dd = Array.isArray(re) ? re : toDD(re);
    const im_dd = Array.isArray(im) ? im : toDD(im);
    const size_scalar = Array.isArray(size) ? size.reduce((a, b) => a + (b || 0), 0) : size;
    const size_dd = toDD(size_scalar);
    const sizeY_dd = toDD(size_scalar / this.config.aspectRatio);
 
    const cr_dd = new Array(4);
    const ci_dd = new Array(4);
    const dcr_dd = new Array(4);
    const dci_dd = new Array(4);
    const temp = new Array(4);
 
    for (let y = 0; y < dimsHeight; y++) {
      const yFrac = (dimsHeight / 2 - y) / dimsHeight;
      arDdMul(temp, 0, yFrac, 0, sizeY_dd[0], sizeY_dd[1]);
      arDdAdd(ci_dd, 0, im_dd[0], im_dd[1], temp[0], temp[1]);
      arDdAdd(dci_dd, 0, ci_dd[0], ci_dd[1], -this.refC[2], -this.refC[3]);
 
      for (let x = 0; x < dimsWidth; x++) {
        const xFrac = (x - dimsWidth / 2) / dimsWidth;
        arDdMul(temp, 0, xFrac, 0, size_dd[0], size_dd[1]);
        arDdAdd(cr_dd, 0, re_dd[0], re_dd[1], temp[0], temp[1]);
        arDdAdd(dcr_dd, 0, cr_dd[0], cr_dd[1], -this.refC[0], -this.refC[1]);
 
        const index = y * dimsWidth + x;
        const index2 = index * 2;
        this.dc[index2] = Math.fround(dcr_dd[0] + dcr_dd[1]);
        this.dc[index2 + 1] = Math.fround(dci_dd[0] + dci_dd[1]);
        this.dz[index2] = this.dc[index2];
        this.dz[index2 + 1] = this.dc[index2 + 1];
      }
    }
  }
 
  getIterationShaderSource() {
    return `#version 300 es
      precision highp float;
      precision highp int;
 
      uniform sampler2D u_state;       // (dzr, dzi, iter, status)
      uniform sampler2D u_checkpoint;  // (bbr, bbi, ref_iter, period)
      uniform sampler2D u_lazy;        // (ckpt_refidx, pending_refidx, ckpt_bbr, ckpt_bbi)
      uniform sampler2D u_deltaC;      // (dcr, dci, 0, 0)
      uniform sampler2D u_refOrbit;    // Reference orbit + threading
 
      uniform vec2 u_resolution;
      uniform int u_iterations;
      uniform int u_exponent;
      uniform float u_epsilon;
      uniform float u_epsilon2;
      uniform float u_pixelSize;
      uniform int u_startIter;
      uniform int u_refOrbitLength;
      uniform int u_refOrbitTexWidth;
      uniform int u_fibPrev;
      uniform int u_fibCurr;
      uniform int u_loopEnabled;
      uniform int u_loopThreshold;
      uniform int u_loopJump;
      uniform float u_loopDeltaR;
      uniform float u_loopDeltaI;
 
      layout(location = 0) out vec4 outState;
      layout(location = 1) out vec4 outCheckpoint;
      layout(location = 2) out vec4 outLazy;
 
      in vec2 v_texCoord;
 
      vec2 getRefOrbit(int idx) {
        if (idx >= u_refOrbitLength) return vec2(0.0);
        int texelIdx = idx * 2;
        int row = texelIdx / u_refOrbitTexWidth;
        int col = texelIdx - row * u_refOrbitTexWidth;
        vec4 data = texelFetch(u_refOrbit, ivec2(col, row), 0);
        return vec2(data.r, data.g);
      }
 
      vec3 getThread(int idx) {
        if (idx >= u_refOrbitLength) return vec3(-1.0, 0.0, 0.0);
        int texelIdx = idx * 2;
        int row = texelIdx / u_refOrbitTexWidth;
        int col = texelIdx - row * u_refOrbitTexWidth;
        vec4 data1 = texelFetch(u_refOrbit, ivec2(col, row), 0);
        vec4 data2 = texelFetch(u_refOrbit, ivec2(col + 1, row), 0);
        return vec3(data1.b, data1.a, data2.r);
      }
 
      void main() {
        ivec2 coord = ivec2(gl_FragCoord.xy);
 
        vec4 state = texelFetch(u_state, coord, 0);
        vec4 checkpoint = texelFetch(u_checkpoint, coord, 0);
        vec4 lazy = texelFetch(u_lazy, coord, 0);
        vec4 dc = texelFetch(u_deltaC, coord, 0);
 
        float dzr = state.r;
        float dzi = state.g;
        float iter = state.b;
        float status = state.a;
 
        float bbr = checkpoint.r;
        float bbi = checkpoint.g;
        int ref_iter = int(checkpoint.b);
        float period = checkpoint.a;
 
        int ckpt_refidx = int(lazy.r);
        int pending_refidx = int(lazy.g);
        float ckpt_bbr = lazy.b;
        float ckpt_bbi = lazy.a;
 
        float dcr = dc.r;
        float dci = dc.g;
 
        int fibPrev = u_fibPrev;
        int fibCurr = u_fibCurr;
 
        if (status == 0.0) {
          for (int i = 0; i < 100000; i++) {
            if (i >= u_iterations) break;
 
            int globalIter = u_startIter + i + 1;
 
            float dz_norm = max(abs(dzr), abs(dzi));
            if (ref_iter > 0 && ref_iter < u_refOrbitLength) {
              vec2 ref_check = getRefOrbit(ref_iter);
              float total_r = ref_check.x + dzr;
              float total_i = ref_check.y + dzi;
              float total_norm = max(abs(total_r), abs(total_i));
 
              if (total_norm < dz_norm * 2.0) {
                dzr = total_r;
                dzi = total_i;
                ref_iter = 0;
                if (ckpt_refidx >= 0) {
                  pending_refidx = ckpt_refidx;
                  bbr = ckpt_bbr;
                  bbi = ckpt_bbi;
                }
              }
            }
 
            if (ref_iter >= u_refOrbitLength) break;
            vec2 ref_val = getRefOrbit(ref_iter);
            float refr = ref_val.x;
            float refi = ref_val.y;
 
            float curr_r = refr + dzr;
            float curr_i = refi + dzi;
            float curr_mag_sq = curr_r * curr_r + curr_i * curr_i;
            if (curr_mag_sq > 4.0 || curr_mag_sq != curr_mag_sq) {
              status = 1.0;
              break;
            }
 
            float old_dzr = dzr;
            float old_dzi = dzi;
            int old_ref_iter = ref_iter;
 
            if (u_exponent == 2) {
              float new_dzr = 2.0 * (refr * dzr - refi * dzi) + dzr * dzr - dzi * dzi + dcr;
              float new_dzi = 2.0 * (refr * dzi + refi * dzr) + 2.0 * dzr * dzi + dci;
              dzr = new_dzr;
              dzi = new_dzi;
            } else {
              float z_pow_r = refr;
              float z_pow_i = refi;
              float coeff = float(u_exponent);
              float result_r = dzr;
              float result_i = dzi;
 
              for (int k = 1; k < 10; k++) {
                if (k >= u_exponent) break;
                result_r += coeff * z_pow_r;
                result_i += coeff * z_pow_i;
                float temp_r = result_r * dzr - result_i * dzi;
                result_i = result_r * dzi + result_i * dzr;
                result_r = temp_r;
                float new_z_pow_r = z_pow_r * refr - z_pow_i * refi;
                z_pow_i = z_pow_r * refi + z_pow_i * refr;
                z_pow_r = new_z_pow_r;
                coeff *= float(u_exponent - k) / float(k + 1);
              }
              dzr = result_r + dcr;
              dzi = result_i + dci;
            }
 
            iter += 1.0;
            ref_iter++;
 
            if (u_loopEnabled != 0 && ref_iter >= u_loopThreshold) {
              dzr += u_loopDeltaR;
              dzi += u_loopDeltaI;
              ref_iter -= u_loopJump;
            }
 
            bool just_updated = false;
            if (globalIter == fibCurr) {
              just_updated = true;
              bbr = old_dzr;
              bbi = old_dzi;
              ckpt_bbr = old_dzr;
              ckpt_bbi = old_dzi;
              ckpt_refidx = old_ref_iter;
              pending_refidx = old_ref_iter;
              period = 0.0;
              int nextFib = fibPrev + fibCurr;
              fibPrev = fibCurr;
              fibCurr = nextFib;
            }
 
            if (ckpt_refidx >= 0 && !just_updated) {
              if (ref_iter == ckpt_refidx) {
                float diff_r = old_dzr - bbr;
                float diff_i = old_dzi - bbi;
                float db = max(abs(diff_r), abs(diff_i));
                if (db <= u_epsilon2) {
                  if (period == 0.0) period = iter;
                  if (db <= u_epsilon) {
                    status = 2.0;
                    break;
                  }
                }
              }
 
              if (pending_refidx >= 2584 && pending_refidx < u_refOrbitLength) {
                vec3 thread = getThread(pending_refidx);
                if (thread.x >= 0.0 && int(thread.x) == ref_iter) {
                  float diff_r = old_dzr - bbr + thread.y;
                  float diff_i = old_dzi - bbi + thread.z;
                  float db = max(abs(diff_r), abs(diff_i));
                  if (db <= u_epsilon2) {
                    if (period == 0.0) period = iter;
                    if (db <= u_epsilon) {
                      status = 2.0;
                      break;
                    }
                  }
                  bbr -= thread.y;
                  bbi -= thread.z;
                  pending_refidx = ref_iter;
                }
              }
            }
          }
        }
 
        outState = vec4(dzr, dzi, iter, status);
        outCheckpoint = vec4(bbr, bbi, float(ref_iter), period);
        outLazy = vec4(float(ckpt_refidx), float(pending_refidx), ckpt_bbr, ckpt_bbi);
      }
    `;
  }
 
  initializeStateTextures() {
    const gl = this.gl;
    const w = this.texWidth;
    const h = this.texHeight;
    const area = w * h;
 
    const stateData = new Float32Array(area * 4);
    const checkpointData = new Float32Array(area * 4);
    const lazyData = new Float32Array(area * 4);
 
    for (let i = 0; i < area; i++) {
      stateData[i * 4 + 0] = this.dz[i * 2];
      stateData[i * 4 + 1] = this.dz[i * 2 + 1];
      stateData[i * 4 + 2] = 1.0;
      stateData[i * 4 + 3] = 0.0;
 
      checkpointData[i * 4 + 0] = 0.0;
      checkpointData[i * 4 + 1] = 0.0;
      checkpointData[i * 4 + 2] = 1.0;
      checkpointData[i * 4 + 3] = 0.0;
 
      lazyData[i * 4 + 0] = -1.0;
      lazyData[i * 4 + 1] = -1.0;
      lazyData[i * 4 + 2] = 0.0;
      lazyData[i * 4 + 3] = 0.0;
    }
 
    gl.bindTexture(gl.TEXTURE_2D, this.pingStateTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.FLOAT, stateData);
    gl.bindTexture(gl.TEXTURE_2D, this.pingCheckpointTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.FLOAT, checkpointData);
    gl.bindTexture(gl.TEXTURE_2D, this.pingLazyTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.FLOAT, lazyData);
  }
 
  uploadRefOrbit() {
    const gl = this.gl;
    const refLen = this.refIterations;
 
    if (refLen <= this.lastUploadedRefIter) return;
 
    const texelsNeeded = refLen * 2;
    const texWidth = this.refOrbitTexWidth;
    const rowsNeeded = Math.ceil(texelsNeeded / texWidth);
 
    if (rowsNeeded > this.refOrbitTexHeight) {
      console.warn('Reference orbit exceeds texture size');
      return;
    }
 
    const data = new Float32Array(texWidth * rowsNeeded * 4);
 
    // Fill from 0, not lastUploadedRefIter, to avoid overwriting existing data with zeros
    // when texSubImage2D uploads full rows
    for (let i = 0; i < refLen; i++) {
      const orbit = this.refOrbit[i];
      const thread = this.threading.getThread(i);
      const texelIdx = i * 2;
 
      const dataIdx1 = texelIdx * 4;
      data[dataIdx1 + 0] = orbit[0] + orbit[1];
      data[dataIdx1 + 1] = orbit[2] + orbit[3];
      data[dataIdx1 + 2] = thread.next;
      data[dataIdx1 + 3] = thread.deltaRe;
 
      const dataIdx2 = (texelIdx + 1) * 4;
      data[dataIdx2 + 0] = thread.deltaIm;
      data[dataIdx2 + 1] = 0.0;
      data[dataIdx2 + 2] = 0.0;
      data[dataIdx2 + 3] = 0.0;
    }
 
    gl.bindTexture(gl.TEXTURE_2D, this.refOrbitTex);
 
    // Upload only new rows (rows that weren't fully uploaded before)
    const startRow = Math.floor(this.lastUploadedRefIter * 2 / texWidth);
    const endRow = Math.ceil(refLen * 2 / texWidth);
 
    for (let row = startRow; row < endRow; row++) {
      const rowOffset = row * texWidth * 4;
      const rowData = data.subarray(rowOffset, rowOffset + texWidth * 4);
      gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, row, texWidth, 1, gl.RGBA, gl.FLOAT, rowData);
    }
 
    this.lastUploadedRefIter = refLen;
  }
 
  async serialize() {
    const base = await super.serialize();
    return {
      ...base,
      refC: this.refC,
      refOrbit: this.refOrbit
    };
  }
 
  static fromSerialized(serialized) {
    const board = new GlZhuoranBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    board.glInitPromise = board.glInitPromise.then(() => {
      board.it = serialized.it;
      board.un = serialized.un;
      board.di = serialized.di;
      board.ch = serialized.ch || 0;
 
      if (serialized.reported) {
        board.reported = new Uint8Array(serialized.reported);
      }
 
      board.cMinRe = serialized.cMinRe;
      board.cMinIm = serialized.cMinIm;
      board.cMaxRe = serialized.cMaxRe;
      board.cMaxIm = serialized.cMaxIm;
 
      if (serialized.refC) {
        board.refC = serialized.refC;
      }
      if (serialized.refOrbit) {
        board.refOrbit = serialized.refOrbit;
        board.refIter = serialized.refOrbit.length / 2;
      }
 
      board.nn = new Array(serialized.config.dimsArea).fill(0);
      if (serialized.completedIndexes) {
        for (let i = 0; i < serialized.completedIndexes.length; i++) {
          board.nn[serialized.completedIndexes[i]] = serialized.completedNn[i];
        }
      }
    });
 
    return board;
  }
}
// WebGL2 adaptive perturbation board using QD precision reference orbit
// For extreme deep zoom when DD precision is insufficient
class GlAdaptiveBoard extends QDReferenceOrbitMixin(GlPerturbationBaseBoard) {
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
 
    // Initialize QD reference orbit
    const refReQD = toQD(re);
    const refImQD = toQD(im);
    this.initQDReferenceOrbit([...refReQD, ...refImQD]);
 
    // Initialize per-pixel perturbation data with adaptive scaling
    this.initPixels(size, re, im);
 
    // Start GL initialization
    this.glInitPromise = this.initGL();
  }
 
  initPixels(size, re, im) {
    // Adaptive scaling: store dc as mantissa with separate scale exponent
    // δc_actual = dc_stored × 2^scale, where dc_stored is in range ~[-2, 2]
    const dimsWidth = this.config.dimsWidth;
    const dimsHeight = this.config.dimsHeight;
    const dimsArea = this.config.dimsArea;
 
    // Convert size to scalar if it's a QD array
    const size_scalar = Array.isArray(size) ? size.reduce((a, b) => a + (b || 0), 0) : size;
    const pixelSize = size_scalar / dimsWidth;
 
    // Compute initial scale: k = floor(log2(pixelSize))
    const log2_pixelSize = Math.log2(pixelSize);
    this.initialScale = Math.floor(log2_pixelSize);
 
    // Mantissa factor: 2^(log2(pixelSize) - k) is in [1, 2)
    const mantissa = Math.pow(2, log2_pixelSize - this.initialScale);
 
    // Per-pixel scale array
    this.pixelScale = new Int32Array(dimsArea);
 
    // Initialize each pixel
    for (let y = 0; y < dimsHeight; y++) {
      const yOffset = dimsHeight / 2 - y;
 
      for (let x = 0; x < dimsWidth; x++) {
        const xOffset = x - dimsWidth / 2;
 
        const index = y * dimsWidth + x;
        const index2 = index * 2;
 
        // δc_stored = mantissa × pixel_offset (normalized to range ~[-dimsWidth/2, +dimsWidth/2] * mantissa)
        this.dc[index2] = Math.fround(mantissa * xOffset);
        this.dc[index2 + 1] = Math.fround(mantissa * yOffset);
 
        // Start with dz = dc
        this.dz[index2] = this.dc[index2];
        this.dz[index2 + 1] = this.dc[index2 + 1];
 
        // All pixels start with the same scale
        this.pixelScale[index] = this.initialScale;
      }
    }
  }
 
  // Override to create additional scale textures
  createTextures() {
    const gl = this.gl;
 
    // Create ping-pong state textures (inherited)
    this.pingStateTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pingCheckpointTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pingLazyTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pingScaleTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pongStateTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pongCheckpointTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pongLazyTex = this.createFloatTexture(this.texWidth, this.texHeight);
    this.pongScaleTex = this.createFloatTexture(this.texWidth, this.texHeight);
 
    // Delta C texture (constant)
    this.deltaCTex = this.createFloatTexture(this.texWidth, this.texHeight);
 
    // Reference orbit texture
    this.refOrbitTex = this.createFloatTexture(this.refOrbitTexWidth, this.refOrbitTexHeight);
 
    // Create 4-MRT framebuffers for ping-pong
    this.pingFB = this.createMRTFramebuffer4(this.pingStateTex, this.pingCheckpointTex, this.pingLazyTex, this.pingScaleTex);
    this.pongFB = this.createMRTFramebuffer4(this.pongStateTex, this.pongCheckpointTex, this.pongLazyTex, this.pongScaleTex);
 
    // Hierarchy textures
    this.level1Tex = this.createFloatTexture(this.level1Width, this.level1Height);
    this.level1FB = this.createFramebuffer(this.level1Tex);
    this.prevLevel1Tex = this.createFloatTexture(this.level1Width, this.level1Height);
    this.prevLevel1FB = this.createFramebuffer(this.prevLevel1Tex);
    this.level2Tex = this.createFloatTexture(this.level2Width, this.level2Height);
    this.level2FB = this.createFramebuffer(this.level2Tex);
 
    // Initialize prevLevel1 to zeros
    gl.bindFramebuffer(gl.FRAMEBUFFER, this.prevLevel1FB);
    gl.viewport(0, 0, this.level1Width, this.level1Height);
    gl.clearColor(0, 0, 0, 0);
    gl.clear(gl.COLOR_BUFFER_BIT);
  }
 
  createMRTFramebuffer4(stateTex, checkpointTex, lazyTex, scaleTex) {
    const gl = this.gl;
    const fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, stateTex, 0);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.TEXTURE_2D, checkpointTex, 0);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT2, gl.TEXTURE_2D, lazyTex, 0);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT3, gl.TEXTURE_2D, scaleTex, 0);
    gl.drawBuffers([gl.COLOR_ATTACHMENT0, gl.COLOR_ATTACHMENT1, gl.COLOR_ATTACHMENT2, gl.COLOR_ATTACHMENT3]);
    const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
    if (status !== gl.FRAMEBUFFER_COMPLETE) {
      throw new Error('4-MRT Framebuffer incomplete: ' + status);
    }
    return fb;
  }
 
  async createShaders() {
    // Call parent to compile shaders and set up standard uniforms
    await super.createShaders();
 
    // Add GlAdaptiveBoard-specific uniforms for scaling
    const gl = this.gl;
    gl.useProgram(this.iterProgram);
    this.iterUniforms.u_scale = gl.getUniformLocation(this.iterProgram, 'u_scale');
    this.iterUniforms.u_initialScale = gl.getUniformLocation(this.iterProgram, 'u_initialScale');
  }
 
  // Adaptive scaling iteration shader - uses ldexp for deep zoom support
  getIterationShaderSource() {
    return `#version 300 es
      precision highp float;
      precision highp int;
 
      uniform sampler2D u_state;       // (dzr, dzi, iter, status)
      uniform sampler2D u_checkpoint;  // (bbr, bbi, ref_iter, period)
      uniform sampler2D u_lazy;        // (ckpt_refidx, pending_refidx, ckpt_bbr, ckpt_bbi)
      uniform sampler2D u_scale;       // (scale, 0, 0, 0)
      uniform sampler2D u_deltaC;      // (dcr, dci, 0, 0)
      uniform sampler2D u_refOrbit;    // Reference orbit + threading
 
      uniform vec2 u_resolution;
      uniform int u_iterations;
      uniform int u_exponent;
      uniform float u_epsilon;
      uniform float u_epsilon2;
      uniform float u_pixelSize;
      uniform int u_startIter;
      uniform int u_refOrbitLength;
      uniform int u_refOrbitTexWidth;
      uniform int u_fibPrev;
      uniform int u_fibCurr;
      uniform int u_loopEnabled;
      uniform int u_loopThreshold;
      uniform int u_loopJump;
      uniform float u_loopDeltaR;
      uniform float u_loopDeltaI;
      uniform int u_initialScale;
 
      layout(location = 0) out vec4 outState;
      layout(location = 1) out vec4 outCheckpoint;
      layout(location = 2) out vec4 outLazy;
      layout(location = 3) out vec4 outScale;
 
      in vec2 v_texCoord;
 
      // ldexp(x, n) = x * 2^n
      float ldexp(float x, int n) {
        return x * exp2(float(n));
      }
 
      vec2 getRefOrbit(int idx) {
        if (idx >= u_refOrbitLength) return vec2(0.0);
        int texelIdx = idx * 2;
        int row = texelIdx / u_refOrbitTexWidth;
        int col = texelIdx - row * u_refOrbitTexWidth;
        vec4 data = texelFetch(u_refOrbit, ivec2(col, row), 0);
        return vec2(data.r, data.g);
      }
 
      vec3 getThread(int idx) {
        if (idx >= u_refOrbitLength) return vec3(-1.0, 0.0, 0.0);
        int texelIdx = idx * 2;
        int row = texelIdx / u_refOrbitTexWidth;
        int col = texelIdx - row * u_refOrbitTexWidth;
        vec4 data1 = texelFetch(u_refOrbit, ivec2(col, row), 0);
        vec4 data2 = texelFetch(u_refOrbit, ivec2(col + 1, row), 0);
        return vec3(data1.b, data1.a, data2.r);
      }
 
      void main() {
        ivec2 coord = ivec2(gl_FragCoord.xy);
 
        vec4 state = texelFetch(u_state, coord, 0);
        vec4 checkpoint = texelFetch(u_checkpoint, coord, 0);
        vec4 lazy = texelFetch(u_lazy, coord, 0);
        vec4 scaleVec = texelFetch(u_scale, coord, 0);
        vec4 dc = texelFetch(u_deltaC, coord, 0);
 
        float dzr = state.r;
        float dzi = state.g;
        float iter = state.b;
        float status = state.a;
 
        float bbr = checkpoint.r;
        float bbi = checkpoint.g;
        int ref_iter = int(checkpoint.b);
        float period = checkpoint.a;
 
        int ckpt_refidx = int(lazy.r);
        int pending_refidx = int(lazy.g);
        float ckpt_bbr = lazy.b;
        float ckpt_bbi = lazy.a;
 
        int scale = int(scaleVec.r);
 
        float dcr = dc.r;
        float dci = dc.g;
 
        int fibPrev = u_fibPrev;
        int fibCurr = u_fibCurr;
 
        if (status == 0.0) {
          for (int i = 0; i < 100000; i++) {
            if (i >= u_iterations) break;
 
            int globalIter = u_startIter + i + 1;
 
            // Rebase check: compute actual dz and see if rebasing helps
            float dzr_actual = ldexp(dzr, scale);
            float dzi_actual = ldexp(dzi, scale);
            float dz_norm = max(abs(dzr_actual), abs(dzi_actual));
 
            if (ref_iter > 0 && ref_iter < u_refOrbitLength) {
              vec2 ref_check = getRefOrbit(ref_iter);
              float total_r = ref_check.x + dzr_actual;
              float total_i = ref_check.y + dzi_actual;
              float total_norm = max(abs(total_r), abs(total_i));
 
              if (total_norm < dz_norm * 2.0) {
                // Rebase: dz = Z + dz, reset ref_iter to 0
                dzr_actual = total_r;
                dzi_actual = total_i;
                ref_iter = 0;
 
                // Renormalize the rebased dz back to scaled form
                float mag = max(abs(dzr_actual), abs(dzi_actual));
                if (mag > 0.0 && mag < 1e30) {
                  int new_scale = int(floor(log2(mag)));
                  dzr = ldexp(dzr_actual, -new_scale);
                  dzi = ldexp(dzi_actual, -new_scale);
                  scale = new_scale;
                } else {
                  dzr = dzr_actual;
                  dzi = dzi_actual;
                  scale = 0;
                }
 
                if (ckpt_refidx >= 0) {
                  pending_refidx = ckpt_refidx;
                  bbr = ckpt_bbr;
                  bbi = ckpt_bbi;
                }
              }
            }
 
            if (ref_iter >= u_refOrbitLength) break;
            vec2 ref_val = getRefOrbit(ref_iter);
            float refr = ref_val.x;
            float refi = ref_val.y;
 
            // Escape check using actual values
            dzr_actual = ldexp(dzr, scale);
            dzi_actual = ldexp(dzi, scale);
            float curr_r = refr + dzr_actual;
            float curr_i = refi + dzi_actual;
            float curr_mag_sq = curr_r * curr_r + curr_i * curr_i;
            if (curr_mag_sq > 4.0 || curr_mag_sq != curr_mag_sq) {
              status = 1.0;
              break;
            }
 
            float old_dzr = dzr;
            float old_dzi = dzi;
            int old_ref_iter = ref_iter;
            int old_scale = scale;
 
            // === PERTURBATION ITERATION with scaling ===
            // For z² + c: new_dz = 2*Z*dz + dz² + dc
            // Linear term (2*Z*dz) stays in scaled coordinates
            // Quadratic term (dz²) needs ldexp(dz*dz, scale) since (dz*2^s)² = dz²*2^(2s)
            // dc needs ldexp(dc, initial_scale - scale) to match current scale
            float new_dzr;
            float new_dzi;
            int scale_diff = u_initialScale - scale;
            float dc_r = ldexp(dcr, scale_diff);
            float dc_i = ldexp(dci, scale_diff);
 
            if (u_exponent == 2) {
              float linear_r = 2.0 * (refr * dzr - refi * dzi);
              float linear_i = 2.0 * (refr * dzi + refi * dzr);
              float dz2_r = ldexp(dzr * dzr - dzi * dzi, scale);
              float dz2_i = ldexp(2.0 * dzr * dzi, scale);
              new_dzr = linear_r + dz2_r + dc_r;
              new_dzi = linear_i + dz2_i + dc_i;
            } else if (u_exponent == 3) {
              // z³ + c: 3*Z²*dz + 3*Z*dz² + dz³
              float ref2_r = refr * refr - refi * refi;
              float ref2_i = 2.0 * refr * refi;
              float t1_r = 3.0 * (ref2_r * dzr - ref2_i * dzi);
              float t1_i = 3.0 * (ref2_r * dzi + ref2_i * dzr);
              float dz2_r = dzr * dzr - dzi * dzi;
              float dz2_i = 2.0 * dzr * dzi;
              float t2_r = ldexp(3.0 * (refr * dz2_r - refi * dz2_i), scale);
              float t2_i = ldexp(3.0 * (refr * dz2_i + refi * dz2_r), scale);
              float dz3_r = dzr * dz2_r - dzi * dz2_i;
              float dz3_i = dzr * dz2_i + dzi * dz2_r;
              float t3_r = ldexp(dz3_r, scale + scale);
              float t3_i = ldexp(dz3_i, scale + scale);
              new_dzr = t1_r + t2_r + t3_r + dc_r;
              new_dzi = t1_i + t2_i + t3_i + dc_i;
            } else {
              // Higher exponents: use direct computation
              float zr = refr + dzr_actual;
              float zi = refi + dzi_actual;
              float zn_r = zr;
              float zn_i = zi;
              for (int p = 1; p < 10; p++) {
                if (p >= u_exponent) break;
                float temp_r = zn_r * zr - zn_i * zi;
                zn_i = zn_r * zi + zn_i * zr;
                zn_r = temp_r;
              }
              float refn_r = refr;
              float refn_i = refi;
              for (int p = 1; p < 10; p++) {
                if (p >= u_exponent) break;
                float temp_r = refn_r * refr - refn_i * refi;
                refn_i = refn_r * refi + refn_i * refr;
                refn_r = temp_r;
              }
              new_dzr = (zn_r - refn_r) + dc_r;
              new_dzi = (zn_i - refn_i) + dc_i;
            }
 
            int new_scale = scale;
 
            // === ADAPTIVE RESCALING ===
            float dz_mag = max(abs(new_dzr), abs(new_dzi));
            if (dz_mag > 0.0 && dz_mag < 1e30) {
              float log2_mag = floor(log2(dz_mag));
              if (log2_mag >= 1.0) {
                int steps = int(log2_mag);
                if (new_scale + steps <= 100) {
                  new_dzr = ldexp(new_dzr, -steps);
                  new_dzi = ldexp(new_dzi, -steps);
                  new_scale = new_scale + steps;
                }
              } else if (log2_mag < -1.0 && new_scale > u_initialScale) {
                int steps = min(int(-log2_mag) - 1, new_scale - u_initialScale);
                if (steps > 0) {
                  new_dzr = ldexp(new_dzr, steps);
                  new_dzi = ldexp(new_dzi, steps);
                  new_scale = new_scale - steps;
                }
              }
            }
 
            dzr = new_dzr;
            dzi = new_dzi;
            scale = new_scale;
            iter += 1.0;
            ref_iter++;
 
            if (u_loopEnabled != 0 && ref_iter >= u_loopThreshold) {
              // Loop delta is in actual units, need to convert to scaled
              float loop_dzr = ldexp(u_loopDeltaR, -scale);
              float loop_dzi = ldexp(u_loopDeltaI, -scale);
              dzr += loop_dzr;
              dzi += loop_dzi;
              ref_iter -= u_loopJump;
            }
 
            // Bounding box updates use old values (before this iteration)
            bool just_updated = false;
            if (globalIter == fibCurr) {
              just_updated = true;
              bbr = old_dzr;
              bbi = old_dzi;
              ckpt_bbr = old_dzr;
              ckpt_bbi = old_dzi;
              ckpt_refidx = old_ref_iter;
              pending_refidx = old_ref_iter;
              period = 0.0;
              int nextFib = fibPrev + fibCurr;
              fibPrev = fibCurr;
              fibCurr = nextFib;
            }
 
            if (ckpt_refidx >= 0 && !just_updated) {
              if (ref_iter == ckpt_refidx) {
                float diff_r = old_dzr - bbr;
                float diff_i = old_dzi - bbi;
                float db = max(abs(diff_r), abs(diff_i));
                // Scale epsilon to match the stored scale
                float eps = ldexp(u_epsilon, -old_scale);
                float eps2 = ldexp(u_epsilon2, -old_scale);
                if (db <= eps2) {
                  if (period == 0.0) period = iter;
                  if (db <= eps) {
                    status = 2.0;
                    break;
                  }
                }
              }
 
              if (pending_refidx >= 2584 && pending_refidx < u_refOrbitLength) {
                vec3 thread = getThread(pending_refidx);
                if (thread.x >= 0.0 && int(thread.x) == ref_iter) {
                  // Thread deltas are in actual units, convert to old_scale
                  float thread_r = ldexp(thread.y, -old_scale);
                  float thread_i = ldexp(thread.z, -old_scale);
                  float diff_r = old_dzr - bbr + thread_r;
                  float diff_i = old_dzi - bbi + thread_i;
                  float db = max(abs(diff_r), abs(diff_i));
                  float eps = ldexp(u_epsilon, -old_scale);
                  float eps2 = ldexp(u_epsilon2, -old_scale);
                  if (db <= eps2) {
                    if (period == 0.0) period = iter;
                    if (db <= eps) {
                      status = 2.0;
                      break;
                    }
                  }
                  bbr -= thread_r;
                  bbi -= thread_i;
                  pending_refidx = ref_iter;
                }
              }
            }
          }
        }
 
        outState = vec4(dzr, dzi, iter, status);
        outCheckpoint = vec4(bbr, bbi, float(ref_iter), period);
        outLazy = vec4(float(ckpt_refidx), float(pending_refidx), ckpt_bbr, ckpt_bbi);
        outScale = vec4(float(scale), 0.0, 0.0, 0.0);
      }
    `;
  }
 
  initializeStateTextures() {
    const gl = this.gl;
    const w = this.texWidth;
    const h = this.texHeight;
    const area = w * h;
 
    const stateData = new Float32Array(area * 4);
    const checkpointData = new Float32Array(area * 4);
    const lazyData = new Float32Array(area * 4);
    const scaleData = new Float32Array(area * 4);
 
    for (let i = 0; i < area; i++) {
      stateData[i * 4 + 0] = this.dz[i * 2];
      stateData[i * 4 + 1] = this.dz[i * 2 + 1];
      stateData[i * 4 + 2] = 1.0;  // iter
      stateData[i * 4 + 3] = 0.0;  // status
 
      checkpointData[i * 4 + 0] = 0.0;
      checkpointData[i * 4 + 1] = 0.0;
      checkpointData[i * 4 + 2] = 1.0;
      checkpointData[i * 4 + 3] = 0.0;
 
      lazyData[i * 4 + 0] = -1.0;
      lazyData[i * 4 + 1] = -1.0;
      lazyData[i * 4 + 2] = 0.0;
      lazyData[i * 4 + 3] = 0.0;
 
      // Scale texture: (scale, 0, 0, 0)
      scaleData[i * 4 + 0] = this.pixelScale[i];
      scaleData[i * 4 + 1] = 0.0;
      scaleData[i * 4 + 2] = 0.0;
      scaleData[i * 4 + 3] = 0.0;
    }
 
    gl.bindTexture(gl.TEXTURE_2D, this.pingStateTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.FLOAT, stateData);
    gl.bindTexture(gl.TEXTURE_2D, this.pingCheckpointTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.FLOAT, checkpointData);
    gl.bindTexture(gl.TEXTURE_2D, this.pingLazyTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.FLOAT, lazyData);
    gl.bindTexture(gl.TEXTURE_2D, this.pingScaleTex);
    gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, w, h, gl.RGBA, gl.FLOAT, scaleData);
  }
 
  doGpuIterations(targetIters) {
    const gl = this.gl;
 
    // Get Fibonacci checkpoints
    while (this.fibCache[this.fibCache.length - 1] < this.it + targetIters + 1000) {
      const n = this.fibCache.length;
      this.fibCache.push(this.fibCache[n - 1] + this.fibCache[n - 2]);
    }
    let fibIdx = 0;
    while (this.fibCache[fibIdx] <= this.it) fibIdx++;
    const fibPrev = fibIdx > 0 ? this.fibCache[fibIdx - 1] : 1;
    const fibCurr = this.fibCache[fibIdx];
 
    // Bind shader and set uniforms
    gl.useProgram(this.iterProgram);
 
    gl.activeTexture(gl.TEXTURE3);
    gl.bindTexture(gl.TEXTURE_2D, this.deltaCTex);
    gl.uniform1i(this.iterUniforms.u_deltaC, 3);
 
    gl.activeTexture(gl.TEXTURE4);
    gl.bindTexture(gl.TEXTURE_2D, this.refOrbitTex);
    gl.uniform1i(this.iterUniforms.u_refOrbit, 4);
 
    gl.uniform2f(this.iterUniforms.u_resolution, this.texWidth, this.texHeight);
    gl.uniform1i(this.iterUniforms.u_iterations, targetIters);
    gl.uniform1i(this.iterUniforms.u_exponent, this.config.exponent);
    gl.uniform1f(this.iterUniforms.u_epsilon, this.epsilon);
    gl.uniform1f(this.iterUniforms.u_epsilon2, this.epsilon2);
    gl.uniform1f(this.iterUniforms.u_pixelSize, this.pix);
    gl.uniform1i(this.iterUniforms.u_startIter, this.it);
    gl.uniform1i(this.iterUniforms.u_refOrbitLength, this.refIterations);
    gl.uniform1i(this.iterUniforms.u_refOrbitTexWidth, this.refOrbitTexWidth);
    gl.uniform1i(this.iterUniforms.u_fibPrev, fibPrev);
    gl.uniform1i(this.iterUniforms.u_fibCurr, fibCurr);
 
    // Loop parameters
    gl.uniform1i(this.iterUniforms.u_loopEnabled, this.refOrbitLoop.enabled ? 1 : 0);
    gl.uniform1i(this.iterUniforms.u_loopThreshold, this.refOrbitLoop.threshold || 0);
    gl.uniform1i(this.iterUniforms.u_loopJump, this.refOrbitLoop.jumpAmount || 0);
    gl.uniform1f(this.iterUniforms.u_loopDeltaR, this.refOrbitLoop.deltaR || 0);
    gl.uniform1f(this.iterUniforms.u_loopDeltaI, this.refOrbitLoop.deltaI || 0);
 
    // GlAdaptiveBoard-specific: initial scale uniform
    gl.uniform1i(this.iterUniforms.u_initialScale, this.initialScale);
 
    // Bind input textures
    const readState = this.isPingRead ? this.pingStateTex : this.pongStateTex;
    const readCheckpoint = this.isPingRead ? this.pingCheckpointTex : this.pongCheckpointTex;
    const readLazy = this.isPingRead ? this.pingLazyTex : this.pongLazyTex;
    const readScale = this.isPingRead ? this.pingScaleTex : this.pongScaleTex;
    // Write to the OPPOSITE buffer (ping-pong pattern)
    const writeFB = this.isPingRead ? this.pongFB : this.pingFB;
 
    gl.activeTexture(gl.TEXTURE0);
    gl.bindTexture(gl.TEXTURE_2D, readState);
    gl.uniform1i(this.iterUniforms.u_state, 0);
 
    gl.activeTexture(gl.TEXTURE1);
    gl.bindTexture(gl.TEXTURE_2D, readCheckpoint);
    gl.uniform1i(this.iterUniforms.u_checkpoint, 1);
 
    gl.activeTexture(gl.TEXTURE2);
    gl.bindTexture(gl.TEXTURE_2D, readLazy);
    gl.uniform1i(this.iterUniforms.u_lazy, 2);
 
    // GlAdaptiveBoard-specific: bind scale texture
    gl.activeTexture(gl.TEXTURE5);
    gl.bindTexture(gl.TEXTURE_2D, readScale);
    gl.uniform1i(this.iterUniforms.u_scale, 5);
 
    // Draw
    gl.bindFramebuffer(gl.FRAMEBUFFER, writeFB);
    gl.viewport(0, 0, this.texWidth, this.texHeight);
    gl.bindVertexArray(this.quadVAO);
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
 
    this.isPingRead = !this.isPingRead;
    this.it += targetIters;
  }
 
  uploadRefOrbit() {
    const gl = this.gl;
    const refLen = this.refIterations;
 
    if (refLen <= this.lastUploadedRefIter) return;
 
    const texelsNeeded = refLen * 2;
    const texWidth = this.refOrbitTexWidth;
    const rowsNeeded = Math.ceil(texelsNeeded / texWidth);
 
    if (rowsNeeded > this.refOrbitTexHeight) {
      console.warn('Reference orbit exceeds texture size');
      return;
    }
 
    const data = new Float32Array(texWidth * rowsNeeded * 4);
 
    // Fill from 0, not lastUploadedRefIter, to avoid overwriting existing data with zeros
    // when texSubImage2D uploads full rows
    for (let i = 0; i < refLen; i++) {
      const orbit = this.qdRefOrbit[i];
      const thread = this.threading.getThread(i);
      const texelIdx = i * 2;
 
      const dataIdx1 = texelIdx * 4;
      // Sum QD components to get f32 value for ref orbit
      data[dataIdx1 + 0] = orbit ? orbit[0] + orbit[1] + orbit[2] + orbit[3] : 0;
      data[dataIdx1 + 1] = orbit ? orbit[4] + orbit[5] + orbit[6] + orbit[7] : 0;
      data[dataIdx1 + 2] = thread.next;
      data[dataIdx1 + 3] = thread.deltaRe;
 
      const dataIdx2 = (texelIdx + 1) * 4;
      data[dataIdx2 + 0] = thread.deltaIm;
      data[dataIdx2 + 1] = 0.0;
      data[dataIdx2 + 2] = 0.0;
      data[dataIdx2 + 3] = 0.0;
    }
 
    gl.bindTexture(gl.TEXTURE_2D, this.refOrbitTex);
 
    // Upload only new rows (rows that weren't fully uploaded before)
    const startRow = Math.floor(this.lastUploadedRefIter * 2 / texWidth);
    const endRow = Math.ceil(refLen * 2 / texWidth);
 
    for (let row = startRow; row < endRow; row++) {
      const rowOffset = row * texWidth * 4;
      const rowData = data.subarray(rowOffset, rowOffset + texWidth * 4);
      gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, row, texWidth, 1, gl.RGBA, gl.FLOAT, rowData);
    }
 
    this.lastUploadedRefIter = refLen;
  }
 
  async serialize() {
    const base = await super.serialize();
    return {
      ...base,
      refC_qd: this.refC_qd,
      qdRefOrbit: this.qdRefOrbit,
      initialScale: this.initialScale,
      pixelScale: Array.from(this.pixelScale)
    };
  }
 
  static fromSerialized(serialized) {
    const board = new GlAdaptiveBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    board.glInitPromise = board.glInitPromise.then(() => {
      board.it = serialized.it;
      board.un = serialized.un;
      board.di = serialized.di;
      board.ch = serialized.ch || 0;
 
      if (serialized.reported) {
        board.reported = new Uint8Array(serialized.reported);
      }
 
      board.cMinRe = serialized.cMinRe;
      board.cMinIm = serialized.cMinIm;
      board.cMaxRe = serialized.cMaxRe;
      board.cMaxIm = serialized.cMaxIm;
 
      if (serialized.refC_qd) {
        board.refC_qd = serialized.refC_qd;
      }
      if (serialized.qdRefOrbit) {
        board.qdRefOrbit = serialized.qdRefOrbit;
        board.refIterations = serialized.qdRefOrbit.length;
      }
      if (serialized.initialScale !== undefined) {
        board.initialScale = serialized.initialScale;
      }
      if (serialized.pixelScale) {
        board.pixelScale = new Int32Array(serialized.pixelScale);
      }
 
      board.nn = new Array(serialized.config.dimsArea).fill(0);
      if (serialized.completedIndexes) {
        for (let i = 0; i < serialized.completedIndexes.length; i++) {
          board.nn[serialized.completedIndexes[i]] = serialized.completedNn[i];
        }
      }
    });
 
    return board;
  }
}
 
// Base class for double-buffered GPU perturbation boards (GpuZhuoranBoard, GpuAdaptiveBoard)
// Provides shared double-buffering infrastructure and result processing
class GpuZhuoranBaseBoard extends GpuBaseBoard {
  // Subclasses must define: static BYTES_PER_PIXEL, static STRIDE
  // PixelState layout: orig_index, iter, status, period, ... (orig_index at offset 0)
 
  // Initialize double-buffering and compaction state (call from subclass constructor)
  initDoubleBuffering() {
    this.stagingBufferIndex = 0;
    this.hasPendingResults = false;
    this.pendingIterationsPerBatch = 0;
    this.baseIt = 1;  // Committed iteration count
 
    // Compaction state - uses bandwidth cost model
    // Compact when cumulative wasted bandwidth > compaction cost
    this.activeCount = this.config.dimsArea;
    this.deadSinceCompaction = 0;
    this.wastedBandwidth = 0;  // Cumulative bytes wasted copying dead pixels
    this.compactionCount = 0;  // Number of compactions performed
    this.pendingActiveCount = this.config.dimsArea;
    this.lastBatchCompacted = false;
    this.cumulativeWastedReads = 0;
  }
 
  // Return iteration count for submitted GPU batches (same as GpuBoard)
  get it() {
    return this.baseIt;
  }
 
  set it(value) {
    this.baseIt = value;
  }
 
  async flushPendingResults() {
    // Process pending results from the staging buffer without starting a new batch
    if (!this.hasPendingResults) return;
 
    if (this.pendingReadbackIndex !== null) {
      await this.processPendingReadback();
    }
 
    // Continue draining results until all are read
    // The staging shader reads from lastStaged which advances each time we read a chunk
    let moreData = true;
    while (moreData) {
      const readbackIndex = this.readbackBufferIndex;
      const commandEncoder = this.device.createCommandEncoder({ label: 'GpuZhuoran drain readback' });
      this.queueResultsReadback(commandEncoder, readbackIndex);
      this.device.queue.submit([commandEncoder.finish()]);
      await this.device.queue.onSubmittedWorkDone();
 
      // Read and process the chunk
      const { countInChunk, data } = await this.readResultsChunk(readbackIndex);
 
      if (countInChunk === 0) {
        moreData = false;  // No more results to read
      } else if (data) {
        this.processResultsData(data, countInChunk);
      }
 
      this.readbackBufferIndex = 1 - readbackIndex;
    }
  }
 
  async readPixelBuffer() {
    // Read GPU pixel buffer for serialization - creates temporary staging buffer on-demand
    if (!this.isGPUReady || !this.buffers.pixels) {
      return null;
    }
 
    const BYTES_PER_PIXEL = this.constructor.BYTES_PER_PIXEL;
    const bufferSize = this.activeCount * BYTES_PER_PIXEL;
 
    // Create temporary staging buffer (only needed during serialization)
    const stagingBuffer = this.device.createBuffer({
      size: bufferSize,
      usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
      label: 'Temp staging for serialization'
    });
 
    // Copy pixels buffer to staging
    const commandEncoder = this.device.createCommandEncoder();
    commandEncoder.copyBufferToBuffer(this.buffers.pixels, 0, stagingBuffer, 0, bufferSize);
    this.device.queue.submit([commandEncoder.finish()]);
    await this.device.queue.onSubmittedWorkDone();
 
    // Read back the data
    await stagingBuffer.mapAsync(GPUMapMode.READ, 0, bufferSize);
    const pixelData = new ArrayBuffer(bufferSize);
    const srcData = stagingBuffer.getMappedRange(0, bufferSize);
    new Uint8Array(pixelData).set(new Uint8Array(srcData));
    stagingBuffer.unmap();
 
    // Destroy temporary buffer immediately
    stagingBuffer.destroy();
 
    return pixelData;
  }
}
 
// WebGPU-accelerated perturbation board using Zhuoran's approach
// Computes high-precision reference orbit on CPU, perturbations on GPU
// Uses DDReferenceOrbitMixin for reference orbit computation
class GpuZhuoranBoard extends DDReferenceOrbitMixin(GpuZhuoranBaseBoard) {
  static BYTES_PER_PIXEL = 60;  // 7 u32 + 8 f32 (with orig_index for compaction)
  static STRIDE = 15;           // 15 fields per pixel
 
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
    this.effort = 18;  // Doubled to reduce batch sizes after GPU readback improvements
 
    // Initialize DD reference orbit (refC, refOrbit, threading, etc.)
    const refRe = Array.isArray(re) ? re : toDD(re);
    const refIm = Array.isArray(im) ? im : toDD(im);
    this.initDDReferenceOrbit([refRe[0], refRe[1], refIm[0], refIm[1]]);
 
    // Initialize per-pixel perturbation data
    this.initPixels(size, re, im);
 
    // Initialize double-buffering (from GpuZhuoranBaseBoard)
    this.initDoubleBuffering();
 
    // Start GPU initialization (async)
    this.gpuInitPromise = this.initGPU();
  }
 
  initPixels(size, re, im) {
    const dimsWidth = this.config.dimsWidth;
    const dimsHeight = this.config.dimsHeight;
    const dimsArea = this.config.dimsArea;
 
    // Convert re/im to DD precision if needed
    const re_dd = Array.isArray(re) ? re : toDD(re);
    const im_dd = Array.isArray(im) ? im : toDD(im);
    // Convert size to scalar if it's a QD array (fixes NaN when size is array)
    const size_scalar = Array.isArray(size) ? size.reduce((a, b) => a + (b || 0), 0) : size;
    const size_dd = toDD(size_scalar);
    const sizeY_dd = toDD(size_scalar / this.config.aspectRatio);
 
    // Per-pixel data arrays
    this.dc = new Float32Array(dimsArea * 2);
    // Delta c from reference [real, imag] pairs
    this.dz = new Float32Array(dimsArea * 2);
    // Current perturbation delta [real, imag] pairs
    this.refIter = new Uint32Array(dimsArea);
    // Which iteration of reference each pixel is following
 
    // Working arrays for DD precision arithmetic
    const cr_dd = new Array(4);
    const ci_dd = new Array(4);
    const dcr_dd = new Array(4);
    const dci_dd = new Array(4);
    const temp = new Array(4);
 
    // Initialize all pixels as perturbations from the reference point
    for (let y = 0; y < dimsHeight; y++) {
      // Use integer arithmetic to avoid float64 rounding: (dims/2 - y) / dims
      const yFrac = (dimsHeight / 2 - y) / dimsHeight;
 
      // ci_dd = im_dd + yFrac * sizeY_dd (in DD precision)
      arDdMul(temp, 0, yFrac, 0, sizeY_dd[0], sizeY_dd[1]);
      arDdAdd(ci_dd, 0, im_dd[0], im_dd[1], temp[0], temp[1]);
 
      // dci_dd = ci_dd - refC_imag
      arDdAdd(dci_dd, 0, ci_dd[0], ci_dd[1], -this.refC[2], -this.refC[3]);
 
      for (let x = 0; x < dimsWidth; x++) {
        // Use integer arithmetic to avoid float64 rounding: (x - dims/2) / dims
        const xFrac = (x - dimsWidth / 2) / dimsWidth;
 
        // cr_dd = re_dd + xFrac * size_dd (in DD precision)
        arDdMul(temp, 0, xFrac, 0, size_dd[0], size_dd[1]);
        arDdAdd(cr_dd, 0, re_dd[0], re_dd[1], temp[0], temp[1]);
 
        // dcr_dd = cr_dd - refC_real
        arDdAdd(dcr_dd, 0, cr_dd[0], cr_dd[1], -this.refC[0], -this.refC[1]);
 
        const index = y * dimsWidth + x;
        const index2 = index * 2;
 
        // Convert DD precision deltas to float32 (Math.fround simulates GPU precision)
        this.dc[index2] = Math.fround(dcr_dd[0] + dcr_dd[1]);
        this.dc[index2 + 1] = Math.fround(dci_dd[0] + dci_dd[1]);
 
        // Start with dz = dc (so z = c_ref + dc = c)
        this.dz[index2] = this.dc[index2];
        this.dz[index2 + 1] = this.dc[index2 + 1];
 
        // Start at iteration 1 (where refOrbit[1] = c_ref)
        this.refIter[index] = 1;
      }
    }
 
    this.checkSpike(size, re, im);
  }
 
  async createBuffers() {
    const dimsArea = this.config.dimsWidth * this.config.dimsHeight;
    const BYTES_PER_PIXEL = GpuZhuoranBoard.BYTES_PER_PIXEL;
    const STRIDE = GpuZhuoranBoard.STRIDE;
 
    // Check buffer size limits before creating (safety margin applied upstream)
    const maxBufferSize = Math.min(
      this.device.limits.maxBufferSize,
      this.device.limits.maxStorageBufferBindingSize
    );
    // Unified PixelState struct: 7 u32 + 8 f32 = 60 bytes per pixel (with orig_index)
    const precomputedCount = this.precomputed ? this.precomputed.getPrecomputedCount() : 0;
    const activePixelCount = dimsArea - precomputedCount;
    const pixelBufferSize = Math.max(BYTES_PER_PIXEL, activePixelCount * BYTES_PER_PIXEL);
 
    if (pixelBufferSize > maxBufferSize) {
      throw new Error(
        `Buffer size (${(pixelBufferSize / (1024 * 1024)).toFixed(1)} MB) ` +
        `exceeds WebGPU limit (${(maxBufferSize / (1024 * 1024)).toFixed(1)} MB). ` +
        `Board ${this.config.dimsWidth}x${this.config.dimsHeight} is too large ` +
        `for GPU acceleration.`);
    }
    const resultsBufferSize = 16 + (activePixelCount * BYTES_PER_PIXEL);
    if (resultsBufferSize > maxBufferSize) {
      throw new Error(
        `Results buffer size (${(resultsBufferSize / (1024 * 1024)).toFixed(1)} MB) ` +
        `exceeds WebGPU limit (${(maxBufferSize / (1024 * 1024)).toFixed(1)} MB).`);
    }
 
    // Single unified pixel state buffer (PixelState struct: 7 u32 + 8 f32 = 60 bytes per pixel)
    // Layout per pixel: [orig_index, iter, status, period, ref_iter, ckpt_refidx, pending_refidx,
    //                    dzr, dzi, bbr, bbi, ckpt_bbr, ckpt_bbi, dcr, dci]
    this.buffers.pixels = this.device.createBuffer({
      size: pixelBufferSize,
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
      label: 'Pixel state buffer'
    });
 
    // Unified iteration state buffer (IterState struct: 5 f32 = 20 bytes per iteration)
    // Combines reference orbit (re, im) and threading data (next, deltaRe, deltaIm)
    // Start with 1MB, will grow by doubling up to 128MB cap
    this.buffers.iters = this.device.createBuffer({
      size: 1 * 1024 * 1024,
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
      label: 'Iteration state buffer'
    });
 
    // Track last uploaded iteration length
    this.lastUploadedIterLength = -1;  // -1 means nothing uploaded yet
 
    // Uniform buffer for parameters
    this.buffers.params = this.device.createBuffer({
      size: 256,  // Increased to hold 32 checkpoint slots
      usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
      label: 'Params buffer'
    });
 
    // Note: stagingPixels buffers are created on-demand in readPixelBuffer() for serialization
    // This saves ~2x pixel buffer size in GPU memory during normal operation
 
    // Initialize pixel state buffer using overlapping typed array views
    // ArrayBuffer holds 60 bytes per pixel (15 x 4 bytes, with orig_index)
    const pixelData = new ArrayBuffer(pixelBufferSize);
    const pixelU32 = new Uint32Array(pixelData);   // For u32 fields (indices 0-6)
    const pixelF32 = new Float32Array(pixelData);  // For f32 fields (indices 7-14)
 
    let activeIdx = 0;
    for (let i = 0; i < dimsArea; i++) {
      if (this.precomputed && this.precomputed.isPrecomputed(i)) {
        continue;
      }
      const idx = activeIdx * STRIDE;  // 15 x 4-byte values per pixel
      // Integer fields (offsets 0-6)
      pixelU32[idx + 0] = i;                       // orig_index (for coordinate computation after compaction)
      pixelU32[idx + 1] = 1;                       // iter (start at 1, z=c is iteration 1)
      pixelU32[idx + 2] = 0;                       // status (0 = computing)
      pixelU32[idx + 3] = 0;                       // period
      pixelU32[idx + 4] = this.refIter[i];        // ref_iter
      pixelU32[idx + 5] = 0xFFFFFFFF;             // ckpt_refidx (sentinel)
      pixelU32[idx + 6] = 0xFFFFFFFF;             // pending_refidx (sentinel)
      // Float fields (offsets 7-14)
      pixelF32[idx + 7] = this.dz[i * 2];         // dzr
      pixelF32[idx + 8] = this.dz[i * 2 + 1];     // dzi
      pixelF32[idx + 9] = 0;                       // bbr
      pixelF32[idx + 10] = 0;                      // bbi
      pixelF32[idx + 11] = 0;                      // ckpt_bbr
      pixelF32[idx + 12] = 0;                      // ckpt_bbi
      pixelF32[idx + 13] = this.dc[i * 2];        // dcr
      pixelF32[idx + 14] = this.dc[i * 2 + 1];    // dci
      activeIdx++;
    }
 
    // Initialize unified iters buffer with initial data (iter 0 and 1)
    // IterState struct: [ref_re, ref_im, thread_next, thread_delta_re, thread_delta_im] = 5 f32
    const initialIterData = new Float32Array(10);  // 2 iters * 5 floats
    // iter 0: z=0, no thread
    initialIterData[0] = 0;   // ref_re
    initialIterData[1] = 0;   // ref_im
    initialIterData[2] = -1;  // thread_next (-1 = no thread)
    initialIterData[3] = 0;   // thread_delta_re
    initialIterData[4] = 0;   // thread_delta_im
    // iter 1: z=c_ref, no thread
    initialIterData[5] = this.refC[0] + this.refC[1];  // ref_re
    initialIterData[6] = this.refC[2] + this.refC[3];  // ref_im
    initialIterData[7] = -1;  // thread_next
    initialIterData[8] = 0;   // thread_delta_re
    initialIterData[9] = 0;   // thread_delta_im
 
    this.device.queue.writeBuffer(this.buffers.pixels, 0, pixelU32);
    this.device.queue.writeBuffer(this.buffers.iters, 0, initialIterData);
 
    // Mark initial data as uploaded
    this.lastUploadedIterLength = 1;  // Uploaded iters 0 and 1
 
    this.activeCount = activePixelCount;
    this.pendingActiveCount = activePixelCount;
    this.deadSinceCompaction = 0;
    this.wastedBandwidth = 0;
    this.initResultsReadback(BYTES_PER_PIXEL, activePixelCount);
  }
 
  createBindGroup() {
    // Unified 5-binding layout for maximum cache coherency
    this.bindGroup = this.device.createBindGroup({
      layout: this.pipeline.getBindGroupLayout(0),
      entries: [
        { binding: 0, resource: { buffer: this.buffers.params } },
        { binding: 1, resource: { buffer: this.buffers.pixels } },
        { binding: 2, resource: { buffer: this.buffers.iters } },
        { binding: 3, resource: { buffer: this.buffers.results } },
        { binding: 4, resource: { buffer: this.buffers.lock } }
      ],
      label: 'Perturbation bind group'
    });
  }
 
  /**
   * Process GPU results using batch-oriented approach (same as GpuBoard).
   * This ensures results are only sent to changeList when batches complete,
   * preventing out-of-order iteration delivery that causes striping.
   */
  processResultsData(data, count) {
    const STRIDE = GpuZhuoranBoard.STRIDE;
    const pixelU32 = new Uint32Array(data);
    const pixelF32 = new Float32Array(data);
    const debugReadback = hasDebugFlag(this.config, 'rb');
 
    this.lastResultsCount = count;
    this.resultsReadbackBatches += 1;
    this.resultsReadbackBytes += count * this.resultsRecordBytes;
 
    const INT_ORIG_INDEX = 0, INT_ITER = 1, INT_STATUS = 2, INT_PERIOD = 3, INT_REF_ITER = 4;
    const FLOAT_DZR = 7, FLOAT_DZI = 8;
 
    let dataIndex = 0;
 
    // OUTER LOOP: Process batches in order
    while (this.batchesToReadback.length > 0) {
      const batch = this.batchesToReadback[0];
 
      // Flush precomputed points before this batch's iteration range
      if (this.precomputed) {
        this.flushPrecomputedUpTo(this.previousBatchEndIter - 1);
      }
 
      // INNER LOOP: Process available data for this batch
      while (batch.remainingPixelCount > 0 && dataIndex < count) {
        const idx = dataIndex * STRIDE;
        const origIndex = pixelU32[idx + INT_ORIG_INDEX];
        const status = pixelU32[idx + INT_STATUS];
        const period = pixelU32[idx + INT_PERIOD];
 
        const iters = pixelU32[idx + INT_ITER];
 
        // Skip already processed pixels (shouldn't happen, but defensive)
        if (this.nn[origIndex] !== 0) {
          if (debugReadback) {
            const same = this.nn[origIndex] === iters ? ' (SAME VALUE)' : ' (DIFFERENT VALUE)';
            console.error(`INVARIANT VIOLATION: Duplicate result for pixel ${origIndex}, existing nn=${this.nn[origIndex]}, new iters=${iters}${same}`);
          }
          dataIndex++;
          continue;
        }
 
        // Skip non-finished pixels (status 0 = still computing)
        if (status === 0) {
          dataIndex++;
          continue;
        }
 
        if (status === 1) {
          // Diverged
          this.nn[origIndex] = iters;
          this.pp[origIndex] = period;
          this.di++;
          if (this.inSpike && this.inSpike[origIndex] && this.ch > 0) this.ch -= 1;
 
          // Accumulate into batchResultsRead
          this.batchResultsRead.push({ iter: iters, nn: [origIndex], vv: [] });
        } else if (status === 2) {
          // Converged
          this.nn[origIndex] = -iters;
          this.pp[origIndex] = period - 1;
          if (this.inSpike && this.inSpike[origIndex] && this.ch > 0) this.ch -= 1;
 
          // Compute final z value using DD reference orbit
          const refIter = pixelU32[idx + INT_REF_ITER];
          const nextRefIter = refIter + 1;
          const dzr = pixelF32[idx + FLOAT_DZR];
          const dzi = pixelF32[idx + FLOAT_DZI];
 
          const ref = this.refOrbit[Math.min(nextRefIter, this.refOrbit.length - 1)];
          
          // Accumulate into batchResultsRead
          this.batchResultsRead.push({
            iter: iters,
            nn: [],
            vv: [{ index: origIndex, z: this.refDzNative(ref, dzr, dzi), p: this.pp[origIndex] }]
          });
        }
 
        this.deadSinceCompaction++;
        batch.remainingPixelCount--;
        dataIndex++;
      }
 
      // Check if batch is complete
      if (batch.remainingPixelCount > 0) {
        // Batch not complete - exit and wait for more data
        break;
      }
 
      // BATCH COMPLETE - Flush to changeList
 
      // Flush precomputed points up to this batch's end iteration
      if (this.precomputed) {
        this.flushPrecomputedIntoResults(batch.endIter - 1);
      }
 
      // Queue results to changeList using queueChanges
      for (const change of this.batchResultsRead) {
        this.queueChanges(change);
      }
 
      // Clear for next batch
      this.batchResultsRead.length = 0;
      this.previousBatchEndIter = batch.endIter;
      this.batchesToReadback.shift();
    }
 
    // Update un count
    // deadSinceCompaction includes results in batchResultsRead that aren't flushed yet
    // Add them back since they're not in changeList yet (view won't see them)
    const pendingPrecomputed = this.precomputed ? this.precomputed.getPendingCount() : 0;
    const pendingInBatchResults = this.batchResultsRead.length;
    this.un = (this.activeCount - this.deadSinceCompaction) + pendingPrecomputed + pendingInBatchResults;
  }
 
  // extendReferenceOrbit() inherited from DDReferenceOrbitMixin
 
  setupReferenceOrbitLoop() {
    // When reference orbit hits threading limit, find a close point to loop back to
    const THREADING_CAPACITY = 1048576;  // 2^20
    const SEARCH_WINDOW = 12000;
 
    if (this.refIterations < THREADING_CAPACITY || this.refOrbitLoopConfigured) {
      return; // Not at limit yet, or already configured
    }
 
    // Get endpoint (current position at threading limit)
    const endpoint = this.refOrbit[THREADING_CAPACITY];
    const endR = endpoint[0] + endpoint[1];
    const endI = endpoint[2] + endpoint[3];
 
    // Search back to find closest point
    let closestIter = THREADING_CAPACITY - SEARCH_WINDOW;
    let closestDist = Infinity;
 
    for (let i = THREADING_CAPACITY - SEARCH_WINDOW; i < THREADING_CAPACITY; i++) {
      const pt = this.refOrbit[i];
      const ptR = pt[0] + pt[1];
      const ptI = pt[2] + pt[3];
      const dr = endR - ptR;
      const di = endI - ptI;
      const dist = Math.max(Math.abs(dr), Math.abs(di)); // Chebyshev distance
 
      if (dist <= closestDist) {  // Use <= to take latest point when tied
        closestDist = dist;
        closestIter = i;
      }
    }
 
    // Compute delta in DD precision
    const closestPt = this.refOrbit[closestIter];
    const tt = this.tt;
    arDdAdd(tt, 0, endpoint[0], endpoint[1], -closestPt[0], -closestPt[1]); // real delta
    arDdAdd(tt, 2, endpoint[2], endpoint[3], -closestPt[2], -closestPt[3]); // imag delta
 
    // Store loop parameters
    this.refOrbitLoop = {
      enabled: true,
      threshold: THREADING_CAPACITY,
      jumpAmount: THREADING_CAPACITY - closestIter,
      deltaR: tt[0] + tt[1], // Convert to float64
      deltaI: tt[2] + tt[3]
    };
 
    this.refOrbitLoopConfigured = true;
 
    // Update threading for loop segment to wrap around
    const loopDeltaR = this.refOrbitLoop.deltaR;
    const loopDeltaI = this.refOrbitLoop.deltaI;
    const epsilon3 = this.threading.epsilon3;
 
    // For each iteration in the loop segment, check if it can thread to another iteration
    // considering the loop wrap (iterations will repeat with a delta offset)
    for (let i = closestIter; i <= THREADING_CAPACITY; i++) {
      const iPt = this.refOrbit[i];
      const iR = iPt[0] + iPt[1];
      const iI = iPt[2] + iPt[3];
 
      // Check if we can thread to same or later iteration (considering it will wrap with delta)
      // Allow j = i for self-threading within the loop (period-N orbits repeat with delta)
      for (let j = i; j <= THREADING_CAPACITY; j++) {
        const jPt = this.refOrbit[j];
        // After loop, iteration j will be at position refOrbit[j] + loop_delta
        const jR = jPt[0] + jPt[1] + loopDeltaR;
        const jI = jPt[2] + jPt[3] + loopDeltaI;
 
        const dr = iR - jR;
        const di = iI - jI;
        const dist = Math.max(Math.abs(dr), Math.abs(di));
 
        if (dist <= epsilon3) {
          // Thread i -> j (wrapping through the loop)
          this.threading.setThread(i, j, jR - iR, jI - iI);
          break;  // Take first match
        }
      }
    }
  }
 
  async createComputePipeline() {
    const shaderCode = `
      struct Params {
        dims_width: u32,
        dims_height: u32,
        iterations_per_batch: u32,
        active_count: u32,
        ref_orbit_length: u32,
        exponent: u32,
        workgroups_x: u32,
        start_iter: u32,
        checkpoint_count: u32,
        buffer_index: u32,      // 0 or 1, for per-buffer batch_active
        ckpt0: u32, ckpt1: u32, ckpt2: u32, ckpt3: u32,
        ckpt4: u32, ckpt5: u32, ckpt6: u32, ckpt7: u32,
        ckpt8: u32, ckpt9: u32, ckpt10: u32, ckpt11: u32,
        ckpt12: u32, ckpt13: u32, ckpt14: u32, ckpt15: u32,
        ckpt16: u32, ckpt17: u32, ckpt18: u32, ckpt19: u32,
        ckpt20: u32, ckpt21: u32, ckpt22: u32, ckpt23: u32,
        ckpt24: u32, ckpt25: u32, ckpt26: u32, ckpt27: u32,
        ckpt28: u32, ckpt29: u32, ckpt30: u32, ckpt31: u32,
        _pad_ckpt: u32,         // Padding after checkpoints
        loop_enabled: u32,      // 1 if loop enabled, 0 otherwise
        loop_threshold: u32,    // ref_iter threshold to trigger loop
        loop_jump: u32,         // Amount to subtract from ref_iter
        pixel_size: f32,
        aspect_ratio: f32,
        loop_delta_r: f32,      // Delta to add to dzr
        loop_delta_i: f32,      // Delta to add to dzi
      }
 
      // Per-pixel state: 7 u32 + 8 f32 = 60 bytes (with orig_index for compaction)
      // Layout (u32 view):
      //   [0] orig_index: u32  (original pixel index for sparse processing)
      //   [1] iter: u32
      //   [2] status: u32
      //   [3] period: u32
      //   [4] ref_iter: u32
      //   [5] ckpt_refidx: u32
      //   [6] pending_refidx: u32
      //   [7] dzr: f32
      //   [8] dzi: f32
      //   [9] bbr: f32
      //   [10] bbi: f32
      //   [11] ckpt_bbr: f32
      //   [12] ckpt_bbi: f32
      //   [13] dcr: f32
      //   [14] dci: f32
      struct PixelState {
        // Integer fields (7 u32)
        orig_index: u32,
        iter: u32,
        status: u32,
        period: u32,
        ref_iter: u32,
        ckpt_refidx: u32,
        pending_refidx: u32,
        // Float fields (8 f32)
        dzr: f32,
        dzi: f32,
        bbr: f32,
        bbi: f32,
        ckpt_bbr: f32,
        ckpt_bbi: f32,
        dcr: f32,
        dci: f32,
      }
 
      // Results buffer with 32-byte header matching staging shader expectations
      // Layout:
      // Offset 0: count (firstEmpty) - atomic, GPU writes finished pixels atomically
      // Offset 4: lastStaged - atomic, updated by staging shader
      // Offset 8-28: active_count, start_iter, iterations_per_batch, padding
      // Offset 32: records[0..N]
      struct Results {
        count: atomic<u32>,
        lastStaged: atomic<u32>,
        active_count: u32,
        start_iter: u32,
        iterations_per_batch: u32,
        _pad0: u32,
        _pad1: u32,
        _pad2: u32,
        records: array<PixelState>,
      }
 
      // Per-iteration state (reference orbit + threading): 5 f32 = 20 bytes
      // Layout (f32 view):
      //   [0] ref_re: f32
      //   [1] ref_im: f32
      //   [2] thread_next: f32 (-1 = no thread)
      //   [3] thread_delta_re: f32
      //   [4] thread_delta_im: f32
      struct IterState {
        ref_re: f32,      // Reference orbit real part
        ref_im: f32,      // Reference orbit imag part
        thread_next: f32, // Next thread index (as f32, -1 = no thread)
        thread_delta_re: f32,
        thread_delta_im: f32,
      }
 
      // Lock buffer for batch collision prevention (see docs/gpu-batch-locking.md)
      // Uses per-buffer-index batch_active to avoid cross-batch race conditions
      struct LockBuffer {
        lock: atomic<u32>,
        batch_active_0: atomic<u32>,
        batch_active_1: atomic<u32>,
        collision_count: atomic<u32>,
      }
 
      @group(0) @binding(0) var<uniform> params: Params;
      @group(0) @binding(1) var<storage, read_write> pixels: array<PixelState>;
      @group(0) @binding(2) var<storage, read> iters: array<IterState>;
      @group(0) @binding(3) var<storage, read_write> results: Results;
      @group(0) @binding(4) var<storage, read_write> lockBuf: LockBuffer;
 
      // Get threading data from unified iters buffer
      // Returns vec3: [next_index_as_f32, deltaRe, deltaIm]
      fn getThread(idx: u32) -> vec3<f32> {
        if (idx >= params.ref_orbit_length) { return vec3<f32>(-1.0, 0.0, 0.0); }
        let iter_data = iters[idx];
        return vec3<f32>(iter_data.thread_next,
          iter_data.thread_delta_re, iter_data.thread_delta_im);
      }
 
      // Get reference orbit values from unified iters buffer
      fn getRefOrbit(idx: u32) -> vec2<f32> {
        if (idx >= params.ref_orbit_length) { return vec2<f32>(0.0, 0.0); }
        return vec2<f32>(iters[idx].ref_re, iters[idx].ref_im);
      }
 
      @compute @workgroup_size(64)
      fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
        // Check per-buffer-index batch_active - skip if guard didn't acquire lock
        var batch_active: u32;
        if (params.buffer_index == 0u) {
          batch_active = atomicLoad(&lockBuf.batch_active_0);
        } else {
          batch_active = atomicLoad(&lockBuf.batch_active_1);
        }
        if (batch_active == 0u) {
          return;  // Batch skipped due to collision
        }
 
        if (global_id.x == 0u && global_id.y == 0u && global_id.z == 0u) {
          results.active_count = params.active_count;
          results.start_iter = params.start_iter;
          results.iterations_per_batch = params.iterations_per_batch;
        }
        // 2D dispatch: calculate linear index from 2D coordinates
        let index = global_id.y * params.workgroups_x + global_id.x;
        if (index >= params.active_count) { return; }
 
        // Skip if already finished
        if (pixels[index].status != 0u) { return; }
 
        // Load state from unified pixel struct
        var iter = pixels[index].iter;
        var pp = pixels[index].period;
        var ref_iter = pixels[index].ref_iter;
        var checkpoint_refidx = pixels[index].ckpt_refidx;
        var pending_checkpoint_refidx = pixels[index].pending_refidx;
        var dzr = pixels[index].dzr;
        var dzi = pixels[index].dzi;
        var bbr = pixels[index].bbr;
        var bbi = pixels[index].bbi;
        var checkpoint_bb_r = pixels[index].ckpt_bbr;
        var checkpoint_bb_i = pixels[index].ckpt_bbi;
        let dcr = pixels[index].dcr;
        let dci = pixels[index].dci;
        var finished = false;
 
        // Convergence thresholds scale with pixel size for deep zooms (no iteration-based escalation)
        // GPU uses float32 precision, so thresholds must be larger than CPU's float64
        let epsilon_base = params.pixel_size / 10.0;   // Final convergence threshold
        let epsilon2_base = params.pixel_size * 10.0;  // Getting close threshold
        let epsilon = epsilon_base;
        let epsilon2 = epsilon2_base;
 
        // Track next checkpoint using O(1) counter for adaptive checkpoints
        var next_checkpoint_idx = 0u;
 
        // Iterate for the batch
        for (var batch_iter = 0u; batch_iter < params.iterations_per_batch; batch_iter++) {
          // Early exit if pixel already finished (converged/diverged)
          if (pixels[index].status != 0u) {
            break;
          }
 
          // Check rebasing before loading reference orbit values to avoid using stale data
          let dz_norm = max(abs(dzr), abs(dzi));
 
          // Peek at reference orbit to check rebasing condition
          if (ref_iter < params.ref_orbit_length) {
            let ref_check = getRefOrbit(ref_iter);
            let total_r_pre = ref_check.x + dzr;
            let total_i_pre = ref_check.y + dzi;
            let total_norm = max(abs(total_r_pre), abs(total_i_pre));
 
            // Rebase when orbit approaches critical point
            if (ref_iter > 0u && total_norm < dz_norm * 2.0) {
              dzr = total_r_pre;  // Set dz = z_total (absolute position)
              dzi = total_i_pre;
              ref_iter = 0u;  // Restart from beginning of reference orbit
 
              // Reset lazy threading state after rebase:
              // - pending_checkpoint_refidx back to checkpoint_refidx
              // - bb back to checkpoint_bb (original dz at checkpoint)
              if (checkpoint_refidx != 0xFFFFFFFFu) {
                pending_checkpoint_refidx = checkpoint_refidx;
                bbr = checkpoint_bb_r;
                bbi = checkpoint_bb_i;
              }
            }
          }
 
          // Load reference orbit values for current (possibly rebased) ref_iter
          if (ref_iter >= params.ref_orbit_length) {
            break;  // Reference orbit too short
          }
          let ref_val = getRefOrbit(ref_iter);
          var refr = ref_val.x;
          var refi = ref_val.y;
 
          // Check current z for divergence
          let curr_total_r = refr + dzr;
          let curr_total_i = refi + dzi;
          let curr_mag_sq = curr_total_r * curr_total_r + curr_total_i * curr_total_i;
 
          // Check divergence (escape radius 2, or NaN/Infinity from numerical errors)
          // NaN/Inf check: !(x <= large) catches both
          if (curr_mag_sq > 4.0 || !(curr_mag_sq <= 1e38)) {
            pixels[index].status = 1u;
            pixels[index].period = pp;
            finished = true;
            break;
          }
 
          // Save dz before iteration (for checkpoint timing)
          let old_dzr = dzr;
          let old_dzi = dzi;
          let old_ref_iter = ref_iter;
 
          // Perturbation iteration using binomial expansion (Horner's method)
          // (z_ref+dz)^n - z_ref^n = sum(k=1 to n) C(n,k) * z_ref^(n-k) * dz^k
          // Computed as: dz * (C(n,1)*z_ref^(n-1) + dz * (C(n,2)*z_ref^(n-2) + ...))
 
          // Build binomial powers: coeff * z_ref^power for each term
          var z_pow_r = refr;
          var z_pow_i = refi;
          var coeff = f32(params.exponent);
 
          // Start Horner's method with innermost term
          var result_r = dzr;
          var result_i = dzi;
 
          // Horner's method: accumulate terms from highest to lowest power of z_ref
          for (var k = 1u; k < params.exponent; k++) {
            // Add coeff * z_ref^power term
            let term_r = coeff * z_pow_r;
            let term_i = coeff * z_pow_i;
            result_r = result_r + term_r;
            result_i = result_i + term_i;
 
            // Multiply by dz (complex multiplication)
            let temp_r = result_r * dzr - result_i * dzi;
            result_i = result_r * dzi + result_i * dzr;
            result_r = temp_r;
 
            // Update z_ref power: z_pow = z_pow * z_ref
            let new_z_pow_r = z_pow_r * refr - z_pow_i * refi;
            z_pow_i = z_pow_r * refi + z_pow_i * refr;
            z_pow_r = new_z_pow_r;
 
            // Update coefficient: coeff *= (n-k) / (k+1)
            coeff *= f32(params.exponent - k) / f32(k + 1u);
          }
 
          // Add perturbation in c
          dzr = result_r + dcr;
          dzi = result_i + dci;
 
          // Check if reference orbit is long enough for next iteration
          let next_ref_check = (ref_iter + 1u) * 2u;
          if (next_ref_check + 1u >= params.ref_orbit_length * 2u) {
            break;
          }
 
          // CONVERGENCE DETECTION: Check if this iteration is a checkpoint
          var just_updated = false;
          if (next_checkpoint_idx < params.checkpoint_count) {
            // Get the offset for the next checkpoint based on index
            var checkpoint_offset = 0u;
            switch (next_checkpoint_idx) {
              case 0u: { checkpoint_offset = params.ckpt0; }
              case 1u: { checkpoint_offset = params.ckpt1; }
              case 2u: { checkpoint_offset = params.ckpt2; }
              case 3u: { checkpoint_offset = params.ckpt3; }
              case 4u: { checkpoint_offset = params.ckpt4; }
              case 5u: { checkpoint_offset = params.ckpt5; }
              case 6u: { checkpoint_offset = params.ckpt6; }
              case 7u: { checkpoint_offset = params.ckpt7; }
              case 8u: { checkpoint_offset = params.ckpt8; }
              case 9u: { checkpoint_offset = params.ckpt9; }
              case 10u: { checkpoint_offset = params.ckpt10; }
              case 11u: { checkpoint_offset = params.ckpt11; }
              case 12u: { checkpoint_offset = params.ckpt12; }
              case 13u: { checkpoint_offset = params.ckpt13; }
              case 14u: { checkpoint_offset = params.ckpt14; }
              case 15u: { checkpoint_offset = params.ckpt15; }
              case 16u: { checkpoint_offset = params.ckpt16; }
              case 17u: { checkpoint_offset = params.ckpt17; }
              case 18u: { checkpoint_offset = params.ckpt18; }
              case 19u: { checkpoint_offset = params.ckpt19; }
              case 20u: { checkpoint_offset = params.ckpt20; }
              case 21u: { checkpoint_offset = params.ckpt21; }
              case 22u: { checkpoint_offset = params.ckpt22; }
              case 23u: { checkpoint_offset = params.ckpt23; }
              case 24u: { checkpoint_offset = params.ckpt24; }
              case 25u: { checkpoint_offset = params.ckpt25; }
              case 26u: { checkpoint_offset = params.ckpt26; }
              case 27u: { checkpoint_offset = params.ckpt27; }
              case 28u: { checkpoint_offset = params.ckpt28; }
              case 29u: { checkpoint_offset = params.ckpt29; }
              case 30u: { checkpoint_offset = params.ckpt30; }
              case 31u: { checkpoint_offset = params.ckpt31; }
              default: {}
            }
 
            // Check if current batch_iter matches this checkpoint
            if (batch_iter == checkpoint_offset) {
              just_updated = true;
              // Store both bb (current) and checkpoint_bb (original, for reset after rebase)
              bbr = old_dzr;  // dz real at checkpoint (BEFORE iteration)
              bbi = old_dzi;  // dz imag at checkpoint
              checkpoint_bb_r = old_dzr;  // Save original for reset
              checkpoint_bb_i = old_dzi;
              checkpoint_refidx = old_ref_iter;  // Store reference iteration (fixed)
              pending_checkpoint_refidx = old_ref_iter;  // Start lazy threading at checkpoint
              pp = 0u;
              next_checkpoint_idx++;  // Move to next checkpoint
            }
          }
          // Check convergence (if we have a checkpoint and didn't just update it)
          // Use 0xFFFFFFFF as sentinel for "no checkpoint yet"
          if (checkpoint_refidx != 0xFFFFFFFFu && !just_updated) {
            // Threading buffer capacity: 64MB / 16 bytes per iteration = 4,194,304 (2^22)
            const THREADING_CAPACITY = 1048576u;
 
            // Fallback: when ref_iter exceeds threading buffer, use absolute position comparison
            if (ref_iter >= THREADING_CAPACITY) {
              // Compute absolute positions (accepts float32 precision loss)
              let z_total_r = refr + old_dzr;
              let z_total_i = refi + old_dzi;
              let checkpoint_ref = getRefOrbit(checkpoint_refidx);
              let z_checkpoint_r = checkpoint_ref.x + checkpoint_bb_r;
              let z_checkpoint_i = checkpoint_ref.y + checkpoint_bb_i;
 
              let diff_r = z_total_r - z_checkpoint_r;
              let diff_i = z_total_i - z_checkpoint_i;
              let db = max(abs(diff_r), abs(diff_i));
 
              if (db <= epsilon2) {
                if (pp == 0u) {
                  pp = iter;
                }
                if (db <= epsilon) {
                  pixels[index].status = 2u;
                  pixels[index].period = pp;
                  finished = true;
                  break;
                }
              }
            } else {
              // LAZY THREADING convergence check (high precision)
              // Case 1: ref_iter == checkpoint_refidx (after rebasing or naturally arriving)
              // Compare dz - bb directly (bb equals checkpoint_bb at this point)
              if (ref_iter == checkpoint_refidx) {
                let dz_diff_r = old_dzr - bbr;
                let dz_diff_i = old_dzi - bbi;
                let db = max(abs(dz_diff_r), abs(dz_diff_i));
 
                if (db <= epsilon2) {
                  if (pp == 0u) {
                    pp = iter;
                  }
                  if (db <= epsilon) {
                    pixels[index].status = 2u;
                    pixels[index].period = pp;
                    finished = true;
                    break;
                  }
                }
              }
 
              // Case 2: Check if thread[pending_checkpoint_refidx].next == ref_iter
              // This handles threading case where we lazily follow thread links
              if (pending_checkpoint_refidx >= 2584u &&
                  pending_checkpoint_refidx < params.ref_orbit_length) {
                let thread = getThread(pending_checkpoint_refidx);
                if (thread.x >= 0.0 && u32(thread.x) == ref_iter) {
                  // Check convergence: add thread delta to diff (matches old code)
                  // total_diff = threaded_delta + dz_diff = thread.delta + (dz - bb)
                  let dz_diff_r = old_dzr - bbr + thread.y;
                  let dz_diff_i = old_dzi - bbi + thread.z;
                  let db = max(abs(dz_diff_r), abs(dz_diff_i));
 
                  if (db <= epsilon2) {
                    if (pp == 0u) {
                      pp = iter;
                    }
                    if (db <= epsilon) {
                      pixels[index].status = 2u;
                      pixels[index].period = pp;
                      finished = true;
                      break;
                    }
                  }
 
                  // Update bb for future checks: bb -= thread.delta
                  // So future: dz - bb_new + next_delta = dz - (bb - delta) + next_delta
                  //          = (dz - bb) + delta + next_delta (accumulated)
                  bbr -= thread.y;
                  bbi -= thread.z;
                  pending_checkpoint_refidx = ref_iter;
                }
              }
            }
          }
 
          iter++;
          ref_iter++;
 
          // Reference orbit loop: when ref_iter hits threshold, apply delta and jump back
          if (params.loop_enabled != 0u && ref_iter >= params.loop_threshold) {
            dzr += params.loop_delta_r;
            dzi += params.loop_delta_i;
            ref_iter -= params.loop_jump;
          }
        }
        // Write back state to unified pixel struct
        pixels[index].iter = iter;
        pixels[index].period = pp;
        pixels[index].ref_iter = ref_iter;
        pixels[index].ckpt_refidx = checkpoint_refidx;
        pixels[index].pending_refidx = pending_checkpoint_refidx;
        pixels[index].dzr = dzr;
        pixels[index].dzi = dzi;
        pixels[index].bbr = bbr;
        pixels[index].bbi = bbi;
        pixels[index].ckpt_bbr = checkpoint_bb_r;
        pixels[index].ckpt_bbi = checkpoint_bb_i;
 
        if (finished) {
          let outIndex = atomicAdd(&results.count, 1u);
          results.records[outIndex] = pixels[index];
        }
      }
    `;
 
    const shaderModule = this.device.createShaderModule({
      code: shaderCode,
      label: 'Perturbation compute shader'
    });
 
    this.pipeline = this.device.createComputePipeline({
      layout: 'auto',
      compute: {
        module: shaderModule,
        entryPoint: 'main'
      },
      label: 'Perturbation compute pipeline'
    });
  }
 
  async compute(targetIters = null) {
    // Prevent concurrent compute() calls
    if (this.isComputing) return;
    this.isComputing = true;
    this.lastBatchCompacted = false;
    const BYTES_PER_PIXEL = GpuZhuoranBoard.BYTES_PER_PIXEL;  // 60 bytes (7 u32 + 8 f32)
    const STRIDE = GpuZhuoranBoard.STRIDE;  // 15 fields per pixel
    const THREADING_CAPACITY = 1048576;  // 2^20
    const BYTES_PER_ITER = 20;  // 5 f32 = 20 bytes
 
    try {
    // ================================================================
    // STEP 1: Check if done BEFORE submitting new work
    // ================================================================
    if (this.activeCount === 0) {
      if (this.precomputed && this.precomputed.getPendingCount() > 0) {
        const remainingIters = this.precomputed.getPendingIterations();
        for (const iter of remainingIters) {
          const pending = this.precomputed.extractAtIteration(iter);
          if (pending) {
            const divergedIndices = [];
            const convergedData = [];
            for (const idx of pending.diverged) {
              this.nn[idx] = iter;
              this.pp[idx] = 1;
              this.di++;
              this.un--;
              divergedIndices.push(idx);
            }
            for (const c of pending.converged) {
              this.nn[c.index] = -iter;
              this.pp[c.index] = c.p;
              this.un--;
              convergedData.push({ index: c.index, z: c.z, p: c.p });
            }
            if (divergedIndices.length > 0 || convergedData.length > 0) {
              this.queueChanges({ iter, nn: divergedIndices, vv: convergedData });
            }
          }
        }
      }
      this.un = 0;
      if (this.hasPendingResults) {
        await this.flushPendingResults();
      }
      return;
    }
    if (this.un === 0) {
      if (this.hasPendingResults) {
        await this.flushPendingResults();
      }
      return;
    }
 
    // ================================================================
    // STEP 2: Calculate batch size and extend reference orbit
    // ================================================================
    const pixelsToIterate = this.un + this.ch;
    let iterationsPerBatch;
    if (targetIters !== null) {
      iterationsPerBatch = targetIters;
    } else {
      iterationsPerBatch = Math.max(17, Math.floor(333337 / Math.max(pixelsToIterate, 1)));
    }
    // Extend reference orbit to exactly what this batch needs
    const currentNeed = this.it + iterationsPerBatch;
    const targetRefIterations = Math.min(currentNeed, THREADING_CAPACITY);
    while (!this.refOrbitEscaped && this.refIterations < targetRefIterations) {
      this.extendReferenceOrbit();
    }
 
    // Setup reference orbit loop when we hit the threading capacity
    if (this.refIterations >= THREADING_CAPACITY && !this.refOrbitLoopConfigured) {
      this.setupReferenceOrbitLoop();
    }
 
    // ================================================================
    // STEP 3: Upload iteration state to GPU (INCREMENTAL UPLOADS)
    // ================================================================
    const totalIters = this.refIterations + 1;
 
    // Resize iters buffer if needed, cap at 128MB
    const requiredIterSize = totalIters * BYTES_PER_ITER;
    const maxBufferSize = 128 * 1024 * 1024;
    const allocSize = Math.min(Math.max(requiredIterSize * 2, 1024), maxBufferSize);
    if (this.buffers.iters.size < requiredIterSize &&
        this.buffers.iters.size < allocSize) {
      await this.device.queue.onSubmittedWorkDone();
      this.buffers.iters.destroy();
      this.buffers.iters = this.device.createBuffer({
        size: allocSize,
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
        label: 'Iteration state buffer'
      });
      this.lastUploadedIterLength = -1;
      this.createBindGroup();
    }
 
    // INCREMENTAL UPLOAD: Only upload new iteration data
    if (this.lastUploadedIterLength < this.refIterations) {
      const startIdx = Math.max(0, this.lastUploadedIterLength + 1);
      const maxIters = Math.floor(this.buffers.iters.size / BYTES_PER_ITER);
      const endIdx = Math.min(this.refIterations, maxIters - 1);
      const count = endIdx - startIdx + 1;
 
      if (count > 0) {
        const iterF32 = new Float32Array(count * 5);
 
        for (let i = 0; i < count; i++) {
          const iterIdx = startIdx + i;
          const ref = this.refOrbit[iterIdx];
          const thread = this.threading.getThread(iterIdx);
 
          const base = i * 5;
          iterF32[base + 0] = ref[0] + ref[1];
          iterF32[base + 1] = ref[2] + ref[3];
          if (!thread) {
            iterF32[base + 2] = -1;
            iterF32[base + 3] = 0;
            iterF32[base + 4] = 0;
          } else {
            iterF32[base + 2] = thread.next;
            iterF32[base + 3] = thread.deltaRe;
            iterF32[base + 4] = thread.deltaIm;
          }
        }
 
        const byteOffset = startIdx * BYTES_PER_ITER;
        this.device.queue.writeBuffer(this.buffers.iters, byteOffset, iterF32);
      }
 
      this.lastUploadedIterLength = this.refIterations;
    }
 
    // ================================================================
    // STEP 4: Set up parameters and dispatch GPU (NON-BLOCKING)
    // ================================================================
    const pixelSize = this.pixelSize;
    const checkpointOffsets = [];
    const bufferIter = this.it;
    for (let i = 0; i < iterationsPerBatch; i++) {
      if (fibonacciPeriod(bufferIter + i) === 1) checkpointOffsets.push(i);
    }
    const checkpointCount = Math.min(checkpointOffsets.length, 32);
 
    const workgroupSize = 64;
    const numWorkgroups = Math.ceil(this.activeCount / workgroupSize);
    const workgroupsX = Math.ceil(Math.sqrt(numWorkgroups));
    const workgroupsY = Math.ceil(numWorkgroups / workgroupsX);
 
    const paramsBuffer = new ArrayBuffer(256);
    const paramsU32 = new Uint32Array(paramsBuffer);
    const paramsF32 = new Float32Array(paramsBuffer);
    const bufferIndex = this.readbackBufferIndex;
 
    paramsU32[0] = this.config.dimsWidth;
    paramsU32[1] = this.config.dimsHeight;
    paramsU32[2] = iterationsPerBatch;
    paramsU32[3] = this.activeCount;
    paramsU32[4] = this.refIterations + 1;
    paramsU32[5] = this.config.exponent || 2;
    paramsU32[6] = workgroupsX * workgroupSize;
    paramsU32[7] = bufferIter;
    paramsU32[8] = checkpointCount;
    paramsU32[9] = bufferIndex;  // buffer_index for per-buffer batch_active
 
    for (let i = 0; i < 32; i++) {
      paramsU32[10 + i] = i < checkpointCount ? checkpointOffsets[i] : 0;
    }
 
    paramsU32[42] = 0;  // _pad_ckpt
    const loop = this.refOrbitLoop || { enabled: false };
    paramsU32[43] = loop.enabled ? 1 : 0;
    paramsU32[44] = loop.threshold || 0;
    paramsU32[45] = loop.jumpAmount || 0;
    paramsF32[46] = pixelSize;
    paramsF32[47] = this.config.aspectRatio;
    paramsF32[48] = loop.deltaR || 0;
    paramsF32[49] = loop.deltaI || 0;
 
    this.device.queue.writeBuffer(this.buffers.params, 0, paramsBuffer);
 
    const commandEncoder = this.device.createCommandEncoder({ label: 'Perturbation compute' });
 
    // Guard pass: try to acquire batch lock (see docs/gpu-batch-locking.md)
    this.queueGuardPass(commandEncoder, bufferIndex);
 
    // Compute pass: iterate pixels (will skip if lock not acquired)
    const passEncoder = commandEncoder.beginComputePass({ label: 'Perturbation pass' });
    passEncoder.setPipeline(this.pipeline);
    passEncoder.setBindGroup(0, this.bindGroup);
    passEncoder.dispatchWorkgroups(workgroupsX, workgroupsY);
    passEncoder.end();
 
    // Queue staging shader pass and copy to staging buffer
    // Staging shader releases the lock after copying
    this.queueResultsReadback(commandEncoder, bufferIndex);
 
    const gpuStartTime = performance.now();
    this.device.queue.submit([commandEncoder.finish()]);
    // Save batch iter range using half-open interval [start, end)
    const batchStartIter = this.baseIt;
    this.baseIt += iterationsPerBatch;
    const batchEndIter = this.baseIt;
    const currentPromise = this.device.queue.onSubmittedWorkDone();
    // GPU is now computing in parallel!
 
    // ================================================================
    // STEP 5: Process pending results from PREVIOUS batch (overlaps with GPU)
    // ================================================================
    if (this.pendingReadbackIndex !== null) {
      await this.processPendingReadback();
    }
 
    // ================================================================
    // STEP 6: Speculative reference orbit extension while GPU works
    // ================================================================
    const speculativeTimeLimit = 100;  // ms
    const nextBatchIt = this.it + iterationsPerBatch;
    const nextBatchNeed = nextBatchIt + iterationsPerBatch;
    const speculativeTarget = Math.min(
      Math.max(nextBatchNeed + 10000, Math.round(nextBatchNeed * 1.1)),
      THREADING_CAPACITY
    );
 
    while (!this.refOrbitEscaped &&
           this.refIterations < speculativeTarget &&
           (performance.now() - gpuStartTime) < speculativeTimeLimit) {
      this.extendReferenceOrbit();
    }
 
    // ================================================================
    // STEP 7: Update pending state for next iteration
    // ================================================================
    this.pendingReadbackIndex = bufferIndex;
    this.pendingReadbackPromise = currentPromise;
    this.readbackBufferIndex = 1 - bufferIndex;
    this.pendingIterationsPerBatch = iterationsPerBatch;
    this.hasPendingResults = true;
    // Batch tracking: half-open interval [start, end) (see docs/gpu-results-readback-design.md)
    this.pendingBatchStartIter = batchStartIter;
    this.pendingBatchEndIter = batchEndIter;
 
    } catch (error) {
      console.error(`GpuZhuoranBoard.compute() ERROR:`, error);
    } finally {
      this.isComputing = false;
    }
  }
 
  // flushPendingResults() and readPixelBuffer() inherited from GpuZhuoranBaseBoard
 
  async serialize() {
    // Wait for any in-progress compute() to finish to avoid mapAsync race condition
    while (this.isComputing) {
      await new Promise(resolve => setTimeout(resolve, 10));
    }
 
    // CRITICAL: Flush pending results before serializing
    if (this.hasPendingResults) {
      await this.flushPendingResults();
    }
 
    // Ensure GPU is ready before reading buffers
    await this.ensureGPUReady();
 
    // Read GPU pixel buffer
    const gpuPixelData = await this.readPixelBuffer();
 
    // Build sparse nn array for completed pixels
    const completedIndexes = [];
    const completedNn = [];
    for (let i = 0; i < this.nn.length; i++) {
      if (this.nn[i] !== 0) {
        completedIndexes.push(i);
        completedNn.push(this.nn[i]);
      }
    }
 
    return {
      ...(await super.serialize()),
      // GPU pixel buffer as array (for JSON serialization)
      gpuPixelData: gpuPixelData ? Array.from(new Uint8Array(gpuPixelData)) : null,
      // DD reference orbit state
      refOrbit: this.refOrbit,
      refC: this.refC,
      refIterations: this.refIterations,
      refOrbitEscaped: this.refOrbitEscaped,
      refOrbitLoop: this.refOrbitLoop || null,
      refOrbitLoopConfigured: this.refOrbitLoopConfigured || false,
      // Board state
      effort: this.effort,
      completedIndexes,
      completedNn,
      activeCount: this.activeCount,
      deadSinceCompaction: this.deadSinceCompaction,
      wastedBandwidth: this.wastedBandwidth,
    };
  }
 
  static fromSerialized(serialized) {
    // GPU boards require async initialization, so this returns a board
    // that will continue initializing in the background
    const board = new GpuZhuoranBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    // Schedule async restoration after GPU init
    board.gpuInitPromise = board.gpuInitPromise.then(async () => {
      if (serialized.activeCount !== undefined) {
        board.activeCount = serialized.activeCount;
        board.deadSinceCompaction = serialized.deadSinceCompaction || 0;
        board.wastedBandwidth = serialized.wastedBandwidth || 0;
        board.pendingActiveCount = board.activeCount;
 
        const bufferSize = board.activeCount * GpuZhuoranBoard.BYTES_PER_PIXEL;
        board.buffers.pixels?.destroy();
        board.buffers.pixels = board.device.createBuffer({
          size: bufferSize,
          usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
          label: 'Pixel state buffer (restored)'
        });
        // Note: stagingPixels are created on-demand in readPixelBuffer() for serialization
        board.initResultsReadback(GpuZhuoranBoard.BYTES_PER_PIXEL, board.activeCount);
        board.createBindGroup();
      }
 
      // Restore GPU pixel buffer
      if (serialized.gpuPixelData && board.isGPUReady) {
        const pixelData = new Uint8Array(serialized.gpuPixelData).buffer;
        await board.writePixelBuffer(pixelData);
      }
 
      // Restore DD reference orbit state
      board.refOrbit = serialized.refOrbit || [];
      board.refC = serialized.refC || [0, 0, 0, 0];
      board.refIterations = serialized.refIterations || 1;
      board.refOrbitEscaped = serialized.refOrbitEscaped || false;
      board.refOrbitLoop = serialized.refOrbitLoop || null;
      board.refOrbitLoopConfigured = serialized.refOrbitLoopConfigured || false;
 
      // Rebuild threading structure from restored reference orbit
      board.rebuildDDThreading();
 
      // Restore Board state
      board.it = serialized.it;
      board.un = serialized.un;
      board.di = serialized.di;
      board.ch = serialized.ch || 0;
      board.effort = serialized.effort || 2;
 
      if (serialized.precomputed) {
        board.precomputed = PrecomputedPoints.fromSerialized(serialized.precomputed);
      }
 
      // Restore nn array
      board.nn = new Array(serialized.config.dimsArea).fill(0);
      if (serialized.completedIndexes) {
        for (let i = 0; i < serialized.completedIndexes.length; i++) {
          board.nn[serialized.completedIndexes[i]] = serialized.completedNn[i];
        }
      }
    });
 
    return board;
  }
}
 
 
/**
 * Adaptive Per-Pixel Scaling GPU Perturbation Board
 *
 * This board uses per-pixel adaptive scaling for deep zooms. It
 * tracks a per-pixel scale exponent that adapts dynamically during iteration.
 *
 * Key insight: Each pixel's perturbation δ is stored as (dz, scale) where
 * δ_actual = dz × 2^scale. When |dz| > 2, we halve dz and increment scale,
 * keeping dz bounded while preserving the actual δ value.
 *
 * This enables accurate escape detection at extreme zoom depths (z=10^40+)
 * where the quadratic term δ² underflows in fixed-scale approaches.
 *
 * See docs/ADAPTIVE-SCALING.md for full mathematical derivation.
 */
// Uses QDReferenceOrbitMixin for reference orbit computation
class GpuAdaptiveBoard extends QDReferenceOrbitMixin(GpuZhuoranBaseBoard) {
  static BYTES_PER_PIXEL = 64;  // 16 × 4 bytes (7 i32 + 8 f32 + 1 i32, with orig_index)
  static STRIDE = 16;           // 16 fields per pixel
 
  constructor(k, size, re, im, config, id, inheritedData = null) {
    super(k, size, re, im, config, id, inheritedData);
    this.effort = 20;  // Doubled to reduce batch sizes after GPU readback improvements
 
    // Initialize QD reference orbit (refC_qd, qdRefOrbit, threading, etc.)
    const refReQD = toQD(re);
    const refImQD = toQD(im);
    this.initQDReferenceOrbit([...refReQD, ...refImQD]);
 
    // Initialize per-pixel perturbation data (sets initialScale and pixelScale)
    this.initPixels(size, re, im);
 
    // Initialize double-buffering (from GpuZhuoranBaseBoard)
    this.initDoubleBuffering();
 
    // Start GPU initialization (async)
    this.gpuInitPromise = this.initGPU();
  }
 
  // get it(), set it() inherited from GpuZhuoranBaseBoard
  // extendReferenceOrbit() inherited from QDReferenceOrbitMixin
 
  // Setup reference orbit loop for very long orbits
  setupReferenceOrbitLoop() {
    // When reference orbit hits threading limit, find a close point to loop back to
    const THREADING_CAPACITY = 1048576;  // 2^20
    const SEARCH_WINDOW = 12000;
 
    if (this.refIterations < THREADING_CAPACITY || this.refOrbitLoopConfigured) {
      return; // Not at limit yet, or already configured
    }
 
    // Get endpoint (current position at threading limit) - QD precision
    const endpoint = this.qdRefOrbit[THREADING_CAPACITY];
 
    // Search back to find closest point (using QD arithmetic)
    let closestIter = THREADING_CAPACITY - SEARCH_WINDOW;
    let closestDist = Infinity;
    const tt = this.tt;
 
    for (let i = THREADING_CAPACITY - SEARCH_WINDOW; i < THREADING_CAPACITY; i++) {
      const pt = this.qdRefOrbit[i];
      // Compute difference in QD precision
      arQdAdd(tt, 0, endpoint[0], endpoint[1], endpoint[2], endpoint[3],
                     -pt[0], -pt[1], -pt[2], -pt[3]); // dr
      arQdAdd(tt, 4, endpoint[4], endpoint[5], endpoint[6], endpoint[7],
                     -pt[4], -pt[5], -pt[6], -pt[7]); // di
 
      // Chebyshev distance: max(|dr|, |di|)
      const dr = tt[0] + tt[1] + tt[2] + tt[3];
      const di = tt[4] + tt[5] + tt[6] + tt[7];
      const dist = Math.max(Math.abs(dr), Math.abs(di));
 
      if (dist <= closestDist) {  // Use <= to take latest point when tied
        closestDist = dist;
        closestIter = i;
      }
    }
 
    // Compute delta in QD precision
    const closestPt = this.qdRefOrbit[closestIter];
    arQdAdd(tt, 0, endpoint[0], endpoint[1], endpoint[2], endpoint[3],
                   -closestPt[0], -closestPt[1], -closestPt[2], -closestPt[3]); // real delta
    arQdAdd(tt, 4, endpoint[4], endpoint[5], endpoint[6], endpoint[7],
                   -closestPt[4], -closestPt[5], -closestPt[6], -closestPt[7]); // imag delta
 
    // Store loop parameters with QD precision delta
    const deltaR_qd = [tt[0], tt[1], tt[2], tt[3]];
    const deltaI_qd = [tt[4], tt[5], tt[6], tt[7]];
 
    this.refOrbitLoop = {
      enabled: true,
      threshold: THREADING_CAPACITY,
      jumpAmount: THREADING_CAPACITY - closestIter,
      deltaR_qd: deltaR_qd,
      deltaI_qd: deltaI_qd,
      deltaR: deltaR_qd[0] + deltaR_qd[1] + deltaR_qd[2] + deltaR_qd[3], // f64 for GPU
      deltaI: deltaI_qd[0] + deltaI_qd[1] + deltaI_qd[2] + deltaI_qd[3]
    };
 
    this.refOrbitLoopConfigured = true;
 
    // Update threading for loop segment to wrap around (using QD precision)
    const loopDeltaR = deltaR_qd[0] + deltaR_qd[1] + deltaR_qd[2] + deltaR_qd[3];
    const loopDeltaI = deltaI_qd[0] + deltaI_qd[1] + deltaI_qd[2] + deltaI_qd[3];
    const epsilon3 = this.threading.epsilon3;
 
    // For each iteration in the loop segment, check if it can thread to another iteration
    // considering the loop wrap (iterations will repeat with a delta offset)
    for (let i = closestIter; i <= THREADING_CAPACITY; i++) {
      const iPt = this.qdRefOrbit[i];
      const iR = iPt[0] + iPt[1] + iPt[2] + iPt[3];
      const iI = iPt[4] + iPt[5] + iPt[6] + iPt[7];
 
      // Check if we can thread to same or later iteration (considering it will wrap with delta)
      // Allow j = i for self-threading within the loop (period-N orbits repeat with delta)
      for (let j = i; j <= THREADING_CAPACITY; j++) {
        const jPt = this.qdRefOrbit[j];
        // After loop, iteration j will be at position qdRefOrbit[j] + loop_delta
        const jR = jPt[0] + jPt[1] + jPt[2] + jPt[3] + loopDeltaR;
        const jI = jPt[4] + jPt[5] + jPt[6] + jPt[7] + loopDeltaI;
 
        const dr = iR - jR;
        const di = iI - jI;
        const dist = Math.max(Math.abs(dr), Math.abs(di));
 
        if (dist <= epsilon3) {
          // Thread i -> j (wrapping through the loop)
          this.threading.setThread(i, j, jR - iR, jI - iI);
          break;  // Take first match
        }
      }
    }
  }
 
  // Upload combined ref orbit + threading to iters buffer
  async uploadIters() {
    const ITER_BYTES = 20;  // 5 f32 per iteration
    const threadingData = this.threading.threads;
    const totalIters = this.refIterations + 1;
 
    // Resize iters buffer if needed
    const requiredSize = totalIters * ITER_BYTES;
    if (this.buffers.iters.size < requiredSize) {
      await this.device.queue.onSubmittedWorkDone();
      this.buffers.iters.destroy();
      this.buffers.iters = this.device.createBuffer({
        size: Math.max(requiredSize * 2, 1024),
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
      });
      this.createBindGroup();
      this.lastUploadedItersLength = -1;  // Force full re-upload after resize
    }
 
    // Upload incrementally from lastUploadedItersLength
    if (this.lastUploadedItersLength < this.refIterations) {
      const startIdx = Math.max(0, this.lastUploadedItersLength + 1);
      const count = this.refIterations - startIdx + 1;
 
      // IterState: [ref_re, ref_im, thread_next, thread_delta_re, thread_delta_im]
      const itersF32 = new Float32Array(count * 5);
      for (let i = 0; i < count; i++) {
        const orbitIdx = startIdx + i;
        const ref = this.qdRefOrbit[orbitIdx];
        const thread = threadingData[orbitIdx] || { next: -1, deltaRe: 0, deltaIm: 0 };
 
        const idx = i * 5;
        // Sum QD components to get f32 value for ref orbit
        itersF32[idx + 0] = ref ? ref[0] + ref[1] + ref[2] + ref[3] : 0;  // ref_re
        itersF32[idx + 1] = ref ? ref[4] + ref[5] + ref[6] + ref[7] : 0;  // ref_im
        itersF32[idx + 2] = thread.next;      // thread_next
        itersF32[idx + 3] = thread.deltaRe;   // thread_delta_re
        itersF32[idx + 4] = thread.deltaIm;   // thread_delta_im
      }
 
      this.device.queue.writeBuffer(this.buffers.iters, startIdx * ITER_BYTES, itersF32);
      this.lastUploadedItersLength = this.refIterations;
    }
  }
 
  initPixels(size, re, im) {
    const dimsWidth = this.config.dimsWidth;
    const dimsHeight = this.config.dimsHeight;
    const dimsArea = this.config.dimsArea;
 
    // Convert size to scalar if it's a QD array
    const size_scalar = Array.isArray(size) ? size.reduce((a, b) => a + (b || 0), 0) : size;
    const pixelSize = size_scalar / dimsWidth;
 
    // Compute initial scale: k = floor(log2(pixelSize))
    const log2_pixelSize = Math.log2(pixelSize);
    this.initialScale = Math.floor(log2_pixelSize);
 
    // Mantissa factor: 2^(log2(pixelSize) - k) is in [1, 2)
    const mantissa = Math.pow(2, log2_pixelSize - this.initialScale);
 
    // Per-pixel data arrays
    this.dc = new Float32Array(dimsArea * 2);       // Delta c [real, imag] pairs
    this.dz = new Float32Array(dimsArea * 2);       // Current perturbation delta [real, imag]
    this.pixelScale = new Int32Array(dimsArea);     // Per-pixel scale exponent
    this.refIter = new Uint32Array(dimsArea);       // Reference iteration index
 
    // Initialize each pixel
    // Both x and y offsets are in raw pixel units. The pixelSize (size/dimsWidth) is
    // already correct because sizeY = size/aspectRatio = size*dimsHeight/dimsWidth,
    // and sizeY/dimsHeight = size/dimsWidth = pixelSize. So no extra scaling needed.
    for (let y = 0; y < dimsHeight; y++) {
      const yOffset = dimsHeight / 2 - y;
 
      for (let x = 0; x < dimsWidth; x++) {
        const xOffset = x - dimsWidth / 2;
 
        const index = y * dimsWidth + x;
        const index2 = index * 2;
 
        // δc_stored = mantissa × pixel_offset (normalized to [~-1, ~+1] range)
        this.dc[index2] = Math.fround(mantissa * xOffset);
        this.dc[index2 + 1] = Math.fround(mantissa * yOffset);
 
        // Start with dz = dc
        this.dz[index2] = this.dc[index2];
        this.dz[index2 + 1] = this.dc[index2 + 1];
 
        // All pixels start with the same scale
        this.pixelScale[index] = this.initialScale;
 
        // Start at iteration 1
        this.refIter[index] = 1;
      }
    }
 
    this.checkSpike(size, re, im);
  }
 
  initPixelsQD() {
    // Override to prevent parent from overwriting our scaled arrays
  }
 
  async createBuffers() {
    const dimsArea = this.config.dimsArea;
    const STRIDE = GpuAdaptiveBoard.STRIDE;  // 16 fields per pixel
 
    // Consolidated 3-binding layout:
    // 0: params (uniform)
    // 1: pixels (PixelState): 7 i32 + 8 f32 + 1 i32 = 64 bytes per pixel (with orig_index)
    // 2: iters (IterState): 5 f32 = 20 bytes per iteration (refOrbit + threading combined)
    const PIXEL_BYTES = GpuAdaptiveBoard.BYTES_PER_PIXEL;  // 64 bytes
    const ITER_BYTES = 20;   // 5 × 4 bytes
 
    const precomputedCount = this.precomputed ? this.precomputed.getPrecomputedCount() : 0;
    const activePixelCount = dimsArea - precomputedCount;
    const pixelBufferSize = Math.max(PIXEL_BYTES, activePixelCount * PIXEL_BYTES);
    const resultsBufferSize = 16 + (activePixelCount * PIXEL_BYTES);
    const maxBufferSize = Math.min(
      this.device.limits.maxBufferSize,
      this.device.limits.maxStorageBufferBindingSize
    );
    if (pixelBufferSize > maxBufferSize) {
      throw new Error(`Buffer size exceeds WebGPU limit`);
    }
    if (resultsBufferSize > maxBufferSize) {
      throw new Error(`Results buffer size exceeds WebGPU limit`);
    }
    // Note: stagingPixels buffers are created on-demand in readPixelBuffer() for serialization
    // This saves ~2x pixel buffer size in GPU memory during normal operation
    this.buffers = {
      params: this.device.createBuffer({
        size: 256,  // Increased to hold 32 checkpoint slots
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
      }),
      pixels: this.device.createBuffer({
        size: pixelBufferSize,
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST
      }),
      iters: this.device.createBuffer({
        size: 1024 * ITER_BYTES,  // Start small, will resize as needed
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
      })
    };
 
    // Initialize pixels buffer with overlapping typed array views
    // PixelState layout: [orig_index, iter, status, period, ref_iter, ckpt_refidx, pending_refidx,
    //                     dzr, dzi, bbr, bbi, ckpt_bbr, ckpt_bbi, dcr, dci, scale]
    const pixelBuffer = new ArrayBuffer(pixelBufferSize);
    const pixelsI32 = new Int32Array(pixelBuffer);
    const pixelsF32 = new Float32Array(pixelBuffer);
 
    let activeIdx = 0;
    for (let i = 0; i < dimsArea; i++) {
      if (this.precomputed && this.precomputed.isPrecomputed(i)) {
        continue;
      }
      const idx = activeIdx * STRIDE;  // 16 fields per pixel
      // Integer fields (indices 0-6)
      pixelsI32[idx + 0] = i;                    // orig_index (for coordinate computation after compaction)
      pixelsI32[idx + 1] = 1;                    // iter starts at 1
      pixelsI32[idx + 2] = 0;                    // status = computing
      pixelsI32[idx + 3] = 0;                    // period = 0
      pixelsI32[idx + 4] = this.refIter[i];     // ref_iter
      pixelsI32[idx + 5] = -1;                   // ckpt_refidx (-1 = no checkpoint)
      pixelsI32[idx + 6] = -1;                   // pending_refidx
      // Float fields (indices 7-14)
      pixelsF32[idx + 7] = this.dz[i * 2];      // dzr (scaled by per-pixel scale)
      pixelsF32[idx + 8] = this.dz[i * 2 + 1];  // dzi
      pixelsF32[idx + 9] = 0;                    // bbr (scaled by initialScale)
      pixelsF32[idx + 10] = 0;                   // bbi
      pixelsF32[idx + 11] = 0;                   // ckpt_bbr
      pixelsF32[idx + 12] = 0;                   // ckpt_bbi
      pixelsF32[idx + 13] = this.dc[i * 2];     // dcr (scaled by initialScale)
      pixelsF32[idx + 14] = this.dc[i * 2 + 1]; // dci
      // GpuAdaptiveBoard-specific field at end (index 15)
      pixelsI32[idx + 15] = this.pixelScale[i]; // scale from initPixels
      activeIdx++;
    }
    this.device.queue.writeBuffer(this.buffers.pixels, 0, pixelBuffer);
 
    this.lastUploadedItersLength = -1;
    this.activeCount = activePixelCount;
    this.pendingActiveCount = activePixelCount;
    this.deadSinceCompaction = 0;
    this.wastedBandwidth = 0;
    this.initResultsReadback(PIXEL_BYTES, activePixelCount);
  }
 
  createBindGroup() {
    this.bindGroup = this.device.createBindGroup({
      layout: this.pipeline.getBindGroupLayout(0),
      entries: [
        { binding: 0, resource: { buffer: this.buffers.params } },
        { binding: 1, resource: { buffer: this.buffers.pixels } },
        { binding: 2, resource: { buffer: this.buffers.iters } },
        { binding: 3, resource: { buffer: this.buffers.results } },
        { binding: 4, resource: { buffer: this.buffers.lock } }
      ],
      label: 'Adaptive perturbation bind group'
    });
  }
 
  /**
   * Process GPU results using batch-oriented approach (same as GpuBoard).
   * This ensures results are only sent to changeList when batches complete,
   * preventing out-of-order iteration delivery that causes striping.
   */
  processResultsData(data, count) {
    const STRIDE = GpuAdaptiveBoard.STRIDE;
    const pixelsI32 = new Int32Array(data);
    const pixelsF32 = new Float32Array(data);
    const debugReadback = hasDebugFlag(this.config, 'rb');
 
    this.lastResultsCount = count;
    this.resultsReadbackBatches += 1;
    this.resultsReadbackBytes += count * this.resultsRecordBytes;
 
    const P_ORIG_INDEX = 0, P_ITER = 1, P_STATUS = 2, P_PERIOD = 3, P_REF_ITER = 4;
    const P_DZR = 7, P_DZI = 8, P_SCALE = 15;
 
    let dataIndex = 0;
 
    // OUTER LOOP: Process batches in order
    while (this.batchesToReadback.length > 0) {
      const batch = this.batchesToReadback[0];
 
      // Flush precomputed points before this batch's iteration range
      if (this.precomputed) {
        this.flushPrecomputedUpTo(this.previousBatchEndIter - 1);
      }
 
      // INNER LOOP: Process available data for this batch
      while (batch.remainingPixelCount > 0 && dataIndex < count) {
        const idx = dataIndex * STRIDE;
        const origIndex = pixelsI32[idx + P_ORIG_INDEX];
        const status = pixelsI32[idx + P_STATUS];
        const period = pixelsI32[idx + P_PERIOD];
 
        const iters = pixelsI32[idx + P_ITER];
 
        // Skip already processed pixels (shouldn't happen, but defensive)
        if (this.nn[origIndex] !== 0) {
          if (debugReadback) {
            const same = this.nn[origIndex] === iters ? ' (SAME VALUE)' : ' (DIFFERENT VALUE)';
            console.error(`INVARIANT VIOLATION: Duplicate result for pixel ${origIndex}, existing nn=${this.nn[origIndex]}, new iters=${iters}${same}`);
          }
          dataIndex++;
          continue;
        }
 
        // Skip non-finished pixels (status 0 = still computing)
        if (status === 0) {
          dataIndex++;
          continue;
        }
 
        if (status === 1) {
          // Diverged
          this.nn[origIndex] = iters;
          this.pp[origIndex] = period;
          this.di++;
          if (this.inSpike && this.inSpike[origIndex] && this.ch > 0) this.ch -= 1;
 
          // Accumulate into batchResultsRead
          this.batchResultsRead.push({ iter: iters, nn: [origIndex], vv: [] });
        } else if (status === 2) {
          // Converged
          this.nn[origIndex] = -iters;
          this.pp[origIndex] = period - 1;
          if (this.inSpike && this.inSpike[origIndex] && this.ch > 0) this.ch -= 1;
 
          // Compute final z value using QD reference orbit with adaptive scaling
          const refIter = pixelsI32[idx + P_REF_ITER];
          const scale = pixelsI32[idx + P_SCALE];
          const dzr = pixelsF32[idx + P_DZR] * Math.pow(2, scale);
          const dzi = pixelsF32[idx + P_DZI] * Math.pow(2, scale);
 
          const ref = this.qdRefOrbit[Math.min(refIter, this.qdRefOrbit.length - 1)];
 
          // Accumulate into batchResultsRead
          this.batchResultsRead.push({
            iter: iters,
            nn: [],
            vv: [{ index: origIndex, z: this.refDzNative(ref, dzr, dzi), p: this.pp[origIndex] }]
          });
        }
 
        this.deadSinceCompaction++;
        batch.remainingPixelCount--;
        dataIndex++;
      }
 
      // Check if batch is complete
      if (batch.remainingPixelCount > 0) {
        // Batch not complete - exit and wait for more data
        break;
      }
 
      // BATCH COMPLETE - Flush to changeList
 
      // Flush precomputed points up to this batch's end iteration
      if (this.precomputed) {
        this.flushPrecomputedIntoResults(batch.endIter - 1);
      }
 
      // Queue results to changeList using queueChanges
      for (const change of this.batchResultsRead) {
        this.queueChanges(change);
      }
 
      // Clear for next batch
      this.batchResultsRead.length = 0;
      this.previousBatchEndIter = batch.endIter;
      this.batchesToReadback.shift();
    }
 
    // Update un count
    // deadSinceCompaction includes results in batchResultsRead that aren't flushed yet
    // Add them back since they're not in changeList yet (view won't see them)
    const pendingPrecomputed = this.precomputed ? this.precomputed.getPendingCount() : 0;
    const pendingInBatchResults = this.batchResultsRead.length;
    this.un = (this.activeCount - this.deadSinceCompaction) + pendingPrecomputed + pendingInBatchResults;
  }
 
  async createComputePipeline() {
    // Consolidated 3-binding adaptive per-pixel scaling perturbation shader
    // Scale conventions:
    //   dz: per-pixel adaptive scale
    //   bb, checkpoint_bb, dc: global initialScale (Option C)
    // Lazy threading: bb gets modified by thread deltas, checkpoint_bb stores original for reset
    const shaderCode = `
      struct Params {
        dims_width: u32,
        dims_height: u32,
        iterations_per_batch: u32,
        active_count: u32,
        ref_orbit_length: u32,
        exponent: u32,
        workgroups_x: u32,
        start_iter: u32,
        checkpoint_count: u32,
        buffer_index: u32,      // 0 or 1, for per-buffer batch_active
        ckpt0: u32, ckpt1: u32, ckpt2: u32, ckpt3: u32,
        ckpt4: u32, ckpt5: u32, ckpt6: u32, ckpt7: u32,
        ckpt8: u32, ckpt9: u32, ckpt10: u32, ckpt11: u32,
        ckpt12: u32, ckpt13: u32, ckpt14: u32, ckpt15: u32,
        ckpt16: u32, ckpt17: u32, ckpt18: u32, ckpt19: u32,
        ckpt20: u32, ckpt21: u32, ckpt22: u32, ckpt23: u32,
        ckpt24: u32, ckpt25: u32, ckpt26: u32, ckpt27: u32,
        ckpt28: u32, ckpt29: u32, ckpt30: u32, ckpt31: u32,
        _pad_ckpt: u32,         // Padding after checkpoints
        loop_enabled: u32,
        loop_threshold: u32,
        loop_jump: u32,
        initial_scale: i32,    // Global scale for dc, bb, threaded_delta
        _pad_scale: u32,       // Padding for alignment
        pixel_size: f32,
        aspect_ratio: f32,
        loop_delta_r: f32,
        loop_delta_i: f32,
      }
 
      // Per-pixel state: 7 i32 + 8 f32 + 1 i32 = 64 bytes (with orig_index for compaction)
      // Layout matches GpuZhuoranBoard for first 15 fields (scale at end)
      // Layout (i32/u32 view):
      //   [0] orig_index: i32  (original pixel index for sparse processing)
      //   [1] iter: i32
      //   [2] status: i32
      //   [3] period: i32
      //   [4] ref_iter: i32
      //   [5] ckpt_refidx: i32
      //   [6] pending_refidx: i32
      //   [7] dzr: f32
      //   [8] dzi: f32
      //   [9] bbr: f32
      //   [10] bbi: f32
      //   [11] ckpt_bbr: f32
      //   [12] ckpt_bbi: f32
      //   [13] dcr: f32
      //   [14] dci: f32
      //   [15] scale: i32  (GpuAdaptiveBoard-specific, at end for layout compatibility)
      struct PixelState {
        // Integer fields (7 i32) - orig_index first, then matches GpuZhuoranBoard
        orig_index: i32,
        iter: i32,
        status: i32,
        period: i32,
        ref_iter: i32,
        ckpt_refidx: i32,
        pending_refidx: i32,
        // Float fields (8 f32)
        dzr: f32,
        dzi: f32,
        bbr: f32,
        bbi: f32,
        ckpt_bbr: f32,
        ckpt_bbi: f32,
        dcr: f32,
        dci: f32,
        // GpuAdaptiveBoard-specific field at end
        scale: i32,
      }
 
      // Results buffer with 32-byte header matching staging shader expectations
      // Layout:
      // Offset 0: count (firstEmpty) - atomic, GPU writes finished pixels atomically
      // Offset 4: lastStaged - atomic, updated by staging shader
      // Offset 8-28: active_count, start_iter, iterations_per_batch, padding
      // Offset 32: records[0..N]
      struct Results {
        count: atomic<u32>,
        lastStaged: atomic<u32>,
        active_count: u32,
        start_iter: u32,
        iterations_per_batch: u32,
        _pad0: u32,
        _pad1: u32,
        _pad2: u32,
        records: array<PixelState>,
      }
 
      // Per-iteration state (reference orbit + threading): 5 f32 = 20 bytes
      // Layout (f32 view):
      //   [0] ref_re: f32
      //   [1] ref_im: f32
      //   [2] thread_next: f32
      //   [3] thread_delta_re: f32
      //   [4] thread_delta_im: f32
      struct IterState {
        ref_re: f32,
        ref_im: f32,
        thread_next: f32,
        thread_delta_re: f32,
        thread_delta_im: f32,
      }
 
      // Lock buffer for batch collision prevention (see docs/gpu-batch-locking.md)
      // Uses per-buffer-index batch_active to avoid cross-batch race conditions
      struct LockBuffer {
        lock: atomic<u32>,
        batch_active_0: atomic<u32>,
        batch_active_1: atomic<u32>,
        collision_count: atomic<u32>,
      }
 
      @group(0) @binding(0) var<uniform> params: Params;
      @group(0) @binding(1) var<storage, read_write> pixels: array<PixelState>;
      @group(0) @binding(2) var<storage, read> iters: array<IterState>;
      @group(0) @binding(3) var<storage, read_write> results: Results;
      @group(0) @binding(4) var<storage, read_write> lockBuf: LockBuffer;
 
      fn getThread(idx: u32) -> vec3<f32> {
        if (idx >= params.ref_orbit_length) { return vec3<f32>(-1.0, 0.0, 0.0); }
        let iter_data = iters[idx];
        return vec3<f32>(iter_data.thread_next,
          iter_data.thread_delta_re, iter_data.thread_delta_im);
      }
 
      fn getRefOrbit(idx: u32) -> vec2<f32> {
        if (idx >= params.ref_orbit_length) { return vec2<f32>(0.0, 0.0); }
        return vec2<f32>(iters[idx].ref_re, iters[idx].ref_im);
      }
 
      @compute @workgroup_size(64)
      fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
        // Check per-buffer-index batch_active - skip if guard didn't acquire lock
        var batch_active: u32;
        if (params.buffer_index == 0u) {
          batch_active = atomicLoad(&lockBuf.batch_active_0);
        } else {
          batch_active = atomicLoad(&lockBuf.batch_active_1);
        }
        if (batch_active == 0u) {
          return;  // Batch skipped due to collision
        }
 
        if (global_id.x == 0u && global_id.y == 0u && global_id.z == 0u) {
          results.active_count = params.active_count;
          results.start_iter = params.start_iter;
          results.iterations_per_batch = params.iterations_per_batch;
        }
        let index = global_id.y * params.workgroups_x + global_id.x;
        if (index >= params.active_count) { return; }
 
        // Read pixel state
        let status = pixels[index].status;
        if (status != 0) { return; }
 
        var iter = u32(pixels[index].iter);
        var scale = pixels[index].scale;
        var pp = u32(pixels[index].period);
        var ref_iter = u32(pixels[index].ref_iter);
        var checkpoint_refidx = u32(pixels[index].ckpt_refidx);
        var pending_checkpoint_refidx = u32(pixels[index].pending_refidx);
 
        // Read float state (all checkpoint-related values in initialScale)
        var dzr = pixels[index].dzr;
        var dzi = pixels[index].dzi;
        var bbr = pixels[index].bbr;
        var bbi = pixels[index].bbi;
        var checkpoint_bb_r = pixels[index].ckpt_bbr;
        var checkpoint_bb_i = pixels[index].ckpt_bbi;
        let dcr = pixels[index].dcr;
        let dci = pixels[index].dci;
        var finished = false;
 
        // Convergence thresholds - scaled by initialScale for comparison (no iteration-based escalation)
        let epsilon_base = params.pixel_size / 10.0;
        let epsilon2_base = params.pixel_size * 10.0;
        // Convert to initialScale for scaled comparisons
        let epsilon = ldexp(epsilon_base, -params.initial_scale);
        let epsilon2 = ldexp(epsilon2_base, -params.initial_scale);
 
        // Track next checkpoint using O(1) counter for adaptive checkpoints
        var next_checkpoint_idx = 0u;
 
        for (var batch_iter = 0u; batch_iter < params.iterations_per_batch; batch_iter++) {
          if (pixels[index].status != 0) { break; }
 
          if (ref_iter >= params.ref_orbit_length) { break; }
 
          let ref_orbit = getRefOrbit(ref_iter);
          var refr = ref_orbit.x;
          var refi = ref_orbit.y;
 
          // Compute actual delta and position: z = Z_ref + δ_actual
          var dzr_actual = 0.0;
          var dzi_actual = 0.0;
          if (scale >= -126) {
            dzr_actual = ldexp(dzr, scale);
            dzi_actual = ldexp(dzi, scale);
          }
          var zr = refr + dzr_actual;
          var zi = refi + dzi_actual;
 
          // === ESCAPE CHECK ===
          // Check BEFORE rebasing to match QDZhuoranBoard behavior
          let z_mag_sq = zr * zr + zi * zi;
          // Check divergence (escape radius 2, or NaN/Infinity from numerical errors)
          if (z_mag_sq > 4.0 || !(z_mag_sq <= 1e38)) {  // NaN/Inf check: !(x <= large) catches both
            pixels[index].status = 1;
            pixels[index].period = i32(pp);
            finished = true;
            break;
          }
 
          // === REBASING ===
          let z_norm = max(abs(zr), abs(zi));
          let dz_norm = max(abs(dzr_actual), abs(dzi_actual));
          if (ref_iter > 0u && z_norm < dz_norm * 2.0) {
            let new_log2 = floor(log2(z_norm));
            let new_scale = max(i32(new_log2), params.initial_scale);
            dzr = ldexp(zr, -new_scale);
            dzi = ldexp(zi, -new_scale);
            scale = new_scale;
            ref_iter = 0u;
 
            // Reset lazy threading state after rebase
            if (checkpoint_refidx != 0xFFFFFFFFu) {
              pending_checkpoint_refidx = checkpoint_refidx;
              bbr = checkpoint_bb_r;
              bbi = checkpoint_bb_i;
            }
 
            let ref0 = getRefOrbit(0u);
            refr = ref0.x;
            refi = ref0.y;
            dzr_actual = ldexp(dzr, scale);
            dzi_actual = ldexp(dzi, scale);
            zr = refr + dzr_actual;
            zi = refi + dzi_actual;
          }
 
          // === CONVERGENCE DETECTION ===
          // bb and threaded_delta are in initialScale, so convert dz to initialScale for comparison
          var just_updated = false;
          if (next_checkpoint_idx < params.checkpoint_count) {
            var checkpoint_offset = 0u;
            switch (next_checkpoint_idx) {
              case 0u: { checkpoint_offset = params.ckpt0; }
              case 1u: { checkpoint_offset = params.ckpt1; }
              case 2u: { checkpoint_offset = params.ckpt2; }
              case 3u: { checkpoint_offset = params.ckpt3; }
              case 4u: { checkpoint_offset = params.ckpt4; }
              case 5u: { checkpoint_offset = params.ckpt5; }
              case 6u: { checkpoint_offset = params.ckpt6; }
              case 7u: { checkpoint_offset = params.ckpt7; }
              case 8u: { checkpoint_offset = params.ckpt8; }
              case 9u: { checkpoint_offset = params.ckpt9; }
              case 10u: { checkpoint_offset = params.ckpt10; }
              case 11u: { checkpoint_offset = params.ckpt11; }
              case 12u: { checkpoint_offset = params.ckpt12; }
              case 13u: { checkpoint_offset = params.ckpt13; }
              case 14u: { checkpoint_offset = params.ckpt14; }
              case 15u: { checkpoint_offset = params.ckpt15; }
              case 16u: { checkpoint_offset = params.ckpt16; }
              case 17u: { checkpoint_offset = params.ckpt17; }
              case 18u: { checkpoint_offset = params.ckpt18; }
              case 19u: { checkpoint_offset = params.ckpt19; }
              case 20u: { checkpoint_offset = params.ckpt20; }
              case 21u: { checkpoint_offset = params.ckpt21; }
              case 22u: { checkpoint_offset = params.ckpt22; }
              case 23u: { checkpoint_offset = params.ckpt23; }
              case 24u: { checkpoint_offset = params.ckpt24; }
              case 25u: { checkpoint_offset = params.ckpt25; }
              case 26u: { checkpoint_offset = params.ckpt26; }
              case 27u: { checkpoint_offset = params.ckpt27; }
              case 28u: { checkpoint_offset = params.ckpt28; }
              case 29u: { checkpoint_offset = params.ckpt29; }
              case 30u: { checkpoint_offset = params.ckpt30; }
              case 31u: { checkpoint_offset = params.ckpt31; }
              default: {}
            }
 
            if (batch_iter == checkpoint_offset) {
              just_updated = true;
              // Store bb and checkpoint_bb in initialScale: bb = dz_actual / 2^initialScale
              let bb_val_r = ldexp(dzr_actual, -params.initial_scale);
              let bb_val_i = ldexp(dzi_actual, -params.initial_scale);
              bbr = bb_val_r;
              bbi = bb_val_i;
              checkpoint_bb_r = bb_val_r;  // Save original for reset after rebase
              checkpoint_bb_i = bb_val_i;
              checkpoint_refidx = ref_iter;
              pending_checkpoint_refidx = ref_iter;  // Start lazy threading at checkpoint
              pp = 0u;
              next_checkpoint_idx = next_checkpoint_idx + 1u;
            }
          }
 
          // Check convergence with lazy threading (all comparisons in initialScale)
          if (checkpoint_refidx != 0xFFFFFFFFu && !just_updated && scale >= -126) {
              // LAZY THREADING convergence check in initialScale
              // Convert current dz to initialScale for comparison
              let dzr_scaled = ldexp(dzr_actual, -params.initial_scale);
              let dzi_scaled = ldexp(dzi_actual, -params.initial_scale);
 
              // Case 1: ref_iter == checkpoint_refidx (after rebasing or naturally arriving)
              if (ref_iter == checkpoint_refidx) {
                let dz_diff_r = dzr_scaled - bbr;
                let dz_diff_i = dzi_scaled - bbi;
                let db = max(abs(dz_diff_r), abs(dz_diff_i));
 
                if (db <= epsilon2) {
                  if (pp == 0u) { pp = iter; }
                  if (db <= epsilon) {
                    pixels[index].status = 2;
                    pixels[index].period = i32(pp);
                    finished = true;
                    break;
                  }
                }
              }
 
              // Case 2: Check if thread[pending_checkpoint_refidx].next == ref_iter
              if (pending_checkpoint_refidx >= 2584u &&
                  pending_checkpoint_refidx < params.ref_orbit_length) {
                let thread = getThread(pending_checkpoint_refidx);
                if (thread.x >= 0.0 && u32(thread.x) == ref_iter) {
                  // Check convergence: add thread delta to diff (convert to initialScale)
                  let thread_r_scaled = ldexp(thread.y, -params.initial_scale);
                  let thread_i_scaled = ldexp(thread.z, -params.initial_scale);
                  let dz_diff_r = dzr_scaled - bbr + thread_r_scaled;
                  let dz_diff_i = dzi_scaled - bbi + thread_i_scaled;
                  let db = max(abs(dz_diff_r), abs(dz_diff_i));
 
                  if (db <= epsilon2) {
                    if (pp == 0u) { pp = iter; }
                    if (db <= epsilon) {
                      pixels[index].status = 2;
                      pixels[index].period = i32(pp);
                      finished = true;
                      break;
                    }
                  }
 
                  // Update bb for future checks: bb -= thread.delta
                  bbr = bbr - thread_r_scaled;
                  bbi = bbi - thread_i_scaled;
                  pending_checkpoint_refidx = ref_iter;
                }
              }
          }
 
          // === PERTURBATION ITERATION ===
          // Binomial expansion: (Z+δz)^n - Z^n = Σ C(n,k)·Z^(n-k)·δz^k
          // All terms computed in scaled coordinates to avoid float32 overflow
          var new_dzr: f32;
          var new_dzi: f32;
          let scale_diff = params.initial_scale - scale;
          let dc_r = ldexp(dcr, scale_diff);
          let dc_i = ldexp(dci, scale_diff);
 
          if (params.exponent == 2u) {
            // z² + c: 2·Z·δz + δz²
            let linear_r = 2.0 * (refr * dzr - refi * dzi);
            let linear_i = 2.0 * (refr * dzi + refi * dzr);
            let dz2_r = ldexp(dzr * dzr - dzi * dzi, scale);
            let dz2_i = ldexp(2.0 * dzr * dzi, scale);
            new_dzr = linear_r + dz2_r + dc_r;
            new_dzi = linear_i + dz2_i + dc_i;
          } else if (params.exponent == 3u) {
            // z³ + c: 3·Z²·δz + 3·Z·δz² + δz³
            let ref2_r = refr * refr - refi * refi;
            let ref2_i = 2.0 * refr * refi;
            let t1_r = 3.0 * (ref2_r * dzr - ref2_i * dzi);
            let t1_i = 3.0 * (ref2_r * dzi + ref2_i * dzr);
            let dz2_r = dzr * dzr - dzi * dzi;
            let dz2_i = 2.0 * dzr * dzi;
            let t2_r = ldexp(3.0 * (refr * dz2_r - refi * dz2_i), scale);
            let t2_i = ldexp(3.0 * (refr * dz2_i + refi * dz2_r), scale);
            let dz3_r = dzr * dz2_r - dzi * dz2_i;
            let dz3_i = dzr * dz2_i + dzi * dz2_r;
            let t3_r = ldexp(dz3_r, scale + scale);
            let t3_i = ldexp(dz3_i, scale + scale);
            new_dzr = t1_r + t2_r + t3_r + dc_r;
            new_dzi = t1_i + t2_i + t3_i + dc_i;
          } else if (params.exponent == 4u) {
            // z⁴ + c: 4·Z³·δz + 6·Z²·δz² + 4·Z·δz³ + δz⁴
            let ref2_r = refr * refr - refi * refi;
            let ref2_i = 2.0 * refr * refi;
            let ref3_r = refr * ref2_r - refi * ref2_i;
            let ref3_i = refr * ref2_i + refi * ref2_r;
            let t1_r = 4.0 * (ref3_r * dzr - ref3_i * dzi);
            let t1_i = 4.0 * (ref3_r * dzi + ref3_i * dzr);
            let dz2_r = dzr * dzr - dzi * dzi;
            let dz2_i = 2.0 * dzr * dzi;
            let t2_r = ldexp(6.0 * (ref2_r * dz2_r - ref2_i * dz2_i), scale);
            let t2_i = ldexp(6.0 * (ref2_r * dz2_i + ref2_i * dz2_r), scale);
            let dz3_r = dzr * dz2_r - dzi * dz2_i;
            let dz3_i = dzr * dz2_i + dzi * dz2_r;
            let t3_r = ldexp(4.0 * (refr * dz3_r - refi * dz3_i), scale + scale);
            let t3_i = ldexp(4.0 * (refr * dz3_i + refi * dz3_r), scale + scale);
            let dz4_r = dz2_r * dz2_r - dz2_i * dz2_i;
            let dz4_i = 2.0 * dz2_r * dz2_i;
            let t4_r = ldexp(dz4_r, scale + scale + scale);
            let t4_i = ldexp(dz4_i, scale + scale + scale);
            new_dzr = t1_r + t2_r + t3_r + t4_r + dc_r;
            new_dzi = t1_i + t2_i + t3_i + t4_i + dc_i;
          } else {
            // Higher exponents: use direct computation (less efficient)
            let dzr_actual = ldexp(dzr, scale);
            let dzi_actual = ldexp(dzi, scale);
            var zr = refr + dzr_actual;
            var zi = refi + dzi_actual;
            var zn_r = zr;
            var zn_i = zi;
            for (var p = 1u; p < params.exponent; p++) {
              let temp_r = zn_r * zr - zn_i * zi;
              zn_i = zn_r * zi + zn_i * zr;
              zn_r = temp_r;
            }
            var refn_r = refr;
            var refn_i = refi;
            for (var p = 1u; p < params.exponent; p++) {
              let temp_r = refn_r * refr - refn_i * refi;
              refn_i = refn_r * refi + refn_i * refr;
              refn_r = temp_r;
            }
            new_dzr = (zn_r - refn_r) + dc_r;
            new_dzi = (zn_i - refn_i) + dc_i;
          }
          var new_scale = scale;
 
          // === ADAPTIVE RESCALING ===
          let dz_mag = max(abs(new_dzr), abs(new_dzi));
          if (dz_mag > 0.0 && dz_mag < 1e30) {  // Guard against Infinity/NaN
            let log2_mag = floor(log2(dz_mag));
            if (log2_mag >= 1.0) {
              let steps = i32(log2_mag);
              // Clamp scale to prevent overflow (max scale ~100, min scale ~initial_scale)
              if (new_scale + steps <= 100) {
                new_dzr = ldexp(new_dzr, -steps);
                new_dzi = ldexp(new_dzi, -steps);
                new_scale = new_scale + steps;
              }
            } else if (log2_mag < -1.0 && new_scale > params.initial_scale) {
              let steps = min(i32(-log2_mag) - 1, new_scale - params.initial_scale);
              if (steps > 0) {
                new_dzr = ldexp(new_dzr, steps);
                new_dzi = ldexp(new_dzi, steps);
                new_scale = new_scale - steps;
              }
            }
          }
 
          dzr = new_dzr;
          dzi = new_dzi;
          scale = new_scale;
          ref_iter = ref_iter + 1u;
          iter = iter + 1u;
        }
 
        // Write back integer state
        pixels[index].iter = i32(iter);
        pixels[index].scale = scale;
        pixels[index].ref_iter = i32(ref_iter);
        pixels[index].ckpt_refidx = i32(checkpoint_refidx);
        pixels[index].pending_refidx = i32(pending_checkpoint_refidx);
        if (pixels[index].status == 0) {
          pixels[index].period = i32(pp);
        }
 
        // Write back float state
        pixels[index].dzr = dzr;
        pixels[index].dzi = dzi;
        pixels[index].bbr = bbr;
        pixels[index].bbi = bbi;
        pixels[index].ckpt_bbr = checkpoint_bb_r;
        pixels[index].ckpt_bbi = checkpoint_bb_i;
 
        if (finished) {
          let outIndex = atomicAdd(&results.count, 1u);
          results.records[outIndex] = pixels[index];
        }
      }
    `;
 
    const shaderModule = this.device.createShaderModule({
      code: shaderCode,
      label: 'Adaptive per-pixel scaling perturbation shader'
    });
 
    // Check for shader compilation errors
    const compilationInfo = await shaderModule.getCompilationInfo();
    for (const msg of compilationInfo.messages) {
      const level = msg.type === 'error' ? 'ERROR' : msg.type === 'warning' ? 'WARN' : 'INFO';
      console.log(`GpuAdaptiveBoard shader ${level}: ${msg.message} ` +
        `(line ${msg.lineNum}, col ${msg.linePos})`);
    }
 
    this.pipeline = this.device.createComputePipeline({
      layout: 'auto',
      compute: {
        module: shaderModule,
        entryPoint: 'main'
      },
      label: 'Adaptive perturbation pipeline'
    });
  }
 
  async compute(targetIters = null) {
    // Prevent concurrent compute() calls
    if (this.isComputing) return;
    this.isComputing = true;
    this.lastBatchCompacted = false;
 
    // Wait for async GPU initialization to complete
    await this.gpuInitPromise;
 
    // GPU required - if device unavailable, computation cannot proceed
    if (!this.device) {
      console.warn('GpuAdaptiveBoard: GPU device not available, cannot compute');
      this.isComputing = false;
      return;
    }
 
    try {
      const THREADING_CAPACITY = 1048576;
      const BYTES_PER_PIXEL = GpuAdaptiveBoard.BYTES_PER_PIXEL;  // 64 bytes
      const STRIDE = GpuAdaptiveBoard.STRIDE;  // 16 fields
 
      // ================================================================
      // STEP 1: Check if done BEFORE submitting new work
      // ================================================================
      if (this.activeCount === 0) {
        if (this.precomputed && this.precomputed.getPendingCount() > 0) {
          const remainingIters = this.precomputed.getPendingIterations();
          for (const iter of remainingIters) {
            const pending = this.precomputed.extractAtIteration(iter);
            if (pending) {
              const divergedIndices = [];
              const convergedData = [];
              for (const idx of pending.diverged) {
                this.nn[idx] = iter;
                this.pp[idx] = 1;
                this.di++;
                this.un--;
                divergedIndices.push(idx);
              }
              for (const c of pending.converged) {
                this.nn[c.index] = -iter;
                this.pp[c.index] = c.p;
                this.un--;
                convergedData.push({ index: c.index, z: c.z, p: c.p });
              }
              if (divergedIndices.length > 0 || convergedData.length > 0) {
                this.queueChanges({ iter, nn: divergedIndices, vv: convergedData });
              }
            }
          }
        }
        this.un = 0;
        if (this.hasPendingResults) {
          await this.flushPendingResults();
        }
        return;
      }
      if (this.un === 0) {
        if (this.hasPendingResults) {
          await this.flushPendingResults();
        }
        return;
      }
 
      // ================================================================
      // STEP 2: Calculate batch size and extend reference orbit
      // ================================================================
      const pixelsToIterate = this.un + this.ch;
      let iterationsPerBatch;
      if (targetIters !== null) {
        iterationsPerBatch = targetIters;
      } else {
        iterationsPerBatch = Math.max(17, Math.floor(333337 / Math.max(pixelsToIterate, 1)));
      }
      // Extend reference orbit to exactly what this batch needs
      const currentNeed = this.it + iterationsPerBatch;
      const targetRefIterations = Math.min(currentNeed, THREADING_CAPACITY);
      while (!this.refOrbitEscaped && this.refIterations < targetRefIterations) {
        this.extendReferenceOrbit();
      }
 
      // Setup reference orbit loop when we hit the threading capacity
      if (this.refIterations >= THREADING_CAPACITY && !this.refOrbitLoopConfigured) {
        this.setupReferenceOrbitLoop();
      }
 
      // ================================================================
      // STEP 3: Upload iteration state to GPU
      // ================================================================
      await this.uploadIters();
 
      // ================================================================
      // STEP 4: Set up parameters and dispatch GPU (NON-BLOCKING)
      // ================================================================
      const checkpointOffsets = [];
      const bufferIter = this.it;
      for (let i = 0; i < iterationsPerBatch; i++) {
        const globalIter = bufferIter + i;
        if (fibonacciPeriod(globalIter) === 1) {
          checkpointOffsets.push(i);
        }
      }
      const checkpointCount = Math.min(checkpointOffsets.length, 32);
 
      const size_scalar = this.size;
      const pixelSize = size_scalar / this.config.dimsWidth;
 
      const workgroupSize = 64;
      const numWorkgroups = Math.ceil(this.activeCount / workgroupSize);
      const workgroupsX = Math.ceil(Math.sqrt(numWorkgroups));
      const workgroupsY = Math.ceil(numWorkgroups / workgroupsX);
 
      const paramsBuffer = new ArrayBuffer(256);
      const paramsU32 = new Uint32Array(paramsBuffer);
      const paramsI32 = new Int32Array(paramsBuffer);
      const paramsF32 = new Float32Array(paramsBuffer);
      const bufferIndex = this.readbackBufferIndex;
 
      paramsU32[0] = this.config.dimsWidth;
      paramsU32[1] = this.config.dimsHeight;
      paramsU32[2] = iterationsPerBatch;
      paramsU32[3] = this.activeCount;
      paramsU32[4] = this.refIterations + 1;
      paramsU32[5] = this.config.exponent || 2;
      paramsU32[6] = workgroupsX * workgroupSize;
      paramsU32[7] = bufferIter;
      paramsU32[8] = checkpointCount;
      paramsU32[9] = bufferIndex;  // buffer_index for per-buffer batch_active
 
      for (let i = 0; i < 32; i++) {
        paramsU32[10 + i] = i < checkpointCount ? checkpointOffsets[i] : 0;
      }
 
      paramsU32[42] = 0;  // _pad_ckpt
      const loop = this.refOrbitLoop || { enabled: false };
      paramsU32[43] = loop.enabled ? 1 : 0;
      paramsU32[44] = loop.threshold || 0;
      paramsU32[45] = loop.jumpAmount || 0;
      paramsI32[46] = this.initialScale;
      paramsU32[47] = 0;  // _pad_scale
      paramsF32[48] = pixelSize;
      paramsF32[49] = this.config.aspectRatio;
      paramsF32[50] = loop.deltaR || 0;
      paramsF32[51] = loop.deltaI || 0;
 
      this.device.queue.writeBuffer(this.buffers.params, 0, paramsBuffer);
 
      const commandEncoder = this.device.createCommandEncoder(
        { label: 'Adaptive perturbation compute' });
 
      // Guard pass: try to acquire batch lock (see docs/gpu-batch-locking.md)
      this.queueGuardPass(commandEncoder, bufferIndex);
 
      // Compute pass: iterate pixels (will skip if lock not acquired)
      const passEncoder = commandEncoder.beginComputePass(
        { label: 'Adaptive perturbation pass' });
      passEncoder.setPipeline(this.pipeline);
      passEncoder.setBindGroup(0, this.bindGroup);
      passEncoder.dispatchWorkgroups(workgroupsX, workgroupsY);
      passEncoder.end();
 
      // Queue staging shader pass and copy to staging buffer
      // Staging shader releases the lock after copying
      this.queueResultsReadback(commandEncoder, bufferIndex);
 
      const gpuStartTime = performance.now();
      this.device.queue.submit([commandEncoder.finish()]);
      // Save batch iter range using half-open interval [start, end)
      const batchStartIter = this.baseIt;
      this.baseIt += iterationsPerBatch;
      const batchEndIter = this.baseIt;
      const currentPromise = this.device.queue.onSubmittedWorkDone();
      // GPU is now computing in parallel!
 
      // ================================================================
      // STEP 5: Process pending results from PREVIOUS batch (overlaps with GPU)
      // ================================================================
      if (this.pendingReadbackIndex !== null) {
        await this.processPendingReadback();
      }
 
      // ================================================================
      // STEP 6: Speculative reference orbit extension while GPU works
      // ================================================================
      const speculativeTimeLimit = 100;  // ms
      const nextBatchIt = this.it + iterationsPerBatch;
      const nextBatchNeed = nextBatchIt + iterationsPerBatch;
      const speculativeTarget = Math.min(
        Math.max(nextBatchNeed + 10000, Math.round(nextBatchNeed * 1.1)),
        THREADING_CAPACITY
      );
 
      while (!this.refOrbitEscaped &&
             this.refIterations < speculativeTarget &&
             (performance.now() - gpuStartTime) < speculativeTimeLimit) {
        this.extendReferenceOrbit();
      }
 
      // ================================================================
      // STEP 7: Update pending state for next iteration
      // ================================================================
      this.pendingReadbackIndex = bufferIndex;
      this.pendingReadbackPromise = currentPromise;
      this.readbackBufferIndex = 1 - bufferIndex;
      this.pendingIterationsPerBatch = iterationsPerBatch;
      this.hasPendingResults = true;
      // Batch tracking: half-open interval [start, end) (see docs/gpu-results-readback-design.md)
      this.pendingBatchStartIter = batchStartIter;
      this.pendingBatchEndIter = batchEndIter;
 
    } catch (error) {
      console.error('GpuAdaptiveBoard.compute() ERROR:',
        error?.message || error, error?.stack || '');
    } finally {
      this.isComputing = false;
    }
  }
 
  // flushPendingResults() and readPixelBuffer() inherited from GpuZhuoranBaseBoard
 
  async serialize() {
    // Wait for any in-progress compute() to finish to avoid mapAsync race condition
    while (this.isComputing) {
      await new Promise(resolve => setTimeout(resolve, 10));
    }
 
    // CRITICAL: Flush pending results before serializing
    if (this.hasPendingResults) {
      await this.flushPendingResults();
    }
 
    // Ensure GPU is ready before reading buffers
    await this.ensureGPUReady();
 
    // Read GPU pixel buffer
    const gpuPixelData = await this.readPixelBuffer();
 
    // Build sparse nn array for completed pixels
    const completedIndexes = [];
    const completedNn = [];
    for (let i = 0; i < this.nn.length; i++) {
      if (this.nn[i] !== 0) {
        completedIndexes.push(i);
        completedNn.push(this.nn[i]);
      }
    }
 
    return {
      ...(await super.serialize()),
      // GPU pixel buffer as array (for JSON serialization)
      gpuPixelData: gpuPixelData ? Array.from(new Uint8Array(gpuPixelData)) : null,
      // QD reference orbit state
      qdRefOrbit: this.qdRefOrbit,
      refC_qd: this.refC_qd,
      refIterations: this.refIterations,
      refOrbitEscaped: this.refOrbitEscaped,
      refOrbitLoop: this.refOrbitLoop || null,
      refOrbitLoopConfigured: this.refOrbitLoopConfigured || false,
      // Per-pixel adaptive scaling
      initialScale: this.initialScale,
      // Board state
      effort: this.effort,
      completedIndexes,
      completedNn,
      activeCount: this.activeCount,
      deadSinceCompaction: this.deadSinceCompaction,
      wastedBandwidth: this.wastedBandwidth,
    };
  }
 
  static fromSerialized(serialized) {
    // GPU boards require async initialization, so this returns a board
    // that will continue initializing in the background
    const board = new GpuAdaptiveBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    // Schedule async restoration after GPU init
    board.gpuInitPromise = board.gpuInitPromise.then(async () => {
      if (serialized.activeCount !== undefined) {
        board.activeCount = serialized.activeCount;
        board.deadSinceCompaction = serialized.deadSinceCompaction || 0;
        board.wastedBandwidth = serialized.wastedBandwidth || 0;
        board.pendingActiveCount = board.activeCount;
 
        const bufferSize = board.activeCount * GpuAdaptiveBoard.BYTES_PER_PIXEL;
        board.buffers.pixels?.destroy();
        board.buffers.pixels = board.device.createBuffer({
          size: bufferSize,
          usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST
        });
        // Note: stagingPixels are created on-demand in readPixelBuffer() for serialization
        board.initResultsReadback(GpuAdaptiveBoard.BYTES_PER_PIXEL, board.activeCount);
        board.createBindGroup();
      }
 
      // Restore GPU pixel buffer
      if (serialized.gpuPixelData && board.isGPUReady) {
        const pixelData = new Uint8Array(serialized.gpuPixelData).buffer;
        await board.writePixelBuffer(pixelData);
      }
 
      // Restore QD reference orbit state
      board.qdRefOrbit = serialized.qdRefOrbit || [];
      board.refC_qd = serialized.refC_qd || new Array(8).fill(0);
      board.refIterations = serialized.refIterations || 1;
      board.refOrbitEscaped = serialized.refOrbitEscaped || false;
      board.refOrbitLoop = serialized.refOrbitLoop || null;
      board.refOrbitLoopConfigured = serialized.refOrbitLoopConfigured || false;
 
      // Restore per-pixel adaptive scaling
      if (serialized.initialScale !== undefined) {
        board.initialScale = serialized.initialScale;
      }
 
      // Rebuild threading structure from restored reference orbit
      board.rebuildQDThreading();
 
      // Restore Board state
      board.it = serialized.it;
      board.un = serialized.un;
      board.di = serialized.di;
      board.ch = serialized.ch || 0;
      board.effort = serialized.effort || 2;
 
      if (serialized.precomputed) {
        board.precomputed = PrecomputedPoints.fromSerialized(serialized.precomputed);
      }
 
      // Restore nn array
      board.nn = new Array(serialized.config.dimsArea).fill(0);
      if (serialized.completedIndexes) {
        for (let i = 0; i < serialized.completedIndexes.length; i++) {
          board.nn[serialized.completedIndexes[i]] = serialized.completedNn[i];
        }
      }
    });
 
    return board;
  }
}
 
 
const forcedBoardTypes = {
    'cpu': CpuBoard,
    'ddz': DDZhuoranBoard,
    'qdz': QDZhuoranBoard,
    'gpu': GpuBoard,
    'gl': GlBoard,
    'glz': GlZhuoranBoard,
    'gla': GlAdaptiveBoard,
    'gpuz': GpuZhuoranBoard,
    'gpua': GpuAdaptiveBoard,
    'qdcpu': QDCpuBoard
};
 
// Cache WebGL2 availability check
let glBoardAvailable = null;
function isGlBoardAvailable() {
  if (glBoardAvailable === null) {
    glBoardAvailable = GlBoard.isAvailable();
    // Logging is now done at point of use (see worker handleMessage)
  }
  return glBoardAvailable;
}
 
function selectBoardClass(pixelSize, dimsArea, gpuMaxBufferSize, forceBoard) {
  if (forceBoard) {
    if (forceBoard in forcedBoardTypes) {
      // Check if forcing a GPU board type but GPU isn't available
      const gpuBoardTypes = ['gpu', 'gpuz', 'gpua'];
      if (gpuBoardTypes.includes(forceBoard) && !gpuMaxBufferSize) {
        throw new Error(`board=${forceBoard} requested but WebGPU is not available. ` +
          `Use a CPU board (cpu, ddz, qdz) or WebGL board (gl, glz, gla) instead.`);
      }
      return forcedBoardTypes[forceBoard];
    } else {
      throw new Error(`Unknown board type: ${forcedBoardType}.` +
        ` Valid types: ${Object.keys(forcedBoardTypes).join(', ')}`);
    }
  }
 
  // Prefer WebGPU boards when available
  if (gpuMaxBufferSize) {
    // Select board type based on zoom level and float32 precision limits
    // Float32 has ~7 decimal digits, so direct iteration works to ~1e-7 pixel size
    // Shallow zooms (z < ~1e7): GpuBoard with simple float32 iteration
    // Medium zooms (z ~1e7 to ~1e30): GpuZhuoranBoard with quad-precision reference
    // Deep zooms (z > ~1e30): GpuAdaptiveBoard with QD-precision reference
    //   orbit and adaptive per-pixel scaling for correct escape detection
    const GpuBoardClass = (
        (pixelSize > 1e-7) ? GpuBoard :
        (pixelSize > 1e-30) ? GpuZhuoranBoard :
        GpuAdaptiveBoard);
    const largestBufferSize = dimsArea * GpuBoardClass.BYTES_PER_PIXEL;
    if (largestBufferSize <= gpuMaxBufferSize) {
      return GpuBoardClass;
    } else {
      const bufferSizeMB = (largestBufferSize / (1024*1024)).toFixed(0);
      const limitMB = (gpuMaxBufferSize / (1024*1024)).toFixed(0);
      console.log(
        `${GpuBoardClass}: dimsArea=${dimsArea} too large for GPU ` +
            `(buffer size ${bufferSizeMB} MB > ${limitMB} MB)`);
      // Fall through to try WebGL2 boards
    }
  }
 
  // WebGPU not available or buffer too large - try WebGL2 boards as fallback
  if (isGlBoardAvailable()) {
    // Shallow zooms: GlBoard with simple float32 iteration
    if (pixelSize > 1e-7) {
      return GlBoard;
    }
    // Medium zooms: GlZhuoranBoard with DD-precision reference orbit
    if (pixelSize > 1e-30 && GlZhuoranBoard.isAvailable()) {
      return GlZhuoranBoard;
    }
    // Deep zooms: GlAdaptiveBoard with QD-precision reference orbit
    if (GlAdaptiveBoard.isAvailable()) {
      return GlAdaptiveBoard;
    }
  }
 
  // No GPU available - fall back to CPU boards
  const CpuBoardClass = (
      (pixelSize > 1e-15) ? CpuBoard :
      (pixelSize > 1e-30) ? DDZhuoranBoard :
      QDZhuoranBoard);
  return CpuBoardClass;
}
 
 
// FractalWorker manages board computation on both main thread and in workers
// Always defined on the main thread (for MockWorker to extend)
// and instantiated in real workers via workerStart
class FractalWorker {
  constructor(workerNumber, name) {
    this.workerNumber = workerNumber;
    this.name = name;
    this.boards = new Map();
    this.hiddenBoards = new Set();
    this.focusedBoardK = null;
    this.computationPaused = false;
    this.steps = 0;
    this.startTime = 0;
    this.endTime = -1;
    this.timer = null;
    this.gpuMaxBufferSize = null;
    // Batch timing collection for benchmarking (debug=b)
    // Maps board.k -> array of {pixels, iters, timeMs}
    this.batchTimings = new Map();
    this.collectBatchTimings = false;
    // Console.log timing output (debug=t)
    this.logTimings = false;
    // Random batch sizes for benchmarking (debug=r)
    this.randomBatching = false;
    this.randomBatchMin = 1;
    this.randomBatchMax = 16;
    // Target time per batch in milliseconds (configurable)
    this.batchTimeMs = 100;
 
    // Fast scheduling using MessageChannel (faster than setTimeout(0))
    // The message queue has higher priority than the timer queue
    this.scheduleChannel = new MessageChannel();
    this.schedulePending = false;
    this.scheduleChannel.port1.onmessage = () => {
      this.schedulePending = false;
      this.iterateBoards();
    };
  }
 
  // Schedule next iteration using MessageChannel (faster than setTimeout(0))
  scheduleNextIteration() {
    if (!this.schedulePending) {
      this.schedulePending = true;
      this.scheduleChannel.port2.postMessage(null);
    }
  }
 
  // Record a batch timing sample for benchmarking
  // startPixels should be board.un captured BEFORE iterate()
  recordBatchTiming(board, startTime, startIter, startPixels) {
    if (!this.collectBatchTimings) return;
    const timeMs = performance.now() - startTime;
    const iters = board.it - startIter;
    // Use the pixel count from before the batch (some may have diverged during)
    const pixels = startPixels;
 
    if (iters > 0 && pixels > 0 && timeMs > 0) {
      if (!this.batchTimings.has(board.k)) {
        this.batchTimings.set(board.k, []);
      }
      this.batchTimings.get(board.k).push({ pixels, iters, timeMs });
    }
  }
 
  // Get batch timings for regression analysis
  getBatchTimings(k) {
    return this.batchTimings.get(k) || [];
  }
 
  // Clear batch timings
  clearBatchTimings(k) {
    if (k !== undefined) {
      this.batchTimings.delete(k);
    } else {
      this.batchTimings.clear();
    }
  }
 
  async handleMessage(type, data) {
    switch (type) {
      case 'addBoard':
        this.workerNumber = data.workerNumber;
        // Debug flags to disable GPU backends for testing fallback chain
        const noGPU = hasDebugFlag(data.config, 'nogpu');
        const noGL = hasDebugFlag(data.config, 'nogl');
        const webGPUAvailable = !noGPU && GpuBoard.isAvailable();
 
        // Query GPU limits once on first use
        if (webGPUAvailable && this.gpuMaxBufferSize === null) {
          this.gpuMaxBufferSize = await GpuBaseBoard.queryMaxBufferSize();
        }
        // Cache WebGL2 availability override for selectBoardClass
        if (noGL) {
          glBoardAvailable = false;
        }
 
        // Log fallback chain status (only for first board)
        if (data.k === 0) {
          if (noGPU) {
            if (noGL) {
              console.log('WebGPU disabled, WebGL2 disabled - falling back to CPU boards');
            } else if (isGlBoardAvailable()) {
              console.log('WebGPU disabled - falling back to WebGL2 boards');
            } else {
              console.log('WebGPU disabled, WebGL2 not available - falling back to CPU boards');
            }
          } else if (!this.gpuMaxBufferSize) {
            if (isGlBoardAvailable()) {
              console.log('WebGPU not available - falling back to WebGL2 boards');
            } else {
              console.log('WebGPU and WebGL2 not available - falling back to CPU boards');
            }
          }
        }
 
        // Explicit board selection via board= parameter
        const forceBoard = data.config.forceBoard;
        const size = data.size;
        const dimsArea = data.config.dimsArea;
        const pixelSize = size / data.config.dimsWidth;
        const BoardClass = selectBoardClass(pixelSize, dimsArea, this.gpuMaxBufferSize, forceBoard);
 
        // Construct the board instance with optional inherited data
        let board = new BoardClass(data.k, size, data.reQD, data.imQD, data.config, data.id, data.inheritedData);
        this.boards.set(data.k, board);
 
        // Log inheritance stats if debug=inherit is set
        if (data.inheritedData && hasDebugFlag(data.config, 'inherit')) {
          const inherited = data.inheritedData.packed ?
            ((data.inheritedData.dIndices?.length || 0) + (data.inheritedData.cIndices?.length || 0)) :
            ((data.inheritedData.diverged?.length || 0) + (data.inheritedData.converged?.length || 0));
          console.log(`Board ${data.k} (${BoardClass.name}): received ${inherited} inherited pixels`);
        }
 
        // Enable batch timing collection if debug=b is set
        if (hasDebugFlag(data.config, 'b')) {
          this.collectBatchTimings = true;
        }
        // Enable console.log timing output if debug=t is set
        if (hasDebugFlag(data.config, 't')) {
          this.logTimings = true;
        }
        // Enable random batch sizes for benchmarking if debug=r is set
        if (hasDebugFlag(data.config, 'r')) {
          this.randomBatching = true;
          this.logTimings = true;  // Also enable timing output
        }
 
      // Store QD-precision coordinates
      board.sizesQD = [size, data.reQD, data.imQD];
 
      // Show coordinates
      let coordStr;
      const digits = Math.ceil(-Math.log10(pixelSize)) + 3;
      const re_str = qdToDecimalString(data.reQD, digits);
      const im_str = qdToDecimalString(data.imQD, digits);
      coordStr = `c=(${re_str}, ${im_str})`;
      console.log(
        `Board ${data.k}: ${board.constructor.name} @ ${coordStr}, ` +
        `dims=${data.config.dimsWidth}x${data.config.dimsHeight}, ` +
        `pixel=${pixelSize.toExponential(3)}`
      );
 
      // Log refC_qd at full precision for deep zoom boards
      // to debug click vs URL differences
      if (board.refC_qd && pixelSize < 1e-45) {
        const refReQD = [board.refC_qd[0], board.refC_qd[1],
          board.refC_qd[2], board.refC_qd[3]];
        const refImQD = [board.refC_qd[4], board.refC_qd[5],
          board.refC_qd[6], board.refC_qd[7]];
        const digits = Math.ceil(-Math.log10(pixelSize)) + 3;
        console.log(`  refC_qd: (${qdToDecimalString(refReQD, digits)}, ` +
          `${qdToDecimalString(refImQD, digits)})`);
      }
 
        // Send board type info once on creation
        this.sendToScheduler({
          type: 'boardCreated',
          data: {
            k: data.k,
            boardType: board.constructor.name
          }
        });
        break;
      case 'removeBoard':
        this.boards.delete(data.k);
        break;
      case 'setFocusedBoard':
        this.focusedBoardK = data.k;
        break;
      case 'setHiddenBoards':
        this.hiddenBoards = new Set(data.hiddenBoards);
        break;
      case 'requestTransfer':
        const transferredBoards = [];
        for (const k of data.boardKeys) {
          if (this.boards.has(k)) {
            const board = this.boards.get(k);
            board.compact();
            const serializedBoard = await board.serialize();
            this.boards.delete(k);
            transferredBoards.push(serializedBoard);
          }
        }
        // Send the serialized boards back to the scheduler
        this.sendToScheduler({
          type: 'downloadTransfer',
          data: { transferredBoards }
        });
        break;
      case 'uploadTransfer':
        // Recreate the board from the serialized data and add it to this worker
        const newBoard = Board.fromSerialized(data.boardData);
        this.boards.set(newBoard.k, newBoard);
        break;
      case 'pause':
        this.computationPaused = data.pause;
        break;
    }
 
    // Start iteration loop if not running (check after every message)
    if (!this.timer && this.boards.size && !this.computationPaused) {
      this.iterateBoards();
    } else {
      const remainingWork = Array.from(this.boards.values()).
          filter(board => !this.hiddenBoards.has(board.k)).
          map(b => b.un * b.effort).reduce((a, b) => a + b, 0);
      this.sendToScheduler({
        type: 'update',
        data: {
          remainingWork,
        }
      });
    }
  }
 
  async iterateBoards() {
    this.timer = null;
    if (this.computationPaused) {
      return;
    }
    let pri = Array.from(this.boards.values())
          .filter(board => (board.unfinished() || board.updateSize || board.hasPendingResults))
          .filter(board => !this.hiddenBoards.has(board.k));
    if (pri.length) {
      // Start timer if it is not already running.
      if (this.endTime) {
        this.startTime = (new Date).getTime();
        this.endTime = 0;
      }
      if (this.steps % 2) {
        // Prioritize most unfinished half the time.
        pri = pri.sort((a, b) => b.un - a.un);
      } else {
        // Prioritize the most recent half the time.
        pri = pri.sort((a, b) => b.k - a.k);
        // Allow the user to prioritize by pointing the mouse.
        if (this.focusedBoardK !== null) {
          pri.sort((a, b) => (a.k === this.focusedBoardK ? -1 : b.k === this.focusedBoardK ? 1 : 0));
        }
      }
      // Exponential scheduling policy
      let shift = Math.floor(this.steps++ / 2) + 1;
      let p = 0;
      while (shift & (1 << p)) { p += 1; }
      const board = pri[Math.min(p, pri.length) % pri.length];
 
      // Calculate targetIters based on time budget and effort
      // Work threshold tuned for ~10-20ms CPU batches and ~50-100ms GPU batches
      // Large batches improve throughput by amortizing per-batch overhead
      const batchTimeMs = this.batchTimeMs || 100;
      const workThreshold = batchTimeMs * 5000000;
      let targetIters;
      if (this.stepMode) {
        // Step mode: always 1 iteration per step
        targetIters = 1;
      } else if (this.randomBatching) {
        // Random batch sizes for benchmarking (debug=r)
        // Produces varied iteration counts for regression analysis
        targetIters = this.randomBatchMin + Math.floor(
          Math.random() * (this.randomBatchMax - this.randomBatchMin + 1)
        );
      } else {
        // Calculate iterations to fill time budget, respecting board limits
        const pixels = Math.max(board.un, 1);
        const effort = Math.max(board.effort, 1);
        const minIters = board.minBatchIters || 1;
        const maxIters = board.maxBatchIters || Infinity;
        targetIters = Math.min(maxIters, Math.max(minIters, Math.floor(workThreshold / (pixels * effort))));
      }
 
      // In step mode, wait for step() to request iterations
      if (this.stepMode && this.stepsRequested <= 0) {
        // If stepsRequested is 0, don't do anything (wait for step() call)
      } else {
        const shouldTime = this.collectBatchTimings || this.logTimings;
        const startTime = shouldTime ? performance.now() : 0;
        const startIter = board.it;
        const startPixels = board.un;
        await board.iterate(targetIters);
        if (shouldTime) {
          const elapsedMs = performance.now() - startTime;
          const actualIters = board.it - startIter;
          if (this.collectBatchTimings) {
            this.recordBatchTiming(board, startTime, startIter, startPixels);
          }
          if (this.logTimings && actualIters > 0) {
            const boardType = board.constructor.name;
            const elapsedUs = elapsedMs * 1000;  // Convert to microseconds
            const usPerPixelIter = elapsedUs / (startPixels * actualIters);
            const compactedFlag = board.lastBatchCompacted ? ' C' : '';
            console.log(`[timing] ${boardType} k=${board.k}: ${startPixels} px × ${actualIters} iters = ${elapsedUs.toFixed(1)}μs${compactedFlag}`);
          }
        }
 
        if (this.stepMode) {
          this.stepsRequested--; // Consume one step
          // Call step callback if set
          if (this.stepCallback) {
            await this.stepCallback();
          }
        }
      }
      const now = (new Date()).getTime();
      const timeSinceUpdate = now - board.lastTime;
      const isFocused = this.focusedBoardK == board.k;
      const hasChanges = board.updateSize > 0 || !board.unfinished();
      // Send updates at least every 100ms, or earlier if enough pixels changed
      const enoughPixels = isFocused ?
        (board.updateSize >= 1429) : (board.updateSize >= 4673);
 
      if (timeSinceUpdate >= 100 || (hasChanges && enoughPixels)) {
        const boardEffort = board.un * board.effort;
        const remainingWork = pri.map(b => b.un * b.effort).reduce((a, b) => a + b, 0);
        const workerInfo = `${this.name}: ` + (board.unfinished() ?
             `boards {${[...this.boards.keys()]}}, work: ${remainingWork}` :
             `board finished`);
 
        // Sort changeList by iteration for consistent histogram construction
        board.changeList.sort((a, b) => a.iter - b.iter);
 
        this.sendToScheduler({
          type: 'iterations',
          data: {
            k: board.k,
            id: board.id,
            it: board.it,
            un: board.un,
            di: board.di,
            ch: board.ch,
            changeList: board.changeList,
            boardEffort,
            remainingWork,
            workerInfo,
            boardType: board.constructor.name,
            compactionCount: board.compactionCount || 0,
            activeCount: board.activeCount || board.config.dimsArea,
            resultsReadbackBytes: board.resultsReadbackBytes || 0,
            resultsReadbackBatches: board.resultsReadbackBatches || 0,
            lastResultsCount: board.lastResultsCount || 0,
            batchTotalCount: board.batchTotalCount || 0,
            batchCollisionCount: board.batchCollisionCount || 0
          }
        });
        board.lastTime = now;
        board.updateSize = 0;
        board.changeList = [];
        board.changeMap = null;
        if (!board.unfinished()) {
          // Delete board when done.
          this.boards.delete(board.k);
        }
      }
    } else {
      // End timer when there is no remaining work
      if (!this.endTime) {
         this.endTime = (new Date).getTime();
      }
      return;
    }
    this.scheduleNextIteration();
  }
 
  // Abstract method to be overridden by subclasses
  // Sends messages from worker back to scheduler
  sendToScheduler(msg) {
    throw new Error('FractalWorker.sendToScheduler() must be implemented by subclass');
  }
}
// </script>
// <script id="mathCode">
// Debug flag 'w': Define MockWorker for main thread debugging
// workerCode has type="text/webworker" so it's not parsed; eval it when needed for MockWorker
if (location.search.includes('debug=')) {
  const debugValue = decodeURIComponent(location.search.match(/[?&]debug=([^&]*)/)?.[1] || '');
  if (debugValue.split(',').includes('w')) {
    // Insert workerCode as a script element to make all classes available in global scope
    // (Using a script element instead of eval because class declarations are block-scoped in eval)
    const workerCodeEl = document.getElementById('workerCode');
    if (workerCodeEl) {
      const script = document.createElement('script');
      script.textContent = workerCodeEl.textContent;
      document.head.appendChild(script);
    }
    // Define MockWorker class that extends FractalWorker
    window.MockWorker = class MockWorker extends FractalWorker {
      constructor(workerNumber) {
        super(workerNumber, `MockWorker ${workerNumber}`);
        this.onmessage = null;  // Callback for sending messages back to Scheduler
 
        // Step mode support (debug=s flag)
        this.stepMode = false;
        this.stepsRequested = 0;
      }
 
      // Override to add step mode support
      async iterateBoards() {
        this.timer = null;
 
        // Step mode: only iterate if steps are requested
        if (this.stepMode && this.stepsRequested === 0) {
          // Wait for step() to be called
          this.timer = setTimeout(() => this.iterateBoards(), 100);
          return;
        }
 
        // Call parent implementation (it will check stepsRequested and decrement if needed)
        await super.iterateBoards();
      }
 
      // Handle incoming messages from Scheduler (when Scheduler calls worker.postMessage())
      // Real Workers receive messages via self.onmessage, but MockWorker receives via this method
      postMessage(msg) {
        // Schedule handleMessage asynchronously to match real Worker behavior
        setTimeout(async () => {
          const { type, data } = msg;
          await this.handleMessage(type, data);
        }, 0);
      }
 
      // Override abstract method to send messages back to Scheduler
      sendToScheduler(msg) {
        if (this.onmessage) {
          this.onmessage({ data: msg });
        }
      }
    };
 
    console.log('MockWorker class defined for main thread debugging');
 
    // Enable step mode if 's' flag is set
    if (debugValue.split(',').includes('s')) {
      // Set step mode flag on MockWorker initialization
      const originalConstructor = window.MockWorker;
      window.MockWorker = class extends originalConstructor {
        constructor(workerNumber) {
          super(workerNumber);
          this.stepMode = true;
          console.log(`MockWorker ${workerNumber} created in step mode`);
        }
      };
 
      // Helper functions for stepping through iterations
      window.step = function(n = 1, workerIndex = 0, callback = null) {
        if (typeof workerIndex === 'function') {
          callback = workerIndex;
          workerIndex = 0;
        }
 
        const worker = window[`worker${workerIndex}`];
        if (!worker || !worker.stepMode) {
          console.log(`Step mode not active for worker${workerIndex}. Load page with ?debug=w,s`);
          return;
        }
 
        worker.stepCallback = callback;
        worker.stepsRequested += n;
 
        if (!callback) {
          console.log(`Stepping worker${workerIndex} ${n} iteration(s)...`);
        }
        return worker.boards;
      };
 
      window.stepAll = function(workerIndex = 0) {
        const worker = window[`worker${workerIndex}`];
        if (!worker) {
          console.log(`No worker${workerIndex} available`);
          return;
        }
 
        worker.stepMode = false;
        worker.stepsRequested = 1; // Queue one step to trigger continuous iteration
        console.log(`Resuming continuous iteration for worker${workerIndex}...`);
      };
 
      window.pause = function(workerIndex = 0) {
        const worker = window[`worker${workerIndex}`];
        if (!worker) {
          console.log(`No worker${workerIndex} available`);
          return;
        }
 
        worker.stepMode = true;
        worker.stepsRequested = 0; // Clear any pending steps
        console.log(`Paused worker${workerIndex}. Use step() or step(n) to continue.`);
      };
 
      window.inspectBoard = function(k = 0, workerIndex = 0) {
        const worker = window[`worker${workerIndex}`];
        if (!worker || !worker.boards.has(k)) {
          console.log(`Board ${k} not found on worker${workerIndex}. Available:`, Array.from(worker?.boards?.keys() || []));
          return null;
        }
 
        const board = worker.boards.get(k);
        console.log(`Board ${k} on worker${workerIndex} (${board.constructor.name}):`);
        console.log(`  Iteration: ${board.it}`);
        console.log(`  Unfinished pixels: ${board.un}`);
        console.log(`  Diverged: ${board.di}`);
        console.log(`  Converged: ${board.ch}`);
 
        return board;
      };
 
      window.tracePixel = async function(k, pixelIndex, workerIndex = 0) {
        const worker = window[`worker${workerIndex}`];
        if (!worker || !worker.boards.has(k)) {
          console.log(`Board ${k} not found on worker${workerIndex}`);
          return null;
        }
 
        const board = worker.boards.get(k);
        const info = {
          boardType: board.constructor.name,
          iteration: board.it,
          nn: board.nn[pixelIndex]
        };
 
        // For Adaptive boards, read GPU state
        if (board.constructor.name === 'GpuAdaptiveBoard') {
          const pixelData = await board.readBuffer(board.buffers.pixels, Uint8Array);
          const offset = pixelIndex * 60;
          const pixelU32 = new Uint32Array(pixelData.buffer, offset, 15);
          const pixelF32 = new Float32Array(pixelData.buffer, offset, 15);
 
          info.status = new Int32Array([pixelU32[0]])[0];
          info.refIter = pixelU32[2];
          info.scale = new Int32Array([pixelU32[4]])[0];
          info.dzr = pixelF32[7];
          info.dzi = pixelF32[8];
          info.dzr_scaled = info.dzr * Math.pow(2, info.scale);
          info.dzi_scaled = info.dzi * Math.pow(2, info.scale);
        }
 
        // For QDZ boards, read CPU state
        if (board.constructor.name === 'QDZhuoranBoard') {
          info.refIter = board.refIter[pixelIndex];
          info.dzr = board.dz[pixelIndex * 2];
          info.dzi = board.dz[pixelIndex * 2 + 1];
        }
 
        console.table(info);
        return info;
      };
 
      // Analyze batch timings collected with debug=b
      // In step mode, each batch does 1 iteration, so we can only measure:
      //   time = overhead + perPixel × pixels
      // For multi-iteration batches (non-step mode), we could separate:
      //   time = perBatch + perIter × iters + perPixelIter × pixels × iters
      window.analyzeBatchTimings = function(k = 0) {
        const worker = window.worker0;
        if (!worker) {
          console.log('No worker available');
          return null;
        }
 
        const timings = worker.getBatchTimings(k);
        if (timings.length < 4) {
          console.log(`Not enough timing data (${timings.length} samples). Run more iterations with debug=b,w,s`);
          return null;
        }
 
        const board = worker.boards.get(k);
        const boardName = board?.constructor.name || 'Unknown';
        const n = timings.length;
 
        // Check if we have iteration variation
        const uniqueIters = [...new Set(timings.map(t => t.iters))];
        const hasIterVariation = uniqueIters.length > 1;
 
        // Simple linear regression: time = overhead + perPixel × pixels
        let sum_p = 0, sum_y = 0, sum_pp = 0, sum_py = 0;
        for (const t of timings) {
          const p = t.pixels;
          const y = t.timeMs * 1000; // μs
          sum_p += p; sum_y += y; sum_pp += p*p; sum_py += p*y;
        }
 
        const det = n * sum_pp - sum_p * sum_p;
        const perPixelUs = det !== 0 ? (n * sum_py - sum_p * sum_y) / det : 0;
        const overheadUs = (sum_y - perPixelUs * sum_p) / n;
 
        // Pixel count range
        const minPixels = Math.min(...timings.map(t => t.pixels));
        const maxPixels = Math.max(...timings.map(t => t.pixels));
 
        console.log(`\nBatch Timing Analysis for Board ${k} (${boardName}):`);
        console.log(`  Samples: ${n}`);
        console.log(`  Pixel range: ${minPixels} - ${maxPixels}`);
        console.log(`  Model: time = ${overheadUs.toFixed(1)} μs + ${perPixelUs.toFixed(4)} μs × pixels`);
        console.log(`  Per-pixel cost: ${Math.max(0, perPixelUs).toFixed(4)} μs/pixel`);
        console.log(`  Overhead: ${Math.max(0, overheadUs).toFixed(1)} μs/batch`);
 
        if (!hasIterVariation) {
          console.log(`\n  Note: In step mode, each batch does 1 iteration.`);
          console.log(`  The per-pixel cost is actually per-pixel-iteration.`);
        }
 
        // Show sample data
        console.log(`\n  Sample data (first 10):`);
        console.table(timings.slice(0, 10).map(t => ({
          pixels: t.pixels,
          iters: t.iters,
          timeMs: t.timeMs.toFixed(2),
          'μs/pixel': (t.timeMs * 1000 / t.pixels).toFixed(3)
        })));
 
        return { perPixelUs: Math.max(0, perPixelUs), overheadUs: Math.max(0, overheadUs), samples: n };
      };
 
      window.clearBatchTimings = function(k) {
        const worker = window.worker0;
        if (worker) {
          worker.clearBatchTimings(k);
          console.log(k !== undefined ? `Cleared timings for board ${k}` : 'Cleared all timings');
        }
      };
 
      console.log('Step mode enabled. Use step(), step(n), pause(), stepAll(), inspectBoard(k), tracePixel(k, pixelIndex)');
      if (window.worker0?.collectBatchTimings) {
        console.log('Batch timing enabled (debug=b). Use analyzeBatchTimings(k), clearBatchTimings(k)');
      }
    }
  }
}
// </script>
 
if (typeof module !== 'undefined') module.exports = { hasDebugFlag, isGlBoardAvailable, selectBoardClass, PrecomputedPoints, Board, CpuBoard, QDCpuBoard, SpatialBucket, DDSpatialBucket, QDSpatialBucket, ReferenceOrbitThreading, CpuZhuoranBaseBoard, DDZhuoranBoard, QDZhuoranBoard, GpuBaseBoard, GpuBoard, GlBoard, GlPerturbationBaseBoard, GlZhuoranBoard, GlAdaptiveBoard, GpuZhuoranBaseBoard, GpuZhuoranBoard, GpuAdaptiveBoard, FractalWorker, declarations, that, MockWorker, defined };