NetPacksLib.cpp 41 KB

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