NetPacksLib.cpp 40 KB

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