NetPacksLib.cpp 44 KB

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