2
0

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