NetPacksLib.cpp 43 KB

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