NetPacksLib.cpp 48 KB

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