NetPacksLib.cpp 40 KB

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