NetPacksLib.cpp 44 KB

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