NetPacksLib.cpp 42 KB

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