NetPacksLib.cpp 44 KB

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