All files / js mklev.js

81% Statements 2575/3179
80.2% Branches 1086/1354
84% Functions 84/100
81% Lines 2575/3179

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 318073x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 62x 62x 62x 14x 62x 62x 148x 148x 148x 148x         148x 14x 62x                   73x 73x       73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 133x 133x 133x 133x 281x 281x 281x 281x 281x 281x 281x 281x 281x 22x 133x 569x 569x 569x 3x 3x 3x 3x 21x 21x 21x 3x 3x 38x 38x 38x 38x 264x 264x   38x 6x 6x 6x 6x 6x 6x 6x 73x 73x 38x 38x 38x 38x 38x 38x 38x   38x 38x 38x 5x 5x 38x 38x 38x 4x 38x 3x 38x 38x 38x 38x 38x 38x 38x 38x 38x 2x 2x 1x 1x 1x 38x 38x 38x 1x 1x 1x 1x 5x 1x 1x 1x 5x 1x 1x 1x 38x 73x 73x 73x 78x 78x 78x               78x 78x     78x 78x 73x 73x 79x 79x 79x     79x 79x 78x 78x 79x 79x 79x 79x 79x 79x 79x 79x 3x 3x 3x     3x 3x 3x 3x 3x 79x 76x 76x 76x 76x 76x 76x 76x 72x 73x 4x 4x 76x 76x 79x 79x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 23963x 23963x 23963x 23288x 23963x 73x 73x 73x 773x 773x 773x 773x 23963x 23963x 23963x 23963x 793x 793x 23963x 773x 773x 773x 773x 773x 773x 773x 773x 773x 773x 773x 773x 773x 773x 773x 773x 773x         773x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x                                                                                                                                                                                                                                   73x 73x 73x 73x 73x 73x 73x 73x 73x                                                             73x 73x 73x 73x 73x 73x 73x 73x 73x 146x 146x 146x 73x 73x 73x 73x 73x 73x 73x 223x 223x 223x 223x 220x 220x 220x 220x 220x 223x 188x 188x 223x 73x 73x 73x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 4683x 369957x 369957x 369957x 369957x 4683x 223x 223x 223x 442x 442x 442x 442x 10521x 10521x 10273x 10273x 194x 442x 95x 95x 95x 73x 549x 549x 549x 549x 73x 192x 192x 192x 92x 92x 92x 92x 88x 88x 88x                   73x                                                                                                                                                                                                                                                         73x 73x 73x 128x 128x 128x 128x     128x 128x 128x 128x 56x 56x 128x 128x 128x 128x 128x 128x 128x 128x 128x 128x 128x 128x 128x 128x 127x 128x 1x 1x 1x 1x 127x 127x 127x 127x 127x 127x 128x 1x 1x 1x 1x   128x 73x 73x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 123x 123x 123x 123x 223x     100x 5x 5x 100x           95x 95x 95x 95x         223x 223x 223x 223x 223x 223x 223x       223x 96x 96x 96x 96x 3x 3x 93x 93x 93x 96x 1x 1x 1x 1x 95x 95x 95x 95x 96x 96x 92x 92x 92x 92x 56x 56x 56x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 9x 9x 9x 56x 7x 7x                                                   7x 56x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 81x 78x 78x 77x 76x 76x 76x 75x 74x 74x 74x 74x 74x 74x 92x 95x 96x 78x 78x 78x 71x 71x 78x 95x 95x 96x 758x 758x 758x 758x 758x 758x 95x 96x 96x 96x 96x 758x 758x 758x 758x 758x 758x 758x 95x 222x 222x 222x 222x 223x 940x 940x 222x 222x 222x 222x 222x 223x 223x 126x 126x 126x 223x 73x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 223x 73x 73x 73x 93x 93x 93x 93x 93x 93x 93x 93x 93x 71x 71x 93x 71x 71x 71x 71x 142x 142x 142x 71x 71x 71x 71x 93x 93x 93x 93x 93x 93x 93x 93x 846x 72x 72x 56x 56x 56x 56x 56x 846x 774x 773x 773x 75x 75x 75x 75x 75x 774x 1x 1x 1x 774x 846x 93x 73x 73x 967x 967x 838x 838x 838x 838x 838x 838x 129x 967x 246913x 246913x 246913x 246913x 246913x 791880x 791880x 791880x 791880x 791880x 1037942x 1037942x 1037942x 1037942x 1037942x 1037942x 395940x 395940x 395940x 395940x 395940x 128639x 976x 976x 127663x 127663x 395940x 3322x 3322x 71796x 395940x 73x 432x 432x 432x 28560x 593906x 593906x 593906x 593906x 593906x 593906x 593906x 4689x 4689x 593906x 28560x 432x 432x 432x 432x 432x 432x 432x 432x 432x 28560x 593906x 593906x 593906x 98985x 98985x 98985x 98985x 98985x 98985x 98985x 98985x 98985x 470973x 593906x 28560x 432x 73x 432x 432x 432x 73x 73x 1489x 1489x 1489x 1489x 1489x 1489x 1489x 1489x 1489x 1489x 1489x 1489x 1489x 1667x 1526x 1667x 1667x     1526x 1667x 15586x 15308x 15308x 15586x 148515x 148515x 695x 586x 393x 43x 393x 94x 178x 178x 178x 148515x 15586x 1361x 1667x 831x 831x 831x 1489x 1489x     831x 1489x 73x 73x 73x 73x 73x 73x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 892x 79x 79x 79x 79x 892x 892x 892x 12311x 12311x 12311x 12311x 12311x 12311x 12048x 12048x 12047x 12047x 12048x 2432x 12048x 9615x 9615x 9615x 9615x 9615x 12048x 12048x 12048x 10655x 10655x 10655x 12048x 12048x 12048x 12048x 12048x 12048x 12048x 168x 168x 168x 168x 1392x 1392x 12048x 613x 613x 613x 779x 779x 779x 779x 779x 779x 12311x 263x 263x 263x 254x 254x 254x 254x 263x       263x 263x 263x 263x 263x 263x 73x 263x     263x 91x 91x 263x 263x 263x 91x 263x     263x 92x 92x 263x 263x 263x 263x 263x 263x 263x 263x 263x 263x 263x 263x 263x 263x 263x 41x 41x 41x 27x 41x 14x 14x 14x 41x 263x 892x 892x 793x 793x 793x 793x 793x 843x 737x 737x 737x 892x 56x 56x 56x 56x 56x 793x 892x 73x 79x 79x 79x 73x 73x 73x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 1029x 73x 73x 1726x 1726x 1726x 1726x 1726x 1726x 1726x 6507x 29283x 29283x 29283x 29283x 6507x 1726x 8423x 16846x 16846x 16846x 16846x 16846x 8423x 1726x 1916x 7580x 7580x 7580x 7580x 7580x 1916x 1726x     1726x 73x 1104x 1104x 1104x 1104x 1104x 1104x 1104x 1104x 1104x 1104x 881x 881x 7578x 881x 1104x 223x 223x 1104x 1104x 1104x 1104x 1104x 1104x 1104x 1104x 1104x 1104x 1104x 872x 872x 872x 872x 872x 872x 15124x 15124x 15124x 15124x 15124x 15124x 872x 872x 6730x 6730x 6730x 6730x 6730x 6730x 872x 872x 24512x 24512x 24512x 24512x 24512x 872x 797x 797x 797x 797x 797x 797x 797x 797x 872x 75x 75x 872x 1104x 73x 73x 75x 75x     75x 75x 75x     75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 75x 73x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 95x 720x 720x 720x 720x 720x 95x 95x 7505x 157605x 157605x 157605x 37940x 37940x 157605x 7505x 95x 73x 4018x 4018x 4018x 4018x 4018x 4018x 4018x 4018x 4018x 4018x 3110x 4018x 3110x 4018x 4018x 3101x 4018x 73x 3980x 3980x 3980x 3980x 3980x 3980x 29x 29x 29x 29x 51x 51x 38x 38x 51x 11x 11x 11x 11x 27x 51x 51x 51x 51x 51x 29x 879x 3980x 73x 73x 3101x 3101x 3101x 3101x 3101x 3101x 3101x 3101x 3101x 3101x 3101x 3101x 3101x 3980x 3980x 3980x 3980x 3101x 3101x 3101x 3101x                       3101x 73x 73x 15486x 15486x 15486x 15486x 15486x 73x 73x 73x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 1099x 367x 194x 20x 1099x 1099x 1099x 1099x 16564x 16564x 16384x 16384x 16564x 16564x 16367x 16564x 16557x 14486x 26x 26x 26x 14486x 14460x 14460x 14460x 14460x 111x 111x 14460x 16564x 1x 1x 16366x 16366x 16366x 16564x 1270x 16564x 991x 991x 16366x 16564x 2492x 2492x 2492x 1909x 1909x 16564x 2223x 2223x 2223x 2117x 2117x 2223x 12340x 12340x 16564x 16564x 623x 15507x 185x 623x 16564x 16564x 4x 4x 914x 901x 1099x 73x 73x 2036x 2036x 2036x 2036x 2036x 2036x 2036x 2036x 1796x 603x 603x 500x 500x 410x 410x 603x 603x 603x 1796x 1193x 1193x 1796x 4x 4x 4x 4x 4x 4x 1x 1x 1x 4x 2036x 240x 240x 208x 208x 240x 240x 240x 2036x 2036x 73x 73x 1815x 1815x 73x 2036x 2036x 2036x 2036x 2036x 2254x 2254x 2254x 2036x 756x 756x 2023x 2023x 2036x 7343x 7343x 2023x 2036x 17443x 17443x 17443x 2036x 17443x 17443x 894x 894x 894x 894x 15420x 2023x 2023x 2036x 73x 5863x 5863x 5863x 22589x 22589x 22589x 22589x 4976x 5863x 73x 73x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 722x 722x 722x 1381x 228x 228x 228x 659x 284x 284x 284x 431x 147x 147x 147x 147x 1381x 1381x 1381x 724x 724x 724x 1019x 1019x 1019x 1019x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 821x 1329x 174x 174x 821x 1381x 73x 73x 92x 92x 92x 92x 92x 92x 92x 249x 1x 1x 249x 3x 3x 248x 245x 245x 249x 92x 258x 258x 258x 258x 258x 258x 258x 258x 258x 258x 258x 258x 258x 258x 258x 134x 134x 134x 134x   258x 339x 339x 339x 339x 162x 162x 339x 177x 177x 177x 339x 339x 339x 339x 339x 339x 339x 258x 339x 73x 73x 73x 258x 258x 258x 258x 393x 393x 393x 339x 393x 258x 258x 393x 393x 79x 79x 13x 13x     13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 79x 393x 179x 179x 142x 179x 37x 37x 7x 7x 6x 6x 6x 6x 6x 6x 6x 7x 37x 37x 37x 37x 13x 13x 37x 179x 258x 258x 258x 73x 1830x 1830x 1830x 1830x 1830x 1830x 1756x 1830x 1830x 1830x 1830x 1830x 1830x 73x 73x 73x 101x 101x 101x 101x 101x 101x 101x 611x 611x 611x 101x 101x 101x 544x 101x 101x 103x 103x 103x 2x 2x 2x 103x 101x 101x 101x 101x 724x 724x 724x 724x 724x 101x 101x 73x 73x 1488x 1488x 1488x 1488x 1488x 1488x 1488x 73x 73x 73x 73x 73x 73x 1522x 1522x 1522x 1522x 1522x 853x 853x 1522x 1522x 1522x 1522x 853x 853x 102x 853x 853x 1522x 1522x 1522x 1522x 1522x 1522x 6048x 42374x 42374x 42374x 42374x 42374x 42374x       42374x 6048x 1522x 1522x 1522x 1522x 1413x 1522x 1522x 1359x 1522x 73x 197x 197x 197x 197x 197x 197x 197x 197x 1522x 197x     197x 197x 197x     197x 197x 197x         197x 73x 119x 119x 119x 119x 119x 119x 119x 119x 119x 119x 119x 119x 95x 119x 119x 119x 119x 119x 119x 119x 119x 119x 24x 119x 95x 95x 119x 73x 73x 95x 95x 95x 95x 95x 95x 95x 95x 95x       95x 95x 95x 95x 95x 95x 24x 24x 24x       24x 24x 24x 95x 73x 73x                                                                                                                                                                         73x                                               73x                                                                   73x                                                                                           73x 73x 73x 73x 73x 73x 73x 73x 248x 248x 248x 248x 248x 248x 248x 248x 45x 45x 248x 248x 25x 25x 25x 248x 8x 8x 8x 8x 248x 11x 11x 11x 248x 9x 9x 9x 248x 10x 10x 10x 248x 248x 21x 21x 21x 248x 12x 12x 12x 248x 6x 6x 6x 248x 9x 9x 9x 248x 248x 248x 52x 52x 52x 52x 52x 73x 73x 73x 6x 6x 6x 73x 110x 110x 110x 129x 129x 129x 129x 110x 110x 110x 73x 52x 52x 52x 52x 52x 52x 52x 52x 5x 5x 5x 52x 11x 11x 52x 12x 12x 52x 24x 52x 52x 52x 52x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 52x 52x 52x 2x 2x 2x 2x 52x 52x 7x 7x 52x 52x 52x 14x 14x 52x 52x 52x 52x 14x 14x           14x 52x 15x 15x 52x 52x 52x 52x 52x 73x 73x 106x 106x 106x 106x 106x 248x 106x 106x 106x 106x 106x 106x 106x 106x 106x 106x 2x 2x 106x 106x 106x       106x 106x 106x 106x 106x 106x 78x 106x 52x       52x 52x 106x 73x 73x 73x 73x 11x 11x 11x 11x 11x 11x 11x 11x 11x 4x 4x 4x 4x 4x 4x 4x 4x 11x 11x 30x 30x 30x 30x 30x 30x 11x 11x     11x 73x 73x 73x 73x 73x 73x 73x 73x 73x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 73x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 73x 73x 73x 73x 1053x 1053x 1053x 1053x 75x 75x 75x 1053x 1053x 215x 215x 215x 629x 76x 76x 1053x 5x 5x 1053x 8x 8x 1053x 29x 29x 1053x 2x 2x 1053x 6x 6x 1053x 27x 27x 1053x 2x 2x 1053x 60x 1053x 471x 192x 192x 55x 55x 55x 55x 137x 188x 76x 76x 152x 304x 304x 304x 304x 152x 76x 192x 192x 192x 192x 192x 192x 192x 192x 43x 43x 192x 18x 192x 192x 1053x 73x 92x 92x 92x 92x 92x 92x 186x 186x 79x 79x 186x 13x 92x 73x 73x 762x 762x 762x 762x 710x 762x 4x 4x 4x 710x 762x 685x 685x 762x 218x 218x 218x 218x     218x 685x 685x 685x 762x 685x 762x 106x 106x 685x 762x 212x 212x 685x 685x 762x 685x 762x 67x 67x 685x 762x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 685x 762x 12x 12x 685x 762x 762x 762x 11x 11x 685x 762x 32x 32x 685x 685x 685x 762x 92x 92x 92x 92x 92x 92x 92x 92x 4x 4x 4x 4x 92x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 71x 36x 66x 35x 35x 71x 71x 17x 17x 17x 71x 71x 71x 53x 53x 53x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 10x 10x 30x 30x 30x 18x 30x 12x 12x 12x 30x 10x 35x 35x 35x 53x 53x 53x 53x 92x 685x 685x 762x 33x 33x 33x 685x 685x 685x 762x 762x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 685x 762x 221x 221x 221x 56x 56x 56x 56x 56x 221x 762x 73x 73x 319124x 319124x 319124x 319124x 319124x 319124x 319124x 319124x 319124x 318377x 319124x 73x 221x 221x 221x 221x 221x 221x 221x 221x 16796x 747x 747x 221x 73x 73x 73x 223x 223x 223x 223x 223x 219x 219x 219x 219x 219x 219x 219x 219x 219x 219x 219x 110x 110x 219x 109x 223x 223x 223x 223x 109x 109x 109x 109x 109x 109x 13x 13x 101x       109x 109x 223x 8284x 100756x 100756x 100756x 100756x 27496x 27496x 27496x 100756x 3270x 3270x 3270x 69990x 69990x 69990x 100756x 100756x 100756x 44370x 44370x 922x 922x 922x 922x 922x 922x 302x 908x 620x 620x 922x 44370x 44370x 203x 203x 401x 401x 401x 49x 398x 352x 352x 352x 110x 338x 242x 242x 352x 401x 401x 203x 44370x 100756x 100756x 223x 73x 73x 298x 298x 298x 298x 1670x 35070x 35070x 3422x 3422x 3422x 3422x 35070x 1670x 298x 298x 298x 298x 298x 1657x 34797x 34797x 3356x 3356x 3356x 3356x 34797x 1657x 298x 298x 298x 298x 298x 697x 46713x 46713x 11878x 11878x 11878x 11878x 46713x 697x 298x 298x 298x 298x 504x 33327x 33327x 12076x 12076x 12076x 12076x 33327x 504x 298x 298x 298x 73x 225x 225x 225x 223x 223x 225x 17840x 374640x 374640x 374640x 374640x 83327x 83327x 83327x 374640x 17840x 225x 73x 73x 225x 225x 225x 223x 223x 225x 225x 225x 225x 225x 225x 16x 16x 225x 225x 108x 108x 821x 821x 108x 225x 225x 225x 225x 1178x 1178x 1178x 225x  
// mklev.js — Level generation (port of mklev.c)
// This is the master level generation module. makelevel() orchestrates:
//   1. clear_level_structures() — reset the map
//   2. makerooms() — place rooms using rectangle allocator
//   3. generate_stairs() — up/down stairs
//   4. makecorridors() → join() — connect rooms with corridors
//   5. make_niches() — wall niches
//   6. vault creation
//   7. special room designation (shop, zoo, temple, etc.)
//   8. fill_ordinary_room() — populate rooms with items/monsters/traps
//
// RNG calls are pervasive throughout — every room dimension, position,
// corridor path, door placement, item/monster creation, and trap placement
// involves RNG.
import { game } from './gstate.js';
import { stairway_add } from './stairs.js';
import { set_wall_state } from './display.js';
import { A_CHAOTIC, A_LAWFUL, A_NEUTRAL, A_WIS, Align2amask, ALTAR, ANTHOLE, ARROW_TRAP, BARRACKS, BEEHIVE, BLCORNER, BR_NO_END1, BR_NO_END2, BR_PORTAL, BRCORNER, COCKNEST, COLNO, CORPSTAT_FEMALE, CORPSTAT_INIT, CORR, COURT, CROSSWALL, D_CLOSED, D_ISOPEN, D_LOCKED, D_NODOOR, D_TRAPPED, DART_TRAP, DBWALL, DIR_180, DIR_E, DIR_N, DIR_S, DIR_W, DOOR, DUST, FIRE_TRAP, FOUNTAIN, G_GONE, GRAVE, HEADSTONE, HOLE, HWALL, ICE, IRONBARS, IS_DOOR, Is_earthlevel, IS_FURNITURE, is_hole, IS_OBSTRUCTED, is_pit, IS_POOL, Is_rogue_level, IS_STWALL, IS_WALL, isok, Is_knox_level, LADDER, LANDMINE, LAVAPOOL, LAVAWALL, LEPREHALL, LEVEL_TELEP, MAGIC_PORTAL, MAGIC_TRAP, MARK, MAX_SUBROOMS, MAX_TYPE, MAXDUNGEON, MAXLEVEL, MAXNROFROOMS, MM_NOGRP, MOAT, MORGUE, OROOM, PIT, POLY_TRAP, POOL, ROCKTRAP, ROLLING_BOULDER_TRAP, ROOM, ROOMOFFSET, ROWNO, RUST_TRAP, SCORR, SDOOR, SHARED, SHOPBASE, SINK, SLP_GAS_TRAP, SPACE_POS, SPIKED_PIT, SQKY_BOARD, STAIRS, STATUE_TRAP, STONE, SWAMP, TAINT_AGE, TDWALL, TELEP_TRAP, TEMPLE, THEMEROOM, TLCORNER, TLWALL, TRAPDOOR, TRAPPED_CHEST, TRAPPED_DOOR, TRCORNER, TRWALL, TUWALL, VAULT, VIBRATING_SQUARE, VWALL, W_NONDIGGABLE, WATER, WEB, XL_DOWN, XL_LEFT, XL_RIGHT, XL_UP, ZOO } from './const.js';
// DIR_180 — imported from const.js
// themeroom_maps.js was removed — map-type rooms go through themerms.js contents() callbacks
import { add_to_container, curse, dealloc_obj, mkcorpstat, mkgold, mkobj, mkobj_at, mksobj, mksobj_at, place_object, rndmonnum, sobj_at, weight } from './mkobj.js';
import { des_map, des_region, finalize_level, reset_des_coder, shuffle, splev_chr2typ } from './sp_lev.js';
import { stock_room } from './shknam.js';
import { in_rooms } from './shk.js';
import { In_endgame as in_endgame, In_mines, In_sokoban, Invocation_lev, is_rogue_level, Sokoban } from './macros.js';
import { stolen_booty, walkfrom, maze_remove_deadends } from './mkmaze.js';
import { Can_fall_thru } from './dbridge.js';
export { Sokoban };
// C ref: mklev.c:in_town
export function in_town(x, y) {
    const lvl = game.level;
    if (!lvl?.flags?.has_town)
        return false;
    let has_subrooms = false;
    const rooms = lvl.rooms || [];
    for (let i = 0; i < rooms.length; i++) {
        const sroom = rooms[i];
        if (!sroom || !(sroom.hx > 0))
            break;
        if ((sroom.nsubrooms || 0) > 0) {
            has_subrooms = true;
            if (insideTownRoom(sroom, x, y))
                return true;
        }
    }
    return !has_subrooms;
}
function insideTownRoom(croom, x, y) {
    if (croom.irregular) {
        const roomno = (croom.roomnoidx ?? game.level?.rooms?.indexOf(croom) ?? -1) + ROOMOFFSET;
        const loc = game.level?.at(x, y);
        return !!loc && !loc.edge && loc.roomno === roomno;
    }
    return x >= (croom.lx - 1) && x <= (croom.hx + 1)
        && y >= (croom.ly - 1) && y <= (croom.hy + 1);
}
// C ref: mklev.c:angry_guards
export function angry_guards(silent) {
    // TODO: implement guard aggression
    return 0;
}
// Direction deltas: index by DIR_* constant
// C ref: mklev.c uses xdir[]/ydir[] arrays
const xdir = [/*W*/-1, /*NW*/-1, /*N*/0, /*NE*/1, /*E*/1, /*SE*/1, /*S*/0, /*SW*/-1];
const ydir = [/*W*/0, /*NW*/-1, /*N*/-1, /*NE*/-1, /*E*/0, /*SE*/1, /*S*/1, /*SW*/1];
import { rn2, rnd, rn1, pushRngLogEntry } from './rng.js';
import { exercise } from './attrib.js';
import { init_rect, rnd_rect, get_rect, split_rects, get_rect_cnt } from './rect.js';
import { GameMap } from './game.js';
import { oinit } from './o_init.js';
import { themeroomMeta } from './themeroom_meta.js';
import { find_level } from './dungeon.js';
import { depth as depth_of_level } from './hacklib.js';
// themerms.js imported dynamically to avoid circular dependency issues
// import { themerooms_generate as themerms_generate } from './levels/themerms.js';
import { level_difficulty, makemon } from './makemon.js';
import { make_engr_at, make_grave, wipe_engr_at, wipeout_text, random_engraving } from './engrave.js';
import { distmin } from './hacklib.js';
// C ref: dungeon.c Is_branchlev() — check if current level has a branch
function is_branchlev() {
    const g = game;
    if (!g.branches) return null;
    for (const br of g.branches) {
        if (br && br.end1 &&
            br.end1.dnum === (g.u?.uz?.dnum ?? 0) &&
            br.end1.dlevel === (g.u?.uz?.dlevel ?? 1))
            return br;
        if (br && br.end2 &&
            br.end2.dnum === (g.u?.uz?.dnum ?? 0) &&
            br.end2.dlevel === (g.u?.uz?.dlevel ?? 1))
            return br;
    }
    return null;
}
function on_level(a, b) {
    return !!a && !!b && a.dnum === b.dnum && a.dlevel === b.dlevel;
}
function at_dgn_entrance(dnum) {
    const uz = game.u?.uz;
    if (!uz || dnum == null) return false;
    for (const br of (game.branches || [])) {
        if (br?.end2?.dnum !== dnum) continue;
        if (on_level(uz, br.end1)) return true;
    }
    return false;
}
function find_knox_branch() {
    const knox = game.knox_level;
    if (!knox) return null;
    for (const br of (game.branches || [])) {
        if (on_level(br?.end1, knox) || on_level(br?.end2, knox)) return br;
    }
    return null;
}
function branch_sort_val(bp) {
    const end1 = bp?.end1 ?? { dnum: 0, dlevel: 0 };
    const end2 = bp?.end2 ?? { dnum: 0, dlevel: 0 };
    return (((end1.dnum * (MAXLEVEL + 1) + end1.dlevel)
        * (MAXDUNGEON + 1) * (MAXLEVEL + 1))
        + (end2.dnum * (MAXLEVEL + 1) + end2.dlevel));
}
// C ref: mklev.c:2624-2659 mk_knox_portal()
// Keep RNG gates and branch insertion/place ordering.
async function mk_knox_portal(x, y) {
    const g = game;
    const wizardMode = !!g.flags?.debug;
    const br = find_knox_branch();
    if (!br) return;
    let source = null;
    if (on_level(g.knox_level, br.end1)) {
        source = br.end2;
    } else {
        // C: disallow Knox branch on a level with one branch already
        if (is_branchlev()) return;
        source = br.end1;
    }
    if (!source) return;
    const ndgns = g.n_dgns ?? g.dungeons?.length ?? 0;
    if (source.dnum < ndgns) return;
    const gate = rn2(3);
    if (gate && !wizardMode) return;
 
    const uz = g.u?.uz;
    const oracle = g.oracle_level;
    const medusa = g.medusa_level;
    const u_depth = depth_of_level(uz);
    const medusa_depth = depth_of_level(medusa);
    if (!(uz?.dnum === oracle?.dnum
        && !at_dgn_entrance(g.quest_dnum)
        && u_depth > 10
        && u_depth < medusa_depth)) {
        return;
    }
    // C: *source = u.uz; insert_branch(br, TRUE)
    source.dnum = uz.dnum;
    source.dlevel = uz.dlevel;
    const branches = g.branches || [];
    const idx = branches.indexOf(br);
    if (idx >= 0) {
        branches.splice(idx, 1);
        const val = branch_sort_val(br);
        let insertAt = branches.length;
        for (let i = 0; i < branches.length; i++) {
            if (val <= branch_sort_val(branches[i])) {
                insertAt = i;
                break;
            }
        }
        branches.splice(insertAt, 0, br);
    }
    await place_branch(br, x, y);
}
// C ref: mklev.c:1648-1663 find_branch_room()
// Finds a room for branch stairway placement.
// RNG: generate_stairs_find_room (rn2(good_count)) + somexyspace (rn1+rn1)
function find_branch_room(mp) {
    const g = game;
    if (g.level.nroom === 0) {
        const mm = mazexy();
        if (mm) {
            mp.x = mm.x;
            mp.y = mm.y;
        }
        return null;
    }
    const croom = generate_stairs_find_room();
    if (croom && !somexyspace(croom, mp)) {
        // impossible — can't place branch
    }
    return croom;
}
// C ref: mklev.c place_branch()
// RNG: find_branch_room → generate_stairs_find_room (rn2) + somexyspace (rn1+rn1)
async function place_branch(branchp, x = 0, y = 0) {
    const g = game;
    if (!branchp || g.made_branch) {
        return;
    }
    const mp = { x, y };
    if (!x) {
        find_branch_room(mp);
    }
 
    const on_end1 = (branchp.end1?.dnum === g.u?.uz?.dnum
        && branchp.end1?.dlevel === g.u?.uz?.dlevel);
    const make_stairs = on_end1
        ? branchp.type !== BR_NO_END1
        : branchp.type !== BR_NO_END2;
    const dest = on_end1 ? branchp.end2 : branchp.end1;
    if (branchp.type === BR_PORTAL) {
        const ttmp = await maketrap(mp.x, mp.y, MAGIC_PORTAL);
        if (ttmp) {
            if (g.flags?.debug_fuzzer && ((g.u?.ucamefrom?.dnum || 0) || (g.u?.ucamefrom?.dlevel || 0))) {
                ttmp.dst.dnum = g.u.ucamefrom.dnum;
                ttmp.dst.dlevel = g.u.ucamefrom.dlevel;
            } else {
                ttmp.dst.dnum = dest?.dnum ?? 0;
                ttmp.dst.dlevel = dest?.dlevel ?? 0;
            }
        }
    } else if (make_stairs && mp.x > 0) {
        const goes_up = on_end1 ? !!branchp.end1_up : !branchp.end1_up;
        const loc = g.level?.at(mp.x, mp.y);
        if (loc) {
            loc.typ = STAIRS;
            loc.ladder = goes_up ? 1 : 2; // LA_UP, LA_DOWN
            stairway_add(mp.x, mp.y, goes_up, false, dest || { dnum: 0, dlevel: 0 });
            if (goes_up) {
                if (g.level) g.level.upstair = { x: mp.x, y: mp.y };
            } else {
                if (g.level) g.level.dnstair = { x: mp.x, y: mp.y };
            }
        }
    }
    g.made_branch = true;
}
const FILL_NORMAL = 1;
import { ARMOR_CLASS, ARROW, BELL, BOULDER, BOW, CHEST, CORPSE, CRAM_RATION, DART, FAKE_AMULET_OF_YENDOR, FOOD_CLASS, FOOD_RATION, GEM_CLASS, GOLD_PIECE, KELP_FROND, LARGE_BOX, LEMBAS_WAFER, MACE, PLATE_MAIL, POT_EXTRA_HEALING, POT_GAIN_ENERGY, POT_HEALING, POT_SPEED, POTION_CLASS, RANDOM_CLASS, RING_CLASS, RING_MAIL, ROCK, SCR_CONFUSE_MONSTER, SCR_ENCHANT_ARMOR, SCR_ENCHANT_WEAPON, SCR_SCARE_MONSTER, SCR_TELEPORTATION, SCROLL_CLASS, SPBOOK_no_NOVEL, SPE_HEALING, STATUE, TALLOW_CANDLE, TOOL_CLASS, TWO_HANDED_SWORD, WAN_DIGGING, WAX_CANDLE, WEAPON_CLASS } from './objects.js';
import { mkclass } from './makemon.js';
import { mons, S_HUMAN, S_ZOMBIE, S_MUMMY } from './monsters.js';
import { antholemon, do_mkroom, fill_zoo, somex, somey, somexyspace } from './mkroom.js';
import {
    PM_ELF, PM_HUMAN, PM_DWARF, PM_ORC, PM_GNOME,
    PM_ARCHEOLOGIST, PM_WIZARD, PM_LEPRECHAUN, PM_KILLER_BEE,
    PM_COCKATRICE, PM_GIANT_SPIDER, PM_MINOTAUR,
    PM_GHOST, PM_SOLDIER, PM_SERGEANT, PM_LIEUTENANT, PM_CAPTAIN,
    PM_SMALL_MIMIC, PM_LARGE_MIMIC, PM_GIANT_MIMIC, S_MIMIC,
} from './monsters.js';
// C ref: themerms.lua:890 is_eligible()
// Check if a themed room is eligible at the current difficulty.
// C ref: themerms.lua is_eligible(room, mkrm)
// During selection (mkrm=nil), only mindiff/maxdiff are checked.
// The eligible callback is only called when a specific room is being
// tested for a particular placement (mkrm ~= nil), not during selection.
function is_themeroom_eligible(room, difficulty) {
    if (room.mindiff != null && difficulty < room.mindiff) return false;
    if (room.maxdiff != null && difficulty > room.maxdiff) return false;
    return true;
}
// C ref: themerms.lua:926 themerooms_generate()
// Reservoir sampling to pick one themed room. Each eligible room triggers
// an rn2(total_frequency) call.
async function themerooms_generate(difficulty) {
    let pick = null;
    let total_frequency = 0;
    for (const meta of themeroomMeta.rooms) {
        if (!is_themeroom_eligible(meta, difficulty)) continue;
        const this_frequency = meta.frequency || 1;
        total_frequency += this_frequency;
        if (this_frequency > 0 && rn2(total_frequency) < this_frequency) {
            pick = meta;
        }
    }
    if (!pick) return false;
    // C ref: mklev.c:412-416 — calls Lua themerooms[pick].contents() for ALL types.
    // C does NOT distinguish map vs room body types — it always calls contents().
    // The contents() callback calls des.map() or des.room() which handles
    // placement, collision checks, and filler_region in C's exact call order.
    const therms_entry = themerooms.find(t => t.name === pick.name);
    if (therms_entry) {
        game.in_mk_themerooms = true;
        game.themeroom_failed = false;
        try {
            await therms_entry.contents();
            return !game.themeroom_failed;
        } finally {
            game.in_mk_themerooms = false;
            game.themeroom_failed = false;
        }
    }
    // Fallback for rooms not in themerms.js (should not happen with complete port)
    if (pick.bodyKind === 'map') return await build_themeroom_map(pick);
    if (pick.bodyKind === 'room') return await build_themeroom_room(pick);
    return create_room(-1, -1, -1, -1, -1, -1, OROOM, -1, true);
}
// Map dimensions for des.map() themed rooms (from themerms.lua)
const MAP_ROOM_DIMS = {
    'L-shaped': [8, 8], 'L-shaped, rot 1': [8, 8],
    'L-shaped, rot 2': [8, 8], 'L-shaped, rot 3': [8, 8],
    'Blocked center': [11, 11],
    'Circular, small': [7, 7], 'Circular, medium': [9, 9],
    'Circular, big': [11, 11],
    'T-shaped': [11, 8], 'T-shaped, rot 1': [8, 11],
    'T-shaped, rot 2': [11, 8], 'T-shaped, rot 3': [8, 11],
    'S-shaped': [8, 11], 'S-shaped, rot 1': [11, 8],
    'Z-shaped': [8, 11], 'Z-shaped, rot 1': [11, 8],
    'Cross': [11, 11], 'Four-leaf clover': [11, 11],
    'Water-surrounded vault': [6, 6],
};
// C ref: sp_lev.c:6163 lspo_map() + filler_region
// When a themed room uses des.map(), the RNG pattern is:
// 1. rn2(100) @ build_room chance check
// 2. rn2(rect_w - map_w + 1) for x placement
// 3. rn2(rect_h - map_h + 1) for y placement
// 4. Possibly percent(30) for filler_region → rn2(100)
// 5. If filler: litstate_rnd → rnd(depth+1) + rn2(77)
async function build_themeroom_map(meta) {
    game.in_mk_themerooms = true;
    try {
        // NOTE: map rooms do NOT go through build_room — no rn2(100) chance check.
        // They use sp_lev.c lspo_map() directly.
        const dims = MAP_ROOM_DIMS[meta.name];
        if (!dims) {
            return create_room(-1, -1, -1, -1, -1, -1, OROOM, -1, true);
        }
        const [mapW, mapH] = dims;
        const mapData = null; // THEMEROOM_MAPS removed — map rooms go through themerms.js
        const mapLines = (mapData?.map || '').split('\n');
        // C ref: sp_lev.c:6147-6275 — themed room map placement with retry
        // Place at random coords, check for collision, retry if overlapping.
        let x, y;
        let tryct = 0;
        let failed = false;
        do {
            x = 1 + rn2(COLNO - 1 - mapW);  // sp_lev.c:6154
            y = rn2(ROWNO - mapH);            // sp_lev.c:6164
            // C ref: sp_lev.c:6246-6274 — collision check
            // If map area overlaps non-STONE tiles, retry
            let okPlacement = true;
            for (let cy = y - 1; cy < Math.min(ROWNO, y + mapH) + 1 && okPlacement; cy++) {
                for (let cx = x - 1; cx < Math.min(COLNO, x + mapW) + 1 && okPlacement; cx++) {
                    if (!isok(cx, cy)) {
                        okPlacement = false;
                    } else {
                        const loc = game.level?.at(cx, cy);
                        if (!loc) {
                            okPlacement = false;
                        } else if (cy < y || cy >= (y + mapH) || cx < x || cx >= (x + mapW)) {
                            // C: outside map interior, border must remain untouched STONE/NO_ROOM.
                            if (loc.typ !== STONE || loc.roomno !== 0) {
                                okPlacement = false;
                            }
                        } else {
                            // C: interior may overlap only if preexisting terrain is STONE or same mptyp.
                            const mapCh = mapLines[cy - y]?.[cx - x] ?? ' ';
                            const mptyp = splev_chr2typ(mapCh);
                            if (mptyp >= MAX_TYPE) {
                                continue; // see-through map marker
                            }
                            if ((loc.typ !== STONE && loc.typ !== mptyp) || loc.roomno !== 0) {
                                okPlacement = false;
                            }
                        }
                    }
                }
            }
            if (okPlacement) break;
            // C ref: sp_lev.c:6269 — tryct++ < 100 (post-increment) allows 101 total tries
            if (tryct++ >= 100) { failed = true; break; }
        } while (true);
        if (failed) {
            return false;
        }
        // Actually draw the map tiles on the level
        if (mapData?.map) {
            // C ref: lspo_map defaults lit to FALSE when not specified
            // in the Lua table. Pass 0 (dark) to match.
            await des_map(mapData.map, x, y, 0);
        }
        // Most map rooms call filler_region(x, y) which does:
        // 1. percent(30) → rn2(100) for themed vs ordinary
        // 2. des.region() → litstate_rnd(-1) — ALWAYS runs
        const hasFiller = !meta.name.startsWith('Water'); // vault room has no filler
        if (hasFiller) {
            const fillType = rn2(100) < 30 ? THEMEROOM : OROOM;
            let seed = Array.isArray(meta.fillSeed)
                ? { x: x + meta.fillSeed[0], y: y + meta.fillSeed[1] }
                : null;
            if (!seed) {
                for (let my = 0; my < mapH && !seed; my++) {
                    for (let mx = 0; mx < mapW; mx++) {
                        if (mapLines[my]?.[mx] === '.') {
                            seed = { x: x + mx, y: y + my };
                            break;
                        }
                    }
                }
            }
            if (!seed) {
                for (let my = 0; my < mapH && !seed; my++) {
                    for (let mx = 0; mx < mapW; mx++) {
                        if (mapLines[my]?.[mx] === '#') {
                            seed = { x: x + mx, y: y + my };
                            break;
                        }
                    }
                }
            }
            if (seed) {
                const fillRoom = des_region(seed.x, seed.y, seed.x, seed.y, fillType, -1, true, FILL_NORMAL);
                if (fillType === THEMEROOM && fillRoom) {
                    await themeroom_fill(fillRoom);
                }
            }
        }
        return true;
    } finally {
        game.in_mk_themerooms = false;
    }
}
function map_themeroom_type(name) {
    switch (name) {
    case 'themed':
        return THEMEROOM;
    case 'ordinary':
    default:
        return OROOM;
    }
}
// C ref: themerms.lua — rooms that compute dimensions via RNG before calling des.room().
// In Lua, arguments are fully evaluated before the function call, so rn2() calls for
// w and h happen BEFORE des.room()'s chance check (rn2(100) in build_room/sp_lev.c).
// These functions must be called in w-first, h-second order to match C.
const DYNAMIC_DIMS = {
    'Mausoleum':                            () => ({ w: 5 + rn2(3)*2, h: 5 + rn2(3)*2 }),
    'Nesting rooms':                        () => ({ w: 9 + rn2(4),   h: 9 + rn2(4)   }),
    'Huge room with another room inside':   () => ({ w: rn2(10)+11,   h: rn2(5)+8     }),
};
async function build_themeroom_room(meta) {
    game.in_mk_themerooms = true;
    try {
        // Compute dynamic dimensions BEFORE chance check to match C's arg evaluation order.
        // In Lua, des.room({ w = rn2(...), h = rn2(...), ... }) evaluates rn2() for w and h
        // before calling des.room(), which contains the rn2(100) chance check.
        const dynDims = DYNAMIC_DIMS[meta.name]?.() ?? null;
        const chance = 100;
        const rtype = (chance <= 0 || rn2(100) < chance)
            ? map_themeroom_type(meta.roomType)
            : OROOM;
        const w = dynDims?.w ?? meta.w ?? -1;
        const h = dynDims?.h ?? meta.h ?? -1;
        const lit = meta.lit ?? -1;
        const ok = create_room(-1, -1, w, h, -1, -1, rtype, lit, true);
        if (ok) {
            const aroom = game.level.rooms[game.level.nroom - 1];
            if (aroom) {
                aroom.needfill = (meta.filled === false || meta.filled === 0)
                    ? 0 : FILL_NORMAL;
                if (meta.roomType === 'themed') {
                    await themeroom_fill(aroom);
                }
            }
        }
        return ok;
    } finally {
        game.in_mk_themerooms = false;
    }
}
// C ref: allmain.c:797 l_nhcore_init()
// Creates Lua state, loads nhcore.lua which loads nhlib.lua.
// nhlib.lua overrides math.random and shuffles align[] — 2 core RNG calls.
// Called from newgame() AFTER u_init_misc() and BEFORE mklev().
export function l_nhcore_init() {
    // C nhlib.lua: align = {"law","neutral","chaos"}; shuffle(align)
    // Preserve both RNG consumption and the resulting permutation.
    const align = [A_LAWFUL, A_NEUTRAL, A_CHAOTIC];
    for (let i = align.length; i > 1; i--) {
        const j = rn2(i);
        [align[i - 1], align[j]] = [align[j], align[i - 1]];
    }
    game.splev_align = align;
}
// NOTE: differs from canonical bones.js — local has explore/bones/debug checks + rn2(3) RNG consumption; canonical just returns 0
// C ref: bones.c:629 getbones()
// Checks for bones level.
// C gates (discover/bones option) run before rn2(3); in explore mode,
// C returns early and does not consume bones RNG here.
function getbones() {
    const flags = game.flags || {};
    // C: if (discover) return 0;  where discover == flags.explore
    if (flags.explore) return false;
    // C: if (!flags.bones) return 0; default is enabled when unset
    if (flags.bones === false) return false;
    // C: if (rn2(3) && !wizard) return 0;
    // In wizard mode, rn2(3) is called but result is ignored (always continue).
    // In normal mode, 2/3 chance of skipping bones.
    if (rn2(3) && !game.flags?.debug) return false;
    // No bones files exist in our environment, so always return false.
    return false;
}
// C ref: mklev.c:1567 mklev()
// Entry point for level generation. Called from newgame().
export async function mklev() {
    const g = game;
    // C: reseed_random(rn2) — reseeds PRNG (ISAAC64 auto-reseeds)
    // C: init_mapseen(&u.uz)
    // C: if (getbones()) return — skip if bones level loaded
    if (getbones()) return;
    g.in_mklev = true;
    await makelevel();
    recount_level_features();
    level_finalize_topology();
    g.in_mklev = false;
    // C harness emits destination mapdump after each newly generated level.
    // This must happen before goto_level() stair transit messaging.
    const dnum = game.u?.uz?.dnum ?? 0;
    const dlevel = game.u?.uz?.dlevel ?? 1;
    const serial = ((game.mapdump_serial ?? 0) + 1);
    game.mapdump_serial = serial;
    pushRngLogEntry(`^mapdump[d${dnum}l${dlevel}_${String(serial).padStart(3, '0')}]`);
    // C: reseed_random(rn2)
}
function recount_level_features() {
    const lvl = game.level;
    if (!lvl?.flags) return;
    let nfountains = 0;
    let nsinks = 0;
    for (let y = 0; y < ROWNO; y++) {
        for (let x = 1; x < COLNO; x++) {
            const typ = lvl.at(x, y)?.typ;
            if (typ === FOUNTAIN) nfountains++;
            if (typ === SINK) nsinks++;
        }
    }
    lvl.flags.nfountains = nfountains;
    lvl.flags.nsinks = nsinks;
}
function is_special_level(lev = game.u?.uz) {
    if (!lev) return null;
    let slev = game.sp_levchn;
    while (slev) {
        const d = slev.dlevel;
        if (d && d.dnum === lev.dnum && d.dlevel === lev.dlevel) return slev;
        slev = slev.next;
    }
    return null;
}
function in_quest(lev = game.u?.uz) {
    return !!lev && lev.dnum === game.quest_dnum;
}
// is_rogue_level: imported from macros.js
function in_hell(lev = game.u?.uz) {
    const dng = game.dungeons?.[lev?.dnum ?? -1];
    return !!dng?.flags?.hellish;
}
// in_endgame: imported from macros.js as In_endgame
function in_v_tower(lev = game.u?.uz) {
    return !!lev && lev.dnum === (game.tower_dnum ?? -1);
}
function is_oracle_level(lev = game.u?.uz) {
    const oracle = game.oracle_level;
    return !!lev && !!oracle && lev.dnum === oracle.dnum && lev.dlevel === oracle.dlevel;
}
function in_mines(lev = game.u?.uz) {
    return !!lev && lev.dnum === (game.mines_dnum ?? -1);
}
function roguename() {
    const opts = process?.env?.ROGUEOPTS || '';
    if (opts) {
        for (const part of opts.split(',')) {
            if (part.startsWith('name=')) return part.slice(5);
        }
    }
    return rn2(3) ? (rn2(2) ? 'Michael Toy' : 'Kenneth Arnold') : 'Glenn Wichman';
}
// NOTE: equivalent to canonical extralev.js but kept to avoid circular dependency (extralev imports from mklev)
function roguejoin(x1, y1, x2, y2, horiz) {
    let middle;
    if (horiz) {
        middle = x1 + rn2(x2 - x1 + 1);
        for (let x = Math.min(x1, middle); x <= Math.max(x1, middle); x++) corr(x, y1);
        for (let y = Math.min(y1, y2); y <= Math.max(y1, y2); y++) corr(middle, y);
        for (let x = Math.min(middle, x2); x <= Math.max(middle, x2); x++) corr(x, y2);
    } else {
        middle = y1 + rn2(y2 - y1 + 1);
        for (let y = Math.min(y1, middle); y <= Math.max(y1, middle); y++) corr(x1, y);
        for (let x = Math.min(x1, x2); x <= Math.max(x1, x2); x++) corr(x, middle);
        for (let y = Math.min(middle, y2); y <= Math.max(middle, y2); y++) corr(x2, y);
    }
}
async function roguecorr(grid, x, y, dir) {
    const roomAt = (rx, ry) => grid[rx]?.[ry];
    const r = roomAt(x, y);
    if (!r) return;
    let fromx, fromy, tox, toy;
    if (dir === XL_DOWN) {
        r.doortable &= ~XL_DOWN;
        if (!r.real) {
            fromx = r.rlx + 1 + 26 * x;
            fromy = r.rly + 7 * y;
        } else {
            fromx = r.rlx + rn2(r.dx) + 1 + 26 * x;
            fromy = r.rly + r.dy + 7 * y;
            await dodoor(fromx, fromy, game.level.rooms[r.nroom]);
            const loc = game.level?.at(fromx, fromy);
            if (loc) loc.flags = D_NODOOR;
            fromy++;
        }
        if (y >= 2) return;
        y++;
        const r2 = roomAt(x, y);
        if (!r2) return;
        r2.doortable &= ~XL_UP;
        if (!r2.real) {
            tox = r2.rlx + 1 + 26 * x;
            toy = r2.rly + 7 * y;
        } else {
            tox = r2.rlx + rn2(r2.dx) + 1 + 26 * x;
            toy = r2.rly - 1 + 7 * y;
            await dodoor(tox, toy, game.level.rooms[r2.nroom]);
            const loc = game.level?.at(tox, toy);
            if (loc) loc.flags = D_NODOOR;
            toy--;
        }
        roguejoin(fromx, fromy, tox, toy, false);
        return;
    }
    if (dir === XL_RIGHT) {
        r.doortable &= ~XL_RIGHT;
        if (!r.real) {
            fromx = r.rlx + 1 + 26 * x;
            fromy = r.rly + 7 * y;
        } else {
            fromx = r.rlx + r.dx + 1 + 26 * x;
            fromy = r.rly + rn2(r.dy) + 7 * y;
            await dodoor(fromx, fromy, game.level.rooms[r.nroom]);
            const loc = game.level?.at(fromx, fromy);
            if (loc) loc.flags = D_NODOOR;
            fromx++;
        }
        if (x >= 2) return;
        x++;
        const r2 = roomAt(x, y);
        if (!r2) return;
        r2.doortable &= ~XL_LEFT;
        if (!r2.real) {
            tox = r2.rlx + 1 + 26 * x;
            toy = r2.rly + 7 * y;
        } else {
            tox = r2.rlx - 1 + 1 + 26 * x;
            toy = r2.rly + rn2(r2.dy) + 7 * y;
            await dodoor(tox, toy, game.level.rooms[r2.nroom]);
            const loc = game.level?.at(tox, toy);
            if (loc) loc.flags = D_NODOOR;
            tox--;
        }
        roguejoin(fromx, fromy, tox, toy, true);
    }
}
function miniwalk(grid, x, y) {
    while (true) {
        const dirs = [];
        const here = grid[x][y];
        if (x > 0 && !(here.doortable & XL_LEFT)
            && (!grid[x - 1][y].doortable || !rn2(10))) dirs.push(0);
        if (x < 2 && !(here.doortable & XL_RIGHT)
            && (!grid[x + 1][y].doortable || !rn2(10))) dirs.push(1);
        if (y > 0 && !(here.doortable & XL_UP)
            && (!grid[x][y - 1].doortable || !rn2(10))) dirs.push(2);
        if (y < 2 && !(here.doortable & XL_DOWN)
            && (!grid[x][y + 1].doortable || !rn2(10))) dirs.push(3);
        if (!dirs.length) return;
        const dir = dirs[rn2(dirs.length)];
        switch (dir) {
        case 0:
            here.doortable |= XL_LEFT;
            x--;
            grid[x][y].doortable |= XL_RIGHT;
            break;
        case 1:
            here.doortable |= XL_RIGHT;
            x++;
            grid[x][y].doortable |= XL_LEFT;
            break;
        case 2:
            here.doortable |= XL_UP;
            y--;
            grid[x][y].doortable |= XL_DOWN;
            break;
        case 3:
            here.doortable |= XL_DOWN;
            y++;
            grid[x][y].doortable |= XL_UP;
            break;
        default:
            return;
        }
        miniwalk(grid, x, y);
    }
}
// NOTE: differs from canonical extralev.js — local sets smeq, passes grid to roguecorr, different nroom init; also circular dep
// makeroguerooms: imported from extralev.js
// C ref: mklev.c makemaz() routing (script-backed in JS)
async function run_level_script(baseName, slev = null) {
    if (!baseName) return false;
    let scriptName = baseName;
    if (scriptName.startsWith('x-') && game.urole?.filecode) {
        scriptName = `${game.urole.filecode}${scriptName.slice(1)}`;
    }
    reset_des_coder();
    // C ref: mkmaze.c makemaz() picks random variant before Lua init.
    // This is logged as rnd(slev->rndlevs), not rn2()+1.
    if (slev && slev.rndlevs > 0) {
        scriptName = `${baseName}-${rnd(slev.rndlevs)}`;
    }
    // C ref: nhlua.c load_lua() -> nhl_init() loads nhlib.lua into a fresh
    // Lua state for each special-level file. nhlib.lua shuffles 3-entry
    // align[] once at load time, consuming rn2(3), rn2(2).
    // We shuffle an actual array and pass it to generate() so scripts
    // that use align get the pre-shuffled values without re-shuffling.
    // C nhlib.lua initial order: {"law","neutral","chaos"} = [A_LAWFUL, A_NEUTRAL, A_CHAOTIC]
    // The JS shuffle must start with the same order so identical RNG produces identical results.
    const _nhlib_align = [A_LAWFUL, A_NEUTRAL, A_CHAOTIC];
    shuffle(_nhlib_align);
    try {
        const mod = await import(`./levels/${scriptName}.js`);
        if (typeof mod.generate === 'function') {
            const out = mod.generate(_nhlib_align);
            if (out && typeof out.then === 'function') await out;
            await finalize_level();
            if (scriptName === 'minetn-1' && In_mines(game.u?.uz)) {
                // C ref: mkmaze.c:712 check_ransacked — set ransacked flag
                game.ransacked = 1;
                await stolen_booty();
            }
            // C ref: sp_lev.c:6058 — C fills special rooms here AND again
            // in makelevel's post-loop. Skipping first fill here for now
            // because the double-fill produces extra RNG. The makelevel
            // loop at the bottom handles it.
            return true;
        }
    } catch (err) {
        if (process?.env?.DEBUG_LEVEL_SCRIPT_FAIL === '1')
            console.error(`[run_level_script] ${scriptName} failed: ${err?.message || err}`);
        return false;
    }
    return false;
}
// C ref: mklev.c:1241 makelevel()
// Master level generation function.
async function makelevel() {
    const g = game;
    // C: oinit() — reassign level-dependent object probabilities
    oinit();
    // C: clear_level_structures()
    clear_level_structures();
    const slev = is_special_level(g.u?.uz);
    const dng = g.dungeons?.[g.u?.uz?.dnum ?? 0];
    const medusa = g.medusa_level;
    let generatedSpecial = false;
    let wantMazeFallback = false;
    // C ref: mklev.c makelevel() branch ordering.
    if (slev && !is_rogue_level(g.u?.uz)) {
        // s_level.flags.align in C is derived from dungeon flags.
        // JS keeps a compatible fallback on the dungeon metadata.
        g.special_level_align = slev.flags?.align ?? dng?.flags?.align ?? 0;
        if (await run_level_script(slev.proto, slev)) generatedSpecial = true;
    } else if (dng?.proto && dng.proto.length > 0) {
        g.special_level_align = dng?.flags?.align ?? 0;
        if (await run_level_script(dng.proto, null)) generatedSpecial = true;
    } else if (dng?.fill_lvl && dng.fill_lvl.length > 0) {
        g.special_level_align = dng?.flags?.align ?? 0;
        if (await run_level_script(dng.fill_lvl, null)) generatedSpecial = true;
    } else if (in_quest(g.u?.uz)) {
        const roleCode = g.urole?.filecode ?? '';
        const loca = find_level(`${roleCode}-loca`);
        const side = ((g.u?.uz?.dlevel ?? 1) < (loca?.dlevel?.dlevel ?? 1)) ? 'a' : 'b';
        g.special_level_align = dng?.flags?.align ?? 0;
        if (await run_level_script(`${roleCode}-fil${side}`, null)) generatedSpecial = true;
    } else if (in_hell(g.u?.uz)
        || (rn2(5)
            && g.u?.uz?.dnum === medusa?.dnum
            && (g.u?.uz?.dlevel ?? 1) > (medusa?.dlevel ?? 999))) {
        g.special_level_align = dng?.flags?.align ?? 0;
        if (await run_level_script(dng?.proto || '', null)) generatedSpecial = true;
        else wantMazeFallback = true;
    }
    // C ref: mkmaze.c:698-699 — Mine Town marks has_town during makemaz,
    // before makelevel() performs fill_special_room() passes.
    if (slev?.flags?.town)
        g.level.flags.has_town = true;
    // C ref: mkmaze.c:1196-1222 — non-special maze levels (Gehennom, below Medusa)
    // When in_hell() or below-Medusa and no level script loaded, generate maze.
    if (!generatedSpecial && wantMazeFallback) {
        await makemaz_empty();
        generatedSpecial = true;
    }
    if (!generatedSpecial) {
        // --- Regular level generation ---
        const rogueLevel = is_rogue_level(g.u?.uz);
        g.level.flags.is_rogue = !!rogueLevel;
        if (rogueLevel) {
            await makeroguerooms();
            await makerogueghost();
        } else {
            await makerooms();
        }
    if (g.level.nroom <= 0) {
        // Fallback: create at least one room
        // This shouldn't happen but prevents crashes
        return;
    }
    sort_rooms();
    await generate_stairs();
    // C ref: mklev.c:1295 — check for dungeon branch on this level
    const branchp = is_branchlev();
    let room_threshold = branchp ? 4 : 3;
    if (!rogueLevel) {
        await makecorridors();
        await make_niches();
        // C ref: mklev.c:1306-1332 — create secret vault and fill with gold
        if (g.vault_x !== -1) {
            const vw = { v: 1 }, vh = { v: 1 };
            const vx = { v: g.vault_x }, vy = { v: g.vault_y };
            if (check_room(vx, vw, vy, vh, true)) {
                // Vault room created — add it and fill with gold
                add_room(vx.v, vy.v, vx.v + vw.v, vy.v + vh.v, true, VAULT, false);
                g.level.flags.has_vault = true; // C: svl.level.flags.has_vault = 1
                room_threshold++;
                const vaultRoom = g.level.rooms[g.level.nroom - 1];
                if (vaultRoom) {
                    vaultRoom.needfill = FILL_NORMAL;
                    // C ref: sp_lev.c:2761-2764 fill_special_room for VAULT
                    await fill_special_room(vaultRoom); // fill vault with gold NOW
                    // C fills vault TWICE: once here, once in the later
                    // fill_special_room loop. The second fill consumes rn2(100)
                    // per tile (from mkgold/rn1) but adds to existing gold.
                    // Keep needfill=FILL_NORMAL so the loop refills.
                }
                // C: mk_knox_portal(vault_x + w, vault_y + h)
                // mk_knox_portal checks Is_branchlev (early return) then
                // consumes rn2(3) only when floating source is still unset.
                await mk_knox_portal(vx.v + vw.v, vy.v + vh.v);
                // C: if (!level.flags.noteleport && !rn2(3)) makevtele()
                if (!g.level.flags.noteleport && !rn2(3)) {
                    // C ref: mklev.c:811 makevtele() = makeniche(TELEP_TRAP)
                    await makeniche(15); // TELEP_TRAP = 15
                }
            } else if (rnd_rect()) {
                // Fallback: try creating vault via rectangle allocator
                if (create_vault()) {
                    // Second chance at placing vault
                    const vr = g.level.rooms[g.level.nroom];
                    if (vr) {
                        const vx2 = { v: vr.lx }, vw2 = { v: 1 };
                        const vy2 = { v: vr.ly }, vh2 = { v: 1 };
                        if (check_room(vx2, vw2, vy2, vh2, true)) {
                            add_room(vx2.v, vy2.v, vx2.v + vw2.v, vy2.v + vh2.v,
                                true, VAULT, false);
                            g.level.flags.has_vault = true;
                            room_threshold++;
                            const vaultRoom = g.level.rooms[g.level.nroom - 1];
                            if (vaultRoom) {
                                vaultRoom.needfill = FILL_NORMAL;
                                await fill_special_room(vaultRoom);
                            }
                            // C ref: mklev.c fill_vault label — both primary and
                            // fallback vault creation paths call mk_knox_portal()
                            // before makevtele().
                            await mk_knox_portal(vx2.v + vw2.v, vy2.v + vh2.v);
                            if (!g.level.flags.noteleport && !rn2(3)) { await makeniche(15); /* TELEP_TRAP */ }
                        } else {
                            if (g.level.rooms[g.level.nroom]) g.level.rooms[g.level.nroom].hx = -1;
                        }
                    }
                }
            }
        }
        // C ref: mklev.c:1355-1383 — special room type selection
        const uz = g.u?.uz;
        const u_depth = ((g.dungeons?.[uz?.dnum ?? 0]?.depth_start ?? 1)
            + (uz?.dlevel ?? 1) - 1);
        const medusa = g.medusa_level;
        const medusa_depth = medusa
            ? ((g.dungeons?.[medusa.dnum ?? 0]?.depth_start ?? 1)
                + (medusa.dlevel ?? 1) - 1)
            : Number.POSITIVE_INFINITY;
        const hasShoptypeEnv = (typeof process !== 'undefined' && process?.env
            && Object.prototype.hasOwnProperty.call(process.env, 'SHOPTYPE'));
        if (g.flags?.debug && hasShoptypeEnv) await do_mkroom(SHOPBASE);
        else if (u_depth > 1 && u_depth < medusa_depth
            && g.level.nroom >= room_threshold && rn2(u_depth) < 3) await do_mkroom(SHOPBASE);
        else if (u_depth > 4 && !rn2(6)) await do_mkroom(COURT);
        else if (u_depth > 5 && !rn2(8)
            && !((g.mvitals?.[PM_LEPRECHAUN]?.mvflags ?? 0) & G_GONE)) await do_mkroom(LEPREHALL);
        else if (u_depth > 6 && !rn2(7)) await do_mkroom(ZOO);
        else if (u_depth > 8 && !rn2(5)) await do_mkroom(TEMPLE);
        else if (u_depth > 9 && !rn2(5)
            && !((g.mvitals?.[PM_KILLER_BEE]?.mvflags ?? 0) & G_GONE)) await do_mkroom(BEEHIVE);
        else if (u_depth > 11 && !rn2(6)) await do_mkroom(MORGUE);
        else if (u_depth > 12 && !rn2(8) && antholemon()) await do_mkroom(ANTHOLE);
        else if (u_depth > 14 && !rn2(4)
            && !((g.mvitals?.[PM_SOLDIER]?.mvflags ?? 0) & G_GONE)) await do_mkroom(BARRACKS);
        else if (u_depth > 15 && !rn2(6)) await do_mkroom(SWAMP);
        else if (u_depth > 16 && !rn2(8)
            && !((g.mvitals?.[PM_COCKATRICE]?.mvflags ?? 0) & G_GONE)) await do_mkroom(COCKNEST);
    }
        // C ref: mklev.c:1370 — place dungeon branch (Mines entrance on level 1)
        if (branchp) {
            const prevstairs = g.stairs;
            await place_branch(branchp);
            if (g.u?.uz?.dnum === 0 && g.u?.uz?.dlevel === 1 && g.stairs !== prevstairs && g.stairs) {
                g.stairs.u_traversed = true;
            }
        }
        // C ref: mklev.c:1391 — choose bonus item room
        let fillable_room_count = 0;
        for (let i = 0; i < g.level.nroom; i++) {
            const rm = g.level.rooms[i];
            if (rm && rm.hx > 0
                && (rm.rtype === OROOM || rm.rtype === THEMEROOM)
                && rm.needfill === FILL_NORMAL)
                fillable_room_count++;
        }
        const bonus_item_room_countdown = fillable_room_count
            ? rn2(fillable_room_count) : -1;
        // C ref: mklev.c:1394-1402 — fill rooms with contents
        let bonus_countdown = bonus_item_room_countdown;
        for (let i = 0; i < g.level.nroom; i++) {
            const rm = g.level.rooms[i];
            if (!rm || rm.hx <= 0) continue;
            const fillable = (rm.rtype === OROOM || rm.rtype === THEMEROOM)
                              && rm.needfill === FILL_NORMAL;
            await fill_ordinary_room(rm, fillable && bonus_countdown === 0);
            if (fillable) bonus_countdown--;
        }
    }
    // C ref: mklev.c:1416 — fill special rooms (shops, zoos, temples, etc.)
    // This runs for ALL levels including special ones.
    // Comment in C: "Fill all special rooms now, regardless of whether this
    // is a special level, proto level, or ordinary level."
    for (let i = 0; i < g.level.nroom; i++) {
        await fill_special_room(g.level.rooms[i]);
    }
    // C ref: mklev.c:1192-1198 — run theme room post-level-generate
    // callbacks. In C, this calls post_level_generate() from the Lua
    // themerms state, which iterates the postprocess table (engraving
    // placement, wall conversion, trap creation, etc.).
    // This must run AFTER fill_special_room, BEFORE wallification.
    const dnum = g.u?.uz?.dnum ?? 0;
    if (g._luathemes_loaded?.[dnum]) {
        await themerooms_post_level_generate();
        wallification(1, 0, COLNO - 1, ROWNO - 1);
    }
}
// C ref: mklev.c — clear_level_structures()
function clear_level_structures() {
    const g = game;
    // C ref: clear_level_structures() resets level-linked chains.
    // Keep fmon scoped to the level being generated.
    g.fmon = null;
    g.level = new GameMap();
    g.level.nroom = 0;
    g.level.rooms = [];
    g.subrooms = [];
    g.made_branch = false;
    g.smeq = new Array(MAXNROFROOMS + 1).fill(0);
    g.level.doorindex = 0;
    g.level.doors = [];
    g.stairs = null;
    g.vault_x = -1;
    // C ref: mklev.c clear_level_structures() level.flags defaults.
    const lf = g.level.flags;
    lf.nfountains = 0;
    lf.nsinks = 0;
    lf.has_shop = false;
    lf.has_vault = false;
    lf.has_zoo = false;
    lf.has_court = false;
    lf.has_morgue = false;
    lf.graveyard = false;
    lf.has_beehive = false;
    lf.has_barracks = false;
    lf.has_temple = false;
    lf.has_swamp = false;
    lf.noteleport = false;
    lf.hardfloor = false;
    lf.nommap = false;
    lf.hero_memory = true;
    lf.shortsighted = false;
    lf.sokoban_rules = false;
    lf.is_maze_lev = false;
    lf.is_cavernous_lev = false;
    lf.arboreal = false;
    lf.has_town = false;
    lf.wizard_bones = false;
    lf.corrmaze = false;
    lf.temperature = in_hell(g.u?.uz) ? 1 : 0;
    lf.rndmongen = true;
    lf.deathdrops = true;
    lf.noautosearch = false;
    lf.fumaroles = false;
    lf.stormy = false;
    lf.stasis_until = 0;
    init_rect();
}
// C ref: mklev.c:356 makerooms()
// Place rooms using the rectangle allocator.
// RNG: extensive — room dimensions, positions, vault decision.
async function makerooms() {
    const g = game;
    let tried_vault = false;
    // C ref: mklev.c:365-380 — load themerms.lua for themed rooms
    // Loading a Lua file via nhl_init triggers nhlib.lua which shuffles
    // the align[] array — 2 core RNG calls (rn2(3), rn2(2)).
    // This only happens ONCE per dungeon branch (C caches in luathemes[dnum]).
    const dnum = g.u?.uz?.dnum ?? 0;
    if (dnum === 0 && !g._luathemes_loaded) {
        g._luathemes_loaded = {};
    }
    if (dnum === 0 && !g._luathemes_loaded?.[dnum]) {
        // nhlib.lua shuffle when loading themerms.lua (first level of branch).
        // Preserve both RNG consumption and the resulting align[] permutation.
        const themedAlign = ['law', 'neutral', 'chaos'];
        for (let i = themedAlign.length; i > 1; i--) {
            const j = rn2(i);
            [themedAlign[i - 1], themedAlign[j]] = [themedAlign[j], themedAlign[i - 1]];
        }
        g._luathemes_align = g._luathemes_align || {};
        g._luathemes_align[dnum] = themedAlign;
        if (g._luathemes_loaded) g._luathemes_loaded[dnum] = true;
    }
    // C ref: mklev.c:382-388 — pre_themerooms_generate (no RNG calls)
    const hasThemes = (dnum === 0);
    // C ref: mklev.c uses level_difficulty() for theme room selection,
    // which is based on depth() not raw dlevel.
    const difficulty = depth_of_level(g.u?.uz);
    let themeroom_tries = 0;
    // Make rooms until satisfied or no more space
    while (g.level.nroom < (MAXNROFROOMS - 1) && rnd_rect()) {
        if (g.level.nroom >= Math.trunc(MAXNROFROOMS / 6) && rn2(2) && !tried_vault) {
            tried_vault = true;
            if (create_vault()) {
                g.vault_x = g.level.rooms[g.level.nroom]?.lx ?? -1;
                g.vault_y = g.level.rooms[g.level.nroom]?.ly ?? -1;
                // mark as unused
                if (g.level.rooms[g.level.nroom]) g.level.rooms[g.level.nroom].hx = -1;
            }
        } else {
            if (hasThemes) {
                // C ref: mklev.c:402-411 — call themerooms_generate()
                if (!(await themerooms_generate(difficulty))) {
                    // C uses post-increment: themeroom_tries++ > 10
                    if (themeroom_tries++ > 10
                        || g.level.nroom >= Math.trunc(MAXNROFROOMS / 6))
                        break;
                }
            } else {
                if (!create_room(-1, -1, -1, -1, -1, -1, OROOM, -1))
                    break;
            }
        }
    }
}
// C ref: mkmap.c:443 litstate_rnd()
// RNG: rnd() and rn2(77) when litstate < 0
function litstate_rnd(litstate) {
    if (litstate < 0) {
        // C ref: mkmap.c:446 — uses depth(&u.uz), not dlevel.
        // depth() accounts for the dungeon's depth_start offset.
        const uz = game.u?.uz;
        const d = depth_of_level(uz);
        return (rnd(1 + Math.abs(d)) < 11 && rn2(77)) ? true : false;
    }
    return !!litstate;
}
function isSolidTile(x, y) {
    if (!isok(x, y)) return true;
    const typ = game.level?.at(x, y)?.typ ?? STONE;
    return IS_STWALL(typ);
}
function isWallOrStone(x, y) {
    if (!isok(x, y)) return 1;
    const typ = game.level?.at(x, y)?.typ ?? STONE;
    return (typ === STONE || isWallTile(x, y)) ? 1 : 0;
}
function isWallTile(x, y) {
    if (!isok(x, y)) return 0;
    const typ = game.level?.at(x, y)?.typ ?? STONE;
    return (IS_WALL(typ) || IS_DOOR(typ) || typ === LAVAWALL
        || typ === WATER || typ === SDOOR || typ === IRONBARS) ? 1 : 0;
}
function extend_spine(locale, wall_there, dx, dy) {
    const nx = 1 + dx;
    const ny = 1 + dy;
    if (!wall_there) return 0;
    if (dx) {
        if (locale[1][0] && locale[1][2] && locale[nx][0] && locale[nx][2]) {
            return 0;
        }
        return 1;
    }
    if (locale[0][1] && locale[2][1] && locale[0][ny] && locale[2][ny]) {
        return 0;
    }
    return 1;
}
export function wall_cleanup(x1, y1, x2, y2) {
    const map = game.level;
    if (!map) return;
    for (let x = x1; x <= x2; x++) {
        for (let y = y1; y <= y2; y++) {
            const loc = map.at(x, y);
            const typ = loc?.typ ?? STONE;
            if (!(IS_WALL(typ) && typ !== DBWALL)) continue;
            if (isSolidTile(x - 1, y - 1) && isSolidTile(x - 1, y)
                && isSolidTile(x - 1, y + 1) && isSolidTile(x, y - 1)
                && isSolidTile(x, y + 1) && isSolidTile(x + 1, y - 1)
                && isSolidTile(x + 1, y) && isSolidTile(x + 1, y + 1)) {
                loc.typ = STONE;
            }
        }
    }
}
function fix_wall_spines(x1, y1, x2, y2) {
    const spineArray = [VWALL, HWALL, HWALL, HWALL,
        VWALL, TRCORNER, TLCORNER, TDWALL,
        VWALL, BRCORNER, BLCORNER, TUWALL,
        VWALL, TLWALL, TRWALL, CROSSWALL];
    const map = game.level;
    if (!map) return;
    for (let x = x1; x <= x2; x++) {
        for (let y = y1; y <= y2; y++) {
            const loc = map.at(x, y);
            const typ = loc?.typ ?? STONE;
            if (!(IS_WALL(typ) && typ !== DBWALL)) continue;
            const locale = [
                [isWallOrStone(x - 1, y - 1), isWallOrStone(x - 1, y), isWallOrStone(x - 1, y + 1)],
                [isWallOrStone(x, y - 1), 0, isWallOrStone(x, y + 1)],
                [isWallOrStone(x + 1, y - 1), isWallOrStone(x + 1, y), isWallOrStone(x + 1, y + 1)],
            ];
            const bits = (extend_spine(locale, isWallTile(x, y - 1), 0, -1) << 3)
                | (extend_spine(locale, isWallTile(x, y + 1), 0, 1) << 2)
                | (extend_spine(locale, isWallTile(x + 1, y), 1, 0) << 1)
                | extend_spine(locale, isWallTile(x - 1, y), -1, 0);
            if (bits) loc.typ = spineArray[bits];
        }
    }
}
export function wallification(x1, y1, x2, y2) {
    wall_cleanup(x1, y1, x2, y2);
    fix_wall_spines(x1, y1, x2, y2);
}
// C ref: sp_lev.c:1407 check_room()
// Validates room placement, shrinking if necessary. RNG: rn2(3) per overlap.
function check_room(lowx, ddx, lowy, ddy, vault) {
    const XLIM = 4, YLIM = 3;
    const map = game.level;
    let hix = lowx.v + ddx.v, hiy = lowy.v + ddy.v;
    const xlim = XLIM + (vault ? 1 : 0);
    const ylim = YLIM + (vault ? 1 : 0);
    const s_lowx = lowx.v, s_ddx = ddx.v;
    const s_lowy = lowy.v, s_ddy = ddy.v;
    if (lowx.v < 3) lowx.v = 3;
    if (lowy.v < 2) lowy.v = 2;
    if (hix > COLNO - 3) hix = COLNO - 3;
    if (hiy > ROWNO - 3) hiy = ROWNO - 3;
    for (;;) { // chk label
        if (hix <= lowx.v || hiy <= lowy.v) return false;
        if (game.in_mk_themerooms
            && s_lowx !== lowx.v && s_ddx !== ddx.v
            && s_lowy !== lowy.v && s_ddy !== ddy.v) {
            return false;
        }
        let retry = false;
        for (let x = lowx.v - xlim; x <= hix + xlim && !retry; x++) {
            if (x <= 0 || x >= COLNO) continue;
            let y = Math.max(lowy.v - ylim, 0);
            const ymax = Math.min(hiy + ylim, ROWNO - 1);
            for (; y <= ymax; y++) {
                const loc = map.at(x, y);
                if (loc && loc.typ !== STONE) {
                    if (!rn2(3)) return false;
                    if (game.in_mk_themerooms) return false;
                    if (x < lowx.v) lowx.v = x + xlim + 1;
                    else hix = x - xlim - 1;
                    if (y < lowy.v) lowy.v = y + ylim + 1;
                    else hiy = y - ylim - 1;
                    retry = true;
                    break;
                }
            }
        }
        if (!retry) break;
    }
    ddx.v = hix - lowx.v;
    ddy.v = hiy - lowy.v;
    if (game.in_mk_themerooms
        && s_lowx !== lowx.v && s_ddx !== ddx.v
        && s_lowy !== lowy.v && s_ddy !== ddy.v) {
        return false;
    }
    return true;
}
// C ref: sp_lev.c:1486 create_room()
// Faithful port of the C room creation function.
// RNG: rnd_rect, rn2 for dimensions/position, litstate_rnd, check_room
// _suppressMidlog: themed room calls suppress >create_room midlog
// because C's themed path doesn't go through the midlog-wrapped create_room
export function create_room(x, y, w, h, xal, yal, rtype, rlit, _suppressMidlog) {
    if (!_suppressMidlog) pushRngLogEntry('>create_room');
    const result = _create_room_impl(x, y, w, h, xal, yal, rtype, rlit);
    if (!_suppressMidlog) pushRngLogEntry(`<create_room=${result ? 1 : 0}`);
    return result;
}
function _create_room_impl(x, y, w, h, xal, yal, rtype, rlit) {
    const g = game;
    const XLIM = 4, YLIM = 3;
    const SPLEV_LEFT = 1;
    const SPLEV_CENTER = 3;
    const SPLEV_RIGHT = 5;
    const TOP = 1;
    const BOTTOM = 5;
    let xabs = 0, yabs = 0;
    let r1 = null, r2 = null;
    let wtmp, htmp;
    let trycnt = 0;
    let vault = false;
    let xlim = XLIM, ylim = YLIM;
    if (rtype === -1) rtype = OROOM;
    if (rtype === VAULT) {
        vault = true;
        xlim++;
        ylim++;
    }
    // Lighting state — RNG if rlit < 0
    rlit = litstate_rnd(rlit);
    do {
        wtmp = w; htmp = h;
        let xtmp = x, ytmp = y;
        let xaltmp = xal, yaltmp = yal;
        // Totally random room (all params -1) or vault
        if ((xtmp < 0 && ytmp < 0 && wtmp < 0 && xaltmp < 0 && yaltmp < 0)
            || vault) {
            r1 = rnd_rect();
            if (!r1) return false;
            const hx = r1.hx, hy = r1.hy, lx = r1.lx, ly = r1.ly;
            let dx, dy;
            if (vault) {
                dx = dy = 1;
            } else {
                dx = 2 + rn2((hx - lx > 28) ? 12 : 8);
                dy = 2 + rn2(4);
                if (dx * dy > 50)
                    dy = Math.trunc(50 / dx);
            }
            const xborder = (lx > 0 && hx < COLNO - 1) ? 2 * xlim : xlim + 1;
            const yborder = (ly > 0 && hy < ROWNO - 1) ? 2 * ylim : ylim + 1;
            if (hx - lx < dx + 3 + xborder || hy - ly < dy + 3 + yborder) {
                r1 = null;
                continue;
            }
            xabs = lx + (lx > 0 ? xlim : 3)
                   + rn2(hx - (lx > 0 ? lx : 3) - dx - xborder + 1);
            yabs = ly + (ly > 0 ? ylim : 2)
                   + rn2(hy - (ly > 0 ? ly : 2) - dy - yborder + 1);
            if (ly === 0 && hy >= ROWNO - 1
                && (!g.level.nroom || !rn2(g.level.nroom))
                && (yabs + dy > Math.trunc(ROWNO / 2))) {
                yabs = rn1(3, 2);
                if (g.level.nroom < 4 && dy > 1)
                    dy--;
            }
            const lowx = { v: xabs }, ddx = { v: dx };
            const lowy = { v: yabs }, ddy = { v: dy };
            if (!check_room(lowx, ddx, lowy, ddy, vault)) {
                r1 = null;
                continue;
            }
            xabs = lowx.v;
            yabs = lowy.v;
            wtmp = ddx.v + 1;
            htmp = ddy.v + 1;
            r2 = { lx: xabs - 1, ly: yabs - 1,
                   hx: xabs + wtmp, hy: yabs + htmp };
        } else {
            let rndpos = 0;
            let dx, dy;
            if (xtmp < 0 && ytmp < 0) {
                xtmp = rnd(5);
                ytmp = rnd(5);
                rndpos = 1;
            }
            if (wtmp < 0 || htmp < 0) {
                wtmp = rn1(15, 3);
                htmp = rn1(8, 2);
            }
            if (xaltmp === -1) xaltmp = rnd(3);
            if (yaltmp === -1) yaltmp = rnd(3);
            xabs = (Math.trunc(((xtmp - 1) * COLNO) / 5)) + 1;
            yabs = (Math.trunc(((ytmp - 1) * ROWNO) / 5)) + 1;
            switch (xaltmp) {
            case SPLEV_LEFT:
                break;
            case SPLEV_RIGHT:
                xabs += Math.trunc(COLNO / 5) - wtmp;
                break;
            case SPLEV_CENTER:
                xabs += Math.trunc((Math.trunc(COLNO / 5) - wtmp) / 2);
                break;
            }
            switch (yaltmp) {
            case TOP:
                break;
            case BOTTOM:
                yabs += Math.trunc(ROWNO / 5) - htmp;
                break;
            case SPLEV_CENTER:
                yabs += Math.trunc((Math.trunc(ROWNO / 5) - htmp) / 2);
                break;
            }
            if (xabs + wtmp - 1 > COLNO - 2) xabs = COLNO - wtmp - 3;
            if (xabs < 2) xabs = 2;
            if (yabs + htmp - 1 > ROWNO - 2) yabs = ROWNO - htmp - 3;
            if (yabs < 2) yabs = 2;
            r2 = {
                lx: xabs - 1,
                ly: yabs - 1,
                hx: xabs + wtmp + rndpos,
                hy: yabs + htmp + rndpos,
            };
            r1 = get_rect(r2);
            dx = wtmp;
            dy = htmp;
            if (r1) {
                const lowx = { v: xabs }, ddx = { v: dx };
                const lowy = { v: yabs }, ddy = { v: dy };
                if (!check_room(lowx, ddx, lowy, ddy, vault)) {
                    r1 = null;
                } else {
                    xabs = lowx.v;
                    yabs = lowy.v;
                }
            }
        }
    } while (++trycnt <= 100 && !r1);
    if (!r1) return false;
    // C ref: sp_lev.c:1650 — split AFTER the loop, using r1 from rnd_rect
    // CRITICAL: use r1 (the rect from rnd_rect), NOT get_rect(r2).
    // get_rect may return a different containing rect when multiple rects
    // contain r2, causing incorrect splits.
    split_rects(r1, r2);
    if (!vault) {
        g.smeq[g.level.nroom] = g.level.nroom;
        add_room(xabs, yabs, xabs + wtmp - 1, yabs + htmp - 1,
                 rlit, rtype, false);
    } else {
        // Vault: just record position, don't create full room
        if (!g.level.rooms[g.level.nroom]) g.level.rooms[g.level.nroom] = {};
        g.level.rooms[g.level.nroom].lx = xabs;
        g.level.rooms[g.level.nroom].ly = yabs;
    }
    return true;
}
// C ref: mklev.c — create_vault() (macro: create_room(-1, -1, 2, 2, -1, -1, VAULT, TRUE))
function create_vault() {
    return create_room(-1, -1, 2, 2, -1, -1, VAULT, true);
}
 
// C ref: mklev.c:303 add_room()
export function add_room(lowx, lowy, hix, hiy, lit, rtype, special) {
    const g = game;
    const croom = {
        lx: lowx, ly: lowy, hx: hix, hy: hiy,
        rtype, rlit: lit ? 1 : 0,
        doorct: 0, fdoor: g.level.doorindex,
        irregular: false, needjoining: !special,
        nsubrooms: 0, sbrooms: [],
        roomnoidx: g.level.nroom,
        needfill: 0,
    };
    // Draw the room on the map
    do_room_or_subroom(croom, lowx, lowy, hix, hiy, lit, rtype, special, true);
    g.level.rooms[g.level.nroom] = croom;
    g.level.nroom++;
    // Sentinel
    if (g.level.nroom < MAXNROFROOMS) {
        g.level.rooms[g.level.nroom] = { hx: -1 };
    }
}
// C ref: mklev.c:1597 topologize()
export function topologize(croom) {
    if (!croom || croom.irregular) return;
    const roomno = (croom.roomnoidx ?? -1) + ROOMOFFSET;
    const lowx = croom.lx, lowy = croom.ly;
    const hix = croom.hx, hiy = croom.hy;
    if (!game.level || roomno < ROOMOFFSET) return;
    if ((game.level.at(lowx, lowy)?.roomno ?? 0) === roomno) return;
    for (let x = lowx; x <= hix; x++) {
        for (let y = lowy; y <= hiy; y++) {
            const loc = game.level.at(x, y);
            if (!loc) continue;
            loc.roomno = roomno;
        }
    }
    for (let x = lowx - 1; x <= hix + 1; x++) {
        for (let y = lowy - 1; y <= hiy + 1; y += (hiy - lowy + 2)) {
            const loc = game.level.at(x, y);
            if (!loc) continue;
            loc.edge = true;
            loc.roomno = loc.roomno ? SHARED : roomno;
        }
    }
    for (let x = lowx - 1; x <= hix + 1; x += (hix - lowx + 2)) {
        for (let y = lowy; y <= hiy; y++) {
            const loc = game.level.at(x, y);
            if (!loc) continue;
            loc.edge = true;
            loc.roomno = loc.roomno ? SHARED : roomno;
        }
    }
    for (const subroom of croom.sbrooms || []) {
        if (subroom) topologize(subroom);
    }
}
// C ref: mklev.c:230 do_room_or_subroom()
function do_room_or_subroom(croom, lowx, lowy, hix, hiy, lit, _rtype, special, is_room) {
    const g = game;
    const map = g.level;
    // Clamp to bounds
    if (!lowx) lowx++;
    if (!lowy) lowy++;
    if (hix >= COLNO - 1) hix = COLNO - 2;
    if (hiy >= ROWNO - 1) hiy = ROWNO - 2;
    // Lighting
    if (lit) {
        for (let x = lowx - 1; x <= hix + 1; x++)
            for (let y = Math.max(lowy - 1, 0); y <= hiy + 1; y++)
                if (map.at(x, y)) map.at(x, y).lit = true;
        croom.rlit = 1;
    } else {
        croom.rlit = 0;
    }
    croom.lx = lowx;
    croom.hx = hix;
    croom.ly = lowy;
    croom.hy = hiy;
    croom.rtype = _rtype;
    croom.doorct = 0;
    croom.fdoor = game.level.doorindex;
    croom.irregular = false;
    croom.nsubrooms = 0;
    croom.sbrooms = [];
    if (!special) {
        croom.needjoining = true;
        // C ref: mklev.c:277-299 do_room_or_subroom()
        // Only set typ and horizontal here. roomno and edge are set
        // later by topologize() in level_finalize_topology().
        for (let x = lowx - 1; x <= hix + 1; x++)
            for (let y = lowy - 1; y <= hiy + 1; y += (hiy - lowy + 2)) {
                const loc = map.at(x, y);
                if (loc) {
                    loc.typ = HWALL;
                    loc.horizontal = true;
                }
            }
        for (let x = lowx - 1; x <= hix + 1; x += (hix - lowx + 2))
            for (let y = lowy; y <= hiy; y++) {
                const loc = map.at(x, y);
                if (loc) {
                    loc.typ = VWALL;
                    loc.horizontal = false;
                }
            }
        for (let x = lowx; x <= hix; x++)
            for (let y = lowy; y <= hiy; y++) {
                const loc = map.at(x, y);
                if (loc) {
                    loc.typ = ROOM;
                }
            }
        if (is_room) {
            const tl = map.at(lowx - 1, lowy - 1);
            const tr = map.at(hix + 1, lowy - 1);
            const bl = map.at(lowx - 1, hiy + 1);
            const br = map.at(hix + 1, hiy + 1);
            if (tl) tl.typ = TLCORNER;
            if (tr) tr.typ = TRCORNER;
            if (bl) bl.typ = BLCORNER;
            if (br) br.typ = BRCORNER;
        } else {
            wallification(lowx - 1, lowy - 1, hix + 1, hiy + 1);
        }
    }
}
// C ref: sp_lev.c:create_subroom() + mklev.c:add_subroom()
export function create_subroom(proom, x, y, w, h, rtype, rlit) {
    if (!proom) return false;
    if ((proom.nsubrooms ?? 0) >= MAX_SUBROOMS) {
        throw new Error('room has too many subrooms');
    }
    const width = proom.hx - proom.lx + 1;
    const height = proom.hy - proom.ly + 1;
    if (width < 4 || height < 4) {
        return false;
    }
    if (w === -1) w = rnd(width - 3);
    if (h === -1) h = rnd(height - 3);
    if (x === -1) x = rnd(width - w);
    if (y === -1) y = rnd(height - h);
    if (x === 1) x = 0;
    if (y === 1) y = 0;
    if ((x + w + 1) === width) x++;
    if ((y + h + 1) === height) y++;
    if (rtype === -1) rtype = OROOM;
    rlit = litstate_rnd(rlit);
    const lowx = proom.lx + x;
    const lowy = proom.ly + y;
    const hix = lowx + w - 1;
    const hiy = lowy + h - 1;
    if (!Array.isArray(game.subrooms)) game.subrooms = [];
    const subroom = {
        lx: lowx, ly: lowy, hx: hix, hy: hiy,
        rtype, rlit,
        doorct: 0, fdoor: game.level.doorindex,
        irregular: false, needjoining: true,
        nsubrooms: 0, sbrooms: [],
        // C ref: topologize() uses (subroom_ptr - svr.rooms) + ROOMOFFSET.
        // In the C data layout, first subroom maps to MAXNROFROOMS + 1.
        roomnoidx: (MAXNROFROOMS + 1) + game.subrooms.length,
        needfill: 0,
    };
    do_room_or_subroom(subroom, lowx, lowy, hix, hiy, rlit, rtype, false, false);
    proom.sbrooms.push(subroom);
    proom.nsubrooms = proom.sbrooms.length;
    game.subrooms.push(subroom);
    return true;
}
// C ref: mklev.c:209 sort_rooms()
function sort_rooms() {
    const g = game;
    const n = g.level.nroom;
    const oldToNew = new Array(n).fill(0);
    const liveRooms = g.level.rooms.slice(0, n)
        .sort((a, b) => (a?.lx || 0) - (b?.lx || 0));
    g.level.rooms = liveRooms;
    if (n < MAXNROFROOMS) {
        g.level.rooms[n] = { hx: -1 };
    }
    // Update roomnoidx after sort
    for (let i = 0; i < n; i++) {
        if (g.level.rooms[i]) {
            oldToNew[g.level.rooms[i].roomnoidx] = i;
            g.level.rooms[i].roomnoidx = i;
        }
    }
    // Update map roomno values to match the new left-to-right room order.
    for (let x = 1; x < COLNO; x++) {
        for (let y = 0; y < ROWNO; y++) {
            const loc = g.level.at(x, y);
            const rno = loc?.roomno ?? 0;
            if (rno >= ROOMOFFSET && rno < MAXNROFROOMS + 1) {
                loc.roomno = oldToNew[rno - ROOMOFFSET] + ROOMOFFSET;
            }
        }
    }
}
// C ref: mklev.c:72 good_rm_wall_doorpos()
function good_rm_wall_doorpos(x, y, dir, room) {
    const g = game;
    const map = g.level;
    const rmno = g.level.rooms.indexOf(room) + ROOMOFFSET;
    if (!isok(x, y) || !room.needjoining) return false;
    const loc = map.at(x, y);
    if (!loc) return false;
    if (!(loc.typ === HWALL || loc.typ === VWALL || IS_DOOR(loc.typ) || loc.typ === SDOOR))
        return false;
    if (bydoor(x, y)) return false;
    const tx = x + xdir[dir], ty = y + ydir[dir];
    if (!isok(tx, ty)) return false;
    const tloc = map.at(tx, ty);
    if (!tloc || IS_OBSTRUCTED(tloc.typ)) return false;
    if (rmno !== tloc.roomno) return false;
    return true;
}
// C ref: mklev.c:105 finddpos_shift()
function finddpos_shift(xp, yp, dir, aroom) {
    const rdir = DIR_180(dir);
    const dx = xdir[rdir], dy = ydir[rdir];
    if (good_rm_wall_doorpos(xp.v, yp.v, rdir, aroom))
        return true;
    if (aroom.irregular) {
        let rx = xp.v;
        let ry = yp.v;
        let fail = false;
        while (!fail && isok(rx, ry)) {
            const loc = game.level.at(rx, ry);
            if (!loc || (loc.typ !== STONE && loc.typ !== CORR)) break;
            rx += dx;
            ry += dy;
            if (good_rm_wall_doorpos(rx, ry, rdir, aroom)) {
                xp.v = rx;
                yp.v = ry;
                return true;
            }
            const next = game.level.at(rx, ry);
            if (!next || (next.typ !== STONE && next.typ !== CORR))
                fail = true;
            if (rx < aroom.lx || rx > aroom.hx || ry < aroom.ly || ry > aroom.hy)
                fail = true;
        }
    }
    return false;
}
// C ref: mklev.c:146 finddpos()
// RNG: rn1(range, base) for random x and y position
function finddpos(cc, dir, aroom) {
    let x1, y1, x2, y2;
    switch (dir) {
    case DIR_N: x1 = aroom.lx; x2 = aroom.hx; y1 = y2 = aroom.ly - 1; break;
    case DIR_S: x1 = aroom.lx; x2 = aroom.hx; y1 = y2 = aroom.hy + 1; break;
    case DIR_W: x1 = x2 = aroom.lx - 1; y1 = aroom.ly; y2 = aroom.hy; break;
    case DIR_E: x1 = x2 = aroom.hx + 1; y1 = aroom.ly; y2 = aroom.hy; break;
    default: return false;
    }
    // Try random points
    let tryct = 0;
    let x, y;
    do {
        x = (x2 - x1) ? rn1(x2 - x1 + 1, x1) : x1;
        y = (y2 - y1) ? rn1(y2 - y1 + 1, y1) : y1;
        const xp = { v: x }, yp = { v: y };
        if (finddpos_shift(xp, yp, dir, aroom)) {
            cc.x = xp.v; cc.y = yp.v;
            return true;
        }
    } while (++tryct < 20);
    // Exhaustive search
    for (x = x1; x <= x2; x++)
        for (y = y1; y <= y2; y++) {
            const xp = { v: x }, yp = { v: y };
            if (finddpos_shift(xp, yp, dir, aroom)) {
                cc.x = xp.v; cc.y = yp.v;
                return true;
            }
        }
    cc.x = x1; cc.y = y1;
    return false;
}
// C ref: mklev.c:1783 maybe_sdoor()
// RNG: rn2(max(2, chance))
function maybe_sdoor(chance) {
    // C ref: mklev.c:1795 — uses depth(&u.uz), not dlevel
    const d = depth_of_level(game.u?.uz);
    return (d > 2) && !rn2(Math.max(2, chance));
}
// C ref: sp_lev.c:2549 dig_corridor()
// RNG: rn2(35) for nxcor abort, rn2(50) for boulder, rn2(dix-diy+1) / rn2(diy-dix+1) for direction
export function dig_corridor(org, dest, npoints_out, nxcor, ftyp, btyp) {
    pushRngLogEntry('>dig_corridor');
    const result = _dig_corridor_impl(org, dest, npoints_out, nxcor, ftyp, btyp);
    pushRngLogEntry(`<dig_corridor=${result ? 1 : 0}`);
    return result;
}
function _dig_corridor_impl(org, dest, npoints_out, nxcor, ftyp, btyp) {
    const map = game.level;
    let dx = 0, dy = 0;
    let xx = org.x, yy = org.y;
    const tx = dest.x, ty = dest.y;
    let npoints = 0;
    if (npoints_out) npoints_out.v = 0;
    if (xx <= 0 || yy <= 0 || tx <= 0 || ty <= 0
        || xx > COLNO - 1 || tx > COLNO - 1 || yy > ROWNO - 1 || ty > ROWNO - 1)
        return false;
    if (tx > xx) dx = 1;
    else if (ty > yy) dy = 1;
    else if (tx < xx) dx = -1;
    else dy = -1;
    xx -= dx;
    yy -= dy;
    let cct = 0;
    while (xx !== tx || yy !== ty) {
        if (cct++ > 500 || (nxcor && !rn2(35)))
            return false;
        xx += dx;
        yy += dy;
        if (xx >= COLNO - 1 || xx <= 0 || yy <= 0 || yy >= ROWNO - 1)
            return false;
        const crm = map.at(xx, yy);
        if (!crm) return false;
        if (crm.typ === btyp) {
            if (ftyp === CORR && maybe_sdoor(100)) {
                npoints++;
                if (npoints_out) npoints_out.v = npoints;
                crm.typ = SCORR;
            } else {
                npoints++;
                if (npoints_out) npoints_out.v = npoints;
                crm.typ = ftyp;
                if (nxcor && !rn2(50)) {
                    try { mksobj_at(BOULDER, xx, yy, true, false); } catch (_e) {}
                }
            }
        } else if (crm.typ !== ftyp && crm.typ !== SCORR) {
            return false;
        }
        // Find next corridor position
        let dix = Math.abs(xx - tx);
        let diy = Math.abs(yy - ty);
        if ((dix > diy) && diy && !rn2(dix - diy + 1)) {
            dix = 0;
        } else if ((diy > dix) && dix && !rn2(diy - dix + 1)) {
            diy = 0;
        }
        // Change direction?
        if (dy && dix > diy) {
            const ddx = (xx > tx) ? -1 : 1;
            const ncr = map.at(xx + ddx, yy);
            if (ncr && (ncr.typ === btyp || ncr.typ === ftyp || ncr.typ === SCORR)) {
                dx = ddx; dy = 0; continue;
            }
        } else if (dx && diy > dix) {
            const ddy = (yy > ty) ? -1 : 1;
            const ncr = map.at(xx, yy + ddy);
            if (ncr && (ncr.typ === btyp || ncr.typ === ftyp || ncr.typ === SCORR)) {
                dy = ddy; dx = 0; continue;
            }
        }
        // Continue straight?
        const straight = map.at(xx + dx, yy + dy);
        if (straight && (straight.typ === btyp || straight.typ === ftyp || straight.typ === SCORR))
            continue;
        // Must change direction
        if (dx) { dx = 0; dy = (ty < yy) ? -1 : 1; }
        else { dy = 0; dx = (tx < xx) ? -1 : 1; }
        const alt = map.at(xx + dx, yy + dy);
        if (alt && (alt.typ === btyp || alt.typ === ftyp || alt.typ === SCORR))
            continue;
        dy = -dy; dx = -dx;
    }
    if (npoints_out) npoints_out.v = npoints;
    return true;
}
// C ref: mklev.c:604 dosdoor()
// RNG: multiple rn2 calls for door state
async function dosdoor(x, y, aroom, type) {
    const map = game.level;
    const loc = map.at(x, y);
    if (!loc) return;
    const shdoor = in_rooms(x, y, SHOPBASE).length > 0;
    if (!IS_WALL(loc.typ)) type = DOOR;
    loc.typ = type;
    if (type === DOOR) {
        if (!rn2(3)) {
            if (!rn2(5))
                loc.flags = D_ISOPEN;
            else if (!rn2(6))
                loc.flags = D_LOCKED;
            else
                loc.flags = D_CLOSED;
            if (loc.flags !== D_ISOPEN && !shdoor
                && level_difficulty() >= 5 && !rn2(25))
                loc.flags |= D_TRAPPED;
        } else {
            loc.flags = shdoor ? D_ISOPEN : D_NODOOR;
        }
        if (loc.flags & D_TRAPPED) {
            // C ref: mklev.c:653-662 — trapped door becomes mimic
            const mv = game.mvitals || [];
            const allMimicsGone = !!(mv[PM_SMALL_MIMIC]?.mvflags & G_GONE)
                && !!(mv[PM_LARGE_MIMIC]?.mvflags & G_GONE)
                && !!(mv[PM_GIANT_MIMIC]?.mvflags & G_GONE);
            if (level_difficulty() >= 9 && !rn2(5) && !allMimicsGone) {
                loc.flags = D_NODOOR;
                await makemon(mkclass(S_MIMIC, 0), x, y, 0);
            }
        }
    } else { // SDOOR
        if (shdoor || !rn2(5))
            loc.flags = D_LOCKED;
        else
            loc.flags = D_CLOSED;
        if (!shdoor && level_difficulty() >= 4 && !rn2(20))
            loc.flags |= D_TRAPPED;
    }
    add_door(x, y, aroom);
}
// C ref: mklev.c:1789 dodoor()
export async function dodoor(x, y, aroom) {
    await dosdoor(x, y, aroom, maybe_sdoor(8) ? SDOOR : DOOR);
}
// C ref: mklev.c:563 add_door()
function add_door(x, y, aroom) {
    const g = game;
    if (!g.level.doors) g.level.doors = [];
    // Check for duplicate
    for (let i = 0; i < aroom.doorct; i++) {
        const d = g.level.doors[aroom.fdoor + i];
        if (d && d.x === x && d.y === y) return;
    }
    if (aroom.doorct === 0) {
        aroom.fdoor = g.level.doorindex;
    }
    aroom.doorct++;
    // C ref: mklev.c:add_door() inserts at aroom->fdoor, shifting doors.
    for (let tmp = g.level.doorindex; tmp > aroom.fdoor; tmp--) {
        g.level.doors[tmp] = g.level.doors[tmp - 1];
    }
    // Rebase other rooms' fdoor indices that point at/after insertion point.
    for (const broom of g.level.rooms || []) {
        if (!broom || broom.hx <= 0 || broom === aroom || !(broom.doorct > 0)) continue;
        if ((broom.fdoor ?? 0) >= aroom.fdoor) broom.fdoor++;
    }
    for (const room of g.level.rooms || []) {
        if (!room || room.hx <= 0) continue;
        for (let m = 0; m < (room.nsubrooms || 0); m++) {
            const broom = room.sbrooms?.[m];
            if (!broom || broom === aroom || !(broom.doorct > 0)) continue;
            if ((broom.fdoor ?? 0) >= aroom.fdoor) broom.fdoor++;
        }
    }
    g.level.doors[aroom.fdoor] = { x, y };
    g.level.doorindex++;
}
// C ref: mklev.c:1795 bydoor() — is there a door adjacent?
function bydoor(x, y) {
    const map = game.level;
    for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
        if (!isok(x + dx, y + dy)) continue;
        const loc = map.at(x + dx, y + dy);
        if (loc && (IS_DOOR(loc.typ) || loc.typ === SDOOR)) return true;
    }
    return false;
}
// C ref: mklev.c:428 join()
// Connect room a to room b with a corridor.
async function join(a, b, nxcor) {
    pushRngLogEntry('>join');
    const g = game;
    const croom = g.level.rooms[a];
    const troom = g.level.rooms[b];
    if (!croom || !troom) { pushRngLogEntry('<join'); return; }
    if (!croom.needjoining || !troom.needjoining) { pushRngLogEntry('<join'); return; }
    if (troom.hx < 0 || croom.hx < 0) { pushRngLogEntry('<join'); return; }
    let dx, dy;
    const cc = { x: 0, y: 0 }, tt = { x: 0, y: 0 };
    if (troom.lx > croom.hx) {
        dx = 1; dy = 0;
        if (!finddpos(cc, DIR_E, croom)) { pushRngLogEntry('<join'); return; }
        if (!finddpos(tt, DIR_W, troom)) { pushRngLogEntry('<join'); return; }
    } else if (troom.hy < croom.ly) {
        dy = -1; dx = 0;
        if (!finddpos(cc, DIR_N, croom)) { pushRngLogEntry('<join'); return; }
        if (!finddpos(tt, DIR_S, troom)) { pushRngLogEntry('<join'); return; }
    } else if (troom.hx < croom.lx) {
        dx = -1; dy = 0;
        if (!finddpos(cc, DIR_W, croom)) { pushRngLogEntry('<join'); return; }
        if (!finddpos(tt, DIR_E, troom)) { pushRngLogEntry('<join'); return; }
    } else {
        dy = 1; dx = 0;
        if (!finddpos(cc, DIR_S, croom)) { pushRngLogEntry('<join'); return; }
        if (!finddpos(tt, DIR_N, troom)) { pushRngLogEntry('<join'); return; }
    }
    const xx = cc.x, yy = cc.y;
    const tx = tt.x - dx, ty = tt.y - dy;
    if (nxcor) {
        const loc = g.level.at(xx + dx, yy + dy);
        if (loc && loc.typ !== STONE) { pushRngLogEntry('<join'); return; }
    }
    const org = { x: xx + dx, y: yy + dy };
    const dest = { x: tx, y: ty };
    const npoints = { v: 0 };
    const arboreal = false; // TODO: level.flags.arboreal
    const ftyp = arboreal ? ROOM : CORR;
    const dig_result = dig_corridor(org, dest, npoints, nxcor, ftyp, STONE);
    if ((npoints.v > 0) && (okdoor(xx, yy) || !nxcor))
        await dodoor(xx, yy, croom);
    if (!dig_result) { pushRngLogEntry('<join'); return; }
    if (okdoor(tt.x, tt.y) || !nxcor)
        await dodoor(tt.x, tt.y, troom);
    if (g.smeq[a] < g.smeq[b])
        g.smeq[b] = g.smeq[a];
    else
        g.smeq[a] = g.smeq[b];
    pushRngLogEntry('<join');
}
// C ref: mklev.c:1987 make_niches()
// RNG: rnd() for count, rn2(6) for level teleport/trapdoor decisions
async function make_niches() {
    const g = game;
    const dep = g.u?.uz?.dlevel ?? 1;
    let ct = rnd(Math.trunc(g.level.nroom / 2) + 1);
    let ltptr = (dep > 15);
    let vamp = (dep > 5 && dep < 25);
    while (ct--) {
        if (ltptr && !rn2(6)) {
            ltptr = false;
            await makeniche(LEVEL_TELEP);
        } else if (vamp && !rn2(6)) {
            vamp = false;
            await makeniche(TRAPDOOR);
        } else {
            await makeniche(/* NO_TRAP */ 0);
        }
    }
}
function cardinal_nextto_room(aroom, x, y) {
    const map = game.level;
    const rmno = game.level.rooms.indexOf(aroom) + ROOMOFFSET;
    if (isok(x - 1, y)) {
        const loc = map.at(x - 1, y);
        if (loc && !loc.edge && loc.roomno === rmno) return true;
    }
    if (isok(x + 1, y)) {
        const loc = map.at(x + 1, y);
        if (loc && !loc.edge && loc.roomno === rmno) return true;
    }
    if (isok(x, y - 1)) {
        const loc = map.at(x, y - 1);
        if (loc && !loc.edge && loc.roomno === rmno) return true;
    }
    if (isok(x, y + 1)) {
        const loc = map.at(x, y + 1);
        if (loc && !loc.edge && loc.roomno === rmno) return true;
    }
    return false;
}
function place_niche(aroom) {
    const dd = { x: 0, y: 0 };
    let dy;
    if (rn2(2)) {
        dy = 1;
        if (!finddpos(dd, DIR_S, aroom)) return null;
    } else {
        dy = -1;
        if (!finddpos(dd, DIR_N, aroom)) return null;
    }
    const xx = dd.x;
    const yy = dd.y;
    const niche = game.level.at(xx, yy + dy);
    const back = game.level.at(xx, yy - dy);
    if (!niche || niche.typ !== STONE) return null;
    if (!back || IS_POOL(back.typ) || IS_FURNITURE(back.typ)) return null;
    if (!cardinal_nextto_room(aroom, xx, yy)) return null;
    return { dy, xx, yy };
}
// C ref: mklev.c:1925 makeniche()
// RNG: rn2(nroom) for room, rn2(5) for doorct check, place_niche with rn2(2),
//      rn2(4) for secret vs open, rn2(7) + rn2(5) for door type, etc.
async function makeniche(trap_type) {
    const g = game;
    let vct = 8;
    while (vct--) {
        const aroom = g.level.rooms[rn2(g.level.nroom)];
        if (!aroom || aroom.rtype !== OROOM) continue;
        if (aroom.doorct === 1 && rn2(5)) continue;
        const niche = place_niche(aroom);
        if (!niche) continue;
        const { dy, xx, yy } = niche;
        const rm = g.level.at(xx, yy + dy);
        if (!rm) continue;
        if (trap_type || !rn2(4)) {
            rm.typ = SCORR;
            if (trap_type) {
                let actualTrap = trap_type;
                if (is_hole(actualTrap) && !Can_fall_thru(g.u?.uz)) {
                    actualTrap = ROCKTRAP;
                }
                const ttmp = await maketrap(xx, yy + dy, actualTrap);
                if (ttmp) {
                    if (actualTrap !== ROCKTRAP)
                        ttmp.once = true;
                    // C ref: mklev.c:757-762 — trap_engravings + wipe_engr_at
                    const TRAP_ENGRAVINGS = {
                        14: 'Vlad was here',  // TRAPDOOR
                        15: 'ad aerarium',    // TELEP_TRAP
                        16: 'ad aerarium',    // LEVEL_TELEP
                    };
                    const engrText = TRAP_ENGRAVINGS[trap_type];
                    if (engrText) {
                        make_engr_at(xx, yy - dy, engrText, null, 0, DUST);
                        // C ref: mklev.c:771 — wipe_engr_at ages the engraving
                        wipe_engr_at(xx, yy - dy, 5, false);
                    }
                }
            }
            await dosdoor(xx, yy, aroom, SDOOR);
        } else {
            rm.typ = CORR;
            if (rn2(7)) {
                await dosdoor(xx, yy, aroom, rn2(5) ? SDOOR : DOOR);
            } else {
                const loc = g.level.at(xx, yy);
                if (!rn2(5) && loc && IS_WALL(loc.typ)) {
                    loc.typ = IRONBARS;
                    if (rn2(3)) {
                        // C ref: mklev.c:776 — human corpse in iron bar niche
                        const humanPtr = mkclass(S_HUMAN, 0);
                        if (humanPtr) {
                            const pm = mons.indexOf(humanPtr);
                            if (pm >= 0) mkcorpse_at_niche(pm, xx, yy + dy);
                        }
                    }
                }
                if (!g.level.flags.noteleport) {
                    try { mksobj_at(SCR_TELEPORTATION, xx, yy + dy, true, false); } catch (_e) {}
                }
                if (!rn2(3)) {
                    try { mkobj_at(RANDOM_CLASS, xx, yy + dy, true); } catch (_e) {}
                }
            }
        }
        return;
    }
}
// C ref: mklev.c — okdoor()
function okdoor(x, y) {
    const map = game.level;
    const loc = map.at(x, y);
    if (!loc) return false;
    if (!(loc.typ === HWALL || loc.typ === VWALL)) return false;
    if (bydoor(x, y)) return false;
    return (
        (isok(x - 1, y) && !IS_OBSTRUCTED(map.at(x - 1, y).typ))
        || (isok(x + 1, y) && !IS_OBSTRUCTED(map.at(x + 1, y).typ))
        || (isok(x, y - 1) && !IS_OBSTRUCTED(map.at(x, y - 1).typ))
        || (isok(x, y + 1) && !IS_OBSTRUCTED(map.at(x, y + 1).typ))
    );
}
// C ref: mklev.c:511 makecorridors()
// RNG: rn2(50) break, rn2(nroom) for extra corridors.
export async function makecorridors() {
    const g = game;
    let any = true;
    // Initialize smeq — each room is its own equivalence class
    for (let i = 0; i < g.level.nroom; i++)
        g.smeq[i] = i;
    // Connect adjacent rooms
    for (let a = 0; a < g.level.nroom - 1; a++) {
        await join(a, a + 1, false);
        if (!rn2(50)) break;
    }
    // Connect rooms 2 apart if not already connected
    for (let a = 0; a < g.level.nroom - 2; a++)
        if (g.smeq[a] !== g.smeq[a + 2])
            await join(a, a + 2, false);
    // Connect any remaining disconnected rooms
    for (let a = 0; any && a < g.level.nroom; a++) {
        any = false;
        for (let b = 0; b < g.level.nroom; b++)
            if (g.smeq[a] !== g.smeq[b]) {
                await join(a, b, false);
                any = true;
            }
    }
    // Extra random corridors
    if (g.level.nroom > 2) {
        const count = rn2(g.level.nroom) + 4;
        for (let i = 0; i < count; i++) {
            let a = rn2(g.level.nroom);
            let b = rn2(g.level.nroom - 2);
            if (b >= a) b += 2;
            await join(a, b, true);
        }
    }
}
// somex / somey — imported from mkroom.js
export function occupied(x, y) {
    const loc = game.level.at(x, y);
    if (!loc) return false;
    return !!(game.level.trapAt(x, y)
        || IS_FURNITURE(loc.typ)
        || loc.typ === LAVAPOOL
        || IS_POOL(loc.typ));
}
// NOTE: differs from canonical mkroom.js — local lacks irregular room handling
// C ref: mkroom.c:694 somexy() — random point in room, not in subroom
// C ref: mkroom.c:744 somexyspace() — accessible point in room
// somexyspace — canonical version imported from mkroom.js
// Do NOT duplicate here. See LORE "Duplicate somexyspace helpers."
// C ref: mklev.c:2189 generate_stairs_room_good()
function generate_stairs_room_good(croom, phase) {
    if (!croom || croom.hx < 0) return false;
    if (!croom.needjoining && phase >= 0) return false;
    // C ref: mkroom.c has_dnstairs()/has_upstairs() — scan the stairway list.
    const inRoom = (sx, sy) => (
        sx >= croom.lx && sx <= croom.hx
        && sy >= croom.ly && sy <= croom.hy
    );
    let hasDown = false;
    let hasUp = false;
    for (let st = game.stairs; st; st = st.next) {
        if (!inRoom(st.sx, st.sy)) continue;
        if (st.up) hasUp = true;
        else hasDown = true;
        if (hasDown && hasUp) break;
    }
    // Fallback for partially populated stairway lists: derive room stair
    // occupancy from map cells and canonical up/down stair markers.
    if (!(hasDown && hasUp) && game.level?.at) {
        const up = game.level.upstair || null;
        const down = game.level.dnstair || null;
        for (let yy = croom.ly; yy <= croom.hy && !(hasDown && hasUp); yy++) {
            for (let xx = croom.lx; xx <= croom.hx; xx++) {
                const loc = game.level.at(xx, yy);
                if (!loc) continue;
                if (loc.typ !== STAIRS && loc.typ !== LADDER) continue;
                if (up && up.x === xx && up.y === yy) hasUp = true;
                if (down && down.x === xx && down.y === yy) hasDown = true;
                if (loc.typ === LADDER) {
                    if (loc.ladder === 1) hasUp = true;
                    if (loc.ladder === 2) hasDown = true;
                }
            }
        }
    }
    // Exclude rooms that already have stairs (unless phase < 1)
    if (phase >= 1 && (hasDown || hasUp))
        return false;
    // C ref: mklev.c:2223 — OROOM always ok, THEMEROOM ok at phase < 2, else reject
    if (croom.rtype !== OROOM && !(phase < 2 && croom.rtype === THEMEROOM))
        return false;
    return true;
}
// C ref: mklev.c:2208 generate_stairs_find_room() — RNG: rn2(ai) or rn2(nroom)
function generate_stairs_find_room() {
    const g = game;
    if (!g.level.nroom) return null;
    const debugGsfr = (typeof process !== 'undefined' && process?.env?.DEBUG_GSFR === '1');
    for (let phase = 2; phase > -1; phase--) {
        const candidates = [];
        for (let i = 0; i < g.level.nroom; i++)
            if (generate_stairs_room_good(g.level.rooms[i], phase))
                candidates.push(i);
        if (debugGsfr) {
            console.error(`gsfr phase=${phase} ai=${candidates.length} nroom=${g.level.nroom}`);
        }
        if (candidates.length > 0) {
            const pick = rn2(candidates.length);
            if (debugGsfr) {
                console.error(`gsfr pick phase=${phase} idx=${pick} room=${candidates[pick]}`);
            }
            return g.level.rooms[candidates[pick]];
        }
    }
    if (debugGsfr) {
        console.error('gsfr fallback');
    }
    return g.level.rooms[rn2(g.level.nroom)];
}
// C ref: mklev.c:2165 mkstairs()
function mkstairs(x, y, up, croom, _force) {
    const g = game;
    const map = g.level;
    const loc = map.at(x, y);
    if (loc) {
        loc.typ = STAIRS;
        // C ref: mklev.c:2193 sets levl[x][y].ladder for every stair.
        loc.ladder = up ? 1 : 2; // LA_UP=1, LA_DOWN=2
    }
    // Track stairs on the room for generate_stairs_room_good
    if (croom) {
        if (up) croom._has_upstairs = true;
        else croom._has_dnstairs = true;
    }
    // C ref: mklev.c:2183 — register in stairway linked list
    const dest = {
        dnum: g.u?.uz?.dnum ?? 0,
        dlevel: (g.u?.uz?.dlevel ?? 1) + (up ? -1 : 1),
    };
    stairway_add(x, y, !!up, false, dest);
    // Legacy: also store on map for backwards compat
    if (up) {
        map.upstair = { x, y };
    } else {
        map.dnstair = { x, y };
    }
}
// C ref: mklev.c:2240 generate_stairs()
// RNG: rn2 in generate_stairs_find_room, rn1 in somexy/somexyspace
async function generate_stairs() {
    const g = game;
    const pos = { x: 0, y: 0 };
    // Down stairs (skip if bottom level)
    // For level 1, this is not the bottom, so we make down stairs
    {
        const croom = generate_stairs_find_room();
        if (croom) {
            if (!somexyspace(croom, pos)) {
                pos.x = somex(croom);
                pos.y = somey(croom);
            }
            mkstairs(pos.x, pos.y, 0, croom, false);
        }
    }
    // Up stairs (skip if level 1 — but only for non-branch entries)
    // For DoD level 1, up stairs come from branch placement, not here
    if ((g.u?.uz?.dlevel ?? 1) !== 1) {
        const croom = generate_stairs_find_room();
        if (croom) {
            if (!somexyspace(croom, pos)) {
                pos.x = somex(croom);
                pos.y = somey(croom);
            }
            mkstairs(pos.x, pos.y, 1, croom, false);
        }
    }
}
// C ref: mkmaze.c:1126 makemaz("") — generate maze for non-special Gehennom
// and below-Medusa levels that don't have a level script.
async function makemaz_empty() {
    const g = game;
    g.level.flags.is_maze_lev = true;
    g.level.flags.corrmaze = !rn2(3);
    // C ref: mkmaze.c:1200-1204 — choose maze style
    // Invocation level gets fixed 1x1 corridors; others get random.
    // C: if (!Invocation_lev(&u.uz) && rn2(2)) — short-circuits rn2(2) on Invocation level
    if (!Invocation_lev(g.u?.uz) && rn2(2)) {
        // C ref: create_maze(-1, -1, !rn2(5))
        // C evaluates !rn2(5) as a parameter BEFORE create_maze executes,
        // so rn2(5) is consumed BEFORE rnd(4) for corrwid/wallthick.
        const rmdeadends = !rn2(5);
        const corrwid = rnd(4);
        let wallthick = rnd(4) - corrwid;
        if (wallthick < 1) wallthick = 1;
        else if (wallthick > 5) wallthick = 5;
        const cw = Math.max(1, Math.min(5, corrwid));
        const scale = cw + wallthick;
        const rdx = Math.trunc((g.x_maze_max ?? ((COLNO - 1) & ~1)) / scale);
        const rdy = Math.trunc((g.y_maze_max ?? ((ROWNO - 1) & ~1)) / scale);
        // Fill maze grid
        if (g.level.flags.corrmaze) {
            for (let x = 2; x < rdx * 2; x++)
                for (let y = 2; y < rdy * 2; y++) {
                    const loc = g.level.at(x, y);
                    if (loc) loc.typ = STONE;
                }
        } else {
            for (let x = 2; x <= rdx * 2; x++)
                for (let y = 2; y <= rdy * 2; y++) {
                    const loc = g.level.at(x, y);
                    if (loc) loc.typ = ((x % 2) && (y % 2)) ? STONE : HWALL;
                }
        }
        const savedXmax = g.x_maze_max, savedYmax = g.y_maze_max;
        g.x_maze_max = rdx * 2;
        g.y_maze_max = rdy * 2;
        const mx = 3 + 2 * rn2((g.x_maze_max >> 1) - 1);
        const my = 3 + 2 * rn2((g.y_maze_max >> 1) - 1);
        walkfrom(mx, my, 0);
        if (rmdeadends) maze_remove_deadends(g.level.flags.corrmaze ? CORR : ROOM);
        g.x_maze_max = savedXmax;
        g.y_maze_max = savedYmax;
    } else {
        // Fixed 1x1 corridors (Invocation level style)
        const xMazeMax = g.x_maze_max ?? ((COLNO - 1) & ~1);
        const yMazeMax = g.y_maze_max ?? ((ROWNO - 1) & ~1);
        for (let x = 2; x <= xMazeMax; x++)
            for (let y = 2; y <= yMazeMax; y++) {
                const loc = g.level.at(x, y);
                if (loc) loc.typ = ((x % 2) && (y % 2)) ? STONE : HWALL;
            }
        const savedXmax = g.x_maze_max, savedYmax = g.y_maze_max;
        g.x_maze_max = xMazeMax;
        g.y_maze_max = yMazeMax;
        const mx = 3 + 2 * rn2((g.x_maze_max >> 1) - 1);
        const my = 3 + 2 * rn2((g.y_maze_max >> 1) - 1);
        walkfrom(mx, my, 0);
        g.x_maze_max = savedXmax;
        g.y_maze_max = savedYmax;
    }
    // C ref: mkmaze.c:1206-1207 — wallification for non-corrmaze
    if (!g.level.flags.corrmaze)
        wallification(2, 2, g.x_maze_max ?? ((COLNO - 1) & ~1), g.y_maze_max ?? ((ROWNO - 1) & ~1));
    // C ref: mkmaze.c:1209-1217 — stairs via mazexy
    // Up stairs
    const mm1 = mazexy();
    if (mm1) mkstairs(mm1.x, mm1.y, 1, null, false);
    // Down stairs (not on Invocation level — that gets vibrating square)
    if (!Invocation_lev(g.u?.uz)) {
        const mm2 = mazexy();
        if (mm2) mkstairs(mm2.x, mm2.y, 0, null, false);
    } else {
        // C ref: mkmaze.c:1215-1217 — vibrating square on Invocation level
        // TODO: pick_vibrasquare_location() + maketrap(VIBRATING_SQUARE)
    }
    // C ref: mkmaze.c:1220 — place_branch
    const branchp = _is_branchlev();
    if (branchp) {
        await place_branch(branchp);
    }
    // C ref: mkmaze.c:1222 — populate_maze (monsters, objects, traps)
    await populate_maze();
}
// C ref: mkmaze.c:1316 mazexy — random ROOM/CORR position in completed maze
function mazexy() {
    const xMazeMax = game.x_maze_max ?? ((COLNO - 1) & ~1);
    const yMazeMax = game.y_maze_max ?? ((ROWNO - 1) & ~1);
    const allowedtyp = game.level?.flags?.corrmaze ? CORR : ROOM;
    let cpt = 0;
    do {
        const x = rnd(xMazeMax);
        const y = rnd(yMazeMax);
        const loc = game.level?.at(x, y);
        if (loc && loc.typ === allowedtyp) {
            return { x, y };
        }
    } while (++cpt < 100);
    // 100 random attempts failed; systematically try every possibility
    for (let x = 1; x <= xMazeMax; x++)
        for (let y = 1; y <= yMazeMax; y++) {
            const loc = game.level?.at(x, y);
            if (loc && loc.typ === allowedtyp)
                return { x, y };
        }
    // Fallback (shouldn't happen)
    return { x: 3, y: 3 };
}
// C ref: mkmaze.c:1098 populate_maze — add monsters/objects/traps to maze
async function populate_maze() {
    const g = game;
    let mm;
    // C ref: mkmaze.c:1103 — random gems/objects
    for (let i = rn1(8, 11); i; i--) {
        mm = mazexy();
        mkobj_at(rn2(2) ? GEM_CLASS : RANDOM_CLASS, mm.x, mm.y, true);
    }
    // C ref: mkmaze.c:1107 — boulders
    for (let i = rn1(10, 2); i; i--) {
        mm = mazexy();
        mksobj_at(BOULDER, mm.x, mm.y, true, false);
    }
    // C ref: mkmaze.c:1111 — minotaurs
    for (let i = rn2(3); i; i--) {
        mm = mazexy();
        await makemon(mons[PM_MINOTAUR], mm.x, mm.y, 0);
    }
    // C ref: mkmaze.c:1115 — random monsters
    for (let i = rn1(5, 7); i; i--) {
        mm = mazexy();
        await makemon(null, mm.x, mm.y, 0);
    }
    // C ref: mkmaze.c:1119 — gold
    for (let i = rn1(6, 7); i; i--) {
        mm = mazexy();
        mkgold(0, mm.x, mm.y);
    }
    // C ref: mkmaze.c:1123 — traps
    for (let i = rn1(6, 7); i; i--) {
        await mktrap_maze();
    }
}
// C ref: mklev.c:2036 mktrap() with MKTRAP_MAZEFLAG — place a random trap in maze
async function mktrap_maze() {
    const g = game;
    let kind;
    // C ref: mklev.c:2064-2068 — Gehennom fire trap bias
    if (in_hell(g.u?.uz) && !rn2(5)) {
        kind = FIRE_TRAP;
    } else {
        do {
            kind = traptype_rnd();
        } while (kind === NO_TRAP);
    }
    // C ref: mklev.c:2070 — hole fallthrough check
    if (is_hole(kind) && !Can_fall_thru(g.u?.uz))
        kind = ROCKTRAP;
    // C ref: mklev.c:2083-2093 — find position via mazexy with retry
    let tryct = 0;
    const avoid_boulder = is_pit(kind) || is_hole(kind);
    let m;
    do {
        if (++tryct > 200) return;
        m = mazexy();
    } while (occupied(m.x, m.y)
             || (avoid_boulder && sobj_at(BOULDER, m.x, m.y)));
    const trap = await maketrap(m.x, m.y, kind);
    kind = trap ? trap.ttyp : NO_TRAP;
    // C ref: mklev.c:2104-2105 — create giant spider on web trap
    if (kind === WEB) {
        await makemon(mons[PM_GIANT_SPIDER], m.x, m.y, 0);
    }
    // C ref: mklev.c:2135-2152 — trap victim during level gen
    const lvl = level_difficulty();
    if (g.in_mklev
        && kind !== NO_TRAP
        && lvl <= rnd(4)
        && kind !== SQKY_BOARD && kind !== RUST_TRAP
        && !(kind === ROLLING_BOULDER_TRAP
             && trap.launch?.x === trap.tx && trap.launch?.y === trap.ty)
        && !is_pit(kind) && (kind < HOLE || kind === MAGIC_TRAP)) {
        if (kind === LANDMINE) {
            trap.ttyp = PIT;
            trap.tseen = true;
        }
        mktrap_victim(trap);
    }
}
 
// ============================================================
// fill_ordinary_room — populate rooms with monsters/items/traps
// ============================================================
const NO_TRAP = 0;
const TRAPNUM = 26; // number of trap types
// C ref: mklev.c:1928 traptype_rnd()
// RNG: rnd(TRAPNUM - 1), and sometimes the result is NO_TRAP requiring retry
function traptype_rnd() {
    const lvl = level_difficulty();
    let kind = rnd(TRAPNUM - 1);
    switch (kind) {
    case TRAPPED_DOOR:
    case TRAPPED_CHEST:
    case MAGIC_PORTAL:
    case VIBRATING_SQUARE:
        kind = NO_TRAP;
        break;
    case ROLLING_BOULDER_TRAP:
    case SLP_GAS_TRAP:
        if (lvl < 2)
            kind = NO_TRAP;
        break;
    case LEVEL_TELEP:
        if (lvl < 5 || game.level?.flags?.noteleport
            || Is_knox_level(game.u?.uz))
            kind = NO_TRAP;
        break;
    case SPIKED_PIT:
        if (lvl < 5)
            kind = NO_TRAP;
        break;
    case LANDMINE:
        if (lvl < 6)
            kind = NO_TRAP;
        break;
    case WEB:
        if (lvl < 7)
            kind = NO_TRAP;
        break;
    case STATUE_TRAP:
    case POLY_TRAP:
        if (lvl < 8)
            kind = NO_TRAP;
        break;
    case FIRE_TRAP:
        if (!in_hell(game.u?.uz))
            kind = NO_TRAP;
        break;
    case TELEP_TRAP:
        if (game.level?.flags?.noteleport)
            kind = NO_TRAP;
        break;
    case HOLE:
        if (rn2(7))
            kind = NO_TRAP;
        break;
    }
    return kind;
}
function mkcorpse_at(pm, x, y) {
    const corpse = mkcorpstat(CORPSE, null, pm, x, y, CORPSTAT_INIT);
    corpse.age -= (TAINT_AGE + 1);
    return corpse;
}
// C ref: mklev.c:786 — iron bar niche corpse creation.
// C passes TRUE (1) as corpstatflags: init = (1 & 0x08) = false, spe = (1 & 0x07) = 1 (FEMALE).
// Using CORPSTAT_FEMALE (1) to match C's TRUE exactly.
function mkcorpse_at_niche(pm, x, y) {
    return mkcorpstat(CORPSE, null, pm, x, y, CORPSTAT_FEMALE);
}
// C ref: mklev.c:2297 find_okay_roompos()
function find_okay_roompos(croom, crd) {
    let tryct = 0;
    do {
        if (++tryct > 200)
            return false;
        if (!somexyspace(croom, crd))
            return false;
    } while (occupied(crd.x, crd.y) || bydoor(crd.x, crd.y));
    return true;
}
export function mktrap_victim(trap) {
    let otmp = null;
    let victim_mnum;
    const lvl = game.u?.uz?.dlevel ?? 1;
    const kind = trap.ttyp;
    const x = trap.tx;
    const y = trap.ty;
    switch (kind) {
    case ARROW_TRAP:
        otmp = mksobj(ARROW, true, false);
        otmp.opoisoned = 0;
        break;
    case DART_TRAP:
        otmp = mksobj(DART, true, false);
        break;
    case ROCKTRAP:
        otmp = mksobj(ROCK, true, false);
        break;
    default:
        break;
    }
    if (otmp)
        place_object(otmp, x, y);
    do {
        let poss_class = RANDOM_CLASS;
        switch (rn2(4)) {
        case 0: poss_class = WEAPON_CLASS; break;
        case 1: poss_class = TOOL_CLASS; break;
        case 2: poss_class = FOOD_CLASS; break;
        case 3: poss_class = GEM_CLASS; break;
        }
        otmp = mkobj(poss_class, false);
        curse(otmp);
        place_object(otmp, x, y);
    } while (!rn2(5));
    switch (rn2(15)) {
    case 0:
        victim_mnum = PM_ELF;
        if (kind === SLP_GAS_TRAP && !(lvl <= 2 && rn2(2)))
            victim_mnum = PM_HUMAN;
        break;
    case 1:
    case 2:
        victim_mnum = PM_DWARF;
        break;
    case 3:
    case 4:
    case 5:
        victim_mnum = PM_ORC;
        break;
    case 6:
    case 7:
    case 8:
    case 9:
        victim_mnum = PM_GNOME;
        if (!rn2(10)) {
            otmp = mksobj(rn2(4) ? TALLOW_CANDLE : WAX_CANDLE, true, false);
            otmp.quan = 1;
            curse(otmp);
            place_object(otmp, x, y);
        }
        break;
    default:
        victim_mnum = PM_HUMAN;
        break;
    }
    if (victim_mnum === PM_HUMAN && rn2(25))
        victim_mnum = rn1(PM_WIZARD - PM_ARCHEOLOGIST, PM_ARCHEOLOGIST);
    mkcorpse_at(victim_mnum, x, y);
}
// C ref: mklev.c:2026 mktrap()
// RNG: traptype_rnd (rnd), somexyspace (rn1+rn2), maketrap
async function mktrap_room(croom) {
    const lvl = level_difficulty();
    let kind;
    // Select trap type
    do {
        kind = traptype_rnd();
    } while (kind === NO_TRAP);
    if (is_hole(kind) && !Can_fall_thru(game.u?.uz))
        kind = ROCKTRAP;
    // Find position in room
    const pos = { x: 0, y: 0 };
    if (!somexyspace(croom, pos)) return;
    const trap = await maketrap(pos.x, pos.y, kind);
    kind = trap ? trap.ttyp : NO_TRAP;
    // C ref: mklev.c:2104-2105 — create giant spider on web trap
    if (kind === WEB) {
        await makemon(mons[PM_GIANT_SPIDER], pos.x, pos.y, 0);
    }
    // C ref: mklev.c:2118-2120 — tutorial return portal destination.
    if (trap && kind === MAGIC_PORTAL
        && ((game.u?.ucamefrom?.dnum || 0) || (game.u?.ucamefrom?.dlevel || 0))) {
        trap.dst.dnum = game.u.ucamefrom.dnum;
        trap.dst.dlevel = game.u.ucamefrom.dlevel;
    }
    // C ref: mklev.c:2135-2152 — dead monster victim on trap during level gen
    if (game.in_mklev
        && kind !== NO_TRAP
        && lvl <= rnd(4)
        && kind !== SQKY_BOARD && kind !== RUST_TRAP
        && !(kind === ROLLING_BOULDER_TRAP
             && trap.launch?.x === trap.tx && trap.launch?.y === trap.ty)
        && !is_pit(kind) && (kind < HOLE || kind === MAGIC_TRAP)) {
        if (kind === LANDMINE) {
            trap.ttyp = PIT;
            trap.tseen = true;
        }
        mktrap_victim(trap);
    }
}
// C ref: mklev.c mkfount()
// RNG: somexyspace for position
// C ref: mklev.c:2343 mkgrave()
// RNG: rn2(10) dobell, somexyspace, rn2(3) gold, rn2(5) buried objects
function mkgrave(croom) {
    if (croom.rtype !== OROOM) return;
    const dobell = !rn2(10);
    const pos = { x: 0, y: 0 };
    if (!find_okay_roompos(croom, pos)) return;
    // C ref: engrave.c:1687 make_grave()
    make_grave(pos.x, pos.y, dobell ? 'Saved by the bell!' : null);
    // Possibly fill with gold
    if (!rn2(3)) {
        try {
            const gold = mksobj(GOLD_PIECE, true, false);
            if (gold) {
                const depth = game.u?.uz?.dlevel ?? 1;
                gold.quan = rnd(20) + depth * rnd(5);
            }
        } catch (_e) {}
    }
    // Buried objects
    for (let tryct = rn2(5); tryct > 0; tryct--) {
        try {
            const otmp = mkobj(0 /* RANDOM_CLASS */, true);
            if (!otmp) break;
            curse(otmp);
        } catch (_e) { break; }
    }
    // Leave a bell if dobell
    if (dobell) {
        try { mksobj_at(BELL, pos.x, pos.y, true, false); } catch (_e) {}
    }
}
// Engravings data from dat/engrave.txt (48 entries, matching C exactly)
// Engravings from the makedefs-processed engrave file.
// Entry 0 is the default added by makedefs (do_rnd_access_file).
// Entries "^?MAIL" and "^." from engrave.txt are EXCLUDED: makedefs'
// random_engraving and supporting data (ENGRAVINGS, getrumor_rng, etc.)
// have been moved to engrave.js which parses them from engrave_data.js.
import { maketrap } from './trap.js';
import { themeroom_fill, themerooms, themerooms_generate as themerms_generate, themerooms_post_level_generate } from './levels/themerms.js';
import { corr, makerogueghost, makeroguerooms } from './extralev.js';
function mkfount(croom) {
    const pos = { x: 0, y: 0 };
    if (!find_okay_roompos(croom, pos)) return;
    // C ref: mklev.c:2283-2287 — create fountain
    const loc = game.level?.at(pos.x, pos.y);
    if (loc) {
        loc.typ = FOUNTAIN;
        if (!rn2(7)) loc.blessedftn = 1;
        game.level.flags.nfountains++;
    }
}
// C ref: mklev.c:2332 mkaltar()
function mkaltar(croom) {
    if (!croom || croom.rtype !== OROOM) return;
    const pos = { x: 0, y: 0 };
    if (!find_okay_roompos(croom, pos)) return;
    const loc = game.level?.at(pos.x, pos.y);
    if (!loc) return;
    // C: set_levltyp(m.x,m.y,ALTAR)
    loc.typ = ALTAR;
    // C: al = rn2(A_LAWFUL + 2) - 1; levl[m.x][m.y].altarmask = Align2amask(al)
    const al = rn2(A_LAWFUL + 2) - 1;
    const amask = Align2amask(al);
    loc.flags = amask;
    // Keep JS field parity for modules that read altarmask explicitly.
    loc.altarmask = amask;
}
// C ref: mklev.c:929 fill_ordinary_room()
// C ref: sp_lev.c:2731 fill_special_room()
// Fills special rooms (vaults with gold, shops with stock, zoos, etc.)
// THEMEROOM already imported from const.js
async function fill_special_room(croom) {
    if (!croom || croom.hx <= 0) return;
    // Recurse into subrooms
    for (let i = 0; i < (croom.nsubrooms || 0); i++) {
        const sub = croom.sbrooms?.[i];
        if (sub) await fill_special_room(sub);
    }
    if (croom.rtype === OROOM || croom.rtype === THEMEROOM) return;
    if (croom.needfill === 0) return; // FILL_NONE
    // C ref: sp_lev.c:2776-2804 — mark per-level special-room flags
    // regardless of whether the room is actively filled this pass.
    switch (croom.rtype) {
    case VAULT:
        game.level.flags.has_vault = true;
        break;
    case ZOO:
        game.level.flags.has_zoo = true;
        break;
    case COURT:
        game.level.flags.has_court = true;
        break;
    case MORGUE:
        game.level.flags.has_morgue = true;
        break;
    case BEEHIVE:
        game.level.flags.has_beehive = true;
        break;
    case BARRACKS:
        game.level.flags.has_barracks = true;
        break;
    case TEMPLE:
        game.level.flags.has_temple = true;
        break;
    case SWAMP:
        game.level.flags.has_swamp = true;
        break;
    default:
        break;
    }
    if (croom.needfill === FILL_NORMAL) {
        // Shop
        if (croom.rtype >= SHOPBASE) {
            await stock_room(croom.rtype - SHOPBASE, croom);
            game.level.flags.has_shop = true;
            return;
        }
        switch (croom.rtype) {
        case VAULT:
            // Fill vault with gold: mkgold(rn1(depth*100, 51), x, y) per cell
            for (let x = croom.lx; x <= croom.hx; x++) {
                for (let y = croom.ly; y <= croom.hy; y++) {
                    const depth = Math.abs(game.u?.uz?.dlevel ?? 1);
                    const amount = rn1(depth * 100, 51);
                    mkgold(amount, x, y);
                }
            }
            break;
        case COURT:
        case ZOO:
        case BEEHIVE:
        case ANTHOLE:
        case COCKNEST:
        case LEPREHALL:
        case MORGUE:
        case BARRACKS:
            await fill_zoo(croom);
            break;
        default:
            break;
        }
    }
}
// C ref: dungeon.c Is_branchlev — check if current level is a branch endpoint
function _is_branchlev() {
    const g = game;
    const dnum = g.u?.uz?.dnum ?? 0;
    const dlevel = g.u?.uz?.dlevel ?? 1;
    const branches = g.branches || [];
    for (const br of branches) {
        if ((br.end1?.dnum === dnum && br.end1?.dlevel === dlevel)
            || (br.end2?.dnum === dnum && br.end2?.dlevel === dlevel)) {
            return br;
        }
    }
    return null;
}
// RNG: rn2(3) monster, while(!rn2(x)) traps, rn2(3) gold, rn2(10) fountain,
//      rn2(60) sink, rn2(60) altar, rn2(x) grave, rn2(20) statue
async function fill_ordinary_room(croom, bonus_items) {
    const g = game;
    if (!croom || (croom.rtype !== OROOM && croom.rtype !== THEMEROOM))
        return;
    // Fill subrooms first
    for (let i = 0; i < (croom.nsubrooms || 0); i++) {
        const sub = croom.sbrooms?.[i];
        if (sub) await fill_ordinary_room(sub, false);
    }
    if (croom.needfill !== FILL_NORMAL)
        return;
    // Put a sleeping monster inside (33% chance, or always if hero has amulet)
    const pos = { x: 0, y: 0 };
    if ((g.u?.uhave?.amulet || !rn2(3)) && somexyspace(croom, pos)) {
        const tmonst = await makemon(null, pos.x, pos.y, MM_NOGRP);
        // C ref: mklev.c:976-978 — random spider gets a web trap
        if (tmonst && tmonst.data === mons[PM_GIANT_SPIDER]
            && !occupied(pos.x, pos.y)) {
            await maketrap(pos.x, pos.y, WEB);
        }
    }
    // Put traps inside
    // C ref: mklev.c:981 — uses level_difficulty()
    let x = 8 - Math.trunc(level_difficulty() / 6);
    if (x <= 1) x = 2;
    let trycnt = 0;
    while (!rn2(x) && ++trycnt < 1000) {
        await mktrap_room(croom);
    }
    // Gold
    if (!rn2(3) && somexyspace(croom, pos)) {
        mkgold(0, pos.x, pos.y);
    }
    // C ref: mklev.c:988-989 — Rogue level skips fountains, sinks,
    // altars, graves, statues, and bonus items.
    if (Is_rogue_level(g.u?.uz)) return;
    // Fountain (10% chance)
    if (!rn2(10)) {
        mkfount(croom);
    }
    // Sink (1/60 chance)
    if (!rn2(60)) {
        // C ref: mklev.c:983 mksink(croom)
        if (find_okay_roompos(croom, pos)) {
            const sinkLoc = g.level?.at(pos.x, pos.y);
            if (sinkLoc) {
                sinkLoc.typ = SINK;
                const lvl = g.level?.flags ?? {};
                lvl.nsinks = (lvl.nsinks || 0) + 1;
            }
        }
    }
    // C ref: mklev.c:995 — mkaltar(croom)
    if (!rn2(60)) {
        mkaltar(croom);
    }
    // Grave — C ref: mklev.c:996 uses depth(&u.uz)
    x = 80 - ((g.u?.uz?.dlevel ?? 1) * 2);
    if (x < 2) x = 2;
    if (!rn2(x)) {
        mkgrave(croom);
    }
    // Statue (5% chance)
    if (!rn2(20) && somexyspace(croom, pos)) {
        mkcorpstat(STATUE, null, null, pos.x, pos.y, CORPSTAT_INIT);
    }
    // Bonus items (supply chest on early levels)
    // C ref: mklev.c:1016-1116
    let skip_chests = false;
    if (bonus_items && somexyspace(croom, pos)) {
        // C ref: mklev.c:1017-1025 — mines branch entry: comestible
        // Is_branchlev checks if current level has a branch stairway.
        // We check stairs: if any stair leads to a different dungeon, this is a branch level.
        const branchp = _is_branchlev();
        const mines_dnum = 2; // mines dungeon number
        const oracle_dlevel = g.oracle_level?.dlevel ?? 5;
        if (branchp && g.u?.uz?.dnum !== mines_dnum
            && (branchp.end1?.dnum === mines_dnum || branchp.end2?.dnum === mines_dnum)) {
            // Mines entrance level — bonus comestible
            // C does NOT set skip_chests here (only the supply chest path does)
            mksobj_at((rn2(5) < 3) ? FOOD_RATION : rn2(2) ? CRAM_RATION : LEMBAS_WAFER,
                pos.x, pos.y, true, false);
        } else if (g.u?.uz?.dnum === 0 && (g.u?.uz?.dlevel ?? 1) < oracle_dlevel && rn2(3)) {
            const depth = g.u?.uz?.dlevel ?? 1;
            // Supply chest on early DoD levels (before oracle)
            const supply_chest = mksobj_at(rn2(3) ? CHEST : LARGE_BOX,
                                           pos.x, pos.y, false, false);
            if (supply_chest) {
                supply_chest.olocked = !!rn2(6);
                // Fill supply chest with items
                let tryct = 0;
                let cursed;
                do {
                    // 50% potion of healing, 50% random supply item
                    const supply_items = [
                        POT_EXTRA_HEALING,
                        POT_SPEED,
                        POT_GAIN_ENERGY,
                        SCR_ENCHANT_WEAPON,
                        SCR_ENCHANT_ARMOR,
                        SCR_CONFUSE_MONSTER,
                        SCR_SCARE_MONSTER,
                        WAN_DIGGING,
                        SPE_HEALING,
                    ];
                    let otyp;
                    if (rn2(2)) {
                        otyp = POT_HEALING;
                    } else {
                        otyp = supply_items[rn2(supply_items.length)];
                    }
                    const otmp = mksobj(otyp, true, false);
                    if (otmp && otyp === POT_HEALING && rn2(2)) {
                        otmp.quan = 2;
                        otmp.owt = weight(otmp);
                    }
                    cursed = otmp?.cursed ?? false;
                    add_to_container(supply_chest, otmp);
                    if (++tryct >= 50) break;
                } while (cursed || !rn2(5));
                // C ref: mklev.c:1089-1116 — maybe extra random item
                if (rn2(3)) {
                    const extra_classes = [
                        FOOD_CLASS, WEAPON_CLASS, ARMOR_CLASS, GEM_CLASS,
                        SCROLL_CLASS, POTION_CLASS, RING_CLASS,
                        SPBOOK_no_NOVEL, SPBOOK_no_NOVEL, SPBOOK_no_NOVEL
                    ];
                    const oclass = extra_classes[rn2(extra_classes.length)];
                    try {
                        let otmp = mkobj(oclass, false);
                        // C: for spellbooks, bias toward lower level
                        // (generate again and take the lower-level one)
                        if (oclass === SPBOOK_no_NOVEL && otmp) {
                            const maxpass = (depth > 2) ? 2 : 3;
                            for (let pass = 1; pass <= maxpass; pass++) {
                                const otmp2 = mkobj(oclass, false);
                                if ((game.objects[otmp.otyp]?.oc_oc2 ?? 0)
                                    <= (game.objects[otmp2.otyp]?.oc_oc2 ?? 0)) {
                                    dealloc_obj(otmp2);
                                } else {
                                    dealloc_obj(otmp);
                                    otmp = otmp2;
                                }
                            }
                        }
                        add_to_container(supply_chest, otmp);
                    } catch (_e) {}
                }
                supply_chest.owt = weight(supply_chest);
            }
            skip_chests = true;
        }
    }
    // C ref: mklev.c:1127 — box/chest check
    // !rn2(nroom * 5 / 2) chance of a box or chest
    if (!skip_chests && !rn2(Math.trunc(g.level.nroom * 5 / 2)) && somexyspace(croom, pos)) {
        const LARGE_BOX2 = 214, CHEST2 = 215;
        try { mksobj_at(rn2(3) ? LARGE_BOX2 : CHEST2, pos.x, pos.y, true, false); } catch (_e) {}
    }
    // C ref: mklev.c:1132-1145 — graffiti check
    // CRITICAL: C calls random_engraving() FIRST, then somexyspace().
    // The RNG order matters for parity.
    const depth = g.u?.uz?.dlevel ?? 1;
    if (!rn2(27 + 3 * Math.abs(depth))) {
        // C: mesg = random_engraving(buf, pristinebuf) — text selection first
        const { text: engrText, pristine: engrPristine } = random_engraving();
        if (engrText) {
            // C ref: mklev.c:1146-1153 — ignore somexyspace() return value and
            // drive retry by selected tile type plus rn2(40).
            let x = pos.x;
            let y = pos.y;
            do {
                somexyspace(croom, pos);
                x = pos.x;
                y = pos.y;
                const tileTyp = g.level?.at(x, y)?.typ;
                if (tileTyp === ROOM) break;
            } while (!rn2(40));
            if (g.level?.at(x, y)?.typ === ROOM) {
                // C: make_engr_at(x, y, mesg, pristinebuf, 0, MARK)
                make_engr_at(x, y, engrText, engrPristine, 0, MARK);
            }
        }
    }
    // C ref: mklev.c:1148-1161 — random objects (skip_nonrogue label)
    if (!rn2(3) && somexyspace(croom, pos)) {
        try { mkobj_at(RANDOM_CLASS, pos.x, pos.y, true); } catch (_e) {}
        let objTrycnt = 0;
        while (!rn2(5)) {
            if (++objTrycnt > 100) break;
            if (somexyspace(croom, pos)) {
                try { mkobj_at(RANDOM_CLASS, pos.x, pos.y, true); } catch (_e) {}
            }
        }
    }
}
// C ref: mklev.c:1420 water_has_kelp()
// RNG: rn2(kelp_pool) or rn2(kelp_moat)
function water_has_kelp(x, y, kelp_pool, kelp_moat) {
    const map = game.level;
    const loc = map.at(x, y);
    if (!loc) return false;
    if (kelp_pool && (loc.typ === POOL || loc.typ === WATER)
        && !rn2(kelp_pool))
        return true;
    if (kelp_moat && loc.typ === MOAT && !rn2(kelp_moat))
        return true;
    return false;
}
export function mineralize_kelp(kelp_pool, kelp_moat, skip_lvl_checks) {
    if (kelp_pool < 0) kelp_pool = 10;
    if (kelp_moat < 0) kelp_moat = 30;
    // Place kelp in water (skip for endgame)
    if (!skip_lvl_checks) {
        // In_endgame check — not on level 1
    }
    for (let x = 2; x < COLNO - 2; x++)
        for (let y = 1; y < ROWNO - 1; y++)
            if (water_has_kelp(x, y, kelp_pool, kelp_moat)) {
                try { mksobj_at(KELP_FROND, x, y, true, false); } catch (_e) {}
            }
}
// C ref: mklev.c:1439 mineralize()
// Places gold and gems in stone walls. Heavy RNG consumer.
export function mineralize(kelp_pool, kelp_moat, goldprob, gemprob, skip_lvl_checks) {
    const map = game.level;
    // C ref: mklev.c:1471-1472
    // Place kelp except on the Endgame planes.
    if (!skip_lvl_checks && in_endgame(game.u?.uz))
        return;
    mineralize_kelp(kelp_pool, kelp_moat, skip_lvl_checks);
    // C ref: mklev.c mineralize() early exclusions.
    // Almost all special levels are excluded.
    if (!skip_lvl_checks) {
        const uz = game.u?.uz;
        const sp = is_special_level(uz);
        if (in_hell(uz)
            || in_v_tower(uz)
            || is_rogue_level(uz)
            || !!game.level?.flags?.arboreal
            || (!!sp && !is_oracle_level(uz) && (!in_mines(uz) || !!sp.flags?.town))) {
            return;
        }
    }
    // Determine gold/gem probabilities
    const absDepth = depth_of_level(game.u?.uz);
    const dunLevel = game.u?.uz?.dlevel ?? 1;
    if (goldprob < 0)
        goldprob = 20 + Math.trunc(absDepth / 3);
    if (gemprob < 0)
        gemprob = Math.trunc(goldprob / 4);
    // C ref: mklev.c:1494-1501 — mines have MORE goodies, quest has fewer
    if (!skip_lvl_checks) {
        const uz = game.u?.uz;
        if (uz && uz.dnum === game.mines_dnum) {
            goldprob *= 2;
            gemprob *= 3;
        } else if (uz && uz.dnum === game.quest_dnum) {
            goldprob = Math.trunc(goldprob / 4);
            gemprob = Math.trunc(gemprob / 6);
        }
    }
    // Seed stone with gold and gems
    for (let x = 2; x < COLNO - 2; x++) {
        for (let y = 1; y < ROWNO - 1; y++) {
            const loc = map.at(x, y);
            const locBelow = map.at(x, y + 1);
            if (!loc || !locBelow) continue;
            if (locBelow.typ !== STONE) {
                y += 2; // next two not eligible
                continue;
            }
            if (loc.typ !== STONE) {
                y += 1;
                continue;
            }
            // Check all 8 neighbors are stone
            const n = (d) => { const l = map.at(x + d[0], y + d[1]); return l && l.typ === STONE; };
            if (!(loc.wall_info & W_NONDIGGABLE)
                && n([0,-1]) && n([1,-1]) && n([-1,-1])
                && n([1,0]) && n([-1,0])
                && n([1,1]) && n([-1,1])) {
                // Gold
                if (rn2(1000) < goldprob) {
                    const otmp = mksobj(GOLD_PIECE, false, false);
                    otmp.ox = x;
                    otmp.oy = y;
                    otmp.quan = 1 + rnd(goldprob * 3);
                    otmp.owt = weight(otmp);
                    if (!rn2(3)) {
                        // add_to_buried(otmp) — buried gold
                    } else {
                        place_object(otmp, x, y);
                    }
                }
                // Gems
                if (rn2(1000) < gemprob) {
                    const cnt = rnd(2 + Math.trunc(dunLevel / 3));
                    for (let i = 0; i < cnt; i++) {
                        const otmp = mkobj(GEM_CLASS, false);
                        if (otmp) {
                            if (otmp.otyp === ROCK) {
                                dealloc_obj(otmp);
                            } else {
                                otmp.ox = x;
                                otmp.oy = y;
                                if (!rn2(3)) {
                                    // add_to_buried(otmp)
                                } else {
                                    place_object(otmp, x, y);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
// C ref: mkmaze.c:1353 get_level_extends()
export function get_level_extends() {
    const map = game.level;
    let xmin = 0, xmax = COLNO - 1, ymin = 0, ymax = ROWNO - 1;
    let found = false, nonwall = false;
    for (xmin = 0; !found && xmin <= COLNO; xmin++) {
        for (let y = 0; y <= ROWNO - 1; y++) {
            const typ = map.at(xmin, y)?.typ ?? STONE;
            if (typ !== STONE) {
                found = true;
                if (!IS_WALL(typ))
                    nonwall = true;
            }
        }
    }
    xmin -= (nonwall || !game.level?.flags?.is_maze_lev) ? 2 : 1;
    if (xmin < 0) xmin = 0;
    found = false;
    nonwall = false;
    for (xmax = COLNO - 1; !found && xmax >= 0; xmax--) {
        for (let y = 0; y <= ROWNO - 1; y++) {
            const typ = map.at(xmax, y)?.typ ?? STONE;
            if (typ !== STONE) {
                found = true;
                if (!IS_WALL(typ))
                    nonwall = true;
            }
        }
    }
    xmax += (nonwall || !game.level?.flags?.is_maze_lev) ? 2 : 1;
    if (xmax >= COLNO) xmax = COLNO - 1;
    found = false;
    nonwall = false;
    for (ymin = 0; !found && ymin <= ROWNO - 1; ymin++) {
        for (let x = xmin; x <= xmax; x++) {
            const typ = map.at(x, ymin)?.typ ?? STONE;
            if (typ !== STONE) {
                found = true;
                if (!IS_WALL(typ))
                    nonwall = true;
            }
        }
    }
    ymin -= (nonwall || !game.level?.flags?.is_maze_lev) ? 2 : 1;
    found = false;
    nonwall = false;
    for (ymax = ROWNO - 1; !found && ymax >= 0; ymax--) {
        for (let x = xmin; x <= xmax; x++) {
            const typ = map.at(x, ymax)?.typ ?? STONE;
            if (typ !== STONE) {
                found = true;
                if (!IS_WALL(typ))
                    nonwall = true;
            }
        }
    }
    ymax += (nonwall || !game.level?.flags?.is_maze_lev) ? 2 : 1;
    return { xmin, xmax, ymin, ymax };
}
// C ref: mkmaze.c:1429 bound_digging()
function bound_digging() {
    if (Is_earthlevel(game.u?.uz))
        return;
    const map = game.level;
    const { xmin, xmax, ymin, ymax } = get_level_extends();
    for (let x = 0; x < COLNO; x++) {
        for (let y = 0; y < ROWNO; y++) {
            const loc = map.at(x, y);
            if (!loc) continue;
            if (IS_STWALL(loc.typ)
                && (y <= ymin || y >= ymax || x <= xmin || x >= xmax)) {
                loc.wall_info |= W_NONDIGGABLE;
                loc.nondiggable = true;
            }
        }
    }
}
// C ref: mklev.c:1533 level_finalize_topology()
export function level_finalize_topology(options = {}) {
    const skipMineralize = !!options.skipMineralize;
    bound_digging();
    if (!skipMineralize) {
        mineralize(-1, -1, -1, -1, false);
    }
    game.in_mklev = false;
    // C ref: mklev.c:1549-1552 — reset special-level offset helpers after mklev.
    game.sp_xstart = 0;
    game.sp_ystart = 0;
    // C ref: mklev.c:1556-1558 — entering a morgue marks the level as graveyard.
    if (game.level?.flags?.has_morgue) {
        game.level.flags.graveyard = true;
    }
    // C ref: mklev.c:1559-1567 — topologize all rectangular rooms on non-maze levels.
    if (!game.level?.flags?.is_maze_lev) {
        const nroom = game.level?.nroom ?? 0;
        for (let i = 0; i < nroom; i++) {
            topologize(game.level.rooms?.[i]);
        }
    }
    set_wall_state();
    // C ref: mklev.c:1570-1573 — preserve original room type metadata.
    const rooms = game.level?.rooms ?? [];
    for (let i = 0; i < rooms.length; i++) {
        const rm = rooms[i];
        if (rm && rm.rtype != null) rm.orig_rtype = rm.rtype;
    }
}