NetPacksLib.cpp 48 KB

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