NetPacksLib.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  1. #include "StdInc.h"
  2. #include "NetPacks.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "mapObjects/CObjectClassesHandler.h"
  5. #include "CArtHandler.h"
  6. #include "CHeroHandler.h"
  7. #include "mapObjects/CObjectHandler.h"
  8. #include "CModHandler.h"
  9. #include "VCMI_Lib.h"
  10. #include "mapping/CMap.h"
  11. #include "spells/CSpellHandler.h"
  12. #include "CCreatureHandler.h"
  13. #include "CGameState.h"
  14. #include "BattleState.h"
  15. #include "CTownHandler.h"
  16. #include "mapping/CMapInfo.h"
  17. #include "StartInfo.h"
  18. #include "CPlayerState.h"
  19. /*
  20. * NetPacksLib.cpp, part of VCMI engine
  21. *
  22. * Authors: listed in file AUTHORS in main folder
  23. *
  24. * License: GNU General Public License v2.0 or later
  25. * Full text of license available in license.txt file, in main folder
  26. *
  27. */
  28. #undef min
  29. #undef max
  30. std::ostream & operator<<(std::ostream & out, const CPack * pack)
  31. {
  32. return out << (pack? pack->toString() : "<nullptr>");
  33. }
  34. DLL_LINKAGE void SetResource::applyGs(CGameState *gs)
  35. {
  36. assert(player < PlayerColor::PLAYER_LIMIT);
  37. vstd::amax(val, 0); //new value must be >= 0
  38. gs->getPlayer(player)->resources[resid] = val;
  39. }
  40. DLL_LINKAGE void SetResources::applyGs(CGameState *gs)
  41. {
  42. assert(player < PlayerColor::PLAYER_LIMIT);
  43. gs->getPlayer(player)->resources = res;
  44. }
  45. DLL_LINKAGE void SetPrimSkill::applyGs(CGameState *gs)
  46. {
  47. CGHeroInstance * hero = gs->getHero(id);
  48. assert(hero);
  49. hero->setPrimarySkill(which, val, abs);
  50. }
  51. DLL_LINKAGE void SetSecSkill::applyGs(CGameState *gs)
  52. {
  53. CGHeroInstance *hero = gs->getHero(id);
  54. hero->setSecSkillLevel(which, val, abs);
  55. }
  56. DLL_LINKAGE SelectMap::SelectMap(const CMapInfo &src)
  57. {
  58. mapInfo = &src;
  59. free = false;
  60. }
  61. DLL_LINKAGE SelectMap::SelectMap()
  62. {
  63. mapInfo = nullptr;
  64. free = true;
  65. }
  66. DLL_LINKAGE SelectMap::~SelectMap()
  67. {
  68. if(free)
  69. delete mapInfo;
  70. }
  71. DLL_LINKAGE UpdateStartOptions::UpdateStartOptions(StartInfo &src)
  72. {
  73. options = &src;
  74. free = false;
  75. }
  76. DLL_LINKAGE UpdateStartOptions::UpdateStartOptions()
  77. {
  78. options = nullptr;
  79. free = true;
  80. }
  81. DLL_LINKAGE UpdateStartOptions::~UpdateStartOptions()
  82. {
  83. if(free)
  84. delete options;
  85. }
  86. DLL_LINKAGE void SetCommanderProperty::applyGs(CGameState *gs)
  87. {
  88. CCommanderInstance * commander = gs->getHero(heroid)->commander;
  89. assert (commander);
  90. switch (which)
  91. {
  92. case BONUS:
  93. commander->accumulateBonus (std::make_shared<Bonus>(accumulatedBonus));
  94. break;
  95. case SPECIAL_SKILL:
  96. commander->accumulateBonus (std::make_shared<Bonus>(accumulatedBonus));
  97. commander->specialSKills.insert (additionalInfo);
  98. break;
  99. case SECONDARY_SKILL:
  100. commander->secondarySkills[additionalInfo] = amount;
  101. break;
  102. case ALIVE:
  103. if (amount)
  104. commander->setAlive(true);
  105. else
  106. commander->setAlive(false);
  107. break;
  108. case EXPERIENCE:
  109. commander->giveStackExp (amount); //TODO: allow setting exp for stacks via netpacks
  110. break;
  111. }
  112. }
  113. DLL_LINKAGE void AddQuest::applyGs(CGameState *gs)
  114. {
  115. assert (vstd::contains(gs->players, player));
  116. auto vec = &gs->players[player].quests;
  117. if (!vstd::contains(*vec, quest))
  118. vec->push_back (quest);
  119. else
  120. logNetwork->warnStream() << "Warning! Attempt to add duplicated quest";
  121. }
  122. DLL_LINKAGE void UpdateArtHandlerLists::applyGs(CGameState *gs)
  123. {
  124. VLC->arth->minors = minors;
  125. VLC->arth->majors = majors;
  126. VLC->arth->treasures = treasures;
  127. VLC->arth->relics = relics;
  128. }
  129. DLL_LINKAGE void UpdateMapEvents::applyGs(CGameState *gs)
  130. {
  131. gs->map->events = events;
  132. }
  133. DLL_LINKAGE void UpdateCastleEvents::applyGs(CGameState *gs)
  134. {
  135. auto t = gs->getTown(town);
  136. t->events = events;
  137. }
  138. DLL_LINKAGE void ChangeFormation::applyGs(CGameState *gs)
  139. {
  140. gs->getHero(hid)->setFormation(formation);
  141. }
  142. DLL_LINKAGE void HeroVisitCastle::applyGs(CGameState *gs)
  143. {
  144. CGHeroInstance *h = gs->getHero(hid);
  145. CGTownInstance *t = gs->getTown(tid);
  146. assert(h);
  147. assert(t);
  148. if(start())
  149. t->setVisitingHero(h);
  150. else
  151. t->setVisitingHero(nullptr);
  152. }
  153. DLL_LINKAGE void ChangeSpells::applyGs(CGameState *gs)
  154. {
  155. CGHeroInstance *hero = gs->getHero(hid);
  156. if(learn)
  157. for(auto sid : spells)
  158. hero->spells.insert(sid);
  159. else
  160. for(auto sid : spells)
  161. hero->spells.erase(sid);
  162. }
  163. DLL_LINKAGE void SetMana::applyGs(CGameState *gs)
  164. {
  165. CGHeroInstance * hero = gs->getHero(hid);
  166. assert(hero);
  167. if(absolute)
  168. hero->mana = val;
  169. else
  170. hero->mana += val;
  171. vstd::amax(hero->mana, 0); //not less than 0
  172. }
  173. DLL_LINKAGE void SetMovePoints::applyGs(CGameState *gs)
  174. {
  175. CGHeroInstance *hero = gs->getHero(hid);
  176. hero->movement = val;
  177. }
  178. DLL_LINKAGE void FoWChange::applyGs(CGameState *gs)
  179. {
  180. TeamState * team = gs->getPlayerTeam(player);
  181. for(int3 t : tiles)
  182. team->fogOfWarMap[t.x][t.y][t.z] = mode;
  183. if (mode == 0) //do not hide too much
  184. {
  185. std::unordered_set<int3, ShashInt3> tilesRevealed;
  186. for (auto & elem : gs->map->objects)
  187. {
  188. const CGObjectInstance *o = elem;
  189. if (o)
  190. {
  191. switch(o->ID)
  192. {
  193. case Obj::HERO:
  194. case Obj::MINE:
  195. case Obj::TOWN:
  196. case Obj::ABANDONED_MINE:
  197. if(vstd::contains(team->players, o->tempOwner)) //check owned observators
  198. gs->getTilesInRange(tilesRevealed, o->getSightCenter(), o->getSightRadius(), o->tempOwner, 1);
  199. break;
  200. }
  201. }
  202. }
  203. for(int3 t : tilesRevealed) //probably not the most optimal solution ever
  204. team->fogOfWarMap[t.x][t.y][t.z] = 1;
  205. }
  206. }
  207. DLL_LINKAGE void SetAvailableHeroes::applyGs(CGameState *gs)
  208. {
  209. PlayerState *p = gs->getPlayer(player);
  210. p->availableHeroes.clear();
  211. for (int i = 0; i < GameConstants::AVAILABLE_HEROES_PER_PLAYER; i++)
  212. {
  213. CGHeroInstance *h = (hid[i]>=0 ? gs->hpool.heroesPool[hid[i]].get() : nullptr);
  214. if(h && army[i])
  215. h->setToArmy(army[i]);
  216. p->availableHeroes.push_back(h);
  217. }
  218. }
  219. DLL_LINKAGE void GiveBonus::applyGs(CGameState *gs)
  220. {
  221. CBonusSystemNode *cbsn = nullptr;
  222. switch(who)
  223. {
  224. case HERO:
  225. cbsn = gs->getHero(ObjectInstanceID(id));
  226. break;
  227. case PLAYER:
  228. cbsn = gs->getPlayer(PlayerColor(id));
  229. break;
  230. case TOWN:
  231. cbsn = gs->getTown(ObjectInstanceID(id));
  232. break;
  233. }
  234. assert(cbsn);
  235. if(Bonus::OneWeek(&bonus))
  236. bonus.turnsRemain = 8 - gs->getDate(Date::DAY_OF_WEEK); // set correct number of days before adding bonus
  237. auto b = std::make_shared<Bonus>(bonus);
  238. cbsn->addNewBonus(b);
  239. std::string &descr = b->description;
  240. if(!bdescr.message.size()
  241. && bonus.source == Bonus::OBJECT
  242. && (bonus.type == Bonus::LUCK || bonus.type == Bonus::MORALE))
  243. {
  244. descr = VLC->generaltexth->arraytxt[bonus.val > 0 ? 110 : 109]; //+/-%d Temporary until next battle"
  245. }
  246. else
  247. {
  248. bdescr.toString(descr);
  249. }
  250. // Some of(?) versions of H3 use %s here instead of %d. Try to replace both of them
  251. boost::replace_first(descr,"%d",boost::lexical_cast<std::string>(std::abs(bonus.val)));
  252. boost::replace_first(descr,"%s",boost::lexical_cast<std::string>(std::abs(bonus.val)));
  253. }
  254. DLL_LINKAGE void ChangeObjPos::applyGs(CGameState *gs)
  255. {
  256. CGObjectInstance *obj = gs->getObjInstance(objid);
  257. if(!obj)
  258. {
  259. logNetwork->errorStream() << "Wrong ChangeObjPos: object " << objid.getNum() << " doesn't exist!";
  260. return;
  261. }
  262. gs->map->removeBlockVisTiles(obj);
  263. obj->pos = nPos;
  264. gs->map->addBlockVisTiles(obj);
  265. }
  266. DLL_LINKAGE void ChangeObjectVisitors::applyGs(CGameState *gs)
  267. {
  268. switch (mode) {
  269. case VISITOR_ADD:
  270. gs->getHero(hero)->visitedObjects.insert(object);
  271. gs->getPlayer(gs->getHero(hero)->tempOwner)->visitedObjects.insert(object);
  272. break;
  273. case VISITOR_ADD_TEAM:
  274. {
  275. TeamState *ts = gs->getPlayerTeam(gs->getHero(hero)->tempOwner);
  276. for (auto & color : ts->players)
  277. {
  278. gs->getPlayer(color)->visitedObjects.insert(object);
  279. }
  280. }
  281. break;
  282. case VISITOR_CLEAR:
  283. for (CGHeroInstance * hero : gs->map->allHeroes)
  284. {
  285. if (hero)
  286. {
  287. hero->visitedObjects.erase(object); // remove visit info from all heroes, including those that are not present on map
  288. }
  289. }
  290. for(auto &elem : gs->players)
  291. {
  292. elem.second.visitedObjects.erase(object);
  293. }
  294. break;
  295. case VISITOR_REMOVE:
  296. gs->getHero(hero)->visitedObjects.erase(object);
  297. break;
  298. }
  299. }
  300. DLL_LINKAGE void PlayerEndsGame::applyGs(CGameState *gs)
  301. {
  302. PlayerState *p = gs->getPlayer(player);
  303. if(victoryLossCheckResult.victory()) p->status = EPlayerStatus::WINNER;
  304. else p->status = EPlayerStatus::LOSER;
  305. }
  306. DLL_LINKAGE void RemoveBonus::applyGs(CGameState *gs)
  307. {
  308. CBonusSystemNode *node;
  309. if (who == HERO)
  310. node = gs->getHero(ObjectInstanceID(whoID));
  311. else
  312. node = gs->getPlayer(PlayerColor(whoID));
  313. BonusList &bonuses = node->getExportedBonusList();
  314. for (int i = 0; i < bonuses.size(); i++)
  315. {
  316. auto b = bonuses[i];
  317. if(b->source == source && b->sid == id)
  318. {
  319. bonus = *b; //backup bonus (to show to interfaces later)
  320. node->removeBonus(b);
  321. break;
  322. }
  323. }
  324. }
  325. DLL_LINKAGE void RemoveObject::applyGs(CGameState *gs)
  326. {
  327. CGObjectInstance *obj = gs->getObjInstance(id);
  328. logGlobal->debugStream() << "removing object id=" << id << "; address=" << (intptr_t)obj << "; name=" << obj->getObjectName();
  329. //unblock tiles
  330. gs->map->removeBlockVisTiles(obj);
  331. if(obj->ID==Obj::HERO)
  332. {
  333. CGHeroInstance *h = static_cast<CGHeroInstance*>(obj);
  334. PlayerState *p = gs->getPlayer(h->tempOwner);
  335. gs->map->heroesOnMap -= h;
  336. p->heroes -= h;
  337. h->detachFrom(h->whereShouldBeAttached(gs));
  338. h->tempOwner = PlayerColor::NEUTRAL; //no one owns beaten hero
  339. vstd::erase_if(h->artifactsInBackpack, [](const ArtSlotInfo& asi)
  340. {
  341. return asi.artifact->artType->id == ArtifactID::GRAIL;
  342. });
  343. if(h->visitedTown)
  344. {
  345. if(h->inTownGarrison)
  346. h->visitedTown->garrisonHero = nullptr;
  347. else
  348. h->visitedTown->visitingHero = nullptr;
  349. h->visitedTown = nullptr;
  350. }
  351. //return hero to the pool, so he may reappear in tavern
  352. gs->hpool.heroesPool[h->subID] = h;
  353. if(!vstd::contains(gs->hpool.pavailable, h->subID))
  354. gs->hpool.pavailable[h->subID] = 0xff;
  355. gs->map->objects[id.getNum()] = nullptr;
  356. //If hero on Boat is removed, the Boat disappears
  357. if(h->boat)
  358. {
  359. gs->map->instanceNames.erase(h->boat->instanceName);
  360. gs->map->objects[h->boat->id.getNum()].dellNull();
  361. h->boat = nullptr;
  362. }
  363. return;
  364. }
  365. auto quest = dynamic_cast<const IQuestObject *>(obj);
  366. if (quest)
  367. {
  368. gs->map->quests[quest->quest->qid] = nullptr;
  369. for (auto &player : gs->players)
  370. {
  371. for (auto &q : player.second.quests)
  372. {
  373. if (q.obj == obj)
  374. {
  375. q.obj = nullptr;
  376. }
  377. }
  378. }
  379. }
  380. for (TriggeredEvent & event : gs->map->triggeredEvents)
  381. {
  382. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  383. {
  384. if (cond.object == obj)
  385. {
  386. if (cond.condition == EventCondition::DESTROY)
  387. {
  388. cond.condition = EventCondition::CONST_VALUE;
  389. cond.value = 1; // destroyed object, from now on always fulfilled
  390. }
  391. if (cond.condition == EventCondition::CONTROL)
  392. {
  393. cond.condition = EventCondition::CONST_VALUE;
  394. cond.value = 0; // destroyed object, from now on can not be fulfilled
  395. }
  396. }
  397. return cond;
  398. };
  399. event.trigger = event.trigger.morph(patcher);
  400. }
  401. gs->map->instanceNames.erase(obj->instanceName);
  402. gs->map->objects[id.getNum()].dellNull();
  403. gs->map->calculateGuardingGreaturePositions();
  404. }
  405. static int getDir(int3 src, int3 dst)
  406. {
  407. int ret = -1;
  408. if(dst.x+1 == src.x && dst.y+1 == src.y) //tl
  409. {
  410. ret = 1;
  411. }
  412. else if(dst.x == src.x && dst.y+1 == src.y) //t
  413. {
  414. ret = 2;
  415. }
  416. else if(dst.x-1 == src.x && dst.y+1 == src.y) //tr
  417. {
  418. ret = 3;
  419. }
  420. else if(dst.x-1 == src.x && dst.y == src.y) //r
  421. {
  422. ret = 4;
  423. }
  424. else if(dst.x-1 == src.x && dst.y-1 == src.y) //br
  425. {
  426. ret = 5;
  427. }
  428. else if(dst.x == src.x && dst.y-1 == src.y) //b
  429. {
  430. ret = 6;
  431. }
  432. else if(dst.x+1 == src.x && dst.y-1 == src.y) //bl
  433. {
  434. ret = 7;
  435. }
  436. else if(dst.x+1 == src.x && dst.y == src.y) //l
  437. {
  438. ret = 8;
  439. }
  440. return ret;
  441. }
  442. void TryMoveHero::applyGs(CGameState *gs)
  443. {
  444. CGHeroInstance *h = gs->getHero(id);
  445. if (!h)
  446. {
  447. logGlobal->errorStream() << "Attempt ot move unavailable hero " << id;
  448. return;
  449. }
  450. h->movement = movePoints;
  451. if((result == SUCCESS || result == BLOCKING_VISIT || result == EMBARK || result == DISEMBARK) && start != end)
  452. {
  453. auto dir = getDir(start,end);
  454. if(dir > 0 && dir <= 8)
  455. h->moveDir = dir;
  456. //else don`t change move direction - hero might have traversed the subterranean gate, direction should be kept
  457. }
  458. if(result == EMBARK) //hero enters boat at destination tile
  459. {
  460. const TerrainTile &tt = gs->map->getTile(CGHeroInstance::convertPosition(end, false));
  461. assert(tt.visitableObjects.size() >= 1 && tt.visitableObjects.back()->ID == Obj::BOAT); //the only visitable object at destination is Boat
  462. CGBoat *boat = static_cast<CGBoat*>(tt.visitableObjects.back());
  463. gs->map->removeBlockVisTiles(boat); //hero blockvis mask will be used, we don't need to duplicate it with boat
  464. h->boat = boat;
  465. boat->hero = h;
  466. }
  467. else if(result == DISEMBARK) //hero leaves boat to destination tile
  468. {
  469. CGBoat *b = const_cast<CGBoat *>(h->boat);
  470. b->direction = h->moveDir;
  471. b->pos = start;
  472. b->hero = nullptr;
  473. gs->map->addBlockVisTiles(b);
  474. h->boat = nullptr;
  475. }
  476. if(start!=end && (result == SUCCESS || result == TELEPORTATION || result == EMBARK || result == DISEMBARK))
  477. {
  478. gs->map->removeBlockVisTiles(h);
  479. h->pos = end;
  480. if(CGBoat *b = const_cast<CGBoat *>(h->boat))
  481. b->pos = end;
  482. gs->map->addBlockVisTiles(h);
  483. }
  484. for(int3 t : fowRevealed)
  485. gs->getPlayerTeam(h->getOwner())->fogOfWarMap[t.x][t.y][t.z] = 1;
  486. }
  487. DLL_LINKAGE void NewStructures::applyGs(CGameState *gs)
  488. {
  489. CGTownInstance *t = gs->getTown(tid);
  490. for(const auto & id : bid)
  491. {
  492. assert(t->town->buildings.at(id) != nullptr);
  493. t->builtBuildings.insert(id);
  494. t->updateAppearance();
  495. }
  496. t->builded = builded;
  497. t->recreateBuildingsBonuses();
  498. }
  499. DLL_LINKAGE void RazeStructures::applyGs(CGameState *gs)
  500. {
  501. CGTownInstance *t = gs->getTown(tid);
  502. for(const auto & id : bid)
  503. {
  504. t->builtBuildings.erase(id);
  505. t->updateAppearance();
  506. }
  507. t->destroyed = destroyed; //yeaha
  508. t->recreateBuildingsBonuses();
  509. }
  510. DLL_LINKAGE void SetAvailableCreatures::applyGs(CGameState *gs)
  511. {
  512. CGDwelling *dw = dynamic_cast<CGDwelling*>(gs->getObjInstance(tid));
  513. assert(dw);
  514. dw->creatures = creatures;
  515. }
  516. DLL_LINKAGE void SetHeroesInTown::applyGs(CGameState *gs)
  517. {
  518. CGTownInstance *t = gs->getTown(tid);
  519. CGHeroInstance *v = gs->getHero(visiting),
  520. *g = gs->getHero(garrison);
  521. bool newVisitorComesFromGarrison = v && v == t->garrisonHero;
  522. bool newGarrisonComesFromVisiting = g && g == t->visitingHero;
  523. if(newVisitorComesFromGarrison)
  524. t->setGarrisonedHero(nullptr);
  525. if(newGarrisonComesFromVisiting)
  526. t->setVisitingHero(nullptr);
  527. if(!newGarrisonComesFromVisiting || v)
  528. t->setVisitingHero(v);
  529. if(!newVisitorComesFromGarrison || g)
  530. t->setGarrisonedHero(g);
  531. if(v)
  532. {
  533. gs->map->addBlockVisTiles(v);
  534. }
  535. if(g)
  536. {
  537. gs->map->removeBlockVisTiles(g);
  538. }
  539. }
  540. DLL_LINKAGE void HeroRecruited::applyGs(CGameState *gs)
  541. {
  542. assert(vstd::contains(gs->hpool.heroesPool, hid));
  543. CGHeroInstance *h = gs->hpool.heroesPool[hid];
  544. CGTownInstance *t = gs->getTown(tid);
  545. PlayerState *p = gs->getPlayer(player);
  546. assert(!h->boat);
  547. h->setOwner(player);
  548. h->pos = tile;
  549. bool fresh = !h->isInitialized();
  550. if(fresh)
  551. { // this is a fresh hero who hasn't appeared yet
  552. h->movement = h->maxMovePoints(true);
  553. }
  554. gs->hpool.heroesPool.erase(hid);
  555. if(h->id == ObjectInstanceID())
  556. {
  557. h->id = ObjectInstanceID(gs->map->objects.size());
  558. gs->map->objects.push_back(h);
  559. }
  560. else
  561. gs->map->objects[h->id.getNum()] = h;
  562. gs->map->heroesOnMap.push_back(h);
  563. p->heroes.push_back(h);
  564. h->attachTo(p);
  565. if(fresh)
  566. {
  567. h->initObj(gs->getRandomGenerator());
  568. }
  569. gs->map->addBlockVisTiles(h);
  570. if(t)
  571. {
  572. t->setVisitingHero(h);
  573. }
  574. }
  575. DLL_LINKAGE void GiveHero::applyGs(CGameState *gs)
  576. {
  577. CGHeroInstance *h = gs->getHero(id);
  578. //bonus system
  579. h->detachFrom(&gs->globalEffects);
  580. h->attachTo(gs->getPlayer(player));
  581. h->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, h->type->heroClass->id)->getTemplates().front();
  582. gs->map->removeBlockVisTiles(h,true);
  583. h->setOwner(player);
  584. h->movement = h->maxMovePoints(true);
  585. gs->map->heroesOnMap.push_back(h);
  586. gs->getPlayer(h->getOwner())->heroes.push_back(h);
  587. gs->map->addBlockVisTiles(h);
  588. h->inTownGarrison = false;
  589. }
  590. DLL_LINKAGE void NewObject::applyGs(CGameState *gs)
  591. {
  592. const TerrainTile &t = gs->map->getTile(pos);
  593. ETerrainType terrainType = t.terType;
  594. CGObjectInstance *o = nullptr;
  595. switch(ID)
  596. {
  597. case Obj::BOAT:
  598. o = new CGBoat();
  599. terrainType = ETerrainType::WATER; //TODO: either boat should only spawn on water, or all water objects should be handled this way
  600. break;
  601. case Obj::MONSTER: //probably more options will be needed
  602. o = new CGCreature();
  603. {
  604. //CStackInstance hlp;
  605. CGCreature *cre = static_cast<CGCreature*>(o);
  606. //cre->slots[0] = hlp;
  607. cre->notGrowingTeam = cre->neverFlees = 0;
  608. cre->character = 2;
  609. cre->gainedArtifact = ArtifactID::NONE;
  610. cre->identifier = -1;
  611. cre->addToSlot(SlotID(0), new CStackInstance(CreatureID(subID), -1)); //add placeholder stack
  612. }
  613. break;
  614. default:
  615. o = new CGObjectInstance();
  616. break;
  617. }
  618. o->ID = ID;
  619. o->subID = subID;
  620. o->pos = pos;
  621. o->appearance = VLC->objtypeh->getHandlerFor(o->ID, o->subID)->getTemplates(terrainType).front();
  622. id = o->id = ObjectInstanceID(gs->map->objects.size());
  623. gs->map->objects.push_back(o);
  624. gs->map->addBlockVisTiles(o);
  625. o->initObj(gs->getRandomGenerator());
  626. gs->map->calculateGuardingGreaturePositions();
  627. logGlobal->debugStream() << "added object id=" << id << "; address=" << (intptr_t)o << "; name=" << o->getObjectName();
  628. }
  629. DLL_LINKAGE void NewArtifact::applyGs(CGameState *gs)
  630. {
  631. assert(!vstd::contains(gs->map->artInstances, art));
  632. gs->map->addNewArtifactInstance(art);
  633. assert(!art->getParentNodes().size());
  634. art->setType(art->artType);
  635. if (CCombinedArtifactInstance* cart = dynamic_cast<CCombinedArtifactInstance*>(art.get()))
  636. cart->createConstituents();
  637. }
  638. DLL_LINKAGE const CStackInstance * StackLocation::getStack()
  639. {
  640. if(!army->hasStackAtSlot(slot))
  641. {
  642. logNetwork->warnStream() << "Warning: " << army->nodeName() << " don't have a stack at slot " << slot;
  643. return nullptr;
  644. }
  645. return &army->getStack(slot);
  646. }
  647. struct ObjectRetriever : boost::static_visitor<const CArmedInstance *>
  648. {
  649. const CArmedInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  650. {
  651. return h;
  652. }
  653. const CArmedInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  654. {
  655. return s->armyObj;
  656. }
  657. };
  658. template <typename T>
  659. struct GetBase : boost::static_visitor<T*>
  660. {
  661. template <typename TArg>
  662. T * operator()(TArg &arg) const
  663. {
  664. return arg;
  665. }
  666. };
  667. DLL_LINKAGE void ArtifactLocation::removeArtifact()
  668. {
  669. CArtifactInstance *a = getArt();
  670. assert(a);
  671. a->removeFrom(*this);
  672. }
  673. DLL_LINKAGE const CArmedInstance * ArtifactLocation::relatedObj() const
  674. {
  675. return boost::apply_visitor(ObjectRetriever(), artHolder);
  676. }
  677. DLL_LINKAGE PlayerColor ArtifactLocation::owningPlayer() const
  678. {
  679. auto obj = relatedObj();
  680. return obj ? obj->tempOwner : PlayerColor::NEUTRAL;
  681. }
  682. DLL_LINKAGE CArtifactSet *ArtifactLocation::getHolderArtSet()
  683. {
  684. return boost::apply_visitor(GetBase<CArtifactSet>(), artHolder);
  685. }
  686. DLL_LINKAGE CBonusSystemNode *ArtifactLocation::getHolderNode()
  687. {
  688. return boost::apply_visitor(GetBase<CBonusSystemNode>(), artHolder);
  689. }
  690. DLL_LINKAGE const CArtifactInstance *ArtifactLocation::getArt() const
  691. {
  692. const ArtSlotInfo *s = getSlot();
  693. if(s && s->artifact)
  694. {
  695. if(!s->locked)
  696. return s->artifact;
  697. else
  698. {
  699. logNetwork->warnStream() << "ArtifactLocation::getArt: This location is locked!";
  700. return nullptr;
  701. }
  702. }
  703. return nullptr;
  704. }
  705. DLL_LINKAGE const CArtifactSet * ArtifactLocation::getHolderArtSet() const
  706. {
  707. ArtifactLocation *t = const_cast<ArtifactLocation*>(this);
  708. return t->getHolderArtSet();
  709. }
  710. DLL_LINKAGE const CBonusSystemNode * ArtifactLocation::getHolderNode() const
  711. {
  712. ArtifactLocation *t = const_cast<ArtifactLocation*>(this);
  713. return t->getHolderNode();
  714. }
  715. DLL_LINKAGE CArtifactInstance *ArtifactLocation::getArt()
  716. {
  717. const ArtifactLocation *t = this;
  718. return const_cast<CArtifactInstance*>(t->getArt());
  719. }
  720. DLL_LINKAGE const ArtSlotInfo *ArtifactLocation::getSlot() const
  721. {
  722. return getHolderArtSet()->getSlot(slot);
  723. }
  724. DLL_LINKAGE void ChangeStackCount::applyGs(CGameState *gs)
  725. {
  726. if(absoluteValue)
  727. sl.army->setStackCount(sl.slot, count);
  728. else
  729. sl.army->changeStackCount(sl.slot, count);
  730. }
  731. DLL_LINKAGE void SetStackType::applyGs(CGameState *gs)
  732. {
  733. sl.army->setStackType(sl.slot, type);
  734. }
  735. DLL_LINKAGE void EraseStack::applyGs(CGameState *gs)
  736. {
  737. sl.army->eraseStack(sl.slot);
  738. }
  739. DLL_LINKAGE void SwapStacks::applyGs(CGameState *gs)
  740. {
  741. CStackInstance *s1 = sl1.army->detachStack(sl1.slot),
  742. *s2 = sl2.army->detachStack(sl2.slot);
  743. sl2.army->putStack(sl2.slot, s1);
  744. sl1.army->putStack(sl1.slot, s2);
  745. }
  746. DLL_LINKAGE void InsertNewStack::applyGs(CGameState *gs)
  747. {
  748. auto s = new CStackInstance(stack.type, stack.count);
  749. sl.army->putStack(sl.slot, s);
  750. }
  751. DLL_LINKAGE void RebalanceStacks::applyGs(CGameState *gs)
  752. {
  753. const CCreature *srcType = src.army->getCreature(src.slot);
  754. TQuantity srcCount = src.army->getStackCount(src.slot);
  755. bool stackExp = VLC->modh->modules.STACK_EXP;
  756. if(srcCount == count) //moving whole stack
  757. {
  758. if(const CCreature *c = dst.army->getCreature(dst.slot)) //stack at dest -> merge
  759. {
  760. assert(c == srcType);
  761. UNUSED(c);
  762. auto alHere = ArtifactLocation (src.getStack(), ArtifactPosition::CREATURE_SLOT);
  763. auto alDest = ArtifactLocation (dst.getStack(), ArtifactPosition::CREATURE_SLOT);
  764. auto artHere = alHere.getArt();
  765. auto artDest = alDest.getArt();
  766. if (artHere)
  767. {
  768. if (alDest.getArt())
  769. {
  770. auto hero = dynamic_cast <CGHeroInstance *>(src.army.get());
  771. if (hero)
  772. {
  773. artDest->move (alDest, ArtifactLocation (hero, alDest.getArt()->firstBackpackSlot (hero)));
  774. }
  775. //else - artifact cna be lost :/
  776. else
  777. {
  778. logNetwork->warnStream() << "Artifact is present at destination slot!";
  779. }
  780. artHere->move (alHere, alDest);
  781. //TODO: choose from dialog
  782. }
  783. else //just move to the other slot before stack gets erased
  784. {
  785. artHere->move (alHere, alDest);
  786. }
  787. }
  788. if (stackExp)
  789. {
  790. ui64 totalExp = srcCount * src.army->getStackExperience(src.slot) + dst.army->getStackCount(dst.slot) * dst.army->getStackExperience(dst.slot);
  791. src.army->eraseStack(src.slot);
  792. dst.army->changeStackCount(dst.slot, count);
  793. dst.army->setStackExp(dst.slot, totalExp /(dst.army->getStackCount(dst.slot))); //mean
  794. }
  795. else
  796. {
  797. src.army->eraseStack(src.slot);
  798. dst.army->changeStackCount(dst.slot, count);
  799. }
  800. }
  801. else //move stack to an empty slot, no exp change needed
  802. {
  803. CStackInstance *stackDetached = src.army->detachStack(src.slot);
  804. dst.army->putStack(dst.slot, stackDetached);
  805. }
  806. }
  807. else
  808. {
  809. if(const CCreature *c = dst.army->getCreature(dst.slot)) //stack at dest -> rebalance
  810. {
  811. assert(c == srcType);
  812. UNUSED(c);
  813. if (stackExp)
  814. {
  815. ui64 totalExp = srcCount * src.army->getStackExperience(src.slot) + dst.army->getStackCount(dst.slot) * dst.army->getStackExperience(dst.slot);
  816. src.army->changeStackCount(src.slot, -count);
  817. dst.army->changeStackCount(dst.slot, count);
  818. dst.army->setStackExp(dst.slot, totalExp /(src.army->getStackCount(src.slot) + dst.army->getStackCount(dst.slot))); //mean
  819. }
  820. else
  821. {
  822. src.army->changeStackCount(src.slot, -count);
  823. dst.army->changeStackCount(dst.slot, count);
  824. }
  825. }
  826. else //split stack to an empty slot
  827. {
  828. src.army->changeStackCount(src.slot, -count);
  829. dst.army->addToSlot(dst.slot, srcType->idNumber, count, false);
  830. if (stackExp)
  831. dst.army->setStackExp(dst.slot, src.army->getStackExperience(src.slot));
  832. }
  833. }
  834. CBonusSystemNode::treeHasChanged();
  835. }
  836. DLL_LINKAGE void PutArtifact::applyGs(CGameState *gs)
  837. {
  838. assert(art->canBePutAt(al));
  839. art->putAt(al);
  840. //al.hero->putArtifact(al.slot, art);
  841. }
  842. DLL_LINKAGE void EraseArtifact::applyGs(CGameState *gs)
  843. {
  844. auto slot = al.getSlot();
  845. if(slot->locked)
  846. {
  847. logGlobal->debugStream() << "Erasing locked artifact: " << slot->artifact->artType->Name();
  848. DisassembledArtifact dis;
  849. dis.al.artHolder = al.artHolder;
  850. auto aset = al.getHolderArtSet();
  851. #ifndef NDEBUG
  852. bool found = false;
  853. #endif
  854. for(auto& p : aset->artifactsWorn)
  855. {
  856. auto art = p.second.artifact;
  857. if(art->canBeDisassembled() && art->isPart(slot->artifact))
  858. {
  859. dis.al.slot = aset->getArtPos(art);
  860. #ifndef NDEBUG
  861. found = true;
  862. #endif
  863. break;
  864. }
  865. }
  866. assert(found && "Failed to determine the assembly this locked artifact belongs to");
  867. logGlobal->debugStream() << "Found the corresponding assembly: " << dis.al.getSlot()->artifact->artType->Name();
  868. dis.applyGs(gs);
  869. }
  870. else
  871. {
  872. logGlobal->debugStream() << "Erasing artifact " << slot->artifact->artType->Name();
  873. }
  874. al.removeArtifact();
  875. }
  876. DLL_LINKAGE void MoveArtifact::applyGs(CGameState *gs)
  877. {
  878. CArtifactInstance *a = src.getArt();
  879. if(dst.slot < GameConstants::BACKPACK_START)
  880. assert(!dst.getArt());
  881. a->move(src, dst);
  882. //TODO what'll happen if Titan's thunder is equipped by pickin git up or the start of game?
  883. if (a->artType->id == ArtifactID::TITANS_THUNDER && dst.slot == ArtifactPosition::RIGHT_HAND) //Titan's Thunder creates new spellbook on equip
  884. {
  885. auto hPtr = boost::get<ConstTransitivePtr<CGHeroInstance> >(&dst.artHolder);
  886. if(hPtr)
  887. {
  888. CGHeroInstance *h = *hPtr;
  889. if(h && !h->hasSpellbook())
  890. gs->giveHeroArtifact(h, ArtifactID::SPELLBOOK);
  891. }
  892. }
  893. }
  894. DLL_LINKAGE void AssembledArtifact::applyGs(CGameState *gs)
  895. {
  896. CArtifactSet *artSet = al.getHolderArtSet();
  897. const CArtifactInstance *transformedArt = al.getArt();
  898. assert(transformedArt);
  899. assert(vstd::contains(transformedArt->assemblyPossibilities(artSet), builtArt));
  900. UNUSED(transformedArt);
  901. auto combinedArt = new CCombinedArtifactInstance(builtArt);
  902. gs->map->addNewArtifactInstance(combinedArt);
  903. //retrieve all constituents
  904. for(const CArtifact * constituent : *builtArt->constituents)
  905. {
  906. ArtifactPosition pos = artSet->getArtPos(constituent->id);
  907. assert(pos >= 0);
  908. CArtifactInstance *constituentInstance = artSet->getArt(pos);
  909. //move constituent from hero to be part of new, combined artifact
  910. constituentInstance->removeFrom(ArtifactLocation(al.artHolder, pos));
  911. combinedArt->addAsConstituent(constituentInstance, pos);
  912. if(!vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], al.slot) && vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], pos))
  913. al.slot = pos;
  914. }
  915. //put new combined artifacts
  916. combinedArt->putAt(al);
  917. }
  918. DLL_LINKAGE void DisassembledArtifact::applyGs(CGameState *gs)
  919. {
  920. CCombinedArtifactInstance *disassembled = dynamic_cast<CCombinedArtifactInstance*>(al.getArt());
  921. assert(disassembled);
  922. std::vector<CCombinedArtifactInstance::ConstituentInfo> constituents = disassembled->constituentsInfo;
  923. disassembled->removeFrom(al);
  924. for(CCombinedArtifactInstance::ConstituentInfo &ci : constituents)
  925. {
  926. ArtifactLocation constituentLoc = al;
  927. constituentLoc.slot = (ci.slot >= 0 ? ci.slot : al.slot); //-1 is slot of main constituent -> it'll replace combined artifact in its pos
  928. disassembled->detachFrom(ci.art);
  929. ci.art->putAt(constituentLoc);
  930. }
  931. gs->map->eraseArtifactInstance(disassembled);
  932. }
  933. DLL_LINKAGE void HeroVisit::applyGs(CGameState *gs)
  934. {
  935. }
  936. DLL_LINKAGE void SetAvailableArtifacts::applyGs(CGameState *gs)
  937. {
  938. if(id >= 0)
  939. {
  940. if(CGBlackMarket *bm = dynamic_cast<CGBlackMarket*>(gs->map->objects[id].get()))
  941. {
  942. bm->artifacts = arts;
  943. }
  944. else
  945. {
  946. logNetwork->errorStream() << "Wrong black market id!";
  947. }
  948. }
  949. else
  950. {
  951. CGTownInstance::merchantArtifacts = arts;
  952. }
  953. }
  954. DLL_LINKAGE void NewTurn::applyGs(CGameState *gs)
  955. {
  956. gs->day = day;
  957. // Update bonuses before doing anything else so hero don't get more MP than needed
  958. gs->globalEffects.popBonuses(Bonus::OneDay); //works for children -> all game objs
  959. gs->globalEffects.updateBonuses(Bonus::NDays);
  960. gs->globalEffects.updateBonuses(Bonus::OneWeek);
  961. //TODO not really a single root hierarchy, what about bonuses placed elsewhere? [not an issue with H3 mechanics but in the future...]
  962. for(NewTurn::Hero h : heroes) //give mana/movement point
  963. {
  964. CGHeroInstance *hero = gs->getHero(h.id);
  965. if(!hero)
  966. {
  967. // retreated or surrendered hero who has not been reset yet
  968. for(auto& hp : gs->hpool.heroesPool)
  969. {
  970. if(hp.second->id == h.id)
  971. {
  972. hero = hp.second;
  973. break;
  974. }
  975. }
  976. }
  977. if(!hero)
  978. {
  979. logGlobal->errorStream() << "Hero " << h.id << " not found in NewTurn::applyGs";
  980. continue;
  981. }
  982. hero->movement = h.move;
  983. hero->mana = h.mana;
  984. }
  985. for(auto i = res.cbegin(); i != res.cend(); i++)
  986. {
  987. assert(i->first < PlayerColor::PLAYER_LIMIT);
  988. gs->getPlayer(i->first)->resources = i->second;
  989. }
  990. for(auto creatureSet : cres) //set available creatures in towns
  991. creatureSet.second.applyGs(gs);
  992. for(CGTownInstance* t : gs->map->towns)
  993. t->builded = 0;
  994. if(gs->getDate(Date::DAY_OF_WEEK) == 1)
  995. gs->updateRumor();
  996. //count days without town for all players, regardless of their turn order
  997. for (auto &p : gs->players)
  998. {
  999. PlayerState & playerState = p.second;
  1000. if (playerState.status == EPlayerStatus::INGAME)
  1001. {
  1002. if (playerState.towns.empty())
  1003. {
  1004. if (playerState.daysWithoutCastle)
  1005. ++(*playerState.daysWithoutCastle);
  1006. else playerState.daysWithoutCastle = 0;
  1007. }
  1008. else
  1009. {
  1010. playerState.daysWithoutCastle = boost::none;
  1011. }
  1012. }
  1013. }
  1014. }
  1015. DLL_LINKAGE void SetObjectProperty::applyGs(CGameState *gs)
  1016. {
  1017. CGObjectInstance *obj = gs->getObjInstance(id);
  1018. if(!obj)
  1019. {
  1020. logNetwork->errorStream() << "Wrong object ID - property cannot be set!";
  1021. return;
  1022. }
  1023. CArmedInstance *cai = dynamic_cast<CArmedInstance *>(obj);
  1024. if(what == ObjProperty::OWNER && cai)
  1025. {
  1026. if(obj->ID == Obj::TOWN)
  1027. {
  1028. CGTownInstance *t = static_cast<CGTownInstance*>(obj);
  1029. if(t->tempOwner < PlayerColor::PLAYER_LIMIT)
  1030. gs->getPlayer(t->tempOwner)->towns -= t;
  1031. if(val < PlayerColor::PLAYER_LIMIT_I)
  1032. {
  1033. PlayerState * p = gs->getPlayer(PlayerColor(val));
  1034. p->towns.push_back(t);
  1035. //reset counter before NewTurn to avoid no town message if game loaded at turn when one already captured
  1036. if(p->daysWithoutCastle)
  1037. p->daysWithoutCastle = boost::none;
  1038. }
  1039. }
  1040. CBonusSystemNode *nodeToMove = cai->whatShouldBeAttached();
  1041. nodeToMove->detachFrom(cai->whereShouldBeAttached(gs));
  1042. obj->setProperty(what,val);
  1043. nodeToMove->attachTo(cai->whereShouldBeAttached(gs));
  1044. }
  1045. else //not an armed instance
  1046. {
  1047. obj->setProperty(what,val);
  1048. }
  1049. }
  1050. DLL_LINKAGE void PrepareHeroLevelUp::applyGs(CGameState *gs)
  1051. {
  1052. CGHeroInstance * h = gs->getHero(hero->id);
  1053. auto proposedSkills = h->getLevelUpProposedSecondarySkills();
  1054. if(skills.size() == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  1055. {
  1056. skills.push_back(*RandomGeneratorUtil::nextItem(proposedSkills, h->skillsInfo.rand));
  1057. }
  1058. else
  1059. {
  1060. skills = proposedSkills;
  1061. }
  1062. }
  1063. DLL_LINKAGE void HeroLevelUp::applyGs(CGameState *gs)
  1064. {
  1065. CGHeroInstance * h = gs->getHero(hero->id);
  1066. h->levelUp(skills);
  1067. }
  1068. DLL_LINKAGE void CommanderLevelUp::applyGs (CGameState *gs)
  1069. {
  1070. CCommanderInstance * commander = gs->getHero(hero->id)->commander;
  1071. assert (commander);
  1072. commander->levelUp();
  1073. }
  1074. DLL_LINKAGE void BattleStart::applyGs(CGameState *gs)
  1075. {
  1076. gs->curB = info;
  1077. gs->curB->localInit();
  1078. }
  1079. DLL_LINKAGE void BattleNextRound::applyGs(CGameState *gs)
  1080. {
  1081. for (int i = 0; i < 2; ++i)
  1082. {
  1083. gs->curB->sides[i].castSpellsCount = 0;
  1084. vstd::amax(--gs->curB->sides[i].enchanterCounter, 0);
  1085. }
  1086. gs->curB->round = round;
  1087. for(CStack *s : gs->curB->stacks)
  1088. {
  1089. s->state -= EBattleStackState::DEFENDING;
  1090. s->state -= EBattleStackState::WAITING;
  1091. s->state -= EBattleStackState::MOVED;
  1092. s->state -= EBattleStackState::HAD_MORALE;
  1093. s->state -= EBattleStackState::FEAR;
  1094. s->state -= EBattleStackState::DRAINED_MANA;
  1095. s->counterAttacksPerformed = 0;
  1096. s->counterAttacksTotalCache = 0;
  1097. // new turn effects
  1098. s->updateBonuses(Bonus::NTurns);
  1099. if(s->alive() && vstd::contains(s->state, EBattleStackState::CLONED))
  1100. {
  1101. //cloned stack has special lifetime marker
  1102. //check it after bonuses updated in battleTurnPassed()
  1103. if(!s->hasBonus(Selector::type(Bonus::NONE).And(Selector::source(Bonus::SPELL_EFFECT, SpellID::CLONE))))
  1104. s->makeGhost();
  1105. }
  1106. }
  1107. for(auto &obst : gs->curB->obstacles)
  1108. obst->battleTurnPassed();
  1109. }
  1110. DLL_LINKAGE void BattleSetActiveStack::applyGs(CGameState *gs)
  1111. {
  1112. gs->curB->activeStack = stack;
  1113. CStack *st = gs->curB->getStack(stack);
  1114. //remove bonuses that last until when stack gets new turn
  1115. st->popBonuses(Bonus::UntilGetsTurn);
  1116. if(vstd::contains(st->state,EBattleStackState::MOVED)) //if stack is moving second time this turn it must had a high morale bonus
  1117. st->state.insert(EBattleStackState::HAD_MORALE);
  1118. }
  1119. DLL_LINKAGE void BattleTriggerEffect::applyGs(CGameState *gs)
  1120. {
  1121. CStack *st = gs->curB->getStack(stackID);
  1122. switch (effect)
  1123. {
  1124. case Bonus::HP_REGENERATION:
  1125. st->firstHPleft += val;
  1126. vstd::amin (st->firstHPleft, (ui32)st->MaxHealth());
  1127. break;
  1128. case Bonus::MANA_DRAIN:
  1129. {
  1130. CGHeroInstance * h = gs->getHero(ObjectInstanceID(additionalInfo));
  1131. st->state.insert (EBattleStackState::DRAINED_MANA);
  1132. h->mana -= val;
  1133. vstd::amax(h->mana, 0);
  1134. break;
  1135. }
  1136. case Bonus::POISON:
  1137. {
  1138. auto b = st->getBonusLocalFirst(Selector::source(Bonus::SPELL_EFFECT, SpellID::POISON)
  1139. .And(Selector::type(Bonus::STACK_HEALTH)));
  1140. if (b)
  1141. b->val = val;
  1142. break;
  1143. }
  1144. case Bonus::ENCHANTER:
  1145. break;
  1146. case Bonus::FEAR:
  1147. st->state.insert(EBattleStackState::FEAR);
  1148. break;
  1149. default:
  1150. logNetwork->warnStream() << "Unrecognized trigger effect type "<< type;
  1151. }
  1152. }
  1153. DLL_LINKAGE void BattleObstaclePlaced::applyGs(CGameState *gs)
  1154. {
  1155. gs->curB->obstacles.push_back(obstacle);
  1156. }
  1157. DLL_LINKAGE void BattleUpdateGateState::applyGs(CGameState *gs)
  1158. {
  1159. if(gs->curB)
  1160. gs->curB->si.gateState = state;
  1161. }
  1162. void BattleResult::applyGs(CGameState *gs)
  1163. {
  1164. for (CStack *s : gs->curB->stacks)
  1165. {
  1166. if (s->base && s->base->armyObj && vstd::contains(s->state, EBattleStackState::SUMMONED))
  1167. {
  1168. //stack with SUMMONED flag but coming from garrison -> most likely resurrected, needs to be removed
  1169. assert(&s->base->armyObj->getStack(s->slot) == s->base);
  1170. const_cast<CArmedInstance*>(s->base->armyObj)->eraseStack(s->slot);
  1171. }
  1172. }
  1173. for (auto & elem : gs->curB->stacks)
  1174. delete elem;
  1175. for(int i = 0; i < 2; ++i)
  1176. {
  1177. if(auto h = gs->curB->battleGetFightingHero(i))
  1178. {
  1179. h->popBonuses(Bonus::OneBattle); //remove any "until next battle" bonuses
  1180. if (h->commander && h->commander->alive)
  1181. {
  1182. for (auto art : h->commander->artifactsWorn) //increment bonuses for commander artifacts
  1183. {
  1184. art.second.artifact->artType->levelUpArtifact (art.second.artifact);
  1185. }
  1186. }
  1187. }
  1188. }
  1189. if(VLC->modh->modules.STACK_EXP)
  1190. {
  1191. for(int i = 0; i < 2; i++)
  1192. if(exp[i])
  1193. gs->curB->battleGetArmyObject(i)->giveStackExp(exp[i]);
  1194. CBonusSystemNode::treeHasChanged();
  1195. }
  1196. for(int i = 0; i < 2; i++)
  1197. gs->curB->battleGetArmyObject(i)->battle = nullptr;
  1198. gs->curB.dellNull();
  1199. }
  1200. void BattleStackMoved::applyGs(CGameState *gs)
  1201. {
  1202. CStack *s = gs->curB->getStack(stack);
  1203. assert(s);
  1204. BattleHex dest = tilesToMove.back();
  1205. //if unit ended movement on quicksands that were created by enemy, that quicksand patch becomes visible for owner
  1206. for(auto &oi : gs->curB->obstacles)
  1207. {
  1208. if(oi->obstacleType == CObstacleInstance::QUICKSAND
  1209. && vstd::contains(oi->getAffectedTiles(), tilesToMove.back()))
  1210. {
  1211. SpellCreatedObstacle *sands = dynamic_cast<SpellCreatedObstacle*>(oi.get());
  1212. assert(sands);
  1213. if(sands->casterSide != !s->attackerOwned)
  1214. sands->visibleForAnotherSide = true;
  1215. }
  1216. }
  1217. s->position = dest;
  1218. }
  1219. DLL_LINKAGE void BattleStackAttacked::applyGs(CGameState *gs)
  1220. {
  1221. CStack *at = gs->curB->getStack(stackAttacked);
  1222. assert(at);
  1223. at->popBonuses(Bonus::UntilBeingAttacked);
  1224. at->count = newAmount;
  1225. at->firstHPleft = newHP;
  1226. if(killed())
  1227. {
  1228. at->state -= EBattleStackState::ALIVE;
  1229. if(at->cloneID >= 0)
  1230. {
  1231. //remove clone as well
  1232. CStack * clone = gs->curB->getStack(at->cloneID);
  1233. if(clone)
  1234. clone->makeGhost();
  1235. at->cloneID = -1;
  1236. }
  1237. }
  1238. //life drain handling
  1239. for (auto & elem : healedStacks)
  1240. {
  1241. elem.applyGs(gs);
  1242. }
  1243. if (willRebirth())
  1244. {
  1245. at->casts--;
  1246. at->state.insert(EBattleStackState::ALIVE); //hmm?
  1247. }
  1248. if (cloneKilled())
  1249. {
  1250. //"hide" killed creatures instead so we keep info about it
  1251. at->makeGhost();
  1252. for(CStack * s : gs->curB->stacks)
  1253. {
  1254. if(s->cloneID == at->ID)
  1255. s->cloneID = -1;
  1256. }
  1257. }
  1258. //killed summoned creature should be removed like clone
  1259. if(killed() && vstd::contains(at->state, EBattleStackState::SUMMONED))
  1260. {
  1261. at->makeGhost();
  1262. }
  1263. }
  1264. DLL_LINKAGE void BattleAttack::applyGs(CGameState *gs)
  1265. {
  1266. CStack *attacker = gs->curB->getStack(stackAttacking);
  1267. if(counter())
  1268. attacker->counterAttacksPerformed++;
  1269. if(shot())
  1270. {
  1271. //don't remove ammo if we have a working ammo cart
  1272. bool hasAmmoCart = false;
  1273. for(const CStack * st : gs->curB->stacks)
  1274. {
  1275. if(st->owner == attacker->owner && st->getCreature()->idNumber == CreatureID::AMMO_CART && st->alive())
  1276. {
  1277. hasAmmoCart = true;
  1278. break;
  1279. }
  1280. }
  1281. if (!hasAmmoCart)
  1282. {
  1283. attacker->shots--;
  1284. }
  1285. }
  1286. for(BattleStackAttacked & stackAttacked : bsa)
  1287. stackAttacked.applyGs(gs);
  1288. attacker->popBonuses(Bonus::UntilAttack);
  1289. }
  1290. DLL_LINKAGE void StartAction::applyGs(CGameState *gs)
  1291. {
  1292. CStack *st = gs->curB->getStack(ba.stackNumber);
  1293. if(ba.actionType == Battle::END_TACTIC_PHASE)
  1294. {
  1295. gs->curB->tacticDistance = 0;
  1296. return;
  1297. }
  1298. if(gs->curB->tacticDistance)
  1299. {
  1300. // moves in tactics phase do not affect creature status
  1301. // (tactics stack queue is managed by client)
  1302. return;
  1303. }
  1304. if(ba.actionType != Battle::HERO_SPELL) //don't check for stack if it's custom action by hero
  1305. {
  1306. assert(st);
  1307. }
  1308. else
  1309. {
  1310. gs->curB->sides[ba.side].usedSpellsHistory.push_back(SpellID(ba.additionalInfo).toSpell());
  1311. }
  1312. switch(ba.actionType)
  1313. {
  1314. case Battle::DEFEND:
  1315. st->state -= EBattleStackState::DEFENDING_ANIM;
  1316. st->state.insert(EBattleStackState::DEFENDING);
  1317. st->state.insert(EBattleStackState::DEFENDING_ANIM);
  1318. break;
  1319. case Battle::WAIT:
  1320. st->state -= EBattleStackState::DEFENDING_ANIM;
  1321. st->state.insert(EBattleStackState::WAITING);
  1322. return;
  1323. case Battle::HERO_SPELL: //no change in current stack state
  1324. return;
  1325. default: //any active stack action - attack, catapult, heal, spell...
  1326. st->state -= EBattleStackState::DEFENDING_ANIM;
  1327. st->state.insert(EBattleStackState::MOVED);
  1328. break;
  1329. }
  1330. if(st)
  1331. st->state -= EBattleStackState::WAITING; //if stack was waiting it has made move, so it won't be "waiting" anymore (if the action was WAIT, then we have returned)
  1332. }
  1333. DLL_LINKAGE void BattleSpellCast::applyGs(CGameState *gs)
  1334. {
  1335. assert(gs->curB);
  1336. const CSpell * spell = SpellID(id).toSpell();
  1337. spell->applyBattle(gs->curB, this);
  1338. }
  1339. void actualizeEffect(CStack * s, const Bonus & ef)
  1340. {
  1341. for(auto stackBonus : s->getBonusList()) //TODO: optimize
  1342. {
  1343. if(stackBonus->source == Bonus::SPELL_EFFECT && stackBonus->type == ef.type && stackBonus->subtype == ef.subtype)
  1344. {
  1345. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, ef.turnsRemain);
  1346. }
  1347. }
  1348. CBonusSystemNode::treeHasChanged();
  1349. }
  1350. void actualizeEffect(CStack * s, const std::vector<Bonus> & ef)
  1351. {
  1352. //actualizing features vector
  1353. for(const Bonus &fromEffect : ef)
  1354. {
  1355. actualizeEffect(s, fromEffect);
  1356. }
  1357. }
  1358. DLL_LINKAGE void SetStackEffect::applyGs(CGameState *gs)
  1359. {
  1360. if(effect.empty())
  1361. {
  1362. logGlobal->errorStream() << "Trying to apply SetStackEffect with no effects";
  1363. return;
  1364. }
  1365. int spellid = effect.begin()->sid; //effects' source ID
  1366. auto processEffect = [spellid, this](CStack * sta, const Bonus & effect)
  1367. {
  1368. if(!sta->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellid).And(Selector::typeSubtype(effect.type, effect.subtype)))
  1369. || spellid == SpellID::DISRUPTING_RAY || spellid == SpellID::ACID_BREATH_DEFENSE)
  1370. {
  1371. //no such effect or cumulative - add new
  1372. logBonus->traceStream() << sta->nodeName() << " receives a new bonus: " << effect.Description();
  1373. sta->addNewBonus(std::make_shared<Bonus>(effect));
  1374. }
  1375. else
  1376. actualizeEffect(sta, effect);
  1377. };
  1378. for(ui32 id : stacks)
  1379. {
  1380. CStack *s = gs->curB->getStack(id);
  1381. if(s)
  1382. for(const Bonus & fromEffect : effect)
  1383. processEffect(s, fromEffect);
  1384. else
  1385. logNetwork->errorStream() << "Cannot find stack " << id;
  1386. }
  1387. for(auto & para : uniqueBonuses)
  1388. {
  1389. CStack *s = gs->curB->getStack(para.first);
  1390. if(s)
  1391. processEffect(s, para.second);
  1392. else
  1393. logNetwork->errorStream() << "Cannot find stack " << para.first;
  1394. }
  1395. }
  1396. DLL_LINKAGE void StacksInjured::applyGs(CGameState *gs)
  1397. {
  1398. for(BattleStackAttacked stackAttacked : stacks)
  1399. stackAttacked.applyGs(gs);
  1400. }
  1401. DLL_LINKAGE void StacksHealedOrResurrected::applyGs(CGameState *gs)
  1402. {
  1403. for(auto & elem : healedStacks)
  1404. {
  1405. CStack * changedStack = gs->curB->getStack(elem.stackID, false);
  1406. //checking if we resurrect a stack that is under a living stack
  1407. auto accessibility = gs->curB->getAccesibility();
  1408. if(!changedStack->alive() && !accessibility.accessible(changedStack->position, changedStack))
  1409. {
  1410. logNetwork->errorStream() << "Cannot resurrect " << changedStack->nodeName() << " because hex " << changedStack->position << " is occupied!";
  1411. return; //position is already occupied
  1412. }
  1413. //applying changes
  1414. bool resurrected = !changedStack->alive(); //indicates if stack is resurrected or just healed
  1415. if(resurrected)
  1416. {
  1417. changedStack->state.insert(EBattleStackState::ALIVE);
  1418. }
  1419. //int missingHPfirst = changedStack->MaxHealth() - changedStack->firstHPleft;
  1420. int res = std::min(elem.healedHP / changedStack->MaxHealth() , changedStack->baseAmount - changedStack->count);
  1421. changedStack->count += res;
  1422. if(elem.lowLevelResurrection)
  1423. changedStack->resurrected += res;
  1424. changedStack->firstHPleft += elem.healedHP - res * changedStack->MaxHealth();
  1425. if(changedStack->firstHPleft > changedStack->MaxHealth())
  1426. {
  1427. changedStack->firstHPleft -= changedStack->MaxHealth();
  1428. if(changedStack->baseAmount > changedStack->count)
  1429. {
  1430. changedStack->count += 1;
  1431. }
  1432. }
  1433. vstd::amin(changedStack->firstHPleft, changedStack->MaxHealth());
  1434. if(resurrected)
  1435. {
  1436. //removing all spells effects
  1437. auto selector = [](const Bonus * b)
  1438. {
  1439. //Special case: DISRUPTING_RAY is "immune" to dispell
  1440. //Other even PERMANENT effects can be removed
  1441. if(b->source == Bonus::SPELL_EFFECT)
  1442. return b->sid != SpellID::DISRUPTING_RAY;
  1443. else
  1444. return false;
  1445. };
  1446. changedStack->popBonuses(selector);
  1447. }
  1448. else if(cure)
  1449. {
  1450. //removing all effects from negative spells
  1451. auto selector = [](const Bonus* b)
  1452. {
  1453. //Special case: DISRUPTING_RAY is "immune" to dispell
  1454. //Other even PERMANENT effects can be removed
  1455. if(b->source == Bonus::SPELL_EFFECT)
  1456. {
  1457. const CSpell * sourceSpell = SpellID(b->sid).toSpell();
  1458. if(!sourceSpell)
  1459. return false;
  1460. return sourceSpell->id != SpellID::DISRUPTING_RAY && sourceSpell->isNegative();
  1461. }
  1462. else
  1463. return false;
  1464. };
  1465. changedStack->popBonuses(selector);
  1466. }
  1467. }
  1468. }
  1469. DLL_LINKAGE void ObstaclesRemoved::applyGs(CGameState *gs)
  1470. {
  1471. if(gs->curB) //if there is a battle
  1472. {
  1473. for(const si32 rem_obst :obstacles)
  1474. {
  1475. for(int i=0; i<gs->curB->obstacles.size(); ++i)
  1476. {
  1477. if(gs->curB->obstacles[i]->uniqueID == rem_obst) //remove this obstacle
  1478. {
  1479. gs->curB->obstacles.erase(gs->curB->obstacles.begin() + i);
  1480. break;
  1481. }
  1482. }
  1483. }
  1484. }
  1485. }
  1486. DLL_LINKAGE CatapultAttack::CatapultAttack()
  1487. {
  1488. type = 3015;
  1489. }
  1490. DLL_LINKAGE CatapultAttack::~CatapultAttack()
  1491. {
  1492. }
  1493. DLL_LINKAGE void CatapultAttack::applyGs(CGameState *gs)
  1494. {
  1495. if(gs->curB && gs->curB->town && gs->curB->town->fortLevel() != CGTownInstance::NONE) //if there is a battle and it's a siege
  1496. {
  1497. for(const auto &it :attackedParts)
  1498. {
  1499. gs->curB->si.wallState[it.attackedPart] =
  1500. SiegeInfo::applyDamage(EWallState::EWallState(gs->curB->si.wallState[it.attackedPart]), it.damageDealt);
  1501. }
  1502. }
  1503. }
  1504. DLL_LINKAGE std::string CatapultAttack::AttackInfo::toString() const
  1505. {
  1506. return boost::str(boost::format("{AttackInfo: destinationTile '%d', attackedPart '%d', damageDealt '%d'}")
  1507. % destinationTile % static_cast<int>(attackedPart) % static_cast<int>(damageDealt));
  1508. }
  1509. DLL_LINKAGE std::ostream & operator<<(std::ostream & out, const CatapultAttack::AttackInfo & attackInfo)
  1510. {
  1511. return out << attackInfo.toString();
  1512. }
  1513. DLL_LINKAGE std::string CatapultAttack::toString() const
  1514. {
  1515. return boost::str(boost::format("{CatapultAttack: attackedParts '%s', attacker '%d'}") % attackedParts % attacker);
  1516. }
  1517. DLL_LINKAGE void BattleStacksRemoved::applyGs(CGameState *gs)
  1518. {
  1519. if(!gs->curB)
  1520. return;
  1521. while(!stackIDs.empty())
  1522. {
  1523. ui32 rem_stack = *stackIDs.begin();
  1524. for(int b=0; b<gs->curB->stacks.size(); ++b) //find it in vector of stacks
  1525. {
  1526. if(gs->curB->stacks[b]->ID == rem_stack) //if found
  1527. {
  1528. CStack * toRemove = gs->curB->stacks[b];
  1529. toRemove->state.erase(EBattleStackState::ALIVE);
  1530. toRemove->state.erase(EBattleStackState::GHOST_PENDING);
  1531. toRemove->state.insert(EBattleStackState::GHOST);
  1532. toRemove->detachFromAll();//TODO: may be some bonuses should remain
  1533. //stack may be removed instantly (not being killed first)
  1534. //handle clone remove also here
  1535. if(toRemove->cloneID >= 0)
  1536. {
  1537. stackIDs.insert(toRemove->cloneID);
  1538. toRemove->cloneID = -1;
  1539. }
  1540. //cleanup remaining clone links if any
  1541. for(CStack * s : gs->curB->stacks)
  1542. {
  1543. if(s->cloneID == toRemove->ID)
  1544. s->cloneID = -1;
  1545. }
  1546. break;
  1547. }
  1548. }
  1549. stackIDs.erase(rem_stack);
  1550. }
  1551. }
  1552. DLL_LINKAGE void BattleStackAdded::applyGs(CGameState *gs)
  1553. {
  1554. newStackID = 0;
  1555. if (!BattleHex(pos).isValid())
  1556. {
  1557. logNetwork->warnStream() << "No place found for new stack!";
  1558. return;
  1559. }
  1560. CStackBasicDescriptor csbd(creID, amount);
  1561. CStack * addedStack = gs->curB->generateNewStack(csbd, attacker, SlotID::SUMMONED_SLOT_PLACEHOLDER, pos); //TODO: netpacks?
  1562. if (summoned)
  1563. addedStack->state.insert(EBattleStackState::SUMMONED);
  1564. gs->curB->localInitStack(addedStack);
  1565. gs->curB->stacks.push_back(addedStack); //the stack is not "SUMMONED", it is permanent
  1566. newStackID = addedStack->ID;
  1567. }
  1568. DLL_LINKAGE void BattleSetStackProperty::applyGs(CGameState *gs)
  1569. {
  1570. CStack * stack = gs->curB->getStack(stackID);
  1571. switch (which)
  1572. {
  1573. case CASTS:
  1574. {
  1575. if (absolute)
  1576. stack->casts = val;
  1577. else
  1578. stack->casts += val;
  1579. vstd::amax(stack->casts, 0);
  1580. break;
  1581. }
  1582. case ENCHANTER_COUNTER:
  1583. {
  1584. auto & counter = gs->curB->sides[gs->curB->whatSide(stack->owner)].enchanterCounter;
  1585. if (absolute)
  1586. counter = val;
  1587. else
  1588. counter += val;
  1589. vstd::amax(counter, 0);
  1590. break;
  1591. }
  1592. case UNBIND:
  1593. {
  1594. stack->popBonuses(Selector::type(Bonus::BIND_EFFECT));
  1595. break;
  1596. }
  1597. case CLONED:
  1598. {
  1599. stack->state.insert(EBattleStackState::CLONED);
  1600. break;
  1601. }
  1602. case HAS_CLONE:
  1603. {
  1604. stack->cloneID = val;
  1605. break;
  1606. }
  1607. }
  1608. }
  1609. DLL_LINKAGE void YourTurn::applyGs(CGameState *gs)
  1610. {
  1611. gs->currentPlayer = player;
  1612. auto & playerState = gs->players[player];
  1613. playerState.daysWithoutCastle = daysWithoutCastle;
  1614. }
  1615. DLL_LINKAGE Component::Component(const CStackBasicDescriptor &stack)
  1616. : id(CREATURE), subtype(stack.type->idNumber), val(stack.count), when(0)
  1617. {
  1618. type = 2002;
  1619. }