NetPacksLib.cpp 43 KB

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