NetPacksLib.cpp 41 KB

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