NetPacksLib.cpp 43 KB

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