NetPacksLib.cpp 43 KB

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