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
|
/*
* CRmgTemplateZone.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 "CRmgTemplateZone.h"
#include "../mapping/CMapEditManager.h"
#include "../mapping/CMap.h"
#include "../VCMI_Lib.h"
#include "../CTownHandler.h"
#include "../CCreatureHandler.h"
#include "../spells/CSpellHandler.h" //for choosing random spells
#include "../mapObjects/CommonConstructors.h"
#include "../mapObjects/MapObjects.h" //needed to resolve templates for CommonConstructors.h
#include "../mapObjects/CGPandoraBox.h"
#include "../mapObjects/CRewardableObject.h"
class CMap;
class CMapEditManager;
//class CGObjectInstance;
CRmgTemplateZone::CTownInfo::CTownInfo() : townCount(0), castleCount(0), townDensity(0), castleDensity(0)
{
}
void CRmgTemplateZone::addRoadNode(const int3& node)
{
roadNodes.insert(node);
}
int CRmgTemplateZone::CTownInfo::getTownCount() const
{
return townCount;
}
void CRmgTemplateZone::CTownInfo::setTownCount(int value)
{
if(value < 0)
throw rmgException("Negative value for town count not allowed.");
townCount = value;
}
int CRmgTemplateZone::CTownInfo::getCastleCount() const
{
return castleCount;
}
void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
{
if(value < 0)
throw rmgException("Negative value for castle count not allowed.");
castleCount = value;
}
int CRmgTemplateZone::CTownInfo::getTownDensity() const
{
return townDensity;
}
void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
{
if(value < 0)
throw rmgException("Negative value for town density not allowed.");
townDensity = value;
}
int CRmgTemplateZone::CTownInfo::getCastleDensity() const
{
return castleDensity;
}
void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
{
if(value < 0)
throw rmgException("Negative value for castle density not allowed.");
castleDensity = value;
}
CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG),roadType(ERoadType::NO_ROAD)
{
occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
}
float CTileInfo::getNearestObjectDistance() const
{
return nearestObjectDistance;
}
void CTileInfo::setNearestObjectDistance(float value)
{
nearestObjectDistance = std::max<float>(0, value); //never negative (or unitialized)
}
bool CTileInfo::shouldBeBlocked() const
{
return occupied == ETileType::BLOCKED;
}
bool CTileInfo::isBlocked() const
{
return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
}
bool CTileInfo::isPossible() const
{
return occupied == ETileType::POSSIBLE;
}
bool CTileInfo::isFree() const
{
return occupied == ETileType::FREE;
}
bool CTileInfo::isRoad() const
{
return roadType != ERoadType::NO_ROAD;
}
bool CTileInfo::isUsed() const
{
return occupied == ETileType::USED;
}
void CTileInfo::setOccupied(ETileType::ETileType value)
{
occupied = value;
}
ETileType::ETileType CTileInfo::getTileType() const
{
return occupied;
}
ETerrainType CTileInfo::getTerrainType() const
{
return terrain;
}
void CTileInfo::setTerrainType(ETerrainType value)
{
terrain = value;
}
void CTileInfo::setRoadType(ERoadType::ERoadType value)
{
roadType = value;
// setOccupied(ETileType::FREE);
}
CRmgTemplateZone::CRmgTemplateZone() :
id(0),
type(ETemplateZoneType::PLAYER_START),
owner(boost::none),
size(1),
townsAreSameType(false),
matchTerrainToTown(true),
townType(ETownType::NEUTRAL),
terrainType (ETerrainType::GRASS),
zoneMonsterStrength(EMonsterStrength::ZONE_NORMAL),
minGuardedValue(0),
questArtZone(nullptr)
{
terrainTypes = getDefaultTerrainTypes();
}
TRmgTemplateZoneId CRmgTemplateZone::getId() const
{
return id;
}
void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
{
if(value <= 0)
throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
id = value;
}
ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
{
return type;
}
void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
{
type = value;
}
int CRmgTemplateZone::getSize() const
{
return size;
}
void CRmgTemplateZone::setSize(int value)
{
if(value <= 0)
throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
size = value;
}
boost::optional<int> CRmgTemplateZone::getOwner() const
{
return owner;
}
void CRmgTemplateZone::setOwner(boost::optional<int> value)
{
if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
owner = value;
}
const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
{
return playerTowns;
}
void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
{
playerTowns = value;
}
const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
{
return neutralTowns;
}
void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
{
neutralTowns = value;
}
bool CRmgTemplateZone::getTownsAreSameType() const
{
return townsAreSameType;
}
void CRmgTemplateZone::setTownsAreSameType(bool value)
{
townsAreSameType = value;
}
const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
{
return townTypes;
}
void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
{
townTypes = value;
}
void CRmgTemplateZone::setMonsterTypes(const std::set<TFaction> & value)
{
monsterTypes = value;
}
std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
{
std::set<TFaction> defaultTowns;
auto towns = VLC->townh->getDefaultAllowed();
for(int i = 0; i < towns.size(); ++i)
{
if(towns[i]) defaultTowns.insert(i);
}
return defaultTowns;
}
bool CRmgTemplateZone::getMatchTerrainToTown() const
{
return matchTerrainToTown;
}
void CRmgTemplateZone::setMatchTerrainToTown(bool value)
{
matchTerrainToTown = value;
}
const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
{
return terrainTypes;
}
void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
{
assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
terrainTypes = value;
}
std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
{
std::set<ETerrainType> terTypes;
static const ETerrainType::EETerrainType allowedTerTypes[] = {ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA};
for (auto & allowedTerType : allowedTerTypes)
terTypes.insert(allowedTerType);
return terTypes;
}
void CRmgTemplateZone::setMinesAmount (TResource res, ui16 amount)
{
mines[res] = amount;
}
std::map<TResource, ui16> CRmgTemplateZone::getMinesInfo() const
{
return mines;
}
void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
{
connections.push_back (otherZone);
}
void CRmgTemplateZone::setQuestArtZone(CRmgTemplateZone * otherZone)
{
questArtZone = otherZone;
}
std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
{
return connections;
}
void CRmgTemplateZone::setMonsterStrength (EMonsterStrength::EMonsterStrength val)
{
assert (vstd::iswithin(val, EMonsterStrength::ZONE_WEAK, EMonsterStrength::ZONE_STRONG));
zoneMonsterStrength = val;
}
void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
{
treasureInfo.push_back(info);
}
std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
{
return treasureInfo;
}
std::set<int3>* CRmgTemplateZone::getFreePaths()
{
return &freePaths;
}
float3 CRmgTemplateZone::getCenter() const
{
return center;
}
void CRmgTemplateZone::setCenter(const float3 &f)
{
//limit boundaries to (0,1) square
//alternate solution - wrap zone around unitary square. If it doesn't fit on one side, will come out on the opposite side
center = f;
center.x = std::fmod(center.x, 1);
center.y = std::fmod(center.y, 1);
if (center.x < 0) //fmod seems to work only for positive numbers? we want to stay positive
center.x = 1 - std::abs(center.x);
if (center.y < 0)
center.y = 1 - std::abs(center.y);
}
bool CRmgTemplateZone::pointIsIn(int x, int y)
{
return true;
}
int3 CRmgTemplateZone::getPos() const
{
return pos;
}
void CRmgTemplateZone::setPos(const int3 &Pos)
{
pos = Pos;
}
void CRmgTemplateZone::addTile (const int3 &pos)
{
tileinfo.insert(pos);
}
std::set<int3> CRmgTemplateZone::getTileInfo () const
{
return tileinfo;
}
std::set<int3> CRmgTemplateZone::getPossibleTiles() const
{
return possibleTiles;
}
void CRmgTemplateZone::discardDistantTiles (CMapGenerator* gen, float distance)
{
//TODO: mark tiles beyond zone as unavailable, but allow to connect with adjacent zones
//for (auto tile : tileinfo)
//{
// if (tile.dist2d(this->pos) > distance)
// {
// gen->setOccupied(tile, ETileType::USED);
// //gen->setOccupied(tile, ETileType::BLOCKED); //fixme: crash at rendering?
// }
//}
vstd::erase_if (tileinfo, [distance, this](const int3 &tile) -> bool
{
return tile.dist2d(this->pos) > distance;
});
}
void CRmgTemplateZone::clearTiles()
{
tileinfo.clear();
}
void CRmgTemplateZone::initFreeTiles (CMapGenerator* gen)
{
vstd::copy_if (tileinfo, vstd::set_inserter(possibleTiles), [gen](const int3 &tile) -> bool
{
return gen->isPossible(tile);
});
if (freePaths.empty())
{
gen->setOccupied(pos, ETileType::FREE);
freePaths.insert(pos); //zone must have at least one free tile where other paths go - for instance in the center
}
}
void CRmgTemplateZone::createBorder(CMapGenerator* gen)
{
for (auto tile : tileinfo)
{
bool edge = false;
gen->foreach_neighbour(tile, [this, gen, &edge](int3 &pos)
{
if (edge)
return; //optimization - do it only once
if (gen->getZoneID(pos) != id) //optimization - better than set search
{
//we are edge if at least one tile does not belong to zone
//mark all nearby tiles blocked and we're done
gen->foreach_neighbour (pos, [this, gen](int3 &nearbyPos)
{
if (gen->isPossible(nearbyPos))
gen->setOccupied(nearbyPos, ETileType::BLOCKED);
});
edge = true;
}
});
}
}
void CRmgTemplateZone::fractalize(CMapGenerator* gen)
{
for (auto tile : tileinfo)
{
if (gen->isFree(tile))
freePaths.insert(tile);
}
std::vector<int3> clearedTiles (freePaths.begin(), freePaths.end());
std::set<int3> possibleTiles;
std::set<int3> tilesToIgnore; //will be erased in this iteration
//the more treasure density, the greater distance between paths. Scaling is experimental.
int totalDensity = 0;
for (auto ti : treasureInfo)
totalDensity += ti.density;
const float minDistance = 10 * 10; //squared
for (auto tile : tileinfo)
{
if (gen->isFree(tile))
clearedTiles.push_back(tile);
else if (gen->isPossible(tile))
possibleTiles.insert(tile);
}
assert (clearedTiles.size()); //this should come from zone connections
std::vector<int3> nodes; //connect them with a grid
if (type != ETemplateZoneType::JUNCTION)
{
//junction is not fractalized, has only one straight path
//everything else remains blocked
while (possibleTiles.size())
{
//link tiles in random order
std::vector<int3> tilesToMakePath(possibleTiles.begin(), possibleTiles.end());
RandomGeneratorUtil::randomShuffle(tilesToMakePath, gen->rand);
int3 nodeFound(-1, -1, -1);
for (auto tileToMakePath : tilesToMakePath)
{
//find closest free tile
float currentDistance = 1e10;
int3 closestTile(-1, -1, -1);
for (auto clearTile : clearedTiles)
{
float distance = tileToMakePath.dist2dSQ(clearTile);
if (distance < currentDistance)
{
currentDistance = distance;
closestTile = clearTile;
}
if (currentDistance <= minDistance)
{
//this tile is close enough. Forget about it and check next one
tilesToIgnore.insert(tileToMakePath);
break;
}
}
//if tiles is not close enough, make path to it
if (currentDistance > minDistance)
{
nodeFound = tileToMakePath;
nodes.push_back(nodeFound);
clearedTiles.push_back(nodeFound); //from now on nearby tiles will be considered handled
break; //next iteration - use already cleared tiles
}
}
for (auto tileToClear : tilesToIgnore)
{
//these tiles are already connected, ignore them
vstd::erase_if_present(possibleTiles, tileToClear);
}
if (!nodeFound.valid()) //nothing else can be done (?)
break;
tilesToIgnore.clear();
}
}
for (auto node : nodes)
{
boost::sort(nodes, [&node](const int3& ourNode, const int3& otherNode) -> bool
{
return node.dist2dSQ(ourNode) < node.dist2dSQ(otherNode);
}
);
std::vector <int3> nearbyNodes;
if (nodes.size() >= 2)
{
nearbyNodes.push_back(nodes[1]); //node[0] is our node we want to connect
}
if (nodes.size() >= 3)
{
nearbyNodes.push_back(nodes[2]);
}
//connect with all the paths
crunchPath(gen, node, findClosestTile(freePaths, node), true, &freePaths);
//connect with nearby nodes
for (auto nearbyNode : nearbyNodes)
{
crunchPath(gen, node, nearbyNode, true, &freePaths);
}
}
for (auto node : nodes)
gen->setOccupied(node, ETileType::FREE); //make sure they are clear
//now block most distant tiles away from passages
float blockDistance = minDistance * 0.25f;
for (auto tile : tileinfo)
{
if (!gen->isPossible(tile))
continue;
bool closeTileFound = false;
for (auto clearTile : freePaths)
{
float distance = tile.dist2dSQ(clearTile);
if (distance < blockDistance)
{
closeTileFound = true;
break;
}
}
if (!closeTileFound) //this tile is far enough from passages
gen->setOccupied(tile, ETileType::BLOCKED);
}
#define PRINT_FRACTALIZED_MAP false
if (PRINT_FRACTALIZED_MAP) //enable to debug
{
std::ofstream out(boost::to_string(boost::format("zone %d") % id));
int levels = gen->map->twoLevel ? 2 : 1;
int width = gen->map->width;
int height = gen->map->height;
for (int k = 0; k < levels; k++)
{
for(int j=0; j<height; j++)
{
for (int i=0; i<width; i++)
{
char t = '?';
switch (gen->getTile(int3(i, j, k)).getTileType())
{
case ETileType::FREE:
t = ' '; break;
case ETileType::BLOCKED:
t = '#'; break;
case ETileType::POSSIBLE:
t = '-'; break;
case ETileType::USED:
t = 'O'; break;
}
out << t;
}
out << std::endl;
}
out << std::endl;
}
out << std::endl;
}
//logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
}
void CRmgTemplateZone::connectLater(CMapGenerator* gen)
{
for (const int3 node : tilesToConnectLater)
{
if (!connectWithCenter(gen, node, true))
logGlobal->errorStream() << boost::format("Failed to connect node %s with center of the zone") % node;
}
}
bool CRmgTemplateZone::crunchPath(CMapGenerator* gen, const int3 &src, const int3 &dst, bool onlyStraight, std::set<int3>* clearedTiles)
{
/*
make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
do not leave zone border
*/
bool result = false;
bool end = false;
int3 currentPos = src;
float distance = currentPos.dist2dSQ (dst);
while (!end)
{
if (currentPos == dst)
{
result = true;
break;
}
auto lastDistance = distance;
auto processNeighbours = [this, gen, ¤tPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
{
if (!result) //not sure if lambda is worth it...
{
if (pos == dst)
{
result = true;
end = true;
}
if (pos.dist2dSQ (dst) < distance)
{
if (!gen->isBlocked(pos))
{
if (gen->getZoneID(pos) == id)
{
if (gen->isPossible(pos))
{
gen->setOccupied (pos, ETileType::FREE);
if (clearedTiles)
clearedTiles->insert(pos);
currentPos = pos;
distance = currentPos.dist2dSQ (dst);
}
else if (gen->isFree(pos))
{
end = true;
result = true;
}
}
}
}
}
};
if (onlyStraight)
gen->foreachDirectNeighbour (currentPos, processNeighbours);
else
gen->foreach_neighbour (currentPos,processNeighbours);
int3 anotherPos(-1, -1, -1);
if (!(result || distance < lastDistance)) //we do not advance, use more advanced pathfinding algorithm?
{
//try any nearby tiles, even if its not closer than current
float lastDistance = 2 * distance; //start with significantly larger value
auto processNeighbours2 = [this, gen, ¤tPos, dst, &lastDistance, &anotherPos, &end, clearedTiles](int3 &pos)
{
if (currentPos.dist2dSQ(dst) < lastDistance) //try closest tiles from all surrounding unused tiles
{
if (gen->getZoneID(pos) == id)
{
if (gen->isPossible(pos))
{
if (clearedTiles)
clearedTiles->insert(pos);
anotherPos = pos;
lastDistance = currentPos.dist2dSQ(dst);
}
}
}
};
if (onlyStraight)
gen->foreachDirectNeighbour(currentPos, processNeighbours2);
else
gen->foreach_neighbour(currentPos, processNeighbours2);
if (anotherPos.valid())
{
if (clearedTiles)
clearedTiles->insert(anotherPos);
gen->setOccupied(anotherPos, ETileType::FREE);
currentPos = anotherPos;
}
}
if (!(result || distance < lastDistance || anotherPos.valid()))
{
//FIXME: seemingly this condition is messed up, tells nothing
//logGlobal->warnStream() << boost::format("No tile closer than %s found on path from %s to %s") % currentPos %src %dst;
break;
}
}
return result;
}
bool CRmgTemplateZone::createRoad(CMapGenerator* gen, const int3& src, const int3& dst)
{
//A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm
std::set<int3> closed; // The set of nodes already evaluated.
std::set<int3> open{src}; // The set of tentative nodes to be evaluated, initially containing the start node
std::map<int3, int3> cameFrom; // The map of navigated nodes.
std::map<int3, float> distances;
//int3 currentNode = src;
gen->setRoad (src, ERoadType::NO_ROAD); //just in case zone guard already has road under it. Road under nodes will be added at very end
cameFrom[src] = int3(-1, -1, -1); //first node points to finish condition
distances[src] = 0;
// Cost from start along best known path.
// Estimated total cost from start to goal through y.
while (open.size())
{
int3 currentNode = *boost::min_element(open, [&distances](const int3 &pos1, const int3 &pos2) -> bool
{
return distances[pos1] < distances[pos2];
});
vstd::erase_if_present (open, currentNode);
closed.insert (currentNode);
if (currentNode == dst || gen->isRoad(currentNode))
{
// The goal node was reached. Trace the path using
// the saved parent information and return path
int3 backTracking = currentNode;
while (cameFrom[backTracking].valid())
{
// add node to path
roads.insert (backTracking);
gen->setRoad (backTracking, ERoadType::COBBLESTONE_ROAD);
//logGlobal->traceStream() << boost::format("Setting road at tile %s") % backTracking;
// do the same for the predecessor
backTracking = cameFrom[backTracking];
}
return true;
}
else
{
bool directNeighbourFound = false;
float movementCost = 1;
auto foo = [gen, this, &open, &closed, &cameFrom, ¤tNode, &distances, &dst, &directNeighbourFound, movementCost](int3& pos) -> void
{
float distance = distances[currentNode] + movementCost;
int bestDistanceSoFar = 1e6; //FIXME: boost::limits
auto it = distances.find(pos);
if (it != distances.end())
bestDistanceSoFar = it->second;
if (distance < bestDistanceSoFar || !vstd::contains(closed, pos))
{
auto obj = gen->map->getTile(pos).topVisitableObj();
//if (gen->map->checkForVisitableDir(currentNode, &gen->map->getTile(pos), pos)) //TODO: why it has no effect?
if (gen->isFree(pos) || pos == dst || (obj && obj->ID == Obj::MONSTER))
{
if (gen->getZoneID(pos) == id || pos == dst) //otherwise guard position may appear already connected to other zone.
{
cameFrom[pos] = currentNode;
open.insert(pos);
distances[pos] = distance;
directNeighbourFound = true;
//logGlobal->traceStream() << boost::format("Found connection between node %s and %s, current distance %d") % currentNode % pos % distance;
}
}
}
};
gen->foreachDirectNeighbour (currentNode, foo); // roads cannot be rendered correctly for diagonal directions
if (!directNeighbourFound)
{
movementCost = 2.1f; //moving diagonally is penalized over moving two tiles straight
gen->foreach_neighbour(currentNode, foo);
}
}
}
logGlobal->warnStream() << boost::format("Failed to create road from %s to %s") % src %dst;
return false;
}
bool CRmgTemplateZone::connectPath(CMapGenerator* gen, const int3& src, bool onlyStraight)
///connect current tile to any other free tile within zone
{
//A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm
std::set<int3> closed; // The set of nodes already evaluated.
std::set<int3> open{ src }; // The set of tentative nodes to be evaluated, initially containing the start node
std::map<int3, int3> cameFrom; // The map of navigated nodes.
std::map<int3, float> distances;
//int3 currentNode = src;
cameFrom[src] = int3(-1, -1, -1); //first node points to finish condition
distances[src] = 0;
// Cost from start along best known path.
// Estimated total cost from start to goal through y.
while (open.size())
{
int3 currentNode = *boost::min_element(open, [&distances](const int3 &pos1, const int3 &pos2) -> bool
{
return distances[pos1] < distances[pos2];
});
vstd::erase_if_present(open, currentNode);
closed.insert(currentNode);
if (gen->isFree(currentNode)) //we reached free paths, stop
{
// Trace the path using the saved parent information and return path
int3 backTracking = currentNode;
while (cameFrom[backTracking].valid())
{
gen->setOccupied(backTracking, ETileType::FREE);
backTracking = cameFrom[backTracking];
}
return true;
}
else
{
auto foo = [gen, this, &open, &closed, &cameFrom, ¤tNode, &distances](int3& pos) -> void
{
if (gen->isBlocked(pos)) //no paths through blocked or occupied tiles
return;
int distance = distances[currentNode] + 1;
int bestDistanceSoFar = 1e6; //FIXME: boost::limits
auto it = distances.find(pos);
if (it != distances.end())
bestDistanceSoFar = it->second;
if (distance < bestDistanceSoFar || !vstd::contains(closed, pos))
{
//auto obj = gen->map->getTile(pos).topVisitableObj();
if (gen->getZoneID(pos) == id)
{
cameFrom[pos] = currentNode;
open.insert(pos);
distances[pos] = distance;
}
}
};
if (onlyStraight)
gen->foreachDirectNeighbour(currentNode, foo);
else
gen->foreach_neighbour(currentNode, foo);
}
}
for (auto tile : closed) //these tiles are sealed off and can't be connected anymore
{
//TODO: refactor, unify?
gen->setOccupied (tile, ETileType::BLOCKED);
vstd::erase_if_present(possibleTiles, tile);
}
return false;
}
bool CRmgTemplateZone::connectWithCenter(CMapGenerator* gen, const int3& src, bool onlyStraight)
///connect current tile to any other free tile within zone
{
//A* algorithm taken from Wiki http://en.wikipedia.org/wiki/A*_search_algorithm
std::set<int3> closed; // The set of nodes already evaluated.
std::set<int3> open{ src }; // The set of tentative nodes to be evaluated, initially containing the start node
std::map<int3, int3> cameFrom; // The map of navigated nodes.
std::map<int3, float> distances;
//int3 currentNode = src;
cameFrom[src] = int3(-1, -1, -1); //first node points to finish condition
distances[src] = 0;
// Cost from start along best known path.
// Estimated total cost from start to goal through y.
while (open.size())
{
int3 currentNode = *boost::min_element(open, [&distances](const int3 &pos1, const int3 &pos2) -> bool
{
return distances[pos1] < distances[pos2];
});
vstd::erase_if_present(open, currentNode);
closed.insert(currentNode);
if (currentNode == pos) //we reached center of the zone, stop
{
// Trace the path using the saved parent information and return path
int3 backTracking = currentNode;
while (cameFrom[backTracking].valid())
{
gen->setOccupied(backTracking, ETileType::FREE);
backTracking = cameFrom[backTracking];
}
return true;
}
else
{
auto foo = [gen, this, &open, &closed, &cameFrom, ¤tNode, &distances](int3& pos) -> void
{
float movementCost = 0;
if (gen->isFree(pos))
movementCost = 1;
else if (gen->isPossible(pos))
movementCost = 2;
else
return;
float distance = distances[currentNode] + movementCost; //we prefer to use already free paths
int bestDistanceSoFar = 1e6; //FIXME: boost::limits
auto it = distances.find(pos);
if (it != distances.end())
bestDistanceSoFar = it->second;
if (distance < bestDistanceSoFar || !vstd::contains(closed, pos))
{
//auto obj = gen->map->getTile(pos).topVisitableObj();
if (gen->getZoneID(pos) == id)
{
cameFrom[pos] = currentNode;
open.insert(pos);
distances[pos] = distance;
}
}
};
if (onlyStraight)
gen->foreachDirectNeighbour(currentNode, foo);
else
gen->foreach_neighbour(currentNode, foo);
}
}
return false;
}
void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
{
requiredObjects.push_back(std::make_pair(obj, strength));
}
void CRmgTemplateZone::addCloseObject(CGObjectInstance * obj, si32 strength)
{
closeObjects.push_back(std::make_pair(obj, strength));
}
void CRmgTemplateZone::addToConnectLater(const int3& src)
{
tilesToConnectLater.insert(src);
}
bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength, bool clearSurroundingTiles, bool zoneGuard)
{
//precalculate actual (randomized) monster strength based on this post
//http://forum.vcmi.eu/viewtopic.php?p=12426#12426
int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
int monsterStrength = (zoneGuard ? 0 : zoneMonsterStrength) + mapMonsterStrength - 1; //array index from 0 to 4
static const int value1[] = {2500, 1500, 1000, 500, 0};
static const int value2[] = {7500, 7500, 7500, 5000, 5000};
static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
strength = strength1 + strength2;
if (strength < 2000)
return false; //no guard at all
CreatureID creId = CreatureID::NONE;
int amount = 0;
std::vector<CreatureID> possibleCreatures;
for (auto cre : VLC->creh->creatures)
{
if (cre->special)
continue;
if (!vstd::contains(monsterTypes, cre->faction))
continue;
if ((cre->AIValue * (cre->ammMin + cre->ammMax) / 2 < strength) && (strength < cre->AIValue * 100)) //at least one full monster. size between average size of given stack and 100
{
possibleCreatures.push_back(cre->idNumber);
}
}
if (possibleCreatures.size())
{
creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
amount = strength / VLC->creh->creatures[creId]->AIValue;
if (amount >= 4)
amount *= gen->rand.nextDouble(0.75, 1.25);
}
else //just pick any available creature
{
creId = CreatureID(132); //Azure Dragon
amount = strength / VLC->creh->creatures[creId]->AIValue;
}
auto guardFactory = VLC->objtypeh->getHandlerFor(Obj::MONSTER, creId);
auto guard = (CGCreature *) guardFactory->create(ObjectTemplate());
guard->character = CGCreature::HOSTILE;
auto hlp = new CStackInstance(creId, amount);
//will be set during initialization
guard->putStack(SlotID(0), hlp);
//logGlobal->traceStream() << boost::format ("Adding stack of %d %s. Map monster strenght %d, zone monster strength %d, base monster value %d")
// % amount % VLC->creh->creatures[creId]->namePl % mapMonsterStrength % zoneMonsterStrength % strength;
placeObject(gen, guard, pos);
if (clearSurroundingTiles)
{
//do not spawn anything near monster
gen->foreach_neighbour (pos, [gen](int3 pos)
{
if (gen->isPossible(pos))
gen->setOccupied(pos, ETileType::FREE);
});
}
return true;
}
bool CRmgTemplateZone::createTreasurePile(CMapGenerator* gen, int3 &pos, float minDistance, const CTreasureInfo& treasureInfo)
{
CTreasurePileInfo info;
std::map<int3, CGObjectInstance *> treasures;
std::set<int3> boundary;
int3 guardPos (-1,-1,-1);
info.nextTreasurePos = pos;
int maxValue = treasureInfo.max;
int minValue = treasureInfo.min;
ui32 desiredValue = (gen->rand.nextInt(minValue, maxValue));
int currentValue = 0;
CGObjectInstance * object = nullptr;
while (currentValue <= desiredValue - 100) //no objects with value below 100 are avaiable
{
treasures[info.nextTreasurePos] = nullptr;
for (auto treasurePos : treasures)
{
gen->foreach_neighbour(treasurePos.first, [gen, &boundary](int3 pos)
{
boundary.insert(pos);
});
}
for (auto treasurePos : treasures)
{
//leaving only boundary around objects
vstd::erase_if_present(boundary, treasurePos.first);
}
for (auto tile : boundary)
{
//we can't extend boundary anymore
if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
break;
}
ObjectInfo oi = getRandomObject(gen, info, desiredValue, maxValue, currentValue);
if (!oi.value) //0 value indicates no object
{
vstd::erase_if_present(treasures, info.nextTreasurePos);
break;
}
else
{
object = oi.generateObject();
//remove from possible objects
auto oiptr = std::find(possibleObjects.begin(), possibleObjects.end(), oi);
assert (oiptr != possibleObjects.end());
oiptr->maxPerZone--;
if (!oiptr->maxPerZone)
possibleObjects.erase(oiptr);
//update treasure pile area
int3 visitablePos = info.nextTreasurePos;
if (oi.templ.isVisitableFromTop())
info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
else
info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
for (auto blockedOffset : oi.templ.getBlockedOffsets())
{
int3 blockPos = info.nextTreasurePos + blockedOffset + oi.templ.getVisitableOffset(); //object will be moved to align vistable pos to treasure pos
info.occupiedPositions.insert(blockPos);
info.blockedPositions.insert(blockPos);
}
info.occupiedPositions.insert(visitablePos + oi.templ.getVisitableOffset());
currentValue += oi.value;
treasures[info.nextTreasurePos] = object;
//now find place for next object
int3 placeFound(-1,-1,-1);
//randomize next position from among possible ones
std::vector<int3> boundaryCopy (boundary.begin(), boundary.end());
//RandomGeneratorUtil::randomShuffle(boundaryCopy, gen->rand);
auto chooseTopTile = [](const int3 & lhs, const int3 & rhs) -> bool
{
return lhs.y < rhs.y;
};
boost::sort(boundaryCopy, chooseTopTile); //start from top tiles to allow objects accessible from bottom
for (auto tile : boundaryCopy)
{
if (gen->isPossible(tile)) //we can place new treasure only on possible tile
{
bool here = true;
gen->foreach_neighbour (tile, [gen, &here, minDistance](int3 pos)
{
if (!(gen->isBlocked(pos) || gen->isPossible(pos)) || gen->getNearestObjectDistance(pos) < minDistance)
here = false;
});
if (here)
{
placeFound = tile;
break;
}
}
}
if (placeFound.valid())
info.nextTreasurePos = placeFound;
else
break; //no more place to add any objects
}
}
if (treasures.size())
{
//find object closest to free path, then connect it to the middle of the zone
int3 closestTile = int3(-1,-1,-1);
float minDistance = 1e10;
for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
{
int3 closestFreeTile = findClosestTile(freePaths, visitablePos);
if (closestFreeTile.dist2d(visitablePos) < minDistance)
{
closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map, to not make path up through it
minDistance = closestFreeTile.dist2d(visitablePos);
}
}
for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
{
int3 closestFreeTile = findClosestTile(freePaths, visitablePos);
if (closestFreeTile.dist2d(visitablePos) < minDistance)
{
closestTile = visitablePos;
minDistance = closestFreeTile.dist2d(visitablePos);
}
}
assert (closestTile.valid());
for (auto tile : info.occupiedPositions)
{
if (gen->map->isInTheMap(tile)) //pile boundary may reach map border
gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
}
if (!connectPath (gen, closestTile, false)) //this place is sealed off, need to find new position
{
return false;
}
//update boundary around our objects, including knowledge about objects visitable from bottom
boundary.clear();
for (auto tile : info.visitableFromBottomPositions)
{
gen->foreach_neighbour(tile, [tile, &boundary](int3 pos)
{
if (pos.y >= tile.y) //don't block these objects from above
boundary.insert(pos);
});
}
for (auto tile : info.visitableFromTopPositions)
{
gen->foreach_neighbour(tile, [&boundary](int3 pos)
{
boundary.insert(pos);
});
}
bool isPileGuarded = currentValue >= minGuardedValue;
for (auto tile : boundary) //guard must be standing there
{
if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
{
guardPos = tile;
break;
}
}
if (guardPos.valid())
{
for (auto treasure : treasures)
{
int3 visitableOffset = treasure.second->getVisitableOffset();
if (treasure.second->ID == Obj::SEER_HUT) //FIXME: find generic solution or figure out why Seer Hut doesn't behave correctly
visitableOffset.x += 1;
placeObject(gen, treasure.second, treasure.first + visitableOffset);
}
if (addMonster(gen, guardPos, currentValue, false))
{//block only if the object is guarded
for (auto tile : boundary)
{
if (gen->isPossible(tile))
gen->setOccupied(tile, ETileType::BLOCKED);
}
//do not spawn anything near monster
gen->foreach_neighbour(guardPos, [gen](int3 pos)
{
if (gen->isPossible(pos))
gen->setOccupied(pos, ETileType::FREE);
});
}
else //mo monster in this pile, make some free space (needed?)
{
for (auto tile : boundary)
if (gen->isPossible(tile))
gen->setOccupied(tile, ETileType::FREE);
}
}
else if (isPileGuarded)//we couldn't make a connection to this location, block it
{
for (auto treasure : treasures)
{
if (gen->isPossible(treasure.first))
gen->setOccupied(treasure.first, ETileType::BLOCKED);
delete treasure.second;
}
}
return true;
}
else //we did not place eveyrthing successfully
{
gen->setOccupied(pos, ETileType::BLOCKED); //TODO: refactor stop condition
vstd::erase_if_present(possibleTiles, pos);
return false;
}
}
void CRmgTemplateZone::initTownType (CMapGenerator* gen)
{
//FIXME: handle case that this player is not present -> towns should be set to neutral
int totalTowns = 0;
auto cutPathAroundTown = [gen, this](const CGTownInstance * town)
{
//cut contour around town in case it was placed in a middle of path. TODO: find better solution
for (auto tile : town->getBlockedPos())
{
gen->foreach_neighbour(tile, [gen, &tile](int3& pos)
{
if (gen->isPossible(pos))
{
gen->setOccupied(pos, ETileType::FREE);
}
});
}
};
auto addNewTowns = [&totalTowns, gen, this, &cutPathAroundTown](int count, bool hasFort, PlayerColor player)
{
for (int i = 0; i < count; i++)
{
si32 subType = townType;
if(totalTowns>0)
{
if(!this->townsAreSameType)
{
if (townTypes.size())
subType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
else
subType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
}
}
auto townFactory = VLC->objtypeh->getHandlerFor(Obj::TOWN, subType);
auto town = (CGTownInstance *) townFactory->create(ObjectTemplate());
town->ID = Obj::TOWN;
town->tempOwner = player;
if (hasFort)
town->builtBuildings.insert(BuildingID::FORT);
town->builtBuildings.insert(BuildingID::DEFAULT);
for (auto spell : VLC->spellh->objects) //add all regular spells to town
{
if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
town->possibleSpells.push_back(spell->id);
}
if (totalTowns <= 0)
{
//register MAIN town of zone
gen->registerZone(town->subID);
//first town in zone goes in the middle
placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
cutPathAroundTown(town);
setPos(town->visitablePos() + int3(0, 1, 0)); //new center of zone that paths connect to
}
else
addRequiredObject (town);
totalTowns++;
}
};
if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
{
//set zone types to player faction, generate main town
logGlobal->infoStream() << "Preparing playing zone";
int player_id = *owner - 1;
auto & playerInfo = gen->map->players[player_id];
PlayerColor player(player_id);
if (playerInfo.canAnyonePlay())
{
player = PlayerColor(player_id);
townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
if (townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
randomizeTownType(gen);
}
else //no player - randomize town
{
player = PlayerColor::NEUTRAL;
randomizeTownType(gen);
}
auto townFactory = VLC->objtypeh->getHandlerFor(Obj::TOWN, townType);
CGTownInstance * town = (CGTownInstance *) townFactory->create(ObjectTemplate());
town->tempOwner = player;
town->builtBuildings.insert(BuildingID::FORT);
town->builtBuildings.insert(BuildingID::DEFAULT);
for (auto spell : VLC->spellh->objects) //add all regular spells to town
{
if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
town->possibleSpells.push_back(spell->id);
}
//towns are big objects and should be centered around visitable position
placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
cutPathAroundTown(town);
setPos(town->visitablePos() + int3(0, 1, 0)); //new center of zone that paths connect to
totalTowns++;
//register MAIN town of zone only
gen->registerZone (town->subID);
if (playerInfo.canAnyonePlay()) //configure info for owning player
{
logGlobal->traceStream() << "Fill player info " << player_id;
// Update player info
playerInfo.allowedFactions.clear();
playerInfo.allowedFactions.insert(townType);
playerInfo.hasMainTown = true;
playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
playerInfo.generateHeroAtMainTown = true;
//now create actual towns
addNewTowns(playerTowns.getCastleCount() - 1, true, player);
addNewTowns(playerTowns.getTownCount(), false, player);
}
else
{
addNewTowns(playerTowns.getCastleCount() - 1, true, PlayerColor::NEUTRAL);
addNewTowns(playerTowns.getTownCount(), false, PlayerColor::NEUTRAL);
}
}
else //randomize town types for any other zones as well
{
randomizeTownType(gen);
}
addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
if (!totalTowns) //if there's no town present, get random faction for dwellings and pandoras
{
//25% chance for neutral
if (gen->rand.nextInt(1, 100) <= 25)
{
townType = ETownType::NEUTRAL;
}
else
{
if (townTypes.size())
townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
else if (monsterTypes.size())
townType = *RandomGeneratorUtil::nextItem(monsterTypes, gen->rand); //this happens in Clash of Dragons in treasure zones, where all towns are banned
else //just in any case
randomizeTownType(gen);
}
}
}
void CRmgTemplateZone::randomizeTownType (CMapGenerator* gen)
{
if (townTypes.size())
townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
else
townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed, we still need some
}
void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
{
if (matchTerrainToTown && townType != ETownType::NEUTRAL)
terrainType = VLC->townh->factions[townType]->nativeTerrain;
else
terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
//TODO: allow new types of terrain?
if (pos.z)
{
if (terrainType != ETerrainType::LAVA)
terrainType = ETerrainType::SUBTERRANEAN;
}
else
{
if (terrainType == ETerrainType::SUBTERRANEAN)
terrainType = ETerrainType::DIRT;
}
paintZoneTerrain (gen, terrainType);
}
void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
{
std::vector<int3> tiles(tileinfo.begin(), tileinfo.end());
gen->editManager->getTerrainSelection().setSelection(tiles);
gen->editManager->drawTerrain(terrainType, &gen->rand);
}
bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
{
static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
std::array<TObjectTypeHandler, 7> factory =
{
VLC->objtypeh->getHandlerFor(Obj::MINE, 0),
VLC->objtypeh->getHandlerFor(Obj::MINE, 1),
VLC->objtypeh->getHandlerFor(Obj::MINE, 2),
VLC->objtypeh->getHandlerFor(Obj::MINE, 3),
VLC->objtypeh->getHandlerFor(Obj::MINE, 4),
VLC->objtypeh->getHandlerFor(Obj::MINE, 5),
VLC->objtypeh->getHandlerFor(Obj::MINE, 6)
};
for (const auto & res : woodOre)
{
for (int i = 0; i < mines[res]; i++)
{
auto mine = (CGMine *) factory.at(static_cast<si32>(res))->create(ObjectTemplate());
mine->producedResource = res;
mine->tempOwner = PlayerColor::NEUTRAL;
mine->producedQuantity = mine->defaultResProduction();
if (!i)
addCloseObject(mine, 1500); //only firts one is close
else
addRequiredObject(mine, 1500);
}
}
for (const auto & res : preciousResources)
{
for (int i = 0; i < mines[res]; i++)
{
auto mine = (CGMine *) factory.at(static_cast<si32>(res))->create(ObjectTemplate());
mine->producedResource = res;
mine->tempOwner = PlayerColor::NEUTRAL;
mine->producedQuantity = mine->defaultResProduction();
addRequiredObject(mine, 3500);
}
}
for (int i = 0; i < mines[Res::GOLD]; i++)
{
auto mine = (CGMine *) factory.at(Res::GOLD)->create(ObjectTemplate());
mine->producedResource = Res::GOLD;
mine->tempOwner = PlayerColor::NEUTRAL;
mine->producedQuantity = mine->defaultResProduction();
addRequiredObject(mine, 7000);
}
return true;
}
EObjectPlacingResult::EObjectPlacingResult CRmgTemplateZone::tryToPlaceObjectAndConnectToPath(CMapGenerator* gen, CGObjectInstance *obj, int3 &pos)
{
//check if we can find a path around this object. Tiles will be set to "USED" after object is successfully placed.
obj->pos = pos;
gen->setOccupied(obj->visitablePos(), ETileType::BLOCKED);
for (auto tile : obj->getBlockedPos())
{
if (gen->map->isInTheMap(tile))
gen->setOccupied(tile, ETileType::BLOCKED);
}
int3 accessibleOffset = getAccessibleOffset(gen, obj->appearance, pos);
if (!accessibleOffset.valid())
{
logGlobal->warnStream() << boost::format("Cannot access required object at position %s, retrying") % pos;
return EObjectPlacingResult::CANNOT_FIT;
}
if (!connectPath(gen, accessibleOffset, true))
{
logGlobal->traceStream() << boost::format("Failed to create path to required object at position %s, retrying") % pos;
return EObjectPlacingResult::SEALED_OFF;
}
else
return EObjectPlacingResult::SUCCESS;
}
bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
{
logGlobal->traceStream() << "Creating required objects";
for(const auto &object : requiredObjects)
{
auto obj = object.first;
int3 pos;
while (true)
{
if (!findPlaceForObject(gen, obj, 3, pos))
{
logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") % id;
return false;
}
if (tryToPlaceObjectAndConnectToPath(gen, obj, pos) == EObjectPlacingResult::SUCCESS)
{
//paths to required objects constitute main paths of zone. otherwise they just may lead to middle and create dead zones
placeObject(gen, obj, pos);
guardObject(gen, obj, object.second, (obj->ID == Obj::MONOLITH_TWO_WAY), true);
break;
}
}
}
for (const auto &obj : closeObjects)
{
setTemplateForObject(gen, obj.first);
auto tilesBlockedByObject = obj.first->getBlockedOffsets();
bool finished = false;
while (!finished)
{
std::vector<int3> tiles(possibleTiles.begin(), possibleTiles.end());
//new tiles vector after each object has been placed, OR misplaced area has been sealed off
boost::remove_if(tiles, [gen, obj, this](int3 &tile)-> bool
{
//object must be accessible from at least one surounding tile
return !this->isAccessibleFromAnywhere(gen, obj.first->appearance, tile);
});
// smallest distance to zone center, greatest distance to nearest object
auto isCloser = [this, gen](const int3 & lhs, const int3 & rhs) -> bool
{
float lDist = this->pos.dist2d(lhs);
float rDist = this->pos.dist2d(rhs);
lDist *= (lDist > 12) ? 10 : 1; //objects within 12 tile radius are preferred (smaller distance rating)
rDist *= (rDist > 12) ? 10 : 1;
return (lDist * 0.5f - std::sqrt(gen->getNearestObjectDistance(lhs))) < (rDist * 0.5f - std::sqrt(gen->getNearestObjectDistance(rhs)));
};
boost::sort(tiles, isCloser);
if (tiles.empty())
{
logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") % id;
return false;
}
for (auto tile : tiles)
{
//code partially adapted from findPlaceForObject()
if (areAllTilesAvailable(gen, obj.first, tile, tilesBlockedByObject))
gen->setOccupied(pos, ETileType::BLOCKED); //why?
else
continue;
EObjectPlacingResult::EObjectPlacingResult result = tryToPlaceObjectAndConnectToPath(gen, obj.first, tile);
if (result == EObjectPlacingResult::SUCCESS)
{
placeObject(gen, obj.first, tile);
guardObject(gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
finished = true;
break;
}
else if (result == EObjectPlacingResult::CANNOT_FIT)
continue; // next tile
else if (result == EObjectPlacingResult::SEALED_OFF)
{
break; //tiles expired, pick new ones
}
else
throw (rmgException("Wrong result of tryToPlaceObjectAndConnectToPath()"));
}
}
}
return true;
}
void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
{
int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
int monsterStrength = zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
minGuardedValue = minGuardedValues[monsterStrength];
auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
{
return lhs.max > rhs.max;
};
//place biggest treasures first at large distance, place smaller ones inbetween
boost::sort(treasureInfo, valueComparator);
//sort treasures by ascending value so we can stop checking treasures with too high value
boost::sort(possibleObjects, [](const ObjectInfo& oi1, const ObjectInfo& oi2) -> bool
{
return oi1.value < oi2.value;
});
int totalDensity = 0;
for (auto t : treasureInfo)
{
//discard objects with too high value to be ever placed
vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
{
return oi.value > t.max;
});
totalDensity += t.density;
//treasure density is inversely proportional to zone size but must be scaled back to map size
//also, normalize it to zone count - higher count means relatively smaller zones
//this is squared distance for optimization purposes
const double minDistance = std::max<float>((125.f / totalDensity), 2);
//distance lower than 2 causes objects to overlap and crash
bool stop = false;
do {
//optimization - don't check tiles which are not allowed
vstd::erase_if(possibleTiles, [gen](const int3 &tile) -> bool
{
return !gen->isPossible(tile);
});
int3 treasureTilePos;
//If we are able to place at least one object with value lower than minGuardedValue, it's ok
do
{
if (!findPlaceForTreasurePile(gen, minDistance, treasureTilePos, t.min))
{
stop = true;
break;
}
}
while (!createTreasurePile(gen, treasureTilePos, minDistance, t)); //failed creation - position was wrong, cannot connect it
} while (!stop);
}
}
void CRmgTemplateZone::createObstacles1(CMapGenerator * gen)
{
if (pos.z) //underground
{
//now make sure all accessible tiles have no additional rock on them
std::vector<int3> accessibleTiles;
for (auto tile : tileinfo)
{
if (gen->isFree(tile) || gen->isUsed(tile))
{
accessibleTiles.push_back(tile);
}
}
gen->editManager->getTerrainSelection().setSelection(accessibleTiles);
gen->editManager->drawTerrain(terrainType, &gen->rand);
}
}
void CRmgTemplateZone::createObstacles2(CMapGenerator* gen)
{
typedef std::vector<ObjectTemplate> obstacleVector;
//obstacleVector possibleObstacles;
std::map <ui8, obstacleVector> obstaclesBySize;
typedef std::pair <ui8, obstacleVector> obstaclePair;
std::vector<obstaclePair> possibleObstacles;
//get all possible obstacles for this terrain
for (auto primaryID : VLC->objtypeh->knownObjects())
{
for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
{
auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
if (handler->isStaticObject())
{
for (auto temp : handler->getTemplates())
{
if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp);
}
}
}
}
for (auto o : obstaclesBySize)
{
possibleObstacles.push_back (std::make_pair(o.first, o.second));
}
boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
{
return p1.first > p2.first; //bigger obstacles first
});
auto sel = gen->editManager->getTerrainSelection();
sel.clearSelection();
auto tryToPlaceObstacleHere = [this, gen, &possibleObstacles](int3& tile, int index)-> bool
{
auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
int3 obstaclePos = tile + temp.getBlockMapOffset();
if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
{
auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
placeObject(gen, obj, obstaclePos, false);
return true;
}
return false;
};
//reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
for (auto tile : boost::adaptors::reverse(tileinfo))
{
//fill tiles that should be blocked with obstacles or are just possible (with some probability)
if (gen->shouldBeBlocked(tile) || (gen->isPossible(tile) && gen->rand.nextInt(1,100) < 60))
{
//start from biggets obstacles
for (int i = 0; i < possibleObstacles.size(); i++)
{
if (tryToPlaceObstacleHere(tile, i))
break;
}
}
}
//cleanup - remove unused possible tiles to make space for roads
for (auto tile : tileinfo)
{
if (gen->isPossible(tile))
{
gen->setOccupied (tile, ETileType::FREE);
}
}
}
void CRmgTemplateZone::connectRoads(CMapGenerator* gen)
{
logGlobal->debug("Started building roads");
std::set<int3> roadNodesCopy(roadNodes);
std::set<int3> processed;
while(!roadNodesCopy.empty())
{
int3 node = *roadNodesCopy.begin();
roadNodesCopy.erase(node);
int3 cross(-1, -1, -1);
auto comparator = [=](int3 lhs, int3 rhs) { return node.dist2dSQ(lhs) < node.dist2dSQ(rhs); };
if (processed.size()) //connect with already existing network
{
cross = *boost::range::min_element(processed, comparator); //find another remaining node
}
else if (roadNodesCopy.size()) //connect with any other unconnected node
{
cross = *boost::range::min_element(roadNodesCopy, comparator); //find another remaining node
}
else //no other nodes left, for example single road node in this zone
break;
logGlobal->debugStream() << "Building road from " << node << " to " << cross;
if (createRoad(gen, node, cross))
{
processed.insert(cross); //don't draw road starting at end point which is already connected
vstd::erase_if_present(roadNodesCopy, cross);
}
processed.insert(node);
}
drawRoads(gen);
logGlobal->debug("Finished building roads");
}
void CRmgTemplateZone::drawRoads(CMapGenerator* gen)
{
std::vector<int3> tiles;
for (auto tile : roads)
{
if(gen->map->isInTheMap(tile))
tiles.push_back (tile);
}
for (auto tile : roadNodes)
{
if (gen->getZoneID(tile) == id) //mark roads for our nodes, but not for zone guards in other zones
tiles.push_back(tile);
}
gen->editManager->getTerrainSelection().setSelection(tiles);
gen->editManager->drawRoad(ERoadType::COBBLESTONE_ROAD, &gen->rand);
}
bool CRmgTemplateZone::fill(CMapGenerator* gen)
{
initTerrainType(gen);
//zone center should be always clear to allow other tiles to connect
gen->setOccupied(this->getPos(), ETileType::FREE);
freePaths.insert(pos);
addAllPossibleObjects (gen);
connectLater(gen); //ideally this should work after fractalize, but fails
fractalize(gen);
placeMines(gen);
createRequiredObjects(gen);
createTreasures(gen);
logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
return true;
}
bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, float min_dist, int3 &pos, int value)
{
float best_distance = 0;
bool result = false;
bool needsGuard = value > minGuardedValue;
//logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
for(auto tile : possibleTiles)
{
auto dist = gen->getNearestObjectDistance(tile);
if ((dist >= min_dist) && (dist > best_distance))
{
bool allTilesAvailable = true;
gen->foreach_neighbour (tile, [&gen, &allTilesAvailable, needsGuard](int3 neighbour)
{
if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour) || (!needsGuard && gen->isFree(neighbour))))
{
allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
}
});
if (allTilesAvailable)
{
best_distance = dist;
pos = tile;
result = true;
}
}
}
if (result)
{
gen->setOccupied(pos, ETileType::BLOCKED); //block that tile //FIXME: why?
}
return result;
}
bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
{
if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
return false;
auto tilesBlockedByObject = temp.getBlockedOffsets();
for (auto blockingTile : tilesBlockedByObject)
{
int3 t = pos + blockingTile;
if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
{
return false; //if at least one tile is not possible, object can't be placed here
}
}
return true;
}
bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile) const
{
return getAccessibleOffset(gen, appearance, tile).valid();
}
int3 CRmgTemplateZone::getAccessibleOffset(CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile) const
{
auto tilesBlockedByObject = appearance.getBlockedOffsets();
int3 ret(-1, -1, -1);
for (int x = -1; x < 2; x++)
{
for (int y = -1; y <2; y++)
{
if (x && y) //check only if object is visitable from another tile
{
int3 offset = int3(x, y, 0) - appearance.getVisitableOffset();
if (!vstd::contains(tilesBlockedByObject, offset))
{
int3 nearbyPos = tile + offset;
if (gen->map->isInTheMap(nearbyPos))
{
if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
ret = nearbyPos;
}
}
}
};
}
return ret;
}
void CRmgTemplateZone::setTemplateForObject(CMapGenerator* gen, CGObjectInstance* obj)
{
if (obj->appearance.id == Obj::NO_OBJ)
{
auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
if (templates.empty())
throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") % obj->ID %obj->subID %pos));
obj->appearance = templates.front();
}
}
bool CRmgTemplateZone::areAllTilesAvailable(CMapGenerator* gen, CGObjectInstance* obj, int3& tile, std::set<int3>& tilesBlockedByObject) const
{
for (auto blockingTile : tilesBlockedByObject)
{
int3 t = tile + blockingTile;
if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
{
//if at least one tile is not possible, object can't be placed here
return false;
}
}
return true;
}
bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
{
//we need object apperance to deduce free tile
setTemplateForObject(gen, obj);
int best_distance = 0;
bool result = false;
auto tilesBlockedByObject = obj->getBlockedOffsets();
for (auto tile : tileinfo)
{
//object must be accessible from at least one surounding tile
if (!isAccessibleFromAnywhere(gen, obj->appearance, tile))
continue;
auto ti = gen->getTile(tile);
auto dist = ti.getNearestObjectDistance();
//avoid borders
if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
{
if (areAllTilesAvailable(gen, obj, tile, tilesBlockedByObject))
{
best_distance = dist;
pos = tile;
result = true;
}
}
}
if (result)
{
gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
}
return result;
}
void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
{
if (!gen->map->isInTheMap(pos))
throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
object->pos = pos;
if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
throw rmgException(boost::to_string(boost::format("Visitable tile %s of object %d at %s is outside the map") % object->visitablePos() % object->id % object->pos()));
for (auto tile : object->getBlockedPos())
{
if (!gen->map->isInTheMap(tile))
throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
}
if (object->appearance.id == Obj::NO_OBJ)
{
auto terrainType = gen->map->getTile(pos).terType;
auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
if (templates.empty())
throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s (terrain %d)") %object->ID %object->subID %pos %terrainType));
object->appearance = templates.front();
}
gen->editManager->insertObject(object, pos);
//logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
}
void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, bool updateDistance)
{
//logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
checkAndPlaceObject (gen, object, pos);
auto points = object->getBlockedPos();
if (object->isVisitable())
points.insert(pos + object->getVisitableOffset());
points.insert(pos);
for(auto p : points)
{
if (gen->map->isInTheMap(p))
{
gen->setOccupied(p, ETileType::USED);
}
}
if (updateDistance)
{
for(auto tile : possibleTiles) //don't need to mark distance for not possible tiles
{
si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
gen->setNearestObjectDistance(tile, std::min<float>(d, gen->getNearestObjectDistance(tile)));
}
}
switch (object->ID)
{
case Obj::TOWN:
case Obj::RANDOM_TOWN:
case Obj::MONOLITH_TWO_WAY:
case Obj::MONOLITH_ONE_WAY_ENTRANCE:
case Obj::MONOLITH_ONE_WAY_EXIT:
case Obj::SUBTERRANEAN_GATE:
{
addRoadNode(object->visitablePos());
}
break;
default:
break;
}
}
void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
{
placeObject(gen, object, pos);
guardObject(gen, object, str, zoneGuard);
}
void CRmgTemplateZone::placeSubterraneanGate(CMapGenerator* gen, int3 pos, si32 guardStrength)
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::SUBTERRANEAN_GATE, 0);
auto gate = factory->create(ObjectTemplate());
placeObject (gen, gate, pos, true);
addToConnectLater (getAccessibleOffset (gen, gate->appearance, pos)); //guard will be placed on accessibleOffset
guardObject (gen, gate, guardStrength, true);
}
std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
{
//get all tiles from which this object can be accessed
int3 visitable = object->visitablePos();
std::vector<int3> tiles;
auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
gen->foreach_neighbour(visitable, [&](int3& pos)
{
if (gen->isPossible(pos) || gen->isFree(pos))
{
if (!vstd::contains(tilesBlockedByObject, pos))
{
if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
{
tiles.push_back(pos);
}
}
};
});
return tiles;
}
bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
{
std::vector<int3> tiles = getAccessibleOffsets(gen, object);
int3 guardTile(-1, -1, -1);
if (tiles.size())
{
//guardTile = tiles.front();
guardTile = getAccessibleOffset(gen, object->appearance, object->pos);
logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
}
else
{
logGlobal->errorStream() << boost::format("Failed to guard object at %s") % object->pos();
return false;
}
if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
{
for (auto pos : tiles)
{
if (!gen->isFree(pos))
gen->setOccupied(pos, ETileType::BLOCKED);
}
gen->foreach_neighbour (guardTile, [&](int3& pos)
{
if (gen->isPossible(pos))
gen->setOccupied (pos, ETileType::FREE);
});
gen->setOccupied (guardTile, ETileType::USED);
}
else //allow no guard or other object in front of this object
{
for (auto tile : tiles)
if (gen->isPossible(tile))
gen->setOccupied (tile, ETileType::FREE);
}
return true;
}
ObjectInfo CRmgTemplateZone::getRandomObject(CMapGenerator* gen, CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
{
//int objectsVisitableFromBottom = 0; //for debug
std::vector<std::pair<ui32, ObjectInfo*>> thresholds; //handle complex object via pointer
ui32 total = 0;
//calculate actual treasure value range based on remaining value
ui32 maxVal = desiredValue - currentValue;
ui32 minValue = 0.25f * (desiredValue - currentValue);
//roulette wheel
for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
{
if (oi.value > maxVal)
break; //this assumes values are sorted in ascending order
if (oi.value >= minValue && oi.maxPerZone > 0)
{
int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
int3 newVisitablePos = info.nextTreasurePos;
if (!oi.templ.isVisitableFromTop())
{
//objectsVisitableFromBottom++;
//there must be free tiles under object
auto blockedOffsets = oi.templ.getBlockedOffsets();
if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos))
continue;
}
//NOTE: y coordinate grows downwards
if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
{
bool fitsHere = false;
if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
{
for (auto tile : info.visitableFromTopPositions)
{
int3 actualTile = tile + newVisitableOffset;
if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
{
fitsHere = true;
break;
}
}
for (auto tile : info.visitableFromBottomPositions)
{
int3 actualTile = tile + newVisitableOffset;
if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
{
fitsHere = true;
break;
}
}
}
else //if new object is not visitable from top, it must be accessible from below or side
{
for (auto tile : info.visitableFromTopPositions)
{
int3 actualTile = tile + newVisitableOffset;
if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
{
fitsHere = true;
break;
}
}
for (auto tile : info.visitableFromBottomPositions)
{
int3 actualTile = tile + newVisitableOffset;
if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
{
fitsHere = true;
break;
}
}
}
if (!fitsHere)
continue;
}
//now check blockmap, including our already reserved pile area
bool fitsBlockmap = true;
std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
blockedOffsets.insert (newVisitableOffset);
for (auto blockingTile : blockedOffsets)
{
int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
{
fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
break;
}
if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
{
fitsBlockmap = false;
break;
}
}
if (!fitsBlockmap)
continue;
total += oi.probability;
thresholds.push_back (std::make_pair (total, &oi));
}
}
if (thresholds.empty())
{
ObjectInfo oi;
//Generate pandora Box with gold if the value is extremely high
if (minValue > 20000) //we don't have object valuable enough
{
oi.generateObject = [minValue]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
obj->resources[Res::GOLD] = minValue;
return obj;
};
oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
oi.value = minValue;
oi.probability = 0;
}
else //generate empty object with 0 value if the value if we can't spawn anything
{
oi.generateObject = [gen]() -> CGObjectInstance *
{
return nullptr;
};
oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
oi.value = 0; // this field is checked to determine no object
oi.probability = 0;
}
return oi;
}
else
{
int r = gen->rand.nextInt (1, total);
//binary search = fastest
auto it = std::lower_bound(thresholds.begin(), thresholds.end(), r,
[](const std::pair<ui32, ObjectInfo*> &rhs, const int lhs)->bool
{
return rhs.first < lhs;
});
return *(it->second);
}
return ObjectInfo(); // unreachable
}
void CRmgTemplateZone::addAllPossibleObjects(CMapGenerator* gen)
{
ObjectInfo oi;
oi.maxPerMap = std::numeric_limits<ui32>().max();
int numZones = gen->getZones().size();
std::vector<CCreature *> creatures; //native creatures for this zone
for (auto cre : VLC->creh->creatures)
{
if (!cre->special && cre->faction == townType)
{
creatures.push_back(cre);
}
}
for (auto primaryID : VLC->objtypeh->knownObjects())
{
for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
{
auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
if (!handler->isStaticObject() && handler->getRMGInfo().value)
{
for (auto temp : handler->getTemplates())
{
if (temp.canBePlacedAt(terrainType))
{
oi.generateObject = [gen, temp]() -> CGObjectInstance *
{
return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
};
auto rmgInfo = handler->getRMGInfo();
oi.value = rmgInfo.value;
oi.probability = rmgInfo.rarity;
oi.templ = temp;
oi.maxPerZone = rmgInfo.zoneLimit;
vstd::amin(oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
possibleObjects.push_back(oi);
}
}
}
}
}
//prisons
//levels 1, 5, 10, 20, 30
static int prisonExp[] = { 0, 5000, 15000, 90000, 500000 };
static int prisonValues[] = { 2500, 5000, 10000, 20000, 30000 };
for (int i = 0; i < 5; i++)
{
oi.generateObject = [i, gen, this]() -> CGObjectInstance *
{
std::vector<ui32> possibleHeroes;
for (int j = 0; j < gen->map->allowedHeroes.size(); j++)
{
if (gen->map->allowedHeroes[j])
possibleHeroes.push_back(j);
}
auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
auto factory = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0);
auto obj = (CGHeroInstance *) factory->create(ObjectTemplate());
obj->subID = hid; //will be initialized later
obj->exp = prisonExp[i];
obj->setOwner(PlayerColor::NEUTRAL);
gen->map->allowedHeroes[hid] = false; //ban this hero
gen->decreasePrisonsRemaining();
obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
return obj;
};
oi.setTemplate(Obj::PRISON, 0, terrainType);
oi.value = prisonValues[i];
oi.probability = 30;
oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
possibleObjects.push_back(oi);
}
//all following objects are unlimited
oi.maxPerZone = std::numeric_limits<ui32>().max();
//dwellings
auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
//don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
static int elementalConfluxROE[] = { 7, 13, 16, 47 };
for (int i = 0; i < 4; i++)
vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
for (auto secondaryID : subObjects)
{
auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
auto creatures = dwellingHandler->getProducedCreatures();
if (creatures.empty())
continue;
auto cre = creatures.front();
if (cre->faction == townType)
{
float nativeZonesCount = gen->getZoneCount(cre->faction);
oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2));
oi.probability = 40;
for (auto temp : dwellingHandler->getTemplates())
{
if (temp.canBePlacedAt(terrainType))
{
oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
{
auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
//dwellingHandler->configureObject(obj, gen->rand);
obj->tempOwner = PlayerColor::NEUTRAL;
return obj;
};
oi.templ = temp;
possibleObjects.push_back(oi);
}
}
}
}
static const int scrollValues[] = { 500, 2000, 3000, 4000, 5000 };
for (int i = 0; i < 5; i++)
{
oi.generateObject = [i, gen]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::SPELL_SCROLL, 0);
auto obj = (CGArtifact *) factory->create(ObjectTemplate());
std::vector<SpellID> out;
for (auto spell : VLC->spellh->objects) //spellh size appears to be greater (?)
{
if (gen->isAllowedSpell(spell->id) && spell->level == i + 1)
{
out.push_back(spell->id);
}
}
auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
obj->storedArtifact = a;
return obj;
};
oi.setTemplate(Obj::SPELL_SCROLL, 0, terrainType);
oi.value = scrollValues[i];
oi.probability = 30;
possibleObjects.push_back(oi);
}
//pandora box with gold
for (int i = 1; i < 5; i++)
{
oi.generateObject = [i]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
obj->resources[Res::GOLD] = i * 5000;
return obj;
};
oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
oi.value = i * 5000;;
oi.probability = 5;
possibleObjects.push_back(oi);
}
//pandora box with experience
for (int i = 1; i < 5; i++)
{
oi.generateObject = [i]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
obj->gainedExp = i * 5000;
return obj;
};
oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
oi.value = i * 6000;;
oi.probability = 20;
possibleObjects.push_back(oi);
}
//pandora box with creatures
static const int tierValues[] = { 5000, 7000, 9000, 12000, 16000, 21000, 27000 };
auto creatureToCount = [](CCreature * creature) -> int
{
int actualTier = creature->level > 7 ? 6 : creature->level - 1;
float creaturesAmount = ((float)tierValues[actualTier]) / creature->AIValue;
if (creaturesAmount <= 5)
{
creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
if (creaturesAmount < 1)
return 0;
}
else if (creaturesAmount <= 12)
{
(creaturesAmount /= 2) *= 2;
}
else if (creaturesAmount <= 50)
{
creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
}
else
{
creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
}
return creaturesAmount;
};
for (auto creature : creatures)
{
int creaturesAmount = creatureToCount(creature);
if (!creaturesAmount)
continue;
oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
auto stack = new CStackInstance(creature, creaturesAmount);
obj->creatures.putStack(SlotID(0), stack);
return obj;
};
oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) / 3;
oi.probability = 3;
possibleObjects.push_back(oi);
}
//Pandora with 12 spells of certain level
for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
{
oi.generateObject = [i, gen]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
std::vector <CSpell *> spells;
for (auto spell : VLC->spellh->objects)
{
if (gen->isAllowedSpell(spell->id) && spell->level == i)
spells.push_back(spell);
}
RandomGeneratorUtil::randomShuffle(spells, gen->rand);
for (int j = 0; j < std::min<int>(12, spells.size()); j++)
{
obj->spells.push_back(spells[j]->id);
}
return obj;
};
oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
oi.value = (i + 1) * 2500; //5000 - 15000
oi.probability = 2;
possibleObjects.push_back(oi);
}
//Pandora with 15 spells of certain school
for (int i = 0; i < 4; i++)
{
oi.generateObject = [i,gen]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
std::vector <CSpell *> spells;
for (auto spell : VLC->spellh->objects)
{
if (gen->isAllowedSpell(spell->id) && spell->school[(ESpellSchool)i])
spells.push_back(spell);
}
RandomGeneratorUtil::randomShuffle(spells, gen->rand);
for (int j = 0; j < std::min<int>(15, spells.size()); j++)
{
obj->spells.push_back(spells[j]->id);
}
return obj;
};
oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
oi.value = 15000;
oi.probability = 2;
possibleObjects.push_back(oi);
}
// Pandora box with 60 random spells
oi.generateObject = [gen]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
auto obj = (CGPandoraBox *) factory->create(ObjectTemplate());
std::vector <CSpell *> spells;
for (auto spell : VLC->spellh->objects)
{
if (gen->isAllowedSpell(spell->id))
spells.push_back(spell);
}
RandomGeneratorUtil::randomShuffle(spells, gen->rand);
for (int j = 0; j < std::min<int>(60, spells.size()); j++)
{
obj->spells.push_back(spells[j]->id);
}
return obj;
};
oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
oi.value = 30000;
oi.probability = 2;
possibleObjects.push_back(oi);
//seer huts with creatures or generic rewards
if (questArtZone) //we won't be placing seer huts if there is no zone left to place arties
{
static const int genericSeerHuts = 8;
int seerHutsPerType = 0;
const int questArtsRemaining = gen->getQuestArtsRemaning().size();
//general issue is that not many artifact types are available for quests
if (questArtsRemaining >= genericSeerHuts + creatures.size())
{
seerHutsPerType = questArtsRemaining / (genericSeerHuts + creatures.size());
}
else if (questArtsRemaining >= genericSeerHuts)
{
seerHutsPerType = 1;
}
oi.maxPerZone = seerHutsPerType;
RandomGeneratorUtil::randomShuffle(creatures, gen->rand);
auto generateArtInfo = [this](ArtifactID id) -> ObjectInfo
{
ObjectInfo artInfo;
artInfo.probability = std::numeric_limits<ui16>::max(); //99,9% to spawn that art in first treasure pile
artInfo.maxPerZone = 1;
artInfo.value = 2000; //treasure art
artInfo.setTemplate(Obj::ARTIFACT, id, this->terrainType);
artInfo.generateObject = [id]() -> CGObjectInstance *
{
auto handler = VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, id);
return handler->create(handler->getTemplates().front());
};
return artInfo;
};
for (int i = 0; i < std::min<int>(creatures.size(), questArtsRemaining - genericSeerHuts); i++)
{
auto creature = creatures[i];
int creaturesAmount = creatureToCount(creature);
if (!creaturesAmount)
continue;
int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
oi.generateObject = [creature, creaturesAmount, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
auto obj = (CGSeerHut *) factory->create(ObjectTemplate());
obj->rewardType = CGSeerHut::CREATURE;
obj->rID = creature->idNumber;
obj->rVal = creaturesAmount;
obj->quest->missionType = CQuest::MISSION_ART;
ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
obj->quest->m5arts.push_back(artid);
obj->quest->lastDay = -1;
obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
gen->banQuestArt(artid);
this->questArtZone->possibleObjects.push_back (generateArtInfo(artid));
return obj;
};
oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
oi.value = ((2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount())) - 4000) / 3;
oi.probability = 3;
possibleObjects.push_back(oi);
}
static int seerExpGold[] = { 5000, 10000, 15000, 20000 };
static int seerValues[] = { 2000, 5333, 8666, 12000 };
for (int i = 0; i < 4; i++) //seems that code for exp and gold reward is similiar
{
int randomAppearance = *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::SEER_HUT), gen->rand);
oi.setTemplate(Obj::SEER_HUT, randomAppearance, terrainType);
oi.value = seerValues[i];
oi.probability = 10;
oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
auto obj = (CGSeerHut *) factory->create(ObjectTemplate());
obj->rewardType = CGSeerHut::EXPERIENCE;
obj->rID = 0; //unitialized?
obj->rVal = seerExpGold[i];
obj->quest->missionType = CQuest::MISSION_ART;
ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
obj->quest->m5arts.push_back(artid);
obj->quest->lastDay = -1;
obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
gen->banQuestArt(artid);
this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
return obj;
};
possibleObjects.push_back(oi);
oi.generateObject = [i, randomAppearance, gen, this, generateArtInfo]() -> CGObjectInstance *
{
auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
auto obj = (CGSeerHut *) factory->create(ObjectTemplate());
obj->rewardType = CGSeerHut::RESOURCES;
obj->rID = Res::GOLD;
obj->rVal = seerExpGold[i];
obj->quest->missionType = CQuest::MISSION_ART;
ArtifactID artid = *RandomGeneratorUtil::nextItem(gen->getQuestArtsRemaning(), gen->rand);
obj->quest->m5arts.push_back(artid);
obj->quest->lastDay = -1;
obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
gen->banQuestArt(artid);
this->questArtZone->possibleObjects.push_back(generateArtInfo(artid));
return obj;
};
possibleObjects.push_back(oi);
}
}
}
void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
{
templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
}
|