NetPacksLib.cpp 42 KB

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