NetPacksLib.cpp 41 KB

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