All files workerBlob.js

99.76% Statements 2986/2993
79.17% Branches 848/1071
99.31% Functions 288/290
99.75% Lines 2874/2881

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      5274x     5274x 5274x 5274x 2x 2x       5274x   358x   358x 358x 358x   358x 358x 358x 358x 358x   358x 358x 358x   358x 358x 358x     358x 358x 358x 358x 358x         6878x 5712x 5712x     944x     4x                                       6628772x 18146x 18146x         4x                     4x 4x           114172472x             54x           6758566x 6758566x         5274x   4x 4x 4x 4x   4x 38x 38x 38x 1154x 1154x 1154x 1154x 2x       4x 4x 4x       5274x                   5274x     5274x 5274x 5274x 5274x         5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x     5274x         5274x 5274x 5274x 5274x 5274x 5274x     5274x                       9168x 9168x 9168x   9168x 38x 17324x 17324x 17156x 17156x 17156x     9168x 1561232x 1561232x 1561232x 1154x 856x   1154x 2x           1154x       9168x 856x 856x   9168x 48x 48x   2x 2x 2x 2x 2x 2x 2x 2x 2x         2x 2x 2x         2x 2x 2x         2x 2x   2x       9168x 9168x       48x       1561232x 1486022x 1486022x 1486022x 1486022x 1486022x 1486022x 1561232x 1154x 1154x     1484870x 1484870x 1561232x 2x 2x 2x   1484870x 1484870x 1484870x 1484870x   1484870x 1484870x 1484870x 1561232x 4x 4x 2x 2x 2x   2x     1484870x             5274x   5274x         5274x 5274x       5274x 5274x     5274x 5274x       5274x 5274x   5274x 5274x 5274x   5274x   5274x 5274x 5274x 5274x 5274x       5274x 5274x 5274x       5274x                   5274x     5274x 5274x 5274x 5274x         5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x     5274x         5274x 5274x 5274x 5274x 5274x 5274x     5274x       5272x 5272x       5274x 5274x                   5274x 5274x   5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x     5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x   5274x             5274x       5274x 5274x 5274x   5274x 5274x     5274x 5274x       5272x       5274x 5274x   5274x 5274x       5274x 5274x 5274x             5274x 5274x   5274x       5274x 5274x 5274x     5274x 5274x     5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x           5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x     5274x         5274x   46x 46x 46x 46x 46x 46x 46x       46x   46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x     46x 46x 46x 46x 46x 46x 46x 46x 46x 46x     46x 46x 46x 46x 46x 46x 46x 2x       46x 46x 46x 46x 46x 794x 794x 25346x 25346x 25346x 25346x 25302x 25302x 25302x 25302x 25302x 25302x 2x               46x 46x 46x       4x               4x     4x 4x     4x 4x 4x 14x         4x 4x 4x 4x 4x 4x 4x 10x 10x 34x 34x 34x   10x 8x   10x   4x 1134x 1134x 3398x 3398x   1134x 1134x   4x         4x 4x 4x 1154x 14x 14x     4x                               1284696x 1284696x     1284696x 1284696x 5655074x 1222x 1222x   5655074x 5655074x 5655074x 15876x 12424x   15876x 10x           15868x         1284696x 1284696x 1284696x 256747028x 15604x 15604x 15604x 15604x 15604x 2x 2x   2x 2x           2x           1284696x 6804x 6804x 6804x 1708894x 15604x   1693292x     6804x 6804x     1284696x 5670674x     1284694x 1284694x 1284694x 1284694x   1284696x 620x   620x 120x 274x 274x   120x     1284694x 1284694x       622x 622x         5670676x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 4082406x 5670676x 15868x 15868x 15868x   4066540x 4066540x 5670676x 2x 2x 2x 2x 2x 2x 2x   4066540x 4066540x   4066540x 4066540x 4066540x 4066540x 5670676x 22x 22x 10x 10x 2x   10x     4066532x       256747028x 256747028x 256747028x 256747028x 256747028x 256747028x 256747028x     256747028x     256747028x 580844x 580844x 580844x 580844x 580844x   256747024x     256747024x 256747024x 256747024x 256747024x 256747024x 256747024x 256747024x 256747024x       256747024x 256747024x   256747028x 15600x     256731426x 256731426x 256731426x       580844x 580844x   580844x 2x 2x     2x 2x 2x     2x       580844x 580844x 580844x         256747052x 256747052x   256747022x 151018x 151018x 151048x       15876x 15876x 15876x 15876x 15876x 15876x 15876x 15876x 15876x 15876x 15876x       6x 6x 6x 6x 6x 6x 6x         5274x   5274x 5274x 5274x 5274x 5274x       5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x 5272x             5274x               5274x     5274x     5274x 5274x 5274x 5274x         5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x   5274x         5274x 5274x 5274x 5274x 5274x 5274x     5274x                       5274x 5274x 5274x 5274x         5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x           5274x       5274x 5274x 5274x   5274x 5274x 5274x 5274x     5274x 5274x       5272x       5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x   5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x     5274x             5274x               50x   50x 50x 50x       5274x       5274x     7329952x 7329952x 7329952x       18324872x             3664976x 3664976x 3664976x 3664976x 3664976x 3634194x   3664976x                   3664978x 3664978x   3664978x         3664978x 3664978x 3664978x 3664978x   3664978x             3664978x 3664978x 14659900x 14659900x 14659900x   2593778x 5585708x 2632938x     2632938x 2632938x 2531898x 2531898x       10667324x 2531898x   10667324x 2531898x       3664976x             3628568x 1126692028x 1138730108x 1110968x     1126692028x 1081014x                   5274x   22x 22x       4576328x 4576328x 4576328x       1961538x 1961538x 1961538x     1961538x 1961538x     1961538x 1961538x     1961538x 1960148x   1390x               5274x   28x 28x       2753626x 2753626x 2753626x             671402x 671402x 671402x     671402x       671402x           671402x 671402x     671402x 571752x   99652x         5274x           50x   50x   50x   50x                     3664978x     3664978x         3664978x 2531898x               3664976x     3664978x 3628568x               110767522x             5274x               5274x                       5274x       22x     22x 22x 22x     22x 22x 22x     22x     22x         22x 22x 22x 22x   22x 42x         43578982x 43578982x 43587886x 39163142x 8906x 8906x         8906x 8906x 8906x         2288134x 2288134x 2288134x   2288134x 2288134x 2288134x 2288134x     2288134x 2288134x 2288134x   2288134x 10x 10x       2288126x 2288126x   2288132x 390x 390x 390x 390x 390x 390x 390x       2288126x 2288126x 2288126x   2288126x 2288126x     2288126x     2288134x 54x               5274x       30x     30x           30x 30x 30x     30x     30x         30x 30x 30x 30x   30x 58x         296757040x 296757040x 296769418x 287365592x 12380x 12380x         12380x 12380x 12380x         1376772x 1376772x 1376772x 1376772x     1376772x 1376772x 1376772x 1376772x 14x 14x         1376760x 1376760x 1376760x   1376760x     1376770x 390x   390x   390x   390x   390x   390x   390x       1376760x 1376760x 1376760x   1376760x     1376760x   1376760x     1376760x     1376772x 52x             5274x   22x     22x 22x 22x     22x 22x 22x     22x 22x 22x 22x 22x   22x           5274x     5274x     5274x     5272x     5272x     5274x     5272x     5274x       5331778x   5331778x 5331778x 976602x     5331776x 5331778x 108850286x 108850286x 108850286x 42986x 1730x   42986x   21704x 21704x 21704x 21704x     21284x 21284x 21284x 21284x 21284x 21284x         21284x 21284x 21284x       2x       108807300x     5331774x   5331778x 2x   5331774x 5331774x         108850286x 108850286x     108850286x 108850286x 108850286x 108850286x 108850286x 108850286x 108850286x 108850286x 108850286x 108850286x 21704x         108850286x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x   2x         108850286x 13828574x 13828574x 13828574x 13828574x 13828574x 13828574x 13828574x 13828574x 13828574x       108828584x 108850286x 2x   108828584x 108828584x     108828584x 108828584x   108850286x     108850286x 108850286x 108850286x     108850286x 108850286x     108850286x   108828584x 108828584x 108828584x 108828584x     108828584x 108828584x 108828584x     108828584x 108828584x 108828584x     108828584x       108828584x 108828584x 108828584x 108828584x     108828584x 108850286x 571918x 571918x 571918x 571918x 571918x 571918x     108256666x 108256666x 108256666x 2907426x 2907426x 2907426x 2907426x       108256666x 16014154x 16014154x 16014154x 16014154x 16014154x 16014154x 16014154x   16014154x 2975290x 37384x   2975290x 21284x             108807300x 108850286x 259920x   108807300x         108828584x 108828584x 108828584x 108828584x   108828584x 108828584x   108828584x 108828584x   108828584x 108828584x   108828584x 108828584x 108828584x 108828584x   108828584x         5274x 5274x 5274x 5274x 5274x 5274x     5274x                                               5274x 5274x 5274x 5274x         5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x     5274x 5274x 5274x     5274x 5274x 5274x 5274x           5274x   6x     6x 6x 6x   6x       6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x   6x 146x 146x 146x 146x 9218x 9218x 9218x 9218x 9218x 9218x     9218x 9218x 9218x 9218x 9218x 2x             5274x                   5274x     5274x 5274x     5274x   5274x       5274x               5274x 5274x 5274x   5274x             5274x   18x     18x 18x 18x   18x             18x 18x 18x 18x     18x 18x   18x 638x 638x   638x 37250x 37250x   37250x 37250x 37250x   37250x 37250x   37250x 37250x     37250x 37250x 37250x 2x             5274x               5274x                   5274x     5274x 5274x     5274x   5274x               5274x       292x         292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x         292x 292x 292x 292x 292x     292x   292x 167490x 167490x   167490x 114103574x 114103574x 114103574x   114103574x   22112x 184x   22112x 22112x             286x   286x 2x 2x       286x 286x 2x 2x       286x 286x   286x   286x 286x     286x     286x 2x 2x       282x 280x 274x   274x 274x     2x   2x 2x         2x         5274x 5274x 5274x   5274x       14784x 2168x     14784x 5596x 5360x   7024x 13176x 7024x   6826x         554x 554x           554x 554x 554x   554x 554x 554x 554x   554x       362x       288x 2x   288x 288x 282x     282x 282x 282x   282x 282x     288x     282x     282x 282x   2x 2x           5274x       5274x       5274x       5274x                   5274x 5274x       5274x 5274x       5274x 5272x 5272x 5272x     5272x 5272x               5272x 5272x   5272x 5272x     5272x 5272x 5272x 5272x 5272x   5272x     5274x 5274x 5274x   5274x                 5274x 5274x   5274x 5274x 5274x         5274x       264x 264x   264x   264x 264x 264x   264x           254x                                                                                                                                                                                                                                                                                                 254x         254x                     252x     252x         252x 252x   252x 2x               252x               252x             252x             252x                 252x 252x 252x   252x 108168394x   108168394x 108168394x 108168394x   108168394x 108168394x 108168394x 108168394x   250x     250x 250x 107658122x   250x         246x                         5686x 2x   5686x 5686x 5686x 5686x 5686x     5686x 5686x 5686x     5686x 242x       5686x 5686x 1843295632x 393201314x       5652x   5680x 1716x 1716x       3938x   3938x 5686x   5686x 3936x       3936x     3936x 3936x     3936x 3936x 3936x     3936x 3936x 5680x 11993364x 11993364x 2916x     3930x     3930x 3930x 3930x   3930x 3930x 3930x 3930x 3930x 3930x 3930x 3930x 3930x 3930x 3930x 3930x 3930x 3930x     5680x 31426x     3930x     3930x         3930x       3930x 3930x 3930x 3930x     3930x       3930x 3930x     3890x     3890x 3878x 3878x 3878x 3878x     3878x 3878x     5674x 232x       3874x 3874x   5680x 377837254x 377837254x 377837254x 377837254x 377837254x 377837254x 377837254x     377837254x   377837254x   56355064x 56355064x 56355064x   56355064x 48342x   56355064x 56355064x     56355064x 2x     321482192x   17041834x 17041834x       17041834x   17041834x 30810x   17041834x         17041834x     17041834x 3090x             3844x 3844x 3844x 5670x 1711114152x 1711114152x 701872170x 299081112x       3782x   3782x 3782x   5664x 59938x 59938x   59938x         59938x       3782x 3782x 3782x     2x   5496x           5274x     5274x     5274x 5274x 5274x 5274x 5274x 5274x       5274x                             5274x                   5274x     5274x 5274x 5274x       5274x 5274x   5274x 5274x   5274x     5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x       5274x             5274x                   5274x   5272x 5272x 5272x       5272x 5272x   5272x 5272x   5272x     5272x 5272x 5272x 5272x     5272x 5272x 5272x 5272x         5274x             5274x       18x   18x     18x 18x 18x     18x     18x       18x 18x 18x     18x 18x   18x 18x 18x     18x   18x   18x       18x 18x 18x 18x 18x     18x   3578x     3578x 3578x     3578x   3578x   2070850x     2070850x 2070850x     2070850x   2070850x 2070850x     2070850x 2070850x     2070850x 2070850x     2070850x       18x       18x     18x         18x   18x 2x                   18x                 18x             18x     18x               18x 18x 18x   18x 2070850x   2070850x 2070850x 2070850x 2070850x 2070850x 2070850x   2070850x 2070850x 2070850x 2070850x 2070850x 2070850x 2070850x 2070850x         18x   18x 18x 18x 18x 18x   18x 18x 18x 18x 18x   18x 18x     18x         28x                             5274x 5274x   5274x 5274x       5274x 5274x 5274x     5274x 5274x   5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x         5274x 5274x 5274x 5274x     5274x               5274x     5274x 5274x 5274x       5274x 5274x 5274x 5274x       5274x 5274x   5274x 5274x   5274x 5274x 5274x   5274x   5274x 5274x             18x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               18x         18x                       732x     732x 732x   732x   732x   732x 732x       732x       732x 732x     732x 732x   732x       732x 1805718x       732x             728x 728x     728x 728x 728x 732x     10x 10x 10x         10x 10x       728x 146x   146x 146x 146x   146x 146x   146x 2510856x 2510856x 2510856x   2510856x   2510856x 2510856x   2510856x         2510856x 2510856x 2510856x       146x 146x     146x       732x 404x 404x         324x     324x 324x 732x 1756974x 1756974x 326x             324x     324x 324x     324x 324x         324x 324x 324x 324x 324x 324x 324x 324x 732x 732x   732x 732x     732x 2592x       732x 732x 732x 732x 732x 732x 732x 732x 732x   732x   732x   732x 732x 732x 732x 732x   732x     732x       324x 324x 324x     324x     324x 324x     324x 324x 324x     324x 324x   732x 20676896x 20676896x 20676896x   20676896x   20676896x   2067804x 2067804x 2067804x 2067804x   2067804x 1400x   2067804x 2067804x 2067804x     2067804x     15200514x 3040x 3040x         730x 52x 162816x 162816x 162816x   162816x   162816x   3040x 3040x       3040x       3040x 3040x 3040x 3040x   3040x   3040x 3040x 3040x 378x   3040x         3040x     3040x 300x                       324x   324x   732x 1726x 1726x   1726x 1726x                     728x           5274x     5274x     5274x 5274x 5274x 5274x 5274x 5274x       5274x                                         5274x                   5274x   5272x 5272x 5272x       5272x 5272x 5272x 5272x 5272x 5272x     5272x     5272x 5272x 5272x 5272x 5272x     5272x 5272x 5272x 5272x         5274x                                         5274x       14x   14x     14x 14x 14x     14x     14x               5274x 5274x   5274x 5274x       5274x     5274x 5274x 5274x   5274x 5274x   5274x   5274x       5274x 5274x 5274x   5274x 5274x 5274x         5274x 5274x   5274x       5274x 5274x   5274x                   5274x     5274x 5274x 5274x       5274x 5274x 5274x 5274x       5274x 5274x   5274x 5274x   5274x 5274x 5274x   5274x   5274x 5274x               606x 606x 606x     606x 606x 20x 20x 20x       20x 20x       606x 230x 230x     230x 230x 906286x 906286x 906286x   906286x   906286x 906286x 906286x 906286x 906286x     230x 230x         14x 14x 14x     14x 14x     14x 14x     14x     14x 14x 14x 14x           14x 760x   760x 94306x   94306x 94306x     94306x 94306x     94306x 94306x     94306x     94306x       14x               14x           14x 14x   14x                                   14x 14x 14x   14x 94306x   94306x 94306x 94306x 94306x 94306x 94306x 94306x   94306x 94306x 94306x 94306x 94306x 94306x 94306x 94306x   14x   14x       32x                               14x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           14x           14x 14x 2x 2x       14x                       608x 608x     608x     608x 2x 2x 2x     608x 608x     608x   608x 608x   608x     608x 608x 608x 608x 882586x       608x 2x       606x   608x 378x 378x       230x 230x 608x 865724x 865724x 234x     230x     230x 230x   230x 230x 230x 230x     230x 230x 230x 230x   230x 230x 230x 230x 230x 608x 608x 608x 608x   608x 1826x     608x 608x 608x 608x 608x 608x 608x 608x 608x   608x   608x   608x   608x 608x 608x 608x   608x 608x   230x           230x 230x 230x     230x 230x 230x     230x 230x 230x   608x 4654018x 4654018x 4654018x 4654018x 4654018x 92154x 92154x 92154x 92154x 92154x 92154x 92154x 92154x 4317050x 2150x       606x 18x 93890x 93890x 93890x 93890x 93890x 2150x 2150x 2150x 2150x     2150x 2150x 2150x 2150x   2150x 2150x 2150x 2150x   2150x 2150x         230x   608x 1416x 1416x 1416x 1416x         2x     606x           5274x     5274x     5274x 5274x 5274x 5274x 5274x 5274x       5274x                                             5274x                   5274x   5272x 5272x 5272x       5272x 5272x 5272x 5272x 5272x 5272x     5272x 5272x       5272x     5272x 5272x 5272x 5272x 5272x     5272x 5272x 5272x 5272x         5274x       5272x 5272x           5274x                       356x 356x 42x 42x   2x           316x             266x       266x 266x 266x   2x 2x 2x             356x       356x             5274x   302x 302x 302x 302x 302x 302x 302x 302x 302x 302x 302x       1956x   362x 362x 362x     362x 288x       356x 356x 356x 356x 356x     356x 356x     356x     356x 356x 356x 356x 356x 356x               362x 6x   6x   6x 6x         350x             350x   60x 60x   318x 318x   1176x 1176x   4x 4x 4x 4x 4x 4x 4x 4x       4x       4x     4x 4x 4x   44x 44x       1956x 698x   1248x     1248x                   68702x 68702x 2x   68702x     68702x   68550x 312x 312x   68550x   34200x     34352x   34352x 2556x       68550x 68550x 68550x 68550x     68550x 2x 2x 2x     2x 2x             68550x 14784x   53768x 6625638x 6625638x       68102x 68550x     3080x 3080x 3080x     3080x                               3080x 3080x 3080x 3080x   72x         154x 72x   154x   68098x           5274x             5274x 5274x       5274x 5274x 5274x 5274x 5274x       5274x 5274x 5274x 5274x 5274x 5274x         5274x 5274x 5274x 5274x   5274x   5274x   5274x   5274x       5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x     5274x 5274x 5274x     5274x 5274x 5274x       5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x   5274x 5274x 5274x 5274x 5274x   5274x   5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x           5274x 5274x 5274x 5274x 5274x 5274x 5274x           5274x 5274x     5274x 5274x       5274x       5274x 5274x       5274x     5274x   5274x             5274x 5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x     5274x   5274x 5274x   5274x     5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x     5274x 5274x     5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x     5274x 5274x 5274x     5274x 5274x     5274x 5274x 5274x     5274x 5274x 5274x     5274x 5274x 5274x   5274x       5274x 5274x 5274x 5274x       5274x 5274x 5274x 5274x       5274x 5274x 5274x 5274x 5274x 5274x 5274x       5274x 5274x 5274x 5274x       5274x 5274x 5274x 5274x 5274x 5274x 5274x       5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x 5274x   5274x 5274x   5274x 5274x   5274x     5274x 5274x   5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x   5274x     5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x     5274x 5274x     5274x 5274x     5274x 5274x     5274x   5274x     5274x   5274x   5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x 5274x 5274x     5274x   5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x     5274x 5274x 5274x 5274x     5274x 5274x 5274x   5274x 5274x   5274x 5274x       5274x 5274x 5274x   5274x     5274x 5274x 5274x   5274x 5274x     5274x   5274x   5274x           5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x     5274x 5274x 5274x 5274x         5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x     5274x 5274x     5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x           5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x         5274x 5274x     5274x 5274x 5274x 5274x     5274x 5274x 5274x     5274x 5274x   5274x   5274x     5274x 5274x 5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x 5274x     5272x 5272x     5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x   5274x 5274x   5274x   5274x 5274x 5274x 5274x   5274x 5274x 5274x   5274x         5274x   5274x     5274x 5274x     5274x 5274x 5274x     5274x 5274x 5274x     5274x 5274x 5274x 5274x 5274x     5274x     5274x           5274x   5274x     5274x     5274x 5274x     5274x     5274x 5274x     5274x 5274x 5274x 5274x 5274x     5274x     5274x         5274x 5274x 5274x 5274x 5274x 5274x 5274x           5274x       5274x 5274x     5274x 5274x 5274x 5274x 5274x       5274x 5274x         5274x 5274x 5274x 5274x 5274x 5274x   5274x 5274x 5274x 5274x       5274x 5274x               5274x
// 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 + '='));
}
 
// Abstract base class for Mandelbrot computation backends.
class Board {
  constructor(k, size, re, im, config, id) {
    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 = 1;        // Work-per pixel
 
    this.pix = this.pixelSize;
    this.epsilon = Math.min(1e-12, this.pix / 10);
    this.epsilon2 = Math.min(1e-9, 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 = [];
  }
 
  // 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
    };
  }
 
  compact() {
  }
 
  queueChanges(changes) {
    if (changes !== null) {
      this.changeList.push(changes);
      this.updateSize += changes.nn.length + changes.vv.length;
    }
  }
 
  static fromSerialized(serialized) {
    const subclasses = new Map([
      ['CpuBoard', CpuBoard],
      ['QDCpuBoard', QDCpuBoard],
      ['PerturbationBoard', PerturbationBoard],
      ['QDPerturbationBoard', QDPerturbationBoard],
      ['DDZhuoranBoard', DDZhuoranBoard],
      ['QDZhuoranBoard', QDZhuoranBoard],
      ['GpuBoard', GpuBoard],
      ['GpuZhuoranBoard', GpuZhuoranBoard],
      ['AdaptiveGpuBoard', AdaptiveGpuBoard]
    ]);
    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);
  }
 
  inspikeDDA(re1, re2, im1, im2) {
    // We do not iterate infinitely for chaotic points in the spike.
    // -1.401155 is the Feigenbaum point boundary
    return (im1 + im2 == 0.0 && re1 >= -2.0 && re1 < -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) {
    super(k, size, re, im, config, id);
    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
    this.ss = Array(this.config.dimsArea).fill(null).map((_, i) => i);  // All pixels active
  }
 
  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];
    }
 
    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() {
    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}`);
      }
    }
 
    this.it++;
    this.queueChanges(changes);
  }
 
  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
    if (db <= this.epsilon2) {
      if (!this.pp[m]) { this.pp[m] = this.it; }  // Record iter when first detected
      if (db <= this.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) {
    super(k, size, re, im, config, id);
    // 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
    // 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);
    // 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 toQDMul instead of toQDScale to capture error terms
      const jQD = toQDAdd(imQD, toQDMul(sizeOverAspect, toQD(jFrac)));
      for (let x = 0; x < this.config.dimsWidth; x++) {
        const rFrac = ((x / this.config.dimsWidth) - 0.5);
        // Use toQDMul instead of toQDScale to capture error terms
        const rQD = toQDAdd(reQD, toQDMul(this.size, toQD(rFrac)));
        // 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
    this.ss = Array(this.config.dimsArea).fill(null).map((_, i) => i);  // All pixels active
  }
 
  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];
    }
 
    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() {
    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();
    }
 
    this.it++;
    this.queueChanges(changes);
  }
 
  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]);
    if (db <= this.epsilon2) {
      if (!this.pp[m]) { this.pp[m] = this.it; }  // Record iter when first detected
      if (db <= this.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
  }
}
 
// CPU board using perturbation theory with sparse DD precision anchors.
class PerturbationBoard extends Board {
  constructor(k, size, re, im, config, id) {
    super(k, size, re, im, config, id);
    this.ddIndexes = [];     // Pixels computed in DD precision
    this.pertIndexes = [];   // Pixels computed as perturbations from DD points
    this.tt = [];            // Working array for DD precision operations
    this.perturbationThreshold = Math.min(0.1, Math.sqrt(1e15 * (size / config.dimsWidth)));
    this.effort = 3;
    this.initPerturbationBoard(size, re, im);
  }
 
  initPerturbationBoard(size, re, im) {
    this.cc = new Array(this.config.dimsArea * 4).fill(NaN);
    // Odd grid ensures that center point corresponds to a DD precision pixel
    const gridSizeX = Math.floor(this.config.dimsWidth / 17 / 2) * 2 + 1;
    const gridSizeY = Math.floor(this.config.dimsHeight / 17 / 2) * 2 + 1;
    const stepX = this.config.dimsWidth / gridSizeX;
    const stepY = this.config.dimsHeight / gridSizeY;
    const offsetX = stepX / 2;
    const offsetY = stepY / 2;
    const pixW = size / this.config.dimsWidth;
    const pixH = (size / this.config.aspectRatio) / this.config.dimsHeight;
    const cc = this.cc;
    re = toDD(re);
    im = toDD(im);
 
    // Initialize reference points and perturbations
    for (let gy = 0; gy < gridSizeY; gy++) {
      const ry = Math.round(gy * stepY + offsetY);
      const jFrac = (0.5 - (ry / this.config.dimsHeight));
      const cj = ddAdd(im, ddScale(toDD(jFrac), size / this.config.aspectRatio))
      for (let gx = 0; gx < gridSizeX; gx++) {
        const rx = Math.round(gx * stepX + offsetX);
        const rFrac = ((rx / this.config.dimsWidth) - 0.5);
        const refIndex = (ry * this.config.dimsWidth + rx);
        const ri = refIndex * 4;
        const cr = ddAdd(re, ddScale(toDD(rFrac), size));
 
        // Initialize reference point
        cc[ri] = cr[0];
        cc[ri+1] = cr[1];
        cc[ri+2] = cj[0];
        cc[ri+3] = cj[1];
        this.ddIndexes.push(refIndex);
        let refspike = this.inspikeDDA(cr[0], cr[1], cj[0], cj[1]);
        if (refspike) {
          this.ch += 1;
        }
 
        // Initialize perturbations around this reference point
        const minY = Math.max(0, Math.floor(ry - offsetY));
        const maxY = Math.min(this.config.dimsHeight - 1, Math.ceil(ry + offsetY));
        const minX = Math.max(0, Math.floor(rx - offsetX));
        const maxX = Math.min(this.config.dimsWidth - 1, Math.ceil(rx + offsetX));
        for (let py = minY; py <= maxY; py++) {
          const dci = (ry - py) * pixH;
          for (let px = minX; px <= maxX; px++) {
            const dcr = (px - rx) * pixW;
            const pertIndex = (py * this.config.dimsWidth + px);
            const pi = pertIndex * 4;
            if (isNaN(cc[pi+3])) {  // Avoid double-initialization
              cc[pi] = dcr;
              cc[pi+1] = dci;
              cc[pi+2] = refIndex;
              cc[pi+3] = Infinity;
              this.pertIndexes.push(pertIndex);
              if (refspike && py == ry) {
                this.ch += 1;
              }
            }
          }
        }
      }
    }
 
    this.zz = this.cc.slice();
    this.bb = [];
    this.nz = [];
  }
 
  static fromSerialized(serialized) {
    const board = new PerturbationBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
    const cc = board.cc;
 
    // Override initialized values with serialized data
    Object.assign(board, serialized);
    delete board.pertZZ;
 
    // 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 arrays from serialized data, leaving empty spots
    board.cc = [];
    board.zz = [];
    board.nz = [];
    board.bb = [];
    board.pp = [];
    const ddIdx = serialized.ddIndexes || [];
    for (let i = 0; i < ddIdx.length; i++) {
      const index = ddIdx[i];
      for (let j = 0; j < 4; j++) {
        board.zz[index * 4 + j] = board.nz[index * 4 + j] = serialized.zz[i * 4 + j];
        board.bb[index * 4 + j] = serialized.bb[i * 4 + j];
        board.cc[index * 4 + j] = cc[index * 4 + j];
      }
      if (!isFinite(cc[index * 4 + 3])) {
        board.initAsDDPrecision(index, cc);
      }
      board.pp[index] = serialized.pp[i];
    }
    for (let i = 0; i < serialized.pertIndexes.length; i++) {
      const index = serialized.pertIndexes[i];
      for (let j = 0; j < 3; j++) {
        board.zz[index * 4 + j] = serialized.pertZZ[i * 3 + j];
        board.cc[index * 4 + j] = cc[index * 4 + j];
      }
      board.zz[index * 4 + 3] = board.cc[index * 4 + 3] = Infinity;
      board.pp[index] = 0;
    }
    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()),
      ddIndexes: this.ddIndexes,
      pertIndexes: this.pertIndexes,
      zz: this.ddIndexes.flatMap(i =>
        [this.zz[i*4], this.zz[i*4+1], this.zz[i*4+2], this.zz[i*4+3]]),
      bb: this.ddIndexes.flatMap(i =>
        [this.bb[i*4], this.bb[i*4+1], this.bb[i*4+2], this.bb[i*4+3]]),
      pp: this.ddIndexes.map(index => this.pp[index]),
      pertZZ: this.pertIndexes.flatMap(i => [this.zz[i*4], this.zz[i*4+1], this.zz[i*4+2]]),
      completedIndexes,
      completedNn,
    };
  }
 
  iterate() {
    let changes = null;
    let results = [0, 0, 0];
    // Precompute DD precision point escape without updating z
    // Update checkpoints at Fibonacci intervals
    const isCheckpoint = fibonacciPeriod(this.it) === 1;
    for (const index of this.ddIndexes) {
      if (isCheckpoint && !this.nn[index]) {
        ArddcCopy(this.bb, index*4, this.zz, index*4);  // bb = checkpoint z
        this.pp[index] = 0;  // Reset pp (period = iter when convergence first detected)
      }
      let r = this.precomputeDD(index);
      results[r + 1] += 1;
      if (r !== 0) {
        if (!changes) {
          changes = { iter: this.it, nn: [], vv: [] };
        }
        if (r < 0) {
          changes.vv.push({
            index: index,
            z: ArddcGet(this.nz, index*4),  // DDc format
            p: this.pp[index]  // period
          });
        } else {
          changes.nn.push(index);
        }
      }
    }
    // Iterate perturbation points that use the old z
    const newDDIndexes = [];
    let cache = { refIndex: null, binZpow: [] };
    for (const index of this.pertIndexes) {
      if (!this.computePerturbation(index, cache)) {
        this.convertToDDPrecision(index);
        let r = this.precomputeDD(index);
        results[r + 1] += 1;
        newDDIndexes.push(index);
        if (r !== 0) {
          if (!changes) {
            changes = { iter: this.it, nn: [], vv: [] };
          }
          if (r < 0) {
            changes.vv.push({
              index: index,
              z: ArddcGet(this.nz, index*4),  // DDc format
              p: this.pp[index]  // period
            });
          } else {
            changes.nn.push(index);
          }
        }
      }
    }
    // Update index arrays
    if (newDDIndexes.length > 0) {
      const newPertIndexes = [];
      let qi = 0;
      for (const index of this.pertIndexes) {
        if (newDDIndexes[qi] == index) {
          qi += 1;
        } else {
          newPertIndexes.push(index);
        }
      }
      this.ddIndexes = this.ddIndexes.concat(newDDIndexes);
      this.pertIndexes = newPertIndexes;
    }
    // Finally update DD precision z with precomputed values
    for (const index of this.ddIndexes) {
      ArddcCopy(this.zz, index*4, this.nz, index*4);
    }
    // Tally progress
    let diverged = results[2];
    let count = results[0] + diverged;
    this.un -= count;
    this.di += diverged;
    // Trim finished pixels from array.
    if (this.pertIndexes.length + this.ddIndexes.length > this.un * 1.25) {
      this.compact();
      // Switch to full DD when perturbations are a small fraction of the work
      if (this.pertIndexes.length < this.ddIndexes.length * 0.5) {
        for (const index of this.pertIndexes) {
          this.convertToDDPrecision(index);
          this.ddIndexes.push(index);
        }
        this.pertIndexes = [];
      }
    }
    this.it++;
    this.queueChanges(changes);
  }
 
  compact() {
    const trimmedDDIndexes = this.ddIndexes.filter(i => !this.nn[i]);
    this.ddIndexes = trimmedDDIndexes;
  }
 
  precomputeDD(m) {
    // DD precision Mandelbrot iteration with convergence detection
    if (this.nn[m]) return 0;
    const m4 = m * 4;
    const tt = this.tt;
    const nz = this.nz;
    const r1 = this.zz[m4];
    const r2 = this.zz[m4+1];
    const j1 = this.zz[m4+2];
    const j2 = this.zz[m4+3];
    const cr1 = this.cc[m4];
    const cr2 = this.cc[m4+1];
    const cj1 = this.cc[m4+2];
    const cj2 = this.cc[m4+3];
    const br1 = this.bb[m4];  // bb = checkpoint z (DD precision)
    const br2 = this.bb[m4+1];
    const bj1 = this.bb[m4+2];
    const bj2 = this.bb[m4+3];
    ArddSquare(tt, 0, r1, r2);                    // 0: rsq = r**2
    ArddSquare(tt, 2, j1, j2);                    // 2: jsq = j**2
    ArddAdd(tt, 4, tt[0], tt[1], tt[2], tt[3]);   // 4: d = rsq+jsq
    if (tt[4] > 4) {  // Check divergence: |z|² > 4
      this.nn[m] = this.it;
      ArddcCopy(nz, m4, this.zz, m4);
      return 1;  // Diverged
    }
    ArddMul(tt, 6, 2 * r1, 2 * r2, j1, j2);       // 6: ja = 2*r*j
    ArddAdd(tt, 8, tt[0], tt[1], -tt[2], -tt[3]); // 8: ra = rsq-jsq
    for (let ord = 2; ord < this.config.exponent; ord++) {
      ArddMul(tt, 0, j1, j2, tt[6], tt[7]);         // 0: j * ja
      ArddMul(tt, 2, r1, r2, tt[8], tt[9]);         // 2: r * ra
      ArddAdd(tt, 4, -tt[0], -tt[1], tt[2], tt[3]); // 4: rt = r*ra - j*ja
      ArddMul(tt, 0, r1, r2, tt[6], tt[7]);         // 0: r * ja
      ArddMul(tt, 2, j1, j2, tt[8], tt[9]);         // 2: j * ra
      ArddAdd(tt, 6, tt[0], tt[1], tt[2], tt[3]);   // 6: ja = r*ja + j*ra
      ArddSet(tt, 8, tt[4], tt[5]);                 // 8: ra = rt
    }
    ArddAdd(nz, m4, tt[8], tt[9], cr1, cr2);        // nz: nzr = ra + cr
    ArddAdd(nz, m4+2, tt[6], tt[7], cj1, cj2);      // nz+2: nzj = ja + cj
    // Check convergence: compare new z to checkpoint
    ArddAbsSub(tt, 0, br1, br2, nz[m4], nz[m4+1]);  // 0: abs(nzr - br)
    ArddAbsSub(tt, 2, bj1, bj2, nz[m4+2], nz[m4+3]);// 2: abs(nzj - bj)
    ArddAdd(tt, 4, tt[0], tt[1], tt[2], tt[3]);     // 4: db = abs(nzr-br)+abs(nzj-bj)
    const db = tt[4] + tt[5]  // distance from checkpoint
    if (db <= this.epsilon2) {
      if (!this.pp[m]) { this.pp[m] = this.it; }  // Record iter when first detected
      if (db <= this.epsilon) {
        this.nn[m] = -this.it;
        if (this.inspikeDDA(cr1, cr2, cj1, cj2) && this.ch > 0) {
          this.ch -= 1;
        }
        return -1;  // Converged
      }
    }
    return 0;  // Continue iterating
  }
 
  computePerturbation(index, cache) {
    const m4 = index * 4;
    const cr = this.cc[m4]
    const ci = this.cc[m4+1]
    const refIndex = this.cc[m4+2]
    const ri4 = refIndex * 4;
    const dr = this.zz[m4];
    const di = this.zz[m4+1];
 
    // Switch to quad when approaching convergence.
    if (this.nn[refIndex] || this.pp[refIndex]) return false;
 
    // Compute binomial powers of z
    if (cache.refIndex !== refIndex) {
      cache.refIndex = refIndex;
      const ri4 = refIndex * 4;
      const zr = this.zz[ri4];
      const zi = this.zz[ri4+2];
      this.fillBinZpow(cache.binZpow, zr, zi);
    }
    const binZpow = cache.binZpow;
 
    // Compute in (z+d)^n - z^n = nz^(n-1) d + (n(n-1)/2)z^(n-2) d^2...
    let r = dr;
    let i = di;
    for (let ord = 0; ord < binZpow.length; ord += 2) {
      r += binZpow[ord];
      i += binZpow[ord+1];
      const rNew = r * dr - i * di;
      i = r * di + i * dr;
      r = rNew;
    }
 
    // Add perturbation in c
    r += cr;
    i += ci;
 
    if (this.isThresholdExceeded(r, i, refIndex)) {
      return false;
    }
 
    this.zz[m4] = r;
    this.zz[m4+1] = i;
    return true;
  }
 
  fillBinZpow(binZpow, zr, zi) {
    let zrCurrent = zr, ziCurrent = zi;
    let coeff = this.config.exponent;
 
    for (let k = 1; k < this.config.exponent - 1; k++) {
      binZpow[k*2-2] = coeff * zrCurrent;
      binZpow[k*2-1] = coeff * ziCurrent;
 
      // Update z power
      const zrNew = zrCurrent * zr - ziCurrent * zi;
      ziCurrent = zrCurrent * zi + ziCurrent * zr;
      zrCurrent = zrNew;
 
      // Update coefficient for next iteration
      coeff *= (this.config.exponent - k) / (k + 1);
    }
 
    // Add the last element without computing the next z power or coefficient
    if (this.config.exponent > 1) {
      binZpow[this.config.exponent*2 - 4] = coeff * zrCurrent;
      binZpow[this.config.exponent*2 - 3] = coeff * ziCurrent;
    }
  }
 
  isThresholdExceeded(dr, di, refIndex) {
    const mag = Math.max(Math.abs(dr), Math.abs(di));
    if (mag > this.perturbationThreshold) return true;
    // If orbit is getting large, then be more careful.
    if (mag * 10 < this.perturbationThreshold) return false;
    const zr = this.zz[refIndex * 4];
    const zi = this.zz[refIndex * 4 + 2];
    return ((dr + zr) ** 2 + (di + zi) ** 2 > 3);
  }
 
  convertToDDPrecision(index) {
    const m4 = index * 4;
    const dr = this.zz[m4];
    const di = this.zz[m4+1];
    const cr = this.cc[m4];
    const ci = this.cc[m4+1];
    const refIndex = this.cc[m4+2];
    const ri4 = refIndex * 4;
    ArddAdd(this.zz, m4, dr, 0, this.zz[ri4], this.zz[ri4+1])
    ArddAdd(this.zz, m4+2, di, 0, this.zz[ri4+2], this.zz[ri4+3])
    ArddAdd(this.cc, m4, cr, 0, this.cc[ri4], this.cc[ri4+1])
    ArddAdd(this.cc, m4+2, ci, 0, this.cc[ri4+2], this.cc[ri4+3])
  }
 
  initAsDDPrecision(index, refcc) {
    const m4 = index * 4;
    const cr = this.cc[m4];
    const ci = this.cc[m4+1];
    const refIndex = this.cc[m4+2];
    const ri4 = refIndex * 4;
    ArddAdd(this.cc, m4, cr, 0, refcc[ri4], refcc[ri4+1])
    ArddAdd(this.cc, m4+2, ci, 0, refcc[ri4+2], refcc[ri4+3])
  }
}
 
// QD-precision CPU board using perturbation theory (quad-double anchors)
class QDPerturbationBoard extends Board {
  constructor(k, size, re, im, config, id) {
    super(k, size, re, im, config, id);
    this.qdIndexes = [];   // Pixels computed in QD precision
    this.tt = new Array(32).fill(0);           // Working array for QD operations
    this.effort = 4;        // Higher cost than quad perturbation
    this.initQDBoard(size, re, im);
  }
 
  initQDBoard(size, re, im) {
    const dimsArea = this.config.dimsArea;
    this.cc = new Array(dimsArea * 8).fill(0);
    this.zz = new Array(dimsArea * 8).fill(0);
    this.bb = new Array(dimsArea * 8).fill(0);
    this.ss = Array.from({length: dimsArea}, (_, i) => i);
    this.nn = new Array(dimsArea).fill(0);
    this.pp = new Array(dimsArea).fill(0);
    this.un = dimsArea;
    this.di = 0;
    const re_o = Array.isArray(re) && re.length === 4 ? re : [re, 0, 0, 0];
    const im_o = Array.isArray(im) && im.length === 4 ? im : [im, 0, 0, 0];
    for (let y = 0; y < this.config.dimsHeight; y++) {
      const jFrac = (0.5 - (y / this.config.dimsHeight));
      const cj = toQDAdd(im_o, toQDScale(toQD(jFrac), size / this.config.aspectRatio));
      for (let x = 0; x < this.config.dimsWidth; x++) {
        const rFrac = ((x / this.config.dimsWidth) - 0.5);
        const cr = toQDAdd(re_o, toQDScale(toQD(rFrac), size));
        const idx = y * this.config.dimsWidth + x;
        const m8 = idx * 8;
        this.cc[m8] = cr[0]; this.cc[m8+1] = cr[1];
        this.cc[m8+2] = cr[2]; this.cc[m8+3] = cr[3];
        this.cc[m8+4] = cj[0]; this.cc[m8+5] = cj[1];
        this.cc[m8+6] = cj[2]; this.cc[m8+7] = cj[3];
        this.zz[m8] = cr[0]; this.zz[m8+1] = cr[1];
        this.zz[m8+2] = cr[2]; this.zz[m8+3] = cr[3];
        this.zz[m8+4] = cj[0]; this.zz[m8+5] = cj[1];
        this.zz[m8+6] = cj[2]; this.zz[m8+7] = cj[3];
        this.bb[m8] = cr[0]; this.bb[m8+1] = cr[1];
        this.bb[m8+2] = cr[2]; this.bb[m8+3] = cr[3];
        this.bb[m8+4] = cj[0]; this.bb[m8+5] = cj[1];
        this.bb[m8+6] = cj[2]; this.bb[m8+7] = cj[3];
        this.qdIndexes.push(idx);
        if (this.inspikeDDA(cr[0], cr[1], cj[0], cj[1])) {
          this.ch += 1;
        }
      }
    }
  }
 
  static fromSerialized(serialized) {
    const board = new QDPerturbationBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
    const cc = board.cc;
 
    // 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 arrays from serialized data (8 floats per pixel for QD)
    board.cc = [];
    board.zz = [];
    board.bb = [];
    board.pp = [];
    const qdIdx = serialized.qdIndexes || [];
    for (let i = 0; i < qdIdx.length; i++) {
      const index = qdIdx[i];
      for (let j = 0; j < 8; j++) {
        board.zz[index * 8 + j] = serialized.zz[i * 8 + j];
        board.bb[index * 8 + j] = serialized.bb[i * 8 + j];
        board.cc[index * 8 + j] = cc[index * 8 + j];
      }
      board.pp[index] = serialized.pp[i];
    }
    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()),
      qdIndexes: this.qdIndexes,
      zz: this.qdIndexes.flatMap(i => this.zz.slice(i*8, i*8+8)),
      bb: this.qdIndexes.flatMap(i => this.bb.slice(i*8, i*8+8)),
      pp: this.qdIndexes.map(index => this.pp[index]),
      completedIndexes,
      completedNn,
    };
  }
 
  initAsQDPrecision(index, refcc) {
    const m8 = index * 8;
    for (let j = 0; j < 4; j++) {
      this.cc[m8 + j] = refcc[m8 + j];
      this.cc[m8 + 4 + j] = refcc[m8 + 4 + j];
    }
  }
 
  iterate() {
    let changes = null;
    const s = this.ss;
    const isCheckpoint = fibonacciPeriod(this.it) === 1;
    if (isCheckpoint) {
      for (let t = 0; t < s.length; ++t) {
        const m = s[t];
        if (this.nn[m]) continue;
        ArqdcCopy(this.bb, m*8, this.zz, m*8);  // bb = checkpoint z position
        this.pp[m] = 0;  // Reset pp
      }
    }
    for (let t = 0; t < s.length; ++t) {
      const index = s[t];
      const result = this.compute(index);
      if (result !== 0) {
        if (!changes) {
          changes = { iter: this.it, nn: [], vv: [] };
        }
        if (result < 0) {
          changes.vv.push({
            index: index,
            z: ArqdcGet(this.zz, index*8),
            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) {
        throw new Error(`excess ss ${s.length}, ${this.ss.length}, ${this.un}`);
      }
    }
    this.it++;
    this.queueChanges(changes);
  }
 
  compact() {
    this.ss = this.ss.filter(i => !this.nn[i]);
  }
 
  compute(m) {
    if (this.nn[m]) return 0;
    const m8 = m * 8;
    const tt = this.tt;
    const r1 = this.zz[m8];
    const r2 = this.zz[m8+1];
    const r3 = this.zz[m8+2];
    const r4 = this.zz[m8+3];
    const j1 = this.zz[m8+4];
    const j2 = this.zz[m8+5];
    const j3 = this.zz[m8+6];
    const j4 = this.zz[m8+7];
    const cr1 = this.cc[m8];
    const cr2 = this.cc[m8+1];
    const cr3 = this.cc[m8+2];
    const cr4 = this.cc[m8+3];
    const cj1 = this.cc[m8+4];
    const cj2 = this.cc[m8+5];
    const cj3 = this.cc[m8+6];
    const cj4 = this.cc[m8+7];
    ArqdSquare(tt, 0, r1, r2, r3, r4);
    ArqdSquare(tt, 4, j1, j2, j3, j4);
    ArqdAdd(tt, 8, tt[0], tt[1], tt[2], tt[3], tt[4], tt[5], tt[6], tt[7]);
    if (tt[8] > 4) {
      this.nn[m] = this.it;
      return 1;  // Diverged
    }
    ArqdMul(tt, 12, 2 * r1, 2 * r2, 2 * r3, 2 * r4, j1, j2, j3, j4);
    ArqdAdd(tt, 20, tt[0], tt[1], tt[2], tt[3], -tt[4], -tt[5], -tt[6], -tt[7]);
    for (let ord = 2; ord < this.config.exponent; ord++) {
      ArqdMul(tt, 0, j1, j2, j3, j4, tt[12], tt[13], tt[14], tt[15]);
      ArqdMul(tt, 4, r1, r2, r3, r4, tt[20], tt[21], tt[22], tt[23]);
      ArqdAdd(tt, 8, -tt[0], -tt[1], -tt[2], -tt[3], tt[4], tt[5], tt[6], tt[7]);
      ArqdMul(tt, 0, r1, r2, r3, r4, tt[12], tt[13], tt[14], tt[15]);
      ArqdMul(tt, 4, j1, j2, j3, j4, tt[20], tt[21], tt[22], tt[23]);
      ArqdAdd(tt, 12, tt[0], tt[1], tt[2], tt[3], tt[4], tt[5], tt[6], tt[7]);
      ArqdSet(tt, 20, tt[8], tt[9], tt[10], tt[11]);
    }
    ArqdAdd(this.zz, m8, tt[20], tt[21], tt[22], tt[23], cr1, cr2, cr3, cr4);
    ArqdAdd(this.zz, m8+4, tt[12], tt[13], tt[14], tt[15], cj1, cj2, cj3, cj4);
    // Check convergence: compare current z to checkpoint
    const br1 = this.bb[m8];
    const br2 = this.bb[m8+1];
    const bj1 = this.bb[m8+4];
    const bj2 = this.bb[m8+5];
    ArqdAbsSub(tt, 0, br1, br2, this.zz[m8], this.zz[m8+1]);
    ArqdAbsSub(tt, 4, bj1, bj2, this.zz[m8+4], this.zz[m8+5]);
    ArqdAdd(tt, 8, tt[0], tt[1], tt[2], tt[3], tt[4], tt[5], tt[6], tt[7]);
    const db = tt[8] + tt[9];
    if (db <= this.epsilon2) {
      if (!this.pp[m]) { this.pp[m] = this.it; }
      if (db <= this.epsilon) {
        this.nn[m] = -this.it;
        if (this.inspikeDDA(cr1, cr2, cj1, cj2) && this.ch > 0) {
          this.ch -= 1;
        }
        return -1;  // Converged
      }
    }
    return 0;
  }
}
 
// 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
    const zr = toDDAdd([ref[0], ref[1]], dzr);
    const zi = toDDAdd([ref[2], ref[3]], dzi);
    return [zr[0], zr[1], zi[0], zi[1]];
  }
 
  // 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 AdaptiveGpuBoard (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
    const zrQD = toQDAdd([ref[0], ref[1], ref[2], ref[3]], [dzr, 0, 0, 0]);
    const ziQD = toQDAdd([ref[4], ref[5], ref[6], ref[7]], [dzi, 0, 0, 0]);
    return [...zrQD, ...ziQD];
  }
 
  // 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) {
    super(k, size, re, im, config, id);
 
    // 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 = 2;  // Effort level for scheduling
  }
 
  // 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 (precision-specific)
  initPixels() { throw new Error('Abstract method'); }
 
  // Shared iterate() method - works for both DD and QD
  iterate() {
    let changes = null;
    // Step 1: Extend reference orbit if needed and not escaped
    const targetRefIterations = Math.max(this.it + 100, this.maxRefIter + 100);
    while (!this.refOrbitEscaped && this.refIterations < targetRefIterations) {
      this.extendReferenceOrbit();
    }
    // 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]);
    }
    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));
 
        if (db <= this.epsilon2) {
          if (!this.pp[index]) {
            this.pp[index] = this.it - 1;
          }
          if (db <= this.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) {
    super(k, size, re, im, config, id);
 
    // 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();
  }
 
  initPixels() {
    const sizeScalar = this.size;
    const reDD = qdToDD(this.re);
    const imDD = qdToDD(this.im);
    const pixW = sizeScalar / this.config.dimsWidth;
    const pixH = (sizeScalar / this.config.aspectRatio) / this.config.dimsHeight;
    const dimsWidth = this.config.dimsWidth;
    const dimsHeight = this.config.dimsHeight;
    const refRe = this.refC[0] + this.refC[1];
    const refIm = this.refC[2] + this.refC[3];
    // Convert DD precision arrays to doubles for perturbation deltas
    const re_double = reDD[0] + reDD[1];
    const im_double = imDD[0] + imDD[1];
    // Initialize all pixels as perturbations from the reference point
    for (let y = 0; y < dimsHeight; y++) {
      const yFrac = (0.5 - y / dimsHeight);
      const ci = im_double + yFrac * (sizeScalar / this.config.aspectRatio);
      const dci = ci - refIm;
      for (let x = 0; x < dimsWidth; x++) {
        const xFrac = (x / dimsWidth - 0.5);
        const cr = re_double + xFrac * sizeScalar;
        const dcr = cr - refRe;
        const index = y * dimsWidth + x;
        this.dc[index * 2] = dcr;
        this.dc[index * 2 + 1] = dci;
        // Start with z = c (skipping trivial first iteration where 0^2+c=c)
        // At refIter=1 where refOrbit[1] = c_ref, with dz = dc: z = c_ref + dc = c
        this.dz[index * 2] = dcr;
        this.dz[index * 2 + 1] = dci;
        this.refIter[index] = 1;  // Start at iteration 1 (z = c)
        this.pixelIndexes.push(index);
        if (this.inspike(cr, ci)) {
          this.ch += 1;
        }
      }
    }
  }
 
  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) {
    super(k, size, re, im, config, id);
 
    // 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();
  }
 
  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
    const refRe = this.refC_qd[0] + this.refC_qd[1] + this.refC_qd[2] + this.refC_qd[3];
    const refIm = this.refC_qd[4] + this.refC_qd[5] + this.refC_qd[6] + this.refC_qd[7];
 
    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;
        this.pixelIndexes.push(index);
 
        // Count spike pixels
        const cr = refRe + dcr;
        const ci = refIm + dci;
        if (this.inspike(cr, ci)) {
          this.ch += 1;
        }
      }
    }
  }
 
  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) {
    super(k, size, re, im, config, id);
 
    // 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.selfBatching = true;  // GPU boards handle batching internally
  }
 
  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 {
      // Check WebGPU availability
      if (!navigator.gpu) {
        console.warn('WebGPU not supported');
        return false;
      }
 
      // Request adapter and device
      const adapter = await navigator.gpu.requestAdapter();
      if (!adapter) {
        console.warn('No WebGPU adapter found');
        return false;
      }
 
      // 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;
      }
 
      // Subclass-specific initialization
      await this.createComputePipeline();
      await this.createBuffers();
      this.createBindGroup();
 
      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() {
    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();
    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 {
      const adapter = await navigator.gpu.requestAdapter();
      if (!adapter) return GpuBaseBoard.GPU_DEFAULT_MAX_BUFFER;
 
      // Request device with higher limits if supported
      const requiredLimits = {};
      if (adapter.limits.maxStorageBufferBindingSize > 134217728) {
        requiredLimits.maxStorageBufferBindingSize = adapter.limits.maxStorageBufferBindingSize;
      }
      if (adapter.limits.maxBufferSize > 134217728) {
        requiredLimits.maxBufferSize = adapter.limits.maxBufferSize;
      }
 
      const device = await adapter.requestDevice({
        requiredLimits: Object.keys(requiredLimits).length > 0 ? requiredLimits : undefined
      });
      const limit = Math.min(
        device.limits.maxBufferSize,
        device.limits.maxStorageBufferBindingSize);
      GpuBaseBoard.cachedMaxBufferSize = Math.floor(limit * 0.9);  // 90% for safety
      return GpuBaseBoard.cachedMaxBufferSize;
    } catch (e) {
      GpuBaseBoard.cachedMaxBufferSize = GpuBaseBoard.GPU_DEFAULT_MAX_BUFFER;
      return GpuBaseBoard.cachedMaxBufferSize;
    }
  }
 
  // 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.
   * Subclasses must have created buffers.pixels and buffers.stagingPixels.
   * Uses a lock to prevent concurrent mapAsync calls.
   * @returns {Promise<ArrayBuffer>} The pixel buffer data
   */
  async readPixelBuffer() {
    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 staging buffer if not present
      if (!this.buffers.stagingPixels) {
        this.buffers.stagingPixels = this.device.createBuffer({
          size: bufferSize,
          usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
          label: 'Staging pixels buffer (serialization)'
        });
      }
 
      // Copy pixels buffer to staging
      const commandEncoder = this.device.createCommandEncoder();
      commandEncoder.copyBufferToBuffer(
        this.buffers.pixels, 0, this.buffers.stagingPixels, 0, bufferSize);
      this.device.queue.submit([commandEncoder.finish()]);
      await this.device.queue.onSubmittedWorkDone();
 
      // Read back the data
      await this.buffers.stagingPixels.mapAsync(GPUMapMode.READ);
      const pixelData = new ArrayBuffer(bufferSize);
      const srcData = this.buffers.stagingPixels.getMappedRange();
      new Uint8Array(pixelData).set(new Uint8Array(srcData));
      this.buffers.stagingPixels.unmap();
 
      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.
class GpuBoard extends GpuBaseBoard {
  static BYTES_PER_PIXEL = 28;  // 3 u32 + 4 f32 (consolidated PixelState struct)
 
  constructor(k, size, re, im, config, id) {
    super(k, size, re, im, config, id);
    this.effort = 1;
    // Epsilon values for convergence detection scale with pixel size
    const pix = this.pixelSize;
    // GPU uses float32 precision, so thresholds must be larger than CPU's float64
    this.epsilon = Math.min(1e-7, pix / 10);   // Final convergence threshold
    this.epsilon2 = Math.min(1e-5, pix * 10);  // Getting close threshold
    this.checkSpike(size, re, im);
    // Start GPU initialization (async)
    this.gpuInitPromise = this.initGPU();
  }
 
  async createComputePipeline() {
    // Mandelbrot shader with period detection for convergence
    // Consolidated 3-binding layout: params, pixels (PixelState struct), active_pixels
    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,
        ckpt0: u32,
        ckpt1: u32,
        ckpt2: u32,
        ckpt3: u32,
        ckpt4: u32,
        ckpt5: u32,
        ckpt6: u32,
        ckpt7: u32,
      }
 
      // Per-pixel state: 3 u32 + 4 f32 = 28 bytes
      // Layout (u32 view):
      //   [0] iter: u32
      //   [1] status: u32
      //   [2] period: u32
      //   [3] zr: f32
      //   [4] zi: f32
      //   [5] base_r: f32
      //   [6] base_i: f32
      struct PixelState {
        iter: u32,
        status: u32,
        period: u32,
        zr: f32,
        zi: f32,
        base_r: f32,
        base_i: f32,
      }
 
      @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> active_pixels: array<u32>;
 
      @compute @workgroup_size(64)
      fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
        // 2D dispatch: calculate linear index from 2D coordinates
        let active_idx = global_id.y * params.workgroups_x + global_id.x;
        if (active_idx >= params.active_count) {
          return;
        }
        let index = active_pixels[active_idx];
        let x = index % params.dims_width;
        let y = index / params.dims_width;
        // Compute c for this pixel
        // Use integer arithmetic to avoid float32 rounding: (coord - dims/2) / dims
        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);
        // Load pixel state
        var zr = pixels[index].zr;
        var zi = pixels[index].zi;
        var iter = pixels[index].iter;
        var base_r = pixels[index].base_r;
        var base_i = pixels[index].base_i;
        var p = pixels[index].period;
        // If this is the first batch and base is still zero, initialize it
        if (iter == 0u && base_r == 0.0 && base_i == 0.0) {
          base_r = zr;  // Initialize to starting z (which is 0,0)
          base_i = zi;
        }
        // Track next checkpoint using O(1) counter for adaptive Fibonacci checkpoints
        var next_checkpoint_idx = 0u;
        // Iterate for this batch
        for (var i = 0u; i < params.iterations_per_batch; i++) {
          // Check if this iteration is a Fibonacci checkpoint
          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; }
              default: {}
            }
            if (i == checkpoint_offset) {
              base_r = zr;
              base_i = zi;
              p = 0u;  // Reset p (period = iter when convergence first detected)
              next_checkpoint_idx++;
            }
          }
          let zr2 = zr * zr;
          let zi2 = zi * zi;
          let mag_sq = zr2 + zi2;
          // Check divergence (escape radius 2, or NaN/Infinity from numerical errors)
          if (mag_sq > 4.0 || !(mag_sq <= 1e38)) {  // NaN/Inf check: !(x <= large) catches both
            pixels[index].status = 1u;  // Diverged
            break;
          }
          // z = z^exponent + c (generalized Mandelbrot)
          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;
          // Check convergence: compare new z to checkpoint
          let dr = zr - base_r;
          let di = zi - base_i;
          let db = abs(dr) + abs(di);  // distance from checkpoint
          if (db <= params.epsilon2) {
            if (p == 0u) {
              p = iter;  // Record iter when convergence first detected
            }
            if (db <= params.epsilon) {
              pixels[index].status = 2u;  // Converged (periodic)
              break;
            }
          }
          iter++;
        }
        // Save state
        pixels[index].zr = zr;
        pixels[index].zi = zi;
        pixels[index].base_r = base_r;
        pixels[index].base_i = base_i;
        pixels[index].iter = iter;
        pixels[index].period = p;
      }
    `;
 
    const shaderModule = this.device.createShaderModule({
      code: shaderCode,
      label: 'Mandelbrot compute shader'
    });
 
    this.pipeline = this.device.createComputePipeline({
      layout: 'auto',
      compute: {
        module: shaderModule,
        entryPoint: 'main'
      },
      label: 'Mandelbrot compute pipeline'
    });
  }
 
  async createBuffers() {
    const dimsArea = this.config.dimsWidth * this.config.dimsHeight;
 
    // Check buffer size limits before creating (safety margin applied upstream)
    const maxBufferSize = Math.min(
      this.device.limits.maxBufferSize,
      this.device.limits.maxStorageBufferBindingSize
    );
    // PixelState struct: 3 u32 + 4 f32 = 28 bytes per pixel
    const BYTES_PER_PIXEL = 28;
    const pixelBufferSize = dimsArea * 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.`);
    }
 
    // Uniform buffer for shader parameters
    this.buffers.params = this.device.createBuffer({
      size: 128,
      usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
      label: 'Parameters buffer'
    });
 
    // Consolidated pixel state buffer
    // (PixelState struct: iter, status, period, zr, zi, base_r, base_i)
    this.buffers.pixels = this.device.createBuffer({
      size: pixelBufferSize,
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
      label: 'Pixel state buffer'
    });
 
    // Storage buffer for active pixel indices (sparse list, max size = dimsArea)
    this.buffers.activePixels = this.device.createBuffer({
      size: dimsArea * 4,  // 4 bytes per u32
      usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
      label: 'Active pixels buffer'
    });
 
    // Staging buffer for reading pixel state back to CPU
    this.buffers.stagingPixels = this.device.createBuffer({
      size: pixelBufferSize,
      usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
      label: 'Staging pixels buffer'
    });
 
    // Initialize pixel state buffer using overlapping typed array views
    // PixelState struct layout: [iter(u32), status(u32), period(u32),
    //   zr(f32), zi(f32), base_r(f32), base_i(f32)]
    const pixelData = new ArrayBuffer(pixelBufferSize);
    const pixelU32 = new Uint32Array(pixelData);
    const pixelF32 = new Float32Array(pixelData);
 
    for (let i = 0; i < dimsArea; i++) {
      const idx7 = i * 7;  // 7 x 4-byte values per pixel
      // Integer fields (offsets 0-2)
      pixelU32[idx7 + 0] = 0;  // iter
      pixelU32[idx7 + 1] = 0;  // status (0 = computing)
      pixelU32[idx7 + 2] = 0;  // period
      // Float fields (offsets 3-6)
      pixelF32[idx7 + 3] = 0;  // zr
      pixelF32[idx7 + 4] = 0;  // zi
      pixelF32[idx7 + 5] = 0;  // base_r
      pixelF32[idx7 + 6] = 0;  // base_i
    }
    this.device.queue.writeBuffer(this.buffers.pixels, 0, pixelData);
 
    // Initialize active pixels list (all pixels start active)
    const activePixels = new Uint32Array(dimsArea);
    for (let i = 0; i < dimsArea; i++) {
      activePixels[i] = i;
    }
    this.device.queue.writeBuffer(this.buffers.activePixels, 0, activePixels);
  }
 
  createBindGroup() {
    // Consolidated 3-binding layout
    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.activePixels } }
      ],
      label: 'Mandelbrot bind group'
    });
  }
 
  async compute() {
    // Prevent concurrent compute() calls
    if (this.isComputing) {
      return;
    }
    this.isComputing = true;
    try {
    const dimsArea = this.config.dimsWidth * this.config.dimsHeight;
    const workgroupSize = 64;
    const BYTES_PER_PIXEL = 28;  // 7 x 4-byte values per pixel
 
    // Prepare parameters for GPU
    const re_double = qdToNumber(this.re);
    const im_double = qdToNumber(this.im);
    const pixel_size = this.size;
 
    // Initialize CPU-side status tracking if needed
    if (!this.cpuStatus) {
      this.cpuStatus = new Uint32Array(dimsArea).fill(0);  // 0 = computing
    }
 
    // Build sparse active pixel list (only pixels still computing)
    const activePixels = [];
    for (let i = 0; i < dimsArea; i++) {
      if (this.cpuStatus[i] === 0) {
        activePixels.push(i);
      }
    }
 
    const activeCount = activePixels.length;
 
    if (activeCount === 0) {
      this.un = 0;
      return;
    }
 
    // Dynamic batch sizing: scale iterations inversely with active pixels
    const targetWork = 333337;  // Prime, reduced for better responsiveness
    // Check for step mode debug flag 's'
    const stepMode = hasDebugFlag(this.config, 's');
    let iterationsPerBatch = stepMode ? 1 : Math.floor(targetWork / Math.max(activeCount, 1));
    // Clamp to reasonable bounds (min 17) unless in step mode
    if (!stepMode) {
      iterationsPerBatch = Math.max(17, iterationsPerBatch);
    }
 
    // Update effort for scheduler (reflects actual iterations per call)
    this.effort = iterationsPerBatch;
 
    // Upload active pixel list to GPU
    const activePixelsData = new Uint32Array(activePixels);
    this.device.queue.writeBuffer(this.buffers.activePixels, 0, activePixelsData);
 
    // 2D workgroup dispatch
    const numWorkgroups = Math.ceil(activeCount / workgroupSize);
    const workgroupsX = Math.ceil(Math.sqrt(numWorkgroups));
    const workgroupsY = Math.ceil(numWorkgroups / workgroupsX);
 
    // Precompute Fibonacci checkpoint offsets for this batch
    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, 8);
 
    // Upload parameters to uniform buffer
    const paramsBuffer = new ArrayBuffer(128);
    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] = activeCount;
    paramsF32[8] = this.epsilon;
    paramsF32[9] = this.epsilon2;
    paramsU32[10] = this.config.exponent;
    paramsU32[11] = workgroupsX * workgroupSize;  // Total threads in X dimension
    paramsU32[12] = bufferIter;  // Starting iteration
    paramsU32[13] = checkpointCount;  // Number of checkpoints in this batch
 
    // Pack all 8 checkpoint offsets (fill unused slots with 0)
    for (let i = 0; i < 8; i++) {
      paramsU32[14 + i] = i < checkpointCount ? checkpointOffsets[i] : 0;
    }
 
    this.device.queue.writeBuffer(this.buffers.params, 0, paramsBuffer);
 
    // Create command encoder
    const commandEncoder = this.device.createCommandEncoder({
      label: 'Mandelbrot compute encoder'
    });
 
    // Compute pass
    const passEncoder = commandEncoder.beginComputePass({
      label: 'Mandelbrot compute pass'
    });
 
    passEncoder.setPipeline(this.pipeline);
    passEncoder.setBindGroup(0, this.bindGroup);
    passEncoder.dispatchWorkgroups(workgroupsX, workgroupsY);  // 2D dispatch
    passEncoder.end();
 
    // Copy consolidated pixel buffer to staging
    commandEncoder.copyBufferToBuffer(
      this.buffers.pixels, 0, this.buffers.stagingPixels, 0, dimsArea * BYTES_PER_PIXEL);
 
    // Submit compute + buffer copy in single batch
    this.device.queue.submit([commandEncoder.finish()]);
    await this.device.queue.onSubmittedWorkDone();
 
    // Update iteration counter (before processing results, like CPU implementations)
    this.it += iterationsPerBatch;
 
    // Read consolidated pixel state buffer
    await this.buffers.stagingPixels.mapAsync(GPUMapMode.READ);
    const pixelData = new ArrayBuffer(dimsArea * BYTES_PER_PIXEL);
    const srcData = this.buffers.stagingPixels.getMappedRange();
    new Uint8Array(pixelData).set(new Uint8Array(srcData));
    this.buffers.stagingPixels.unmap();
 
    // Create typed array views for reading pixel state
    const pixelU32 = new Uint32Array(pixelData);
    const pixelF32 = new Float32Array(pixelData);
 
    // Initialize lastReportedIters if needed
    if (!this.lastReportedIters) {
      this.lastReportedIters = new Uint32Array(dimsArea).fill(0);
    }
 
    // Find pixels that NEWLY diverged or converged this batch
    const pixelsByIteration = new Map(); // For diverged: iter -> [indices]
    const convergedByIteration = new Map(); // For converged: iter -> [{index, z, p}]
 
    for (const i of activePixels) {
      const idx7 = i * 7;
      const iters = pixelU32[idx7 + 0];   // iter
      const status = pixelU32[idx7 + 1];  // status
      const period = pixelU32[idx7 + 2];  // period
      const zr = pixelF32[idx7 + 3];      // zr
      const zi = pixelF32[idx7 + 4];      // zi
      const lastIters = this.lastReportedIters[i];
 
      // Update CPU-side status tracking
      this.cpuStatus[i] = status;
 
      if (status === 1) {
        // Diverged - newly diverged in this batch?
        if (lastIters === 0 || iters !== lastIters) {
          this.nn[i] = iters;
          this.pp[i] = 1;
 
          if (!pixelsByIteration.has(iters)) {
            pixelsByIteration.set(iters, []);
          }
          pixelsByIteration.get(iters).push(i);
          this.lastReportedIters[i] = iters;
 
          // Decrement ch if this pixel was in the spike
          if (this.inSpike && this.inSpike[i] && this.ch > 0) {
            this.ch -= 1;
          }
        }
      } else if (status === 2) {
        // Converged - newly converged in this batch?
        if (lastIters === 0 || iters !== lastIters) {
          this.nn[i] = -iters;  // Negative iteration for converged pixels
 
          // Add 1 because GPU shader increments iter before setting checkpoint,
          // so period value is 1 less than what CPU board would store
          this.pp[i] = period + 1;
 
          if (!convergedByIteration.has(iters)) {
            convergedByIteration.set(iters, []);
          }
          convergedByIteration.get(iters).push({
            index: i,
            z: [zr, zi],  // float64 pair
            p: this.pp[i]
          });
          this.lastReportedIters[i] = iters;
 
          // Decrement ch if this pixel was in the spike
          if (this.inSpike && this.inSpike[i] && this.ch > 0) {
            this.ch -= 1;
          }
        }
      }
    }
 
    // Count total finished pixels across entire grid (for statistics)
    let totalDiverged = 0;
    let totalConverged = 0;
    let stillComputing = 0;
    for (let i = 0; i < dimsArea; i++) {
      const status = this.cpuStatus[i];
      if (status === 1) totalDiverged++;
      else if (status === 2) totalConverged++;
      else stillComputing++;
    }
 
    // Create change objects for newly diverged and converged pixels
    const allIterations = new Set([...pixelsByIteration.keys(),
                                    ...convergedByIteration.keys()]);
    const sortedIterations = Array.from(allIterations).sort((a, b) => a - b);
    let totalChanges = 0;
 
    for (const iter of sortedIterations) {
      const divergedIndices = pixelsByIteration.get(iter) || [];
      const convergedData = convergedByIteration.get(iter) || [];
 
      this.changeList.push({
        iter: iter,
        nn: divergedIndices,
        vv: convergedData
      });
      totalChanges += divergedIndices.length + convergedData.length;
    }
 
    // Update board statistics
    this.di = totalDiverged;
    this.un = stillComputing;
    this.updateSize = totalChanges;
 
    } catch (error) {
      console.error(`GpuBoard.compute() ERROR:`, error);
    } finally {
      this.isComputing = false;
    }
  }
 
  async serialize() {
    // 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 (like CPU boards)
    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,
      // CPU-side state
      cpuStatus: this.cpuStatus ? Array.from(this.cpuStatus) : null,
      lastReportedIters: this.lastReportedIters ? Array.from(this.lastReportedIters) : null,
      effort: this.effort,
      // Completed pixels (sparse format)
      completedIndexes,
      completedNn,
    };
  }
 
  static async fromSerializedAsync(serialized) {
    const board = new GpuBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    // Wait for GPU initialization
    await board.ensureGPUReady();
 
    // Restore GPU pixel buffer
    if (serialized.gpuPixelData && board.isGPUReady) {
      const pixelData = new Uint8Array(serialized.gpuPixelData).buffer;
      await board.writePixelBuffer(pixelData);
    }
 
    // Restore CPU-side state
    if (serialized.cpuStatus) {
      board.cpuStatus = new Uint32Array(serialized.cpuStatus);
    }
    if (serialized.lastReportedIters) {
      board.lastReportedIters = new Uint32Array(serialized.lastReportedIters);
    }
    board.effort = serialized.effort || 1;
 
    // Restore Board state
    board.it = serialized.it;
    board.un = serialized.un;
    board.di = serialized.di;
    board.ch = serialized.ch || 0;
 
    // Restore nn array from base serialization
    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;
  }
 
  static fromSerialized(serialized) {
    // For backwards compatibility with sync Board.fromSerialized
    // GPU boards require async initialization, so this returns a board
    // that will continue initializing in the background
    const board = new GpuBoard(
      serialized.k,
      serialized.sizesQD[0],
      serialized.sizesQD[1],
      serialized.sizesQD[2],
      serialized.config,
      serialized.id
    );
 
    // Schedule async restoration
    board.gpuInitPromise = board.gpuInitPromise.then(async () => {
      // Restore GPU pixel buffer
      if (serialized.gpuPixelData && board.isGPUReady) {
        const pixelData = new Uint8Array(serialized.gpuPixelData).buffer;
        await board.writePixelBuffer(pixelData);
      }
 
      // Restore CPU-side state
      if (serialized.cpuStatus) {
        board.cpuStatus = new Uint32Array(serialized.cpuStatus);
      }
      if (serialized.lastReportedIters) {
        board.lastReportedIters = new Uint32Array(serialized.lastReportedIters);
      }
      board.effort = serialized.effort || 1;
 
      // Restore Board state
      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];
        }
      }
    });
 
    return board;
  }
}
 
// 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(GpuBaseBoard) {
  static BYTES_PER_PIXEL = 56;  // 6 u32 + 8 f32 (unified PixelState struct)
 
  constructor(k, size, re, im, config, id) {
    super(k, size, re, im, config, id);
 
    this.effort = 2;  // Same as DDZhuoranBoard
 
    // 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);
 
    // 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, toDD(yFrac)[0], toDD(yFrac)[1], 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, toDD(xFrac)[0], toDD(xFrac)[1], 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;
 
    // 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: 6 u32 + 8 f32 = 56 bytes per pixel
    const pixelBufferSize = dimsArea * 56;
 
    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.`);
    }
 
    // Single unified pixel state buffer (PixelState struct: 6 u32 + 8 f32 = 56 bytes per pixel)
    // Layout per pixel: [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: 128,
      usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
      label: 'Params buffer'
    });
 
    // Initialize pixel state buffer using overlapping typed array views
    // ArrayBuffer holds 56 bytes per pixel (14 x 4 bytes)
    const pixelData = new ArrayBuffer(pixelBufferSize);
    const pixelU32 = new Uint32Array(pixelData);   // For u32 fields (indices 0-5)
    const pixelF32 = new Float32Array(pixelData);  // For f32 fields (indices 6-13)
 
    for (let i = 0; i < dimsArea; i++) {
      const idx14 = i * 14;  // 14 x 4-byte values per pixel
      // Integer fields (offsets 0-5)
      pixelU32[idx14 + 0] = 1;                      // iter (start at 1, z=c is iteration 1)
      pixelU32[idx14 + 1] = 0;                      // status (0 = computing)
      pixelU32[idx14 + 2] = 0;                      // period
      pixelU32[idx14 + 3] = this.refIter[i];       // ref_iter
      pixelU32[idx14 + 4] = 0xFFFFFFFF;            // ckpt_refidx (sentinel)
      pixelU32[idx14 + 5] = 0xFFFFFFFF;            // pending_refidx (sentinel)
      // Float fields (offsets 6-13)
      pixelF32[idx14 + 6] = this.dz[i * 2];        // dzr
      pixelF32[idx14 + 7] = this.dz[i * 2 + 1];    // dzi
      pixelF32[idx14 + 8] = 0;                      // bbr
      pixelF32[idx14 + 9] = 0;                      // bbi
      pixelF32[idx14 + 10] = 0;                     // ckpt_bbr
      pixelF32[idx14 + 11] = 0;                     // ckpt_bbi
      pixelF32[idx14 + 12] = this.dc[i * 2];       // dcr
      pixelF32[idx14 + 13] = this.dc[i * 2 + 1];   // dci
    }
 
    // 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
  }
 
  createBindGroup() {
    // Unified 3-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 } }
      ],
      label: 'Perturbation bind group'
    });
  }
 
  // 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,
        ckpt0: u32,
        ckpt1: u32,
        ckpt2: u32,
        ckpt3: u32,
        ckpt4: u32,
        ckpt5: u32,
        ckpt6: u32,
        ckpt7: u32,
        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
        _padding: u32,          // Alignment padding
        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: 6 u32 + 8 f32 = 56 bytes
      // Layout (u32 view):
      //   [0] iter: u32
      //   [1] status: u32
      //   [2] period: u32
      //   [3] ref_iter: u32
      //   [4] ckpt_refidx: u32
      //   [5] pending_refidx: u32
      //   [6] dzr: f32
      //   [7] dzi: f32
      //   [8] bbr: f32
      //   [9] bbi: f32
      //   [10] ckpt_bbr: f32
      //   [11] ckpt_bbi: f32
      //   [12] dcr: f32
      //   [13] dci: f32
      struct PixelState {
        // Integer fields (6 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,
      }
 
      // 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,
      }
 
      @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>;
 
      // 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>) {
        // 2D dispatch: calculate linear index from 2D coordinates
        let index = global_id.y * params.workgroups_x + global_id.x;
        let dimsArea = params.dims_width * params.dims_height;
        if (index >= dimsArea) { 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;
 
        // Convergence thresholds scale with pixel size for deep zooms
        // GPU uses float32 precision, so thresholds must be larger than CPU's float64
        let epsilon = min(1e-7, params.pixel_size / 10.0);   // Final convergence threshold
        let epsilon2 = min(1e-5, params.pixel_size * 10.0);  // Getting close threshold
 
        // 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;
            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; }
              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;
                  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;
                    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;
                      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;
      }
    `;
 
    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() {
    // Prevent concurrent compute() calls
    if (this.isComputing) {
      return;
    }
    this.isComputing = true;
    const dimsArea = this.config.dimsWidth * this.config.dimsHeight;
 
    try {
    // Calculate batch size first (needed to determine reference orbit buffer)
    const pixelsToIterate = this.un + this.ch;
    // Check for step mode debug flag 's'
    const stepMode = hasDebugFlag(this.config, 's');
    const iterationsPerBatch = stepMode ? 1 : Math.max(17,
      Math.floor(333337 / Math.max(pixelsToIterate, 1)));
 
    // Update effort for scheduler (reflects actual iterations per call)
    this.effort = iterationsPerBatch;
 
    // Step 1: Extend reference orbit on CPU as needed
    // Extend to what pixels need (this.it) plus enough buffer for next batch
    const THREADING_CAPACITY = 1048576;  // 2^20
    const currentNeed = this.it + iterationsPerBatch;
    // Also allow growth for thread-following, but cap to avoid waste
    // Use proportional buffer (10%) for long periods, or fixed 10k buffer for short periods
    const maxAllowedGrowth = Math.max(currentNeed + 10000, Math.round(currentNeed * 1.1));
    const threadingBuffer = Math.min(this.refIterations + 100, maxAllowedGrowth);
    // Cap at threading capacity - don't extend beyond this point
    const targetRefIterations = Math.min(
      Math.max(currentNeed, threadingBuffer),
      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 2: Upload iteration state to GPU (INCREMENTAL UPLOADS)
    // IterState struct: 5 f32 per iteration
    // (ref_re, ref_im, thread_next, thread_delta_re, thread_delta_im)
    const totalIters = this.refIterations + 1;  // Include iteration 0
    const BYTES_PER_ITER = 20;  // 5 f32 = 20 bytes
 
    // 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) {
      // Only resize if we can actually allocate a larger buffer (not already at max cap)
      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;  // Reset after resize
      this.createBindGroup();
    }
 
    // INCREMENTAL UPLOAD: Only upload new iteration data
    if (this.lastUploadedIterLength < this.refIterations) {
      const startIdx = Math.max(0, this.lastUploadedIterLength + 1);
      // Cap to buffer capacity
      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);  // 5 floats per iteration
 
        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;
          // Reference orbit (DD precision -> f32)
          iterF32[base + 0] = ref[0] + ref[1];      // ref_re
          iterF32[base + 1] = ref[2] + ref[3];      // ref_im
          // Threading data
          if (!thread) {
            iterF32[base + 2] = -1;   // thread_next (-1 = no thread)
            iterF32[base + 3] = 0;    // thread_delta_re
            iterF32[base + 4] = 0;    // thread_delta_im
          } 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 3: Check if all done
    if (this.un === 0) {
      this.isComputing = false;
      return;  // All pixels finished
    }
 
    // Step 4: Set up parameters
    // Batch size already calculated above (before reference orbit extension)
    const pixelSize = this.pixelSize;
 
    // Step 4a: Precompute checkpoint offsets for this batch using fibonacciPeriod
    const checkpointOffsets = [];
    const bufferIter = this.it;
    for (let i = 0; i < iterationsPerBatch; i++) {
      const globalIter = bufferIter + i;
      if (fibonacciPeriod(globalIter) === 1) {
        checkpointOffsets.push(i);
      }
    }
 
    // Cap at 8 checkpoints (hardware limit based on uniform buffer fields)
    // Note: checkpointCount can be 0 if no checkpoints in this batch
    // That's OK - we'll keep comparing to the last checkpoint from a previous batch
    const checkpointCount = Math.min(checkpointOffsets.length, 8);
 
    // Step 5: Dispatch GPU compute - process all pixels
    const workgroupSize = 64;
    const numWorkgroups = Math.ceil(dimsArea / workgroupSize);
 
    // 2D workgroup dispatch
    const workgroupsX = Math.ceil(Math.sqrt(numWorkgroups));
    const workgroupsY = Math.ceil(numWorkgroups / workgroupsX);
 
    // Pack params: dims_width, dims_height, iterations_per_batch, active_count,
    // ref_orbit_length, exponent, workgroups_x, start_iter, checkpoint_count,
    // ckpt0-7, loop params, pixel_size, aspect_ratio, loop deltas
    const paramsBuffer = new ArrayBuffer(128);  // Extended for new layout
    const paramsU32 = new Uint32Array(paramsBuffer);
    const paramsF32 = new Float32Array(paramsBuffer);
    paramsU32[0] = this.config.dimsWidth;
    paramsU32[1] = this.config.dimsHeight;
    paramsU32[2] = iterationsPerBatch;
    paramsU32[3] = dimsArea;  // active_count: Process all pixels, skip finished ones in shader
    paramsU32[4] = this.refIterations + 1;  // ref_orbit_length: includes iteration 0
    paramsU32[5] = this.config.exponent || 2;
    paramsU32[6] = workgroupsX * workgroupSize;  // Total threads in X dimension
    // start_iter: Starting iteration (what's in the buffer before iter++)
    paramsU32[7] = bufferIter;
    paramsU32[8] = checkpointCount;  // Number of checkpoints in this batch
 
    // Pack all 8 checkpoint offsets (fill unused slots with 0)
    for (let i = 0; i < 8; i++) {
      paramsU32[9 + i] = i < checkpointCount ? checkpointOffsets[i] : 0;
    }
 
    // Pack reference orbit loop parameters
    const loop = this.refOrbitLoop || { enabled: false };
    paramsU32[17] = loop.enabled ? 1 : 0;
    paramsU32[18] = loop.threshold || 0;
    paramsU32[19] = loop.jumpAmount || 0;
    paramsU32[20] = 0;  // padding
    paramsF32[21] = pixelSize;
    paramsF32[22] = this.config.aspectRatio;
    paramsF32[23] = loop.deltaR || 0;
    paramsF32[24] = loop.deltaI || 0;
 
    this.device.queue.writeBuffer(this.buffers.params, 0, paramsBuffer);
 
    const commandEncoder = this.device.createCommandEncoder(
      { label: 'Perturbation compute' });
    const passEncoder = commandEncoder.beginComputePass({ label: 'Perturbation pass' });
    passEncoder.setPipeline(this.pipeline);
    passEncoder.setBindGroup(0, this.bindGroup);
    passEncoder.dispatchWorkgroups(workgroupsX, workgroupsY);  // 2D dispatch
    passEncoder.end();
 
    this.device.queue.submit([commandEncoder.finish()]);
 
    // Step 6: Read back results (unified PixelState buffer)
    await this.device.queue.onSubmittedWorkDone();
 
    // Read unified pixel buffer and create overlapping views
    // PixelState struct: 6 u32 + 8 f32 = 14 x 4-byte values per pixel
    const pixelBuffer = await this.readBuffer(this.buffers.pixels, Uint32Array);
    const pixelU32 = pixelBuffer;  // Already Uint32Array for u32 fields
    const pixelF32 = new Float32Array(pixelBuffer.buffer);  // Overlapping view for f32 fields
 
    // Update global iteration counter (before processing results, like CPU implementations)
    this.it += iterationsPerBatch;
 
    // PixelState struct offsets (14 values per pixel, matching shader struct layout)
    const INT_ITER = 0, INT_STATUS = 1, INT_PERIOD = 2, INT_REF_ITER = 3;
    const FLOAT_DZR = 6, FLOAT_DZI = 7;  // f32 fields start at offset 6
 
    // Step 7: Update board state
    const pixelsByIteration = new Map();  // Group diverged pixels by their exact iteration
    const convergedByIteration = new Map();  // Group converged pixels by their exact iteration
    let hasConverged = false;
 
    // First pass: check for diverged pixels and count converged
    let divergedCount = 0;
    let convergedCount = 0;
 
    for (let i = 0; i < dimsArea; i++) {
      const idx14 = i * 14;  // 14 values per pixel in unified struct
      const status = pixelU32[idx14 + INT_STATUS];
      const period = pixelU32[idx14 + INT_PERIOD];
 
      if (this.nn[i] !== 0) continue;  // Already finished
 
      if (status === 1) {
        // Newly diverged
        const iters = pixelU32[idx14 + INT_ITER];
        divergedCount++;
        this.nn[i] = iters;
        this.pp[i] = period;
 
        if (!pixelsByIteration.has(iters)) {
          pixelsByIteration.set(iters, []);
        }
        pixelsByIteration.get(iters).push(i);
        this.di++;
        this.un--;
 
        // Decrement ch if this pixel was in the spike
        if (this.inSpike && this.inSpike[i] && this.ch > 0) {
          this.ch -= 1;
        }
      } else if (status === 2) {
        convergedCount++;
        hasConverged = true;
      }
    }
 
    // Second pass: process converged pixels (f32 fields already available in pixelF32)
    if (hasConverged) {
      for (let i = 0; i < dimsArea; i++) {
        const idx14 = i * 14;
        const status = pixelU32[idx14 + INT_STATUS];
        const period = pixelU32[idx14 + INT_PERIOD];
 
        if (this.nn[i]) continue;  // Already finished
 
        if (status === 2) {
          // Newly converged
          const iters = pixelU32[idx14 + INT_ITER];
          this.nn[i] = -iters;
 
          // period from shader is pp (iteration when first within epsilon2)
          // Store pp - 1 because fibonacciPeriod() adds 1 in its calculation
          this.pp[i] = period - 1;
 
          // Get converged position: refOrbit[refIter+1] + dz
          // dz corresponds to refIter+1 because we computed new dz but didn't increment ref_iter
          const refIter = pixelU32[idx14 + INT_REF_ITER];
          const nextRefIter = refIter + 1;
          const dzr = pixelF32[idx14 + FLOAT_DZR];
          const dzi = pixelF32[idx14 + FLOAT_DZI];
 
          const ref = this.refOrbit[Math.min(nextRefIter, this.refOrbit.length - 1)];
          // Compute z = ref + dz with proper DD addition
          const zr = toDDAdd([ref[0], ref[1]], dzr);
          const zi = toDDAdd([ref[2], ref[3]], dzi);
          if (!convergedByIteration.has(iters)) {
            convergedByIteration.set(iters, []);
          }
          convergedByIteration.get(iters).push({
            index: i,
            z: [zr[0], zr[1], zi[0], zi[1]],  // DDc format
            p: this.pp[i]  // Raw pp value (UI will call fibonacciPeriod to calculate period)
          });
          this.un--;
 
          // Decrement ch if this pixel was in the spike
          if (this.inSpike && this.inSpike[i] && this.ch > 0) {
            this.ch -= 1;
          }
        }
      }
    }
 
    // NOTE: When refOrbitEscaped is true, we do NOT mark remaining pixels as diverged.
    // The GPU shader will continue iterating those pixels individually, and they will
    // either diverge naturally or continue until maxiter. This matches the behavior
    // of DDZhuoranBoard which rebases pixels when the reference orbit escapes.
 
    // Create change objects grouped by iteration
    const allIterations = new Set([...pixelsByIteration.keys(),
                                    ...convergedByIteration.keys()]);
    const sortedIterations = Array.from(allIterations).sort((a, b) => a - b);
 
    for (const iter of sortedIterations) {
      const divergedIndices = pixelsByIteration.get(iter) || [];
      const convergedData = convergedByIteration.get(iter) || [];
 
      if (divergedIndices.length > 0 || convergedData.length > 0) {
        this.queueChanges({
          iter: iter,
          nn: divergedIndices,
          vv: convergedData
        });
      }
    }
 
    } catch (error) {
      console.error(`GpuZhuoranBoard.compute() ERROR:`, error);
    } finally {
      this.isComputing = false;
    }
  }
 
  async serialize() {
    // 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,
    };
  }
 
  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 () => {
      // 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;
 
      // 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 AdaptiveGpuBoard extends QDReferenceOrbitMixin(GpuBaseBoard) {
  static BYTES_PER_PIXEL = 60;  // 15 × 4 bytes (7 i32 + 8 f32)
 
  constructor(k, size, re, im, config, id) {
    super(k, size, re, im, config, id);
 
    this.effort = 2;  // Same as DDZhuoranBoard
 
    // 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);
 
    // Start GPU initialization (async)
    this.gpuInitPromise = this.initGPU();
  }
 
  // 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;
 
    // Consolidated 3-binding layout:
    // 0: params (uniform)
    // 1: pixels (PixelState): 7 i32 + 8 f32 = 60 bytes per pixel
    // 2: iters (IterState): 5 f32 = 20 bytes per iteration (refOrbit + threading combined)
    const PIXEL_BYTES = 60;  // 15 × 4 bytes
    const ITER_BYTES = 20;   // 5 × 4 bytes
 
    this.buffers = {
      params: this.device.createBuffer({
        size: 128,
        usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
      }),
      pixels: this.device.createBuffer({
        size: dimsArea * PIXEL_BYTES,
        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: [iter, scale, status, period, ref_iter, ckpt_refidx, pending_refidx,
    //                     dzr, dzi, bbr, bbi, ckpt_bbr, ckpt_bbi, dcr, dci]
    const pixelBuffer = new ArrayBuffer(dimsArea * PIXEL_BYTES);
    const pixelsI32 = new Int32Array(pixelBuffer);
    const pixelsF32 = new Float32Array(pixelBuffer);
 
    for (let i = 0; i < dimsArea; i++) {
      const idx = i * 15;  // 15 fields per pixel
      // Integer fields (indices 0-6)
      pixelsI32[idx + 0] = 1;                    // iter starts at 1
      pixelsI32[idx + 1] = this.pixelScale[i];  // scale from initPixels
      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
    }
    this.device.queue.writeBuffer(this.buffers.pixels, 0, pixelBuffer);
 
    this.lastUploadedItersLength = -1;
  }
 
  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 } }
      ]
    });
  }
 
  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,
        ckpt0: u32,
        ckpt1: u32,
        ckpt2: u32,
        ckpt3: u32,
        ckpt4: u32,
        ckpt5: u32,
        ckpt6: u32,
        ckpt7: u32,
        loop_enabled: u32,
        loop_threshold: u32,
        loop_jump: u32,
        initial_scale: i32,    // Global scale for dc, bb, threaded_delta
        pixel_size: f32,
        aspect_ratio: f32,
        loop_delta_r: f32,
        loop_delta_i: f32,
      }
 
      // Per-pixel state: 7 i32 + 8 f32 = 60 bytes
      // Layout (i32/u32 view):
      //   [0] iter: i32
      //   [1] scale: 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
      struct PixelState {
        // Integer fields (7 i32)
        iter: i32,
        scale: 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,
      }
 
      // 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,
      }
 
      @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>;
 
      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>) {
        let index = global_id.y * params.workgroups_x + global_id.x;
        let dimsArea = params.dims_width * params.dims_height;
        if (index >= dimsArea) { 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;
 
        // Convergence thresholds - scaled by initialScale for comparison
        let epsilon_actual = min(1e-7, params.pixel_size / 10.0);
        let epsilon2_actual = min(1e-5, params.pixel_size * 10.0);
        // Convert to initialScale for scaled comparisons
        let epsilon = ldexp(epsilon_actual, -params.initial_scale);
        let epsilon2 = ldexp(epsilon2_actual, -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);
            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; }
              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) {
            const THREADING_CAPACITY = 1048576u;
 
            if (ref_iter >= THREADING_CAPACITY) {
              // Fallback: compare absolute positions (in actual coords)
              let z_total_r = zr;
              let z_total_i = zi;
              let bbr_actual = ldexp(checkpoint_bb_r, params.initial_scale);
              let bbi_actual = ldexp(checkpoint_bb_i, params.initial_scale);
              let ref_ckpt = getRefOrbit(checkpoint_refidx);
              let z_checkpoint_r = ref_ckpt.x + bbr_actual;
              let z_checkpoint_i = ref_ckpt.y + bbi_actual;
 
              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_actual) {
                if (pp == 0u) { pp = iter; }
                if (db <= epsilon_actual) {
                  pixels[index].status = 2;
                  pixels[index].period = i32(pp);
                  break;
                }
              }
            } else {
              // 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);
                    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);
                      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;
      }
    `;
 
    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(`AdaptiveGpuBoard 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() {
    // Prevent concurrent compute() calls
    if (this.isComputing) return;
    this.isComputing = true;
 
    // Wait for async GPU initialization to complete
    await this.gpuInitPromise;
 
    // GPU required - if device unavailable, computation cannot proceed
    if (!this.device) {
      console.warn('AdaptiveGpuBoard: GPU device not available, cannot compute');
      this.isComputing = false;
      return;
    }
 
    try {
      const dimsArea = this.config.dimsWidth * this.config.dimsHeight;
 
      // Calculate batch size
      const pixelsToIterate = this.un + this.ch;
      // Check for step mode debug flag 's'
      const stepMode = hasDebugFlag(this.config, 's');
      const iterationsPerBatch = stepMode ? 1 : Math.max(17,
        Math.floor(333337 / Math.max(pixelsToIterate, 1)));
      this.effort = iterationsPerBatch;
 
      // Extend reference orbit on CPU as needed
      const THREADING_CAPACITY = 1048576;
      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();
      }
 
      // Upload combined ref orbit + threading data
      await this.uploadIters();
 
      if (this.un === 0) {
        this.isComputing = false;
        return;
      }
 
      // Compute checkpoint offsets for convergence detection (enabled at all zoom levels)
      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, 8);
 
      // Get scalar size for pixelSize computation
      const size_scalar = this.size;
      const pixelSize = size_scalar / this.config.dimsWidth;
 
      const workgroupSize = 64;
      const numWorkgroups = Math.ceil(dimsArea / workgroupSize);
      const workgroupsX = Math.ceil(Math.sqrt(numWorkgroups));
      const workgroupsY = Math.ceil(numWorkgroups / workgroupsX);
 
      // Pack params
      const paramsBuffer = new ArrayBuffer(128);
      const paramsU32 = new Uint32Array(paramsBuffer);
      const paramsI32 = new Int32Array(paramsBuffer);
      const paramsF32 = new Float32Array(paramsBuffer);
 
      paramsU32[0] = this.config.dimsWidth;
      paramsU32[1] = this.config.dimsHeight;
      paramsU32[2] = iterationsPerBatch;
      paramsU32[3] = dimsArea;
      paramsU32[4] = this.refIterations + 1;
      paramsU32[5] = this.config.exponent || 2;
      paramsU32[6] = workgroupsX * workgroupSize;
      paramsU32[7] = bufferIter;
      paramsU32[8] = checkpointCount;
 
      for (let i = 0; i < 8; i++) {
        paramsU32[9 + i] = i < checkpointCount ? checkpointOffsets[i] : 0;
      }
 
      const loop = this.refOrbitLoop || { enabled: false };
      paramsU32[17] = loop.enabled ? 1 : 0;
      paramsU32[18] = loop.threshold || 0;
      paramsU32[19] = loop.jumpAmount || 0;
      paramsI32[20] = this.initialScale;  // initial_scale for dc term in AdaptiveGpuBoard
      paramsF32[21] = pixelSize;
      paramsF32[22] = this.config.aspectRatio;
      paramsF32[23] = loop.deltaR || 0;
      paramsF32[24] = loop.deltaI || 0;
 
      this.device.queue.writeBuffer(this.buffers.params, 0, paramsBuffer);
 
      const commandEncoder = this.device.createCommandEncoder(
        { label: 'Adaptive perturbation compute' });
      const passEncoder = commandEncoder.beginComputePass(
        { label: 'Adaptive perturbation pass' });
      passEncoder.setPipeline(this.pipeline);
      passEncoder.setBindGroup(0, this.bindGroup);
      passEncoder.dispatchWorkgroups(workgroupsX, workgroupsY);
      passEncoder.end();
 
      this.device.queue.submit([commandEncoder.finish()]);
      await this.device.queue.onSubmittedWorkDone();
 
      this.it += iterationsPerBatch;
 
      // Read consolidated pixels buffer
      // PixelState layout (15 fields × 4 bytes = 60 bytes/pixel):
      //   Int32 (indices 0-6): iter, scale, status, period, ref_iter, ckpt_refidx, pending_refidx
      //   Float32 (indices 7-14): dzr, dzi, bbr, bbi, ckpt_bbr, ckpt_bbi, dcr, dci
      const pixelsU32 = await this.readBuffer(this.buffers.pixels, Uint32Array);
      const pixelsI32 = new Int32Array(pixelsU32.buffer);
      const pixelsF32 = new Float32Array(pixelsU32.buffer);
 
      // Process GPU results
      const pixelsByIteration = new Map();
      const convergedByIteration = new Map();
      let hasConverged = false;
 
      // PixelState field indices (in units of 4 bytes)
      const STRIDE = 15;  // 15 fields per pixel
      const P_ITER = 0, P_SCALE = 1, P_STATUS = 2, P_PERIOD = 3, P_REF_ITER = 4;
      const P_DZR = 7, P_DZI = 8;
 
      for (let i = 0; i < dimsArea; i++) {
        const idx = i * STRIDE;
        const status = pixelsI32[idx + P_STATUS];
        const period = pixelsI32[idx + P_PERIOD];
        if (this.nn[i] !== 0) continue;
        if (status === 1) {
          const iters = pixelsI32[idx + P_ITER];
          this.nn[i] = iters;
          this.pp[i] = period;
          if (!pixelsByIteration.has(iters)) pixelsByIteration.set(iters, []);
          pixelsByIteration.get(iters).push(i);
          this.di++;
          this.un--;
          if (this.inSpike && this.inSpike[i] && this.ch > 0) this.ch -= 1;
        } else if (status === 2) {
          hasConverged = true;
        }
      }
 
      if (hasConverged) {
        for (let i = 0; i < dimsArea; i++) {
          const idx = i * STRIDE;
          const status = pixelsI32[idx + P_STATUS];
          const period = pixelsI32[idx + P_PERIOD];
          if (this.nn[i]) continue;
          if (status === 2) {
            const iters = pixelsI32[idx + P_ITER];
            this.nn[i] = -iters;
            this.pp[i] = period - 1;
            const refIter = pixelsI32[idx + P_REF_ITER];
            // AdaptiveGpuBoard stores dz BEFORE iteration (break before iter step),
            // so dz corresponds to refIter, not refIter+1
            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)];
            // Compute z = ref + dz in full QD precision (8 elements for complex)
            const zrQD = toQDAdd([ref[0], ref[1], ref[2], ref[3]], [dzr, 0, 0, 0]);
            const ziQD = toQDAdd([ref[4], ref[5], ref[6], ref[7]], [dzi, 0, 0, 0]);
            if (!convergedByIteration.has(iters)) convergedByIteration.set(iters, []);
            convergedByIteration.get(iters).push(
              { index: i, z: [...zrQD, ...ziQD], p: this.pp[i] });
            this.un--;
            if (this.inSpike && this.inSpike[i] && this.ch > 0) this.ch -= 1;
          }
        }
      }
 
      const allIterations = new Set([...pixelsByIteration.keys(),
                                      ...convergedByIteration.keys()]);
      for (const iter of Array.from(allIterations).sort((a, b) => a - b)) {
        const divergedIndices = pixelsByIteration.get(iter) || [];
        const convergedData = convergedByIteration.get(iter) || [];
        if (divergedIndices.length > 0 || convergedData.length > 0) {
          this.queueChanges({ iter: iter, nn: divergedIndices, vv: convergedData });
        }
      }
 
    } catch (error) {
      console.error('AdaptiveGpuBoard.compute() ERROR:',
        error?.message || error, error?.stack || '');
    } finally {
      this.isComputing = false;
    }
  }
 
  async serialize() {
    // 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,
    };
  }
 
  static fromSerialized(serialized) {
    // GPU boards require async initialization, so this returns a board
    // that will continue initializing in the background
    const board = new AdaptiveGpuBoard(
      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 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;
 
      // 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;
  }
}
 
function workerLog(message) {
  self.postMessage({
    type: 'log',
    data: message
  });
}
 
const forcedBoardTypes = {
    'cpu': CpuBoard,
    'ddz': DDZhuoranBoard,
    'qdz': QDZhuoranBoard,
    'pert': PerturbationBoard,
    'qdpert': QDPerturbationBoard,
    'gpu': GpuBoard,
    'gpuz': GpuZhuoranBoard,
    'adaptive': AdaptiveGpuBoard,
    'qdcpu': QDCpuBoard
};
 
function selectBoardClass(pixelSize, dimsArea, gpuMaxBufferSize, forceBoard) {
  if (forceBoard) {
    if (forceBoard in forcedBoardTypes) {
      return forcedBoardTypes[forceBoard];
    } else {
      throw new Error(`Unknown board type: ${forcedBoardType}.` +
        ` Valid types: ${Object.keys(forcedBoardTypes).join(', ')}`);
    }
  }
 
  // First, try to select a GPU board.
  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): AdaptiveGpuBoard with QD-precision reference
    //   orbit and adaptive per-pixel scaling for correct escape detection
    const GpuBoardClass = (
        (pixelSize > 1e-7) ? GpuBoard :
        (pixelSize > 1e-30) ? GpuZhuoranBoard :
        AdaptiveGpuBoard);
    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), using CPU`);
    }
  }
 
  // If GPU is not available, select a CPU board
  const CpuBoardClass = (
      (pixelSize > 1e-15) ? CpuBoard :
      (pixelSize > 1e-30) ? PerturbationBoard :
      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;
  }
 
  async handleMessage(type, data) {
    switch (type) {
      case 'addBoard':
        this.workerNumber = data.workerNumber;
        const enableGPU = data.config.enableGPU;
        const webGPUAvailable = GpuBoard.isAvailable();
 
        // Query GPU limits once on first use
        if (enableGPU && webGPUAvailable && this.gpuMaxBufferSize === null) {
          this.gpuMaxBufferSize = await GpuBaseBoard.queryMaxBufferSize();
        }
 
        // 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
        let board = new BoardClass(data.k, size, data.reQD, data.imQD, data.config, data.id);
        this.boards.set(data.k, board);
 
      // 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))
          .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];
 
      // In step mode, handle stepping behavior
      if (this.stepMode) {
        if (this.stepsRequested > 0) {
          await board.iterate();
          this.stepsRequested--; // Consume one step
 
          // Call step callback if set
          if (this.stepCallback) {
            await this.stepCallback();
          }
        }
        // If stepsRequested is 0, don't do anything (wait for step() call)
      } else {
        // Normal mode - loop until workDone threshold
        // GPU boards handle batching internally, so only call iterate() once
        if (board.selfBatching) {
          await board.iterate();
        } else {
          for (let workDone = 0; workDone < 17377 && board.unfinished(); ) {
            workDone += board.un * board.effort;
            await board.iterate();
          }
        }
      }
      const now = (new Date()).getTime();
      if (this.focusedBoardK == board.k ?
          (board.updateSize >= 1429 || now - board.lastTime >= 100) :
          (board.updateSize >= 4673 || now - board.lastTime >= 500)) {
        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`);
        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
          }
        });
        board.lastTime = now;
        board.updateSize = 0;
        board.changeList = [];
        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.timer = setTimeout(() => this.iterateBoards(), 0);
  }
 
  // 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">
//////////// DD (double-double) precision utilities ///////////
 
function toDD(x) {
  return Array.isArray(x) ? x : [x, 0];
}
 
// Convert complex [real, imag] to DDc format [r_hi, r_lo, i_hi, i_lo]
function toDDc(c) {
  if (c.length == 4) { return c; }
  const r = toDD(c[0]);
  const j = toDD(c[1]);
  return [r[0], r[1], j[0], j[1]];
}
 
// Add two DD values, returning DD result
function toDDAdd(a, b) {
  const aa = toDD(a);
  const bb = toDD(b);
  const out = [0, 0];
  ArddAdd(out, 0, aa[0], aa[1], bb[0], bb[1]);
  return out;
}
 
// Convert various complex formats to QDc format (8 elements)
// Handles: float64 pair [r, i], DDc [r_hi, r_lo, i_hi, i_lo], QDc [r0..r3, i0..i3]
function toQDc(c) {
  if (!c) return null;
  if (c.length === 8) return c;  // Already QDc
  if (c.length === 4) {
    // DDc format: [r_hi, r_lo, i_hi, i_lo]
    return [c[0], c[1], 0, 0, c[2], c[3], 0, 0];
  }
  if (c.length === 2) {
    // Float64 pair: [real, imag]
    return [c[0], 0, 0, 0, c[1], 0, 0, 0];
  }
  return null;
}
 
// Oct helpers for both main thread and workers (via mathCode)
function toQD(x) {
  if (!Array.isArray(x)) return [x, 0, 0, 0];
  if (x.length >= 4) return [x[0], x[1], x[2], x[3]];
  if (x.length === 3) return [x[0], x[1], x[2], 0];
  return [x[0], x[1] || 0, 0, 0];
}
 
function toQDScale(a, s) {
  const o = toQD(a);
  return [o[0] * s, o[1] * s, o[2] * s, o[3] * s];
}
 
function toQDAdd(a, b) {
  const aa = toQD(a);
  const bb = toQD(b);
  const out = new Array(4);
  ArqdAdd(out, 0, aa[0], aa[1], aa[2], aa[3], bb[0], bb[1], bb[2], bb[3]);
  return out;
}
 
function toQDSub(a, b) {
  const bb = toQD(b);
  return toQDAdd(a, [-bb[0], -bb[1], -bb[2], -bb[3]]);
}
 
function toQDMul(a, b) {
  const aa = toQD(a);
  const bb = toQD(b);
  const out = new Array(4);
  ArqdMul(out, 0, aa[0], aa[1], aa[2], aa[3], bb[0], bb[1], bb[2], bb[3]);
  return out;
}
 
function toQDSquare(a) {
  const aa = toQD(a);
  const out = new Array(4);
  ArqdSquare(out, 0, aa[0], aa[1], aa[2], aa[3]);
  return out;
}
 
function toQDDouble(a) {
  const aa = toQD(a);
  return [aa[0] * 2, aa[1] * 2, aa[2] * 2, aa[3] * 2];
}
 
function qdToNumber(o) {
  const v = toQD(o);
  return v[0] + v[1] + v[2] + v[3];
}
 
function qdToDD(o) {
  const v = toQD(o);
  return [v[0], v[1] + v[2] + v[3]];
}
 
// Convert a float64 to its exact BigInt representation, scaled by 10^scale.
function float64ToBigIntScaled(x, scale) {
  if (x === 0) return 0n;
  if (!Number.isFinite(x)) return 0n;
  const sign = x < 0 ? -1n : 1n;
  const absX = Math.abs(x);
  const buffer = new ArrayBuffer(8);
  const view = new DataView(buffer);
  view.setFloat64(0, absX);
  const bits = view.getBigUint64(0);
  const expBits = Number((bits >> 52n) & 0x7FFn);
  const mantissaBits = bits & 0xFFFFFFFFFFFFFn;
  let binaryExp, mantissa;
  if (expBits === 0) {
    mantissa = mantissaBits;
    binaryExp = -1022 - 52;
  } else {
    mantissa = (1n << 52n) | mantissaBits;
    binaryExp = expBits - 1023 - 52;
  }
  const five = 5n, two = 2n;
  let result = sign * mantissa * (five ** BigInt(scale));
  const netBinaryExp = binaryExp + scale;
  if (netBinaryExp >= 0) {
    result = result * (two ** BigInt(netBinaryExp));
  } else {
    result = result / (two ** BigInt(-netBinaryExp));
  }
  return result;
}
 
function decimalToQD(decimalString) {
  let s = decimalString.trim().toLowerCase();
  const neg = s.startsWith('-');
  if (neg) s = s.slice(1);
  if (s.startsWith('+')) s = s.slice(1);
  let exp = 0;
  const eIdx = s.indexOf('e');
  if (eIdx !== -1) {
    exp = parseInt(s.slice(eIdx + 1), 10);
    s = s.slice(0, eIdx);
  }
  const parts = s.split('.');
  const intPart = parts[0] || '0';
  const fracPart = parts[1] || '';
  let scale = fracPart.length - exp;
  const bigStr = intPart + fracPart;
  let n = BigInt(bigStr.replace(/^0+/, '') || '0');
  if (neg) n = -n;
  if (scale < 0) {
    n = n * (BigInt(10) ** BigInt(-scale));
    scale = 0;
  }
  // Use internal scale of 60 decimal places for exact float64 representation
  const internalScale = 60;
  if (scale < internalScale) {
    n = n * (BigInt(10) ** BigInt(internalScale - scale));
  } else if (scale > internalScale) {
    n = n / (BigInt(10) ** BigInt(scale - internalScale));
  }
  const limbs = [];
  let residual = n;
  const divisor = BigInt(10) ** BigInt(internalScale);
  for (let i = 0; i < 4; i++) {
    if (residual === 0n) { limbs.push(0); continue; }
    const limb = Number(residual) / Number(divisor);
    limbs.push(limb);
    const limbBigInt = float64ToBigIntScaled(limb, internalScale);
    residual = residual - limbBigInt;
  }
  // Normalize the result to ensure consistent representation across all QD operations.
  // Without this, limbs may not satisfy |limb[i]| < ulp(limb[i-1])/2, causing
  // ArqdAdd/toQDAdd to produce different representations when adding zero.
  // Uses quickTwoSum cascade to renormalize (fully inlined to avoid dependency issues).
  let s0 = limbs[0] + limbs[1], e0 = limbs[1] - (s0 - limbs[0]);
  let s1 = e0 + limbs[2], e1 = limbs[2] - (s1 - e0);
  let s2 = e1 + limbs[3], s3 = limbs[3] - (s2 - e1);
  let t0 = s0 + s1; s1 = s1 - (t0 - s0); s0 = t0;
  t0 = s1 + s2; s2 = s2 - (t0 - s1); s1 = t0;
  t0 = s2 + s3; s3 = s3 - (t0 - s2); s2 = t0;
  return [s0, s1, s2, s3];
}
 
// Parse a complex number string into QD precision real and imaginary parts.
// Accepts formats like: "-0.74543+0.11301i", "0.5i", "-i", "0.25", ""
// Returns { re: QD array, im: QD array } or null if parsing fails
function parseComplexToQD(coordString) {
  const trimmed = coordString.trim();
 
  // Empty string returns null to signal default/inherit behavior
  if (trimmed === '') {
    return null;
  }
 
  // Match: optional real part, then optional imaginary part (with 'i' or just 'i')
  const match = trimmed.match(
    /([-+]?\d*\.?\d+(?:e[-+]?\d+)?\b)?(?:([-+]?\d*\.?\d+(?:e[-+]?\d+)?)i|([-+]?i))?$/
  );
 
  if (!match) {
    return null;
  }
 
  // Extract real part (default to '0' if not present)
  const realStr = match[1] || '0';
 
  // Extract imaginary part: either match[2] (number with 'i') or match[3] (just 'i' or '-i')
  let imagStr = match[2] || (match[3] ? match[3].replace('i', '1') : '0');
 
  return {
    re: decimalToQD(realStr),
    im: decimalToQD(imagStr)
  };
}
 
// Convert QD value to decimal string with exact BigInt arithmetic.
function qdToDecimalString(qd, digits) {
  const o = Array.isArray(qd) ? qd : [qd, 0, 0, 0];
  const internalScale = 60;
  let total = 0n;
  for (let i = 0; i < 4; i++) {
    if (o[i] !== 0) {
      total += float64ToBigIntScaled(o[i], internalScale);
    }
  }
  const neg = total < 0n;
  if (neg) total = -total;
  const divisor = BigInt(10) ** BigInt(internalScale);
  const intPart = total / divisor;
  let fracPart = total % divisor;
  let result = intPart.toString();
  if (digits > 0) {
    let fracStr = fracPart.toString().padStart(internalScale, '0');
    if (digits < fracStr.length) {
      const roundDigit = parseInt(fracStr[digits]);
      fracStr = fracStr.slice(0, digits);
      if (roundDigit >= 5) {
        let carry = 1;
        let chars = fracStr.split('');
        for (let i = chars.length - 1; i >= 0 && carry; i--) {
          const d = parseInt(chars[i]) + carry;
          chars[i] = (d % 10).toString();
          carry = Math.floor(d / 10);
        }
        fracStr = chars.join('');
        if (carry) result = (BigInt(result) + 1n).toString();
      }
    } else {
      fracStr = fracStr.padEnd(digits, '0');
    }
    fracStr = fracStr.replace(/0+$/, '');
    if (fracStr.length > 0) result += '.' + fracStr;
  }
  return result;
}
 
function fast2Sum(a, b) {
  let s = a + b;
  let t = b - (s - a);
  return [s, t];
}
 
function slow2Sum(a, b) {
  let s = a + b;
  let c = s - a;
  return [s, (a - (s - c)) + (b - c)];
}
 
function ddSplit(a) {
  const c = (134217729) * a;  // 2^27 + 1, Veltkamp-Dekker constant
  const x = c - (c - a);
  const y = a - x;
  return [x, y];
}
 
function twoProduct(a, b) {
  let p = a * b;
  let [ah, al] = ddSplit(a);
  let [bh, bl] = ddSplit(b);
  let err = ((ah * bh - p) + ah * bl + al * bh) + al * bl;
  return [p, err];
}
 
function twoSquare(a) {
  let p = a * a;
  let [ah, al] = ddSplit(a);
  let err = ((ah * ah - p) + 2 * ah * al) + al * al;
  return [p, err];
}
 
function ddAdd(a, b) {
  let [a1, a0] = a;
  let [b1, b0] = b;
  let [h1, h2] = slow2Sum(a1, b1);
  let [l1, l2] = slow2Sum(a0, b0);
  let [v1, v2] = fast2Sum(h1, h2 + l1);
  return fast2Sum(v1, v2 + l2);
}
 
function ddMul(a, b) {
  let [a1, a0] = a;
  let [b1, b0] = b;
  let [p1, p2] = twoProduct(a1, b1);
  return fast2Sum(p1, p2 + a1 * b0 + b1 * a0);
}
 
function ddDouble(a) {
  return [a[0] * 2, a[1] * 2];
}
 
function ddScale(q, s) {
  let [q1, q0] = q;
  let [p1, p2] = twoProduct(q1, s);
  return fast2Sum(p1, p2 + s * q0);
}
 
function ddSquare(a) {
  let [a1, a0] = a;
  let [p1, p2] = twoSquare(a1);
  return fast2Sum(p1, p2 + 2 * a1 * a0);
}
 
function ddcPow(q, n) {
  if (n === 1) return q;
  if (n === 2) return ddcSquare(q);
  if (n === 3) return ddcMul(ddcSquare(q), q);
  let result = [1, 0, 0, 0];
  let base = q;
  while (n > 0) {
    if (n % 2 === 1) { result = ddcMul(result, base); }
    base = ddcSquare(base);
    n = Math.floor(n / 2);
  }
  return result;
}
 
function ddNegate(a) {
  let [a1, a0] = a;
  return [-a1, -a0];
}
 
function ddSub(a, b) {
  return ddAdd(a, ddNegate(b));
}
 
function qdDiv(a, b) {
  let reciprocal = ddReciprocal(b);
  return ddMul(a, reciprocal);
}
 
function ddReciprocal(b, iters = 2) {
  if (b[0] === 0 && b[1] === 0) {
    return [NaN, 0];  // Return NaN for division by zero
  }
  // Refine the approximation using Newton-Raphson iteration
  let x = [1 / b[0], 0];
  for (let i = 0; i < iters; i++) {
    x = ddMul(x, ddSub([2, 0], ddMul(x, b)));
  }
  return x;
}
 
// Complex operations in DD precision
function ddcAdd(a, b) {
  let realSum = ddAdd([a[0], a[1]], [b[0], b[1]]);
  let imagSum = ddAdd([a[2], a[3]], [b[2], b[3]]);
  return [realSum[0], realSum[1], imagSum[0], imagSum[1]];
}
 
// Complex subtraction in DD precision
function ddcSub(a, b) {
  let realDiff = ddSub([a[0], a[1]], [b[0], b[1]]);
  let imagDiff = ddSub([a[2], a[3]], [b[2], b[3]]);
  return [realDiff[0], realDiff[1], imagDiff[0], imagDiff[1]];
}
 
// Complex multiplication in DD precision
function ddcMul(a, b) {
  let ac = ddMul([a[0], a[1]], [b[0], b[1]]);
  let bd = ddMul([a[2], a[3]], [b[2], b[3]]);
  let adbc = ddMul(ddAdd([a[0], a[1]], [a[2], a[3]]), ddAdd([b[0], b[1]], [b[2], b[3]]));
  let real = ddSub(ac, bd);
  let imag = ddSub(adbc, ddAdd(ac, bd));
  return [real[0], real[1], imag[0], imag[1]];
}
 
// Complex doubling in DD precision
function ddcDouble(a) {
  let realDouble = ddDouble([a[0], a[1]]);
  let imagDouble = ddDouble([a[2], a[3]]);
  return [realDouble[0], realDouble[1], imagDouble[0], imagDouble[1]];
}
 
// Complex squaring in DD precision
function ddcSquare(a) {
  let a0a0 = ddSquare([a[0], a[1]]);
  let a1a1 = ddSquare([a[2], a[3]]);
  let a0a1 = ddMul([a[0], a[1]], [a[2], a[3]]);
  let real = ddSub(a0a0, a1a1);
  let imag = ddDouble(a0a1);
  return [real[0], real[1], imag[0], imag[1]];
}
 
// Complex absolute value in DD precision
function ddcAbs(a) {
  let a0a0 = ddSquare([a[0], a[1]]);
  let a1a1 = ddSquare([a[2], a[3]]);
  return ddAdd(a0a0, a1a1);
}
 
function qdParse(s) {
  s = s.trim().toLowerCase();
  if (s === "infinity" || s === "+infinity") return [Infinity, 0];
  if (s === "-infinity") return [-Infinity, 0];
  if (s === "nan") return [NaN, 0];
  let sign = 1;
  if (s[0] === '-') {
    sign = -1;
    s = s.slice(1);
  } else if (s[0] === '+') {
    s = s.slice(1);
  }
  let e = 0;
  let parts = s.split('e');
  if (parts.length > 1) {
    s = parts[0];
    e = parseInt(parts[1]);
  }
  let decimalPos = s.indexOf('.');
  if (decimalPos !== -1) {
    s = s.replace('.', '');
    e -= s.length - decimalPos;
  }
  s = s.replace(/^0+/, '');
  if (s === '') return [0, 0];
  let result = [0, 0];
  for (let digit of s) {
    result = ddAdd(ddMul(result, [10, 0]), [parseInt(digit), 0]);
  }
  if (e !== 0) {
    result = ddMul(result, qdPow10(e));
  }
  if (sign === -1) {
    result = ddNegate(result);
  }
  return result;
}
 
function qdPow10(e) {
  if (e < 0) return ddReciprocal(qdPow10(-e));
  // Up to 1e16, the second component is zero.
  if (e <= 16) { return [10 ** e, 0]; }
  if (e % 2) { return ddMul([1e15, 0], qdPow10(e - 15)) };
  return ddSquare(qdPow10(e / 2));
}
 
function qdFloor(q) {
  let [a, b] = q;
  let fl = Math.floor(a);
  let [r0, r1] = ddAdd([a, b], [-fl, 0]);
  if (r0 < 0 || (r0 === 0 && r1 < 0)) {
    fl -= 1;
  }
  return [fl, 0];
}
 
function ddCompare(a, b) {
  if (a[0] < b[0]) return -1;
  if (a[0] > b[0]) return 1;
  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;
}
 
function qdCompare(a, b) {
  if (a[0] < b[0]) return -1;
  if (a[0] > b[0]) return 1;
  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  if (a[2] < b[2]) return -1;
  if (a[2] > b[2]) return 1;
  if (a[3] < b[3]) return -1;
  if (a[3] > b[3]) return 1;
  return 0;
}
 
function qdLt(a, s) {
  return a[0] < s || (a[0] == s && a[1] < 0);
}
 
function ddEq(a, s) {
  return a[0] == s && a[1] == 0;
}
 
function qdEq(a, s) {
  return a[0] === s && a[1] === 0 && a[2] === 0 && a[3] === 0;
}
 
function qdAbs(q) {
  return (q[0] + q[1] < 0) ? ddNegate(q) : q;
}
 
function qdFixed(q, digits = 0) {
  // With fixed-point notation, digits specifies the number of digits after the decimal point.
  return qdFormat(q, digits, true);
}
 
const ddTen = [10, 0];
 
function qdFormat(q, digits = 'auto', useFixedPoint = false) {
  // With scientific notation, digits specifies the number of significant digits.
  let [a, b] = q;
  let s = a < 0 || (a === 0 && b < 0) ? '-' : '';
  let autoFormat = (digits == 'auto');
  if (autoFormat) {
     digits = 32;
  }
  q = qdAbs(q);
  if (!isFinite(a) || !isFinite(b)) return a.toString();
  if (a === 0 && b === 0) {
     if (autoFormat) return '0';
     if (useFixedPoint) digits += 1;
     return '0' + (digits > 1 ? '.' + '0'.repeat(digits - 1) : '');
  }
  // Scale q to be between 1 and 10
  let e = parseInt(q[0].toExponential().match(/e([+-]\d+)/)[1]);
  if (ddCompare(q, qdPow10(e)) < 0) { e -= 1; }
  if (ddCompare(q, qdPow10(1+e)) >= 0) { e += 1; }
  if (e) { q = ddMul(q, qdPow10(-e)); }
  if (!qdLt(q, 10)) { // Hit boundary condition
    q = qdDiv(q, ddTen);
    e += 1;
  }
  let result = '';
  let nonzeroDigits = digits;
  if (useFixedPoint && !autoFormat) {
     nonzeroDigits = nonzeroDigits + e + 1;
  }
  for (let i = 0; i < nonzeroDigits + 1; i++) {
    let floorQ = qdFloor(q);
    let digit = floorQ[0];
    result += digit;
    q = ddSub(q, floorQ);
    q = ddMul(q, ddTen);
  }
  // Rounding
  if (nonzeroDigits < 0) {
    // No nonzero signficant digits? Treat as zero.
    result = '?';
    nonzeroDigits = 0;
    e = 0;
  } else if (parseInt(result[nonzeroDigits]) >= 5) {
    result = result.slice(0, nonzeroDigits) + '?';
    let carry = 1;
    for (let i = nonzeroDigits - 1; i >= 0; i--) {
      let digit = parseInt(result[i]) + carry;
      if (digit < 10) {
        result = result.slice(0, i) + digit + result.slice(i + 1);
        carry = 0;
        break;
      } else {
        result = result.slice(0, i) + '0' + result.slice(i + 1);
        carry = 1;
      }
    }
    if (carry) {
      result = '1' + result;
      nonzeroDigits += 1;
      e++;
    }
  }
  result = result.slice(0, nonzeroDigits);
  epart = '';
  if (!useFixedPoint && (!autoFormat || e < -6 || e >= 32)) {
    // Scientific notation
    if (result.length > 1) {
      result = result[0] + '.' + result.slice(1);
    }
    if (e !== 0) {
      epart = 'e' + e;
    }
  } else {
    // Fixed-point notation
    if (e >= 0) {
      result = result.padEnd(e + 1, '0');
      result = result.slice(0, e + 1) + '.' + result.slice(e + 1);
    } else {
      result = '0.' + '0'.repeat(-e - 1) + result;
    }
    // Ensure the correct number of digits after the decimal point
    let [intPart, fracPart] = result.split('.');
    if (digits <= 0) {
      result = intPart;
    } else {
      fracPart = (fracPart || '').padEnd(digits, '0');
      result = intPart + '.' + fracPart;
    }
  }
  if (autoFormat) {
    // Auto digit selection: trim trailing zeros
    result = result.replace(/\.0+$|(\.\d*[1-9])0+$/, "$1");
  }
  return s + result + epart;
}
 
// Array in-place DD precision, allows fast computation
// by avoiding array constructors
 
function Afast2Sum(r, i, a, b) {
  let s = a + b;
  r[i] = s;
  r[i+1] = b - (s - a);
}
 
function Aslow2Sum(r, i, a, b) {
  let s = a + b;
  let c = s - a;
  r[i] = s;
  r[i+1] = (a - (s - c)) + (b - c);
}
 
function ArddSplit(r, i, a) {
  const c = (134217729) * a;  // 2^27 + 1, Veltkamp-Dekker constant
  const x = c - (c - a);
  const y = a - x;
  r[i] = x;
  r[i+1] = y;
}
 
function AtwoProduct(r, i, a, b) {
  const p = a * b;
  ArddSplit(r, i, a);
  const ah = r[i];
  const al = r[i+1];
  ArddSplit(r, i, b);
  const bh = r[i];
  const bl = r[i+1];
  const err = ((ah * bh - p) + ah * bl + al * bh) + al * bl;
  r[i] = p;
  r[i+1] = err;
}
 
function AtwoSquare(r, i, a) {
  const p = a * a;
  ArddSplit(r, i, a);
  const ah = r[i];
  const al = r[i+1];
  const err = ((ah * ah - p) + 2 * ah * al) + al * al;
  r[i] = p;
  r[i+1] = err;
}
 
function AquickTwoSum(a, b) {
  const s = a + b;
  return [s, b - (s - a)];
}
 
function AsymmetricTwoSum(a, b) {
  const s = a + b;
  const bb = s - a;
  return [s, (a - (s - bb)) + (b - bb)];
}
 
// Three-sum from QD library: combines three values with proper error propagation
// Returns [sum, err1, err2] where sum + err1 + err2 = a + b + c (exactly)
function ArqdThreeSum(a, b, c) {
  let [t1, t2] = AsymmetricTwoSum(a, b);
  let [newA, t3] = AsymmetricTwoSum(c, t1);
  let [newB, newC] = AsymmetricTwoSum(t2, t3);
  return [newA, newB, newC];
}
 
function ArddAdd(r, i, a1, a2, b1, b2) {
  Aslow2Sum(r, i, a1, b1);
  const h1 = r[i];
  const h2 = r[i+1];
  Aslow2Sum(r, i, a2, b2);
  const l1 = r[i];
  const l2 = r[i+1];
  Afast2Sum(r, i, h1, h2 + l1);
  const v1 = r[i];
  const v2 = r[i+1];
  Afast2Sum(r, i, v1, v2 + l2);
}
 
function ArddMul(r, i, a1, a2, b1, b2) {
  AtwoProduct(r, i, a1, b1);
  const p1 = r[i];
  const p2 = r[i+1];
  Afast2Sum(r, i, p1, p2 + a1 * b2 + b1 * a2);
}
 
function ArddSet(r, i, a1, a2) {
  r[i] = a1;
  r[i+1] = a2;
}
 
function ArddcCopy(r, i, s, si) {
  r[i] = s[si];
  r[i+1] = s[si+1];
  r[i+2] = s[si+2];
  r[i+3] = s[si+3];
}
 
function ArddcGet(s, si) {
  return s.slice(si, si+4);
}
 
function ArddSquare(r, i, a1, a2) {
  AtwoSquare(r, i, a1);
  const p1 = r[i];
  const p2 = r[i+1];
  Afast2Sum(r, i, p1, p2 + 2 * a1 * a2);
}
 
function ArddAbsSub(r, i, a1, a2, b1, b2) {
  ArddAdd(r, i, a1, a2, -b1, -b2);
  if (r[i] + r[i+1] < 0) {
    r[i] = -r[i];
    r[i+1] = -r[i+1];
  }
}
 
// Oct-double (four-limb) helpers for deeper precision
 
function ArqdTwoProduct(a, b) {
  const tmp = [];
  AtwoProduct(tmp, 0, a, b);
  return [tmp[0], tmp[1]];
}
 
function ArqdTwoSquare(a) {
  const tmp = [];
  AtwoSquare(tmp, 0, a);
  return [tmp[0], tmp[1]];
}
 
// Renormalization algorithm from QD library (Hida, Li, Bailey)
// Takes 5 inputs and produces 4 normalized outputs
function ArqdRenorm(r, i, c0, c1, c2, c3, c4) {
  let t0, t1, t2, t3, s;
 
  // First pass: propagate from bottom to top, collecting errors
  [s, t3] = AquickTwoSum(c3, c4);
  [s, t2] = AquickTwoSum(c2, s);
  [s, t1] = AquickTwoSum(c1, s);
  [c0, t0] = AquickTwoSum(c0, s);
 
  // Second pass: combine error terms
  [s, t2] = AquickTwoSum(t2, t3);
  [s, t1] = AquickTwoSum(t1, s);
  [c1, t0] = AquickTwoSum(t0, s);
 
  // Third pass: final cleanup
  [s, t1] = AquickTwoSum(t1, t2);
  [c2, t0] = AquickTwoSum(t0, s);
 
  c3 = t0 + t1;
 
  ArqdSet(r, i, c0, c1, c2, c3);
}
 
function ArqdSet(r, i, a1, a2, a3, a4) {
  r[i] = a1;
  r[i+1] = a2;
  r[i+2] = a3;
  r[i+3] = a4;
}
 
function ArqdcCopy(r, i, s, si) {
  r[i] = s[si];
  r[i+1] = s[si+1];
  r[i+2] = s[si+2];
  r[i+3] = s[si+3];
  r[i+4] = s[si+4];
  r[i+5] = s[si+5];
  r[i+6] = s[si+6];
  r[i+7] = s[si+7];
}
 
function ArqdcGet(s, si) {
  return s.slice(si, si+8);
}
 
function ArqdAdd(r, i, a1, a2, a3, a4, b1, b2, b3, b4) {
  let s0, s1, s2, s3, s4, t0, t1, t2;
  [s0, t0] = AsymmetricTwoSum(a1, b1);
  [s1, t1] = AsymmetricTwoSum(a2, b2);
  [s2, t2] = AsymmetricTwoSum(a3, b3);
  s3 = a4 + b4;
 
  [s1, t0] = AsymmetricTwoSum(s1, t0);
  [s2, t1] = AsymmetricTwoSum(s2, t1);
  s3 += t2;
 
  [s2, t0] = AsymmetricTwoSum(s2, t0);
  s3 += t1;
 
  [s3, s4] = AsymmetricTwoSum(s3, t0);
 
  [s0, s1] = AquickTwoSum(s0, s1);
  [s1, s2] = AquickTwoSum(s1, s2);
  [s2, s3] = AquickTwoSum(s2, s3);
  [s3, s4] = AquickTwoSum(s3, s4);
 
  s2 += s4;
  [s2, s3] = AquickTwoSum(s2, s3);
  [s1, s2] = AquickTwoSum(s1, s2);
 
  ArqdSet(r, i, s0, s1, s2, s3);
}
 
// QD library sloppy_mul algorithm (Hida, Li, Bailey)
// Uses TwoProduct for 6 products (levels 0-2) for nearly full 212-bit precision
function ArqdMul(r, i, a1, a2, a3, a4, b1, b2, b3, b4) {
  // Level 0: a[0]*b[0]
  let [p0, q0] = ArqdTwoProduct(a1, b1);
 
  // Level 1: a[0]*b[1], a[1]*b[0]
  let [p1, q1] = ArqdTwoProduct(a1, b2);
  let [p2, q2] = ArqdTwoProduct(a2, b1);
 
  // Level 2: a[0]*b[2], a[1]*b[1], a[2]*b[0]
  let [p3, q3] = ArqdTwoProduct(a1, b3);
  let [p4, q4] = ArqdTwoProduct(a2, b2);
  let [p5, q5] = ArqdTwoProduct(a3, b1);
 
  // Accumulate terms using three_sum
  [p1, p2, q0] = ArqdThreeSum(p1, p2, q0);
  [p2, q1, q2] = ArqdThreeSum(p2, q1, q2);
  [p3, p4, p5] = ArqdThreeSum(p3, p4, p5);
 
  // Further combining
  let [s0, t0] = AsymmetricTwoSum(p2, p3);
  let [s1, t1] = AsymmetricTwoSum(q1, p4);
  let s2 = q2 + p5;
  [s1, t0] = AsymmetricTwoSum(s1, t0);
  s2 += t0 + t1;
 
  // Level 3 cross-products and remaining error terms
  s1 += a1 * b4 + a2 * b3 + a3 * b2 + a4 * b1 + q0 + q3 + q4 + q5;
 
  // Renormalize
  ArqdRenorm(r, i, p0, p1, s0, s1, s2);
}
 
// QD library optimized sqr algorithm (Hida, Li, Bailey)
// Exploits symmetry: a[i]*a[j] = a[j]*a[i], so compute once and double
// Uses TwoSquare (cheaper than TwoProduct) where possible
function ArqdSquare(r, i, a1, a2, a3, a4) {
  // Level 0: a[0]² - use TwoSquare
  let [p0, q0] = ArqdTwoSquare(a1);
 
  // Level 1: 2*a[0]*a[1] - single TwoProduct with doubled arg
  let [p1, q1] = ArqdTwoProduct(2 * a1, a2);
 
  // Level 2: 2*a[0]*a[2] + a[1]²
  let [p2, q2] = ArqdTwoProduct(2 * a1, a3);
  let [p3, q3] = ArqdTwoSquare(a2);
 
  // Accumulate level 1
  [p1, p2, q0] = ArqdThreeSum(p1, q0, p2);
 
  // Accumulate level 2
  [p2, q1, q2] = ArqdThreeSum(p2, q1, q2);
  [p3, q3] = AsymmetricTwoSum(p3, q3);
 
  // Combine accumulated values
  let [s0, t0] = AsymmetricTwoSum(p2, p3);
  let [s1, t1] = AsymmetricTwoSum(q1, q3);
  let s2 = q2;
  [s1, t0] = AsymmetricTwoSum(s1, t0);
  s2 += t0 + t1;
 
  // Level 3: 2*a[0]*a[3] + 2*a[1]*a[2] (plain multiply)
  s1 += 2 * a1 * a4 + 2 * a2 * a3 + q0;
 
  // Renormalize
  ArqdRenorm(r, i, p0, p1, s0, s1, s2);
}
 
// Oct-precision absolute difference: r = |a - b|
// Used for cycle detection in QDPerturbationBoard
function ArqdAbsSub(r, i, a1, a2, a3, a4, b1, b2, b3, b4) {
  ArqdAdd(r, i, a1, a2, a3, a4, -b1, -b2, -b3, -b4);
  if (r[i] + r[i+1] + r[i+2] + r[i+3] < 0) {
    r[i] = -r[i];
    r[i+1] = -r[i+1];
    r[i+2] = -r[i+2];
    r[i+3] = -r[i+3];
  }
}
 
// Additional shared utility function for tracking cycles.
 
function fibonacciPeriod(iteration) {
  // Returns 1 at Fibonacci checkpoints (1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...)
  // Otherwise returns distance from most recent Fibonacci checkpoint plus 1.
  // Fibonacci growth (φ ≈ 1.618) reduces aliasing with periods compared to power-of-2.
  if (iteration === 0) return 1;
  if (iteration === 1) return 1;
 
  // Find largest Fibonacci number <= iteration
  let a = 1, b = 1;
  while (b < iteration) {
    const next = a + b;
    a = b;
    b = next;
  }
 
  // Return 1 if iteration is exact Fibonacci, else distance from previous
  if (b === iteration) return 1;
  return iteration - a + 1;
}
 
// Catmull-Rom spline interpolation for smooth movie camera paths.
// Uses quad-double precision for numerical stability at deep zoom.
function catmullRom1DQD(p0, p1, p2, p3, t) {
  const t2 = t * t;
  const t3 = t2 * t;
  const c0 = (-t3 + 2*t2 - t) / 2;
  const c2 = (-3*t3 + 4*t2 + t) / 2;
  const c3 = (t3 - t2) / 2;
  // Compute offsets from p1 for numerical stability
  const s0 = toQDSub(p0, p1);
  const s2 = toQDSub(p2, p1);
  const s3 = toQDSub(p3, p1);
  return toQDAdd(toQDAdd(toQDAdd(toQDScale(s0, c0),
           toQDScale(s3, c3)), toQDScale(s2, c2)), p1);
}
 
function catmullRomSplineQD(p0, p1, p2, p3, t) {
  return [
    catmullRom1DQD(p0[0], p1[0], p2[0], p3[0], t),
    catmullRom1DQD(p0[1], p1[1], p2[1], p3[1], t)
  ];
}
 
// </script>
 
if (typeof module !== 'undefined') module.exports = { hasDebugFlag, workerLog, selectBoardClass, toDD, toDDc, toDDAdd, toQDc, toQD, toQDScale, toQDAdd, toQDSub, toQDMul, toQDSquare, toQDDouble, qdToNumber, qdToDD, float64ToBigIntScaled, decimalToQD, parseComplexToQD, qdToDecimalString, fast2Sum, slow2Sum, ddSplit, twoProduct, twoSquare, ddAdd, ddMul, ddDouble, ddScale, ddSquare, ddcPow, ddNegate, ddSub, qdDiv, ddReciprocal, ddcAdd, ddcSub, ddcMul, ddcDouble, ddcSquare, ddcAbs, qdParse, qdPow10, qdFloor, ddCompare, qdCompare, qdLt, ddEq, qdEq, qdAbs, qdFixed, qdFormat, Afast2Sum, Aslow2Sum, ArddSplit, AtwoProduct, AtwoSquare, AquickTwoSum, AsymmetricTwoSum, ArqdThreeSum, ArddAdd, ArddMul, ArddSet, ArddcCopy, ArddcGet, ArddSquare, ArddAbsSub, ArqdTwoProduct, ArqdTwoSquare, ArqdRenorm, ArqdSet, ArqdcCopy, ArqdcGet, ArqdAdd, ArqdMul, ArqdSquare, ArqdAbsSub, fibonacciPeriod, catmullRom1DQD, catmullRomSplineQD, Board, CpuBoard, QDCpuBoard, PerturbationBoard, QDPerturbationBoard, SpatialBucket, DDSpatialBucket, QDSpatialBucket, ReferenceOrbitThreading, CpuZhuoranBaseBoard, DDZhuoranBoard, QDZhuoranBoard, GpuBaseBoard, GpuBoard, GpuZhuoranBoard, AdaptiveGpuBoard, FractalWorker };