Game.lua 115 KB
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
-- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2019 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org

require "engine.class"
require "engine.GameTurnBased"
require "engine.interface.GameMusic"
require "engine.interface.GameSound"
require "engine.interface.GameTargeting"
local KeyBind = require "engine.KeyBind"
local Savefile = require "engine.Savefile"
local DamageType = require "engine.DamageType"
local Zone = require "mod.class.Zone"
local Tiles = require "engine.Tiles"
local Map = require "engine.Map"
local Level = require "engine.Level"
local Birther = require "mod.dialogs.Birther"
local Astar = require "engine.Astar"
local DirectPath = require "engine.DirectPath"
local Shader = require "engine.Shader"
local HighScores = require "engine.HighScores"
local FontPackage = require "engine.FontPackage"

local NicerTiles = require "mod.class.NicerTiles"
local GameState = require "mod.class.GameState"
local Store = require "mod.class.Store"
local Trap = require "mod.class.Trap"
local Grid = require "mod.class.Grid"
local Actor = require "mod.class.Actor"
local Party = require "mod.class.Party"
local Player = require "mod.class.Player"
local NPC = require "mod.class.NPC"
local Entity = require "engine.Entity"

local DebugConsole = require "engine.DebugConsole"
local FlyingText = require "engine.FlyingText"
local Tooltip = require "mod.class.Tooltip"
local BigNews = require "mod.class.BigNews"

local Calendar = require "engine.Calendar"
local Gestures = require "engine.ui.Gestures"

local Dialog = require "engine.ui.Dialog"
local MapMenu = require "mod.dialogs.MapMenu"

module(..., package.seeall, class.inherit(engine.GameTurnBased, engine.interface.GameMusic, engine.interface.GameSound, engine.interface.GameTargeting))

-- Difficulty settings
-- Adjustments handled in _M:loaded, _M:noStairsTime, NPC:addedToLevel, Actor::on_set_temporary_effect, 
-- data.damage_types (setDefaultProjector), GameState:zoneCheckBackupGuardian
DIFFICULTY_EASY = 1
DIFFICULTY_NORMAL = 2
DIFFICULTY_NIGHTMARE = 3
DIFFICULTY_INSANE = 4
DIFFICULTY_MADNESS = 5
PERMADEATH_INFINITE = 1
PERMADEATH_MANY = 2
PERMADEATH_ONE = 3

-- Tell the engine that we have a fullscreen shader that supports gamma correction
support_shader_gamma = true

function _M:init()
	engine.GameTurnBased.init(self, engine.KeyBind.new(), 1000, 100)
	engine.interface.GameMusic.init(self)
	engine.interface.GameSound.init(self)

	-- Pause at birth
	self.paused = true

	-- Same init as when loaded from a savefile
	self:loaded()

	self.visited_zones = {}
	self.tiles_attachements = {}
	self.tiles_facing = {}
end

function _M:run()
	class:triggerHook{"ToME:run"}
	local ret = self:runReal()
	class:triggerHook{"ToME:runDone"}
	return ret
end

function _M:runReal()
	self.delayed_log_damage = {}
	self.delayed_log_messages = {}
	self.calendar = Calendar.new("/data/calendar_allied.lua", "Today is the %s %s of the %s year of the Age of Ascendancy of Maj'Eyal.\nThe time is %02d:%02d.", 122, 167, 11)

	self.uiset:activate()

	local flyfont, flysize = FontPackage:getFont("flyer")
	self.tooltip = Tooltip.new(self.uiset.init_font_mono, self.uiset.init_size_mono, {255,255,255}, {30,30,30,230})
	self.tooltip2 = Tooltip.new(self.uiset.init_font_mono, self.uiset.init_size_mono, {255,255,255}, {30,30,30,230})
	self.flyers = FlyingText.new(flyfont, flysize, flyfont, flysize + 3)
	self.flyers:enableShadow(0.6)
	game:setFlyingText(self.flyers)

	self.bignews = BigNews.new(FontPackage:getFont("bignews"))

	self.nicer_tiles = NicerTiles.new()

	-- Ok everything is good to go, activate the game in the engine!
	self:setCurrent()

	-- Start time
	self.real_starttime = os.time()

	self:setupDisplayMode(false, "postinit")
	if self.level and self.level.data.day_night then self.state:dayNightCycle() end
	if self.level and self.player then self:rebuildCalendar() end

	-- Setup inputs
	self:setupCommands()
	self:setupMouse()

	-- Starting from here we create a new game
	if self.player and self.player.dead then
		print("Player is dead, rebooting")
		util.showMainMenu()
		return
	end
	if not self.player then self:newGame() end

	engine.interface.GameTargeting.init(self)
	if self.target then self.target:enableFBORenderer("ui/targetshader.png", "target_fbo") end

	self.uiset.hotkeys_display.actor = self.player
	self.uiset.npcs_display.actor = self.player

	-- Run the current music if any
	self:onTickEnd(function()
		self:playMusic()
		if self.level then
			self.level.map:moveViewSurround(self.player.x, self.player.y, config.settings.tome.scroll_dist, config.settings.tome.scroll_dist)
		end
	end)

	-- Create the map scroll text overlay
	local lfont = FontPackage:get("bignews", true)
	lfont:setStyle("bold")
	local s = core.display.drawStringBlendedNewSurface(lfont, _t"<Scroll mode, press direction keys to scroll, press again to exit>", unpack(colors.simple(colors.GOLD)))
	lfont:setStyle("normal")
	self.caps_scroll = {s:glTexture()}
	self.caps_scroll.w, self.caps_scroll.h = s:getSize()

	self.zone_font = FontPackage:get("zone")

	self.shake_time = nil
	self.shake_force = 0
	self.shake_x = 0
	self.shake_y = 0

	self.inited = true

	if self.level and self.level.map then
		self.nicer_tiles:postProcessLevelTilesOnLoad(self.level)
	end
end

function _M:rebuildCalendar()
	self.calendar = Calendar.new("/data/calendar_"..(self.player.calendar or "allied")..".lua", "Today is the %s %s of the %s year of the Age of Ascendancy of Maj'Eyal.\nThe time is %02d:%02d.", (self.player.calendar_start_year or 122), (self.player.calendar_start_day or 167), (self.player.calendar_start_hour or 11))
end

--- Resize the hotkeys
function _M:resizeIconsHotkeysToolbar()
	self.uiset:resizeIconsHotkeysToolbar()
end

--- Checks if the current character is "tainted" by cheating
function _M:isTainted()
	if config.settings.cheat then return true end
	return (game.player and game.player.__cheated) and true or false
end

--- Sets the player name
function _M:setPlayerName(name)
	name = name:removeColorCodes():gsub("#", " "):sub(1, 25)
	self.save_name = name
	self.player_name = name
	if self.party and self.party:findMember{main=true} then
		self.party:findMember{main=true}.name = name
	end
end

function _M:newGame()
	self.party = Party.new{}
	local player = Player.new{name=self.player_name, game_ender=true}
	self.party:addMember(player, {
		control="full",
		type="player",
		title=_t"Main character",
		main=true,
		orders = {target=true, anchor=true, behavior=true, leash=true, talents=true},
	})
	self.party:setPlayer(player)

	-- Create the entity to store various game state things
	self.state = GameState.new{}
	local birth_done = function()
		if self.state.birth.__allow_rod_recall then self.state:allowRodRecall(true) self.state.birth.__allow_rod_recall = nil end
		if self.state.birth.__allow_transmo_chest and profile.mod.allow_build.birth_transmo_chest then
			self.state.birth.__allow_transmo_chest = nil
			local chest = self.zone:makeEntityByName(self.level, "object", "TRANSMO_CHEST")
			if chest then
				self.zone:addEntity(self.level, chest, "object")
				self.player:addObject(self.player:getInven("INVEN"), chest)
			end
		end

		for i = 1, 50 do
			local o = self.state:generateRandart{add_pool=true}
			self.zone.object_list[#self.zone.object_list+1] = o
		end

		self.player.innate_player = true
		if config.settings.cheat then self.player.__cheated = true end

		if game.__mod_info then
			local beta = engine.version_hasbeta()
			self.player.__created_in_version = game.__mod_info.version_name..(beta and "-"..beta or "")
		end

		if self.player.max_life_bonus then
			self.player.max_life = self.player.max_life + self.player.max_life_bonus
			self.player.life = self.player.life + self.player.max_life_bonus
			self.player.max_life_bonus = nil
		end

		self.player:recomputeGlobalSpeed()
		self:rebuildCalendar()

		-- Force the hotkeys to be sorted.
		self.player:sortHotkeys()

		-- Register the character online if possible
		self.player:getUUID()
		self:updateCurrentChar()
	end

	if not config.settings.tome.tactical_mode_set then
		self.always_target = true
	else
		self.always_target = config.settings.tome.tactical_mode
	end
	local nb_unlocks, max_unlocks, categories = self:countBirthUnlocks()
	local unlocks_order = { class=1, race=2, cometic=3, other=4 }
	local unlocks = {}
	for cat, d in pairs(categories) do unlocks[#unlocks+1] = {desc=d.nb.."/"..d.max.." ".._t(cat), order=unlocks_order[cat] or 99} end
	table.sort(unlocks, "order")
	self.creating_player = true
	self.extra_birth_option_defs = {}
	self:triggerHook{"ToME:extraBirthOptions", options = self.extra_birth_option_defs}
	local birth; birth = Birther.new(("Character Creation ( %s unlocked options)"):tformat(table.concat(table.extract_field(unlocks, "desc", ipairs), ", ")), self.player, {"base", "world", "difficulty", "permadeath", "race", "subrace", "sex", "class", "subclass" }, function(loaded)
		if not loaded then
			self.calendar = Calendar.new("/data/calendar_"..(self.player.calendar or "allied")..".lua", "Today is the %s %s of the %s year of the Age of Ascendancy of Maj'Eyal.\nThe time is %02d:%02d.", 122, 167, 11)
			self.player:check("make_tile")
			self.player.make_tile = nil
			self.player:check("before_starting_zone")
			self.player:check("class_start_check")

			-- Save current state of extra birth options.
			self.player.extra_birth_options = {}
			for _, option in ipairs(self.extra_birth_option_defs) do
				if option.id then
					self.player.extra_birth_options[option.id] = config.settings.tome[option.id]
				end
			end

			-- Configure & create the worldmap
			self.player.last_wilderness = self.player.default_wilderness[3] or "wilderness"
			game:onLevelLoad(self.player.last_wilderness.."-1", function(zone, level)
				game.player.wild_x, game.player.wild_y = game.player.default_wilderness[1], game.player.default_wilderness[2]
				if type(game.player.wild_x) == "string" and type(game.player.wild_y) == "string" then
					local spot = level:pickSpot{type=game.player.wild_x, subtype=game.player.wild_y} or {x=1,y=1}
					game.player.wild_x, game.player.wild_y = spot.x, spot.y
				end
			end)

			-- Generate
			if self.player.__game_difficulty then self:setupDifficulty(self.player.__game_difficulty) end
			self:setupPermadeath(self.player)
			--self:changeLevel(1, "test")
			self:changeLevel(self.player.starting_level or 1, self.player.starting_zone, {force_down=self.player.starting_level_force_down, direct_switch=true})

			print("[PLAYER BIRTH] resolve...")
			self.player:resolve()
			self.player:resolve(nil, true)
			self.player.energy.value = self.energy_to_act
			Map:setViewerFaction(self.player.faction)
			self.player:updateModdableTile()

			self.paused = true
			print("[PLAYER BIRTH] resolved!")
			local birthend = function()
				local d = require("engine.dialogs.ShowText").new(_t"Welcome to #LIGHT_BLUE#Tales of Maj'Eyal", "intro-"..self.player.starting_intro, {name=self.player.name}, nil, nil, function()
					self.player:resetToFull()
					self.player:registerCharacterPlayed()
					self.player:onBirth(birth)
					-- For quickbirth
					savefile_pipe:push(self.player.name, "entity", self.party, "engine.CharacterVaultSave")

					self.player:grantQuest(self.player.starting_quest)
					self.creating_player = false

					birth_done()
					self.player:check("on_birth_done")
					self:setTacticalMode(self.always_target)
					self:triggerHook{"ToME:birthDone"}

					if __module_extra_info.birth_done_script then loadstring(__module_extra_info.birth_done_script)() end
				end, true)
				self:registerDialog(d)
				if __module_extra_info.no_birth_popup then d.key:triggerVirtual("EXIT") end
			end

			if self.player.no_birth_levelup or __module_extra_info.no_birth_popup then birthend()
			else self.player:playerLevelup(birthend, true) end
		-- Player was loaded from a premade
		else
			self.calendar = Calendar.new("/data/calendar_"..(self.player.calendar or "allied")..".lua", "Today is the %s %s of the %s year of the Age of Ascendancy of Maj'Eyal.\nThe time is %02d:%02d.", 122, 167, 11)
			Map:setViewerFaction(self.player.faction)
			if self.player.__game_difficulty then self:setupDifficulty(self.player.__game_difficulty) end
			self:setupPermadeath(self.player)

			-- Configure & create the worldmap
			self.player.last_wilderness = self.player.default_wilderness[3] or "wilderness"
			game:onLevelLoad(self.player.last_wilderness.."-1", function(zone, level)
				game.player.wild_x, game.player.wild_y = game.player.default_wilderness[1], game.player.default_wilderness[2]
				if type(game.player.wild_x) == "string" and type(game.player.wild_y) == "string" then
					local spot = level:pickSpot{type=game.player.wild_x, subtype=game.player.wild_y} or {x=1,y=1}
					game.player.wild_x, game.player.wild_y = spot.x, spot.y
				end
			end)

			-- Tell the level gen code to add all the party
			self.to_re_add_actors = {}
			for act, _ in pairs(self.party.members) do if self.player ~= act then self.to_re_add_actors[act] = true end end

			self:changeLevel(self.player.starting_level or 1, self.player.starting_zone, {force_down=self.player.starting_level_force_down, direct_switch=true})
			self.player:grantQuest(self.player.starting_quest)
			self.creating_player = false

			-- Add all items so they regen correctly
			self.player:inventoryApplyAll(function(inven, item, o) game:addEntity(o) end)

			birth_done()
			self.player:check("on_birth_done")
			self:setTacticalMode(self.always_target)
			self:triggerHook{"ToME:birthDone"}
		end
	end, quickbirth, 800, 600)
	self:registerDialog(birth)
end

function _M:setupDifficulty(d)
	self.difficulty = d
end

--- Apply game difficulty to a zone, updating zone.level_range
-- @param zone the zone to update
-- @param level_range number(lowest base level) or table (level ranges) to update the level range to
--  will not update a zone that has already been updated unless level_range is specified
--  saves the original zone.level_range to zone.base_level_range
function _M:applyDifficulty(zone, level_range)
	if not zone.__applied_difficulty or level_range then
		zone.base_level_range = zone.base_level_range or table.clone(zone.level_range, true)
		if type(level_range) == "number" then
			zone.level_range = {level_range, level_range}
		elseif type(level_range) == "table" then
			zone.level_range = table.clone(level_range)
		end
		-- difficulty effects are phased in as the player reaches level 10
		local diff_adjust = math.min(1, game:getPlayer(true).level/10)
		local lev_mult = game.state.birth.difficulty_level_mult or 1
		local lev_add = game.state.birth.difficulty_level_add or 0
		
		if lev_mult ~= 1 then
			local diff_adjust = math.min(1, game:getPlayer(true).level/10)
			lev_mult = 1 + (lev_mult - 1)*diff_adjust
			lev_add = lev_add*diff_adjust
			zone.level_range[1] = zone.level_range[1]*lev_mult + lev_add
			zone.level_range[2] = zone.level_range[2]*lev_mult + lev_add
			zone:updateBaseLevel()
		end
		zone.__applied_difficulty = true
	end
end

function _M:setupPermadeath(p)
	if p:attr("infinite_lifes") then self.permadeath = PERMADEATH_INFINITE
	elseif p:attr("easy_mode_lifes") then self.permadeath = PERMADEATH_MANY
	else self.permadeath = PERMADEATH_ONE
	end
end

function _M:loaded()
	engine.GameTurnBased.loaded(self)
	engine.interface.GameMusic.loaded(self)
	engine.interface.GameSound.loaded(self)
	Zone:setup{
		npc_class="mod.class.NPC", grid_class="mod.class.Grid", object_class="mod.class.Object", trap_class="mod.class.Trap",
		on_setup = function(zone)
			self:applyDifficulty(zone) -- Increases zone level for higher difficulties
		end,
	}
	Zone.check_filter = function(...) return self.state:entityFilter(...) end
	Zone.default_prob_filter = true
	Zone.default_filter = function(...) return self.state:defaultEntityFilter(...) end
	Zone.alter_filter = function(...) return self.state:entityFilterAlter(...) end
	Zone.post_filter = function(...) return self.state:entityFilterPost(...) end
	Zone.ego_filter = function(...) return self.state:egoFilter(...) end
	Entity.alter_entity_load = function(e)
		if e:getEntityKind() == "object" and e.unique and not e.randart and e.level_range and not e.force_max_level_range then
			e.level_range = table.clone(e.level_range)
			e.level_range[2] = nil
		end
	end

	self.uiset = (require("mod.class.uiset."..(config.settings.tome.uiset_mode or "Minimalist"))).new()

	Map:setViewerActor(self.player)
	self:setupDisplayMode(false, "init")
	self:setupDisplayMode(false, "postinit")
	if self.player then self.player.changed = true end
	self.key = engine.KeyBind.new()

	if self.always_target == true or self.always_target == "old" then Map:setViewerFaction(self.player.faction) end
	if self.player and config.settings.cheat then self.player.__cheated = true end
	self:onTickEnd(function() self:updateCurrentChar() end)

	if self.zone and self.zone.on_loaded then self.zone.on_loaded(self.level.level) end
end

function _M:computeAttachementSpotsFromTable(ta)
	local base = ta.default_base or 64
	local res = { }

	for tile, data in pairs(ta.tiles or {}) do
		local base = data.base or base
		local yoff = data.yoff or 0
		local t = {}
		res[tile] = t
		for kind, d in pairs(data) do if kind ~= "base" and kind ~= "yoff" then
			t[kind] = { x=d.x / base, y=(d.y + yoff) / base }
		end end
	end

	for race, data in pairs(ta.dolls or {}) do
		local base = data.base or base
		for sex, d in pairs(data) do if sex ~= "base" then
			local t = {}
			res["dolls_"..race.."_"..sex] = t
			local yoff = d.yoff or 0
			local base = d.base or base
			for kind, d in pairs(d) do if kind ~= "yoff" and kind ~= "base" then
				t[kind] = { x=d.x / base, y=(d.y + yoff) / base }
			end end
		end end
	end

	self.tiles_attachements = res
end

function _M:computeAttachementSpots()
	local t = {}
	if fs.exists(Tiles.prefix.."attachements.lua") then
		print("Loading tileset attachements from ", Tiles.prefix.."attachements.lua")
		local f, err = loadfile(Tiles.prefix.."attachements.lua")
		if not f then print("Loading tileset attachements error", err)
		else
			setfenv(f, t)
			local ok, err = pcall(f)
			if not ok then print("Loading tileset attachements error", err) end
		end
	end
	for _, file in ipairs(fs.list(Tiles.prefix)) do if file:find("^attachements%-.+.lua$") then
		print("Loading tileset attachements from ", Tiles.prefix..file)
		local f, err = loadfile(Tiles.prefix..file)
		if not f then print("Loading tileset attachements error", err)
		else
			setfenv(f, t)
			local ok, err = pcall(f)
			if not ok then print("Loading tileset attachements error", err) end
		end
	end end
	self:computeAttachementSpotsFromTable(t)
end

function _M:computeFacingsFromTable(ta)
	local base = ta.default_base or 64
	local res = { }

	for tile, data in pairs(ta.tiles or {}) do
		res[tile] = data
	end

	for race, data in pairs(ta.dolls or {}) do
		local base = data.base or base
		for sex, d in pairs(data) do if sex ~= "base" then
			local t = {}
			res["dolls_"..race.."_"..sex] = d
		end end
	end

	self.tiles_facing = res
end

function _M:computeFacings()
	local t = {}
	if fs.exists(Tiles.prefix.."facings.lua") then
		print("Loading tileset facings from ", Tiles.prefix.."facings.lua")
		local f, err = loadfile(Tiles.prefix.."facings.lua")
		if not f then print("Loading tileset facings error", err)
		else
			setfenv(f, t)
			local ok, err = pcall(f)
			if not ok then print("Loading tileset facings error", err) end
		end
	end
	for _, file in ipairs(fs.list(Tiles.prefix)) do if file:find("^facings%-.+.lua$") then
		print("Loading tileset facings from ", Tiles.prefix..file)
		local f, err = loadfile(Tiles.prefix..file)
		if not f then print("Loading tileset facings error", err)
		else
			setfenv(f, t)
			local ok, err = pcall(f)
			if not ok then print("Loading tileset facings error", err) end
		end
	end end
	self:computeFacingsFromTable(t)
end

function _M:setupDisplayMode(reboot, mode)
	if not mode or mode == "init" then
		local gfx = config.settings.tome.gfx
		self:saveSettings("tome.gfx", ('tome.gfx = {tiles=%q, size=%q, tiles_custom_dir=%q, tiles_custom_moddable=%s, tiles_custom_adv=%s}\n'):format(gfx.tiles, gfx.size, gfx.tiles_custom_dir or "", gfx.tiles_custom_moddable and "true" or "false", gfx.tiles_custom_adv and "true" or "false"))

		if reboot then
			self.change_res_dialog = true
			self:saveGame()
			util.showMainMenu(false, nil, nil, self.__mod_info.short_name, self.save_name, false)
		end

		Map:resetTiles()
	end

	if not mode or mode == "postinit" then
		local gfx = config.settings.tome.gfx

		-- Select tiles
		Tiles.prefix = "/data/gfx/"..gfx.tiles.."/"
		if config.settings.tome.gfx.tiles == "customtiles" then
			Tiles.prefix = "/data/gfx/"..config.settings.tome.gfx.tiles_custom_dir.."/"
		end
		print("[DISPLAY MODE] Tileset: "..gfx.tiles)
		print("[DISPLAY MODE] Size: "..gfx.size)

		-- Load attachement spots for this tileset
		self:computeAttachementSpots()
		self:computeFacings()

		local do_bg = gfx.tiles == "ascii_full"
		local _, _, tw, th = gfx.size:find("^([0-9]+)x([0-9]+)$")
		tw, th = tonumber(tw), tonumber(th)
		if not tw then tw, th = 64, 64 end
		local pot_th = math.pow(2, math.ceil(math.log(th-0.1) / math.log(2.0)))
		local fsize = math.floor( pot_th/th*(0.7 * th + 5) )

		local map_x, map_y, map_w, map_h = self.uiset:getMapSize()
		if th <= 20 then
			Map:setViewPort(map_x, map_y, map_w, map_h, tw, th, "/data/font/FSEX300.ttf", pot_th, do_bg)
		else
			Map:setViewPort(map_x, map_y, map_w, map_h, tw, th, nil, fsize, do_bg)
		end

		-- Show a count for stacked objects
		Map.object_stack_count = true

		Map.tiles.use_images = true
		if gfx.tiles == "ascii" then
			Map.tiles.use_images = false
			Map.tiles.force_back_color = {r=0, g=0, b=0, a=255}
			Map.tiles.no_moddable_tiles = true
		elseif gfx.tiles == "ascii_full" then
			Map.tiles.use_images = false
			Map.tiles.no_moddable_tiles = true
		elseif gfx.tiles == "shockbolt" then
			Map.tiles.nicer_tiles = true
			if tw > 64 then Map.tiles.sharp_scaling = true end
		elseif gfx.tiles == "oldrpg" then
			Map.tiles.nicer_tiles = true
			Map.tiles.sharp_scaling = true
		elseif gfx.tiles == "customtiles" then
			Map.tiles.no_moddable_tiles = not config.settings.tome.gfx.tiles_custom_moddable
			Map.tiles.nicer_tiles = config.settings.tome.gfx.tiles_custom_adv
		end

		if self.level then
			if self.level.map.finished then
				self.level.map:recreate()
				self.level.map:moveViewSurround(self.player.x, self.player.y, 8, 8)
			end
			engine.interface.GameTargeting.init(self)
		end
		self:setupMiniMap()

		self:createFBOs()

		self:createMapGridLines()
	end
end

function _M:createMapGridLines()
	if not config.settings.tome.show_grid_lines then
		Map:setupGridLines(0, 0, 0, 0, 0)
	elseif self.posteffects and self.posteffects.line_grids and self.posteffects.line_grids.shad then
		Map:setupGridLines(6, unpack(colors.hex1alpha"d5990880"))
	else
		Map:setupGridLines(2, unpack(colors.hex1alpha"d5990880"))
	end
	if self.level and self.level.map then self.level.map:regenGridLines() end
end

function _M:createFBOs()
	print("[GAME] Creating FBOs")

	-- Create the framebuffer
	self.fbo = core.display.newFBO(Map.viewport.width, Map.viewport.height)
	if self.fbo then
		self.fbo_shader = Shader.new("main_fbo")
		self.posteffects = {
			wobbling = Shader.new("main_fbo/wobbling"),
			underwater = Shader.new("main_fbo/underwater"),
			motionblur = Shader.new("main_fbo/motionblur"),
			blur = Shader.new("main_fbo/blur"),
			timestop = Shader.new("main_fbo/timestop"),
			line_grids = Shader.new("main_fbo/line_grids"),
			gestures = Shader.new("main_fbo/gestures"),
			sharpen = Shader.new("main_fbo/sharpen"),
		}
		self.posteffects_use = { self.fbo_shader.shad }
		if not self.fbo_shader.shad then self.fbo = nil self.fbo_shader = nil end
		self.fbo2 = core.display.newFBO(Map.viewport.width, Map.viewport.height)

		if self.gestures and self.posteffects and self.posteffects.gestures and self.posteffects.gestures.shad then self.gestures.shader = self.posteffects.gestures.shad end
	end

	if self.player then self.player:updateMainShader() end

	self.full_fbo = core.display.newFBO(self.w, self.h)
	if self.full_fbo then self.full_fbo_shader = Shader.new("full_fbo") if not self.full_fbo_shader.shad then self.full_fbo = nil self.full_fbo_shader = nil end end

	if self.fbo and self.fbo2 then core.particles.defineFramebuffer(self.fbo)
	else core.particles.defineFramebuffer(nil) end

	if self.target then self.target:enableFBORenderer("ui/targetshader.png", "target_fbo") end

	Map:enableFBORenderer("target_fbo")

--	self.mm_fbo = core.display.newFBO(200, 200)
--	if self.mm_fbo then self.mm_fbo_shader = Shader.new("mm_fbo") if not self.mm_fbo_shader.shad then self.mm_fbo = nil self.mm_fbo_shader = nil end end
end

function _M:resizeMapViewport(w, h, x, y)
	x = x and math.floor(x) or Map.display_x
	y = y and math.floor(y) or Map.display_y
	w = math.floor(w)
	h = math.floor(h)

	-- convert from older faulty versions
	if game.level and game.level.map and (rawget(game.level.map, "display_x") or rawget(game.level.map, "display_y")) then
		game.level.map.display_x, game.level.map.display_y = nil, nil
	end
	Map.display_x = x
	Map.display_y = y
	Map.viewport.width = w
	Map.viewport.height = h
	Map.viewport.mwidth = math.floor(w / Map.tile_w)
	Map.viewport.mheight = math.floor(h / Map.tile_h)

	self:createFBOs()

	if self.level then
		self.level.map:makeCMap()
		self.level.map:redisplay()
		if self.player then
			self.player:updateMainShader()
			self.level.map:moveViewSurround(self.player.x, self.player.y, config.settings.tome.scroll_dist, config.settings.tome.scroll_dist)
		end
	end
end

function _M:setupMiniMap()
	if self.level and self.level.map and self.level.map.finished then self.uiset:setupMinimap(self.level) end
end

--- Sets up a text flyers
function _M:setFlyingText(fl)
	self.flyers = fl
	function self.flyers:add(x, y, duration, xvel, yvel, str, color, bigfont)
		local slowness = (config.settings.tome.flyers_fade_time or 10)/10
		return FlyingText.add(fl, x, y, duration*slowness, xvel/slowness, yvel/slowness, str, color, bigfont)
	end
end

function _M:save()
	self.total_playtime = (self.total_playtime or 0) + (os.time() - (self.last_update or self.real_starttime))
	self.last_update = os.time()
	return class.save(self, self:defaultSavedFields{difficulty=true, permadeath=true, to_re_add_actors=true, party=true, _chronoworlds=true, total_playtime=true, on_level_load_fcts=true, visited_zones=true, bump_attack_disabled=true, show_npc_list=true, always_target=true}, true)
end

function _M:updateCurrentChar()
	if not self.party then return end
	local player = self.party:findMember{main=true}

	local class_evo = ""
	if self.descriptor and self.descriptor.class_evolution then class_evo = " ("..self.descriptor.class_evolution..")" end
	profile:currentCharacter(self.__mod_info.full_version_string, ("%s the level %d %s %s"):format(player.name, player.level, player.descriptor.subrace, (player.descriptor.subclass or "")..class_evo), player.__te4_uuid)

	if core.discord and self.zone then
		local all_kills_kind = player.all_kills_kind or {}

		self.total_playtime = (self.total_playtime or 0) + (os.time() - (self.last_update or self.real_starttime or os.time()))
		self.last_update = os.time()

		local playtime = ""
		local days = math.floor(self.total_playtime/86400)
		local hours = math.floor(self.total_playtime/3600) % 24
		local minutes = math.floor(self.total_playtime/60) % 60
		local seconds = self.total_playtime % 60

		if days > 0 then
			playtime = ("%id %ih %im %ss"):format(days, hours, minutes, seconds)
		elseif hours > 0 then
			playtime = ("%ih %im %ss"):format(hours, minutes, seconds)
		elseif minutes > 0 then
			playtime = ("%im %ss"):format(minutes, seconds)
		else
			playtime = ("%ss"):format(seconds)
		end

		local info = {}
		info.zone = self:getZoneName()
		info.char = ("Lvl %d %s %s"):format(player.level, player.descriptor.subrace, (player.descriptor.subclass or "")..class_evo)
		info.splash = "default"
		info.splash_text = ("%d elite/%d rare/%d boss kills; playtime %s"):format(all_kills_kind.elite or 0, all_kills_kind.rare or 0, all_kills_kind.boss or 0, playtime)
		
		local sc = Birther:getBirthDescriptor("subclass", player.descriptor.subclass)
		if sc then
			info.icon = sc.name:lower():gsub("[^a-z0-9]", "_")
			info.icon_text = ("%s playing on %s %s; died %d time%s!"):format(player.name, player.descriptor.permadeath, player.descriptor.difficulty, player.died_times and #player.died_times or 0, (player.died_times and #player.died_times == 1) and "" or "s")
		end

		-- Determine which dlc it originates from
		local _, _, addon = self.zone.short_name:find("^([^+]+)%+(.*)$")
		if addon then
			local addon_data = self.__mod_info.addons[addon]
			if addon_data and addon_data.id_dlc then
				info.splash = addon
			end
		end
		-- Let the DLC override it in a more smart way
		self:triggerHook{"Discord:check", info=info}

		core.discord.updatePresence{state=info.zone, details=info.char, large_image=info.splash, large_image_text=info.splash_text, small_image=info.icon, small_image_text=info.icon_text}
	end
end

function _M:getSaveDescription()
	local player = self.party:findMember{main=true}

	return {
		name = player.name,
		description = ([[%s the level %d %s %s.
Difficulty: %s / %s
Campaign: %s
Exploring level %s of %s.]]):tformat(
		player.name, player.level, _t(player.descriptor.subrace), _t(player.descriptor.subclass),
		_t(player.descriptor.difficulty), _t(player.descriptor.permadeath),
		_t(player.descriptor.world),
		self.level and self.level.level or "--", self.zone and self.zone.name or "--"
		),
	}
end

function _M:getVaultDescription(e)
	e = e:findMember{main=true} -- Because vault "chars" are actualy parties for tome
	return {
		name = ([[%s the %s %s]]):tformat(e.name, _t(e.descriptor.subrace), _t(e.descriptor.subclass)),
		descriptors = e.descriptor,
		description = ([[%s the %s %s.
Difficulty: %s / %s
Campaign: %s]]):tformat(
		e.name, _t(e.descriptor.subrace), _t(e.descriptor.subclass),
		_t(e.descriptor.difficulty), _t(e.descriptor.permadeath),
		_t(e.descriptor.world)
		),
	}
end

function _M:getStore(def)
	print("[STORE] Grabbing", def)
	return Store.stores_def[def]:clone()
end

function _M:leaveLevel(level, lev, old_lev)
	self.to_re_add_actors = self.to_re_add_actors or {}

	if level:hasEntity(self.player) then
		level.exited = level.exited or {}
		if lev > old_lev then
			level.exited.down = {x=self.player.x, y=self.player.y, turn=self.turn}
		else
			level.exited.up = {x=self.player.x, y=self.player.y, turn=self.turn}
		end
	end

	if level.no_remove_entities then return end

	level.last_turn = self.turn

	if self.change_level_party then
		game.party:switchParty(self.change_level_party)
		for act, _ in pairs(self.party.members) do
			if self.player ~= act then -- No check, we will add all the party
				level:removeEntity(act)
				self.to_re_add_actors[act] = true
			end
		end
	elseif self.change_level_party_back then
		for act, _ in pairs(self.party.members) do
			if level:hasEntity(act) then -- Just remove it all, it's a temporary party
				level:removeEntity(act)
			end
		end
	else
		for act, _ in pairs(self.party.members) do
			if self.player ~= act and level:hasEntity(act) then
				level:removeEntity(act)
				self.to_re_add_actors[act] = true
			end
		end
		if level:hasEntity(self.player) then level:removeEntity(self.player) end
	end
end

function _M:onLevelLoad(id, fct, data)
	if self.zone and self.level and id == self.zone.short_name.."-"..self.level.level then
		print("Direct execute of on level load", id, fct, data)
		fct(self.zone, self.level, data)
		return
	end

	self.on_level_load_fcts = self.on_level_load_fcts or {}
	self.on_level_load_fcts[id] = self.on_level_load_fcts[id] or {}
	local l = self.on_level_load_fcts[id]
	l[#l+1] = {fct=fct, data=data}
	print("Registering on level load", id, fct, data)
end

function _M:onLevelLoadRun()
	self.on_level_load_fcts = self.on_level_load_fcts or {}
	print("Running on level loads", self.zone.short_name.."-"..self.level.level)
	for i, fct in ipairs(self.on_level_load_fcts[self.zone.short_name.."-"..self.level.level] or {}) do
		fct.fct(self.zone, self.level, fct.data)
	end
	self.on_level_load_fcts[self.zone.short_name.."-"..self.level.level] = nil
end

function _M:noStairsTime()
	local nb = 2
	if game.difficulty == game.DIFFICULTY_EASY then nb = 0
	elseif game.difficulty == game.DIFFICULTY_NIGHTMARE then nb = 3
	elseif game.difficulty == game.DIFFICULTY_INSANE then nb = 5
	elseif game.difficulty == game.DIFFICULTY_MADNESS then nb = 9
	end
	return nb * 10
end

function _M:changeLevelCheck(lev, zone, params)
	params = params or {}
	if not params.direct_switch and (self:getPlayer(true).last_kill_turn and self:getPlayer(true).last_kill_turn >= self.turn - self:noStairsTime()) and not config.settings.cheat then
		local left = math.ceil((10 + self:getPlayer(true).last_kill_turn - self.turn + self:noStairsTime()) / 10)
		self.logPlayer(self.player, "#LIGHT_RED#You may not change level so soon after a kill (%d game turns left to wait)!", left)
		return false
	end
	if not self.player.can_change_level then
		self.logPlayer(self.player, "#LIGHT_RED#You may not change level without your own body!")
		return false
	end
	if zone and not self.player.can_change_zone then
		self.logPlayer(self.player, "#LIGHT_RED#You may not leave the zone with this character!")
		return false
	end
	if self.player:hasEffect(self.player.EFF_PARADOX_CLONE) or self.player:hasEffect(self.player.EFF_IMMINENT_PARADOX_CLONE) then
		self.logPlayer(self.player, "#LIGHT_RED#You cannot escape your fate by leaving the level!")
		return false
	end
	return true
end

function _M:changeLevel(lev, zone, params)
	params = params or {}
	if not self:changeLevelCheck(lev, zone, params) then return end

	-- Transmo!
	local p = self:getPlayer(true)
	local oldzone, oldlevel = game.zone, game.level
	if not params.direct_switch and p:attr("has_transmo") and p:transmoGetNumberItems() > 0 and not game.player.no_inventory_access then
		local d
		local titleupdator = self.player:getEncumberTitleUpdator(p:transmoGetName())
		d = self.player:showEquipInven(titleupdator(), nil, function(o, inven, item, button, event)
			if not o then return end
			local ud = require("mod.dialogs.UseItemDialog").new(event == "button", self.player, o, item, inven, function(_, _, _, stop)
				d:generate()
				d:generateList()
				d:updateTitle(titleupdator())
				if stop then self:unregisterDialog(d) end
			end, true)
			self:registerDialog(ud)
		end)
		d.unload = function()
			local inven = p:getInven("INVEN")
			for i = #inven, 1, -1 do
				local o = inven[i]
				if o.__transmo then
					p:transmoInven(inven, i, o, p.default_transmo_source)
				end
			end
			if game.zone == oldzone and game.level == oldlevel then
				self:changeLevelReal(lev, zone, params)
			end
		end
		-- Select the chest tab
		d.c_inven.dont_update_last_tabs = true
		d.c_inven:switchTab{kind="transmo"}
		p:transmoHelpPopup()
	else
		self:changeLevelReal(lev, zone, params)
	end
end

--- Handle level generation failure with input from the player
-- @param lev = level (number) that failed to generate
-- @param zone = zone to change to, either short_name (string) or a zone object
-- @param params = table of params for changeLevel
-- @params level = new level (that failed to generate)
-- @params old_zone = previous zone
-- @params old_level = previous level
function _M:changeLevelFailure(lev, zone, params, level, old_zone, old_level)
	local failed_zone, failed_level = self.zone, level -- store failed zone/level
	local failed_room_map = table.get(level, "map", "room_map") -- store the room map

	self.zone, self.level = failed_zone:clone(), level and level:clone() -- restore to copies so originals match memory addresses
	local to_re_add_actors = self.to_re_add_actors
	print("=====Level Generation Failure: Unable to create level", lev, "of zone:", failed_zone.short_name, "===")

	local choices = {{name=("Stay: level %s of %s"):tformat(old_level.level, old_zone.name), choice="stay"},
	{name=("Keep Trying: level %s of %s"):tformat(lev, failed_zone.name), choice="try"},
	{name=("Log the problem, Stay: level %s of %s"):tformat(old_level.level, old_zone.name), choice="log"}}
	if config.settings.cheat then
		table.insert(choices, {name=_t"Debug the problem (move to the failed zone/level)", choice="debug"})
	end
	local function generation_dump()
		print("\n=====START Level Generation Failure Log=====\n")
		print("=====Zone=====:", failed_zone, "====") table.print_shallow(failed_zone)
		print("=====Generator Data:=====", failed_zone.generator, "====") table.print(failed_zone.generator)
		print("=====Failed Level====:", failed_level, "====") table.print_shallow(failed_level)
		print("\n=====END Level Generation Failure Log=====\n")
	end
	local choice_handler = function(sel)
		if not sel then 
			print("[changeLevelFailure] Stay selected by default")
		elseif sel.choice == "try" then
			print("[changeLevelFailure]", sel.name)
			game:changeLevelReal(lev, zone, params)
		elseif sel.choice == "log" then -- output zone/level/generator summary to the output log
		-- failed_zone/failed_level are the copies of the last versions that failed to generate
		-- Could add bug uploading here if desired
		-- Consider grabbing last xx lines of the game.log to find out what forcing the level to be recreated.
		-- (Search for last instance of "[Zone:newLevel]".."\t"..failed_zone.short_name.."\tbeginning level generation, count:\t1")

			print("[changeLevelFailure]", sel.name)
			generation_dump()
			Dialog:simplePopup(_t"Information logged", _t"Information on the failed zone and level dumped to the log file.")
		elseif sel.choice == "debug" then
			print("[changeLevelFailure]", sel.name)
			generation_dump()
			failed_zone._level_generation_count = nil
			self.zone, self.level = failed_zone, failed_level
			params._debug_mode = true
			self.to_re_add_actors = to_re_add_actors
			self:changeLevelReal(lev, failed_zone, params)
			table.set(self.level, "map", "room_map", failed_room_map) -- restore the room map
		else
			print("[changeLevelFailure]", sel.name)
		end
	end
	local text = ("The game could not generate level %s of %s after %s attempts. What do you want to do?"):tformat(lev, failed_zone.name, failed_zone._level_generation_count-1)
	Dialog:multiButtonPopup(_t"Level Generation Failure", text,
		choices, math.max(500, game.w/2), nil, choice_handler,
		false,
		1 -- default to stay on the previous level
	)
	self.zone, self.level = old_zone, old_level
	new_level = false
end

function _M:changeLevelReal(lev, zone, params)
	-- Unlock first!
	if not params.temporary_zone_shift_back and self.zone and self.zone.temp_shift_zone and zone and zone ~= self.zone.short_name then
		self:changeLevelReal(1, "useless", {temporary_zone_shift_back=true})
	end

	local oz, ol = self.zone, self.level

	local st = core.game.getTime()
	local sti = 1

	-- Flush particles remaining to draw
	core.particles.flushLast()

	-- Finish stuff registered for the previous level
	self:onTickEndExecute()

	if self.zone and self.level then self.party:leftLevel(params.temporary_zone_shift_back or (zone and zone == self.zone.short_name)) end

	if self.player:isTalentActive(self.player.T_JUMPGATE) then
		self.player:forceUseTalent(self.player.T_JUMPGATE, {ignore_energy=true})
	end

	if self.player:isTalentActive(self.player.T_JUMPGATE_TWO) then
		self.player:forceUseTalent(self.player.T_JUMPGATE_TWO, {ignore_energy=true})
	end

	-- clear chrono worlds and their various effects
	if self._chronoworlds and not params.keep_chronoworlds then self._chronoworlds = nil end

	local left_zone = self.zone
	local old_lev = (self.level and not zone) and self.level.level or -1000
	if params.keep_old_lev then old_lev = self.level.level end

	local force_recreate = false
	local recreate_nothing = false
	local popup = nil
	local afternicer = nil
	local force_back_pos = nil

	if params._debug_mode then
		print("Entering zone:", self.zone.name, "level:", self.level and self.level.level, "in debug mode")	
		if not self.level then self.change_level_party = nil self.change_level_party_back = nil return end
	elseif params.temporary_zone_shift then -- We only switch temporarily, keep the old one around
		if params.temporary_zone_shift_party then self.change_level_party = params.temporary_zone_shift_party end

		self:leaveLevel(self.level, lev, old_lev)

		if type(zone) == "string" then
			self.zone = Zone.new(zone)
		else
			self.zone = zone
		end
		if type(self.zone.save_per_level) == "nil" then self.zone.save_per_level = config.settings.tome.save_zone_levels and true or false end

		local level, new_level = self.zone:getLevel(self, lev, old_lev, true)
		if (not level or self.zone._level_generation_count > self.zone._max_level_generation_count) and not params._debug_mode then -- handle level generation failure
			self:changeLevelFailure(lev, zone, params, level, oz, ol)
		else
			self.visited_zones[self.zone.short_name] = true
			world:seenZone(self.zone.short_name)
			self.zone.temp_shift_zone = oz
			self.zone.temp_shift_level = ol
			if params.temporary_zone_shift_save_pos then
				local p = self:getPlayer(true)
				self.zone.temp_shift_pos = {x=p.x, y=p.y}
			end

			if new_level then
				afternicer = self.state:startEvents()
			end
		end
	elseif params.temporary_zone_shift_back then -- We switch back
		popup = Dialog:simpleWaiter(_t"Loading level", _t"Please wait while loading the level...", nil, 10000)
		core.display.forceRedraw()

		if self.zone.zone_party then self.change_level_party_back = true end

		local old = self.zone

		if self.zone and self.zone.on_leave then
			local nl, nz, stop = self.zone.on_leave(lev, old_lev, old.temp_shift_zone)
			if stop then self.change_level_party = nil self.change_level_party_back = nil return end
			if nl then lev = nl end
			if nz then zone = nz end
		end

		if self.zone and self.level then self.player:onLeaveLevel(self.zone, self.level) end
		if self.zone then
			self.zone:leaveLevel(false, lev, old_lev)
			self.zone:leave()
		end

		self.zone = old.temp_shift_zone
		self.level = old.temp_shift_level
		if old.temp_shift_pos then force_back_pos = old.temp_shift_pos end

		self.visited_zones[self.zone.short_name] = true
		world:seenZone(self.zone.short_name)
		force_recreate = true
	elseif not params.temporary_zone_shift then -- We move to a new zone as normal
		if self.zone and self.zone.on_leave then
			local nl, nz, stop = self.zone.on_leave(lev, old_lev, zone)
			if stop then self.change_level_party = nil self.change_level_party_back = nil return end
			if nl then lev = nl end
			if nz then zone = nz end
		end

		if self.zone and self.level then self.player:onLeaveLevel(self.zone, self.level) end

		if zone then
			if self.zone then
				self.zone:leaveLevel(false, lev, old_lev)
				self.zone:leave()
			end
			if type(zone) == "string" then
				self.zone = Zone.new(zone)
			else
				self.zone = zone
			end
			if self.zone.tier1 then
				if lev == 1 and game.state:tier1Killed(game.state.birth.start_tier1_skip or 3) then
					self.zone.tier1 = nil
					Dialog:yesnoPopup(_t"Easy!", _t"This zone is so easy for you that you can stroll to the last area with ease.", function(ret) if ret then
						game:changeLevel(self.zone.max_level)
					end end, _t"Stroll", _t"Stay there")
				end
			end
			if type(self.zone.save_per_level) == "nil" then self.zone.save_per_level = config.settings.tome.save_zone_levels and true or false end
		end

		local level, new_level = self.zone:getLevel(self, lev, old_lev)

		-- handle level generation failure
		if (not level or self.zone._level_generation_count > self.zone._max_level_generation_count) and not params._debug_mode then
			self:changeLevelFailure(lev, zone, params, level, oz, ol)
			self.zone, self.level = oz, ol -- by default, stay on current zone/level
			new_level = false
		else
			self.visited_zones[self.zone.short_name] = true
			world:seenZone(self.zone.short_name)

			if new_level then
				afternicer = self.state:startEvents()
			end
		end
	end

	-- Store for later
	if params.temporary_zone_shift_party then self.zone.zone_party = true end

	-- Post process walls
	self.nicer_tiles:postProcessLevelTiles(self.level)

	-- Post process if needed once the nicer tiles are done
	if self.level.data and self.level.data.post_nicer_tiles then self.level.data.post_nicer_tiles(self.level) end
	self.zone:runPostGeneration(self.level)

	-- After ? events ?
	if afternicer then afternicer() end

	-- Check if we need to switch the current guardian
	self.state:zoneCheckBackupGuardian()

	-- Check if we must do some special things on load of this level
	self:onLevelLoadRun()

	-- Decay level ?
	if self.level.last_turn and self.level.data.decay and self.level.last_turn + self.level.data.decay[1] * 10 < self.turn then
		local only = self.level.data.decay.only or nil
		if not only or only.actor then
--			local nb_actor, remain_actor = self.level:decay(Map.ACTOR, function(e) return not e.unique and not e.lore and not e.quest and self.level.last_turn + rng.range(self.level.data.decay[1], self.level.data.decay[2]) < self.turn * 10 end)
--			if not self.level.data.decay.no_respawn then
--				local gen = self.zone:getGenerator("actor", self.level)
--				if gen.regenFrom then gen:regenFrom(remain_actor) end
--			end
		end

		if not only or only.object then
			local nb_object, remain_object = self.level:decay(Map.OBJECT, function(e) return not e.unique and not e.lore and not e.quest and self.level.last_turn + rng.range(self.level.data.decay[1], self.level.data.decay[2]) < self.turn * 10 end)
--			if not self.level.data.decay.no_respawn then
--				local gen = self.zone:getGenerator("object", self.level)
--				if gen.regenFrom then gen:regenFrom(remain_object) end
--			end
		end
	end

	-- No placements to do, old party is still there, jsut switch it on
	if self.change_level_party_back then
		game.party:switchToOldParty()
	-- Move back to old wilderness position
	elseif self.zone.wilderness then
		local x, y = self.player.wild_x, self.player.wild_y
		local blocking_actor = self.level.map(x, y, engine.Map.ACTOR)
		if blocking_actor then
			-- This is mostly protecting the Angolwen Apprentice from misc stuff like leaving Timepoint Zero
			local newx, newy = util.findFreeGrid(x, y, 2, true, {[Map.ACTOR]=true})
			if newx and newy then blocking_actor:move(newx, newy, true)
			else blocking_actor:teleportRandom(x, y, 10) end
		end
		self.player:move(x, y, true)
		self.player.last_wilderness = self.zone.short_name
	-- Place the player on the level
	else
		local x, y = nil, nil
		if force_back_pos then
			x, y = force_back_pos.x, force_back_pos.y
		elseif (params.auto_zone_stair or self.level.data.auto_zone_stair) and left_zone then
			-- Dirty but quick
			local list, catchall = {}, {}
			for i = 0, self.level.map.w - 1 do for j = 0, self.level.map.h - 1 do
				local idx = i + j * self.level.map.w
				if self.level.map.map[idx][Map.TERRAIN] and self.level.map.map[idx][Map.TERRAIN].change_zone == left_zone.short_name then
					list[#list+1] = {i, j}
				elseif self.level.map.map[idx][Map.TERRAIN] and self.level.map.map[idx][Map.TERRAIN].change_zone_catchall then
					catchall[#catchall+1] = {i, j}
				end
			end end
			if #list > 0 then x, y = unpack((rng.table(list)))
			elseif #catchall  > 0 then x, y = unpack((rng.table(catchall)))
			end
		elseif params.auto_level_stair then
			-- Dirty but quick
			local list = {}
			for i = 0, self.level.map.w - 1 do for j = 0, self.level.map.h - 1 do
				local idx = i + j * self.level.map.w
				if self.level.map.map[idx][Map.TERRAIN] and not self.level.map.map[idx][Map.TERRAIN].change_zone and self.level.map.map[idx][Map.TERRAIN].change_level == old_lev - self.level.level then
					list[#list+1] = {i, j}
				end
			end end
			if #list > 0 then x, y = unpack((rng.table(list))) end
		end

		-- if self.level.exited then -- use the last location, if defined
		-- 	local turn = 0
		-- 	if self.level.exited.down then
		-- 		x, y, turn = self.level.exited.down.x, self.level.exited.down.y, self.level.exited.down.turn or 0
		-- 	end
		-- 	if self.level.exited.up and (self.level.exited.up.turn or 0) > turn then
		-- 		x, y = self.level.exited.up.x, self.level.exited.up.y
		-- 	end
		-- end

		if not x then -- Default to stairs
			if lev > old_lev and not params.force_down and self.level.default_up then x, y = self.level.default_up.x, self.level.default_up.y
			elseif self.level.default_down then x, y = self.level.default_down.x, self.level.default_down.y
			end
			if not x and self.level.default_up then x, y = self.level.default_up.x, self.level.default_up.y end
		end

		-- Check if there is already an actor at that location, if so move it
		x = x or 1 y = y or 1
		local blocking_actor = self.level.map(x, y, engine.Map.ACTOR)
		if blocking_actor then
			local newx, newy = util.findFreeGrid(x, y, 20, true, {[Map.ACTOR]=true})
			if newx and newy then blocking_actor:move(newx, newy, true)
			else blocking_actor:teleportRandom(x, y, 200) end
		end
		if self.player:canMove(x, y) then
			self.player:move(x, y, true)
		else
			self.player:move(x, y, true)
			self.player:teleportRandom(x, y, 200)
		end
	end
	self.player.changed = true
	if self.to_re_add_actors and not self.zone.wilderness and not self.zone.stellar_map then for act, _ in pairs(self.to_re_add_actors) do
		local x, y = util.findFreeGrid(self.player.x, self.player.y, 20, true, {[Map.ACTOR]=true})
		if x then act:move(x, y, true) end
	end end

	-- Re add entities
	self.level:addEntity(self.player)
	if self.to_re_add_actors and not self.zone.wilderness and not self.zone.stellar_map then
		for act, _ in pairs(self.to_re_add_actors) do
			self.level:addEntity(act)
			act:setTarget(nil)
			if act.ai_state and act.ai_state.tactic_leash_anchor then
				act.ai_state.tactic_leash_anchor = self.player
			end
		end
		self.to_re_add_actors = nil
	end

	if self.zone.on_enter then
		self.zone.on_enter(lev, old_lev, zone)
	end

	self.player:onEnterLevel(self.zone, self.level)
	self.player:resetMoveAnim()

	local musics = {}
	local keep_musics = false
	if self.level.data.ambient_music then
		if self.level.data.ambient_music ~= "last" then
			if type(self.level.data.ambient_music) == "string" then musics[#musics+1] = self.level.data.ambient_music
			elseif type(self.level.data.ambient_music) == "table" then for i, name in ipairs(self.level.data.ambient_music) do musics[#musics+1] = name end
			elseif type(self.level.data.ambient_music) == "function" then for i, name in ipairs{self.level.data.ambient_music()} do musics[#musics+1] = name end
			end
		elseif self.level.data.ambient_music == "last" then
			keep_musics = true
		end
	end
	if not keep_musics then self:playAndStopMusic(unpack(musics)) end

	-- Update the minimap
	self:setupMiniMap()

	-- Tell the map to use path strings to speed up path calculations
	for uid, e in pairs(self.level.entities) do
		if e.getPathString then
			self.level.map:addPathString(e:getPathString())
		end
	end
	self.zone_name_s = nil

	-- Special stuff
	for uid, act in pairs(self.level.entities) do if act.removeEffectsFilter then act:removeEffectsFilter(act, function(e) return e.zone_wide_effect end, nil, nil, true) end end
	for uid, act in pairs(self.level.entities) do
		if act.setEffect then
			if self.level.data.zero_gravity then act:setEffect(act.EFF_ZERO_GRAVITY, 1, {})
			else act:removeEffect(act.EFF_ZERO_GRAVITY, nil, true) end
		end
	end
	if self.level.data.effects then
		for uid, act in pairs(self.level.entities) do
			if act.setEffect then for _, effid in ipairs(self.level.data.effects) do
				act:setEffect(effid, 1, {})
			end end
		end
	end
	self.level.data.effects_allow = true

	-- Level feeling
	local feeling
	if self.level.special_feeling then
		feeling = self.level.special_feeling
	else
		local lev = self.zone.base_level + self.level.level - 1
		if self.zone.level_adjust_level then lev = self.zone:level_adjust_level(self.level) end
		local diff = lev - self.player.level
		if diff >= 5 then feeling = _t"You feel a thrill of terror and your heart begins to pound in your chest. You feel terribly threatened upon entering this area."
		elseif diff >= 2 then feeling = _t"You feel mildly anxious, and walk with caution."
		elseif diff >= -2 then feeling = nil
		elseif diff >= -5 then feeling = _t"You feel very confident walking into this place."
		else feeling = _t"You stride into this area without a second thought, while stifling a yawn. You feel your time might be better spent elsewhere."
		end
	end
	if feeling then self.log("#TEAL#%s", feeling) end

	-- Autosave
--	if config.settings.tome.autosave and not config.settings.cheat and ((left_zone and left_zone.short_name ~= "wilderness") or self.zone.save_per_level) and (left_zone and left_zone.short_name ~= self.zone.short_name) then self:saveGame() end

	self.player:onEnterLevelEnd(self.zone, self.level)

	-- Day/Night cycle
	if self.level.data.day_night then self.state:dayNightCycle() end

	if not recreate_nothing then
		--self.level.map:redisplay() -- not needed, reopen doest it
		self.level.map:reopen(true)
		if force_recreate then self.level.map:recreate() end
	end

	-- Anti stairscum
	if self.level.last_turn and self.level.last_turn < self.turn then
		local perc = util.bound(math.floor((self.turn - self.level.last_turn) / 10), 0, 10)
		for uid, target in pairs(self.level.entities) do
			if target.life and target.max_life and ((self.player:reactionToward(target) < 0) or target:attr("hostile_for_level_change")) then
				target.life = util.bound(target.life + target.max_life * perc / 10, 0, target.max_life)
				target.changed = true
				target.talents_cd = {}

				local todel = {}
				for eff_id, p in pairs(target.tmp) do
					local e = target.tempeffect_def[eff_id]
					if e.status == "detrimental" then todel[#todel+1] = eff_id end
				end
				while #todel > 0 do
					target:removeEffect(table.remove(todel))
				end
			end
		end
	end

	if popup then popup:done() end

	self.change_level_party = nil
	self.change_level_party_back = nil

	self:dieClonesDie()

	self:triggerHook{"Game:changeLevel"}
end

function _M:dieClonesDie()
	if not self.level then return end
	local p = self:getPlayer(true)
	if not p.puuid then return end
	for uid, e in pairs(self.level.entities) do
		if p.puuid == e.puuid and e ~= p then self.level:removeEntity(e) end
	end
end

function _M:getPlayer(main)
	if main then
		return self.party:findMember{main=true}
	else
		return self.player
	end
end

function _M:getCampaign()
	return self:getPlayer(true).descriptor.world
end

function _M:isCampaign(name)
	return self:getPlayer(true).descriptor.world == name
end

--- Says if this savefile is usable or not
function _M:isLoadable()
	if not self:getPlayer(true).dead or not self.player.dead then return true end
	return false
end

--- Clones the game world for chronomancy spells
function _M:chronoClone(name)
	self:getPlayer(true):attr("time_travel_times", 1)

	local d = Dialog:simpleWaiter(_t"Chronomancy", _t"Folding the space time structure...")

	local to_reload = {}
	for uid, e in pairs(self.level.entities) do
		if type(e.project) == "table" and e.project.def and e.project.def.typ and e.project.def.typ.line_function then
			e.project.def.typ.line_function.line = { game.level.map.w, game.level.map.h, e.project.def.typ.line_function:export() }
			to_reload[#to_reload + 1] = e
		end
	end

	local ret = self:cloneFull()

	for uid, e in pairs(to_reload) do e:loaded() end

	if name then
		self._chronoworlds = self._chronoworlds or {}
		self._chronoworlds[name] = ret
		ret = nil
	end
	d:done()
	return ret
end

--- Restores a chronomancy clone
function _M:chronoRestore(name, remove)
	local ngame
	if type(name) == "string" then
		ngame = self._chronoworlds[name]
		if remove then self._chronoworlds[name] = nil end
	else ngame = name end
	if not ngame then return false end

	local d = Dialog:simpleWaiter(_t"Chronomancy", _t"Unfolding the space time structure...")

	_G.game = ngame
	ngame:cloneReloaded()

	game.inited = nil
	game:runReal()
	game.key:setupRebootKeys() -- engine does it for us but not on chronoworld reload
	game.key:setCurrent()
	game.mouse:setCurrent()
	profile.chat:setupOnGame()

	core.wait.disable() -- "game" changed, we cant just unload the dialog, it doesnt exist anymore
	if game.player.resetMainShader then game.player:resetMainShader() end
	return true
end

function _M:getZoneName()
	if not self.zone then
		name = _t"the great unknown"
	elseif self.zone.display_name then
		name = self.zone.display_name()
	elseif not self.level then
		name = self.zone.name
	else
		local lev = self.level.level
		if self.level.data.reverse_level_display then lev = 1 + self.level.data.max_level - lev end
		if self.zone.max_level == 1 then
			name = self.zone.name
		else
			name = ("%s (%d)"):format(self.zone.name, lev)
		end
	end
	return name
end

--- Update the zone name, if needed
function _M:updateZoneName()
	if not self.zone_font then return end
	local name = self:getZoneName()
	if self.zone_name_s and self.old_zone_name == name then return end

	local s = core.display.drawStringBlendedNewSurface(self.zone_font, name, unpack(colors.simple(colors.GOLD)))
	self.zone_name_w, self.zone_name_h = s:getSize()
	self.zone_name_s, self.zone_name_tw, self.zone_name_th = s:glTexture()
	self.old_zone_name = name
	print("Updating zone name", name)
end

function _M:tick()
	if self.level then
		self:targetOnTick()

		engine.GameTurnBased.tick(self)
		-- Fun stuff: this can make the game realtime, although calling it in display() will make it work better
		-- (since display is on a set FPS while tick() ticks as much as possible
		-- engine.GameEnergyBased.tick(self)
	else
		engine.Game.tick(self)
	end

	-- Check damages to log
	self:displayDelayedLogMessages()
	self:displayDelayedLogDamage()

	if self.tick_loopback then
		self.tick_loopback = nil
		return self:tick()
	end

	if savefile_pipe.saving then self.player.changed = true end
	if self:onTickEndExists() then return false end -- Force a new tick
	if self.creating_player then return true end
	if self.paused and not savefile_pipe.saving then return true end
end

-- Game Log management functions:
-- logVisible: determines if a message should be visible to the player
-- logMessage: creates the message to be passed to the display
-- delayedLogMessage: queues an actor-specific message for display at the end of the current game tick
-- displayDelayedLogMessages: displays the queued delayedLogMessage messages (before combat damage messages)
-- delayedLogDamage: queues combat damage (and associated message) for display at the end of the current game tick
-- displayDelayedLogDamage: collates and displays queued delayedLogDamage information

--- Output a message to the log based on the visibility of an actor to the player
-- @param e the actor(entity) to check visibility for
-- @param style the message to display
-- @param ... arguments to be passed to format for style
function _M.logSeen(e, style, ...)
	if e and e.player or (not e.dead and e.x and e.y and game.level and game.level.map.seens(e.x, e.y) and game.player:canSee(e)) then game.log(style, ...) end
end

--- Determine whether an action between 2 actors (or entities or effects) should produce a message in the log
--		and if they should be identified to the player
-- @param source: source of the action
-- @param target: target of the action
-- @return[1] [type=boolean] message visible to player
-- @return[2] [type=boolean] source is identified by player
-- @return[3] [type=boolean] target is identified by player
function _M:logVisible(source, target)
	-- target should display if it's the player, an acting entity (actor, projectile, or trap) in a seen tile, or a non-acting entity without coordinates
	local tgt, tgtSeen
	if target then
		if target.player then tgt, tgtSeen = true, true
		else
			if target.__is_actor or target.__is_projectile or target.__is_trap then
				tgt = game.level.map.seens(target.x, target.y)
			else
				tgt = not target.x
			end
			tgtSeen = tgt and game.player:canSee(target) or false
		end
	end
	
	local src, srcSeen, src_act = false, false
	-- Special cases
	if not source.x then -- special case: unpositioned source uses target parameters (for timed effects on target)
		if tgtSeen then
			src, srcSeen = tgt, tgtSeen
		else
			src, tgt = nil, nil
		end
	else -- source should display if it's the player or an acting entity in a seen tile, or same as target for non-acting entities
		if source.player then src, srcSeen = true, true
		else
			if source.__is_actor or source.__is_projectile or source.__is_trap then
				src = game.level.map.seens(source.x, source.y)
			else
				src = tgt
			end
			srcSeen = src and game.player:canSee(source) or false
		end
	end
	return src or tgt or false, srcSeen, tgtSeen
end

--- Generate a message (string) for the log with possible source and target,
-- 		highlights the player and takes visibility into account
-- @param source: source (primary) actor
-- @param srcSeen: [type=boolean] source is identified
-- @param target: target (secondary) actor
-- @param tgtSeen: [type=boolean] target is identified
-- @param style the message to display
-- @param ... arguments to be passed to format for style
-- @return the string with certain fields replaced:
-- #source#|#Source# -> <displayString>..self.name|self:getName():capitalize()
-- #target#|#Target# -> target.name|target:getName():capitalize()
function _M:logMessage(source, srcSeen, target, tgtSeen, style, ...)
	-- I18N
	style = style:tformat(...)
	local srcname = _t"something"
	local Dstring
		if source.player then
			srcname = "#fbd578#"..source.name.."#LAST#"
		elseif srcSeen then
			srcname = engine.Entity.check(source, "getName") or source.name or _t"unknown"
		end
		if srcname ~= _t"something" then Dstring = source.__is_actor and source.getDisplayString and source:getDisplayString() end
	style = style:noun_sub("#source#", srcname)
	style = style:noun_sub("#Source#", (Dstring or "")..srcname:capitalize())
	local tgtname = _t"something"
	if target then
		if target.player then
			tgtname = "#fbd578#"..target.name.."#LAST#"
		elseif tgtSeen then
			tgtname = engine.Entity.check(target, "getName") or target.name or _t"unknown"
		end
	end
	style = style:noun_sub("#target#", tgtname)
	style = style:noun_sub("#Target#", tgtname:capitalize())
	return style
end

--- Log an entity-specific message for display later with displayDelayedLogMessages
-- useful to avoid spamming repeated messages
-- @param source: source (primary) actor
-- @param target [optional]: target (secondary) actor (used only to resolve msg)
-- @param label: a unique tag for this message
-- @param msg raw string passed to logMessage
--	takes visibility into account
-- 	only one message (processed with logMessage) will be logged for each source and label
function _M:delayedLogMessage(source, target, label, msg, ...)
	local visible, srcSeen, tgtSeen = self:logVisible(source, target)
	if visible then
		self.delayed_log_messages[source] = self.delayed_log_messages[source] or {}
		local src = self.delayed_log_messages[source]
		src[label] = self:logMessage(source, srcSeen, target, tgtSeen, msg, ...)
	end
end

--- Push all queued delayed log messages to the combat log
-- Called at the end of each game tick
function _M:displayDelayedLogMessages()
	if not self.uiset or not self.uiset.logdisplay then return end
	for src, msgs in pairs(self.delayed_log_messages) do
		for label, msg in pairs(msgs) do
			game.uiset.logdisplay(self:logMessage(src, true, nil, nil, msg))
		end
	end
	self.delayed_log_messages = {}
end

--- Collate and push all queued delayed log damage information to the combat log
-- Called at the end of each game tick
function _M:displayDelayedLogDamage()
	if not self.uiset or not self.uiset.logdisplay then return end
	for real_src, psrcs in pairs(self.delayed_log_damage) do
		for src, tgts in pairs(psrcs) do
			for target, dams in pairs(tgts) do
				if #dams.descs > 1 then
					game.uiset.logdisplay(self:logMessage(src, dams.srcSeen, target, dams.tgtSeen, "#Source# hits #Target# for %s (#RED##{bold}#%0.0f#LAST##{normal}# total damage)%s.", table.concat(dams.descs, ", "), dams.total, dams.healing<0 and (" #LIGHT_GREEN#[%0.0f healing]#LAST#"):tformat(-dams.healing) or ""))
				else
					if dams.healing >= 0 then
						game.uiset.logdisplay(self:logMessage(src, dams.srcSeen, target, dams.tgtSeen, "#Source# hits #Target# for %s damage.", table.concat(dams.descs, ", ")))
					elseif src == target then
						game.uiset.logdisplay(self:logMessage(src, dams.srcSeen, target, dams.tgtSeen, "#Source# receives %s.", table.concat(dams.descs, ", ")))
					else
						game.uiset.logdisplay(self:logMessage(src, dams.srcSeen, target, dams.tgtSeen, "#Target# receives %s from #Source#.", table.concat(dams.descs, ", ")))
					end
				end
				local rsrc = real_src.resolveSource and real_src:resolveSource() or real_src
				local rtarget = target.resolveSource and target:resolveSource() or target
				local x, y = target.x or -1, target.y or -1
				local sx, sy = self.level.map:getTileToScreen(x, y, true)
				if target.dead then
					if dams.tgtSeen and (rsrc == self.player or rtarget == self.player or self.party:hasMember(rsrc) or self.party:hasMember(rtarget)) then
						self.flyers:add(sx, sy, 30, (rng.range(0,2)-1) * 0.5, rng.float(-2.5, -1.5), ("Kill (%d)!"):tformat(dams.total), {255,0,255}, true)
						self:delayedLogMessage(target, nil,  "death", self:logMessage(src, dams.srcSeen, target, dams.tgtSeen, _t"#{bold}##Source# killed #Target#!#{normal}#"))
					end
				elseif dams.total > 0 or dams.healing == 0 then
					if dams.tgtSeen and (rsrc == self.player or self.party:hasMember(rsrc)) then
						self.flyers:add(sx, sy, 30, (rng.range(0,2)-1) * 0.5, rng.float(-3, -2), tostring(-math.ceil(dams.total)), {0,255,dams.is_crit and 200 or 0}, dams.is_crit)
					elseif dams.tgtSeen and (rtarget == self.player or self.party:hasMember(rtarget)) then
						self.flyers:add(sx, sy, 30, (rng.range(0,2)-1) * 0.5, -rng.float(-3, -2), tostring(-math.ceil(dams.total)), {255,dams.is_crit and 200 or 0,0}, dams.is_crit)
					end
				end
			end
		end
	end
	if self.delayed_death_message then game.log("%s", self.delayed_death_message) end
	self.delayed_death_message = nil
	self.delayed_log_damage = {}
end

--- Queue combat damage values and messages for later display with displayDelayedLogDamage
-- @param src: source (primary) actor dealing the damage
-- @param target: target (secondary) actor receiving the damage
-- @param dam: [type=number] damage effectively dealt, added to total
--		negative dam is counted as healing and summed separately
-- @param desc: [type=string] text description of damage dealth, passed directly to log message
-- @param crit: [type=boolean] set true if the damage was dealt via critcal hit
function _M:delayedLogDamage(src, target, dam, desc, crit)
	if not target or not src then return end
	local psrc = src.__project_source or src -- assign message to indirect damage source if available
	local visible, srcSeen, tgtSeen = self:logVisible(psrc, target)
	if visible then -- only log damage the player is aware of
		local t = table.getTable(self.delayed_log_damage, src, psrc, target)
		table.update(t, {total=0, healing=0, descs={}})
		t.descs[#t.descs+1] = desc
		if dam>=0 then
			t.total = t.total + dam
		else
			t.healing = t.healing + dam
		end
		t.is_crit = t.is_crit or crit
		t.srcSeen = srcSeen
		t.tgtSeen = tgtSeen
	end
end

--- Called every game turns
function _M:onTurn()
	if self.zone then
		if self.zone.on_turn then self.zone:on_turn() end
	end

	-- Process overlay effects
	self.level.map:processEffects(self.turn % 10 ~= 0)

	-- The following happens only every 10 game turns (once for every turn of 1 mod speed actors)
	if self.turn % 10 ~= 0 then return end

	-- Day/Night cycle
	if self.level.data.day_night then self.state:dayNightCycle() end

	if not self.day_of_year or self.day_of_year ~= self.calendar:getDayOfYear(self.turn) then
		self.log(self.calendar:getTimeDate(self.turn))
		self.day_of_year = self.calendar:getDayOfYear(self.turn)
	end

	if self.turn % 500 ~= 0 then return end
	self:dieClonesDie()
	truncate_printlog(Savefile.TRUNCATE_PRINTLOG_TO)
end

function _M:updateFOV()
	self.player:playerFOV()
end

function _M:shakeScreen(time, force)
	self.shake_time = time
	self.shake_force = force
end

function _M:displaySeensMap(map, x, y, nb_keyframe)
	map._map:drawSeensTexture(x, y)
end

function _M:displayMap(nb_keyframes, prev_fbo)
	-- Now the map, if any
	if self.level and self.level.map and self.level.map.finished then
		local map = self.level.map

		if self.shake_time then
			if self.shake_time <= 0 then
				self.shake_time = nil
				self.shake_x = 0
				self.shake_y = 0
			else
				self.shake_time = self.shake_time - nb_keyframes
				self.shake_x = self.shake_x + rng.range(-self.shake_force, self.shake_force)
				self.shake_y = self.shake_y + rng.range(-self.shake_force, self.shake_force)
			end
		end

		-- Display the map and compute FOV for the player if needed
		local changed = map.changed
		if changed then self:updateFOV() end

		-- Ugh I dont like that but .. special case for timestop, for now it'll do!
		if self.player and self.player:attr("timestopping") and self.player.x and self.posteffects and self.posteffects.timestop and self.posteffects.timestop.shad then
			self.posteffects.timestop.shad:paramNumber2("texSize", map.viewport.width, map.viewport.height)
			local sx, sy = map:getTileToScreen(self.player.x, self.player.y)
			self.posteffects.timestop.shad:paramNumber2("playerPos", sx + map.tile_w / 2, sy + map.tile_h / 2)
			self.posteffects.timestop.shad:paramNumber("tick_real", core.game.getTime())
		end

		-- Display using Framebuffer, so that we can use shaders and all
		if self.fbo then
			if self.level.data.display_prepare then self.level.data.display_prepare(self.level, 0, 0, nb_keyframes) end
			self.fbo:use(true)
				if self.level.data.background then self.level.data.background(self.level, 0, 0, nb_keyframes) end
				map:display(0, 0, nb_keyframes, config.settings.tome.smooth_fov, self.fbo)
				if self.level.data.foreground then self.level.data.foreground(self.level, 0, 0, nb_keyframes) end
				if self.level.data.weather_particle then self.state:displayWeather(self.level, self.level.data.weather_particle, nb_keyframes) end
				if self.level.data.weather_shader then self.state:displayWeatherShader(self.level, self.level.data.weather_shader, map.display_x, map.display_y, nb_keyframes) end
			self.fbo:use(false, prev_fbo)

			-- 2nd pass to apply distorting particles
			self.fbo2:use(true)
				self.fbo:toScreen(0, 0, map.viewport.width, map.viewport.height)
				core.particles.drawAlterings()
				if self.posteffects and self.posteffects.line_grids and self.posteffects.line_grids.shad then self.posteffects.line_grids.shad:use(true) end
				map._map:toScreenLineGrids(map.display_x, map.display_y)
				if self.posteffects and self.posteffects.line_grids and self.posteffects.line_grids.shad then self.posteffects.line_grids.shad:use(false) end
				if config.settings.tome.smooth_fov then self:displaySeensMap(map, 0, 0, nb_keyframes) end
			self.fbo2:use(false, prev_fbo)

			_2DNoise:bind(1, false)
			self.fbo2:postEffects(self.fbo, prev_fbo, map.display_x + self.shake_x, map.display_y + self.shake_y, map.viewport.width, map.viewport.height, unpack(self.posteffects_use))
			if self.target then self.target:display(nil, nil, prev_fbo, nb_keyframes) end

		-- Basic display; no FBOs
		else
			if self.level.data.background then self.level.data.background(self.level, map.display_x, map.display_y, nb_keyframes) end
			map:display(nil, nil, nb_keyframes, config.settings.tome.smooth_fov, nil)
			if self.target then self.target:display(nil, nil, prev_fbo, nb_keyframes) end
			if self.level.data.foreground then self.level.data.foreground(self.level, map.display_x, map.display_y, nb_keyframes) end
			if self.level.data.weather_particle then self.state:displayWeather(self.level, self.level.data.weather_particle, nb_keyframes) end
			if self.level.data.weather_shader then self.state:displayWeatherShader(self.level, self.level.data.weather_shader, map.display_x, map.display_y, nb_keyframes) end
			core.particles.drawAlterings()
			if self.posteffects and self.posteffects.line_grids and self.posteffects.line_grids.shad then self.posteffects.line_grids.shad:use(true) end
			map._map:toScreenLineGrids(map.display_x, map.display_y)
			if self.posteffects and self.posteffects.line_grids and self.posteffects.line_grids.shad then self.posteffects.line_grids.shad:use(false) end
			if config.settings.tome.smooth_fov then self:displaySeensMap(map, map.display_x, map.display_y, nb_keyframes) end
		end

		-- Handle ambient sounds
		if self.level.data.ambient_bg_sounds then self.state:playAmbientSounds(self.level, self.level.data.ambient_bg_sounds, nb_keyframes) end

		if not self.zone_name_s then self:updateZoneName() end

		-- emotes display
		map:displayEmotes(nb_keyframe or 1)

		-- Mouse gestures
		self.gestures:update()
		-- self.gestures:display(map.display_x, map.display_y + map.viewport.height - self.gestures.font_h - 5)
		self.gestures:display(map.display_x, map.display_y, nb_keyframes)

		-- Inform the player that map is in scroll mode
		if self.scroll_lock_enabled then
			local w = map.viewport.width * 0.5
			local h = w * self.caps_scroll.h / self.caps_scroll.w
			self.caps_scroll[1]:toScreenFull(
				map.display_x + (map.viewport.width - w) / 2,
				map.display_y + (map.viewport.height - h) / 2,
				w, h,
				self.caps_scroll[2] * w / self.caps_scroll.w, self.caps_scroll[3] * h / self.caps_scroll.h,
				1, 1, 1, 0.5
			)
		end
	end
end

--- Called when screen resolution changes
function _M:checkResolutionChange(w, h, ow, oh)
	self:createFBOs()

	return self.uiset:handleResolutionChange(w, h, ow, oh)
end

function _M:display(nb_keyframes)
	-- If switching resolution, blank everything but the dialog
	if self.change_res_dialog then engine.GameTurnBased.display(self, nb_keyframes) return end

	if not core.display.redrawingForSavefileScreenshot() then
		-- Don't change gamma here during redrawing for savefile screenshot.
		-- I suspect that the following code is actually unnecessary, but I'm not changing it.

		-- Reset gamma setting, something somewhere is disrupting it, this is a stop gap solution
		if self.support_shader_gamma and self.full_fbo_shader and self.full_fbo_shader.shad then self.full_fbo_shader.shad:uniGamma(config.settings.gamma_correction / 100) end
	end
 
	if self.full_fbo then self.full_fbo:use(true) end

	-- Now the ui
	self.uiset:display(nb_keyframes)

	-- "Big News"
	self.bignews:display(nb_keyframes)

	if self.player then self.player.changed = false end

	engine.GameTurnBased.display(self, nb_keyframes)

	-- Tooltip is displayed over all else, even dialogs but before FBO
	local mx, my, button = core.mouse.get()

	self.old_ctrl_state = self.ctrl_state
	self.ctrl_state = core.key.modState("ctrl")

	-- if tooltip is in way of mouse and its not locked then move it
	if not self.uiset.no_ui then
		if self.tooltip.w and mx > self.w - self.tooltip.w and my > Tooltip:tooltip_bound_y2() - self.tooltip.h and not self.tooltip.locked then
			self:targetDisplayTooltip(Map.display_x, self.h, self.old_ctrl_state~=self.ctrl_state, nb_keyframes )
		else
			self:targetDisplayTooltip(self.w, self.h, self.old_ctrl_state~=self.ctrl_state, nb_keyframes )
		end
	end

	if self.full_fbo then
		self.full_fbo:use(false)
		self.full_fbo:toScreen(0, 0, self.w, self.h, self.full_fbo_shader.shad)
	end

	if self.wasd_state and self.wasd_state.cnt > 0 then
		self.wasd_state.cd = self.wasd_state.cd - nb_keyframes
		if self.wasd_state.cd <= 0 then			
			self.wasd_state.cd = self.wasd_state.base_cd
			self:onTickEnd(function() self:executeWASD() end)
		end
	end
end

--- Called when a dialog is registered to appear on screen
function _M:onRegisterDialog(d)
	-- Clean up tooltip
	self.tooltip_x, self.tooltip_y = nil, nil
	self.tooltip2_x, self.tooltip2_y = nil, nil
	if self.player then self.player:updateMainShader() end

--	if self.player and self.player.runStop then self.player:runStop(_t"dialog poping up") end
--	if self.player and self.player.restStop then self.player:restStop(_t"dialog poping up") end
end
function _M:onUnregisterDialog(d)
	-- Clean up tooltip
	self.tooltip_x, self.tooltip_y = nil, nil
	self.tooltip2_x, self.tooltip2_y = nil, nil
	if self.player then self.player:updateMainShader() self.player.changed = true end
end

function _M:setTacticalMode(mode, silent)
	local vs = "true"
	if mode == "old" then
		self.always_target = "old"
		vs = "'old'"
		Map:setViewerFaction(self.player.faction)
		if not silent then self.log("Showing big healthbars and tactical borders.") end
	elseif mode == "health" then
		self.always_target = "health"
		vs = "'health'"
		Map:setViewerFaction(nil)
		if not silent then self.log("Showing healthbars only.") end
	elseif mode == nil then
		self.always_target = nil
		vs = "nil"
		Map:setViewerFaction(nil)
		if not silent then self.log("Showing no tactical information.") end
	elseif mode == true then
		self.always_target = true
		vs = "true"
		Map:setViewerFaction(self.player.faction)
		if not silent then self.log("Showing small healthbars and tactical borders.") end
	end

	config.settings.tome.tactical_mode = self.always_target
	config.settings.tome.tactical_mode_set = true
	game:saveSettings("tome.tactical_mode", ([[
tome.tactical_mode = %s
tome.tactical_mode_set = true
]]):format(vs))
end

function _M:setupCommands()
	-- Make targeting work
	self.normal_key = self.key
	self:targetSetupKey()

	-- Activate profiler keybinds
	self.key:setupProfiler()

	-- Activate mouse gestures
	self.gestures = Gestures.new("Gesture: ", self.key, true)
	if self.posteffects and self.posteffects.gestures and self.posteffects.gestures.shad then self.gestures.shader = self.posteffects.gestures.shad end

	-- Helper function to not allow some actions on the wilderness map
	local not_wild = function(f, bypass) return function(...) if self.zone and (not self.zone.wilderness or (bypass and bypass())) then f(...) else self.logPlayer(self.player, "You cannot do that on the world map.") end end end

	-- Debug mode
	self.key:addCommands{
		[{"_d","ctrl"}] = function() if config.settings.cheat then
			local g = self.level.map(self.player.x, self.player.y, Map.TERRAIN)
			print(g.define_as, g.image, g.z)
			for i, a in ipairs(g.add_mos or {}) do print(" => ", a.image) end
			local add = g.add_displays
			if add then for i, e in ipairs(add) do
				print(" -", e.image, e.z or "+"..i)
				for i, a in ipairs(e.add_mos or {}) do print("   => ", a.image, (a.display_x or 0).."x"..(a.display_y or 0)) end
			end end
			print("---")
			local mos = {}
			g:getMapObjects(game.level.map.tiles, mos, 1)
			table.print(mos)
			print("===============")
			local attrs = game.level.map.attrs[self.player.x + self.player.y * self.level.map.w]
			table.print(attrs)
			print("===============")
		end end,
		[{"_g","ctrl"}] = function() if config.settings.cheat then
			game.player:takeHit(100, game.player)
			game.player:useEnergy()
			-- DamageType:get(DamageType.ACID).projector(game.player, game.player.x, game.player.y, DamageType.ACID, 100)
do return end
			game.player:setEffect("EFF_STUNNED", 1, {apply_power=200})
do return end
			local f, err = loadfile("/data/general/events/rat-lich.lua")
			print(f, err)
			setfenv(f, setmetatable({level=self.level, zone=self.zone}, {__index=_G}))
			print(pcall(f))
do return end
			self:changeLevel(game.level.level + 1)
do return end
			package.loaded["mod.dialogs.shimmer.ShimmerDemo"] = nil
			self:registerDialog(require("mod.dialogs.shimmer.ShimmerDemo").new(game.player, "iron throne couture: "))
do return end
			self:changeLevel(1, "tareyal+bamboo-forest")
do return end
			if self.zone.short_name ~= "test" then
				self:changeLevel(1, "test")
			else
				self:changeLevel(game.level.level + 1)
			end
do return end
			local m = game.zone:makeEntity(game.level, "actor", {name="elven mage"}, nil, true)
			local x, y = util.findFreeGrid(game.player.x, game.player.y, 20, true, {[Map.ACTOR]=true})
			if m and x then
				game.zone:addEntity(game.level, m, "actor", x, y)
			end
		end end,
		[{"_f","ctrl"}] = function() if config.settings.cheat then
			local m = game.zone:makeEntityByName(game.level, "actor", "NPC_HUMANOID_KROG")
			local x, y = util.findFreeGrid(game.player.x, game.player.y, 20, true, {[Map.ACTOR]=true})
			if m and x then
				game.zone:addEntity(game.level, m, "actor", x, y)
			end
do return end
			Birther:showCosmeticCustomizer(self.player, "plops")
do return end
			self.player.quests["love-melinda"] = nil
			self.player:grantQuest("love-melinda")
			self.player:hasQuest("love-melinda"):melindaCompanion(self.player, "Defiler", "Corruptor")
		end end,
		[{"_UP","ctrl"}] = function()
			game.tooltip.container.scrollbar.pos = util.minBound(game.tooltip.container.scrollbar.pos - 1, 0, game.tooltip.container.scrollbar.max)
		end,
		[{"_DOWN","ctrl"}] = function()
			game.tooltip.container.scrollbar.pos = util.minBound(game.tooltip.container.scrollbar.pos + 1, 0, game.tooltip.container.scrollbar.max)
		end,
		[{"_HOME","ctrl"}] = function()
			game.tooltip.container.scrollbar.pos = 0
		end,
		[{"_END","ctrl"}] = function()
			game.tooltip.container.scrollbar.pos = game.tooltip.container.scrollbar.max
		end,
	}

	self.key.any_key = function(sym)
		-- Control resets the tooltip
		if sym == self.key._LCTRL or sym == self.key._RCTRL then
			self.player.changed = true
			self.tooltip.old_tmx = nil
		elseif sym == self.key._LSHIFT or sym == self.key._RSHIFT then
			self.player.changed = true
		end
	end
	self.key:unicodeInput(true)
	self.key:addBinds
	{
		-- Movements
		MOVE_LEFT = function() if self.scroll_lock_enabled and self.level then self.level.map:scrollDir(4) else self.player:moveDir(4) end end,
		MOVE_RIGHT = function() if self.scroll_lock_enabled and self.level then self.level.map:scrollDir(6) else self.player:moveDir(6) end end,
		MOVE_UP = function() if self.scroll_lock_enabled and self.level then self.level.map:scrollDir(8) else self.player:moveDir(8) end end,
		MOVE_DOWN = function() if self.scroll_lock_enabled and self.level then self.level.map:scrollDir(2) else self.player:moveDir(2) end end,
		MOVE_LEFT_UP = function() if self.scroll_lock_enabled and self.level then self.level.map:scrollDir(7) else self.player:moveDir(7) end end,
		MOVE_LEFT_DOWN = function() if self.scroll_lock_enabled and self.level then self.level.map:scrollDir(1) else self.player:moveDir(1) end end,
		MOVE_RIGHT_UP = function() if self.scroll_lock_enabled and self.level then self.level.map:scrollDir(9) else self.player:moveDir(9) end end,
		MOVE_RIGHT_DOWN = function() if self.scroll_lock_enabled and self.level then self.level.map:scrollDir(3) else self.player:moveDir(3) end end,
		MOVE_STAY = function() if self.scroll_lock_enabled and self.level then self.level.map:centerViewAround(self.player.x, self.player.y) else if self.player:enoughEnergy() then self.player:describeFloor(self.player.x, self.player.y) self.player:waitTurn() end end end,

		SCROLL_MAP = function() self.scroll_lock_enabled = not self.scroll_lock_enabled end,

		RUN = function()
			self.log("Run in which direction?")
			local co = coroutine.create(function()
				local x, y = self.player:getTarget{type="hit", no_restrict=true, range=1, immediate_keys=true, default_target=self.player}
				if x and y then self.player:runInit(util.getDir(x, y, self.player.x, self.player.y)) end
			end)
			local ok, err = coroutine.resume(co)
			if not ok and err then print(debug.traceback(co)) error(err) end
		end,

		RUN_AUTO = function()
			local ae = function() if self.level and self.zone then
				local seen = {}
				-- Check for visible monsters.  Only see LOS actors, so telepathy wont prevent it
				core.fov.calc_circle(self.player.x, self.player.y, self.level.map.w, self.level.map.h, self.player.sight or 10,
					function(_, x, y) return self.level.map:opaque(x, y) end,
					function(_, x, y)
						local actor = self.level.map(x, y, self.level.map.ACTOR)
						if actor and actor ~= self.player and self.player:reactionToward(actor) < 0 and
							self.player:canSee(actor) and self.level.map.seens(x, y) then seen[#seen + 1] = {x=x, y=y, actor=actor} end
					end, nil)
				if self.zone.no_autoexplore or self.level.no_autoexplore then
					self.log("You may not auto-explore this level.")
				elseif #seen > 0 then
					local dir = game.level.map:compassDirection(seen[1].x - self.player.x, seen[1].y - self.player.y)
					self.log("You may not auto-explore with enemies in sight (%s to the %s%s)!", seen[1].actor:getName(), dir, self.level.map:isOnScreen(seen[1].x, seen[1].y) and "" or " - offscreen")
					for _, node in ipairs(seen) do
						node.actor:addParticles(engine.Particles.new("notice_enemy", 1))
					end
				else
					if not self.player:autoExplore() then
						self.log("There is nowhere left to explore.")
						self:triggerHook{"Player:autoExplore:nowhere"}
					else
						while self.player:enoughEnergy() and self.player:runStep() do end
					end
				end
			end end

			if config.settings.tome.rest_before_explore then
				local ok = false
				self.player:restInit(nil, nil, nil, function() ok = self.player.resting.rested_fully end, function() if ok then self:onTickEnd(ae) self.tick_loopback = true end end)
			else
				ae()
			end
		end,

		RUN_LEFT = function() self.player:runInit(4) while self.player:enoughEnergy() and self.player:runStep() do end  end,
		RUN_RIGHT = function() self.player:runInit(6) while self.player:enoughEnergy() and self.player:runStep() do end  end,
		RUN_UP = function() self.player:runInit(8) while self.player:enoughEnergy() and self.player:runStep() do end  end,
		RUN_DOWN = function() self.player:runInit(2) while self.player:enoughEnergy() and self.player:runStep() do end  end,
		RUN_LEFT_UP = function() self.player:runInit(7) while self.player:enoughEnergy() and self.player:runStep() do end  end,
		RUN_LEFT_DOWN = function() self.player:runInit(1) while self.player:enoughEnergy() and self.player:runStep() do end  end,
		RUN_RIGHT_UP = function() self.player:runInit(9) while self.player:enoughEnergy() and self.player:runStep() do end  end,
		RUN_RIGHT_DOWN = function() self.player:runInit(3) while self.player:enoughEnergy() and self.player:runStep() do end  end,

		ATTACK_OR_MOVE_LEFT = function() self.player:attackOrMoveDir(4) end,
		ATTACK_OR_MOVE_RIGHT = function() self.player:attackOrMoveDir(6) end,
		ATTACK_OR_MOVE_UP = function() self.player:attackOrMoveDir(8) end,
		ATTACK_OR_MOVE_DOWN = function() self.player:attackOrMoveDir(2) end,
		ATTACK_OR_MOVE_LEFT_UP = function() self.player:attackOrMoveDir(7) end,
		ATTACK_OR_MOVE_LEFT_DOWN = function() self.player:attackOrMoveDir(1) end,
		ATTACK_OR_MOVE_RIGHT_UP = function() self.player:attackOrMoveDir(9) end,
		ATTACK_OR_MOVE_RIGHT_DOWN = function() self.player:attackOrMoveDir(3) end,

		-- Hotkeys
		-- bindings done after
		HOTKEY_PREV_PAGE = not_wild(function() self.player:prevHotkeyPage() self.log("Hotkey page %d is now displayed.", self.player.hotkey_page) end),
		HOTKEY_NEXT_PAGE = not_wild(function() self.player:nextHotkeyPage() self.log("Hotkey page %d is now displayed.", self.player.hotkey_page) end),

		-- Party commands
		SWITCH_PARTY_1 = not_wild(function() self.party:select(1) end),
		SWITCH_PARTY_2 = not_wild(function() self.party:select(2) end),
		SWITCH_PARTY_3 = not_wild(function() self.party:select(3) end),
		SWITCH_PARTY_4 = not_wild(function() self.party:select(4) end),
		SWITCH_PARTY_5 = not_wild(function() self.party:select(5) end),
		SWITCH_PARTY_6 = not_wild(function() self.party:select(6) end),
		SWITCH_PARTY_7 = not_wild(function() self.party:select(7) end),
		SWITCH_PARTY_8 = not_wild(function() self.party:select(8) end),
		SWITCH_PARTY = not_wild(function() self:registerDialog(require("mod.dialogs.PartySelect").new()) end),
		ORDER_PARTY_1 = not_wild(function() self.party:giveOrders(1) end),
		ORDER_PARTY_2 = not_wild(function() self.party:giveOrders(2) end),
		ORDER_PARTY_3 = not_wild(function() self.party:giveOrders(3) end),
		ORDER_PARTY_4 = not_wild(function() self.party:giveOrders(4) end),
		ORDER_PARTY_5 = not_wild(function() self.party:giveOrders(5) end),
		ORDER_PARTY_6 = not_wild(function() self.party:giveOrders(6) end),
		ORDER_PARTY_7 = not_wild(function() self.party:giveOrders(7) end),
		ORDER_PARTY_8 = not_wild(function() self.party:giveOrders(8) end),

		-- Actions
		CHANGE_LEVEL = function()
			local e = self.level.map(self.player.x, self.player.y, Map.TERRAIN)
			if self.player:enoughEnergy() and e.change_level then
				if self.player:attr("never_move") then self.log("You cannot currently leave the level.") return end

				local stop = {}
				for eff_id, p in pairs(self.player.tmp) do
					local e = self.player.tempeffect_def[eff_id]
					if e.status == "detrimental" and not e.no_stop_enter_worlmap then stop[#stop+1] = e.desc end
				end

				if e.change_zone and #stop > 0 and e.change_zone:find("^wilderness") then
					self.log("You cannot go into the wilds with the following effects: %s", table.concat(stop, ", "))
				else
					-- Do not unpause, the player is allowed first move on next level
					if e.change_level_check and e:change_level_check(self.player) then return end
					self:changeLevel(e.change_zone and e.change_level or self.level.level + e.change_level, e.change_zone, {keep_old_lev=e.keep_old_lev, force_down=e.force_down, auto_zone_stair=e.change_zone_auto_stairs, auto_level_stair=e.change_level_auto_stairs, temporary_zone_shift_back=e.change_level_shift_back})
				end
			else
				self.log("There is no way out of this level here.")
			end
		end,
		REST = function()
			self.player:restInit()
		end,
		PICKUP_FLOOR = not_wild(function()
			if self.player.no_inventory_access then return end
			self.player:playerPickup()
		end),
		DROP_FLOOR = function()
			if self.player.no_inventory_access then return end
			self.player:playerDrop()
		end,
		SHOW_INVENTORY = function()
			if self.player.no_inventory_access then return end
			local d
			local titleupdator = self.player:getEncumberTitleUpdator(_t"Inventory")
			d = self.player:showEquipInven(titleupdator(), nil, function(o, inven, item, button, event)
				if not o then return end
				local ud = require("mod.dialogs.UseItemDialog").new(event == "button", self.player, o, item, inven, function(_, _, _, stop)
					d:generate()
					d:generateList()
					d:updateTitle(titleupdator())
					if stop then self:unregisterDialog(d) end
				end)
				self:registerDialog(ud)
			end)
		end,
		SHOW_EQUIPMENT = "SHOW_INVENTORY",
		WEAR_ITEM = function()
			if self.player.no_inventory_access then return end
			self.player:playerWear()
		end,
		TAKEOFF_ITEM = function()
			if self.player.no_inventory_access then return end
			self.player:playerTakeoff()
		end,
		USE_ITEM = not_wild(function()
			if self.player.no_inventory_access then return end
			self.player:playerUseItem()
		end),

		QUICK_SWITCH_WEAPON = function()
			if self.player.no_inventory_access then return end
			self.player:quickSwitchWeapons()
		end,

		USE_TALENTS = not_wild(function()
			self:registerDialog(require("mod.dialogs.UseTalents").new(self.player))
		end),

		LEVELUP = function()
			if self.player:attr("no_levelup_access") then
				if type(self.player.no_levelup_access_log) == "string" then
					game.log(self.player.no_levelup_access_log)
				end
				return
			end
			self.player:playerLevelup(nil, false)
		end,

		TOGGLE_AUTOTALENT = function()
			self.player.no_automatic_talents = not self.player.no_automatic_talents
			game.log("#GOLD#Automatic talent usage: %s", not self.player.no_automatic_talents and _t"#LIGHT_GREEN#enabled" or _t"#LIGHT_RED#disabled")
		end,

		TOGGLE_AUTOACCEPT_TARGET = function()
			config.settings.auto_accept_target = not config.settings.auto_accept_target
			game:saveSettings("auto_accept_target", ("auto_accept_target = %s\n"):format(tostring(config.settings.auto_accept_target)))
			game.log("#GOLD#Automatic accept target mode: %s", config.settings.auto_accept_target and _t"#LIGHT_GREEN#enabled" or _t"#LIGHT_RED#disabled")			
		end,

		SAVE_GAME = function()
			self:saveGame()
		end,

		SHOW_QUESTS = function()
			self:registerDialog(require("engine.dialogs.ShowQuests").new(self.party:findMember{main=true}))
		end,

		SHOW_CHARACTER_SHEET = function()
			self:registerDialog(require("mod.dialogs.CharacterSheet").new(self.player))
		end,

		SHOW_CHARACTER_SHEET_CURSOR = function()
			local mx, my = self.mouse.last_pos.x, self.mouse.last_pos.y
			local tmx, tmy = self.level.map:getMouseTile(mx, my)
			local a = self.level.map(tmx, tmy, Map.ACTOR)
			a = (config.settings.cheat or self.player:canSee(a)) and a or self.player
			if a.showCharacterSheet then a = a:showCharacterSheet() end
			self:registerDialog(require("mod.dialogs.CharacterSheet").new(a))
		end,

		CENTER_ON_PLAYER = function()
			self.level.map:centerViewAround(self.player.x, self.player.y)
		end,

		SHOW_MESSAGE_LOG = function()
			self:registerDialog(require("mod.dialogs.ShowChatLog").new(_t"Message Log", 0.6, self.uiset.logdisplay, profile.chat))
		end,

		-- Show time
		SHOW_TIME = function()
			self.log(self.calendar:getTimeDate(self.turn))
		end,
		-- Exit the game
		QUIT_GAME = function()
			self:onQuit()
		end,
		-- Lua console
		LUA_CONSOLE = function()
			if config.settings.cheat then
				self:registerDialog(DebugConsole.new())
			end
		end,
		-- Debug dialog
		DEBUG_MODE = function()
			if config.settings.cheat then
				self:registerDialog(require("mod.dialogs.debug.DebugMain").new())
			end
		end,

		-- Toggle monster list
		TOGGLE_NPC_LIST = function()
			self.show_npc_list = not self.show_npc_list
			self.player.changed = true

			if (self.show_npc_list) then
				self.log("Displaying creatures.")
			else
				self.log("Displaying talents.")
			end
			if self.uiset.resizeIconsHotkeysToolbar then self.uiset:resizeIconsHotkeysToolbar() end
		end,

		SCREENSHOT = function() self:saveScreenshot() end,

		HELP = "EXIT",
		EXIT = function()
			if self.tooltip.locked then
				self.tooltip.locked = false
				self.tooltip.container.focused = self.tooltip.locked
				game.log("Tooltip %s", self.tooltip.locked and "locked" or "unlocked")
			end
			local menu
			local l = {
				"resume",
				{ _t"Show Achievements", function() self:unregisterDialog(menu) self:registerDialog(require("mod.dialogs.ShowAchievements").new(_t"Tales of Maj'Eyal Achievements", self.player)) end },
				{ _t"Show known Lore", function() self:unregisterDialog(menu) self:registerDialog(require("mod.dialogs.ShowLore").new(_t"Tales of Maj'Eyal Lore", self.party)) end },
				{ _t"Show ingredients", function() self:unregisterDialog(menu) self:registerDialog(require("mod.dialogs.ShowIngredients").new(self.party)) end },
				"highscores",
				{ _t"Inventory", function() self:unregisterDialog(menu) self.key:triggerVirtual("SHOW_INVENTORY") end },
				{ _t"Character Sheet", function() self:unregisterDialog(menu) self.key:triggerVirtual("SHOW_CHARACTER_SHEET") end },
				"keybinds",
				"language",
				{_t"Game Options", function() self:unregisterDialog(menu) self:registerDialog(require("mod.dialogs.GameOptions").new()) end},
				"video",
				"sound",
				"save",
				"quit",
				"exit",
			}
			local adds = self.uiset:getMainMenuItems()
			for i = #adds, 1, -1 do table.insert(l, 10, adds[i]) end
			self:triggerHook{"Game:alterGameMenu", menu=l, unregister=function() self:unregisterDialog(menu) end}
			menu = require("engine.dialogs.GameMenu").new(l)
			self:registerDialog(menu)
		end,

		TACTICAL_DISPLAY = function()
			if self.always_target == true then
				self:setTacticalMode("old")
			elseif self.always_target == "old" then
				self:setTacticalMode("health")
			elseif self.always_target == "health" then
				self:setTacticalMode(nil)
			elseif self.always_target == nil then
				self:setTacticalMode(true)
			end
		end,

		LOOK_AROUND = function()
			self.log("Looking around... (direction keys to select interesting things, shift+direction keys to move freely)")
			local co = coroutine.create(function()
				local x, y = self.player:getTarget{type="hit", no_restrict=true, range=2000}
				if x and y then
					local tmx, tmy = self.level.map:getTileToScreen(x, y)
					self:registerDialog(MapMenu.new(tmx, tmy, x, y))
				end
			end)
			local ok, err = coroutine.resume(co)
			if not ok and err then print(debug.traceback(co)) error(err) end
		end,

		LOCK_TOOLTIP = function()
			if not self.tooltip.empty then
				self.tooltip.locked = not self.tooltip.locked
				self.tooltip.container.focused = self.tooltip.locked
				game.log("Tooltip %s", self.tooltip.locked and "locked" or "unlocked")
			end
		end,

		LOCK_TOOLTIP_COMPARE = function()
			if not self.tooltip.empty then
				self.tooltip.locked = not self.tooltip.locked
				self.tooltip.container.focused = self.tooltip.locked
				game.log("Tooltip %s", self.tooltip.locked and "locked" or "unlocked")
			end
		end,

		SHOW_MAP = function()
			if config.settings.tome.uiset_mode == "Minimalist" then
				self.uiset.mm_mode = util.boundWrap((self.uiset.mm_mode or 2) + 1, 1, 3)
				if self.uiset.mm_mode == 1 then
					self.uiset.no_minimap = true
				elseif self.uiset.mm_mode == 2 then
					self.uiset.no_minimap = false
				elseif self.uiset.mm_mode == 3 then
					game:registerDialog(require("mod.dialogs.ShowMap").new(function() self.uiset.mm_mode = 1 self.uiset.no_minimap = true end))
				end
			else
				game:registerDialog(require("mod.dialogs.ShowMap").new())
			end
		end,

		USERCHAT_SHOW_TALK = function()
			self.show_userchat = not self.show_userchat
		end,

		TOGGLE_UI = function()
			self.uiset:toggleUI()
		end,

		TOGGLE_BUMP_ATTACK = function()
			local game_or_player = not config.settings.tome.actor_based_movement_mode and self or game.player

			if game_or_player.bump_attack_disabled then
				self.log("Movement Mode: #LIGHT_GREEN#Default#LAST#.")
				game_or_player.bump_attack_disabled = false
			else
				self.log("Movement Mode: #LIGHT_RED#Passive#LAST#.")
				game_or_player.bump_attack_disabled = true
			end
		end,

		MTXN_PURCHASE = function()
			if not profile:canMTXN() then return end
			package.loaded["engine.dialogs.microtxn.ShowPurchasable"] = nil
			self:registerDialog(require("engine.dialogs.microtxn.ShowPurchasable").new())
		end,

		MTXN_USE = function()
			if not profile:canMTXN() then return end
			package.loaded["engine.dialogs.microtxn.UsePurchased"] = nil
			self:registerDialog(require("engine.dialogs.microtxn.UsePurchased").new())
		end,
	}
	-- add key bindings for targeting mode
	self.targetmode_key:addBinds{
		SHOW_CHARACTER_SHEET_CURSOR = function()
			local target = table.get(self, "target", "target", "entity") -- gets the actor under the targeting reticle
			target = target and (config.settings.cheat or self.player:canSee(target)) and target or self.player
			self:registerDialog(require("mod.dialogs.CharacterSheet").new(target))
		end,
		SHOW_CHARACTER_SHEET = function()
			self:registerDialog(require("mod.dialogs.CharacterSheet").new(self.player))
		end,
		LUA_CONSOLE = self.key.virtuals.LUA_CONSOLE,
	}
	engine.interface.PlayerHotkeys:bindAllHotkeys(self.key, not_wild(function(i)
		self:targetTriggerHotkey(i)
		self.player:activateHotkey(i)
	end, function() return self.player.allow_talents_worldmap end))

	self:setupWASD()
	self.key:setCurrent()
end

function _M:executeWASD()
	local ws = self.wasd_state
	if     ws.left  and ws.up   then self.key:triggerVirtual("MOVE_LEFT_UP")
	elseif ws.right and ws.up   then self.key:triggerVirtual("MOVE_RIGHT_UP")
	elseif ws.left  and ws.down then self.key:triggerVirtual("MOVE_LEFT_DOWN")
	elseif ws.right and ws.down then self.key:triggerVirtual("MOVE_RIGHT_DOWN")
	elseif ws.right             then self.key:triggerVirtual("MOVE_RIGHT")
	elseif ws.left              then self.key:triggerVirtual("MOVE_LEFT")
	elseif ws.up                then self.key:triggerVirtual("MOVE_UP")
	elseif ws.down              then self.key:triggerVirtual("MOVE_DOWN")
	end
	ws.has_executed_once = true
end

function _M:setupWASD()
	self.wasd_state = {cnt=0, cd=12, base_cd=3}
	local function update_wasd()
		local ws = self.wasd_state
		local old_cnt = ws.cnt
		ws.cnt = 0
		if ws.left then ws.cnt = ws.cnt + 1 end
		if ws.right then ws.cnt = ws.cnt + 1 end
		if ws.up then ws.cnt = ws.cnt + 1 end
		if ws.down then ws.cnt = ws.cnt + 1 end
		if ws.cnt == 0 then ws.has_executed_once = false ws.cd = ws.cd + 3 * ws.base_cd end
	end

	if config.settings.tome.use_wasd then
		self.key:addBinds{
			MOVE_WASD_UP    = function(sym, ctrl, shift, alt, meta, unicode, isup, key) if isup and not self.wasd_state.has_executed_once then self:executeWASD() end self.wasd_state.up = not isup and true or false update_wasd() end,
			MOVE_WASD_DOWN  = function(sym, ctrl, shift, alt, meta, unicode, isup, key) if isup and not self.wasd_state.has_executed_once then self:executeWASD() end self.wasd_state.down = not isup and true or false update_wasd() end,
			MOVE_WASD_LEFT  = function(sym, ctrl, shift, alt, meta, unicode, isup, key) if isup and not self.wasd_state.has_executed_once then self:executeWASD() end self.wasd_state.left = not isup and true or false update_wasd() end,
			MOVE_WASD_RIGHT = function(sym, ctrl, shift, alt, meta, unicode, isup, key) if isup and not self.wasd_state.has_executed_once then self:executeWASD() end self.wasd_state.right = not isup and true or false update_wasd() end,
		}
	else
		self.key:removeBind("MOVE_WASD_UP")
		self.key:removeBind("MOVE_WASD_DOWN")
		self.key:removeBind("MOVE_WASD_LEFT")
		self.key:removeBind("MOVE_WASD_RIGHT")
	end
end

function _M:setupMouse(reset)
	if reset == nil or reset then self.mouse:reset() end

	local cur_obj = nil
	local outline = Shader.new("objectsoutline").shad

	self.mouse:registerZone(Map.display_x, Map.display_y, Map.viewport.width, Map.viewport.height, function(button, mx, my, xrel, yrel, bx, by, event, extra)
		if not self.uiset:isLocked() or not game.level then return end

		local tmx, tmy = game.level.map:getMouseTile(mx, my)
		if core.shader.allow("adv") and outline then
			local o = self.level.map(tmx, tmy, Map.OBJECT)
			if cur_obj and cur_obj._mo then cur_obj._mo:shader(nil) end
			if o and o._mo and not o.shader then
				outline:uniTextSize(Map.tile_w, Map.tile_h)
				o._mo:shader(outline)
				cur_obj = o
			end
		end

		self.tooltip.add_map_str = extra and extra.log_str


		if game.tooltip.locked then
			if button == "wheelup" and event == "button" then
				game.tooltip.container.scrollbar.pos = util.minBound(game.tooltip.container.scrollbar.pos - 1, 0, game.tooltip.container.scrollbar.max)
			elseif button == "wheeldown" and event == "button" then
				game.tooltip.container.scrollbar.pos = util.minBound(game.tooltip.container.scrollbar.pos + 1, 0, game.tooltip.container.scrollbar.max)
			end
			if button == "middle" then
				if not game.tooltip.container.draging then
					game.tooltip.container.draging = true
					game.tooltip.container.drag_x_start = mx
					game.tooltip.container.drag_y_start = my
				else
					game.tooltip.container.scrollbar.pos = util.minBound(game.tooltip.container.scrollbar.pos + my - game.tooltip.container.drag_y_start, 0, game.tooltip.container.scrollbar.max)
					game.tooltip.container.drag_x_start = mx
					game.tooltip.container.drag_y_start = my
				end
			else
				game.tooltip.container.draging = false
			end
		end

		-- Handle targeting
		if not config.settings.tome.disable_mouse_targeting and self:targetMouse(button, mx, my, xrel, yrel, event) then return end

		-- Cheat kill
		if config.settings.cheat then
			if button == "right" and core.key.modState("ctrl") and core.key.modState("shift") and core.key.modState("alt") and not xrel and not yrel and event == "button" and self.zone and not self.zone.wilderness then
				local target = game.level.map(tmx, tmy, Map.ACTOR)
				if target then game._cheat_move_actor = target game.log("#GOLD#CHEAT MOVE ACTOR %s: ctrl+shift+alt+right click on an empty map spot to move it", target:getName())
				elseif game._cheat_move_actor then game._cheat_move_actor:move(tmx, tmy, true) end
				return
			elseif button == "right" and core.key.modState("ctrl") and core.key.modState("shift") and not xrel and not yrel and event == "button" and self.zone and not self.zone.wilderness then
				local target = game.level.map(tmx, tmy, Map.ACTOR)
				if target then target:die(game.player) end
				return
			end
		end

		-- Handle Use menu
		if button == "right" then
			if event == "motion" then
				self.gestures:changeMouseButton(true)
				self.gestures:mouseMove(mx, my)
			elseif event == "button" then
				if not self.gestures:isGesturing() then
					if not xrel and not yrel then
						-- Handle Use menu
						self:mouseRightClick(mx, my, extra)
						return
					end
				else
					self.gestures:changeMouseButton(false)
					self.gestures:useGesture()
					self.gestures:reset()
				end
			end
		end

		-- Default left button action
		if button == "left" and not xrel and not yrel and event == "button" and self.zone and not self.zone.wilderness then if self:mouseLeftClick(mx, my) then return end end

		-- Default middle button action
		if button == "middle" and not xrel and not yrel and event == "button" and self.zone and not self.zone.wilderness then if self:mouseMiddleClick(mx, my) then return end end

		-- Handle the mouse movement/scrolling
		self.player:mouseHandleDefault(self.key, self.key == self.normal_key, button, mx, my, xrel, yrel, event)
	end, nil, "playmap")

	self.uiset:setupMouse(self.mouse)

	if not reset then self.mouse:setCurrent() end
end

--- Left mouse click on the map
function _M:mouseLeftClick(mx, my)
	if not self.level then return end
	local tmx, tmy =