NetPacksLib.cpp 40 KB

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