NetPacksLib.cpp 42 KB

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