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
|
/*
* VCAI.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "VCAI.h"
#include "FuzzyHelper.h"
#include "ResourceManager.h"
#include "BuildingManager.h"
#include "Goals/Goals.h"
#include "../../lib/ArtifactUtils.h"
#include "../../lib/UnlockGuard.h"
#include "../../lib/StartInfo.h"
#include "../../lib/mapObjects/MapObjects.h"
#include "../../lib/mapObjects/ObjectTemplate.h"
#include "../../lib/CConfigHandler.h"
#include "../../lib/IGameSettings.h"
#include "../../lib/gameState/CGameState.h"
#include "../../lib/gameState/UpgradeInfo.h"
#include "../../lib/bonuses/Limiters.h"
#include "../../lib/bonuses/Updaters.h"
#include "../../lib/bonuses/Propagators.h"
#include "../../lib/entities/building/CBuilding.h"
#include "../../lib/networkPacks/PacksForClient.h"
#include "../../lib/networkPacks/PacksForClientBattle.h"
#include "../../lib/networkPacks/PacksForServer.h"
#include "../../lib/serializer/CTypeList.h"
#include "../../lib/pathfinder/PathfinderCache.h"
#include "../../lib/pathfinder/PathfinderOptions.h"
#include "AIhelper.h"
extern FuzzyHelper * fh;
const double SAFE_ATTACK_CONSTANT = 1.5;
//one thread may be turn of AI and another will be handling a side effect for AI2
thread_local CCallback * cb = nullptr;
thread_local VCAI * ai = nullptr;
//std::map<int, std::map<int, int> > HeroView::infosCount;
//helper RAII to manage global ai/cb ptrs
struct SetGlobalState
{
SetGlobalState(VCAI * AI)
{
assert(!ai);
assert(!cb);
ai = AI;
cb = AI->myCb.get();
}
~SetGlobalState()
{
//TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
//TODO: to ensure that, make rm unique_ptr
ai = nullptr;
cb = nullptr;
}
};
#define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai)
#define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
#define MAKING_TURN SET_GLOBAL_STATE(this)
VCAI::VCAI()
{
LOG_TRACE(logAi);
makingTurn = nullptr;
destinationTeleport = ObjectInstanceID();
destinationTeleportPos = int3(-1);
ah = new AIhelper();
ah->setAI(this);
}
VCAI::~VCAI()
{
delete ah;
LOG_TRACE(logAi);
finish();
}
void VCAI::availableCreaturesChanged(const CGDwelling * town)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::heroMoved(const TryMoveHero & details, bool verbose)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
//enemy hero may have left visible area
validateObject(details.id);
auto hero = cb->getHero(details.id);
const int3 from = hero ? hero->convertToVisitablePos(details.start) : (details.start - int3(0,1,0));
const int3 to = hero ? hero->convertToVisitablePos(details.end) : (details.end - int3(0,1,0));
const CGObjectInstance * o1 = vstd::frontOrNull(cb->getVisitableObjs(from, verbose));
const CGObjectInstance * o2 = vstd::frontOrNull(cb->getVisitableObjs(to, verbose));
if(details.result == TryMoveHero::TELEPORTATION)
{
auto t1 = dynamic_cast<const CGTeleport *>(o1);
auto t2 = dynamic_cast<const CGTeleport *>(o2);
if(t1 && t2)
{
if(cb->isTeleportChannelBidirectional(t1->channel))
{
if(o1->ID == Obj::SUBTERRANEAN_GATE && o1->ID == o2->ID) // We need to only add subterranean gates in knownSubterraneanGates. Used for features not yet ported to use teleport channels
{
knownSubterraneanGates[o1] = o2;
knownSubterraneanGates[o2] = o1;
logAi->debug("Found a pair of subterranean gates between %s and %s!", from.toString(), to.toString());
}
}
}
//FIXME: teleports are not correctly visited
unreserveObject(hero, t1);
unreserveObject(hero, t2);
}
else if(details.result == TryMoveHero::EMBARK && hero)
{
//make sure AI not attempt to visit used boat
validateObject(hero->boat);
}
else if(details.result == TryMoveHero::DISEMBARK && o1)
{
auto boat = dynamic_cast<const CGBoat *>(o1);
if(boat)
addVisitableObj(boat);
}
}
void VCAI::heroInGarrisonChange(const CGTownInstance * town)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::centerView(int3 pos, int focusTime)
{
LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
NET_EVENT_HANDLER;
}
void VCAI::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::artifactAssembled(const ArtifactLocation & al)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
status.addQuery(queryID, "TavernWindow");
requestActionASAP([=](){ answerQuery(queryID, 0); });
}
void VCAI::showThievesGuildWindow(const CGObjectInstance * obj)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::playerBlocked(int reason, bool start)
{
LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
NET_EVENT_HANDLER;
if(start && reason == PlayerBlocked::UPCOMING_BATTLE)
status.setBattle(UPCOMING_BATTLE);
if(reason == PlayerBlocked::ONGOING_MOVEMENT)
status.setMove(start);
}
void VCAI::showPuzzleMap()
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::showShipyardDialog(const IShipyard * obj)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
{
LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf.toString());
NET_EVENT_HANDLER;
logAi->debug("Player %d (%s): I heard that player %d (%s) %s.", playerID, playerID.toString(), player, player.toString(), (victoryLossCheckResult.victory() ? "won" : "lost"));
if(player == playerID)
{
if(victoryLossCheckResult.victory())
{
logAi->debug("VCAI: I won! Incredible!");
logAi->debug("Turn nr %d", myCb->getDate());
}
else
{
logAi->debug("VCAI: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.toString());
}
finish();
}
}
void VCAI::artifactPut(const ArtifactLocation & al)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::artifactRemoved(const ArtifactLocation & al)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::artifactDisassembled(const ArtifactLocation & al)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
{
LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->getObjectName() : std::string("n/a")));
NET_EVENT_HANDLER;
if(start && visitedObj) //we can end visit with null object, anyway
{
markObjectVisited(visitedObj);
unreserveObject(visitor, visitedObj);
completeGoal(sptr(Goals::VisitObj(visitedObj->id.getNum()).sethero(visitor))); //we don't need to visit it anymore
//TODO: what if we visited one-time visitable object that was reserved by another hero (shouldn't, but..)
if (visitedObj->ID == Obj::HERO)
{
visitedHeroes[visitor].insert(HeroPtr(dynamic_cast<const CGHeroInstance *>(visitedObj)));
}
}
status.heroVisit(visitedObj, start);
}
void VCAI::availableArtifactsChanged(const CGBlackMarket * bm)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
//buildArmyIn(town);
//moveCreaturesToHero(town);
}
void VCAI::tileHidden(const std::unordered_set<int3> & pos)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
validateVisitableObjs();
clearPathsInfo();
}
void VCAI::tileRevealed(const std::unordered_set<int3> & pos)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
for(int3 tile : pos)
{
for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
addVisitableObj(obj);
}
clearPathsInfo();
}
void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
auto firstHero = cb->getHero(hero1);
auto secondHero = cb->getHero(hero2);
status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->getNameTranslated() % firstHero->tempOwner % secondHero->getNameTranslated() % secondHero->tempOwner));
requestActionASAP([=]()
{
float goalpriority1 = 0;
float goalpriority2 = 0;
auto firstGoal = getGoal(firstHero);
if(firstGoal->goalType == Goals::GATHER_ARMY)
goalpriority1 = firstGoal->priority;
auto secondGoal = getGoal(secondHero);
if(secondGoal->goalType == Goals::GATHER_ARMY)
goalpriority2 = secondGoal->priority;
auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
{
this->pickBestCreatures(h1, h2);
this->pickBestArtifacts(h1, h2);
};
//Do not attempt army or artifacts exchange if we visited ally player
//Visits can still be useful if hero have skills like Scholar
if(firstHero->tempOwner != secondHero->tempOwner)
{
logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
}
else if(goalpriority1 > goalpriority2)
{
transferFrom2to1(firstHero, secondHero);
}
else if(goalpriority1 < goalpriority2)
{
transferFrom2to1(secondHero, firstHero);
}
else //regular criteria
{
if(firstHero->getFightingStrength() > secondHero->getFightingStrength() && ah->canGetArmy(firstHero, secondHero))
transferFrom2to1(firstHero, secondHero);
else if(ah->canGetArmy(secondHero, firstHero))
transferFrom2to1(secondHero, firstHero);
}
completeGoal(sptr(Goals::VisitHero(firstHero->id.getNum()))); //TODO: what if we were visited by other hero in the meantime?
completeGoal(sptr(Goals::VisitHero(secondHero->id.getNum())));
answerQuery(query, 0);
});
}
void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, PrimarySkill which, si64 val)
{
LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", static_cast<int>(which) % val);
NET_EVENT_HANDLER;
}
void VCAI::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level, QueryID queryID)
{
LOG_TRACE_PARAMS(logAi, "level '%i'", level);
NET_EVENT_HANDLER;
status.addQuery(queryID, "RecruitmentDialog");
requestActionASAP([=](){
recruitCreatures(dwelling, dst);
checkHeroArmy(dynamic_cast<const CGHeroInstance*>(dst));
answerQuery(queryID, 0);
});
}
void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::newObject(const CGObjectInstance * obj)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
if(obj->isVisitable())
addVisitableObj(obj);
}
//to prevent AI from accessing objects that got deleted while they became invisible (Cover of Darkness, enemy hero moved etc.) below code allows AI to know deletion of objects out of sight
//see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
void VCAI::objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
vstd::erase_if_present(visitableObjs, obj);
vstd::erase_if_present(alreadyVisited, obj);
for(auto h : cb->getHeroesInfo())
unreserveObject(h, obj);
std::function<bool(const Goals::TSubgoal &)> checkRemovalValidity = [&](const Goals::TSubgoal & x) -> bool
{
if((x->goalType == Goals::VISIT_OBJ) && (x->objid == obj->id.getNum()))
return true;
else if(x->parent && checkRemovalValidity(x->parent)) //repeat this lambda check recursively on parent goal
return true;
else
return false;
};
//clear VCAI / main loop caches
vstd::erase_if(lockedHeroes, [&](const std::pair<HeroPtr, Goals::TSubgoal> & x) -> bool
{
return checkRemovalValidity(x.second);
});
vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
{
return checkRemovalValidity(x.first);
});
vstd::erase_if(basicGoals, checkRemovalValidity);
vstd::erase_if(goalsToAdd, checkRemovalValidity);
vstd::erase_if(goalsToRemove, checkRemovalValidity);
for(auto goal : ultimateGoalsFromBasic)
vstd::erase_if(goal.second, checkRemovalValidity);
//clear resource manager goal cache
ah->removeOutdatedObjectives(checkRemovalValidity);
//TODO: Find better way to handle hero boat removal
if(auto hero = dynamic_cast<const CGHeroInstance *>(obj))
{
if(hero->boat)
{
vstd::erase_if_present(visitableObjs, hero->boat);
vstd::erase_if_present(alreadyVisited, hero->boat);
for(auto h : cb->getHeroesInfo())
unreserveObject(h, hero->boat);
}
}
//TODO
//there are other places where CGObjectinstance ptrs are stored...
//
if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
{
lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
}
}
void VCAI::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
requestActionASAP([=]()
{
makePossibleUpgrades(visitor);
});
}
void VCAI::playerBonusChanged(const Bonus & bonus, bool gain)
{
LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
NET_EVENT_HANDLER;
}
void VCAI::heroCreated(const CGHeroInstance * h)
{
LOG_TRACE(logAi);
if(h->visitedTown)
townVisitsThisWeek[HeroPtr(h)].insert(h->visitedTown);
NET_EVENT_HANDLER;
}
void VCAI::advmapSpellCast(const CGHeroInstance * caster, SpellID spellID)
{
LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
NET_EVENT_HANDLER;
}
void VCAI::showInfoDialog(EInfoWindowMode type, const std::string & text, const std::vector<Component> & components, int soundID)
{
LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
NET_EVENT_HANDLER;
}
void VCAI::requestRealized(PackageApplied * pa)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
if(status.haveTurn())
{
if(pa->packType == CTypeList::getInstance().getTypeID<EndTurn>(nullptr))
{
if(pa->result)
status.madeTurn();
}
}
if(pa->packType == CTypeList::getInstance().getTypeID<QueryReply>(nullptr))
{
status.receivedAnswerConfirmation(pa->requestID, pa->result);
}
}
void VCAI::receivedResource()
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
status.addQuery(queryID, "UniversityWindow");
requestActionASAP([=](){ answerQuery(queryID, 0); });
}
void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
{
LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
NET_EVENT_HANDLER;
}
void VCAI::battleResultsApplied()
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
assert(status.getBattle() == ENDING_BATTLE);
status.setBattle(NO_BATTLE);
}
void VCAI::beforeObjectPropertyChanged(const SetObjectProperty * sop)
{
}
void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
if(sop->what == ObjProperty::OWNER)
{
if(myCb->getPlayerRelations(playerID, sop->identifier.as<PlayerColor>()) == PlayerRelations::ENEMIES)
{
//we want to visit objects owned by oppponents
auto obj = myCb->getObj(sop->id, false);
if(obj)
{
addVisitableObj(obj); // TODO: Remove once save compatibility broken. In past owned objects were removed from this set
vstd::erase_if_present(alreadyVisited, obj);
}
}
}
}
void VCAI::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
{
LOG_TRACE_PARAMS(logAi, "what '%i'", what);
NET_EVENT_HANDLER;
if(town->getOwner() == playerID && what == 1) //built
completeGoal(sptr(Goals::BuildThis(buildingID, town)));
}
void VCAI::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
{
LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
NET_EVENT_HANDLER;
}
void VCAI::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
{
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
status.addQuery(queryID, "MarketWindow");
requestActionASAP([=](){ answerQuery(queryID, 0); });
}
void VCAI::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain)
{
//TODO: AI support for ViewXXX spell
LOG_TRACE(logAi);
NET_EVENT_HANDLER;
}
void VCAI::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
{
LOG_TRACE(logAi);
env = ENV;
myCb = CB;
cbc = CB;
ah->init(CB.get());
NET_EVENT_HANDLER; //sets ah->rm->cb
playerID = *myCb->getPlayerID();
myCb->waitTillRealize = true;
myCb->unlockGsWhenWaiting = true;
pathfinderCache = std::make_unique<PathfinderCache>(myCb.get(), PathfinderOptions(myCb.get()));
if(!fh)
fh = new FuzzyHelper();
retrieveVisitableObjs();
}
std::shared_ptr<const CPathsInfo> VCAI::getPathsInfo(const CGHeroInstance * h) const
{
return pathfinderCache->getPathsInfo(h);
}
void VCAI::invalidatePaths()
{
pathfinderCache->invalidatePaths();
}
void VCAI::yourTurn(QueryID queryID)
{
LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
NET_EVENT_HANDLER;
status.addQuery(queryID, "YourTurn");
requestActionASAP([=](){ answerQuery(queryID, 0); });
status.startedTurn();
makingTurn = std::make_unique<boost::thread>(&VCAI::makeTurn, this);
}
void VCAI::heroGotLevel(const CGHeroInstance * hero, PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
{
LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
NET_EVENT_HANDLER;
status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->getNameTranslated() % hero->level));
requestActionASAP([=](){ answerQuery(queryID, 0); });
}
void VCAI::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
{
LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
NET_EVENT_HANDLER;
status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
requestActionASAP([=](){ answerQuery(queryID, 0); });
}
void VCAI::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel, bool safeToAutoaccept)
{
LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i', autoaccept '%i'", text % askID % soundID % selection % cancel % safeToAutoaccept);
NET_EVENT_HANDLER;
int sel = 0;
status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
% components.size() % text));
if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
sel = static_cast<int>(components.size());
if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
sel = 1;
requestActionASAP([=]()
{
answerQuery(askID, sel);
});
}
void VCAI::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
{
// LOG_TRACE_PARAMS(logAi, "askID '%i', exits '%s'", askID % exits);
NET_EVENT_HANDLER;
status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits")
% exits.size()));
int chosenExit = -1;
if(impassable)
{
knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
}
else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.valid())
{
auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
chosenExit = vstd::find_pos(exits, neededExit);
}
for(auto exit : exits)
{
if(status.channelProbing() && exit.first == destinationTeleport)
{
chosenExit = vstd::find_pos(exits, exit);
break;
}
else
{
// TODO: Implement checking if visiting that teleport will uncovert any FoW
// So far this is the best option to handle decision about probing
auto obj = cb->getObj(exit.first, false);
if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
{
if(exit.first != destinationTeleport)
teleportChannelProbingList.push_back(exit.first);
}
}
}
requestActionASAP([=]()
{
answerQuery(askID, chosenExit);
});
}
void VCAI::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
{
LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
NET_EVENT_HANDLER;
std::string s1 = up ? up->nodeName() : "NONE";
std::string s2 = down ? down->nodeName() : "NONE";
status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
//you can't request action from action-response thread
requestActionASAP([=]()
{
if(removableUnits && !cb->getStartInfo()->isRestorationOfErathiaCampaign())
pickBestCreatures(down, up);
answerQuery(queryID, 0);
});
}
void VCAI::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
{
NET_EVENT_HANDLER;
status.addQuery(askID, "Map object select query");
requestActionASAP([=](){ answerQuery(askID, selectedObject.getNum()); });
}
void makePossibleUpgrades(const CArmedInstance * obj)
{
if(!obj)
return;
for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
{
if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
{
UpgradeInfo upgradeInfo(s->getId());
do
{
cb->fillUpgradeInfo(obj, SlotID(i), upgradeInfo);
if(upgradeInfo.hasUpgrades())
{
// creature at given slot might have alternative upgrades, pick best one
CreatureID upgID = *vstd::maxElementByFun(upgradeInfo.getAvailableUpgrades(), [](const CreatureID & id)
{
return id.toCreature()->getAIValue();
});
if(cb->getResourceAmount().canAfford(upgradeInfo.getUpgradeCostsFor(upgID) * s->count))
{
cb->upgradeCreature(obj, SlotID(i), upgID);
logAi->debug("Upgraded %d %s to %s", s->count, upgradeInfo.oldID.toCreature()->getNamePluralTranslated(),
upgradeInfo.getUpgrade().toCreature()->getNamePluralTranslated());
}
else
break;
}
}
while(upgradeInfo.hasUpgrades());
}
}
}
void VCAI::makeTurn()
{
MAKING_TURN;
auto day = cb->getDate(Date::DAY);
logAi->info("Player %d (%s) starting turn, day %d", playerID, playerID.toString(), day);
boost::shared_lock gsLock(CGameState::mutex);
setThreadName("VCAI::makeTurn");
switch(cb->getDate(Date::DAY_OF_WEEK))
{
case 1:
{
townVisitsThisWeek.clear();
std::vector<const CGObjectInstance *> objs;
retrieveVisitableObjs(objs, true);
for(const CGObjectInstance * obj : objs)
{
if(isWeeklyRevisitable(obj))
{
addVisitableObj(obj);
vstd::erase_if_present(alreadyVisited, obj);
}
}
break;
}
}
markHeroAbleToExplore(primaryHero());
visitedHeroes.clear();
try
{
//it looks messy here, but it's better to have armed heroes before attempting realizing goals
for (const CGTownInstance * t : cb->getTownsInfo())
moveCreaturesToHero(t);
mainLoop();
/*Below function is also responsible for hero movement via internal wander function. By design it is separate logic for heroes that have nothing to do.
Heroes that were not picked by striveToGoal(sptr(Goals::Win())); recently (so they do not have new goals and cannot continue/reevaluate previously locked goals) will do logic in wander().*/
performTypicalActions();
//for debug purpose
for (auto h : cb->getHeroesInfo())
{
if (h->movementPointsRemaining())
logAi->info("Hero %s has %d MP left", h->getNameTranslated(), h->movementPointsRemaining());
}
}
catch (boost::thread_interrupted & e)
{
(void)e;
logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
return;
}
catch (std::exception & e)
{
logAi->debug("Making turn thread has caught an exception: %s", e.what());
}
endTurn();
}
std::vector<HeroPtr> VCAI::getMyHeroes() const
{
std::vector<HeroPtr> ret;
for(auto h : cb->getHeroesInfo())
{
ret.push_back(h);
}
return ret;
}
void VCAI::mainLoop()
{
std::vector<Goals::TSubgoal> elementarGoals; //no duplicates allowed (operator ==)
basicGoals.clear();
validateVisitableObjs();
//get all potential and saved goals
//TODO: not lose
basicGoals.push_back(sptr(Goals::Win()));
for (auto goalPair : lockedHeroes)
{
fh->setPriority(goalPair.second); //re-evaluate, as heroes moved in the meantime
basicGoals.push_back(goalPair.second);
}
if (ah->hasTasksLeft())
basicGoals.push_back(ah->whatToDo());
for (auto quest : myCb->getMyQuests())
{
basicGoals.push_back(sptr(Goals::CompleteQuest(quest)));
}
basicGoals.push_back(sptr(Goals::Build()));
invalidPathHeroes.clear();
for (int pass = 0; pass< 30 && basicGoals.size(); pass++)
{
vstd::removeDuplicates(basicGoals); //TODO: container which does this automagically without has would be nice
goalsToAdd.clear();
goalsToRemove.clear();
elementarGoals.clear();
ultimateGoalsFromBasic.clear();
ah->updatePaths(getMyHeroes());
logAi->debug("Main loop: decomposing %i basic goals", basicGoals.size());
for (auto basicGoal : basicGoals)
{
logAi->debug("Main loop: decomposing basic goal %s", basicGoal->name());
auto goalToDecompose = basicGoal;
Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
int maxAbstractGoals = 10;
while (!elementarGoal->isElementar && maxAbstractGoals)
{
try
{
elementarGoal = decomposeGoal(goalToDecompose);
}
catch (goalFulfilledException & e)
{
//it is impossible to continue some goals (like exploration, for example)
//complete abstract goal for now, but maybe main goal finds another path
logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
completeGoal(e.goal); //put in goalsToRemove
break;
}
catch(cannotFulfillGoalException & e)
{
//it is impossible to continue some goals (like exploration, for example)
//complete abstract goal for now, but maybe main goal finds another path
goalsToRemove.push_back(basicGoal);
logAi->debug("Goal %s decomposition failed: %s", goalToDecompose->name(), e.what());
break;
}
catch (std::exception & e) //decomposition failed, which means we can't decompose entire tree
{
goalsToRemove.push_back(basicGoal);
logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
break;
}
if (elementarGoal->isAbstract) //we can decompose it further
{
goalsToAdd.push_back(elementarGoal);
//decompose further now - this is necesssary if we can't add over 10 goals in the pool
goalToDecompose = elementarGoal;
//there is a risk of infinite abstract goal loop, though it indicates failed logic
maxAbstractGoals--;
}
else if (elementarGoal->isElementar) //should be
{
logAi->debug("Found elementar goal %s", elementarGoal->name());
elementarGoals.push_back(elementarGoal);
ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
break;
}
else //should never be here
throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
}
}
logAi->trace("Main loop: selecting best elementar goal");
//now choose one elementar goal to realize
Goals::TGoalVec possibleGoals(elementarGoals.begin(), elementarGoals.end()); //copy to vector
Goals::TSubgoal goalToRealize = sptr(Goals::Invalid());
while (possibleGoals.size())
{
//allow assign goals to heroes with 0 movement, but don't realize them
//maybe there are better ones left
auto bestGoal = fh->chooseSolution(possibleGoals);
if (bestGoal->hero) //lock this hero to fulfill goal
{
setGoal(bestGoal->hero, bestGoal);
if (!bestGoal->hero->movementPointsRemaining() || vstd::contains(invalidPathHeroes, bestGoal->hero))
{
if (!vstd::erase_if_present(possibleGoals, bestGoal))
{
logAi->error("erase_if_preset failed? Something very wrong!");
break;
}
continue; //chose next from the list
}
}
goalToRealize = bestGoal; //we found our goal to execute
break;
}
//realize best goal
if (!goalToRealize->invalid())
{
logAi->debug("Trying to realize %s (value %2.3f)", goalToRealize->name(), goalToRealize->priority);
try
{
boost::this_thread::interruption_point();
goalToRealize->accept(this); //visitor pattern
boost::this_thread::interruption_point();
}
catch (boost::thread_interrupted & e)
{
(void)e;
logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
throw; //rethrow, we want to truly end this thread
}
catch (goalFulfilledException & e)
{
//the sub-goal was completed successfully
completeGoal(e.goal);
//local goal was also completed?
completeGoal(goalToRealize);
// remove abstract visit tile if we completed the elementar one
vstd::erase_if_present(goalsToAdd, goalToRealize);
}
catch (std::exception & e)
{
logAi->debug("Failed to realize subgoal of type %s, I will stop.", goalToRealize->name());
logAi->debug("The error message was: %s", e.what());
//erase base goal if we failed to execute decomposed goal
for (auto basicGoal : ultimateGoalsFromBasic[goalToRealize])
goalsToRemove.push_back(basicGoal);
// sometimes resource manager contains an elementar goal which is not able to execute anymore and just fails each turn.
ai->ah->notifyGoalCompleted(goalToRealize);
//we failed to realize best goal, but maybe others are still possible?
}
//remove goals we couldn't decompose
for (auto goal : goalsToRemove)
vstd::erase_if_present(basicGoals, goal);
//add abstract goals
boost::sort(goalsToAdd, [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
{
return lhs->priority > rhs->priority; //highest priority at the beginning
});
//max number of goals = 10
int i = 0;
while (basicGoals.size() < 10 && goalsToAdd.size() > i)
{
if (!vstd::contains(basicGoals, goalsToAdd[i])) //don't add duplicates
basicGoals.push_back(goalsToAdd[i]);
i++;
}
}
else //no elementar goals possible
{
logAi->debug("Goal decomposition exhausted");
break;
}
}
}
void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
{
LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->getNameTranslated() % obj->getObjectName() % obj->anchorPos().toString());
switch(obj->ID)
{
case Obj::TOWN:
moveCreaturesToHero(dynamic_cast<const CGTownInstance *>(obj));
if(h->visitedTown) //we are inside, not just attacking
{
townVisitsThisWeek[h].insert(h->visitedTown);
if(!h->hasSpellbook() && ah->freeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
{
if(h->visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
}
}
break;
}
completeGoal(sptr(Goals::VisitObj(obj->id.getNum()).sethero(h)));
}
void VCAI::moveCreaturesToHero(const CGTownInstance * t)
{
if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
{
pickBestCreatures(t->visitingHero, t);
}
}
void VCAI::pickBestCreatures(const CArmedInstance * destinationArmy, const CArmedInstance * source)
{
const CArmedInstance * armies[] = {destinationArmy, source};
auto bestArmy = ah->getSortedSlots(destinationArmy, source);
//foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
for(SlotID i = SlotID(0); i.getNum() < bestArmy.size() && i.validSlot(); i.advance(1)) //i-th strongest creature type will go to i-th slot
{
const CCreature * targetCreature = bestArmy[i.getNum()].creature;
for(auto armyPtr : armies)
{
for(SlotID j = SlotID(0); j.validSlot(); j.advance(1))
{
if(armyPtr->getCreature(j) == targetCreature && (i != j || armyPtr != destinationArmy)) //it's a searched creature not in dst SLOT
{
//can't take away last creature without split. generate a new stack with 1 creature which is weak but fast
if(armyPtr == source
&& source->needsLastStack()
&& source->stacksCount() == 1
&& (!destinationArmy->hasStackAtSlot(i) || destinationArmy->getCreature(i) == targetCreature))
{
auto weakest = ah->getWeakestCreature(bestArmy);
if(weakest->creature == targetCreature)
{
if(1 == source->getStackCount(j))
break;
// move all except 1 of weakest creature from source to destination
cb->splitStack(
source,
destinationArmy,
j,
destinationArmy->getSlotFor(targetCreature),
destinationArmy->getStackCount(i) + source->getStackCount(j) - 1);
break;
}
else
{
// Source last stack is not weakest. Move 1 of weakest creature from destination to source
cb->splitStack(
destinationArmy,
source,
destinationArmy->getSlotFor(weakest->creature),
source->getFreeSlot(),
1);
}
}
cb->mergeOrSwapStacks(armyPtr, destinationArmy, j, i);
}
}
}
}
//TODO - having now strongest possible army, we may want to think about arranging stacks
auto hero = dynamic_cast<const CGHeroInstance *>(destinationArmy);
if(hero)
checkHeroArmy(hero);
}
void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
{
auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
{
bool changeMade = false;
do
{
changeMade = false;
//we collect gear always in same order
std::vector<ArtifactLocation> allArtifacts;
if(giveStuffToFirstHero)
{
for(auto p : h->artifactsWorn)
{
if(p.second.artifact)
allArtifacts.push_back(ArtifactLocation(h->id, p.first));
}
}
for(auto slot : h->artifactsInBackpack)
allArtifacts.push_back(ArtifactLocation(h->id, h->getArtPos(slot.artifact)));
if(otherh)
{
for(auto p : otherh->artifactsWorn)
{
if(p.second.artifact)
allArtifacts.push_back(ArtifactLocation(otherh->id, p.first));
}
for(auto slot : otherh->artifactsInBackpack)
allArtifacts.push_back(ArtifactLocation(otherh->id, otherh->getArtPos(slot.artifact)));
}
//we give stuff to one hero or another, depending on giveStuffToFirstHero
const CGHeroInstance * target = nullptr;
if(giveStuffToFirstHero || !otherh)
target = h;
else
target = otherh;
for(auto location : allArtifacts)
{
if(location.slot == ArtifactPosition::MACH4 || location.slot == ArtifactPosition::SPELLBOOK)
continue; // don't attempt to move catapult and spellbook
if(location.artHolder == target->id && ArtifactUtils::isSlotEquipment(location.slot))
continue; //don't reequip artifact we already wear
auto s = cb->getHero(location.artHolder)->getSlot(location.slot);
if(!s || s->locked) //we can't move locks
continue;
auto artifact = s->artifact;
if(!artifact)
continue;
//FIXME: why are the above possible to be null?
bool emptySlotFound = false;
for(auto slot : artifact->getType()->getPossibleSlots().at(target->bearerType()))
{
if(target->isPositionFree(slot) && artifact->canBePutAt(target, slot, true)) //combined artifacts are not always allowed to move
{
ArtifactLocation destLocation(target->id, slot);
cb->swapArtifacts(location, destLocation); //just put into empty slot
emptySlotFound = true;
changeMade = true;
break;
}
}
if(!emptySlotFound) //try to put that atifact in already occupied slot
{
for(auto slot : artifact->getType()->getPossibleSlots().at(target->bearerType()))
{
auto otherSlot = target->getSlot(slot);
if(otherSlot && otherSlot->artifact) //we need to exchange artifact for better one
{
//if that artifact is better than what we have, pick it
if(compareArtifacts(artifact, otherSlot->artifact) && artifact->canBePutAt(target, slot, true)) //combined artifacts are not always allowed to move
{
ArtifactLocation destLocation(target->id, slot);
cb->swapArtifacts(location, ArtifactLocation(target->id, target->getArtPos(otherSlot->artifact)));
changeMade = true;
break;
}
}
}
}
if(changeMade)
break; //start evaluating artifacts from scratch
}
}
while(changeMade);
};
equipBest(h, other, true);
if(other)
equipBest(h, other, false);
}
void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
{
//now used only for visited dwellings / towns, not BuyArmy goal
for(int i = 0; i < d->creatures.size(); i++)
{
if(!d->creatures[i].second.size())
continue;
int count = d->creatures[i].first;
CreatureID creID = d->creatures[i].second.back();
vstd::amin(count, ah->freeResources() / VLC->creatures()->getById(creID)->getFullRecruitCost());
if(count > 0)
cb->recruitCreatures(d, recruiter, creID, count, i);
}
}
bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, std::optional<float> movementCostLimit)
{
int3 op = obj->visitablePos();
auto paths = ah->getPathsToTile(h, op);
for(const auto & path : paths)
{
if(movementCostLimit && movementCostLimit.value() < path.movementCost())
return false;
if(isGoodForVisit(obj, h, path))
return true;
}
return false;
}
bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const
{
const int3 pos = obj->visitablePos();
const int3 targetPos = path.firstTileToGet();
if (!targetPos.valid())
return false;
if (!isTileNotReserved(h.get(), targetPos))
return false;
if (obj->wasVisited(playerID))
return false;
if (cb->getPlayerRelations(playerID, obj->tempOwner) != PlayerRelations::ENEMIES && !isWeeklyRevisitable(obj))
return false; // Otherwise we flag or get weekly resources / creatures
if (!isSafeToVisit(h, pos))
return false;
if (!shouldVisit(h, obj))
return false;
if (vstd::contains(alreadyVisited, obj))
return false;
if (vstd::contains(reservedObjs, obj))
return false;
// TODO: looks extra if we already have AIPath
//if (!isAccessibleForHero(targetPos, h))
// return false;
const CGObjectInstance * topObj = cb->getVisitableObjs(obj->visitablePos()).back(); //it may be hero visiting this obj
//we don't try visiting object on which allied or owned hero stands
// -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
return !(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES); //all of the following is met
}
bool VCAI::isTileNotReserved(const CGHeroInstance * h, int3 t) const
{
if(t.valid())
{
auto obj = cb->getTopObj(t);
if(obj && vstd::contains(ai->reservedObjs, obj)
&& vstd::contains(reservedHeroesMap, h)
&& !vstd::contains(reservedHeroesMap.at(h), obj))
return false; //do not capture object reserved by another hero
else
return true;
}
else
{
return false;
}
}
bool VCAI::canRecruitAnyHero(const CGTownInstance * t) const
{
//TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
if(!t)
t = findTownWithTavern();
if(!t)
return false;
if(cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST) //TODO: use ResourceManager
return false;
if(cb->getHeroesInfo().size() >= cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
return false;
if(!cb->getAvailableHeroes(t).size())
return false;
return true;
}
void VCAI::wander(HeroPtr h)
{
auto visitTownIfAny = [this](HeroPtr h) -> bool
{
if (h->visitedTown)
{
townVisitsThisWeek[h].insert(h->visitedTown);
buildArmyIn(h->visitedTown);
return true;
}
return false;
};
//unclaim objects that are now dangerous for us
auto reservedObjsSetCopy = reservedHeroesMap[h];
for(auto obj : reservedObjsSetCopy)
{
if(!isSafeToVisit(h, obj->visitablePos()))
unreserveObject(h, obj);
}
TimeCheck tc("looking for wander destination");
for(int k = 0; k < 10 && h->movementPointsRemaining(); k++)
{
validateVisitableObjs();
ah->updatePaths(getMyHeroes());
std::vector<ObjectIdRef> dests;
//also visit our reserved objects - but they are not prioritized to avoid running back and forth
vstd::copy_if(reservedHeroesMap[h], std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
{
return ah->isTileAccessible(h, obj->visitablePos());
});
int pass = 0;
std::vector<std::optional<float>> distanceLimits = {1.0, 2.0, std::nullopt};
while(!dests.size() && pass < distanceLimits.size())
{
auto & distanceLimit = distanceLimits[pass];
logAi->debug("Looking for wander destination pass=%i, cost limit=%f", pass, distanceLimit.value_or(-1.0));
vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
{
return isGoodForVisit(obj, h, distanceLimit);
});
pass++;
}
if(!dests.size())
{
logAi->debug("Looking for town destination");
if(cb->getVisitableObjs(h->visitablePos()).size() > 1)
moveHeroToTile(h->visitablePos(), h); //just in case we're standing on blocked subterranean gate
auto compareReinforcements = [&](const CGTownInstance * lhs, const CGTownInstance * rhs) -> bool
{
const CGHeroInstance * hptr = h.get();
auto r1 = ah->howManyReinforcementsCanGet(hptr, lhs);
auto r2 = ah->howManyReinforcementsCanGet(hptr, rhs);
if (r1 != r2)
return r1 < r2;
else
return ah->howManyReinforcementsCanBuy(hptr, lhs) < ah->howManyReinforcementsCanBuy(hptr, rhs);
};
std::vector<const CGTownInstance *> townsReachable;
std::vector<const CGTownInstance *> townsNotReachable;
for(const CGTownInstance * t : cb->getTownsInfo())
{
if(!t->visitingHero && !vstd::contains(townVisitsThisWeek[h], t))
{
if(isAccessibleForHero(t->visitablePos(), h))
townsReachable.push_back(t);
else
townsNotReachable.push_back(t);
}
}
if(townsReachable.size()) //travel to town with largest garrison, or empty - better than nothing
{
dests.push_back(*boost::max_element(townsReachable, compareReinforcements));
}
else if(townsNotReachable.size())
{
//TODO pick the truly best
const CGTownInstance * t = *boost::max_element(townsNotReachable, compareReinforcements);
logAi->debug("%s can't reach any town, we'll try to make our way to %s at %s", h->getNameTranslated(), t->getNameTranslated(), t->visitablePos().toString());
int3 posBefore = h->visitablePos();
striveToGoal(sptr(Goals::ClearWayTo(t->visitablePos()).sethero(h))); //TODO: drop "strive", add to mainLoop
//if out hero is stuck, we may need to request another hero to clear the way we see
if(posBefore == h->visitablePos() && h == primaryHero()) //hero can't move
{
if(canRecruitAnyHero(t))
recruitHero(t);
}
break;
}
else if(cb->getResourceAmount(EGameResID::GOLD) >= GameConstants::HERO_GOLD_COST)
{
std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
{
for(const CGHeroInstance * h : cb->getHeroesInfo())
{
if(!t->getArmyStrength() || ah->howManyReinforcementsCanGet(h, t))
return true;
}
return false;
});
if (towns.size())
{
recruitHero(*boost::max_element(towns, compareArmyStrength));
}
break;
}
else
{
logAi->debug("Nowhere more to go...");
break;
}
}
//end of objs empty
if(dests.size()) //performance improvement
{
Goals::TGoalVec targetObjectGoals;
for(auto destination : dests)
{
vstd::concatenate(targetObjectGoals, ah->howToVisitObj(h, destination, false));
}
if(targetObjectGoals.size())
{
auto bestObjectGoal = fh->chooseSolution(targetObjectGoals);
//wander should not cause heroes to be reserved - they are always considered free
if(bestObjectGoal->goalType == Goals::VISIT_OBJ)
{
auto chosenObject = cb->getObjInstance(ObjectInstanceID(bestObjectGoal->objid));
if(chosenObject != nullptr)
logAi->debug("Of all %d destinations, object %s at pos=%s seems nice", dests.size(), chosenObject->getObjectName(), chosenObject->anchorPos().toString());
}
else
logAi->debug("Trying to realize goal of type %s as part of wandering.", bestObjectGoal->name());
try
{
decomposeGoal(bestObjectGoal)->accept(this);
}
catch(const goalFulfilledException & e)
{
if(e.goal->goalType == Goals::EGoals::VISIT_TILE || e.goal->goalType == Goals::EGoals::VISIT_OBJ)
continue;
throw;
}
}
else
{
logAi->debug("Nowhere more to go...");
break;
}
visitTownIfAny(h);
}
}
visitTownIfAny(h); //in case hero is just sitting in town
}
void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
{
if(goal->invalid())
{
vstd::erase_if_present(lockedHeroes, h);
}
else
{
lockedHeroes[h] = goal;
goal->setisElementar(false); //Force always evaluate goals before realizing
}
}
void VCAI::evaluateGoal(HeroPtr h)
{
if(vstd::contains(lockedHeroes, h))
fh->setPriority(lockedHeroes[h]);
}
void VCAI::completeGoal(Goals::TSubgoal goal)
{
if (goal->goalType == Goals::WIN) //we can never complete this goal - unless we already won
return;
logAi->debug("Completing goal: %s", goal->name());
//notify Managers
ah->notifyGoalCompleted(goal);
//notify mainLoop()
goalsToRemove.push_back(goal); //will be removed from mainLoop() goals
for (auto basicGoal : basicGoals) //we could luckily fulfill any of our goals
{
if (basicGoal->fulfillsMe(goal))
goalsToRemove.push_back(basicGoal);
}
//unreserve heroes
if(const CGHeroInstance * h = goal->hero.get(true))
{
auto it = lockedHeroes.find(h);
if(it != lockedHeroes.end())
{
if(it->second == goal || it->second->fulfillsMe(goal)) //FIXME this is overspecified, fulfillsMe should be complete
{
logAi->debug(goal->completeMessage());
lockedHeroes.erase(it); //goal fulfilled, free hero
}
}
}
else //complete goal for all heroes maybe?
{
vstd::erase_if(lockedHeroes, [goal](std::pair<HeroPtr, Goals::TSubgoal> p)
{
if(p.second == goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
{
logAi->debug(p.second->completeMessage());
return true;
}
return false;
});
}
}
void VCAI::battleStart(const BattleID & battleID, const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, BattleSide side, bool replayAllowed)
{
NET_EVENT_HANDLER;
assert(!playerID.isValidPlayer() || status.getBattle() == UPCOMING_BATTLE);
status.setBattle(ONGOING_BATTLE);
const CGObjectInstance * presumedEnemy = vstd::backOrNull(cb->getVisitableObjs(tile)); //may be nullptr in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->getNameTranslated() : "a army") % (presumedEnemy ? presumedEnemy->getObjectName() : "unknown enemy") % tile.toString());
CAdventureAI::battleStart(battleID, army1, army2, tile, hero1, hero2, side, replayAllowed);
}
void VCAI::battleEnd(const BattleID & battleID, const BattleResult * br, QueryID queryID)
{
NET_EVENT_HANDLER;
assert(status.getBattle() == ONGOING_BATTLE);
status.setBattle(ENDING_BATTLE);
bool won = br->winner == myCb->getBattle(battleID)->battleGetMySide();
logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.toString(), (won ? "won" : "lost"), battlename);
battlename.clear();
CAdventureAI::battleEnd(battleID, br, queryID);
}
void VCAI::waitTillFree()
{
auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
status.waitTillFree();
}
void VCAI::markObjectVisited(const CGObjectInstance * obj)
{
if(!obj)
return;
if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj)) //we may want to visit it with another hero
{
if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_HERO) //we may want to visit it with another hero
return;
if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_BONUS) //or another time
return;
}
if(obj->ID == Obj::MONSTER)
return;
alreadyVisited.insert(obj);
}
void VCAI::reserveObject(HeroPtr h, const CGObjectInstance * obj)
{
reservedObjs.insert(obj);
reservedHeroesMap[h].insert(obj);
logAi->debug("reserved object id=%d; address=%p; name=%s", obj->id, obj, obj->getObjectName());
}
void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance * obj)
{
vstd::erase_if_present(reservedObjs, obj); //unreserve objects
vstd::erase_if_present(reservedHeroesMap[h], obj);
}
void VCAI::markHeroUnableToExplore(HeroPtr h)
{
heroesUnableToExplore.insert(h);
}
void VCAI::markHeroAbleToExplore(HeroPtr h)
{
vstd::erase_if_present(heroesUnableToExplore, h);
}
bool VCAI::isAbleToExplore(HeroPtr h)
{
return !vstd::contains(heroesUnableToExplore, h);
}
void VCAI::clearPathsInfo()
{
heroesUnableToExplore.clear();
}
void VCAI::validateVisitableObjs()
{
std::string errorMsg;
auto shouldBeErased = [&](const CGObjectInstance * obj) -> bool
{
if(obj)
return !cb->getObj(obj->id, false); // no verbose output needed as we check object visibility
else
return true;
};
//errorMsg is captured by ref so lambda will take the new text
errorMsg = " shouldn't be on the visitable objects list!";
vstd::erase_if(visitableObjs, shouldBeErased);
//FIXME: how comes our own heroes become inaccessible?
vstd::erase_if(reservedHeroesMap, [](std::pair<HeroPtr, std::set<const CGObjectInstance *>> hp) -> bool
{
return !hp.first.get(true);
});
for(auto & p : reservedHeroesMap)
{
errorMsg = " shouldn't be on list for hero " + p.first->getNameTranslated() + "!";
vstd::erase_if(p.second, shouldBeErased);
}
errorMsg = " shouldn't be on the reserved objs list!";
vstd::erase_if(reservedObjs, shouldBeErased);
//TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
errorMsg = " shouldn't be on the already visited objs list!";
vstd::erase_if(alreadyVisited, shouldBeErased);
}
void VCAI::retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned) const
{
foreach_tile_pos([&](const int3 & pos)
{
for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
{
if(includeOwned || obj->tempOwner != playerID)
out.push_back(obj);
}
});
}
void VCAI::retrieveVisitableObjs()
{
foreach_tile_pos([&](const int3 & pos)
{
for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
{
if(obj->tempOwner != playerID)
addVisitableObj(obj);
}
});
}
std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
{
std::vector<const CGObjectInstance *> ret;
for(const CGObjectInstance * obj : visitableObjs)
{
if(obj->tempOwner == playerID)
ret.push_back(obj);
}
return ret;
}
void VCAI::addVisitableObj(const CGObjectInstance * obj)
{
if(obj->ID == Obj::EVENT)
return;
visitableObjs.insert(obj);
// All teleport objects seen automatically assigned to appropriate channels
auto teleportObj = dynamic_cast<const CGTeleport *>(obj);
if(teleportObj)
CGTeleport::addToChannel(knownTeleportChannels, teleportObj);
}
const CGObjectInstance * VCAI::lookForArt(ArtifactID aid) const
{
for(const CGObjectInstance * obj : ai->visitableObjs)
{
if(obj->ID == Obj::ARTIFACT && dynamic_cast<const CGArtifact *>(obj)->getArtifact() == aid)
return obj;
}
return nullptr;
//TODO what if more than one artifact is available? return them all or some selection criteria
}
bool VCAI::isAccessible(const int3 & pos) const
{
//TODO precalculate for speed
for(const CGHeroInstance * h : cb->getHeroesInfo())
{
if(isAccessibleForHero(pos, h))
return true;
}
return false;
}
HeroPtr VCAI::getHeroWithGrail() const
{
for(const CGHeroInstance * h : cb->getHeroesInfo())
{
if(h->hasArt(ArtifactID::GRAIL))
return h;
}
return nullptr;
}
const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate)
{
//TODO smarter definition of unvisited
for(const CGObjectInstance * obj : visitableObjs)
{
if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
return obj;
}
return nullptr;
}
bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies) const
{
// Don't visit tile occupied by allied hero
if(!includeAllies)
{
for(auto obj : cb->getVisitableObjs(pos))
{
if(obj->ID == Obj::HERO && cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES)
{
if(obj != h.get())
return false;
}
}
}
return getPathsInfo(h.get())->getPathInfo(pos)->reachable();
}
bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
{
//TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
auto afterMovementCheck = [&]() -> void
{
waitTillFree(); //movement may cause battle or blocking dialog
if(!h)
{
lostHero(h);
teleportChannelProbingList.clear();
if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
status.setChannelProbing(false);
throw cannotFulfillGoalException("Hero was lost!");
}
};
logAi->debug("Moving hero %s to tile %s", h->getNameTranslated(), dst.toString());
int3 startHpos = h->visitablePos();
bool ret = false;
if(startHpos == dst)
{
//FIXME: this assertion fails also if AI moves onto defeated guarded object
assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
cb->moveHero(*h, h->convertFromVisitablePos(dst), false);
afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
// If revisiting, teleport probing is never done, and so the entries into the list would remain unused and uncleared
teleportChannelProbingList.clear();
// not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
ret = true;
}
else
{
CGPath path;
getPathsInfo(h.get())->getPath(path, dst);
if(path.nodes.empty())
{
logAi->error("Hero %s cannot reach %s.", h->getNameTranslated(), dst.toString());
throw goalFulfilledException(sptr(Goals::VisitTile(dst).sethero(h)));
}
int i = (int)path.nodes.size() - 1;
auto getObj = [&](int3 coord, bool ignoreHero)
{
auto tile = cb->getTile(coord, false);
assert(tile);
return tile->topVisitableObj(ignoreHero);
//return cb->getTile(coord,false)->topVisitableObj(ignoreHero);
};
auto isTeleportAction = [&](EPathNodeAction action) -> bool
{
if(action != EPathNodeAction::TELEPORT_NORMAL && action != EPathNodeAction::TELEPORT_BLOCKING_VISIT)
{
if(action != EPathNodeAction::TELEPORT_BATTLE)
{
return false;
}
}
return true;
};
auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
{
if(CGTeleport::isConnected(currentObject, nextObjectTop))
return nextObjectTop;
if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
{
if(CGTeleport::isConnected(currentObject, nextObject))
return nextObject;
}
return nullptr;
};
auto doMovement = [&](int3 dst, bool transit)
{
cb->moveHero(*h, h->convertFromVisitablePos(dst), transit);
};
auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
{
destinationTeleport = exitId;
if(exitPos.valid())
destinationTeleportPos = exitPos;
cb->moveHero(*h, h->pos, false);
destinationTeleport = ObjectInstanceID();
destinationTeleportPos = int3(-1);
afterMovementCheck();
};
auto doChannelProbing = [&]() -> void
{
auto currentPos = h->visitablePos();
auto currentExit = getObj(currentPos, true)->id;
status.setChannelProbing(true);
for(auto exit : teleportChannelProbingList)
doTeleportMovement(exit, int3(-1));
teleportChannelProbingList.clear();
status.setChannelProbing(false);
doTeleportMovement(currentExit, currentPos);
};
for(; i > 0; i--)
{
int3 currentCoord = path.nodes[i].coord;
int3 nextCoord = path.nodes[i - 1].coord;
auto currentObject = getObj(currentCoord, currentCoord == h->visitablePos());
auto nextObjectTop = getObj(nextCoord, false);
auto nextObject = getObj(nextCoord, true);
auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
{
//we use special login if hero standing on teleporter it's mean we need
doTeleportMovement(destTeleportObj->id, nextCoord);
if(teleportChannelProbingList.size())
doChannelProbing();
markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
continue;
}
//stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
if(path.nodes[i - 1].turns)
{
//blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
break;
}
int3 endpos = path.nodes[i - 1].coord;
if(endpos == h->visitablePos())
continue;
bool isConnected = false;
bool isNextObjectTeleport = false;
// Check there is node after next one; otherwise transit is pointless
if(i - 2 >= 0)
{
isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
}
if(isConnected || isNextObjectTeleport)
{
// Hero should be able to go through object if it's allow transit
doMovement(endpos, true);
}
else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
{
doMovement(endpos, true);
}
else
{
doMovement(endpos, false);
}
afterMovementCheck();
if(teleportChannelProbingList.size())
doChannelProbing();
}
if(path.nodes[0].action == EPathNodeAction::BLOCKING_VISIT)
{
ret = h && i == 0; // when we take resource we do not reach its position. We even might not move
}
}
if(h)
{
if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
{
if(visitedObject != *h)
performObjectInteraction(visitedObject, h);
}
}
if(h) //we could have lost hero after last move
{
completeGoal(sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway
completeGoal(sptr(Goals::ClearWayTo(dst).sethero(h)));
ret = ret || (dst == h->visitablePos());
if(!ret) //reserve object we are heading towards
{
auto obj = vstd::frontOrNull(cb->getVisitableObjs(dst));
if(obj && obj != *h)
reserveObject(h, obj);
}
if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
{
vstd::erase_if_present(lockedHeroes, h); //hero seemingly is confused or has only 95mp which is not enough to move
invalidPathHeroes.insert(h);
throw cannotFulfillGoalException("Invalid path found!");
}
evaluateGoal(h); //new hero position means new game situation
logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->getNameTranslated(), startHpos.toString(), h->visitablePos().toString(), ret);
}
return ret;
}
void VCAI::buildStructure(const CGTownInstance * t, BuildingID building)
{
auto name = t->getTown()->buildings.at(building)->getNameTranslated();
logAi->debug("Player %d will build %s in town of %s at %s", ai->playerID, name, t->getNameTranslated(), t->anchorPos().toString());
cb->buildBuilding(t, building); //just do this;
}
void VCAI::tryRealize(Goals::Explore & g)
{
throw cannotFulfillGoalException("EXPLORE is not an elementar goal!");
}
void VCAI::tryRealize(Goals::RecruitHero & g)
{
if(cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST)
throw cannotFulfillGoalException("Not enough gold to recruit hero!");
if(const CGTownInstance * t = findTownWithTavern())
{
recruitHero(t, true);
//TODO try to free way to blocked town
//TODO: adventure map tavern or prison?
}
else
{
throw cannotFulfillGoalException("No town to recruit hero!");
}
}
void VCAI::tryRealize(Goals::VisitTile & g)
{
if(!g.hero->movementPointsRemaining())
throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
{
logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->getNameTranslated(), g.tile.toString());
throw goalFulfilledException(sptr(g));
}
if(ai->moveHeroToTile(g.tile, g.hero.get()))
{
throw goalFulfilledException(sptr(g));
}
}
void VCAI::tryRealize(Goals::VisitObj & g)
{
auto position = g.tile;
if(!g.hero->movementPointsRemaining())
throw cannotFulfillGoalException("Cannot visit object: hero is out of MPs!");
if(position == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
{
logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->getNameTranslated(), g.tile.toString());
throw goalFulfilledException(sptr(g));
}
if(ai->moveHeroToTile(position, g.hero.get()))
{
throw goalFulfilledException(sptr(g));
}
}
void VCAI::tryRealize(Goals::VisitHero & g)
{
if(!g.hero->movementPointsRemaining())
throw cannotFulfillGoalException("Cannot visit target hero: hero is out of MPs!");
const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid));
if(obj)
{
if(ai->moveHeroToTile(obj->visitablePos(), g.hero.get()))
{
throw goalFulfilledException(sptr(g));
}
}
else
{
throw cannotFulfillGoalException("Cannot visit hero: object not found!");
}
}
void VCAI::tryRealize(Goals::BuildThis & g)
{
auto b = BuildingID(g.bid);
auto t = g.town;
if (t)
{
if (cb->canBuildStructure(t, b) == EBuildingState::ALLOWED)
{
logAi->debug("Player %d will build %s in town of %s at %s",
playerID, t->getTown()->buildings.at(b)->getNameTranslated(), t->getNameTranslated(), t->anchorPos().toString());
cb->buildBuilding(t, b);
throw goalFulfilledException(sptr(g));
}
}
throw cannotFulfillGoalException("Cannot build a given structure!");
}
void VCAI::tryRealize(Goals::DigAtTile & g)
{
assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
{
cb->dig(g.hero.get());
completeGoal(sptr(g)); // finished digging
}
else
{
ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
throw cannotFulfillGoalException("A hero can't dig!\n");
}
}
void VCAI::tryRealize(Goals::Trade & g) //trade
{
if(ah->freeResources()[g.resID] >= g.value) //goal is already fulfilled. Why we need this check, anyway?
throw goalFulfilledException(sptr(g));
int acquiredResources = 0;
if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
{
if(const auto * m = dynamic_cast<const IMarket*>(obj))
{
auto freeRes = ah->freeResources(); //trade only resources which are not reserved
for(auto it = ResourceSet::nziterator(freeRes); it.valid(); it++)
{
auto res = it->resType;
if(res.getNum() == g.resID) //sell any other resource
continue;
int toGive;
int toGet;
m->getOffer(res, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
toGive = static_cast<int>(toGive * (it->resVal / toGive)); //round down
//TODO trade only as much as needed
if (toGive) //don't try to sell 0 resources
{
cb->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, res, GameResID(g.resID), toGive);
acquiredResources = static_cast<int>(toGet * (it->resVal / toGive));
logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, acquiredResources, g.resID, obj->getObjectName());
}
if (ah->freeResources()[g.resID] >= g.value)
throw goalFulfilledException(sptr(g)); //we traded all we needed
}
throw cannotFulfillGoalException("I cannot get needed resources by trade!");
}
else
{
throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
}
}
else
{
throw cannotFulfillGoalException("No object that could be used to raise resources!");
}
}
void VCAI::tryRealize(Goals::BuyArmy & g)
{
auto t = g.town;
ui64 valueBought = 0;
//buy the stacks with largest AI value
makePossibleUpgrades(t);
while (valueBought < g.value)
{
auto res = ah->allResources();
std::vector<creInfo> creaturesInDwellings;
for (int i = 0; i < t->creatures.size(); i++)
{
auto ci = infoFromDC(t->creatures[i]);
if(!ci.count
|| ci.creID == CreatureID::NONE
|| (g.objid != -1 && ci.creID.getNum() != g.objid)
|| t->getUpperArmy()->getSlotFor(ci.creID) == SlotID())
continue;
vstd::amin(ci.count, res / ci.cre->getFullRecruitCost()); //max count we can afford
if(!ci.count)
continue;
ci.level = i; //this is important for Dungeon Summoning Portal
creaturesInDwellings.push_back(ci);
}
if (creaturesInDwellings.empty())
throw cannotFulfillGoalException("Can't buy any more creatures!");
creInfo ci =
*boost::max_element(creaturesInDwellings, [](const creInfo & lhs, const creInfo & rhs)
{
//max value of creatures we can buy with our res
int value1 = lhs.cre->getAIValue() * lhs.count;
int value2 = rhs.cre->getAIValue() * rhs.count;
return value1 < value2;
});
cb->recruitCreatures(t, t->getUpperArmy(), ci.creID, ci.count, ci.level);
valueBought += ci.count * ci.cre->getAIValue();
}
throw goalFulfilledException(sptr(g)); //we bought as many creatures as we wanted
}
void VCAI::tryRealize(Goals::Invalid & g)
{
throw cannotFulfillGoalException("I don't know how to fulfill this!");
}
void VCAI::tryRealize(Goals::AbstractGoal & g)
{
logAi->debug("Attempting realizing goal with code %s", g.name());
throw cannotFulfillGoalException("Unknown type of goal !");
}
const CGTownInstance * VCAI::findTownWithTavern() const
{
for(const CGTownInstance * t : cb->getTownsInfo())
if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
return t;
return nullptr;
}
Goals::TSubgoal VCAI::getGoal(HeroPtr h) const
{
auto it = lockedHeroes.find(h);
if(it != lockedHeroes.end())
return it->second;
else
return sptr(Goals::Invalid());
}
std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
{
std::vector<HeroPtr> ret;
for(auto h : cb->getHeroesInfo())
{
//&& !vstd::contains(lockedHeroes, h)
//at this point we assume heroes exhausted their locked goals
if(canAct(h))
ret.push_back(h);
}
return ret;
}
bool VCAI::canAct(HeroPtr h) const
{
auto mission = lockedHeroes.find(h);
if(mission != lockedHeroes.end())
{
//FIXME: I'm afraid there can be other conditions when heroes can act but not move :?
if(mission->second->goalType == Goals::DIG_AT_TILE && !mission->second->isElementar)
return false;
}
return h->movementPointsRemaining();
}
HeroPtr VCAI::primaryHero() const
{
auto hs = cb->getHeroesInfo();
if (hs.empty())
return nullptr;
else
return *boost::max_element(hs, compareHeroStrength);
}
void VCAI::endTurn()
{
logAi->info("Player %d (%s) ends turn", playerID, playerID.toString());
if(!status.haveTurn())
{
logAi->error("Not having turn at the end of turn???");
}
logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
do
{
cb->endTurn();
}
while(status.haveTurn()); //for some reasons, our request may fail -> stop requesting end of turn only after we've received a confirmation that it's over
logGlobal->info("Player %d (%s) ended turn", playerID, playerID.toString());
}
void VCAI::striveToGoal(Goals::TSubgoal basicGoal)
{
//TODO: this function is deprecated and should be dropped altogether
auto goalToDecompose = basicGoal;
Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
int maxAbstractGoals = 10;
while (!elementarGoal->isElementar && maxAbstractGoals)
{
try
{
elementarGoal = decomposeGoal(goalToDecompose);
}
catch (goalFulfilledException & e)
{
//it is impossible to continue some goals (like exploration, for example)
completeGoal(e.goal); //put in goalsToRemove
logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
return;
}
catch (std::exception & e)
{
goalsToRemove.push_back(basicGoal);
logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
return;
}
if (elementarGoal->isAbstract) //we can decompose it further
{
goalsToAdd.push_back(elementarGoal);
//decompose further now - this is necesssary if we can't add over 10 goals in the pool
goalToDecompose = elementarGoal;
//there is a risk of infinite abstract goal loop, though it indicates failed logic
maxAbstractGoals--;
}
else if (elementarGoal->isElementar) //should be
{
logAi->debug("Found elementar goal %s", elementarGoal->name());
ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
break;
}
else //should never be here
throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
}
//realize best goal
if (!elementarGoal->invalid())
{
logAi->debug("Trying to realize %s (value %2.3f)", elementarGoal->name(), elementarGoal->priority);
try
{
boost::this_thread::interruption_point();
elementarGoal->accept(this); //visitor pattern
boost::this_thread::interruption_point();
}
catch (boost::thread_interrupted & e)
{
(void)e;
logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
throw; //rethrow, we want to truly end this thread
}
catch (goalFulfilledException & e)
{
//the sub-goal was completed successfully
completeGoal(e.goal);
//local goal was also completed
completeGoal(elementarGoal);
}
catch (std::exception & e)
{
logAi->debug("Failed to realize subgoal of type %s, I will stop.", elementarGoal->name());
logAi->debug("The error message was: %s", e.what());
//erase base goal if we failed to execute decomposed goal
for (auto basicGoalToRemove : ultimateGoalsFromBasic[elementarGoal])
goalsToRemove.push_back(basicGoalToRemove);
}
}
}
Goals::TSubgoal VCAI::decomposeGoal(Goals::TSubgoal ultimateGoal)
{
if(ultimateGoal->isElementar)
{
logAi->warn("Trying to decompose elementar goal %s", ultimateGoal->name());
return ultimateGoal;
}
const int searchDepth = 30;
Goals::TSubgoal goal = ultimateGoal;
logAi->debug("Decomposing goal %s", ultimateGoal->name());
int maxGoals = searchDepth; //preventing deadlock for mutually dependent goals
while (maxGoals)
{
boost::this_thread::interruption_point();
goal = goal->whatToDoToAchieve(); //may throw if decomposition fails
--maxGoals;
if (goal == ultimateGoal) //compare objects by value
if (goal->isElementar == ultimateGoal->isElementar)
throw cannotFulfillGoalException((boost::format("Goal dependency loop detected for %s!")
% ultimateGoal->name()).str());
if (goal->isAbstract || goal->isElementar)
return goal;
else
logAi->debug("Considering: %s", goal->name());
}
throw cannotFulfillGoalException("Too many subgoals, don't know what to do");
}
void VCAI::performTypicalActions()
{
for(auto h : getUnblockedHeroes())
{
if(!h) //hero might be lost. getUnblockedHeroes() called once on start of turn
continue;
logAi->debug("Hero %s started wandering, MP=%d", h->getNameTranslated(), h->movementPointsRemaining());
makePossibleUpgrades(*h);
pickBestArtifacts(*h);
try
{
wander(h);
}
catch(std::exception & e)
{
logAi->debug("Cannot use this hero anymore, received exception: %s", e.what());
continue;
}
}
}
void VCAI::buildArmyIn(const CGTownInstance * t)
{
makePossibleUpgrades(t->visitingHero);
makePossibleUpgrades(t);
recruitCreatures(t, t->getUpperArmy());
moveCreaturesToHero(t);
}
void VCAI::checkHeroArmy(HeroPtr h)
{
auto it = lockedHeroes.find(h);
if(it != lockedHeroes.end())
{
if(it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
}
}
void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
{
logAi->debug("Trying to recruit a hero in %s at %s", t->getNameTranslated(), t->visitablePos().toString());
auto heroes = cb->getAvailableHeroes(t);
if(heroes.size())
{
auto hero = heroes[0];
if(heroes.size() >= 2) //makes sense to recruit two heroes with starting amries in first week
{
if(heroes[1]->getTotalStrength() > hero->getTotalStrength())
hero = heroes[1];
}
cb->recruitHero(t, hero);
throw goalFulfilledException(sptr(Goals::RecruitHero().settown(t)));
}
else if(throwing)
{
throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
}
}
void VCAI::finish()
{
//we want to lock to avoid multiple threads from calling makingTurn->join() at same time
boost::lock_guard<boost::mutex> multipleCleanupGuard(turnInterruptionMutex);
if(makingTurn)
{
makingTurn->interrupt();
makingTurn->join();
makingTurn.reset();
}
}
void VCAI::requestActionASAP(std::function<void()> whatToDo)
{
boost::thread newThread([this, whatToDo]()
{
setThreadName("VCAI::requestActionASAP::whatToDo");
SET_GLOBAL_STATE(this);
boost::shared_lock gsLock(CGameState::mutex);
whatToDo();
});
newThread.detach();
}
void VCAI::lostHero(HeroPtr h)
{
logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name);
vstd::erase_if_present(lockedHeroes, h);
for(auto obj : reservedHeroesMap[h])
{
vstd::erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
}
vstd::erase_if_present(reservedHeroesMap, h);
vstd::erase_if_present(visitedHeroes, h);
for (auto heroVec : visitedHeroes)
{
vstd::erase_if_present(heroVec.second, h);
}
//remove goals with removed hero assigned from main loop
vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
{
if(x.first->hero == h)
return true;
else
return false;
});
auto removedHeroGoalPredicate = [&](const Goals::TSubgoal & x) ->bool
{
if(x->hero == h)
return true;
else
return false;
};
vstd::erase_if(basicGoals, removedHeroGoalPredicate);
vstd::erase_if(goalsToAdd, removedHeroGoalPredicate);
vstd::erase_if(goalsToRemove, removedHeroGoalPredicate);
for(auto goal : ultimateGoalsFromBasic)
vstd::erase_if(goal.second, removedHeroGoalPredicate);
}
void VCAI::answerQuery(QueryID queryID, int selection)
{
logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
if(queryID != QueryID(-1))
{
cb->selectionMade(selection, queryID);
}
else
{
logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
//do nothing
}
}
void VCAI::requestSent(const CPackForServer * pack, int requestID)
{
//BNLOG("I have sent request of type %s", typeid(*pack).name());
if(auto reply = dynamic_cast<const QueryReply *>(pack))
{
status.attemptedAnsweringQuery(reply->qid, requestID);
}
}
std::string VCAI::getBattleAIName() const
{
if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
return settings["server"]["enemyAI"].String();
else
return "BattleAI";
}
void VCAI::validateObject(const CGObjectInstance * obj)
{
validateObject(obj->id);
}
void VCAI::validateObject(ObjectIdRef obj)
{
auto matchesId = [&](const CGObjectInstance * hlpObj) -> bool
{
return hlpObj->id == obj.id;
};
if(!obj)
{
vstd::erase_if(visitableObjs, matchesId);
for(auto & p : reservedHeroesMap)
vstd::erase_if(p.second, matchesId);
vstd::erase_if(reservedObjs, matchesId);
}
}
AIStatus::AIStatus()
{
battle = NO_BATTLE;
havingTurn = false;
ongoingHeroMovement = false;
ongoingChannelProbing = false;
}
AIStatus::~AIStatus()
{
}
void AIStatus::setBattle(BattleState BS)
{
boost::unique_lock<boost::mutex> lock(mx);
LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
battle = BS;
cv.notify_all();
}
BattleState AIStatus::getBattle()
{
boost::unique_lock<boost::mutex> lock(mx);
return battle;
}
void AIStatus::addQuery(QueryID ID, std::string description)
{
if(ID == QueryID(-1))
{
logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
return;
}
assert(ID.getNum() >= 0);
boost::unique_lock<boost::mutex> lock(mx);
assert(!vstd::contains(remainingQueries, ID));
remainingQueries[ID] = description;
cv.notify_all();
logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
}
void AIStatus::removeQuery(QueryID ID)
{
boost::unique_lock<boost::mutex> lock(mx);
assert(vstd::contains(remainingQueries, ID));
std::string description = remainingQueries[ID];
remainingQueries.erase(ID);
cv.notify_all();
logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
}
int AIStatus::getQueriesCount()
{
boost::unique_lock<boost::mutex> lock(mx);
return static_cast<int>(remainingQueries.size());
}
void AIStatus::startedTurn()
{
boost::unique_lock<boost::mutex> lock(mx);
havingTurn = true;
cv.notify_all();
}
void AIStatus::madeTurn()
{
boost::unique_lock<boost::mutex> lock(mx);
havingTurn = false;
cv.notify_all();
}
void AIStatus::waitTillFree()
{
boost::unique_lock<boost::mutex> lock(mx);
while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
cv.wait_for(lock, boost::chrono::milliseconds(100));
}
bool AIStatus::haveTurn()
{
boost::unique_lock<boost::mutex> lock(mx);
return havingTurn;
}
void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
{
boost::unique_lock<boost::mutex> lock(mx);
assert(vstd::contains(remainingQueries, queryID));
std::string description = remainingQueries[queryID];
logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
requestToQueryID[answerRequestID] = queryID;
}
void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
{
QueryID query;
{
boost::unique_lock<boost::mutex> lock(mx);
assert(vstd::contains(requestToQueryID, answerRequestID));
query = requestToQueryID[answerRequestID];
assert(vstd::contains(remainingQueries, query));
requestToQueryID.erase(answerRequestID);
}
if(result)
{
removeQuery(query);
}
else
{
logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
//TODO safely retry
}
}
void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
{
boost::unique_lock<boost::mutex> lock(mx);
if(started)
{
objectsBeingVisited.push_back(obj);
}
else
{
// There can be more than one object visited at the time (eg. hero visits Subterranean Gate
// causing visit to hero on the other side.
// However, we are guaranteed that start/end visit notification maintain stack order.
assert(!objectsBeingVisited.empty());
objectsBeingVisited.pop_back();
}
cv.notify_all();
}
void AIStatus::setMove(bool ongoing)
{
boost::unique_lock<boost::mutex> lock(mx);
ongoingHeroMovement = ongoing;
cv.notify_all();
}
void AIStatus::setChannelProbing(bool ongoing)
{
boost::unique_lock<boost::mutex> lock(mx);
ongoingChannelProbing = ongoing;
cv.notify_all();
}
bool AIStatus::channelProbing()
{
return ongoingChannelProbing;
}
bool isWeeklyRevisitable(const CGObjectInstance * obj)
{
//TODO: allow polling of remaining creatures in dwelling
if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
return rewardable->configuration.getResetDuration() == 7;
if(dynamic_cast<const CGDwelling *>(obj))
return true;
switch(obj->ID)
{
case Obj::STABLES:
case Obj::MAGIC_WELL:
case Obj::HILL_FORT:
return true;
case Obj::BORDER_GATE:
case Obj::BORDERGUARD:
return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
}
return false;
}
bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
{
switch(obj->ID)
{
case Obj::TOWN:
case Obj::HERO: //never visit our heroes at random
return obj->tempOwner != h->tempOwner; //do not visit our towns at random
case Obj::BORDER_GATE:
{
for(auto q : ai->myCb->getMyQuests())
{
if(q.obj == obj)
{
return false; // do not visit guards or gates when wandering
}
}
return true; //we don't have this quest yet
}
case Obj::BORDERGUARD: //open borderguard if possible
return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
case Obj::SEER_HUT:
case Obj::QUEST_GUARD:
{
for(auto q : ai->myCb->getMyQuests())
{
if(q.obj == obj)
{
if(q.quest->checkQuest(h.h))
return true; //we completed the quest
else
return false; //we can't complete this quest
}
}
return true; //we don't have this quest yet
}
case Obj::CREATURE_GENERATOR1:
{
if(obj->tempOwner != h->tempOwner)
return true; //flag just in case
bool canRecruitCreatures = false;
const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
for(auto level : d->creatures)
{
for(auto c : level.second)
{
if(h->getSlotFor(CreatureID(c)) != SlotID())
canRecruitCreatures = true;
}
}
return canRecruitCreatures;
}
case Obj::HILL_FORT:
{
for(auto slot : h->Slots())
{
if(slot.second->getType()->hasUpgrades())
return true; //TODO: check price?
}
return false;
}
case Obj::MONOLITH_ONE_WAY_ENTRANCE:
case Obj::MONOLITH_ONE_WAY_EXIT:
case Obj::MONOLITH_TWO_WAY:
case Obj::WHIRLPOOL:
return false;
case Obj::SCHOOL_OF_MAGIC:
case Obj::SCHOOL_OF_WAR:
{
if (ai->ah->freeGold() < 1000)
return false;
break;
}
case Obj::LIBRARY_OF_ENLIGHTENMENT:
if(h->level < 12)
return false;
break;
case Obj::TREE_OF_KNOWLEDGE:
{
TResources myRes = ai->ah->freeResources();
if(myRes[EGameResID::GOLD] < 2000 || myRes[EGameResID::GEMS] < 10)
return false;
break;
}
case Obj::MAGIC_WELL:
return h->mana < h->manaLimit();
case Obj::PRISON:
return ai->myCb->getHeroesInfo().size() < cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP);
case Obj::TAVERN:
{
//TODO: make AI actually recruit heroes
//TODO: only on request
if(ai->myCb->getHeroesInfo().size() >= cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
return false;
else if(ai->ah->freeGold() < GameConstants::HERO_GOLD_COST)
return false;
break;
}
case Obj::BOAT:
return false;
//Boats are handled by pathfinder
case Obj::EYE_OF_MAGI:
return false; //this object is useless to visit, but could be visited indefinitely
}
if(obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
return false;
return true;
}
std::optional<BattleAction> VCAI::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
{
return std::nullopt;
}
|