NetPacksLib.cpp 48 KB

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