NetPacksLib.cpp 47 KB

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