NetPacksLib.cpp 43 KB

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