NetPacksLib.cpp 39 KB

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