NetPacksLib.cpp 45 KB

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