NetPacksLib.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835
  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. bool found = false;
  852. for(auto& p : aset->artifactsWorn)
  853. {
  854. auto art = p.second.artifact;
  855. if(art->canBeDisassembled() && art->isPart(slot->artifact))
  856. {
  857. dis.al.slot = aset->getArtPos(art);
  858. found = true;
  859. break;
  860. }
  861. }
  862. assert(found && "Failed to determine the assembly this locked artifact belongs to");
  863. logGlobal->debugStream() << "Found the corresponding assembly: " << dis.al.getSlot()->artifact->artType->Name();
  864. dis.applyGs(gs);
  865. }
  866. else
  867. {
  868. logGlobal->debugStream() << "Erasing artifact " << slot->artifact->artType->Name();
  869. }
  870. al.removeArtifact();
  871. }
  872. DLL_LINKAGE void MoveArtifact::applyGs(CGameState *gs)
  873. {
  874. CArtifactInstance *a = src.getArt();
  875. if(dst.slot < GameConstants::BACKPACK_START)
  876. assert(!dst.getArt());
  877. a->move(src, dst);
  878. //TODO what'll happen if Titan's thunder is equipped by pickin git up or the start of game?
  879. if (a->artType->id == ArtifactID::TITANS_THUNDER && dst.slot == ArtifactPosition::RIGHT_HAND) //Titan's Thunder creates new spellbook on equip
  880. {
  881. auto hPtr = boost::get<ConstTransitivePtr<CGHeroInstance> >(&dst.artHolder);
  882. if(hPtr)
  883. {
  884. CGHeroInstance *h = *hPtr;
  885. if(h && !h->hasSpellbook())
  886. gs->giveHeroArtifact(h, ArtifactID::SPELLBOOK);
  887. }
  888. }
  889. }
  890. DLL_LINKAGE void AssembledArtifact::applyGs(CGameState *gs)
  891. {
  892. CArtifactSet *artSet = al.getHolderArtSet();
  893. const CArtifactInstance *transformedArt = al.getArt();
  894. assert(transformedArt);
  895. assert(vstd::contains(transformedArt->assemblyPossibilities(artSet), builtArt));
  896. UNUSED(transformedArt);
  897. auto combinedArt = new CCombinedArtifactInstance(builtArt);
  898. gs->map->addNewArtifactInstance(combinedArt);
  899. //retrieve all constituents
  900. for(const CArtifact * constituent : *builtArt->constituents)
  901. {
  902. ArtifactPosition pos = artSet->getArtPos(constituent->id);
  903. assert(pos >= 0);
  904. CArtifactInstance *constituentInstance = artSet->getArt(pos);
  905. //move constituent from hero to be part of new, combined artifact
  906. constituentInstance->removeFrom(ArtifactLocation(al.artHolder, pos));
  907. combinedArt->addAsConstituent(constituentInstance, pos);
  908. if(!vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], al.slot) && vstd::contains(combinedArt->artType->possibleSlots[artSet->bearerType()], pos))
  909. al.slot = pos;
  910. }
  911. //put new combined artifacts
  912. combinedArt->putAt(al);
  913. }
  914. DLL_LINKAGE void DisassembledArtifact::applyGs(CGameState *gs)
  915. {
  916. CCombinedArtifactInstance *disassembled = dynamic_cast<CCombinedArtifactInstance*>(al.getArt());
  917. assert(disassembled);
  918. std::vector<CCombinedArtifactInstance::ConstituentInfo> constituents = disassembled->constituentsInfo;
  919. disassembled->removeFrom(al);
  920. for(CCombinedArtifactInstance::ConstituentInfo &ci : constituents)
  921. {
  922. ArtifactLocation constituentLoc = al;
  923. constituentLoc.slot = (ci.slot >= 0 ? ci.slot : al.slot); //-1 is slot of main constituent -> it'll replace combined artifact in its pos
  924. disassembled->detachFrom(ci.art);
  925. ci.art->putAt(constituentLoc);
  926. }
  927. gs->map->eraseArtifactInstance(disassembled);
  928. }
  929. DLL_LINKAGE void HeroVisit::applyGs(CGameState *gs)
  930. {
  931. }
  932. DLL_LINKAGE void SetAvailableArtifacts::applyGs(CGameState *gs)
  933. {
  934. if(id >= 0)
  935. {
  936. if(CGBlackMarket *bm = dynamic_cast<CGBlackMarket*>(gs->map->objects[id].get()))
  937. {
  938. bm->artifacts = arts;
  939. }
  940. else
  941. {
  942. logNetwork->errorStream() << "Wrong black market id!";
  943. }
  944. }
  945. else
  946. {
  947. CGTownInstance::merchantArtifacts = arts;
  948. }
  949. }
  950. DLL_LINKAGE void NewTurn::applyGs(CGameState *gs)
  951. {
  952. gs->day = day;
  953. // Update bonuses before doing anything else so hero don't get more MP than needed
  954. gs->globalEffects.popBonuses(Bonus::OneDay); //works for children -> all game objs
  955. gs->globalEffects.updateBonuses(Bonus::NDays);
  956. gs->globalEffects.updateBonuses(Bonus::OneWeek);
  957. //TODO not really a single root hierarchy, what about bonuses placed elsewhere? [not an issue with H3 mechanics but in the future...]
  958. for(NewTurn::Hero h : heroes) //give mana/movement point
  959. {
  960. CGHeroInstance *hero = gs->getHero(h.id);
  961. if(!hero)
  962. {
  963. // retreated or surrendered hero who has not been reset yet
  964. for(auto& hp : gs->hpool.heroesPool)
  965. {
  966. if(hp.second->id == h.id)
  967. {
  968. hero = hp.second;
  969. break;
  970. }
  971. }
  972. }
  973. if(!hero)
  974. {
  975. logGlobal->errorStream() << "Hero " << h.id << " not found in NewTurn::applyGs";
  976. continue;
  977. }
  978. hero->movement = h.move;
  979. hero->mana = h.mana;
  980. }
  981. for(auto i = res.cbegin(); i != res.cend(); i++)
  982. {
  983. assert(i->first < PlayerColor::PLAYER_LIMIT);
  984. gs->getPlayer(i->first)->resources = i->second;
  985. }
  986. for(auto creatureSet : cres) //set available creatures in towns
  987. creatureSet.second.applyGs(gs);
  988. for(CGTownInstance* t : gs->map->towns)
  989. t->builded = 0;
  990. if(gs->getDate(Date::DAY_OF_WEEK) == 1)
  991. gs->updateRumor();
  992. //count days without town for all players, regardless of their turn order
  993. for (auto &p : gs->players)
  994. {
  995. PlayerState & playerState = p.second;
  996. if (playerState.status == EPlayerStatus::INGAME)
  997. {
  998. if (playerState.towns.empty())
  999. {
  1000. if (playerState.daysWithoutCastle)
  1001. ++(*playerState.daysWithoutCastle);
  1002. else playerState.daysWithoutCastle = 0;
  1003. }
  1004. else
  1005. {
  1006. playerState.daysWithoutCastle = boost::none;
  1007. }
  1008. }
  1009. }
  1010. }
  1011. DLL_LINKAGE void SetObjectProperty::applyGs(CGameState *gs)
  1012. {
  1013. CGObjectInstance *obj = gs->getObjInstance(id);
  1014. if(!obj)
  1015. {
  1016. logNetwork->errorStream() << "Wrong object ID - property cannot be set!";
  1017. return;
  1018. }
  1019. CArmedInstance *cai = dynamic_cast<CArmedInstance *>(obj);
  1020. if(what == ObjProperty::OWNER && cai)
  1021. {
  1022. if(obj->ID == Obj::TOWN)
  1023. {
  1024. CGTownInstance *t = static_cast<CGTownInstance*>(obj);
  1025. if(t->tempOwner < PlayerColor::PLAYER_LIMIT)
  1026. gs->getPlayer(t->tempOwner)->towns -= t;
  1027. if(val < PlayerColor::PLAYER_LIMIT_I)
  1028. {
  1029. PlayerState * p = gs->getPlayer(PlayerColor(val));
  1030. p->towns.push_back(t);
  1031. //reset counter before NewTurn to avoid no town message if game loaded at turn when one already captured
  1032. if(p->daysWithoutCastle)
  1033. p->daysWithoutCastle = boost::none;
  1034. }
  1035. }
  1036. CBonusSystemNode *nodeToMove = cai->whatShouldBeAttached();
  1037. nodeToMove->detachFrom(cai->whereShouldBeAttached(gs));
  1038. obj->setProperty(what,val);
  1039. nodeToMove->attachTo(cai->whereShouldBeAttached(gs));
  1040. }
  1041. else //not an armed instance
  1042. {
  1043. obj->setProperty(what,val);
  1044. }
  1045. }
  1046. DLL_LINKAGE void PrepareHeroLevelUp::applyGs(CGameState *gs)
  1047. {
  1048. CGHeroInstance * h = gs->getHero(hero->id);
  1049. auto proposedSkills = h->getLevelUpProposedSecondarySkills();
  1050. if(skills.size() == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  1051. {
  1052. skills.push_back(*RandomGeneratorUtil::nextItem(proposedSkills, h->skillsInfo.rand));
  1053. }
  1054. else
  1055. {
  1056. skills = proposedSkills;
  1057. }
  1058. }
  1059. DLL_LINKAGE void HeroLevelUp::applyGs(CGameState *gs)
  1060. {
  1061. CGHeroInstance * h = gs->getHero(hero->id);
  1062. h->levelUp(skills);
  1063. }
  1064. DLL_LINKAGE void CommanderLevelUp::applyGs (CGameState *gs)
  1065. {
  1066. CCommanderInstance * commander = gs->getHero(hero->id)->commander;
  1067. assert (commander);
  1068. commander->levelUp();
  1069. }
  1070. DLL_LINKAGE void BattleStart::applyGs(CGameState *gs)
  1071. {
  1072. gs->curB = info;
  1073. gs->curB->localInit();
  1074. }
  1075. DLL_LINKAGE void BattleNextRound::applyGs(CGameState *gs)
  1076. {
  1077. for (int i = 0; i < 2; ++i)
  1078. {
  1079. gs->curB->sides[i].castSpellsCount = 0;
  1080. vstd::amax(--gs->curB->sides[i].enchanterCounter, 0);
  1081. }
  1082. gs->curB->round = round;
  1083. for(CStack *s : gs->curB->stacks)
  1084. {
  1085. s->state -= EBattleStackState::DEFENDING;
  1086. s->state -= EBattleStackState::WAITING;
  1087. s->state -= EBattleStackState::MOVED;
  1088. s->state -= EBattleStackState::HAD_MORALE;
  1089. s->state -= EBattleStackState::FEAR;
  1090. s->state -= EBattleStackState::DRAINED_MANA;
  1091. s->counterAttacksPerformed = 0;
  1092. s->counterAttacksTotalCache = 0;
  1093. // new turn effects
  1094. s->updateBonuses(Bonus::NTurns);
  1095. if(s->alive() && vstd::contains(s->state, EBattleStackState::CLONED))
  1096. {
  1097. //cloned stack has special lifetime marker
  1098. //check it after bonuses updated in battleTurnPassed()
  1099. if(!s->hasBonus(Selector::type(Bonus::NONE).And(Selector::source(Bonus::SPELL_EFFECT, SpellID::CLONE))))
  1100. s->makeGhost();
  1101. }
  1102. }
  1103. for(auto &obst : gs->curB->obstacles)
  1104. obst->battleTurnPassed();
  1105. }
  1106. DLL_LINKAGE void BattleSetActiveStack::applyGs(CGameState *gs)
  1107. {
  1108. gs->curB->activeStack = stack;
  1109. CStack *st = gs->curB->getStack(stack);
  1110. //remove bonuses that last until when stack gets new turn
  1111. st->popBonuses(Bonus::UntilGetsTurn);
  1112. if(vstd::contains(st->state,EBattleStackState::MOVED)) //if stack is moving second time this turn it must had a high morale bonus
  1113. st->state.insert(EBattleStackState::HAD_MORALE);
  1114. }
  1115. DLL_LINKAGE void BattleTriggerEffect::applyGs(CGameState *gs)
  1116. {
  1117. CStack *st = gs->curB->getStack(stackID);
  1118. switch (effect)
  1119. {
  1120. case Bonus::HP_REGENERATION:
  1121. st->firstHPleft += val;
  1122. vstd::amin (st->firstHPleft, (ui32)st->MaxHealth());
  1123. break;
  1124. case Bonus::MANA_DRAIN:
  1125. {
  1126. CGHeroInstance * h = gs->getHero(ObjectInstanceID(additionalInfo));
  1127. st->state.insert (EBattleStackState::DRAINED_MANA);
  1128. h->mana -= val;
  1129. vstd::amax(h->mana, 0);
  1130. break;
  1131. }
  1132. case Bonus::POISON:
  1133. {
  1134. auto b = st->getBonusLocalFirst(Selector::source(Bonus::SPELL_EFFECT, SpellID::POISON)
  1135. .And(Selector::type(Bonus::STACK_HEALTH)));
  1136. if (b)
  1137. b->val = val;
  1138. break;
  1139. }
  1140. case Bonus::ENCHANTER:
  1141. break;
  1142. case Bonus::FEAR:
  1143. st->state.insert(EBattleStackState::FEAR);
  1144. break;
  1145. default:
  1146. logNetwork->warnStream() << "Unrecognized trigger effect type "<< type;
  1147. }
  1148. }
  1149. DLL_LINKAGE void BattleObstaclePlaced::applyGs(CGameState *gs)
  1150. {
  1151. gs->curB->obstacles.push_back(obstacle);
  1152. }
  1153. DLL_LINKAGE void BattleUpdateGateState::applyGs(CGameState *gs)
  1154. {
  1155. if(gs->curB)
  1156. gs->curB->si.gateState = state;
  1157. }
  1158. void BattleResult::applyGs(CGameState *gs)
  1159. {
  1160. for (CStack *s : gs->curB->stacks)
  1161. {
  1162. if (s->base && s->base->armyObj && vstd::contains(s->state, EBattleStackState::SUMMONED))
  1163. {
  1164. //stack with SUMMONED flag but coming from garrison -> most likely resurrected, needs to be removed
  1165. assert(&s->base->armyObj->getStack(s->slot) == s->base);
  1166. const_cast<CArmedInstance*>(s->base->armyObj)->eraseStack(s->slot);
  1167. }
  1168. }
  1169. for (auto & elem : gs->curB->stacks)
  1170. delete elem;
  1171. for(int i = 0; i < 2; ++i)
  1172. {
  1173. if(auto h = gs->curB->battleGetFightingHero(i))
  1174. {
  1175. h->popBonuses(Bonus::OneBattle); //remove any "until next battle" bonuses
  1176. if (h->commander && h->commander->alive)
  1177. {
  1178. for (auto art : h->commander->artifactsWorn) //increment bonuses for commander artifacts
  1179. {
  1180. art.second.artifact->artType->levelUpArtifact (art.second.artifact);
  1181. }
  1182. }
  1183. }
  1184. }
  1185. if(VLC->modh->modules.STACK_EXP)
  1186. {
  1187. for(int i = 0; i < 2; i++)
  1188. if(exp[i])
  1189. gs->curB->battleGetArmyObject(i)->giveStackExp(exp[i]);
  1190. CBonusSystemNode::treeHasChanged();
  1191. }
  1192. for(int i = 0; i < 2; i++)
  1193. gs->curB->battleGetArmyObject(i)->battle = nullptr;
  1194. gs->curB.dellNull();
  1195. }
  1196. void BattleStackMoved::applyGs(CGameState *gs)
  1197. {
  1198. CStack *s = gs->curB->getStack(stack);
  1199. assert(s);
  1200. BattleHex dest = tilesToMove.back();
  1201. //if unit ended movement on quicksands that were created by enemy, that quicksand patch becomes visible for owner
  1202. for(auto &oi : gs->curB->obstacles)
  1203. {
  1204. if(oi->obstacleType == CObstacleInstance::QUICKSAND
  1205. && vstd::contains(oi->getAffectedTiles(), tilesToMove.back()))
  1206. {
  1207. SpellCreatedObstacle *sands = dynamic_cast<SpellCreatedObstacle*>(oi.get());
  1208. assert(sands);
  1209. if(sands->casterSide != !s->attackerOwned)
  1210. sands->visibleForAnotherSide = true;
  1211. }
  1212. }
  1213. s->position = dest;
  1214. }
  1215. DLL_LINKAGE void BattleStackAttacked::applyGs(CGameState *gs)
  1216. {
  1217. CStack *at = gs->curB->getStack(stackAttacked);
  1218. assert(at);
  1219. at->popBonuses(Bonus::UntilBeingAttacked);
  1220. at->count = newAmount;
  1221. at->firstHPleft = newHP;
  1222. if(killed())
  1223. {
  1224. at->state -= EBattleStackState::ALIVE;
  1225. if(at->cloneID >= 0)
  1226. {
  1227. //remove clone as well
  1228. CStack * clone = gs->curB->getStack(at->cloneID);
  1229. if(clone)
  1230. clone->makeGhost();
  1231. at->cloneID = -1;
  1232. }
  1233. }
  1234. //life drain handling
  1235. for (auto & elem : healedStacks)
  1236. {
  1237. elem.applyGs(gs);
  1238. }
  1239. if (willRebirth())
  1240. {
  1241. at->casts--;
  1242. at->state.insert(EBattleStackState::ALIVE); //hmm?
  1243. }
  1244. if (cloneKilled())
  1245. {
  1246. //"hide" killed creatures instead so we keep info about it
  1247. at->makeGhost();
  1248. for(CStack * s : gs->curB->stacks)
  1249. {
  1250. if(s->cloneID == at->ID)
  1251. s->cloneID = -1;
  1252. }
  1253. }
  1254. //killed summoned creature should be removed like clone
  1255. if(killed() && vstd::contains(at->state, EBattleStackState::SUMMONED))
  1256. {
  1257. at->makeGhost();
  1258. }
  1259. }
  1260. DLL_LINKAGE void BattleAttack::applyGs(CGameState *gs)
  1261. {
  1262. CStack *attacker = gs->curB->getStack(stackAttacking);
  1263. if(counter())
  1264. attacker->counterAttacksPerformed++;
  1265. if(shot())
  1266. {
  1267. //don't remove ammo if we have a working ammo cart
  1268. bool hasAmmoCart = false;
  1269. for(const CStack * st : gs->curB->stacks)
  1270. {
  1271. if(st->owner == attacker->owner && st->getCreature()->idNumber == CreatureID::AMMO_CART && st->alive())
  1272. {
  1273. hasAmmoCart = true;
  1274. break;
  1275. }
  1276. }
  1277. if (!hasAmmoCart)
  1278. {
  1279. attacker->shots--;
  1280. }
  1281. }
  1282. for(BattleStackAttacked & stackAttacked : bsa)
  1283. stackAttacked.applyGs(gs);
  1284. attacker->popBonuses(Bonus::UntilAttack);
  1285. }
  1286. DLL_LINKAGE void StartAction::applyGs(CGameState *gs)
  1287. {
  1288. CStack *st = gs->curB->getStack(ba.stackNumber);
  1289. if(ba.actionType == Battle::END_TACTIC_PHASE)
  1290. {
  1291. gs->curB->tacticDistance = 0;
  1292. return;
  1293. }
  1294. if(gs->curB->tacticDistance)
  1295. {
  1296. // moves in tactics phase do not affect creature status
  1297. // (tactics stack queue is managed by client)
  1298. return;
  1299. }
  1300. if(ba.actionType != Battle::HERO_SPELL) //don't check for stack if it's custom action by hero
  1301. {
  1302. assert(st);
  1303. }
  1304. else
  1305. {
  1306. gs->curB->sides[ba.side].usedSpellsHistory.push_back(SpellID(ba.additionalInfo).toSpell());
  1307. }
  1308. switch(ba.actionType)
  1309. {
  1310. case Battle::DEFEND:
  1311. st->state -= EBattleStackState::DEFENDING_ANIM;
  1312. st->state.insert(EBattleStackState::DEFENDING);
  1313. st->state.insert(EBattleStackState::DEFENDING_ANIM);
  1314. break;
  1315. case Battle::WAIT:
  1316. st->state -= EBattleStackState::DEFENDING_ANIM;
  1317. st->state.insert(EBattleStackState::WAITING);
  1318. return;
  1319. case Battle::HERO_SPELL: //no change in current stack state
  1320. return;
  1321. default: //any active stack action - attack, catapult, heal, spell...
  1322. st->state -= EBattleStackState::DEFENDING_ANIM;
  1323. st->state.insert(EBattleStackState::MOVED);
  1324. break;
  1325. }
  1326. if(st)
  1327. 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)
  1328. }
  1329. DLL_LINKAGE void BattleSpellCast::applyGs(CGameState *gs)
  1330. {
  1331. assert(gs->curB);
  1332. const CSpell * spell = SpellID(id).toSpell();
  1333. spell->applyBattle(gs->curB, this);
  1334. }
  1335. void actualizeEffect(CStack * s, const Bonus & ef)
  1336. {
  1337. for(auto stackBonus : s->getBonusList()) //TODO: optimize
  1338. {
  1339. if(stackBonus->source == Bonus::SPELL_EFFECT && stackBonus->type == ef.type && stackBonus->subtype == ef.subtype)
  1340. {
  1341. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, ef.turnsRemain);
  1342. }
  1343. }
  1344. CBonusSystemNode::treeHasChanged();
  1345. }
  1346. void actualizeEffect(CStack * s, const std::vector<Bonus> & ef)
  1347. {
  1348. //actualizing features vector
  1349. for(const Bonus &fromEffect : ef)
  1350. {
  1351. actualizeEffect(s, fromEffect);
  1352. }
  1353. }
  1354. DLL_LINKAGE void SetStackEffect::applyGs(CGameState *gs)
  1355. {
  1356. if(effect.empty())
  1357. {
  1358. logGlobal->errorStream() << "Trying to apply SetStackEffect with no effects";
  1359. return;
  1360. }
  1361. int spellid = effect.begin()->sid; //effects' source ID
  1362. auto processEffect = [spellid, this](CStack * sta, const Bonus & effect)
  1363. {
  1364. if(!sta->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellid).And(Selector::typeSubtype(effect.type, effect.subtype)))
  1365. || spellid == SpellID::DISRUPTING_RAY || spellid == SpellID::ACID_BREATH_DEFENSE)
  1366. {
  1367. //no such effect or cumulative - add new
  1368. logBonus->traceStream() << sta->nodeName() << " receives a new bonus: " << effect.Description();
  1369. sta->addNewBonus(std::make_shared<Bonus>(effect));
  1370. }
  1371. else
  1372. actualizeEffect(sta, effect);
  1373. };
  1374. for(ui32 id : stacks)
  1375. {
  1376. CStack *s = gs->curB->getStack(id);
  1377. if(s)
  1378. for(const Bonus & fromEffect : effect)
  1379. processEffect(s, fromEffect);
  1380. else
  1381. logNetwork->errorStream() << "Cannot find stack " << id;
  1382. }
  1383. for(auto & para : uniqueBonuses)
  1384. {
  1385. CStack *s = gs->curB->getStack(para.first);
  1386. if(s)
  1387. processEffect(s, para.second);
  1388. else
  1389. logNetwork->errorStream() << "Cannot find stack " << para.first;
  1390. }
  1391. }
  1392. DLL_LINKAGE void StacksInjured::applyGs(CGameState *gs)
  1393. {
  1394. for(BattleStackAttacked stackAttacked : stacks)
  1395. stackAttacked.applyGs(gs);
  1396. }
  1397. DLL_LINKAGE void StacksHealedOrResurrected::applyGs(CGameState *gs)
  1398. {
  1399. for(auto & elem : healedStacks)
  1400. {
  1401. CStack * changedStack = gs->curB->getStack(elem.stackID, false);
  1402. //checking if we resurrect a stack that is under a living stack
  1403. auto accessibility = gs->curB->getAccesibility();
  1404. if(!changedStack->alive() && !accessibility.accessible(changedStack->position, changedStack))
  1405. {
  1406. logNetwork->errorStream() << "Cannot resurrect " << changedStack->nodeName() << " because hex " << changedStack->position << " is occupied!";
  1407. return; //position is already occupied
  1408. }
  1409. //applying changes
  1410. bool resurrected = !changedStack->alive(); //indicates if stack is resurrected or just healed
  1411. if(resurrected)
  1412. {
  1413. changedStack->state.insert(EBattleStackState::ALIVE);
  1414. }
  1415. //int missingHPfirst = changedStack->MaxHealth() - changedStack->firstHPleft;
  1416. int res = std::min(elem.healedHP / changedStack->MaxHealth() , changedStack->baseAmount - changedStack->count);
  1417. changedStack->count += res;
  1418. if(elem.lowLevelResurrection)
  1419. changedStack->resurrected += res;
  1420. changedStack->firstHPleft += elem.healedHP - res * changedStack->MaxHealth();
  1421. if(changedStack->firstHPleft > changedStack->MaxHealth())
  1422. {
  1423. changedStack->firstHPleft -= changedStack->MaxHealth();
  1424. if(changedStack->baseAmount > changedStack->count)
  1425. {
  1426. changedStack->count += 1;
  1427. }
  1428. }
  1429. vstd::amin(changedStack->firstHPleft, changedStack->MaxHealth());
  1430. if(resurrected)
  1431. {
  1432. //removing all spells effects
  1433. auto selector = [](const Bonus * b)
  1434. {
  1435. //Special case: DISRUPTING_RAY is "immune" to dispell
  1436. //Other even PERMANENT effects can be removed
  1437. if(b->source == Bonus::SPELL_EFFECT)
  1438. return b->sid != SpellID::DISRUPTING_RAY;
  1439. else
  1440. return false;
  1441. };
  1442. changedStack->popBonuses(selector);
  1443. }
  1444. else if(cure)
  1445. {
  1446. //removing all effects from negative spells
  1447. auto selector = [](const Bonus* b)
  1448. {
  1449. //Special case: DISRUPTING_RAY is "immune" to dispell
  1450. //Other even PERMANENT effects can be removed
  1451. if(b->source == Bonus::SPELL_EFFECT)
  1452. {
  1453. const CSpell * sourceSpell = SpellID(b->sid).toSpell();
  1454. if(!sourceSpell)
  1455. return false;
  1456. return sourceSpell->id != SpellID::DISRUPTING_RAY && sourceSpell->isNegative();
  1457. }
  1458. else
  1459. return false;
  1460. };
  1461. changedStack->popBonuses(selector);
  1462. }
  1463. }
  1464. }
  1465. DLL_LINKAGE void ObstaclesRemoved::applyGs(CGameState *gs)
  1466. {
  1467. if(gs->curB) //if there is a battle
  1468. {
  1469. for(const si32 rem_obst :obstacles)
  1470. {
  1471. for(int i=0; i<gs->curB->obstacles.size(); ++i)
  1472. {
  1473. if(gs->curB->obstacles[i]->uniqueID == rem_obst) //remove this obstacle
  1474. {
  1475. gs->curB->obstacles.erase(gs->curB->obstacles.begin() + i);
  1476. break;
  1477. }
  1478. }
  1479. }
  1480. }
  1481. }
  1482. DLL_LINKAGE CatapultAttack::CatapultAttack()
  1483. {
  1484. type = 3015;
  1485. }
  1486. DLL_LINKAGE CatapultAttack::~CatapultAttack()
  1487. {
  1488. }
  1489. DLL_LINKAGE void CatapultAttack::applyGs(CGameState *gs)
  1490. {
  1491. if(gs->curB && gs->curB->town && gs->curB->town->fortLevel() != CGTownInstance::NONE) //if there is a battle and it's a siege
  1492. {
  1493. for(const auto &it :attackedParts)
  1494. {
  1495. gs->curB->si.wallState[it.attackedPart] =
  1496. SiegeInfo::applyDamage(EWallState::EWallState(gs->curB->si.wallState[it.attackedPart]), it.damageDealt);
  1497. }
  1498. }
  1499. }
  1500. DLL_LINKAGE std::string CatapultAttack::AttackInfo::toString() const
  1501. {
  1502. return boost::str(boost::format("{AttackInfo: destinationTile '%d', attackedPart '%d', damageDealt '%d'}")
  1503. % destinationTile % static_cast<int>(attackedPart) % static_cast<int>(damageDealt));
  1504. }
  1505. DLL_LINKAGE std::ostream & operator<<(std::ostream & out, const CatapultAttack::AttackInfo & attackInfo)
  1506. {
  1507. return out << attackInfo.toString();
  1508. }
  1509. DLL_LINKAGE std::string CatapultAttack::toString() const
  1510. {
  1511. return boost::str(boost::format("{CatapultAttack: attackedParts '%s', attacker '%d'}") % attackedParts % attacker);
  1512. }
  1513. DLL_LINKAGE void BattleStacksRemoved::applyGs(CGameState *gs)
  1514. {
  1515. if(!gs->curB)
  1516. return;
  1517. while(!stackIDs.empty())
  1518. {
  1519. ui32 rem_stack = *stackIDs.begin();
  1520. for(int b=0; b<gs->curB->stacks.size(); ++b) //find it in vector of stacks
  1521. {
  1522. if(gs->curB->stacks[b]->ID == rem_stack) //if found
  1523. {
  1524. CStack * toRemove = gs->curB->stacks[b];
  1525. toRemove->state.erase(EBattleStackState::ALIVE);
  1526. toRemove->state.erase(EBattleStackState::GHOST_PENDING);
  1527. toRemove->state.insert(EBattleStackState::GHOST);
  1528. toRemove->detachFromAll();//TODO: may be some bonuses should remain
  1529. //stack may be removed instantly (not being killed first)
  1530. //handle clone remove also here
  1531. if(toRemove->cloneID >= 0)
  1532. {
  1533. stackIDs.insert(toRemove->cloneID);
  1534. toRemove->cloneID = -1;
  1535. }
  1536. //cleanup remaining clone links if any
  1537. for(CStack * s : gs->curB->stacks)
  1538. {
  1539. if(s->cloneID == toRemove->ID)
  1540. s->cloneID = -1;
  1541. }
  1542. break;
  1543. }
  1544. }
  1545. stackIDs.erase(rem_stack);
  1546. }
  1547. }
  1548. DLL_LINKAGE void BattleStackAdded::applyGs(CGameState *gs)
  1549. {
  1550. newStackID = 0;
  1551. if (!BattleHex(pos).isValid())
  1552. {
  1553. logNetwork->warnStream() << "No place found for new stack!";
  1554. return;
  1555. }
  1556. CStackBasicDescriptor csbd(creID, amount);
  1557. CStack * addedStack = gs->curB->generateNewStack(csbd, attacker, SlotID::SUMMONED_SLOT_PLACEHOLDER, pos); //TODO: netpacks?
  1558. if (summoned)
  1559. addedStack->state.insert(EBattleStackState::SUMMONED);
  1560. gs->curB->localInitStack(addedStack);
  1561. gs->curB->stacks.push_back(addedStack); //the stack is not "SUMMONED", it is permanent
  1562. newStackID = addedStack->ID;
  1563. }
  1564. DLL_LINKAGE void BattleSetStackProperty::applyGs(CGameState *gs)
  1565. {
  1566. CStack * stack = gs->curB->getStack(stackID);
  1567. switch (which)
  1568. {
  1569. case CASTS:
  1570. {
  1571. if (absolute)
  1572. stack->casts = val;
  1573. else
  1574. stack->casts += val;
  1575. vstd::amax(stack->casts, 0);
  1576. break;
  1577. }
  1578. case ENCHANTER_COUNTER:
  1579. {
  1580. auto & counter = gs->curB->sides[gs->curB->whatSide(stack->owner)].enchanterCounter;
  1581. if (absolute)
  1582. counter = val;
  1583. else
  1584. counter += val;
  1585. vstd::amax(counter, 0);
  1586. break;
  1587. }
  1588. case UNBIND:
  1589. {
  1590. stack->popBonuses(Selector::type(Bonus::BIND_EFFECT));
  1591. break;
  1592. }
  1593. case CLONED:
  1594. {
  1595. stack->state.insert(EBattleStackState::CLONED);
  1596. break;
  1597. }
  1598. case HAS_CLONE:
  1599. {
  1600. stack->cloneID = val;
  1601. break;
  1602. }
  1603. }
  1604. }
  1605. DLL_LINKAGE void YourTurn::applyGs(CGameState *gs)
  1606. {
  1607. gs->currentPlayer = player;
  1608. auto & playerState = gs->players[player];
  1609. playerState.daysWithoutCastle = daysWithoutCastle;
  1610. }
  1611. DLL_LINKAGE Component::Component(const CStackBasicDescriptor &stack)
  1612. : id(CREATURE), subtype(stack.type->idNumber), val(stack.count), when(0)
  1613. {
  1614. type = 2002;
  1615. }