2
0

NetPacksLib.cpp 41 KB

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