NetPacksLib.cpp 46 KB

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