NetPacksLib.cpp 43 KB

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