NetPacksLib.cpp 40 KB

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