NetPacksLib.cpp 44 KB

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