NetPacksLib.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  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. std::ostream & operator<<(std::ostream & out, const CPack * pack)
  32. {
  33. return out << (pack? pack->toString() : "<nullptr>");
  34. }
  35. DLL_LINKAGE void SetResources::applyGs(CGameState *gs)
  36. {
  37. assert(player < PlayerColor::PLAYER_LIMIT);
  38. if(abs)
  39. gs->getPlayer(player)->resources = res;
  40. else
  41. gs->getPlayer(player)->resources += res;
  42. //just ensure that player resources are not negative
  43. //server is responsible to check if player can afford deal
  44. //but events on server side are allowed to take more than player have
  45. gs->getPlayer(player)->resources.positive();
  46. }
  47. DLL_LINKAGE void SetPrimSkill::applyGs(CGameState *gs)
  48. {
  49. CGHeroInstance * hero = gs->getHero(id);
  50. assert(hero);
  51. hero->setPrimarySkill(which, val, abs);
  52. }
  53. DLL_LINKAGE void SetSecSkill::applyGs(CGameState *gs)
  54. {
  55. CGHeroInstance *hero = gs->getHero(id);
  56. hero->setSecSkillLevel(which, val, abs);
  57. }
  58. DLL_LINKAGE SelectMap::SelectMap(const CMapInfo &src)
  59. {
  60. mapInfo = &src;
  61. free = false;
  62. }
  63. DLL_LINKAGE SelectMap::SelectMap()
  64. {
  65. mapInfo = nullptr;
  66. free = true;
  67. }
  68. DLL_LINKAGE SelectMap::~SelectMap()
  69. {
  70. if(free)
  71. delete mapInfo;
  72. }
  73. DLL_LINKAGE UpdateStartOptions::UpdateStartOptions(StartInfo &src)
  74. {
  75. options = &src;
  76. free = false;
  77. }
  78. DLL_LINKAGE UpdateStartOptions::UpdateStartOptions()
  79. {
  80. options = nullptr;
  81. free = true;
  82. }
  83. DLL_LINKAGE UpdateStartOptions::~UpdateStartOptions()
  84. {
  85. if(free)
  86. delete options;
  87. }
  88. DLL_LINKAGE void SetCommanderProperty::applyGs(CGameState *gs)
  89. {
  90. CCommanderInstance * commander = gs->getHero(heroid)->commander;
  91. assert (commander);
  92. switch (which)
  93. {
  94. case BONUS:
  95. commander->accumulateBonus (std::make_shared<Bonus>(accumulatedBonus));
  96. break;
  97. case SPECIAL_SKILL:
  98. commander->accumulateBonus (std::make_shared<Bonus>(accumulatedBonus));
  99. commander->specialSKills.insert (additionalInfo);
  100. break;
  101. case SECONDARY_SKILL:
  102. commander->secondarySkills[additionalInfo] = amount;
  103. break;
  104. case ALIVE:
  105. if (amount)
  106. commander->setAlive(true);
  107. else
  108. commander->setAlive(false);
  109. break;
  110. case EXPERIENCE:
  111. commander->giveStackExp(amount); //TODO: allow setting exp for stacks via netpacks
  112. break;
  113. }
  114. }
  115. DLL_LINKAGE void AddQuest::applyGs(CGameState *gs)
  116. {
  117. assert (vstd::contains(gs->players, player));
  118. auto vec = &gs->players[player].quests;
  119. if (!vstd::contains(*vec, quest))
  120. vec->push_back (quest);
  121. else
  122. logNetwork->warn("Warning! Attempt to add duplicated quest");
  123. }
  124. DLL_LINKAGE void UpdateArtHandlerLists::applyGs(CGameState *gs)
  125. {
  126. VLC->arth->minors = minors;
  127. VLC->arth->majors = majors;
  128. VLC->arth->treasures = treasures;
  129. VLC->arth->relics = relics;
  130. }
  131. DLL_LINKAGE void UpdateMapEvents::applyGs(CGameState *gs)
  132. {
  133. gs->map->events = events;
  134. }
  135. DLL_LINKAGE void UpdateCastleEvents::applyGs(CGameState *gs)
  136. {
  137. auto t = gs->getTown(town);
  138. t->events = events;
  139. }
  140. DLL_LINKAGE void ChangeFormation::applyGs(CGameState *gs)
  141. {
  142. gs->getHero(hid)->setFormation(formation);
  143. }
  144. DLL_LINKAGE void HeroVisitCastle::applyGs(CGameState *gs)
  145. {
  146. CGHeroInstance *h = gs->getHero(hid);
  147. CGTownInstance *t = gs->getTown(tid);
  148. assert(h);
  149. assert(t);
  150. if(start())
  151. t->setVisitingHero(h);
  152. else
  153. t->setVisitingHero(nullptr);
  154. }
  155. DLL_LINKAGE void ChangeSpells::applyGs(CGameState *gs)
  156. {
  157. CGHeroInstance *hero = gs->getHero(hid);
  158. if(learn)
  159. for(auto sid : spells)
  160. hero->spells.insert(sid);
  161. else
  162. for(auto sid : spells)
  163. hero->spells.erase(sid);
  164. }
  165. DLL_LINKAGE void SetMana::applyGs(CGameState *gs)
  166. {
  167. CGHeroInstance * hero = gs->getHero(hid);
  168. assert(hero);
  169. if(absolute)
  170. hero->mana = val;
  171. else
  172. hero->mana += val;
  173. vstd::amax(hero->mana, 0); //not less than 0
  174. }
  175. DLL_LINKAGE void SetMovePoints::applyGs(CGameState *gs)
  176. {
  177. CGHeroInstance *hero = gs->getHero(hid);
  178. assert(hero);
  179. if(absolute)
  180. hero->movement = val;
  181. else
  182. hero->movement += val;
  183. vstd::amax(hero->movement, 0); //not less than 0
  184. }
  185. DLL_LINKAGE void FoWChange::applyGs(CGameState *gs)
  186. {
  187. TeamState * team = gs->getPlayerTeam(player);
  188. for(int3 t : tiles)
  189. {
  190. if(mode == 0 && team->fogOfWarMap[t.x][t.y][t.z] > 1)
  191. continue;
  192. else if(mode == 1 && team->fogOfWarMap[t.x][t.y][t.z])
  193. continue;
  194. team->fogOfWarMap[t.x][t.y][t.z] = mode;
  195. }
  196. }
  197. DLL_LINKAGE void SetAvailableHeroes::applyGs(CGameState *gs)
  198. {
  199. PlayerState *p = gs->getPlayer(player);
  200. p->availableHeroes.clear();
  201. for (int i = 0; i < GameConstants::AVAILABLE_HEROES_PER_PLAYER; i++)
  202. {
  203. CGHeroInstance *h = (hid[i]>=0 ? gs->hpool.heroesPool[hid[i]].get() : nullptr);
  204. if(h && army[i])
  205. h->setToArmy(army[i]);
  206. p->availableHeroes.push_back(h);
  207. }
  208. }
  209. DLL_LINKAGE void GiveBonus::applyGs(CGameState *gs)
  210. {
  211. CBonusSystemNode *cbsn = nullptr;
  212. switch(who)
  213. {
  214. case HERO:
  215. cbsn = gs->getHero(ObjectInstanceID(id));
  216. break;
  217. case PLAYER:
  218. cbsn = gs->getPlayer(PlayerColor(id));
  219. break;
  220. case TOWN:
  221. cbsn = gs->getTown(ObjectInstanceID(id));
  222. break;
  223. }
  224. assert(cbsn);
  225. if(Bonus::OneWeek(&bonus))
  226. bonus.turnsRemain = 8 - gs->getDate(Date::DAY_OF_WEEK); // set correct number of days before adding bonus
  227. auto b = std::make_shared<Bonus>(bonus);
  228. cbsn->addNewBonus(b);
  229. std::string &descr = b->description;
  230. if(!bdescr.message.size()
  231. && bonus.source == Bonus::OBJECT
  232. && (bonus.type == Bonus::LUCK || bonus.type == Bonus::MORALE))
  233. {
  234. descr = VLC->generaltexth->arraytxt[bonus.val > 0 ? 110 : 109]; //+/-%d Temporary until next battle"
  235. }
  236. else
  237. {
  238. bdescr.toString(descr);
  239. }
  240. // Some of(?) versions of H3 use %s here instead of %d. Try to replace both of them
  241. boost::replace_first(descr,"%d",boost::lexical_cast<std::string>(std::abs(bonus.val)));
  242. boost::replace_first(descr,"%s",boost::lexical_cast<std::string>(std::abs(bonus.val)));
  243. }
  244. DLL_LINKAGE void ChangeObjPos::applyGs(CGameState *gs)
  245. {
  246. CGObjectInstance *obj = gs->getObjInstance(objid);
  247. if(!obj)
  248. {
  249. logNetwork->error("Wrong ChangeObjPos: object %d doesn't exist!", objid.getNum());
  250. return;
  251. }
  252. gs->removeSightnObj(obj);
  253. gs->map->removeBlockVisTiles(obj);
  254. obj->pos = nPos;
  255. gs->map->addBlockVisTiles(obj);
  256. gs->addSightObj(obj);
  257. }
  258. DLL_LINKAGE void ChangeObjectVisitors::applyGs(CGameState *gs)
  259. {
  260. switch (mode) {
  261. case VISITOR_ADD:
  262. gs->getHero(hero)->visitedObjects.insert(object);
  263. gs->getPlayer(gs->getHero(hero)->tempOwner)->visitedObjects.insert(object);
  264. break;
  265. case VISITOR_ADD_TEAM:
  266. {
  267. TeamState *ts = gs->getPlayerTeam(gs->getHero(hero)->tempOwner);
  268. for (auto & color : ts->players)
  269. {
  270. gs->getPlayer(color)->visitedObjects.insert(object);
  271. }
  272. }
  273. break;
  274. case VISITOR_CLEAR:
  275. for (CGHeroInstance * hero : gs->map->allHeroes)
  276. {
  277. if (hero)
  278. {
  279. hero->visitedObjects.erase(object); // remove visit info from all heroes, including those that are not present on map
  280. }
  281. }
  282. for(auto &elem : gs->players)
  283. {
  284. elem.second.visitedObjects.erase(object);
  285. }
  286. break;
  287. case VISITOR_REMOVE:
  288. gs->getHero(hero)->visitedObjects.erase(object);
  289. break;
  290. }
  291. }
  292. DLL_LINKAGE void PlayerEndsGame::applyGs(CGameState *gs)
  293. {
  294. PlayerState *p = gs->getPlayer(player);
  295. if(victoryLossCheckResult.victory()) p->status = EPlayerStatus::WINNER;
  296. else p->status = EPlayerStatus::LOSER;
  297. }
  298. DLL_LINKAGE void RemoveBonus::applyGs(CGameState *gs)
  299. {
  300. CBonusSystemNode *node;
  301. if (who == HERO)
  302. node = gs->getHero(ObjectInstanceID(whoID));
  303. else
  304. node = gs->getPlayer(PlayerColor(whoID));
  305. BonusList &bonuses = node->getExportedBonusList();
  306. for (int i = 0; i < bonuses.size(); i++)
  307. {
  308. auto b = bonuses[i];
  309. if(b->source == source && b->sid == id)
  310. {
  311. bonus = *b; //backup bonus (to show to interfaces later)
  312. node->removeBonus(b);
  313. break;
  314. }
  315. }
  316. }
  317. DLL_LINKAGE void RemoveObject::applyGs(CGameState *gs)
  318. {
  319. CGObjectInstance *obj = gs->getObjInstance(id);
  320. logGlobal->debug("removing object id=%d; address=%x; name=%s", id, (intptr_t)obj, obj->getObjectName());
  321. //unblock tiles
  322. gs->removeSightnObj(obj);
  323. gs->map->removeBlockVisTiles(obj);
  324. if(obj->ID==Obj::HERO)
  325. {
  326. CGHeroInstance *h = static_cast<CGHeroInstance*>(obj);
  327. PlayerState *p = gs->getPlayer(h->tempOwner);
  328. gs->map->heroesOnMap -= h;
  329. p->heroes -= h;
  330. h->detachFrom(h->whereShouldBeAttached(gs));
  331. h->tempOwner = PlayerColor::NEUTRAL; //no one owns beaten hero
  332. vstd::erase_if(h->artifactsInBackpack, [](const ArtSlotInfo& asi)
  333. {
  334. return asi.artifact->artType->id == ArtifactID::GRAIL;
  335. });
  336. if(h->visitedTown)
  337. {
  338. if(h->inTownGarrison)
  339. h->visitedTown->garrisonHero = nullptr;
  340. else
  341. h->visitedTown->visitingHero = nullptr;
  342. h->visitedTown = nullptr;
  343. }
  344. //return hero to the pool, so he may reappear in tavern
  345. gs->hpool.heroesPool[h->subID] = h;
  346. if(!vstd::contains(gs->hpool.pavailable, h->subID))
  347. gs->hpool.pavailable[h->subID] = 0xff;
  348. gs->map->objects[id.getNum()] = nullptr;
  349. //If hero on Boat is removed, the Boat disappears
  350. if(h->boat)
  351. {
  352. gs->map->instanceNames.erase(h->boat->instanceName);
  353. gs->map->objects[h->boat->id.getNum()].dellNull();
  354. h->boat = nullptr;
  355. }
  356. return;
  357. }
  358. auto quest = dynamic_cast<const IQuestObject *>(obj);
  359. if (quest)
  360. {
  361. gs->map->quests[quest->quest->qid] = nullptr;
  362. for (auto &player : gs->players)
  363. {
  364. for (auto &q : player.second.quests)
  365. {
  366. if (q.obj == obj)
  367. {
  368. q.obj = nullptr;
  369. }
  370. }
  371. }
  372. }
  373. for (TriggeredEvent & event : gs->map->triggeredEvents)
  374. {
  375. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  376. {
  377. if (cond.object == obj)
  378. {
  379. if (cond.condition == EventCondition::DESTROY || cond.condition == EventCondition::DESTROY_0)
  380. {
  381. cond.condition = EventCondition::CONST_VALUE;
  382. cond.value = 1; // destroyed object, from now on always fulfilled
  383. }
  384. else if (cond.condition == EventCondition::CONTROL || cond.condition == EventCondition::HAVE_0)
  385. {
  386. cond.condition = EventCondition::CONST_VALUE;
  387. cond.value = 0; // destroyed object, from now on can not be fulfilled
  388. }
  389. }
  390. return cond;
  391. };
  392. event.trigger = event.trigger.morph(patcher);
  393. }
  394. gs->map->instanceNames.erase(obj->instanceName);
  395. gs->map->objects[id.getNum()].dellNull();
  396. gs->map->calculateGuardingGreaturePositions();
  397. }
  398. static int getDir(int3 src, int3 dst)
  399. {
  400. int ret = -1;
  401. if(dst.x+1 == src.x && dst.y+1 == src.y) //tl
  402. {
  403. ret = 1;
  404. }
  405. else if(dst.x == src.x && dst.y+1 == src.y) //t
  406. {
  407. ret = 2;
  408. }
  409. else if(dst.x-1 == src.x && dst.y+1 == src.y) //tr
  410. {
  411. ret = 3;
  412. }
  413. else if(dst.x-1 == src.x && dst.y == src.y) //r
  414. {
  415. ret = 4;
  416. }
  417. else if(dst.x-1 == src.x && dst.y-1 == src.y) //br
  418. {
  419. ret = 5;
  420. }
  421. else if(dst.x == src.x && dst.y-1 == src.y) //b
  422. {
  423. ret = 6;
  424. }
  425. else if(dst.x+1 == src.x && dst.y-1 == src.y) //bl
  426. {
  427. ret = 7;
  428. }
  429. else if(dst.x+1 == src.x && dst.y == src.y) //l
  430. {
  431. ret = 8;
  432. }
  433. return ret;
  434. }
  435. void TryMoveHero::applyGs(CGameState *gs)
  436. {
  437. CGHeroInstance *h = gs->getHero(id);
  438. if (!h)
  439. {
  440. logGlobal->error("Attempt ot move unavailable hero %d", id.getNum());
  441. return;
  442. }
  443. if(start != end)
  444. gs->removeSightnObj(h);
  445. h->movement = movePoints;
  446. if((result == SUCCESS || result == BLOCKING_VISIT || result == EMBARK || result == DISEMBARK) && start != end)
  447. {
  448. auto dir = getDir(start,end);
  449. if(dir > 0 && dir <= 8)
  450. h->moveDir = dir;
  451. //else don`t change move direction - hero might have traversed the subterranean gate, direction should be kept
  452. }
  453. if(result == EMBARK) //hero enters boat at destination tile
  454. {
  455. const TerrainTile &tt = gs->map->getTile(CGHeroInstance::convertPosition(end, false));
  456. assert(tt.visitableObjects.size() >= 1 && tt.visitableObjects.back()->ID == Obj::BOAT); //the only visitable object at destination is Boat
  457. CGBoat *boat = static_cast<CGBoat*>(tt.visitableObjects.back());
  458. gs->map->removeBlockVisTiles(boat); //hero blockvis mask will be used, we don't need to duplicate it with boat
  459. h->boat = boat;
  460. boat->hero = h;
  461. }
  462. else if(result == DISEMBARK) //hero leaves boat to destination tile
  463. {
  464. CGBoat *b = const_cast<CGBoat *>(h->boat);
  465. b->direction = h->moveDir;
  466. b->pos = start;
  467. b->hero = nullptr;
  468. gs->map->addBlockVisTiles(b);
  469. h->boat = nullptr;
  470. }
  471. if(start != end)
  472. {
  473. if(result == SUCCESS || result == TELEPORTATION || result == EMBARK || result == DISEMBARK)
  474. {
  475. gs->map->removeBlockVisTiles(h);
  476. h->pos = end;
  477. if(CGBoat *b = const_cast<CGBoat *>(h->boat))
  478. b->pos = end;
  479. gs->map->addBlockVisTiles(h);
  480. }
  481. gs->addSightObj(h);
  482. }
  483. }
  484. DLL_LINKAGE void NewStructures::applyGs(CGameState *gs)
  485. {
  486. CGTownInstance *t = gs->getTown(tid);
  487. for(const auto & id : bid)
  488. {
  489. assert(t->town->buildings.at(id) != nullptr);
  490. t->builtBuildings.insert(id);
  491. t->updateAppearance();
  492. }
  493. t->builded = builded;
  494. gs->removeSightnObj(t);
  495. t->recreateBuildingsBonuses();
  496. gs->addSightObj(t);
  497. }
  498. DLL_LINKAGE void RazeStructures::applyGs(CGameState *gs)
  499. {
  500. CGTownInstance *t = gs->getTown(tid);
  501. for(const auto & id : bid)
  502. {
  503. t->builtBuildings.erase(id);
  504. t->updateAppearance();
  505. }
  506. t->destroyed = destroyed; //yeaha
  507. gs->removeSightnObj(t);
  508. t->recreateBuildingsBonuses();
  509. gs->addSightObj(t);
  510. }
  511. DLL_LINKAGE void SetAvailableCreatures::applyGs(CGameState *gs)
  512. {
  513. CGDwelling *dw = dynamic_cast<CGDwelling*>(gs->getObjInstance(tid));
  514. assert(dw);
  515. dw->creatures = creatures;
  516. }
  517. DLL_LINKAGE void SetHeroesInTown::applyGs(CGameState *gs)
  518. {
  519. CGTownInstance *t = gs->getTown(tid);
  520. CGHeroInstance *v = gs->getHero(visiting),
  521. *g = gs->getHero(garrison);
  522. bool newVisitorComesFromGarrison = v && v == t->garrisonHero;
  523. bool newGarrisonComesFromVisiting = g && g == t->visitingHero;
  524. if(newVisitorComesFromGarrison)
  525. t->setGarrisonedHero(nullptr);
  526. if(newGarrisonComesFromVisiting)
  527. t->setVisitingHero(nullptr);
  528. if(!newGarrisonComesFromVisiting || v)
  529. t->setVisitingHero(v);
  530. if(!newVisitorComesFromGarrison || g)
  531. t->setGarrisonedHero(g);
  532. if(v)
  533. {
  534. gs->map->addBlockVisTiles(v);
  535. }
  536. if(g)
  537. {
  538. gs->map->removeBlockVisTiles(g);
  539. }
  540. }
  541. DLL_LINKAGE void HeroRecruited::applyGs(CGameState *gs)
  542. {
  543. assert(vstd::contains(gs->hpool.heroesPool, hid));
  544. CGHeroInstance *h = gs->hpool.heroesPool[hid];
  545. CGTownInstance *t = gs->getTown(tid);
  546. PlayerState *p = gs->getPlayer(player);
  547. assert(!h->boat);
  548. h->setOwner(player);
  549. h->pos = tile;
  550. bool fresh = !h->isInitialized();
  551. if(fresh)
  552. { // this is a fresh hero who hasn't appeared yet
  553. h->movement = h->maxMovePoints(true);
  554. }
  555. gs->hpool.heroesPool.erase(hid);
  556. if(h->id == ObjectInstanceID())
  557. {
  558. h->id = ObjectInstanceID(gs->map->objects.size());
  559. gs->map->objects.push_back(h);
  560. }
  561. else
  562. gs->map->objects[h->id.getNum()] = h;
  563. gs->map->heroesOnMap.push_back(h);
  564. p->heroes.push_back(h);
  565. h->attachTo(p);
  566. if(fresh)
  567. {
  568. h->initObj(gs->getRandomGenerator());
  569. }
  570. gs->map->addBlockVisTiles(h);
  571. if(t)
  572. {
  573. t->setVisitingHero(h);
  574. }
  575. gs->addSightObj(h);
  576. }
  577. DLL_LINKAGE void GiveHero::applyGs(CGameState *gs)
  578. {
  579. CGHeroInstance *h = gs->getHero(id);
  580. //bonus system
  581. h->detachFrom(&gs->globalEffects);
  582. h->attachTo(gs->getPlayer(player));
  583. h->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, h->type->heroClass->id)->getTemplates().front();
  584. gs->map->removeBlockVisTiles(h,true);
  585. h->setOwner(player);
  586. h->movement = h->maxMovePoints(true);
  587. gs->map->heroesOnMap.push_back(h);
  588. gs->getPlayer(h->getOwner())->heroes.push_back(h);
  589. gs->map->addBlockVisTiles(h);
  590. h->inTownGarrison = false;
  591. }
  592. DLL_LINKAGE void NewObject::applyGs(CGameState *gs)
  593. {
  594. const TerrainTile &t = gs->map->getTile(pos);
  595. ETerrainType terrainType = t.terType;
  596. CGObjectInstance *o = nullptr;
  597. switch(ID)
  598. {
  599. case Obj::BOAT:
  600. o = new CGBoat();
  601. terrainType = ETerrainType::WATER; //TODO: either boat should only spawn on water, or all water objects should be handled this way
  602. break;
  603. case Obj::MONSTER: //probably more options will be needed
  604. o = new CGCreature();
  605. {
  606. //CStackInstance hlp;
  607. CGCreature *cre = static_cast<CGCreature*>(o);
  608. //cre->slots[0] = hlp;
  609. cre->notGrowingTeam = cre->neverFlees = 0;
  610. cre->character = 2;
  611. cre->gainedArtifact = ArtifactID::NONE;
  612. cre->identifier = -1;
  613. cre->addToSlot(SlotID(0), new CStackInstance(CreatureID(subID), -1)); //add placeholder stack
  614. }
  615. break;
  616. default:
  617. o = new CGObjectInstance();
  618. break;
  619. }
  620. o->ID = ID;
  621. o->subID = subID;
  622. o->pos = pos;
  623. o->appearance = VLC->objtypeh->getHandlerFor(o->ID, o->subID)->getTemplates(terrainType).front();
  624. id = o->id = ObjectInstanceID(gs->map->objects.size());
  625. gs->map->objects.push_back(o);
  626. gs->map->addBlockVisTiles(o);
  627. o->initObj(gs->getRandomGenerator());
  628. gs->map->calculateGuardingGreaturePositions();
  629. gs->addSightObj(o);
  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. if(what == ObjProperty::OWNER)
  1028. {
  1029. CArmedInstance *cai = dynamic_cast<CArmedInstance *>(obj);
  1030. if(cai)
  1031. {
  1032. if(obj->ID == Obj::TOWN)
  1033. {
  1034. CGTownInstance *t = static_cast<CGTownInstance*>(obj);
  1035. if(t->tempOwner < PlayerColor::PLAYER_LIMIT)
  1036. gs->getPlayer(t->tempOwner)->towns -= t;
  1037. if(val < PlayerColor::PLAYER_LIMIT_I)
  1038. {
  1039. PlayerState * p = gs->getPlayer(PlayerColor(val));
  1040. p->towns.push_back(t);
  1041. //reset counter before NewTurn to avoid no town message if game loaded at turn when one already captured
  1042. if(p->daysWithoutCastle)
  1043. p->daysWithoutCastle = boost::none;
  1044. }
  1045. }
  1046. gs->removeSightnObj(obj);
  1047. CBonusSystemNode *nodeToMove = cai->whatShouldBeAttached();
  1048. nodeToMove->detachFrom(cai->whereShouldBeAttached(gs));
  1049. obj->setProperty(what,val);
  1050. nodeToMove->attachTo(cai->whereShouldBeAttached(gs));
  1051. gs->addSightObj(obj);
  1052. }
  1053. else
  1054. {
  1055. gs->removeSightnObj(obj);
  1056. obj->setProperty(what, val);
  1057. gs->addSightObj(obj);
  1058. }
  1059. }
  1060. else //not an armed instance
  1061. {
  1062. obj->setProperty(what,val);
  1063. }
  1064. }
  1065. DLL_LINKAGE void PrepareHeroLevelUp::applyGs(CGameState *gs)
  1066. {
  1067. CGHeroInstance * h = gs->getHero(hero->id);
  1068. auto proposedSkills = h->getLevelUpProposedSecondarySkills();
  1069. if(skills.size() == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  1070. {
  1071. skills.push_back(*RandomGeneratorUtil::nextItem(proposedSkills, h->skillsInfo.rand));
  1072. }
  1073. else
  1074. {
  1075. skills = proposedSkills;
  1076. }
  1077. }
  1078. DLL_LINKAGE void HeroLevelUp::applyGs(CGameState *gs)
  1079. {
  1080. CGHeroInstance * h = gs->getHero(hero->id);
  1081. h->levelUp(skills);
  1082. }
  1083. DLL_LINKAGE void CommanderLevelUp::applyGs (CGameState *gs)
  1084. {
  1085. CCommanderInstance * commander = gs->getHero(hero->id)->commander;
  1086. assert (commander);
  1087. commander->levelUp();
  1088. }
  1089. DLL_LINKAGE void BattleStart::applyGs(CGameState *gs)
  1090. {
  1091. gs->curB = info;
  1092. gs->curB->localInit();
  1093. }
  1094. DLL_LINKAGE void BattleNextRound::applyGs(CGameState *gs)
  1095. {
  1096. for (int i = 0; i < 2; ++i)
  1097. {
  1098. gs->curB->sides[i].castSpellsCount = 0;
  1099. vstd::amax(--gs->curB->sides[i].enchanterCounter, 0);
  1100. }
  1101. gs->curB->round = round;
  1102. for(CStack *s : gs->curB->stacks)
  1103. {
  1104. s->state -= EBattleStackState::DEFENDING;
  1105. s->state -= EBattleStackState::WAITING;
  1106. s->state -= EBattleStackState::MOVED;
  1107. s->state -= EBattleStackState::HAD_MORALE;
  1108. s->state -= EBattleStackState::FEAR;
  1109. s->state -= EBattleStackState::DRAINED_MANA;
  1110. s->counterAttacks.reset();
  1111. // new turn effects
  1112. s->updateBonuses(Bonus::NTurns);
  1113. if(s->alive() && s->isClone())
  1114. {
  1115. //cloned stack has special lifetime marker
  1116. //check it after bonuses updated in battleTurnPassed()
  1117. if(!s->hasBonus(Selector::type(Bonus::NONE).And(Selector::source(Bonus::SPELL_EFFECT, SpellID::CLONE))))
  1118. s->makeGhost();
  1119. }
  1120. }
  1121. for(auto &obst : gs->curB->obstacles)
  1122. obst->battleTurnPassed();
  1123. }
  1124. DLL_LINKAGE void BattleSetActiveStack::applyGs(CGameState *gs)
  1125. {
  1126. gs->curB->activeStack = stack;
  1127. CStack *st = gs->curB->getStack(stack);
  1128. //remove bonuses that last until when stack gets new turn
  1129. st->popBonuses(Bonus::UntilGetsTurn);
  1130. if(vstd::contains(st->state,EBattleStackState::MOVED)) //if stack is moving second time this turn it must had a high morale bonus
  1131. st->state.insert(EBattleStackState::HAD_MORALE);
  1132. }
  1133. DLL_LINKAGE void BattleTriggerEffect::applyGs(CGameState *gs)
  1134. {
  1135. CStack * st = gs->curB->getStack(stackID);
  1136. assert(st);
  1137. switch(effect)
  1138. {
  1139. case Bonus::HP_REGENERATION:
  1140. {
  1141. int32_t toHeal = val;
  1142. CHealth health = st->healthAfterHealed(toHeal, EHealLevel::HEAL, EHealPower::PERMANENT);
  1143. st->setHealth(health);
  1144. break;
  1145. }
  1146. case Bonus::MANA_DRAIN:
  1147. {
  1148. CGHeroInstance * h = gs->getHero(ObjectInstanceID(additionalInfo));
  1149. st->state.insert (EBattleStackState::DRAINED_MANA);
  1150. h->mana -= val;
  1151. vstd::amax(h->mana, 0);
  1152. break;
  1153. }
  1154. case Bonus::POISON:
  1155. {
  1156. auto b = st->getBonusLocalFirst(Selector::source(Bonus::SPELL_EFFECT, SpellID::POISON)
  1157. .And(Selector::type(Bonus::STACK_HEALTH)));
  1158. if (b)
  1159. b->val = val;
  1160. break;
  1161. }
  1162. case Bonus::ENCHANTER:
  1163. break;
  1164. case Bonus::FEAR:
  1165. st->state.insert(EBattleStackState::FEAR);
  1166. break;
  1167. default:
  1168. logNetwork->error("Unrecognized trigger effect type %d", effect);
  1169. }
  1170. }
  1171. DLL_LINKAGE void BattleObstaclePlaced::applyGs(CGameState *gs)
  1172. {
  1173. gs->curB->obstacles.push_back(obstacle);
  1174. }
  1175. DLL_LINKAGE void BattleUpdateGateState::applyGs(CGameState *gs)
  1176. {
  1177. if(gs->curB)
  1178. gs->curB->si.gateState = state;
  1179. }
  1180. void BattleResult::applyGs(CGameState *gs)
  1181. {
  1182. for (CStack *s : gs->curB->stacks)
  1183. {
  1184. if (s->base && s->base->armyObj && vstd::contains(s->state, EBattleStackState::SUMMONED))
  1185. {
  1186. //stack with SUMMONED flag but coming from garrison -> most likely resurrected, needs to be removed
  1187. assert(&s->base->armyObj->getStack(s->slot) == s->base);
  1188. const_cast<CArmedInstance*>(s->base->armyObj)->eraseStack(s->slot);
  1189. }
  1190. }
  1191. for (auto & elem : gs->curB->stacks)
  1192. delete elem;
  1193. for(int i = 0; i < 2; ++i)
  1194. {
  1195. if(auto h = gs->curB->battleGetFightingHero(i))
  1196. {
  1197. h->popBonuses(Bonus::OneBattle); //remove any "until next battle" bonuses
  1198. if (h->commander && h->commander->alive)
  1199. {
  1200. for (auto art : h->commander->artifactsWorn) //increment bonuses for commander artifacts
  1201. {
  1202. art.second.artifact->artType->levelUpArtifact (art.second.artifact);
  1203. }
  1204. }
  1205. }
  1206. }
  1207. if(VLC->modh->modules.STACK_EXP)
  1208. {
  1209. for(int i = 0; i < 2; i++)
  1210. if(exp[i])
  1211. gs->curB->battleGetArmyObject(i)->giveStackExp(exp[i]);
  1212. CBonusSystemNode::treeHasChanged();
  1213. }
  1214. for(int i = 0; i < 2; i++)
  1215. gs->curB->battleGetArmyObject(i)->battle = nullptr;
  1216. gs->curB.dellNull();
  1217. }
  1218. void BattleStackMoved::applyGs(CGameState *gs)
  1219. {
  1220. CStack *s = gs->curB->getStack(stack);
  1221. assert(s);
  1222. BattleHex dest = tilesToMove.back();
  1223. //if unit ended movement on quicksands that were created by enemy, that quicksand patch becomes visible for owner
  1224. for(auto &oi : gs->curB->obstacles)
  1225. {
  1226. if(oi->obstacleType == CObstacleInstance::QUICKSAND
  1227. && vstd::contains(oi->getAffectedTiles(), tilesToMove.back()))
  1228. {
  1229. SpellCreatedObstacle *sands = dynamic_cast<SpellCreatedObstacle*>(oi.get());
  1230. assert(sands);
  1231. if(sands->casterSide != s->side)
  1232. sands->visibleForAnotherSide = true;
  1233. }
  1234. }
  1235. s->position = dest;
  1236. }
  1237. DLL_LINKAGE void BattleStackAttacked::applyGs(CGameState *gs)
  1238. {
  1239. CStack * at = gs->curB->getStack(stackAttacked);
  1240. assert(at);
  1241. at->popBonuses(Bonus::UntilBeingAttacked);
  1242. if(willRebirth())
  1243. at->health.reset();//kill stack first
  1244. else
  1245. at->setHealth(newHealth);
  1246. if(killed())
  1247. {
  1248. at->state -= EBattleStackState::ALIVE;
  1249. if(at->cloneID >= 0)
  1250. {
  1251. //remove clone as well
  1252. CStack * clone = gs->curB->getStack(at->cloneID);
  1253. if(clone)
  1254. clone->makeGhost();
  1255. at->cloneID = -1;
  1256. }
  1257. }
  1258. //life drain handling
  1259. for(auto & elem : healedStacks)
  1260. elem.applyGs(gs);
  1261. if(willRebirth())
  1262. {
  1263. //TODO: handle rebirth with StacksHealedOrResurrected
  1264. at->casts.use();
  1265. at->state.insert(EBattleStackState::ALIVE);
  1266. at->setHealth(newHealth);
  1267. //removing all spells effects
  1268. auto selector = [](const Bonus * b)
  1269. {
  1270. //Special case: DISRUPTING_RAY is "immune" to dispell
  1271. //Other even PERMANENT effects can be removed
  1272. if(b->source == Bonus::SPELL_EFFECT)
  1273. return b->sid != SpellID::DISRUPTING_RAY;
  1274. else
  1275. return false;
  1276. };
  1277. at->popBonuses(selector);
  1278. }
  1279. if(cloneKilled())
  1280. {
  1281. //"hide" killed creatures instead so we keep info about it
  1282. at->makeGhost();
  1283. for(CStack * s : gs->curB->stacks)
  1284. {
  1285. if(s->cloneID == at->ID)
  1286. s->cloneID = -1;
  1287. }
  1288. }
  1289. //killed summoned creature should be removed like clone
  1290. if(killed() && vstd::contains(at->state, EBattleStackState::SUMMONED))
  1291. at->makeGhost();
  1292. }
  1293. DLL_LINKAGE void BattleAttack::applyGs(CGameState * gs)
  1294. {
  1295. CStack * attacker = gs->curB->getStack(stackAttacking);
  1296. assert(attacker);
  1297. if(counter())
  1298. attacker->counterAttacks.use();
  1299. if(shot())
  1300. attacker->shots.use();
  1301. for(BattleStackAttacked & stackAttacked : bsa)
  1302. stackAttacked.applyGs(gs);
  1303. attacker->popBonuses(Bonus::UntilAttack);
  1304. }
  1305. DLL_LINKAGE void StartAction::applyGs(CGameState *gs)
  1306. {
  1307. CStack *st = gs->curB->getStack(ba.stackNumber);
  1308. if(ba.actionType == Battle::END_TACTIC_PHASE)
  1309. {
  1310. gs->curB->tacticDistance = 0;
  1311. return;
  1312. }
  1313. if(gs->curB->tacticDistance)
  1314. {
  1315. // moves in tactics phase do not affect creature status
  1316. // (tactics stack queue is managed by client)
  1317. return;
  1318. }
  1319. if(ba.actionType != Battle::HERO_SPELL) //don't check for stack if it's custom action by hero
  1320. {
  1321. assert(st);
  1322. }
  1323. else
  1324. {
  1325. gs->curB->sides[ba.side].usedSpellsHistory.push_back(SpellID(ba.additionalInfo).toSpell());
  1326. }
  1327. switch(ba.actionType)
  1328. {
  1329. case Battle::DEFEND:
  1330. st->state -= EBattleStackState::DEFENDING_ANIM;
  1331. st->state.insert(EBattleStackState::DEFENDING);
  1332. st->state.insert(EBattleStackState::DEFENDING_ANIM);
  1333. break;
  1334. case Battle::WAIT:
  1335. st->state -= EBattleStackState::DEFENDING_ANIM;
  1336. st->state.insert(EBattleStackState::WAITING);
  1337. return;
  1338. case Battle::HERO_SPELL: //no change in current stack state
  1339. return;
  1340. default: //any active stack action - attack, catapult, heal, spell...
  1341. st->state -= EBattleStackState::DEFENDING_ANIM;
  1342. st->state.insert(EBattleStackState::MOVED);
  1343. break;
  1344. }
  1345. if(st)
  1346. 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)
  1347. }
  1348. DLL_LINKAGE void BattleSpellCast::applyGs(CGameState *gs)
  1349. {
  1350. assert(gs->curB);
  1351. const CSpell * spell = SpellID(id).toSpell();
  1352. spell->applyBattle(gs->curB, this);
  1353. }
  1354. void actualizeEffect(CStack * s, const Bonus & ef)
  1355. {
  1356. for(auto stackBonus : s->getBonusList()) //TODO: optimize
  1357. {
  1358. if(stackBonus->source == Bonus::SPELL_EFFECT && stackBonus->type == ef.type && stackBonus->subtype == ef.subtype)
  1359. {
  1360. stackBonus->turnsRemain = std::max(stackBonus->turnsRemain, ef.turnsRemain);
  1361. }
  1362. }
  1363. CBonusSystemNode::treeHasChanged();
  1364. }
  1365. void actualizeEffect(CStack * s, const std::vector<Bonus> & ef)
  1366. {
  1367. //actualizing features vector
  1368. for(const Bonus &fromEffect : ef)
  1369. {
  1370. actualizeEffect(s, fromEffect);
  1371. }
  1372. }
  1373. DLL_LINKAGE void SetStackEffect::applyGs(CGameState *gs)
  1374. {
  1375. if(effect.empty() && cumulativeEffects.empty())
  1376. {
  1377. logGlobal->error("Trying to apply SetStackEffect with no effects");
  1378. return;
  1379. }
  1380. si32 spellid = effect.empty() ? cumulativeEffects.begin()->sid : effect.begin()->sid; //effects' source ID
  1381. auto processEffect = [spellid, this](CStack * sta, const Bonus & effect, bool cumulative)
  1382. {
  1383. if(cumulative || !sta->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellid).And(Selector::typeSubtype(effect.type, effect.subtype))))
  1384. {
  1385. //no such effect or cumulative - add new
  1386. logBonus->trace("%s receives a new bonus: %s", sta->nodeName(), effect.Description());
  1387. sta->addNewBonus(std::make_shared<Bonus>(effect));
  1388. }
  1389. else
  1390. {
  1391. logBonus->trace("%s updated bonus: %s", sta->nodeName(), effect.Description());
  1392. actualizeEffect(sta, effect);
  1393. }
  1394. };
  1395. for(ui32 id : stacks)
  1396. {
  1397. CStack *s = gs->curB->getStack(id);
  1398. if(s)
  1399. {
  1400. for(const Bonus & fromEffect : effect)
  1401. processEffect(s, fromEffect, false);
  1402. for(const Bonus & fromEffect : cumulativeEffects)
  1403. processEffect(s, fromEffect, true);
  1404. }
  1405. else
  1406. logNetwork->error("Cannot find stack %d", id);
  1407. }
  1408. for(auto & para : uniqueBonuses)
  1409. {
  1410. CStack *s = gs->curB->getStack(para.first);
  1411. if(s)
  1412. processEffect(s, para.second, false);
  1413. else
  1414. logNetwork->error("Cannot find stack %d", para.first);
  1415. }
  1416. for(auto & para : cumulativeUniqueBonuses)
  1417. {
  1418. CStack *s = gs->curB->getStack(para.first);
  1419. if(s)
  1420. processEffect(s, para.second, true);
  1421. else
  1422. logNetwork->error("Cannot find stack %d", para.first);
  1423. }
  1424. }
  1425. DLL_LINKAGE void StacksInjured::applyGs(CGameState *gs)
  1426. {
  1427. for(BattleStackAttacked stackAttacked : stacks)
  1428. stackAttacked.applyGs(gs);
  1429. }
  1430. DLL_LINKAGE void StacksHealedOrResurrected::applyGs(CGameState *gs)
  1431. {
  1432. for(auto & elem : healedStacks)
  1433. {
  1434. CStack * changedStack = gs->curB->getStack(elem.stackId, false);
  1435. assert(changedStack);
  1436. //checking if we resurrect a stack that is under a living stack
  1437. auto accessibility = gs->curB->getAccesibility();
  1438. if(!changedStack->alive() && !accessibility.accessible(changedStack->position, changedStack))
  1439. {
  1440. logNetwork->error("Cannot resurrect %s because hex %d is occupied!", changedStack->nodeName(), changedStack->position.hex);
  1441. return; //position is already occupied
  1442. }
  1443. //applying changes
  1444. bool resurrected = !changedStack->alive(); //indicates if stack is resurrected or just healed
  1445. if(resurrected)
  1446. {
  1447. if(auto totalHealth = changedStack->health.available())
  1448. logGlobal->warn("Dead stack %s with positive total HP %d", changedStack->nodeName(), totalHealth);
  1449. changedStack->state.insert(EBattleStackState::ALIVE);
  1450. }
  1451. changedStack->setHealth(elem);
  1452. if(resurrected)
  1453. {
  1454. //removing all spells effects
  1455. auto selector = [](const Bonus * b)
  1456. {
  1457. //Special case: DISRUPTING_RAY is "immune" to dispell
  1458. //Other even PERMANENT effects can be removed
  1459. if(b->source == Bonus::SPELL_EFFECT)
  1460. return b->sid != SpellID::DISRUPTING_RAY;
  1461. else
  1462. return false;
  1463. };
  1464. changedStack->popBonuses(selector);
  1465. }
  1466. else if(cure)
  1467. {
  1468. //removing all effects from negative spells
  1469. auto selector = [](const Bonus * b)
  1470. {
  1471. //Special case: DISRUPTING_RAY is "immune" to dispell
  1472. //Other even PERMANENT effects can be removed
  1473. if(b->source == Bonus::SPELL_EFFECT)
  1474. {
  1475. const CSpell * sourceSpell = SpellID(b->sid).toSpell();
  1476. if(!sourceSpell)
  1477. return false;
  1478. return sourceSpell->id != SpellID::DISRUPTING_RAY && sourceSpell->isNegative();
  1479. }
  1480. else
  1481. return false;
  1482. };
  1483. changedStack->popBonuses(selector);
  1484. }
  1485. }
  1486. }
  1487. DLL_LINKAGE void ObstaclesRemoved::applyGs(CGameState *gs)
  1488. {
  1489. if(gs->curB) //if there is a battle
  1490. {
  1491. for(const si32 rem_obst :obstacles)
  1492. {
  1493. for(int i=0; i<gs->curB->obstacles.size(); ++i)
  1494. {
  1495. if(gs->curB->obstacles[i]->uniqueID == rem_obst) //remove this obstacle
  1496. {
  1497. gs->curB->obstacles.erase(gs->curB->obstacles.begin() + i);
  1498. break;
  1499. }
  1500. }
  1501. }
  1502. }
  1503. }
  1504. DLL_LINKAGE CatapultAttack::CatapultAttack()
  1505. {
  1506. attacker = -1;
  1507. }
  1508. DLL_LINKAGE CatapultAttack::~CatapultAttack()
  1509. {
  1510. }
  1511. DLL_LINKAGE void CatapultAttack::applyGs(CGameState *gs)
  1512. {
  1513. if(gs->curB && gs->curB->town && gs->curB->town->fortLevel() != CGTownInstance::NONE) //if there is a battle and it's a siege
  1514. {
  1515. for(const auto &it :attackedParts)
  1516. {
  1517. gs->curB->si.wallState[it.attackedPart] =
  1518. SiegeInfo::applyDamage(EWallState::EWallState(gs->curB->si.wallState[it.attackedPart]), it.damageDealt);
  1519. }
  1520. }
  1521. }
  1522. DLL_LINKAGE std::string CatapultAttack::AttackInfo::toString() const
  1523. {
  1524. return boost::str(boost::format("{AttackInfo: destinationTile '%d', attackedPart '%d', damageDealt '%d'}")
  1525. % destinationTile % static_cast<int>(attackedPart) % static_cast<int>(damageDealt));
  1526. }
  1527. DLL_LINKAGE std::string CatapultAttack::toString() const
  1528. {
  1529. std::ostringstream out;
  1530. out << "[";
  1531. for(auto it = attackedParts.begin(); it != attackedParts.end(); ++it)
  1532. {
  1533. out << it->toString();
  1534. if(std::prev(attackedParts.end()) != it) out << ", ";
  1535. }
  1536. out << "]";
  1537. return boost::str(boost::format("{CatapultAttack: attackedParts '%s', attacker '%d'}") % out.str() % attacker);
  1538. }
  1539. DLL_LINKAGE void BattleStacksRemoved::applyGs(CGameState *gs)
  1540. {
  1541. if(!gs->curB)
  1542. return;
  1543. while(!stackIDs.empty())
  1544. {
  1545. ui32 rem_stack = *stackIDs.begin();
  1546. for(int b=0; b<gs->curB->stacks.size(); ++b) //find it in vector of stacks
  1547. {
  1548. if(gs->curB->stacks[b]->ID == rem_stack) //if found
  1549. {
  1550. CStack * toRemove = gs->curB->stacks[b];
  1551. toRemove->state.erase(EBattleStackState::ALIVE);
  1552. toRemove->state.erase(EBattleStackState::GHOST_PENDING);
  1553. toRemove->state.insert(EBattleStackState::GHOST);
  1554. toRemove->detachFromAll();//TODO: may be some bonuses should remain
  1555. //stack may be removed instantly (not being killed first)
  1556. //handle clone remove also here
  1557. if(toRemove->cloneID >= 0)
  1558. {
  1559. stackIDs.insert(toRemove->cloneID);
  1560. toRemove->cloneID = -1;
  1561. }
  1562. //cleanup remaining clone links if any
  1563. for(CStack * s : gs->curB->stacks)
  1564. {
  1565. if(s->cloneID == toRemove->ID)
  1566. s->cloneID = -1;
  1567. }
  1568. break;
  1569. }
  1570. }
  1571. stackIDs.erase(rem_stack);
  1572. }
  1573. }
  1574. DLL_LINKAGE void BattleStackAdded::applyGs(CGameState *gs)
  1575. {
  1576. newStackID = 0;
  1577. if(!BattleHex(pos).isValid())
  1578. {
  1579. logNetwork->warn("No place found for new stack!");
  1580. return;
  1581. }
  1582. CStackBasicDescriptor csbd(creID, amount);
  1583. CStack * addedStack = gs->curB->generateNewStack(csbd, side, SlotID::SUMMONED_SLOT_PLACEHOLDER, pos); //TODO: netpacks?
  1584. if(summoned)
  1585. addedStack->state.insert(EBattleStackState::SUMMONED);
  1586. addedStack->localInit(gs->curB.get());
  1587. gs->curB->stacks.push_back(addedStack);
  1588. newStackID = addedStack->ID;
  1589. }
  1590. DLL_LINKAGE void BattleSetStackProperty::applyGs(CGameState * gs)
  1591. {
  1592. CStack * stack = gs->curB->getStack(stackID);
  1593. switch(which)
  1594. {
  1595. case CASTS:
  1596. {
  1597. if(absolute)
  1598. logNetwork->error("Can not change casts in absolute mode");
  1599. else
  1600. stack->casts.use(-val);
  1601. break;
  1602. }
  1603. case ENCHANTER_COUNTER:
  1604. {
  1605. auto & counter = gs->curB->sides[gs->curB->whatSide(stack->owner)].enchanterCounter;
  1606. if(absolute)
  1607. counter = val;
  1608. else
  1609. counter += val;
  1610. vstd::amax(counter, 0);
  1611. break;
  1612. }
  1613. case UNBIND:
  1614. {
  1615. stack->popBonuses(Selector::type(Bonus::BIND_EFFECT));
  1616. break;
  1617. }
  1618. case CLONED:
  1619. {
  1620. stack->state.insert(EBattleStackState::CLONED);
  1621. break;
  1622. }
  1623. case HAS_CLONE:
  1624. {
  1625. stack->cloneID = val;
  1626. break;
  1627. }
  1628. }
  1629. }
  1630. DLL_LINKAGE void PlayerCheated::applyGs(CGameState *gs)
  1631. {
  1632. if(!player.isValidPlayer())
  1633. return;
  1634. gs->getPlayer(player)->enteredLosingCheatCode = losingCheatCode;
  1635. gs->getPlayer(player)->enteredWinningCheatCode = winningCheatCode;
  1636. }
  1637. DLL_LINKAGE void YourTurn::applyGs(CGameState *gs)
  1638. {
  1639. gs->currentPlayer = player;
  1640. auto & playerState = gs->players[player];
  1641. playerState.daysWithoutCastle = daysWithoutCastle;
  1642. }
  1643. DLL_LINKAGE Component::Component(const CStackBasicDescriptor &stack)
  1644. : id(CREATURE), subtype(stack.type->idNumber), val(stack.count), when(0)
  1645. {
  1646. }