NetPacksLib.cpp 41 KB

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