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
|
/*
* CGTownInstance.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 "CGTownInstance.h"
#include "CObjectClassesHandler.h"
#include "../spells/CSpellHandler.h"
#include "../NetPacks.h"
#include "../CGeneralTextHandler.h"
#include "../CModHandler.h"
#include "../IGameCallback.h"
#include "../CGameState.h"
#include "../mapping/CMap.h"
#include "../CPlayerState.h"
#include "../serializer/JsonSerializeFormat.h"
#include "../HeroBonus.h"
VCMI_LIB_NAMESPACE_BEGIN
std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
std::vector<int> CGTownInstance::universitySkills;
CSpecObjInfo::CSpecObjInfo():
owner(nullptr)
{
}
CCreGenAsCastleInfo::CCreGenAsCastleInfo():
CSpecObjInfo(), asCastle(false),identifier(0)
{
}
void CCreGenAsCastleInfo::serializeJson(JsonSerializeFormat & handler)
{
handler.serializeString("sameAsTown", instanceId);
if(!handler.saving)
{
asCastle = !instanceId.empty();
allowedFactions.clear();
}
if(!asCastle)
{
std::vector<bool> standard;
standard.resize(VLC->townh->size(), true);
JsonSerializeFormat::LIC allowedLIC(standard, &FactionID::decode, &FactionID::encode);
allowedLIC.any = allowedFactions;
handler.serializeLIC("allowedFactions", allowedLIC);
if(!handler.saving)
{
allowedFactions = allowedLIC.any;
}
}
}
CCreGenLeveledInfo::CCreGenLeveledInfo():
CSpecObjInfo(),
minLevel(0), maxLevel(7)
{
}
void CCreGenLeveledInfo::serializeJson(JsonSerializeFormat & handler)
{
handler.serializeInt("minLevel", minLevel, ui8(1));
handler.serializeInt("maxLevel", maxLevel, ui8(7));
if(!handler.saving)
{
//todo: safely allow any level > 7
vstd::amax(minLevel, 1);
vstd::amin(minLevel, 7);
vstd::abetween(maxLevel, minLevel, 7);
}
}
void CCreGenLeveledCastleInfo::serializeJson(JsonSerializeFormat & handler)
{
CCreGenAsCastleInfo::serializeJson(handler);
CCreGenLeveledInfo::serializeJson(handler);
}
CGDwelling::CGDwelling():
CArmedInstance()
{
info = nullptr;
}
CGDwelling::~CGDwelling()
{
vstd::clear_pointer(info);
}
void CGDwelling::initObj(CRandomGenerator & rand)
{
switch(ID)
{
case Obj::CREATURE_GENERATOR1:
case Obj::CREATURE_GENERATOR4:
{
VLC->objtypeh->getHandlerFor(ID, subID)->configureObject(this, rand);
if (getOwner() != PlayerColor::NEUTRAL)
cb->gameState()->players[getOwner()].dwellings.push_back (this);
assert(!creatures.empty());
assert(!creatures[0].second.empty());
break;
}
case Obj::REFUGEE_CAMP:
//is handled within newturn func
break;
case Obj::WAR_MACHINE_FACTORY:
creatures.resize(3);
creatures[0].second.push_back(CreatureID::BALLISTA);
creatures[1].second.push_back(CreatureID::FIRST_AID_TENT);
creatures[2].second.push_back(CreatureID::AMMO_CART);
break;
default:
assert(0);
break;
}
}
void CGDwelling::initRandomObjectInfo()
{
vstd::clear_pointer(info);
switch(ID)
{
case Obj::RANDOM_DWELLING: info = new CCreGenLeveledCastleInfo();
break;
case Obj::RANDOM_DWELLING_LVL: info = new CCreGenAsCastleInfo();
break;
case Obj::RANDOM_DWELLING_FACTION: info = new CCreGenLeveledInfo();
break;
}
if(info)
info->owner = this;
}
void CGDwelling::setPropertyDer(ui8 what, ui32 val)
{
switch (what)
{
case ObjProperty::OWNER: //change owner
if (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR2
|| ID == Obj::CREATURE_GENERATOR3 || ID == Obj::CREATURE_GENERATOR4)
{
if (tempOwner != PlayerColor::NEUTRAL)
{
std::vector<ConstTransitivePtr<CGDwelling> >* dwellings = &cb->gameState()->players[tempOwner].dwellings;
dwellings->erase (std::find(dwellings->begin(), dwellings->end(), this));
}
if (PlayerColor(val) != PlayerColor::NEUTRAL) //can new owner be neutral?
cb->gameState()->players[PlayerColor(val)].dwellings.push_back (this);
}
break;
case ObjProperty::AVAILABLE_CREATURE:
creatures.resize(1);
creatures[0].second.resize(1);
creatures[0].second[0] = CreatureID(val);
break;
}
}
void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
{
if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
{
InfoWindow iw;
iw.player = h->tempOwner;
iw.text.addTxt(MetaString::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
iw.text.addReplacement(MetaString::OBJ_NAMES, ID);
cb->sendAndApply(&iw);
return;
}
PlayerRelations::PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
if ( relations == PlayerRelations::ALLIES )
return;//do not allow recruiting or capturing
if( !relations && stacksCount() > 0) //object is guarded, owned by enemy
{
BlockingDialog bd(true,false);
bd.player = h->tempOwner;
bd.text.addTxt(MetaString::GENERAL_TXT, 421); //Much to your dismay, the %s is guarded by %s %s. Do you wish to fight the guards?
bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
bd.text.addReplacement(MetaString::ARRAY_TXT, 173 + Slots().begin()->second->getQuantityID()*3);
bd.text.addReplacement(*Slots().begin()->second);
cb->showBlockingDialog(&bd);
return;
}
// TODO this shouldn't be hardcoded
if(!relations && ID != Obj::WAR_MACHINE_FACTORY && ID != Obj::REFUGEE_CAMP)
{
cb->setOwner(this, h->tempOwner);
}
BlockingDialog bd (true,false);
bd.player = h->tempOwner;
if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
{
bd.text.addTxt(MetaString::ADVOB_TXT, ID == Obj::CREATURE_GENERATOR1 ? 35 : 36); //{%s} Would you like to recruit %s? / {%s} Would you like to recruit %s, %s, %s, or %s?
bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
for(auto & elem : creatures)
bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
}
else if(ID == Obj::REFUGEE_CAMP)
{
bd.text.addTxt(MetaString::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
bd.text.addReplacement(MetaString::OBJ_NAMES, ID);
for(auto & elem : creatures)
bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
}
else if(ID == Obj::WAR_MACHINE_FACTORY)
bd.text.addTxt(MetaString::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
else
throw std::runtime_error("Illegal dwelling!");
cb->showBlockingDialog(&bd);
}
void CGDwelling::newTurn(CRandomGenerator & rand) const
{
if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
return;
//town growths and War Machines Factories are handled separately
if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
return;
if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
{
cb->setObjProperty(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster(rand));
}
bool change = false;
SetAvailableCreatures sac;
sac.creatures = creatures;
sac.tid = id;
for (size_t i = 0; i < creatures.size(); i++)
{
if(creatures[i].second.size())
{
CCreature *cre = VLC->creh->objects[creatures[i].second[0]];
TQuantity amount = cre->growth * (1 + cre->valOfBonuses(Bonus::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(Bonus::CREATURE_GROWTH);
if (VLC->modh->settings.DWELLINGS_ACCUMULATE_CREATURES && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
sac.creatures[i].first += amount;
else
sac.creatures[i].first = amount;
change = true;
}
}
if(change)
cb->sendAndApply(&sac);
updateGuards();
}
void CGDwelling::updateGuards() const
{
//TODO: store custom guard config and use it
//TODO: store boolean flag for guards
bool guarded = false;
//default condition - creatures are of level 5 or higher
for (auto creatureEntry : creatures)
{
if (VLC->creh->objects[creatureEntry.second.at(0)]->level >= 5 && ID != Obj::REFUGEE_CAMP)
{
guarded = true;
break;
}
}
if (guarded)
{
for (auto creatureEntry : creatures)
{
const CCreature * crea = VLC->creh->objects[creatureEntry.second.at(0)];
SlotID slot = getSlotFor(crea->idNumber);
if (hasStackAtSlot(slot)) //stack already exists, overwrite it
{
ChangeStackCount csc;
csc.army = this->id;
csc.slot = slot;
csc.count = crea->growth * 3;
csc.absoluteValue = true;
cb->sendAndApply(&csc);
}
else //slot is empty, create whole new stack
{
InsertNewStack ns;
ns.army = this->id;
ns.slot = slot;
ns.type = crea->idNumber;
ns.count = crea->growth * 3;
cb->sendAndApply(&ns);
}
}
}
}
void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h) const
{
CreatureID crid = creatures[0].second[0];
CCreature *crs = VLC->creh->objects[crid];
TQuantity count = creatures[0].first;
if(crs->level == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
{
if(count) //there are available creatures
{
SlotID slot = h->getSlotFor(crid);
if(!slot.validSlot()) //no available slot
{
InfoWindow iw;
iw.player = h->tempOwner;
iw.text.addTxt(MetaString::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
cb->showInfoDialog(&iw);
}
else //give creatures
{
SetAvailableCreatures sac;
sac.tid = id;
sac.creatures = creatures;
sac.creatures[0].first = 0;
InfoWindow iw;
iw.player = h->tempOwner;
iw.text.addTxt(MetaString::GENERAL_TXT, 423); //%d %s join your army.
iw.text.addReplacement(count);
iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
cb->showInfoDialog(&iw);
cb->sendAndApply(&sac);
cb->addToSlot(StackLocation(h, slot), crs, count);
}
}
else //there no creatures
{
InfoWindow iw;
iw.text.addTxt(MetaString::GENERAL_TXT, 422); //There are no %s here to recruit.
iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
iw.player = h->tempOwner;
cb->sendAndApply(&iw);
}
}
else
{
if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
{
//there is 1 war machine available to recruit if hero doesn't have one
SetAvailableCreatures sac;
sac.tid = id;
sac.creatures = creatures;
sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
cb->sendAndApply(&sac);
}
OpenWindow ow;
ow.id1 = id.getNum();
ow.id2 = h->id.getNum();
ow.window = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP)
? OpenWindow::RECRUITMENT_FIRST
: OpenWindow::RECRUITMENT_ALL;
cb->sendAndApply(&ow);
}
}
void CGDwelling::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
{
if (result.winner == 0)
{
onHeroVisit(hero);
}
}
void CGDwelling::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
{
auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
{
if(answer)
cb->startBattleI(hero, this);
}
else if(answer)
{
heroAcceptsCreatures(hero);
}
}
void CGDwelling::serializeJsonOptions(JsonSerializeFormat & handler)
{
if(!handler.saving)
initRandomObjectInfo();
switch (ID)
{
case Obj::WAR_MACHINE_FACTORY:
case Obj::REFUGEE_CAMP:
//do nothing
break;
case Obj::RANDOM_DWELLING:
case Obj::RANDOM_DWELLING_LVL:
case Obj::RANDOM_DWELLING_FACTION:
info->serializeJson(handler);
//fall through
default:
serializeJsonOwner(handler);
break;
}
}
int CGTownInstance::getSightRadius() const //returns sight distance
{
auto ret = CBuilding::HEIGHT_NO_TOWER;
for(const auto & bid : builtBuildings)
{
if(bid.IsSpecialOrGrail())
{
auto height = town->buildings.at(bid)->height;
if(ret < height)
ret = height;
}
}
return ret;
}
void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
{
///this is freakin' overcomplicated solution
switch (what)
{
case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, visitingHero->id.getNum());
break;
case ObjProperty::STRUCTURE_CLEAR_VISITORS:
bonusingBuildings[val]->setProperty (ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
break;
case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, garrisonHero->id.getNum());
break;
case ObjProperty::BONUS_VALUE_FIRST:
bonusValue.first = val;
break;
case ObjProperty::BONUS_VALUE_SECOND:
bonusValue.second = val;
break;
}
}
CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
{
if (hasBuilt(BuildingID::CASTLE))
return CASTLE;
if (hasBuilt(BuildingID::CITADEL))
return CITADEL;
if (hasBuilt(BuildingID::FORT))
return FORT;
return NONE;
}
int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
{
if (hasBuilt(BuildingID::CAPITOL))
return 3;
if (hasBuilt(BuildingID::CITY_HALL))
return 2;
if (hasBuilt(BuildingID::TOWN_HALL))
return 1;
if (hasBuilt(BuildingID::VILLAGE_HALL))
return 0;
return -1;
}
int CGTownInstance::mageGuildLevel() const
{
if (hasBuilt(BuildingID::MAGES_GUILD_5))
return 5;
if (hasBuilt(BuildingID::MAGES_GUILD_4))
return 4;
if (hasBuilt(BuildingID::MAGES_GUILD_3))
return 3;
if (hasBuilt(BuildingID::MAGES_GUILD_2))
return 2;
if (hasBuilt(BuildingID::MAGES_GUILD_1))
return 1;
return 0;
}
int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
{
return town->hordeLvl.at(HID);
}
int CGTownInstance::creatureGrowth(const int & level) const
{
return getGrowthInfo(level).totalGrowth();
}
GrowthInfo CGTownInstance::getGrowthInfo(int level) const
{
GrowthInfo ret;
if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
return ret;
if (creatures[level].second.empty())
return ret; //no dwelling
const CCreature *creature = VLC->creh->objects[creatures[level].second.back()];
const int base = creature->growth;
int castleBonus = 0;
ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[590], base));// \n\nBasic growth %d"
if (hasBuilt(BuildingID::CASTLE))
ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CASTLE, castleBonus = base));
else if (hasBuilt(BuildingID::CITADEL))
ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CITADEL, castleBonus = base / 2));
if(town->hordeLvl.at(0) == level)//horde 1
if(hasBuilt(BuildingID::HORDE_1))
ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_1, creature->hordeGrowth));
if(town->hordeLvl.at(1) == level)//horde 2
if(hasBuilt(BuildingID::HORDE_2))
ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_2, creature->hordeGrowth));
int dwellingBonus = 0;
if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
{
dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
}
if(dwellingBonus)
ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[591], dwellingBonus));// \nExternal dwellings %+d
//other *-of-legion-like bonuses (%d to growth cumulative with grail)
TConstBonusListPtr bonuses = getBonuses(Selector::type()(Bonus::CREATURE_GROWTH).And(Selector::subtype()(level)));
for(const auto & b : *bonuses)
ret.entries.push_back(GrowthInfo::Entry(b->val, b->Description()));
//statue-of-legion-like bonus: % to base+castle
TConstBonusListPtr bonuses2 = getBonuses(Selector::type()(Bonus::CREATURE_GROWTH_PERCENT));
for(const auto & b : *bonuses2)
ret.entries.push_back(GrowthInfo::Entry(b->val * (base + castleBonus) / 100, b->Description()));
if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::GRAIL, ret.totalGrowth() / 2));
return ret;
}
int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<ConstTransitivePtr<CGDwelling> >& dwellings) const
{
int totalBonus = 0;
for (const auto& dwelling : dwellings)
{
for (const auto& creature : dwelling->creatures)
{
totalBonus += vstd::contains(creatureIds, creature.second[0]) ? 1 : 0;
}
}
return totalBonus;
}
TResources CGTownInstance::dailyIncome() const
{
TResources ret;
for (auto & p : town->buildings)
{
BuildingID buildingUpgrade;
for (auto & p2 : town->buildings)
{
if (p2.second->upgrade == p.first)
{
buildingUpgrade = p2.first;
}
}
if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
{
ret += p.second->produce;
}
}
return ret;
}
bool CGTownInstance::hasFort() const
{
return hasBuilt(BuildingID::FORT);
}
bool CGTownInstance::hasCapitol() const
{
return hasBuilt(BuildingID::CAPITOL);
}
CGTownInstance::CGTownInstance()
:CGDwelling(), IShipyard(this), IMarket(this), town(nullptr), builded(0), destroyed(0), identifier(0), alignment(0xff)
{
this->setNodeType(CBonusSystemNode::TOWN);
}
CGTownInstance::~CGTownInstance()
{
for (auto & elem : bonusingBuildings)
delete elem;
}
int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
{
if(checkGuild && mageGuildLevel() < level)
return 0;
int ret = 6 - level; //how many spells are available at this level
if (hasBuilt(BuildingSubID::LIBRARY))
ret++;
return ret;
}
bool CGTownInstance::needsLastStack() const
{
if(garrisonHero)
return true;
else return false;
}
void CGTownInstance::setOwner(const PlayerColor player) const
{
removeCapitols(player);
cb->setOwner(this, player);
}
void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
{
if(!cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
{
if(armedGarrison() || visitingHero)
{
const CGHeroInstance * defendingHero = visitingHero ? visitingHero : garrisonHero;
const CArmedInstance * defendingArmy = defendingHero ? (CArmedInstance *)defendingHero : this;
const bool isBattleOutside = isBattleOutsideTown(defendingHero);
if(!isBattleOutside && visitingHero && defendingHero == visitingHero)
{
//we have two approaches to merge armies: mergeGarrisonOnSiege() and used in the CGameHandler::garrisonSwap(ObjectInstanceID tid)
auto nodeSiege = defendingHero->whereShouldBeAttachedOnSiege(isBattleOutside);
if(nodeSiege == (CBonusSystemNode *)this)
cb->swapGarrisonOnSiege(this->id);
const_cast<CGHeroInstance *>(defendingHero)->inTownGarrison = false; //hack to return visitor from garrison after battle
}
cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (isBattleOutside ? nullptr : this));
}
else
{
auto heroColor = h->getOwner();
onTownCaptured(heroColor);
if(cb->gameState()->getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
{
return; //we just won game, we do not need to perform any extra actions
//TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
}
cb->heroVisitCastle(this, h);
}
}
else if(h->visitablePos() == visitablePos())
{
bool commander_recover = h->commander && !h->commander->alive;
if (commander_recover) // rise commander from dead
{
SetCommanderProperty scp;
scp.heroid = h->id;
scp.which = SetCommanderProperty::ALIVE;
scp.amount = 1;
cb->sendAndApply(&scp);
}
cb->heroVisitCastle(this, h);
// TODO(vmarkovtsev): implement payment for rising the commander
if (commander_recover) // info window about commander
{
InfoWindow iw;
iw.player = h->tempOwner;
iw.text << h->commander->getName();
iw.components.push_back(Component(*h->commander));
cb->showInfoDialog(&iw);
}
}
else
{
logGlobal->error("%s visits allied town of %s from different pos?", h->name, name);
}
}
void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
{
//FIXME: find out why this issue appears on random maps
if(visitingHero == h)
{
cb->stopHeroVisitCastle(this, h);
logGlobal->trace("%s correctly left town %s", h->name, name);
}
else
logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->name, name);
}
std::string CGTownInstance::getObjectName() const
{
return name + ", " + town->faction->name;
}
bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
{
return town->getBuildingType(subId) != BuildingID::NONE;
}
void CGTownInstance::initOverriddenBids()
{
for(const auto & bid : builtBuildings)
{
auto & overrideThem = town->buildings.at(bid)->overrideBids;
for(auto & overrideIt : overrideThem)
overriddenBuildings.insert(overrideIt);
}
}
bool CGTownInstance::isBonusingBuildingAdded(BuildingID::EBuildingID bid) const
{
auto present = std::find_if(bonusingBuildings.begin(), bonusingBuildings.end(), [&](CGTownBuilding* building)
{
return building->getBuildingType().num == bid;
});
return present != bonusingBuildings.end();
}
//it does not check hasBuilt because this check is in the OnHeroVisit handler
void CGTownInstance::tryAddOnePerWeekBonus(BuildingSubID::EBuildingSubID subID)
{
auto bid = town->getBuildingType(subID);
if(bid != BuildingID::NONE && !isBonusingBuildingAdded(bid))
bonusingBuildings.push_back(new COPWBonus(bid, subID, this));
}
void CGTownInstance::tryAddVisitingBonus(BuildingSubID::EBuildingSubID subID)
{
auto bid = town->getBuildingType(subID);
if(bid != BuildingID::NONE && !isBonusingBuildingAdded(bid))
bonusingBuildings.push_back(new CTownBonus(bid, subID, this));
}
void CGTownInstance::addTownBonuses()
{
for(const auto & kvp : town->buildings)
{
if(vstd::contains(overriddenBuildings, kvp.first))
continue;
if(kvp.second->IsVisitingBonus())
bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
if(kvp.second->IsWeekBonus())
bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
}
}
void CGTownInstance::deleteTownBonus(BuildingID::EBuildingID bid)
{
size_t i = 0;
CGTownBuilding * freeIt = nullptr;
for(i = 0; i != bonusingBuildings.size(); i++)
{
if(bonusingBuildings[i]->getBuildingType() == bid)
{
freeIt = bonusingBuildings[i];
break;
}
}
if(freeIt == nullptr)
return;
auto building = town->buildings.at(bid);
auto isVisitingBonus = building->IsVisitingBonus();
auto isWeekBonus = building->IsWeekBonus();
if(!isVisitingBonus && !isWeekBonus)
return;
bonusingBuildings.erase(bonusingBuildings.begin() + i);
if(isVisitingBonus)
delete (CTownBonus *)freeIt;
else if(isWeekBonus)
delete (COPWBonus *)freeIt;
}
void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
{
blockVisit = true;
if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
else
creatures.resize(GameConstants::CREATURES_PER_TOWN);
for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
{
BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
int upgradeNum = 0;
for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
{
if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
creatures[level].second.push_back(town->creatures[level][upgradeNum]);
}
}
initOverriddenBids();
addTownBonuses(); //add special bonuses from buildings to the bonusingBuildings vector.
recreateBuildingsBonuses();
updateAppearance();
}
bool CGTownInstance::hasBuiltInOldWay(ETownType::ETownType type, BuildingID bid) const
{
return (this->town->faction != nullptr && this->town->faction->index == type && hasBuilt(bid));
}
void CGTownInstance::newTurn(CRandomGenerator & rand) const
{
if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
{
//give resources if there's a Mystic Pond
if (hasBuilt(BuildingSubID::MYSTIC_POND)
&& cb->getDate(Date::DAY) != 1
&& (tempOwner < PlayerColor::PLAYER_LIMIT)
)
{
int resID = rand.nextInt(2, 5); //bonus to random rare resource
resID = (resID==2)?1:resID;
int resVal = rand.nextInt(1, 4);//with size 1..4
cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
}
auto manaVortex = getBonusingBuilding(BuildingSubID::MANA_VORTEX);
if (manaVortex != nullptr)
cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
//get Mana Vortex or Stables bonuses
//same code is in the CGameHandler::buildStructure method
if (visitingHero != nullptr)
cb->visitCastleObjects(this, visitingHero);
if (garrisonHero != nullptr)
cb->visitCastleObjects(this, garrisonHero);
if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
{
std::vector<SlotID> nativeCrits; //slots
for (auto & elem : Slots())
{
if (elem.second->type->faction == subID) //native
{
nativeCrits.push_back(elem.first); //collect matching slots
}
}
if (nativeCrits.size())
{
SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
StackLocation sl(this, pos);
const CCreature *c = getCreature(pos);
if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
{
cb->changeStackCount(sl, c->growth);
}
else //upgrade
{
cb->changeStackType(sl, VLC->creh->objects[*c->upgrades.begin()]);
}
}
if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
{
int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
if (!town->creatures[i].empty())
{
CreatureID c = town->creatures[i][0];
SlotID n;
TQuantity count = creatureGrowth(i);
if (!count) // no dwelling
count = VLC->creh->objects[c]->growth;
{//no lower tiers or above current month
if ((n = getSlotFor(c)).validSlot())
{
StackLocation sl(this, n);
if (slotEmpty(n))
cb->insertNewStack(sl, VLC->creh->objects[c], count);
else //add to existing
cb->changeStackCount(sl, count);
}
}
}
}
}
}
}
/*
int3 CGTownInstance::getSightCenter() const
{
return pos - int3(2,0,0);
}
*/
bool CGTownInstance::passableFor(PlayerColor color) const
{
if (!armedGarrison())//empty castle - anyone can visit
return true;
if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
return false;
return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
}
void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
{
offsets = {int3(-1,2,0), int3(-3,2,0)};
}
void CGTownInstance::mergeGarrisonOnSiege() const
{
auto getWeakestStackSlot = [&](ui64 powerLimit)
{
std::vector<SlotID> weakSlots;
auto stacksList = visitingHero->stacks;
std::pair<SlotID, CStackInstance *> pair;
while(stacksList.size())
{
pair = *vstd::minElementByFun(stacksList, [&](std::pair<SlotID, CStackInstance *> elem)
{
return elem.second->getPower();
});
if(powerLimit > pair.second->getPower() &&
(weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
{
weakSlots.push_back(pair.first);
stacksList.erase(pair.first);
}
else
break;
}
if(weakSlots.size())
return *std::max_element(weakSlots.begin(), weakSlots.end());
return SlotID();
};
auto count = static_cast<int>(stacks.size());
for(int i = 0; i < count; i++)
{
auto pair = *vstd::maxElementByFun(stacks, [&](std::pair<SlotID, CStackInstance *> elem)
{
ui64 power = elem.second->getPower();
auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
power += visitingHero->getStack(dst).getPower();
return power;
});
auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
if(dst.validSlot())
cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
else
{
dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
if(dst.validSlot())
cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
}
}
}
void CGTownInstance::removeCapitols (PlayerColor owner) const
{
if (hasCapitol()) // search if there's an older capitol
{
PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
{
if (*i != this && (*i)->hasCapitol())
{
RazeStructures rs;
rs.tid = id;
rs.bid.insert(BuildingID::CAPITOL);
rs.destroyed = destroyed;
cb->sendAndApply(&rs);
return;
}
}
}
}
void CGTownInstance::clearArmy() const
{
while(!stacks.empty())
{
cb->eraseStack(StackLocation(this, stacks.begin()->first));
}
}
int CGTownInstance::getBoatType() const
{
switch (town->faction->alignment)
{
case EAlignment::EVIL : return 0;
case EAlignment::GOOD : return 1;
case EAlignment::NEUTRAL : return 2;
}
assert(0);
return -1;
}
int CGTownInstance::getMarketEfficiency() const
{
if(!hasBuiltSomeTradeBuilding())
return 0;
const PlayerState *p = cb->getPlayerState(tempOwner);
assert(p);
int marketCount = 0;
for(const CGTownInstance *t : p->towns)
if(t->hasBuiltSomeTradeBuilding())
marketCount++;
return marketCount;
}
bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
{
switch(mode)
{
case EMarketMode::RESOURCE_RESOURCE:
case EMarketMode::RESOURCE_PLAYER:
return hasBuilt(BuildingID::MARKETPLACE);
case EMarketMode::ARTIFACT_RESOURCE:
case EMarketMode::RESOURCE_ARTIFACT:
return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
case EMarketMode::CREATURE_RESOURCE:
return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
case EMarketMode::CREATURE_UNDEAD:
return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
case EMarketMode::RESOURCE_SKILL:
return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
default:
assert(0);
return false;
}
}
std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
{
if(mode == EMarketMode::RESOURCE_ARTIFACT)
{
std::vector<int> ret;
for(const CArtifact *a : merchantArtifacts)
if(a)
ret.push_back(a->id);
else
ret.push_back(-1);
return ret;
}
else if ( mode == EMarketMode::RESOURCE_SKILL )
{
return universitySkills;
}
else
return IMarket::availableItemsIds(mode);
}
void CGTownInstance::setType(si32 ID, si32 subID)
{
assert(ID == Obj::TOWN); // just in case
CGObjectInstance::setType(ID, subID);
town = (*VLC->townh)[subID]->town;
randomizeArmy(subID);
updateAppearance();
}
void CGTownInstance::updateAppearance()
{
auto terrain = cb->gameState()->getTile(visitablePos())->terType->id;
//FIXME: not the best way to do this
auto app = VLC->objtypeh->getHandlerFor(ID, subID)->getOverride(terrain, this);
if (app)
appearance = app;
}
std::string CGTownInstance::nodeName() const
{
return "Town (" + (town ? town->faction->name : "unknown") + ") of " + name;
}
void CGTownInstance::deserializationFix()
{
attachTo(townAndVis);
//Hero is already handled by CGameState::attachArmedObjects
// if(visitingHero)
// visitingHero->attachTo(&townAndVis);
// if(garrisonHero)
// garrisonHero->attachTo(this);
}
void CGTownInstance::updateMoraleBonusFromArmy()
{
auto b = getExportedBonusList().getFirst(Selector::sourceType()(Bonus::ARMY).And(Selector::type()(Bonus::MORALE)));
if(!b)
{
b = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
addNewBonus(b);
}
if (garrisonHero)
{
b->val = 0;
CBonusSystemNode::treeHasChanged();
}
else
CArmedInstance::updateMoraleBonusFromArmy();
}
void CGTownInstance::recreateBuildingsBonuses()
{
BonusList bl;
getExportedBonusList().getBonuses(bl, Selector::sourceType()(Bonus::TOWN_STRUCTURE));
for(auto b : bl)
removeBonus(b);
for(const auto & bid : builtBuildings)
{
if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
continue;
auto building = town->buildings.at(bid);
if(building->buildingBonuses.empty())
continue;
for(auto & bonus : building->buildingBonuses)
{
if(bonus->limiter && bonus->effectRange == Bonus::ONLY_ENEMY_ARMY) //ONLY_ENEMY_ARMY is only mark for OppositeSide limiter to avoid extra dynamic_cast.
{
auto bCopy = std::make_shared<Bonus>(*bonus); //just a copy of the shared_ptr has been changed and reassigned.
bCopy->limiter = std::make_shared<OppositeSideLimiter>(this->getOwner());
addNewBonus(bCopy);
continue;
}
if(bonus->propagator != nullptr && bonus->propagator->getPropagatorType() == ALL_CREATURES)
VLC->creh->addBonusForAllCreatures(bonus);
else
addNewBonus(bonus);
}
}
}
void CGTownInstance::setVisitingHero(CGHeroInstance *h)
{
assert(!!visitingHero == !h);
if(h)
{
PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
assert(p);
h->detachFrom(*p);
h->attachTo(townAndVis);
visitingHero = h;
h->visitedTown = this;
h->inTownGarrison = false;
}
else
{
PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
visitingHero->visitedTown = nullptr;
visitingHero->detachFrom(townAndVis);
visitingHero->attachTo(*p);
visitingHero = nullptr;
}
}
void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
{
assert(!!garrisonHero == !h);
if(h)
{
PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
assert(p);
h->detachFrom(*p);
h->attachTo(*this);
garrisonHero = h;
h->visitedTown = this;
h->inTownGarrison = true;
}
else
{
PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
garrisonHero->visitedTown = nullptr;
garrisonHero->inTownGarrison = false;
garrisonHero->detachFrom(*this);
garrisonHero->attachTo(*p);
garrisonHero = nullptr;
}
updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
}
bool CGTownInstance::armedGarrison() const
{
return !stacks.empty() || garrisonHero;
}
const CTown * CGTownInstance::getTown() const
{
if(ID == Obj::RANDOM_TOWN)
return VLC->townh->randomTown;
else
{
if(nullptr == town)
{
return (*VLC->townh)[subID]->town;
}
else
return town;
}
}
int CGTownInstance::getTownLevel() const
{
// count all buildings that are not upgrades
int level = 0;
for(const auto & bid : builtBuildings)
{
if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
level++;
}
return level;
}
CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
{
return townAndVis;
}
const CArmedInstance * CGTownInstance::getUpperArmy() const
{
if(garrisonHero)
return garrisonHero;
return this;
}
const CGTownBuilding * CGTownInstance::getBonusingBuilding(BuildingSubID::EBuildingSubID subId) const
{
for(const auto building : bonusingBuildings)
{
if(building->getBuildingSubtype() == subId)
return building;
}
return nullptr;
}
bool CGTownInstance::hasBuiltSomeTradeBuilding() const
{
for(const auto & bid : builtBuildings)
{
if(town->buildings.at(bid)->IsTradeBuilding())
return true;
}
return false;
}
bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
{
for(const auto & bid : builtBuildings)
{
if(town->buildings.at(bid)->subId == buildingID)
return true;
}
return false;
}
bool CGTownInstance::hasBuilt(BuildingID buildingID) const
{
return vstd::contains(builtBuildings, buildingID);
}
bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
{
if (townID == town->faction->index || townID == ETownType::ANY)
return hasBuilt(buildingID);
return false;
}
TResources CGTownInstance::getBuildingCost(BuildingID buildingID) const
{
if (vstd::contains(town->buildings, buildingID))
return town->buildings.at(buildingID)->resources;
else
{
logGlobal->error("Town %s at %s has no possible building %d!", name, pos.toString(), buildingID.toEnum());
return TResources();
}
}
CBuilding::TRequired CGTownInstance::genBuildingRequirements(BuildingID buildID, bool deep) const
{
const CBuilding * building = town->buildings.at(buildID);
//TODO: find better solution to prevent infinite loops
std::set<BuildingID> processed;
std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
[&](const BuildingID & id) -> CBuilding::TRequired::Variant
{
const CBuilding * build = town->buildings.at(id);
CBuilding::TRequired::OperatorAll requirements;
if (!hasBuilt(id))
{
if (deep)
requirements.expressions.push_back(id);
else
return id;
}
if(!vstd::contains(processed, id))
{
processed.insert(id);
if (build->upgrade != BuildingID::NONE)
requirements.expressions.push_back(dependTest(build->upgrade));
requirements.expressions.push_back(build->requirements.morph(dependTest));
}
return requirements;
};
CBuilding::TRequired::OperatorAll requirements;
if (building->upgrade != BuildingID::NONE)
{
const CBuilding * upgr = town->buildings.at(building->upgrade);
requirements.expressions.push_back(dependTest(upgr->bid));
processed.clear();
}
requirements.expressions.push_back(building->requirements.morph(dependTest));
CBuilding::TRequired::Variant variant(requirements);
CBuilding::TRequired ret(variant);
ret.minimize();
return ret;
}
void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
{
if(visitingHero == h)
cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
else if(garrisonHero == h)
cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
else
{
//should never ever happen
logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->name, structureInstanceID);
throw std::runtime_error("internal error");
}
}
void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
{
if(result.winner == BattleSide::ATTACKER)
{
clearArmy();
onTownCaptured(hero->getOwner());
}
}
void CGTownInstance::onTownCaptured(const PlayerColor winner) const
{
setOwner(winner);
FoWChange fw;
fw.player = winner;
fw.mode = 1;
cb->getTilesInRange(fw.tiles, getSightCenter(), getSightRadius(), winner, 1);
cb->sendAndApply(& fw);
}
void CGTownInstance::afterAddToMap(CMap * map)
{
if(ID == Obj::TOWN)
map->towns.push_back(this);
}
void CGTownInstance::afterRemoveFromMap(CMap * map)
{
if (ID == Obj::TOWN)
vstd::erase_if_present(map->towns, this);
}
void CGTownInstance::reset()
{
CGTownInstance::merchantArtifacts.clear();
CGTownInstance::universitySkills.clear();
}
void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
{
CGObjectInstance::serializeJsonOwner(handler);
CCreatureSet::serializeJson(handler, "army", 7);
handler.serializeBool<ui8>("tightFormation", formation, 1, 0, 0);
handler.serializeString("name", name);
{
auto decodeBuilding = [this](const std::string & identifier) -> si32
{
auto rawId = VLC->modh->identifiers.getIdentifier(CModHandler::scopeMap(), getTown()->getBuildingScope(), identifier);
if(rawId)
return rawId.get();
else
return -1;
};
auto encodeBuilding = [this](si32 index) -> std::string
{
return getTown()->buildings.at(BuildingID(index))->identifier;
};
const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
if(handler.saving)
{
bool customBuildings = false;
boost::logic::tribool hasFort(false);
for(const BuildingID & id : forbiddenBuildings)
{
buildingsLIC.none.insert(id);
customBuildings = true;
}
for(const BuildingID & id : builtBuildings)
{
if(id == BuildingID::DEFAULT)
continue;
const CBuilding * building = getTown()->buildings.at(id);
if(building->mode == CBuilding::BUILD_AUTO)
continue;
if(id == BuildingID::FORT)
hasFort = true;
buildingsLIC.all.insert(id);
customBuildings = true;
}
if(customBuildings)
handler.serializeLIC("buildings", buildingsLIC);
else
handler.serializeBool("hasFort",hasFort);
}
else
{
handler.serializeLIC("buildings", buildingsLIC);
builtBuildings.insert(BuildingID::VILLAGE_HALL);
if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
{
builtBuildings.insert(BuildingID::DEFAULT);
bool hasFort = false;
handler.serializeBool("hasFort",hasFort);
if(hasFort)
builtBuildings.insert(BuildingID::FORT);
}
else
{
for(const si32 item : buildingsLIC.none)
forbiddenBuildings.insert(BuildingID(item));
for(const si32 item : buildingsLIC.all)
builtBuildings.insert(BuildingID(item));
}
}
}
{
std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
if(handler.saving)
{
for(SpellID id : possibleSpells)
spellsLIC.any[id.num] = true;
for(SpellID id : obligatorySpells)
spellsLIC.all[id.num] = true;
}
handler.serializeLIC("spells", spellsLIC);
if(!handler.saving)
{
possibleSpells.clear();
for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
{
if(spellsLIC.any[idx])
possibleSpells.push_back(SpellID(idx));
}
obligatorySpells.clear();
for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
{
if(spellsLIC.all[idx])
obligatorySpells.push_back(SpellID(idx));
}
}
}
}
PlayerColor CGTownBuilding::getOwner() const
{
return town->getOwner();
}
int32_t CGTownBuilding::getObjGroupIndex() const
{
return -1;
}
int32_t CGTownBuilding::getObjTypeIndex() const
{
return 0;
}
int3 CGTownBuilding::visitablePos() const
{
return town->visitablePos();
}
int3 CGTownBuilding::getPosition() const
{
return town->getPosition();
}
COPWBonus::COPWBonus(BuildingID bid, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown)
{
bID = bid;
bType = subId;
town = cgTown;
indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
}
void COPWBonus::setProperty(ui8 what, ui32 val)
{
switch (what)
{
case ObjProperty::VISITORS:
visitors.insert(val);
break;
case ObjProperty::STRUCTURE_CLEAR_VISITORS:
visitors.clear();
break;
}
}
void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
{
ObjectInstanceID heroID = h->id;
if(town->hasBuilt(bID))
{
InfoWindow iw;
iw.player = h->tempOwner;
switch (this->bType)
{
case BuildingSubID::STABLES:
if(!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
{
GiveBonus gb;
gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
gb.id = heroID.getNum();
cb->giveHeroBonus(&gb);
SetMovePoints mp;
mp.val = 600;
mp.absolute = false;
mp.hid = heroID;
cb->setMovePoints(&mp);
iw.text << VLC->generaltexth->allTexts[580];
cb->showInfoDialog(&iw);
}
break;
case BuildingSubID::MANA_VORTEX:
if(visitors.empty())
{
if(h->mana < h->manaLimit() * 2)
cb->setManaPoints (heroID, 2 * h->manaLimit());
//TODO: investigate line below
//cb->setObjProperty (town->id, ObjProperty::VISITED, true);
iw.text << getVisitingBonusGreeting();
cb->showInfoDialog(&iw);
//extra visit penalty if hero alredy had double mana points (or even more?!)
town->addHeroToStructureVisitors(h, indexOnTV);
}
break;
}
}
}
CTownBonus::CTownBonus(BuildingID index, BuildingSubID::EBuildingSubID subId, CGTownInstance * cgTown)
{
bID = index;
bType = subId;
town = cgTown;
indexOnTV = static_cast<si32>(town->bonusingBuildings.size());
}
void CTownBonus::setProperty (ui8 what, ui32 val)
{
if(what == ObjProperty::VISITORS)
visitors.insert(ObjectInstanceID(val));
}
void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
{
ObjectInstanceID heroID = h->id;
if(town->hasBuilt(bID) && visitors.find(heroID) == visitors.end())
{
si64 val = 0;
InfoWindow iw;
PrimarySkill::PrimarySkill what = PrimarySkill::NONE;
switch(bType)
{
case BuildingSubID::KNOWLEDGE_VISITING_BONUS: //wall of knowledge
what = PrimarySkill::KNOWLEDGE;
val = 1;
iw.components.push_back(Component(Component::PRIM_SKILL, 3, 1, 0));
break;
case BuildingSubID::SPELL_POWER_VISITING_BONUS: //order of fire
what = PrimarySkill::SPELL_POWER;
val = 1;
iw.components.push_back(Component(Component::PRIM_SKILL, 2, 1, 0));
break;
case BuildingSubID::ATTACK_VISITING_BONUS: //hall of Valhalla
what = PrimarySkill::ATTACK;
val = 1;
iw.components.push_back(Component(Component::PRIM_SKILL, 0, 1, 0));
break;
case BuildingSubID::EXPERIENCE_VISITING_BONUS: //academy of battle scholars
what = PrimarySkill::EXPERIENCE;
val = static_cast<int>(h->calculateXp(1000));
iw.components.push_back(Component(Component::EXPERIENCE, 0, val, 0));
break;
case BuildingSubID::DEFENSE_VISITING_BONUS: //cage of warlords
what = PrimarySkill::DEFENSE;
val = 1;
iw.components.push_back(Component(Component::PRIM_SKILL, 1, 1, 0));
break;
case BuildingSubID::CUSTOM_VISITING_BONUS:
const auto building = town->town->buildings.at(bID);
if(!h->hasBonusFrom(Bonus::TOWN_STRUCTURE, Bonus::getSid32(building->town->faction->index, building->bid)))
{
const auto & bonuses = building->onVisitBonuses;
applyBonuses(const_cast<CGHeroInstance *>(h), bonuses);
}
break;
}
if(what != PrimarySkill::NONE)
{
iw.player = cb->getOwner(heroID);
iw.text << getVisitingBonusGreeting();
cb->showInfoDialog(&iw);
cb->changePrimSkill (cb->getHero(heroID), what, val);
town->addHeroToStructureVisitors(h, indexOnTV);
}
}
}
void CTownBonus::applyBonuses(CGHeroInstance * h, const BonusList & bonuses) const
{
auto addToVisitors = false;
for(auto bonus : bonuses)
{
GiveBonus gb;
InfoWindow iw;
if(bonus->type == Bonus::TOWN_MAGIC_WELL)
{
if(h->mana >= h->manaLimit())
return;
cb->setManaPoints(h->id, h->manaLimit());
bonus->duration = Bonus::ONE_DAY;
}
gb.bonus = * bonus;
gb.id = h->id.getNum();
cb->giveHeroBonus(&gb);
if(bonus->duration == Bonus::PERMANENT)
addToVisitors = true;
iw.player = cb->getOwner(h->id);
iw.text << getCustomBonusGreeting(gb.bonus);
cb->showInfoDialog(&iw);
}
if(addToVisitors)
town->addHeroToStructureVisitors(h, indexOnTV);
}
GrowthInfo::Entry::Entry(const std::string &format, int _count)
: count(_count)
{
description = boost::str(boost::format(format) % count);
}
GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
: count(_count)
{
description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->Name() % count);
}
GrowthInfo::Entry::Entry(int _count, const std::string &fullDescription)
: count(_count)
{
description = fullDescription;
}
CTownAndVisitingHero::CTownAndVisitingHero()
{
setNodeType(TOWN_AND_VISITOR);
}
int GrowthInfo::totalGrowth() const
{
int ret = 0;
for(const Entry &entry : entries)
ret += entry.count;
return ret;
}
const std::string CGTownBuilding::getVisitingBonusGreeting() const
{
auto bonusGreeting = town->town->getGreeting(bType);
if(!bonusGreeting.empty())
return bonusGreeting;
switch(bType)
{
case BuildingSubID::MANA_VORTEX:
bonusGreeting = std::string(VLC->generaltexth->localizedTexts["townHall"]["greetingManaVortex"].String());
break;
case BuildingSubID::KNOWLEDGE_VISITING_BONUS:
bonusGreeting = std::string(VLC->generaltexth->localizedTexts["townHall"]["greetingKnowledge"].String());
break;
case BuildingSubID::SPELL_POWER_VISITING_BONUS:
bonusGreeting = std::string(VLC->generaltexth->localizedTexts["townHall"]["greetingSpellPower"].String());
break;
case BuildingSubID::ATTACK_VISITING_BONUS:
bonusGreeting = std::string(VLC->generaltexth->localizedTexts["townHall"]["greetingAttack"].String());
break;
case BuildingSubID::EXPERIENCE_VISITING_BONUS:
bonusGreeting = std::string(VLC->generaltexth->localizedTexts["townHall"]["greetingExperience"].String());
break;
case BuildingSubID::DEFENSE_VISITING_BONUS:
bonusGreeting = std::string(VLC->generaltexth->localizedTexts["townHall"]["greetingDefence"].String());
break;
}
auto buildingName = town->town->getSpecialBuilding(bType)->Name();
if(bonusGreeting.empty())
{
bonusGreeting = "Error: Bonus greeting for '%s' is not localized.";
logGlobal->error("'%s' building of '%s' faction has not localized bonus greeting.", buildingName, town->town->getLocalizedFactionName());
}
boost::algorithm::replace_first(bonusGreeting, "%s", buildingName);
town->town->setGreeting(bType, bonusGreeting);
return bonusGreeting;
}
const std::string CGTownBuilding::getCustomBonusGreeting(const Bonus & bonus) const
{
if(bonus.type == Bonus::TOWN_MAGIC_WELL)
{
auto bonusGreeting = std::string(VLC->generaltexth->localizedTexts["townHall"]["greetingInTownMagicWell"].String());
auto buildingName = town->town->getSpecialBuilding(bType)->Name();
boost::algorithm::replace_first(bonusGreeting, "%s", buildingName);
return bonusGreeting;
}
auto bonusGreeting = std::string(VLC->generaltexth->localizedTexts["townHall"]["greetingCustomBonus"].String()); //"%s gives you +%d %s%s"
std::string param = "";
std::string until = "";
if(bonus.type == Bonus::MORALE)
param = VLC->generaltexth->allTexts[384];
else if(bonus.type == Bonus::LUCK)
param = VLC->generaltexth->allTexts[385];
until = bonus.duration == (ui16)Bonus::ONE_BATTLE
? VLC->generaltexth->localizedTexts["townHall"]["greetingCustomUntil"].String() : ".";
boost::format fmt = boost::format(bonusGreeting) % bonus.description % bonus.val % param % until;
std::string greeting = fmt.str();
return greeting;
}
VCMI_LIB_NAMESPACE_END
|