CGameHandler.cpp 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260
  1. /*
  2. * CGameHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CGameHandler.h"
  12. #include "CVCMIServer.h"
  13. #include "ServerNetPackVisitors.h"
  14. #include "ServerSpellCastEnvironment.h"
  15. #include "battles/BattleProcessor.h"
  16. #include "processors/HeroPoolProcessor.h"
  17. #include "processors/PlayerMessageProcessor.h"
  18. #include "queries/QueriesProcessor.h"
  19. #include "queries/MapQueries.h"
  20. #include "../lib/ArtifactUtils.h"
  21. #include "../lib/CArtHandler.h"
  22. #include "../lib/CBuildingHandler.h"
  23. #include "../lib/CCreatureHandler.h"
  24. #include "../lib/CCreatureSet.h"
  25. #include "../lib/CGeneralTextHandler.h"
  26. #include "../lib/CHeroHandler.h"
  27. #include "../lib/CSoundBase.h"
  28. #include "../lib/CThreadHelper.h"
  29. #include "../lib/CTownHandler.h"
  30. #include "../lib/GameConstants.h"
  31. #include "../lib/UnlockGuard.h"
  32. #include "../lib/GameSettings.h"
  33. #include "../lib/ScriptHandler.h"
  34. #include "../lib/StartInfo.h"
  35. #include "../lib/TerrainHandler.h"
  36. #include "../lib/VCMIDirs.h"
  37. #include "../lib/VCMI_Lib.h"
  38. #include "../lib/int3.h"
  39. #include "../lib/filesystem/FileInfo.h"
  40. #include "../lib/filesystem/Filesystem.h"
  41. #include "../lib/gameState/CGameState.h"
  42. #include "../lib/mapping/CMap.h"
  43. #include "../lib/mapping/CMapService.h"
  44. #include "../lib/modding/ModIncompatibility.h"
  45. #include "../lib/pathfinder/CPathfinder.h"
  46. #include "../lib/pathfinder/PathfinderOptions.h"
  47. #include "../lib/pathfinder/TurnInfo.h"
  48. #include "../lib/registerTypes/RegisterTypes.h"
  49. #include "../lib/rmg/CMapGenOptions.h"
  50. #include "../lib/serializer/CTypeList.h"
  51. #include "../lib/serializer/Cast.h"
  52. #include "../lib/serializer/Connection.h"
  53. #include "../lib/serializer/JsonSerializer.h"
  54. #include "../lib/spells/CSpellHandler.h"
  55. #include "vstd/CLoggerBase.h"
  56. #include <vcmi/events/EventBus.h>
  57. #include <vcmi/events/GenericEvents.h>
  58. #include <vcmi/events/AdventureEvents.h>
  59. #ifndef _MSC_VER
  60. #include <boost/thread/xtime.hpp>
  61. #endif
  62. #define COMPLAIN_RET_IF(cond, txt) do {if (cond){complain(txt); return;}} while(0)
  63. #define COMPLAIN_RET_FALSE_IF(cond, txt) do {if (cond){complain(txt); return false;}} while(0)
  64. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  65. #define COMPLAIN_RETF(txt, FORMAT) {complain(boost::str(boost::format(txt) % FORMAT)); return false;}
  66. template <typename T> class CApplyOnGH;
  67. class CBaseForGHApply
  68. {
  69. public:
  70. virtual bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const =0;
  71. virtual ~CBaseForGHApply(){}
  72. template<typename U> static CBaseForGHApply *getApplier(const U * t=nullptr)
  73. {
  74. return new CApplyOnGH<U>();
  75. }
  76. };
  77. template <typename T> class CApplyOnGH : public CBaseForGHApply
  78. {
  79. public:
  80. bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const override
  81. {
  82. T *ptr = static_cast<T*>(pack);
  83. try
  84. {
  85. ApplyGhNetPackVisitor applier(*gh, *gs);
  86. ptr->visit(applier);
  87. return applier.getResult();
  88. }
  89. catch(ExceptionNotAllowedAction & e)
  90. {
  91. (void)e;
  92. return false;
  93. }
  94. }
  95. };
  96. template <>
  97. class CApplyOnGH<CPack> : public CBaseForGHApply
  98. {
  99. public:
  100. bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const override
  101. {
  102. logGlobal->error("Cannot apply on GH plain CPack!");
  103. assert(0);
  104. return false;
  105. }
  106. };
  107. static inline double distance(int3 a, int3 b)
  108. {
  109. return std::sqrt((double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
  110. }
  111. PlayerStatus PlayerStatuses::operator[](PlayerColor player)
  112. {
  113. boost::unique_lock<boost::mutex> l(mx);
  114. if (players.find(player) != players.end())
  115. {
  116. return players.at(player);
  117. }
  118. else
  119. {
  120. throw std::runtime_error("No such player!");
  121. }
  122. }
  123. void PlayerStatuses::addPlayer(PlayerColor player)
  124. {
  125. boost::unique_lock<boost::mutex> l(mx);
  126. players[player];
  127. }
  128. bool PlayerStatuses::checkFlag(PlayerColor player, bool PlayerStatus::*flag)
  129. {
  130. boost::unique_lock<boost::mutex> l(mx);
  131. if (players.find(player) != players.end())
  132. {
  133. return players[player].*flag;
  134. }
  135. else
  136. {
  137. throw std::runtime_error("No such player!");
  138. }
  139. }
  140. void PlayerStatuses::setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val)
  141. {
  142. boost::unique_lock<boost::mutex> l(mx);
  143. if (players.find(player) != players.end())
  144. {
  145. players[player].*flag = val;
  146. }
  147. else
  148. {
  149. throw std::runtime_error("No such player!");
  150. }
  151. cv.notify_all();
  152. }
  153. template <typename T>
  154. void callWith(std::vector<T> args, std::function<void(T)> fun, ui32 which)
  155. {
  156. fun(args[which]);
  157. }
  158. const Services * CGameHandler::services() const
  159. {
  160. return VLC;
  161. }
  162. const CGameHandler::BattleCb * CGameHandler::battle() const
  163. {
  164. return this;
  165. }
  166. const CGameHandler::GameCb * CGameHandler::game() const
  167. {
  168. return this;
  169. }
  170. vstd::CLoggerBase * CGameHandler::logger() const
  171. {
  172. return logGlobal;
  173. }
  174. events::EventBus * CGameHandler::eventBus() const
  175. {
  176. return serverEventBus.get();
  177. }
  178. CVCMIServer * CGameHandler::gameLobby() const
  179. {
  180. return lobby;
  181. }
  182. void CGameHandler::levelUpHero(const CGHeroInstance * hero, SecondarySkill skill)
  183. {
  184. changeSecSkill(hero, skill, 1, 0);
  185. expGiven(hero);
  186. }
  187. void CGameHandler::levelUpHero(const CGHeroInstance * hero)
  188. {
  189. // required exp for at least 1 lvl-up hasn't been reached
  190. if (!hero->gainsLevel())
  191. {
  192. return;
  193. }
  194. // give primary skill
  195. logGlobal->trace("%s got level %d", hero->getNameTranslated(), hero->level);
  196. auto primarySkill = hero->nextPrimarySkill(getRandomGenerator());
  197. SetPrimSkill sps;
  198. sps.id = hero->id;
  199. sps.which = primarySkill;
  200. sps.abs = false;
  201. sps.val = 1;
  202. sendAndApply(&sps);
  203. PrepareHeroLevelUp pre;
  204. pre.heroId = hero->id;
  205. sendAndApply(&pre);
  206. HeroLevelUp hlu;
  207. hlu.player = hero->tempOwner;
  208. hlu.heroId = hero->id;
  209. hlu.primskill = primarySkill;
  210. hlu.skills = pre.skills;
  211. if (hlu.skills.size() == 0)
  212. {
  213. sendAndApply(&hlu);
  214. levelUpHero(hero);
  215. }
  216. else if (hlu.skills.size() == 1)
  217. {
  218. sendAndApply(&hlu);
  219. levelUpHero(hero, pre.skills.front());
  220. }
  221. else if (hlu.skills.size() > 1)
  222. {
  223. auto levelUpQuery = std::make_shared<CHeroLevelUpDialogQuery>(this, hlu, hero);
  224. hlu.queryID = levelUpQuery->queryID;
  225. queries->addQuery(levelUpQuery);
  226. sendAndApply(&hlu);
  227. //level up will be called on query reply
  228. }
  229. }
  230. void CGameHandler::levelUpCommander (const CCommanderInstance * c, int skill)
  231. {
  232. SetCommanderProperty scp;
  233. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  234. if (hero)
  235. scp.heroid = hero->id;
  236. else
  237. {
  238. complain ("Commander is not led by hero!");
  239. return;
  240. }
  241. scp.accumulatedBonus.subtype = 0;
  242. scp.accumulatedBonus.additionalInfo = 0;
  243. scp.accumulatedBonus.duration = BonusDuration::PERMANENT;
  244. scp.accumulatedBonus.turnsRemain = 0;
  245. scp.accumulatedBonus.source = BonusSource::COMMANDER;
  246. scp.accumulatedBonus.valType = BonusValueType::BASE_NUMBER;
  247. if (skill <= ECommander::SPELL_POWER)
  248. {
  249. scp.which = SetCommanderProperty::BONUS;
  250. auto difference = [](std::vector< std::vector <ui8> > skillLevels, std::vector <ui8> secondarySkills, int skill)->int
  251. {
  252. int s = std::min (skill, (int)ECommander::SPELL_POWER); //spell power level controls also casts and resistance
  253. return skillLevels.at(skill).at(secondarySkills.at(s)) - (secondarySkills.at(s) ? skillLevels.at(skill).at(secondarySkills.at(s)-1) : 0);
  254. };
  255. switch (skill)
  256. {
  257. case ECommander::ATTACK:
  258. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  259. scp.accumulatedBonus.subtype = PrimarySkill::ATTACK;
  260. break;
  261. case ECommander::DEFENSE:
  262. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  263. scp.accumulatedBonus.subtype = PrimarySkill::DEFENSE;
  264. break;
  265. case ECommander::HEALTH:
  266. scp.accumulatedBonus.type = BonusType::STACK_HEALTH;
  267. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_BASE;
  268. break;
  269. case ECommander::DAMAGE:
  270. scp.accumulatedBonus.type = BonusType::CREATURE_DAMAGE;
  271. scp.accumulatedBonus.subtype = 0;
  272. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_BASE;
  273. break;
  274. case ECommander::SPEED:
  275. scp.accumulatedBonus.type = BonusType::STACKS_SPEED;
  276. break;
  277. case ECommander::SPELL_POWER:
  278. scp.accumulatedBonus.type = BonusType::MAGIC_RESISTANCE;
  279. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::RESISTANCE);
  280. sendAndApply (&scp); //additional pack
  281. scp.accumulatedBonus.type = BonusType::CREATURE_SPELL_POWER;
  282. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::SPELL_POWER) * 100; //like hero with spellpower = ability level
  283. sendAndApply (&scp); //additional pack
  284. scp.accumulatedBonus.type = BonusType::CASTS;
  285. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::CASTS);
  286. sendAndApply (&scp); //additional pack
  287. scp.accumulatedBonus.type = BonusType::CREATURE_ENCHANT_POWER; //send normally
  288. break;
  289. }
  290. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, skill);
  291. sendAndApply (&scp);
  292. scp.which = SetCommanderProperty::SECONDARY_SKILL;
  293. scp.additionalInfo = skill;
  294. scp.amount = c->secondarySkills.at(skill) + 1;
  295. sendAndApply (&scp);
  296. }
  297. else if (skill >= 100)
  298. {
  299. scp.which = SetCommanderProperty::SPECIAL_SKILL;
  300. scp.accumulatedBonus = *VLC->creh->skillRequirements.at(skill-100).first;
  301. scp.additionalInfo = skill; //unnormalized
  302. sendAndApply (&scp);
  303. }
  304. expGiven(hero);
  305. }
  306. void CGameHandler::levelUpCommander(const CCommanderInstance * c)
  307. {
  308. if (!c->gainsLevel())
  309. {
  310. return;
  311. }
  312. CommanderLevelUp clu;
  313. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  314. if(hero)
  315. {
  316. clu.heroId = hero->id;
  317. clu.player = hero->tempOwner;
  318. }
  319. else
  320. {
  321. complain ("Commander is not led by hero!");
  322. return;
  323. }
  324. //picking sec. skills for choice
  325. for (int i = 0; i <= ECommander::SPELL_POWER; ++i)
  326. {
  327. if (c->secondarySkills.at(i) < ECommander::MAX_SKILL_LEVEL)
  328. clu.skills.push_back(i);
  329. }
  330. int i = 100;
  331. for (auto specialSkill : VLC->creh->skillRequirements)
  332. {
  333. if (c->secondarySkills.at(specialSkill.second.first) == ECommander::MAX_SKILL_LEVEL
  334. && c->secondarySkills.at(specialSkill.second.second) == ECommander::MAX_SKILL_LEVEL
  335. && !vstd::contains (c->specialSKills, i))
  336. clu.skills.push_back (i);
  337. ++i;
  338. }
  339. int skillAmount = static_cast<int>(clu.skills.size());
  340. if (!skillAmount)
  341. {
  342. sendAndApply(&clu);
  343. levelUpCommander(c);
  344. }
  345. else if (skillAmount == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  346. {
  347. sendAndApply(&clu);
  348. levelUpCommander(c, *RandomGeneratorUtil::nextItem(clu.skills, getRandomGenerator()));
  349. }
  350. else if (skillAmount > 1) //apply and ask for secondary skill
  351. {
  352. auto commanderLevelUp = std::make_shared<CCommanderLevelUpDialogQuery>(this, clu, hero);
  353. clu.queryID = commanderLevelUp->queryID;
  354. queries->addQuery(commanderLevelUp);
  355. sendAndApply(&clu);
  356. }
  357. }
  358. void CGameHandler::expGiven(const CGHeroInstance *hero)
  359. {
  360. if (hero->gainsLevel())
  361. levelUpHero(hero);
  362. else if (hero->commander && hero->commander->gainsLevel())
  363. levelUpCommander(hero->commander);
  364. //if (hero->commander && hero->level > hero->commander->level && hero->commander->gainsLevel())
  365. // levelUpCommander(hero->commander);
  366. // else
  367. // levelUpHero(hero);
  368. }
  369. void CGameHandler::changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs)
  370. {
  371. if (which == PrimarySkill::EXPERIENCE) // Check if scenario limit reached
  372. {
  373. if (gs->map->levelLimit != 0)
  374. {
  375. TExpType expLimit = VLC->heroh->reqExp(gs->map->levelLimit);
  376. TExpType resultingExp = abs ? val : hero->exp + val;
  377. if (resultingExp > expLimit)
  378. {
  379. // set given experience to max possible, but don't decrease if hero already over top
  380. abs = true;
  381. val = std::max(expLimit, hero->exp);
  382. InfoWindow iw;
  383. iw.player = hero->tempOwner;
  384. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 1); //can gain no more XP
  385. iw.text.replaceRawString(hero->getNameTranslated());
  386. sendAndApply(&iw);
  387. }
  388. }
  389. }
  390. SetPrimSkill sps;
  391. sps.id = hero->id;
  392. sps.which = which;
  393. sps.abs = abs;
  394. sps.val = val;
  395. sendAndApply(&sps);
  396. //only for exp - hero may level up
  397. if (which == PrimarySkill::EXPERIENCE)
  398. {
  399. if (hero->commander && hero->commander->alive)
  400. {
  401. //FIXME: trim experience according to map limit?
  402. SetCommanderProperty scp;
  403. scp.heroid = hero->id;
  404. scp.which = SetCommanderProperty::EXPERIENCE;
  405. scp.amount = val;
  406. sendAndApply (&scp);
  407. CBonusSystemNode::treeHasChanged();
  408. }
  409. expGiven(hero);
  410. }
  411. }
  412. void CGameHandler::changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs)
  413. {
  414. if(!hero)
  415. {
  416. logGlobal->error("changeSecSkill provided no hero");
  417. return;
  418. }
  419. SetSecSkill sss;
  420. sss.id = hero->id;
  421. sss.which = which;
  422. sss.val = val;
  423. sss.abs = abs;
  424. sendAndApply(&sss);
  425. if (hero->visitedTown)
  426. giveSpells(hero->visitedTown, hero);
  427. }
  428. void CGameHandler::handleClientDisconnection(std::shared_ptr<CConnection> c)
  429. {
  430. if(lobby->state == EServerState::SHUTDOWN || !gs || !gs->scenarioOps)
  431. return;
  432. for(auto & playerConnections : connections)
  433. {
  434. PlayerColor playerId = playerConnections.first;
  435. auto * playerSettings = gs->scenarioOps->getPlayersSettings(playerId.getNum());
  436. if(!playerSettings)
  437. continue;
  438. auto playerConnection = vstd::find(playerConnections.second, c);
  439. if(playerConnection != playerConnections.second.end())
  440. {
  441. std::string messageText = boost::str(boost::format("%s (cid %d) was disconnected") % playerSettings->name % c->connectionID);
  442. playerMessages->broadcastMessage(playerId, messageText);
  443. }
  444. }
  445. }
  446. void CGameHandler::handleReceivedPack(CPackForServer * pack)
  447. {
  448. //prepare struct informing that action was applied
  449. auto sendPackageResponse = [&](bool succesfullyApplied)
  450. {
  451. PackageApplied applied;
  452. applied.player = pack->player;
  453. applied.result = succesfullyApplied;
  454. applied.packType = typeList.getTypeID(pack);
  455. applied.requestID = pack->requestID;
  456. pack->c->sendPack(&applied);
  457. };
  458. CBaseForGHApply * apply = applier->getApplier(typeList.getTypeID(pack)); //and appropriate applier object
  459. if(isBlockedByQueries(pack, pack->player))
  460. {
  461. sendPackageResponse(false);
  462. }
  463. else if(apply)
  464. {
  465. const bool result = apply->applyOnGH(this, this->gs, pack);
  466. if(result)
  467. logGlobal->trace("Message %s successfully applied!", typeid(*pack).name());
  468. else
  469. complain((boost::format("Got false in applying %s... that request must have been fishy!")
  470. % typeid(*pack).name()).str());
  471. sendPackageResponse(true);
  472. }
  473. else
  474. {
  475. logGlobal->error("Message cannot be applied, cannot find applier (unregistered type)!");
  476. sendPackageResponse(false);
  477. }
  478. vstd::clear_pointer(pack);
  479. }
  480. CGameHandler::CGameHandler()
  481. : turnTimerHandler(*this)
  482. {}
  483. CGameHandler::CGameHandler(CVCMIServer * lobby)
  484. : lobby(lobby)
  485. , heroPool(std::make_unique<HeroPoolProcessor>(this))
  486. , battles(std::make_unique<BattleProcessor>(this))
  487. , queries(std::make_unique<QueriesProcessor>())
  488. , playerMessages(std::make_unique<PlayerMessageProcessor>(this))
  489. , complainNoCreatures("No creatures to split")
  490. , complainNotEnoughCreatures("Cannot split that stack, not enough creatures!")
  491. , complainInvalidSlot("Invalid slot accessed!")
  492. , turnTimerHandler(*this)
  493. {
  494. QID = 1;
  495. IObjectInterface::cb = this;
  496. applier = std::make_shared<CApplier<CBaseForGHApply>>();
  497. registerTypesServerPacks(*applier);
  498. spellEnv = new ServerSpellCastEnvironment(this);
  499. }
  500. CGameHandler::~CGameHandler()
  501. {
  502. delete spellEnv;
  503. delete gs;
  504. }
  505. void CGameHandler::reinitScripting()
  506. {
  507. serverEventBus = std::make_unique<events::EventBus>();
  508. #if SCRIPTING_ENABLED
  509. serverScripts.reset(new scripting::PoolImpl(this, spellEnv));
  510. #endif
  511. }
  512. void CGameHandler::init(StartInfo *si, Load::ProgressAccumulator & progressTracking)
  513. {
  514. if (si->seedToBeUsed == 0)
  515. {
  516. si->seedToBeUsed = static_cast<ui32>(std::time(nullptr));
  517. }
  518. CMapService mapService;
  519. gs = new CGameState();
  520. gs->preInit(VLC);
  521. logGlobal->info("Gamestate created!");
  522. gs->init(&mapService, si, progressTracking);
  523. logGlobal->info("Gamestate initialized!");
  524. // reset seed, so that clients can't predict any following random values
  525. getRandomGenerator().resetSeed();
  526. for (auto & elem : gs->players)
  527. {
  528. states.addPlayer(elem.first);
  529. }
  530. reinitScripting();
  531. }
  532. static bool evntCmp(const CMapEvent &a, const CMapEvent &b)
  533. {
  534. return a.earlierThan(b);
  535. }
  536. void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false, bool clear = false)
  537. {// bool forced = true - if creature should be replaced, if false - only if no creature was set
  538. const PlayerState * p = getPlayerState(town->tempOwner);
  539. if (!p)
  540. {
  541. assert(town->tempOwner == PlayerColor::NEUTRAL);
  542. return;
  543. }
  544. if (forced || town->creatures.at(GameConstants::CREATURES_PER_TOWN).second.empty())//we need to change creature
  545. {
  546. SetAvailableCreatures ssi;
  547. ssi.tid = town->id;
  548. ssi.creatures = town->creatures;
  549. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.clear();//remove old one
  550. const std::vector<ConstTransitivePtr<CGDwelling> > &dwellings = p->dwellings;
  551. if (dwellings.empty())//no dwellings - just remove
  552. {
  553. sendAndApply(&ssi);
  554. return;
  555. }
  556. auto dwelling = *RandomGeneratorUtil::nextItem(dwellings, getRandomGenerator());
  557. // for multi-creature dwellings like Golem Factory
  558. auto creatureId = RandomGeneratorUtil::nextItem(dwelling->creatures, getRandomGenerator())->second[0];
  559. if (clear)
  560. {
  561. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = std::max(1, (VLC->creh->objects.at(creatureId)->getGrowth())/2);
  562. }
  563. else
  564. {
  565. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = VLC->creh->objects.at(creatureId)->getGrowth();
  566. }
  567. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.push_back(creatureId);
  568. sendAndApply(&ssi);
  569. }
  570. }
  571. void CGameHandler::newTurn()
  572. {
  573. logGlobal->trace("Turn %d", gs->day+1);
  574. NewTurn n;
  575. n.specialWeek = NewTurn::NO_ACTION;
  576. n.creatureid = CreatureID::NONE;
  577. n.day = gs->day + 1;
  578. bool firstTurn = !getDate(Date::DAY);
  579. bool newWeek = getDate(Date::DAY_OF_WEEK) == 7; //day numbers are confusing, as day was not yet switched
  580. bool newMonth = getDate(Date::DAY_OF_MONTH) == 28;
  581. std::map<PlayerColor, si32> hadGold;//starting gold - for buildings like dwarven treasury
  582. if (firstTurn)
  583. {
  584. for (auto obj : gs->map->objects)
  585. {
  586. if (obj && obj->ID == Obj::PRISON) //give imprisoned hero 0 exp to level him up. easiest to do at this point
  587. {
  588. changePrimSkill (getHero(obj->id), PrimarySkill::EXPERIENCE, 0);
  589. }
  590. }
  591. }
  592. if (newWeek && !firstTurn)
  593. {
  594. n.specialWeek = NewTurn::NORMAL;
  595. bool deityOfFireBuilt = false;
  596. for (const CGTownInstance *t : gs->map->towns)
  597. {
  598. if (t->hasBuilt(BuildingID::GRAIL, ETownType::INFERNO))
  599. {
  600. deityOfFireBuilt = true;
  601. break;
  602. }
  603. }
  604. if (deityOfFireBuilt)
  605. {
  606. n.specialWeek = NewTurn::DEITYOFFIRE;
  607. n.creatureid = CreatureID::IMP;
  608. }
  609. else if(VLC->settings()->getBoolean(EGameSettings::CREATURES_ALLOW_RANDOM_SPECIAL_WEEKS))
  610. {
  611. int monthType = getRandomGenerator().nextInt(99);
  612. if (newMonth) //new month
  613. {
  614. if (monthType < 40) //double growth
  615. {
  616. n.specialWeek = NewTurn::DOUBLE_GROWTH;
  617. if (VLC->settings()->getBoolean(EGameSettings::CREATURES_ALLOW_ALL_FOR_DOUBLE_MONTH))
  618. {
  619. n.creatureid = VLC->creh->pickRandomMonster(getRandomGenerator());
  620. }
  621. else if (VLC->creh->doubledCreatures.size())
  622. {
  623. n.creatureid = *RandomGeneratorUtil::nextItem(VLC->creh->doubledCreatures, getRandomGenerator());
  624. }
  625. else
  626. {
  627. complain("Cannot find creature that can be spawned!");
  628. n.specialWeek = NewTurn::NORMAL;
  629. }
  630. }
  631. else if (monthType < 50)
  632. n.specialWeek = NewTurn::PLAGUE;
  633. }
  634. else //it's a week, but not full month
  635. {
  636. if (monthType < 25)
  637. {
  638. n.specialWeek = NewTurn::BONUS_GROWTH; //+5
  639. std::pair<int, CreatureID> newMonster(54, CreatureID());
  640. do
  641. {
  642. newMonster.second = VLC->creh->pickRandomMonster(getRandomGenerator());
  643. } while (VLC->creh->objects[newMonster.second] &&
  644. (*VLC->townh)[VLC->creatures()->getById(newMonster.second)->getFaction()]->town == nullptr); // find first non neutral creature
  645. n.creatureid = newMonster.second;
  646. }
  647. }
  648. }
  649. }
  650. for (auto & elem : gs->players)
  651. {
  652. if (elem.first == PlayerColor::NEUTRAL)
  653. continue;
  654. else if (elem.first >= PlayerColor::PLAYER_LIMIT)
  655. assert(0); //illegal player number!
  656. std::pair<PlayerColor, si32> playerGold(elem.first, elem.second.resources[EGameResID::GOLD]);
  657. hadGold.insert(playerGold);
  658. if (newWeek) //new heroes in tavern
  659. heroPool->onNewWeek(elem.first);
  660. n.res[elem.first] = elem.second.resources;
  661. if(!firstTurn && newWeek) //weekly crystal generation if 1 or more crystal dragons in any hero army or town garrison
  662. {
  663. bool hasCrystalGenCreature = false;
  664. for(CGHeroInstance * hero : elem.second.heroes)
  665. {
  666. for(auto stack : hero->stacks)
  667. {
  668. if(stack.second->hasBonusOfType(BonusType::SPECIAL_CRYSTAL_GENERATION))
  669. {
  670. hasCrystalGenCreature = true;
  671. break;
  672. }
  673. }
  674. }
  675. if(!hasCrystalGenCreature) //not found in armies, check towns
  676. {
  677. for(CGTownInstance * town : elem.second.towns)
  678. {
  679. for(auto stack : town->stacks)
  680. {
  681. if(stack.second->hasBonusOfType(BonusType::SPECIAL_CRYSTAL_GENERATION))
  682. {
  683. hasCrystalGenCreature = true;
  684. break;
  685. }
  686. }
  687. }
  688. }
  689. if(hasCrystalGenCreature)
  690. n.res[elem.first][EGameResID::CRYSTAL] += 3;
  691. }
  692. for (CGHeroInstance *h : (elem).second.heroes)
  693. {
  694. if (h->visitedTown)
  695. giveSpells(h->visitedTown, h);
  696. NewTurn::Hero hth;
  697. hth.id = h->id;
  698. auto ti = std::make_unique<TurnInfo>(h, 1);
  699. // TODO: this code executed when bonuses of previous day not yet updated (this happen in NewTurn::applyGs). See issue 2356
  700. hth.move = h->movementPointsLimitCached(gs->map->getTile(h->visitablePos()).terType->isLand(), ti.get());
  701. hth.mana = h->getManaNewTurn();
  702. n.heroes.insert(hth);
  703. if (!firstTurn) //not first day
  704. {
  705. for (int k = 0; k < GameConstants::RESOURCE_QUANTITY; k++)
  706. {
  707. n.res[elem.first][k] += h->valOfBonuses(BonusType::GENERATE_RESOURCE, k);
  708. }
  709. }
  710. }
  711. }
  712. for (CGTownInstance *t : gs->map->towns)
  713. {
  714. PlayerColor player = t->tempOwner;
  715. handleTownEvents(t, n);
  716. if (newWeek) //first day of week
  717. {
  718. if (t->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  719. setPortalDwelling(t, true, (n.specialWeek == NewTurn::PLAGUE ? true : false)); //set creatures for Portal of Summoning
  720. if (!firstTurn)
  721. if (t->hasBuilt(BuildingSubID::TREASURY) && player < PlayerColor::PLAYER_LIMIT)
  722. n.res[player][EGameResID::GOLD] += hadGold.at(player)/10; //give 10% of starting gold
  723. if (!vstd::contains(n.cres, t->id))
  724. {
  725. n.cres[t->id].tid = t->id;
  726. n.cres[t->id].creatures = t->creatures;
  727. }
  728. auto & sac = n.cres.at(t->id);
  729. for (int k=0; k < GameConstants::CREATURES_PER_TOWN; k++) //creature growths
  730. {
  731. if (!t->creatures.at(k).second.empty()) // there are creatures at this level
  732. {
  733. ui32 &availableCount = sac.creatures.at(k).first;
  734. const CCreature *cre = VLC->creh->objects.at(t->creatures.at(k).second.back());
  735. if (n.specialWeek == NewTurn::PLAGUE)
  736. availableCount = t->creatures.at(k).first / 2; //halve their number, no growth
  737. else
  738. {
  739. if (firstTurn) //first day of game: use only basic growths
  740. availableCount = cre->getGrowth();
  741. else
  742. availableCount += t->creatureGrowth(k);
  743. //Deity of fire week - upgrade both imps and upgrades
  744. if (n.specialWeek == NewTurn::DEITYOFFIRE && vstd::contains(t->creatures.at(k).second, n.creatureid))
  745. availableCount += 15;
  746. if (cre->getId() == n.creatureid) //bonus week, effect applies only to identical creatures
  747. {
  748. if (n.specialWeek == NewTurn::DOUBLE_GROWTH)
  749. availableCount *= 2;
  750. else if (n.specialWeek == NewTurn::BONUS_GROWTH)
  751. availableCount += 5;
  752. }
  753. }
  754. }
  755. }
  756. }
  757. if (!firstTurn && player < PlayerColor::PLAYER_LIMIT)//not the first day and town not neutral
  758. {
  759. n.res[player] = n.res[player] + t->dailyIncome();
  760. }
  761. if(t->hasBuilt(BuildingID::GRAIL)
  762. && t->town->buildings.at(BuildingID::GRAIL)->height == CBuilding::HEIGHT_SKYSHIP)
  763. {
  764. // Skyship, probably easier to handle same as Veil of darkness
  765. //do it every new day after veils apply
  766. if (player != PlayerColor::NEUTRAL) //do not reveal fow for neutral player
  767. {
  768. FoWChange fw;
  769. fw.mode = 1;
  770. fw.player = player;
  771. // find all hidden tiles
  772. const auto fow = getPlayerTeam(player)->fogOfWarMap;
  773. auto shape = fow->shape();
  774. for(size_t z = 0; z < shape[0]; z++)
  775. for(size_t x = 0; x < shape[1]; x++)
  776. for(size_t y = 0; y < shape[2]; y++)
  777. if (!(*fow)[z][x][y])
  778. fw.tiles.insert(int3(x, y, z));
  779. sendAndApply (&fw);
  780. }
  781. }
  782. if (t->hasBonusOfType (BonusType::DARKNESS))
  783. {
  784. for (auto & player : gs->players)
  785. {
  786. if (getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  787. getPlayerRelations(player.first, t->tempOwner) == PlayerRelations::ENEMIES)
  788. changeFogOfWar(t->visitablePos(), t->getBonusLocalFirst(Selector::type()(BonusType::DARKNESS))->val, player.first, true);
  789. }
  790. }
  791. }
  792. if (newMonth)
  793. {
  794. SetAvailableArtifacts saa;
  795. saa.id = -1;
  796. pickAllowedArtsSet(saa.arts, getRandomGenerator());
  797. sendAndApply(&saa);
  798. }
  799. sendAndApply(&n);
  800. if (newWeek)
  801. {
  802. //spawn wandering monsters
  803. if (newMonth && (n.specialWeek == NewTurn::DOUBLE_GROWTH || n.specialWeek == NewTurn::DEITYOFFIRE))
  804. {
  805. spawnWanderingMonsters(n.creatureid);
  806. }
  807. //new week info popup
  808. if (!firstTurn)
  809. {
  810. InfoWindow iw;
  811. switch (n.specialWeek)
  812. {
  813. case NewTurn::DOUBLE_GROWTH:
  814. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 131);
  815. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  816. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  817. break;
  818. case NewTurn::PLAGUE:
  819. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 132);
  820. break;
  821. case NewTurn::BONUS_GROWTH:
  822. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 134);
  823. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  824. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  825. break;
  826. case NewTurn::DEITYOFFIRE:
  827. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 135);
  828. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 42); //%s imp
  829. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 42); //%s imp
  830. iw.text.replacePositiveNumber(15); //%+d 15
  831. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 43); //%s familiar
  832. iw.text.replacePositiveNumber(15); //%+d 15
  833. break;
  834. default:
  835. if (newMonth)
  836. {
  837. iw.text.appendLocalString(EMetaText::ARRAY_TXT, (130));
  838. iw.text.replaceLocalString(EMetaText::ARRAY_TXT, getRandomGenerator().nextInt(32, 41));
  839. }
  840. else
  841. {
  842. iw.text.appendLocalString(EMetaText::ARRAY_TXT, (133));
  843. iw.text.replaceLocalString(EMetaText::ARRAY_TXT, getRandomGenerator().nextInt(43, 57));
  844. }
  845. }
  846. for (auto & elem : gs->players)
  847. {
  848. iw.player = elem.first;
  849. sendAndApply(&iw);
  850. }
  851. }
  852. }
  853. logGlobal->trace("Info about turn %d has been sent!", n.day);
  854. handleTimeEvents();
  855. //call objects
  856. for (auto & elem : gs->map->objects)
  857. {
  858. if (elem)
  859. elem->newTurn(getRandomGenerator());
  860. }
  861. synchronizeArtifactHandlerLists(); //new day events may have changed them. TODO better of managing that
  862. }
  863. void CGameHandler::run(bool resume)
  864. {
  865. LOG_TRACE_PARAMS(logGlobal, "resume=%d", resume);
  866. using namespace boost::posix_time;
  867. for (auto cc : lobby->connections)
  868. {
  869. auto players = lobby->getAllClientPlayers(cc->connectionID);
  870. std::stringstream sbuffer;
  871. sbuffer << "Connection " << cc->connectionID << " will handle " << players.size() << " player: ";
  872. for (PlayerColor color : players)
  873. {
  874. sbuffer << color << " ";
  875. {
  876. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  877. connections[color].insert(cc);
  878. }
  879. }
  880. logGlobal->info(sbuffer.str());
  881. }
  882. #if SCRIPTING_ENABLED
  883. services()->scripts()->run(serverScripts);
  884. #endif
  885. if(resume)
  886. events::GameResumed::defaultExecute(serverEventBus.get());
  887. auto playerTurnOrder = generatePlayerTurnOrder();
  888. if(!resume)
  889. for(auto & playerColor : playerTurnOrder)
  890. turnTimerHandler.onGameplayStart(gs->players[playerColor]);
  891. while(lobby->state == EServerState::GAMEPLAY)
  892. {
  893. if(!resume)
  894. {
  895. newTurn();
  896. events::TurnStarted::defaultExecute(serverEventBus.get());
  897. }
  898. std::list<PlayerColor>::iterator it;
  899. if (resume)
  900. {
  901. it = std::find(playerTurnOrder.begin(), playerTurnOrder.end(), gs->currentPlayer);
  902. }
  903. else
  904. {
  905. it = playerTurnOrder.begin();
  906. }
  907. resume = false;
  908. for (; (it != playerTurnOrder.end()) && (lobby->state == EServerState::GAMEPLAY) ; it++)
  909. {
  910. auto playerColor = *it;
  911. auto onGetTurn = [&](events::PlayerGotTurn & event)
  912. {
  913. //if player runs out of time, he shouldn't get the turn (especially AI)
  914. //pre-trigger may change anything, should check before each player
  915. //TODO: is it enough to check only one player?
  916. checkVictoryLossConditionsForAll();
  917. auto player = event.getPlayer();
  918. const PlayerState * playerState = &gs->players[player];
  919. if(playerState->status != EPlayerStatus::INGAME)
  920. {
  921. event.setPlayer(PlayerColor::CANNOT_DETERMINE);
  922. }
  923. else
  924. {
  925. states.setFlag(player, &PlayerStatus::makingTurn, true);
  926. YourTurn yt;
  927. yt.player = player;
  928. //Change local daysWithoutCastle counter for local interface message //TODO: needed?
  929. yt.daysWithoutCastle = playerState->daysWithoutCastle;
  930. applyAndSend(&yt);
  931. turnTimerHandler.onPlayerGetTurn(gs->players[player]);
  932. }
  933. };
  934. events::PlayerGotTurn::defaultExecute(serverEventBus.get(), onGetTurn, playerColor);
  935. if(playerColor != PlayerColor::CANNOT_DETERMINE)
  936. {
  937. //wait till turn is done
  938. const int waitTime = 100; //ms
  939. boost::unique_lock<boost::mutex> lock(states.mx);
  940. while(states.players.at(playerColor).makingTurn && lobby->state == EServerState::GAMEPLAY)
  941. {
  942. turnTimerHandler.onPlayerMakingTurn(gs->players[playerColor], waitTime);
  943. if(gs->curB)
  944. turnTimerHandler.onBattleLoop(waitTime);
  945. static time_duration p = milliseconds(waitTime);
  946. states.cv.timed_wait(lock, p);
  947. }
  948. }
  949. }
  950. //additional check that game is not finished
  951. bool activePlayer = false;
  952. for (auto player : playerTurnOrder)
  953. {
  954. if (gs->players[player].status == EPlayerStatus::INGAME)
  955. activePlayer = true;
  956. }
  957. if(!activePlayer)
  958. lobby->state = EServerState::GAMEPLAY_ENDED;
  959. }
  960. }
  961. std::list<PlayerColor> CGameHandler::generatePlayerTurnOrder() const
  962. {
  963. // Generate player turn order
  964. std::list<PlayerColor> playerTurnOrder;
  965. for (const auto & player : gs->players) // add human players first
  966. {
  967. if (player.second.human)
  968. playerTurnOrder.push_back(player.first);
  969. }
  970. for (const auto & player : gs->players) // then add non-human players
  971. {
  972. if (!player.second.human)
  973. playerTurnOrder.push_back(player.first);
  974. }
  975. return playerTurnOrder;
  976. }
  977. void CGameHandler::giveSpells(const CGTownInstance *t, const CGHeroInstance *h)
  978. {
  979. if (!h->hasSpellbook())
  980. return; //hero hasn't spellbook
  981. ChangeSpells cs;
  982. cs.hid = h->id;
  983. cs.learn = true;
  984. if (t->hasBuilt(BuildingID::GRAIL, ETownType::CONFLUX) && t->hasBuilt(BuildingID::MAGES_GUILD_1))
  985. {
  986. // Aurora Borealis give spells of all levels even if only level 1 mages guild built
  987. for (int i = 0; i < h->maxSpellLevel(); i++)
  988. {
  989. std::vector<SpellID> spells;
  990. getAllowedSpells(spells, i+1);
  991. for (auto & spell : spells)
  992. cs.spells.insert(spell);
  993. }
  994. }
  995. else
  996. {
  997. for (int i = 0; i < std::min(t->mageGuildLevel(), h->maxSpellLevel()); i++)
  998. {
  999. for (int j = 0; j < t->spellsAtLevel(i+1, true) && j < t->spells.at(i).size(); j++)
  1000. {
  1001. if (!h->spellbookContainsSpell(t->spells.at(i).at(j)))
  1002. cs.spells.insert(t->spells.at(i).at(j));
  1003. }
  1004. }
  1005. }
  1006. if (!cs.spells.empty())
  1007. sendAndApply(&cs);
  1008. }
  1009. bool CGameHandler::removeObject(const CGObjectInstance * obj)
  1010. {
  1011. if (!obj || !getObj(obj->id))
  1012. {
  1013. logGlobal->error("Something wrong, that object already has been removed or hasn't existed!");
  1014. return false;
  1015. }
  1016. RemoveObject ro;
  1017. ro.id = obj->id;
  1018. sendAndApply(&ro);
  1019. checkVictoryLossConditionsForAll(); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1020. return true;
  1021. }
  1022. bool CGameHandler::moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit, PlayerColor asker)
  1023. {
  1024. const CGHeroInstance *h = getHero(hid);
  1025. // not turn of that hero or player can't simply teleport hero (at least not with this function)
  1026. if (!h || (asker != PlayerColor::NEUTRAL && (teleporting || h->getOwner() != gs->currentPlayer)))
  1027. {
  1028. if(h && getStartInfo()->turnTimerInfo.isEnabled() && gs->players[h->getOwner()].turnTimer.turnTimer == 0)
  1029. return true; //timer expired, no error
  1030. logGlobal->error("Illegal call to move hero!");
  1031. return false;
  1032. }
  1033. logGlobal->trace("Player %d (%s) wants to move hero %d from %s to %s", asker, asker.getStr(), hid.getNum(), h->pos.toString(), dst.toString());
  1034. const int3 hmpos = h->convertToVisitablePos(dst);
  1035. if (!gs->map->isInTheMap(hmpos))
  1036. {
  1037. logGlobal->error("Destination tile is outside the map!");
  1038. return false;
  1039. }
  1040. const TerrainTile t = *getTile(hmpos);
  1041. const int3 guardPos = gs->guardingCreaturePosition(hmpos);
  1042. const bool embarking = !h->boat && !t.visitableObjects.empty() && t.visitableObjects.back()->ID == Obj::BOAT;
  1043. const bool disembarking = h->boat
  1044. && t.terType->isLand()
  1045. && (dst == h->pos
  1046. || (h->boat->layer == EPathfindingLayer::SAIL && !t.blocked));
  1047. //result structure for start - movement failed, no move points used
  1048. TryMoveHero tmh;
  1049. tmh.id = hid;
  1050. tmh.start = h->pos;
  1051. tmh.end = dst;
  1052. tmh.result = TryMoveHero::FAILED;
  1053. tmh.movePoints = h->movementPointsRemaining();
  1054. //check if destination tile is available
  1055. auto pathfinderHelper = std::make_unique<CPathfinderHelper>(gs, h, PathfinderOptions());
  1056. auto ti = pathfinderHelper->getTurnInfo();
  1057. const bool canFly = pathfinderHelper->hasBonusOfType(BonusType::FLYING_MOVEMENT) || (h->boat && h->boat->layer == EPathfindingLayer::AIR);
  1058. const bool canWalkOnSea = pathfinderHelper->hasBonusOfType(BonusType::WATER_WALKING) || (h->boat && h->boat->layer == EPathfindingLayer::WATER);
  1059. const int cost = pathfinderHelper->getMovementCost(h->visitablePos(), hmpos, nullptr, nullptr, h->movementPointsRemaining());
  1060. //it's a rock or blocked and not visitable tile
  1061. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1062. if (((!t.terType->isPassable() || (t.blocked && !t.visitable && !canFly))
  1063. && complain("Cannot move hero, destination tile is blocked!"))
  1064. || ((!h->boat && !canWalkOnSea && !canFly && t.terType->isWater() && (t.visitableObjects.size() < 1 || !t.visitableObjects.back()->isCoastVisitable())) //hero is not on boat/water walking and dst water tile doesn't contain boat/hero (objs visitable from land) -> we test back cause boat may be on top of another object (#276)
  1065. && complain("Cannot move hero, destination tile is on water!"))
  1066. || ((h->boat && h->boat->layer == EPathfindingLayer::SAIL && t.terType->isLand() && t.blocked)
  1067. && complain("Cannot disembark hero, tile is blocked!"))
  1068. || ((distance(h->pos, dst) >= 1.5 && !teleporting)
  1069. && complain("Tiles are not neighboring!"))
  1070. || ((h->inTownGarrison)
  1071. && complain("Can not move garrisoned hero!"))
  1072. || (((int)h->movementPointsRemaining() < cost && dst != h->pos && !teleporting)
  1073. && complain("Hero doesn't have any movement points left!"))
  1074. || ((transit && !canFly && !CGTeleport::isTeleport(t.topVisitableObj()))
  1075. && complain("Hero cannot transit over this tile!"))
  1076. /*|| (states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1077. && complain("Cannot move hero during the battle"))*/)
  1078. {
  1079. //send info about movement failure
  1080. sendAndApply(&tmh);
  1081. return false;
  1082. }
  1083. //several generic blocks of code
  1084. // should be called if hero changes tile but before applying TryMoveHero package
  1085. auto leaveTile = [&]()
  1086. {
  1087. for (CGObjectInstance *obj : gs->map->getTile(int3(h->pos.x-1, h->pos.y, h->pos.z)).visitableObjects)
  1088. {
  1089. obj->onHeroLeave(h);
  1090. }
  1091. this->getTilesInRange(tmh.fowRevealed, h->getSightCenter()+(tmh.end-tmh.start), h->getSightRadius(), h->tempOwner, 1);
  1092. };
  1093. auto doMove = [&](TryMoveHero::EResult result, EGuardLook lookForGuards,
  1094. EVisitDest visitDest, ELEaveTile leavingTile) -> bool
  1095. {
  1096. LOG_TRACE_PARAMS(logGlobal, "Hero %s starts movement from %s to %s", h->getNameTranslated() % tmh.start.toString() % tmh.end.toString());
  1097. auto moveQuery = std::make_shared<CHeroMovementQuery>(this, tmh, h);
  1098. queries->addQuery(moveQuery);
  1099. if (leavingTile == LEAVING_TILE)
  1100. leaveTile();
  1101. if (isInTheMap(guardPos))
  1102. tmh.attackedFrom = std::make_optional(guardPos);
  1103. tmh.result = result;
  1104. sendAndApply(&tmh);
  1105. if (visitDest == VISIT_DEST && t.topVisitableObj() && t.topVisitableObj()->id == h->id)
  1106. { // Hero should be always able to visit any object he staying on even if there guards around
  1107. visitObjectOnTile(t, h);
  1108. }
  1109. else if (lookForGuards == CHECK_FOR_GUARDS && isInTheMap(guardPos))
  1110. {
  1111. const TerrainTile &guardTile = *gs->getTile(guardPos);
  1112. objectVisited(guardTile.visitableObjects.back(), h);
  1113. moveQuery->visitDestAfterVictory = visitDest==VISIT_DEST;
  1114. }
  1115. else if (visitDest == VISIT_DEST)
  1116. {
  1117. visitObjectOnTile(t, h);
  1118. }
  1119. for(auto topQuery = queries->topQuery(h->tempOwner); true; topQuery = queries->topQuery(h->tempOwner))
  1120. {
  1121. moveQuery = std::dynamic_pointer_cast<CHeroMovementQuery>(topQuery);
  1122. if(moveQuery
  1123. && (!transit || result == TryMoveHero::FAILED || moveQuery->tmh.stopMovement()))
  1124. queries->popIfTop(moveQuery);
  1125. else
  1126. break;
  1127. }
  1128. logGlobal->trace("Hero %s ends movement", h->getNameTranslated());
  1129. return result != TryMoveHero::FAILED;
  1130. };
  1131. //interaction with blocking object (like resources)
  1132. auto blockingVisit = [&]() -> bool
  1133. {
  1134. for (CGObjectInstance *obj : t.visitableObjects)
  1135. {
  1136. if(h->boat && !obj->isBlockedVisitable() && !h->boat->onboardVisitAllowed)
  1137. return doMove(TryMoveHero::SUCCESS, this->IGNORE_GUARDS, DONT_VISIT_DEST, REMAINING_ON_TILE);
  1138. if (obj != h && obj->isBlockedVisitable() && !obj->passableFor(h->tempOwner))
  1139. {
  1140. EVisitDest visitDest = VISIT_DEST;
  1141. if(h->boat && !h->boat->onboardVisitAllowed)
  1142. visitDest = DONT_VISIT_DEST;
  1143. return doMove(TryMoveHero::BLOCKING_VISIT, this->IGNORE_GUARDS, visitDest, REMAINING_ON_TILE);
  1144. }
  1145. }
  1146. return false;
  1147. };
  1148. if (!transit && embarking)
  1149. {
  1150. tmh.movePoints = h->movementPointsAfterEmbark(h->movementPointsRemaining(), cost, false, ti);
  1151. return doMove(TryMoveHero::EMBARK, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  1152. // In H3 embark ignore guards
  1153. }
  1154. if (disembarking)
  1155. {
  1156. tmh.movePoints = h->movementPointsAfterEmbark(h->movementPointsRemaining(), cost, true, ti);
  1157. return doMove(TryMoveHero::DISEMBARK, CHECK_FOR_GUARDS, VISIT_DEST, LEAVING_TILE);
  1158. }
  1159. if (teleporting)
  1160. {
  1161. if (blockingVisit()) // e.g. hero on the other side of teleporter
  1162. return true;
  1163. doMove(TryMoveHero::TELEPORTATION, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  1164. // visit town for town portal \ castle gates
  1165. // do not use generic visitObjectOnTile to avoid double-teleporting
  1166. // if this moveHero call was triggered by teleporter
  1167. if (!t.visitableObjects.empty())
  1168. {
  1169. if (CGTownInstance * town = dynamic_cast<CGTownInstance *>(t.visitableObjects.back()))
  1170. town->onHeroVisit(h);
  1171. }
  1172. return true;
  1173. }
  1174. //still here? it is standard movement!
  1175. {
  1176. tmh.movePoints = (int)h->movementPointsRemaining() >= cost
  1177. ? h->movementPointsRemaining() - cost
  1178. : 0;
  1179. EGuardLook lookForGuards = CHECK_FOR_GUARDS;
  1180. EVisitDest visitDest = VISIT_DEST;
  1181. if (transit)
  1182. {
  1183. if (CGTeleport::isTeleport(t.topVisitableObj()))
  1184. visitDest = DONT_VISIT_DEST;
  1185. if (canFly)
  1186. {
  1187. lookForGuards = IGNORE_GUARDS;
  1188. visitDest = DONT_VISIT_DEST;
  1189. }
  1190. }
  1191. else if (blockingVisit())
  1192. return true;
  1193. if(h->boat && !h->boat->onboardAssaultAllowed)
  1194. lookForGuards = IGNORE_GUARDS;
  1195. doMove(TryMoveHero::SUCCESS, lookForGuards, visitDest, LEAVING_TILE);
  1196. return true;
  1197. }
  1198. }
  1199. bool CGameHandler::teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker)
  1200. {
  1201. const CGHeroInstance *h = getHero(hid);
  1202. const CGTownInstance *t = getTown(dstid);
  1203. if (!h || !t || h->getOwner() != gs->currentPlayer)
  1204. COMPLAIN_RET("Invalid call to teleportHero!");
  1205. const CGTownInstance *from = h->visitedTown;
  1206. if (((h->getOwner() != t->getOwner())
  1207. && complain("Cannot teleport hero to another player"))
  1208. || (from->town->faction->getId() != t->town->faction->getId()
  1209. && complain("Source town and destination town should belong to the same faction"))
  1210. || ((!from || !from->hasBuilt(BuildingSubID::CASTLE_GATE))
  1211. && complain("Hero must be in town with Castle gate for teleporting"))
  1212. || (!t->hasBuilt(BuildingSubID::CASTLE_GATE)
  1213. && complain("Cannot teleport hero to town without Castle gate in it")))
  1214. return false;
  1215. int3 pos = h->convertFromVisitablePos(t->visitablePos());
  1216. moveHero(hid,pos,1);
  1217. return true;
  1218. }
  1219. void CGameHandler::setOwner(const CGObjectInstance * obj, const PlayerColor owner)
  1220. {
  1221. PlayerColor oldOwner = getOwner(obj->id);
  1222. SetObjectProperty sop(obj->id, ObjProperty::OWNER, owner.getNum());
  1223. sendAndApply(&sop);
  1224. std::set<PlayerColor> playerColors = {owner, oldOwner};
  1225. checkVictoryLossConditions(playerColors);
  1226. const CGTownInstance * town = dynamic_cast<const CGTownInstance *>(obj);
  1227. if (town) //town captured
  1228. {
  1229. if (owner < PlayerColor::PLAYER_LIMIT) //new owner is real player
  1230. {
  1231. if (town->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  1232. setPortalDwelling(town, true, false);
  1233. }
  1234. if (oldOwner < PlayerColor::PLAYER_LIMIT) //old owner is real player
  1235. {
  1236. if (getPlayerState(oldOwner)->towns.empty() && getPlayerState(oldOwner)->status != EPlayerStatus::LOSER) //previous player lost last last town
  1237. {
  1238. InfoWindow iw;
  1239. iw.player = oldOwner;
  1240. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  1241. iw.text.replaceLocalString(EMetaText::COLOR, oldOwner.getNum());
  1242. sendAndApply(&iw);
  1243. }
  1244. }
  1245. }
  1246. const PlayerState * p = getPlayerState(owner);
  1247. if ((obj->ID == Obj::CREATURE_GENERATOR1 || obj->ID == Obj::CREATURE_GENERATOR4) && p && p->dwellings.size()==1)//first dwelling captured
  1248. {
  1249. for (const CGTownInstance * t : getPlayerState(owner)->towns)
  1250. {
  1251. if (t->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  1252. setPortalDwelling(t);//set initial creatures for all portals of summoning
  1253. }
  1254. }
  1255. }
  1256. void CGameHandler::showBlockingDialog(BlockingDialog *iw)
  1257. {
  1258. auto dialogQuery = std::make_shared<CBlockingDialogQuery>(this, *iw);
  1259. queries->addQuery(dialogQuery);
  1260. iw->queryID = dialogQuery->queryID;
  1261. sendToAllClients(iw);
  1262. }
  1263. void CGameHandler::showTeleportDialog(TeleportDialog *iw)
  1264. {
  1265. auto dialogQuery = std::make_shared<CTeleportDialogQuery>(this, *iw);
  1266. queries->addQuery(dialogQuery);
  1267. iw->queryID = dialogQuery->queryID;
  1268. sendToAllClients(iw);
  1269. }
  1270. void CGameHandler::giveResource(PlayerColor player, GameResID which, int val) //TODO: cap according to Bersy's suggestion
  1271. {
  1272. if (!val) return; //don't waste time on empty call
  1273. TResources resources;
  1274. resources[which] = val;
  1275. giveResources(player, resources);
  1276. }
  1277. void CGameHandler::giveResources(PlayerColor player, TResources resources)
  1278. {
  1279. SetResources sr;
  1280. sr.abs = false;
  1281. sr.player = player;
  1282. sr.res = resources;
  1283. sendAndApply(&sr);
  1284. }
  1285. void CGameHandler::giveCreatures(const CArmedInstance *obj, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove)
  1286. {
  1287. COMPLAIN_RET_IF(!creatures.stacksCount(), "Strange, giveCreatures called without args!");
  1288. COMPLAIN_RET_IF(obj->stacksCount(), "Cannot give creatures from not-cleared object!");
  1289. COMPLAIN_RET_IF(creatures.stacksCount() > GameConstants::ARMY_SIZE, "Too many stacks to give!");
  1290. //first we move creatures to give to make them army of object-source
  1291. for (auto & elem : creatures.Slots())
  1292. {
  1293. addToSlot(StackLocation(obj, obj->getSlotFor(elem.second->type)), elem.second->type, elem.second->count);
  1294. }
  1295. tryJoiningArmy(obj, h, remove, true);
  1296. }
  1297. void CGameHandler::takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures)
  1298. {
  1299. std::vector<CStackBasicDescriptor> cres = creatures;
  1300. if (cres.size() <= 0)
  1301. return;
  1302. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  1303. for (CStackBasicDescriptor &sbd : cres)
  1304. {
  1305. TQuantity collected = 0;
  1306. while(collected < sbd.count)
  1307. {
  1308. bool foundSth = false;
  1309. for (auto i = obj->Slots().begin(); i != obj->Slots().end(); i++)
  1310. {
  1311. if (i->second->type == sbd.type)
  1312. {
  1313. TQuantity take = std::min(sbd.count - collected, i->second->count); //collect as much cres as we can
  1314. changeStackCount(StackLocation(obj, i->first), -take, false);
  1315. collected += take;
  1316. foundSth = true;
  1317. break;
  1318. }
  1319. }
  1320. if (!foundSth) //we went through the whole loop and haven't found appropriate cres
  1321. {
  1322. complain("Unexpected failure during taking creatures!");
  1323. return;
  1324. }
  1325. }
  1326. }
  1327. }
  1328. void CGameHandler::heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  1329. {
  1330. HeroVisitCastle vc;
  1331. vc.hid = hero->id;
  1332. vc.tid = obj->id;
  1333. vc.flags |= 1;
  1334. sendAndApply(&vc);
  1335. visitCastleObjects(obj, hero);
  1336. giveSpells (obj, hero);
  1337. checkVictoryLossConditionsForPlayer(hero->tempOwner); //transported artifact?
  1338. }
  1339. void CGameHandler::visitCastleObjects(const CGTownInstance * t, const CGHeroInstance * h)
  1340. {
  1341. for (auto building : t->bonusingBuildings)
  1342. building->onHeroVisit(h);
  1343. }
  1344. void CGameHandler::stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  1345. {
  1346. HeroVisitCastle vc;
  1347. vc.hid = hero->id;
  1348. vc.tid = obj->id;
  1349. sendAndApply(&vc);
  1350. }
  1351. void CGameHandler::removeArtifact(const ArtifactLocation &al)
  1352. {
  1353. EraseArtifact ea;
  1354. ea.al = al;
  1355. sendAndApply(&ea);
  1356. }
  1357. void CGameHandler::changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells)
  1358. {
  1359. ChangeSpells cs;
  1360. cs.hid = hero->id;
  1361. cs.spells = spells;
  1362. cs.learn = give;
  1363. sendAndApply(&cs);
  1364. }
  1365. void CGameHandler::giveHeroBonus(GiveBonus * bonus)
  1366. {
  1367. sendAndApply(bonus);
  1368. }
  1369. void CGameHandler::setMovePoints(SetMovePoints * smp)
  1370. {
  1371. sendAndApply(smp);
  1372. }
  1373. void CGameHandler::setManaPoints(ObjectInstanceID hid, int val)
  1374. {
  1375. SetMana sm;
  1376. sm.hid = hid;
  1377. sm.val = val;
  1378. sm.absolute = true;
  1379. sendAndApply(&sm);
  1380. }
  1381. void CGameHandler::giveHero(ObjectInstanceID id, PlayerColor player, ObjectInstanceID boatId)
  1382. {
  1383. GiveHero gh;
  1384. gh.id = id;
  1385. gh.player = player;
  1386. gh.boatId = boatId;
  1387. sendAndApply(&gh);
  1388. //Reveal fow around new hero, especially released from Prison
  1389. auto h = getHero(id);
  1390. changeFogOfWar(h->pos, h->getSightRadius(), player, false);
  1391. }
  1392. void CGameHandler::changeObjPos(ObjectInstanceID objid, int3 newPos)
  1393. {
  1394. ChangeObjPos cop;
  1395. cop.objid = objid;
  1396. cop.nPos = newPos;
  1397. sendAndApply(&cop);
  1398. }
  1399. void CGameHandler::useScholarSkill(ObjectInstanceID fromHero, ObjectInstanceID toHero)
  1400. {
  1401. const CGHeroInstance * h1 = getHero(fromHero);
  1402. const CGHeroInstance * h2 = getHero(toHero);
  1403. int h1_scholarSpellLevel = h1->valOfBonuses(BonusType::LEARN_MEETING_SPELL_LIMIT, -1);
  1404. int h2_scholarSpellLevel = h2->valOfBonuses(BonusType::LEARN_MEETING_SPELL_LIMIT, -1);
  1405. if (h1_scholarSpellLevel < h2_scholarSpellLevel)
  1406. {
  1407. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  1408. std::swap(fromHero, toHero);
  1409. }
  1410. int ScholarSpellLevel = std::max(h1_scholarSpellLevel, h2_scholarSpellLevel);//heroes can trade up to this level
  1411. if (!ScholarSpellLevel || !h1->hasSpellbook() || !h2->hasSpellbook())
  1412. return;//no scholar skill or no spellbook
  1413. int h1Lvl = std::min(ScholarSpellLevel, h1->maxSpellLevel()),
  1414. h2Lvl = std::min(ScholarSpellLevel, h2->maxSpellLevel());//heroes can receive this levels
  1415. ChangeSpells cs1;
  1416. cs1.learn = true;
  1417. cs1.hid = toHero;//giving spells to first hero
  1418. for (auto it : h1->getSpellsInSpellbook())
  1419. if (h2Lvl >= it.toSpell()->level && !h2->spellbookContainsSpell(it))//hero can learn it and don't have it yet
  1420. cs1.spells.insert(it);//spell to learn
  1421. ChangeSpells cs2;
  1422. cs2.learn = true;
  1423. cs2.hid = fromHero;
  1424. for (auto it : h2->getSpellsInSpellbook())
  1425. if (h1Lvl >= it.toSpell()->level && !h1->spellbookContainsSpell(it))
  1426. cs2.spells.insert(it);
  1427. if (!cs1.spells.empty() || !cs2.spells.empty())//create a message
  1428. {
  1429. int ScholarSkillLevel = std::max(h1->getSecSkillLevel(SecondarySkill::SCHOLAR),
  1430. h2->getSecSkillLevel(SecondarySkill::SCHOLAR));
  1431. InfoWindow iw;
  1432. iw.player = h1->tempOwner;
  1433. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, 18, ScholarSkillLevel, 0);
  1434. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  1435. iw.text.replaceRawString(h1->getNameTranslated());
  1436. if (!cs2.spells.empty())//if found new spell - apply
  1437. {
  1438. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 140);//learns
  1439. int size = static_cast<int>(cs2.spells.size());
  1440. for (auto it : cs2.spells)
  1441. {
  1442. iw.components.emplace_back(Component::EComponentType::SPELL, it, 1, 0);
  1443. iw.text.appendLocalString(EMetaText::SPELL_NAME, it.toEnum());
  1444. switch (size--)
  1445. {
  1446. case 2:
  1447. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);
  1448. case 1:
  1449. break;
  1450. default:
  1451. iw.text.appendRawString(", ");
  1452. }
  1453. }
  1454. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 142);//from %s
  1455. iw.text.replaceRawString(h2->getNameTranslated());
  1456. sendAndApply(&cs2);
  1457. }
  1458. if (!cs1.spells.empty() && !cs2.spells.empty())
  1459. {
  1460. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);//and
  1461. }
  1462. if (!cs1.spells.empty())
  1463. {
  1464. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 147);//teaches
  1465. int size = static_cast<int>(cs1.spells.size());
  1466. for (auto it : cs1.spells)
  1467. {
  1468. iw.components.emplace_back(Component::EComponentType::SPELL, it, 1, 0);
  1469. iw.text.appendLocalString(EMetaText::SPELL_NAME, it.toEnum());
  1470. switch (size--)
  1471. {
  1472. case 2:
  1473. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);
  1474. case 1:
  1475. break;
  1476. default:
  1477. iw.text.appendRawString(", ");
  1478. }
  1479. }
  1480. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 148);//from %s
  1481. iw.text.replaceRawString(h2->getNameTranslated());
  1482. sendAndApply(&cs1);
  1483. }
  1484. sendAndApply(&iw);
  1485. }
  1486. }
  1487. void CGameHandler::heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  1488. {
  1489. auto h1 = getHero(hero1), h2 = getHero(hero2);
  1490. if (getPlayerRelations(h1->getOwner(), h2->getOwner()))
  1491. {
  1492. auto exchange = std::make_shared<CGarrisonDialogQuery>(this, h1, h2);
  1493. ExchangeDialog hex;
  1494. hex.queryID = exchange->queryID;
  1495. hex.player = h1->getOwner();
  1496. hex.hero1 = hero1;
  1497. hex.hero2 = hero2;
  1498. sendAndApply(&hex);
  1499. useScholarSkill(hero1,hero2);
  1500. queries->addQuery(exchange);
  1501. }
  1502. }
  1503. void CGameHandler::sendToAllClients(CPackForClient * pack)
  1504. {
  1505. logNetwork->trace("\tSending to all clients: %s", typeid(*pack).name());
  1506. for (auto c : lobby->connections)
  1507. {
  1508. if(!c->isOpen())
  1509. continue;
  1510. c->sendPack(pack);
  1511. }
  1512. }
  1513. void CGameHandler::sendAndApply(CPackForClient * pack)
  1514. {
  1515. sendToAllClients(pack);
  1516. gs->apply(pack);
  1517. logNetwork->trace("\tApplied on gs: %s", typeid(*pack).name());
  1518. }
  1519. void CGameHandler::applyAndSend(CPackForClient * pack)
  1520. {
  1521. gs->apply(pack);
  1522. sendToAllClients(pack);
  1523. }
  1524. void CGameHandler::sendAndApply(CGarrisonOperationPack * pack)
  1525. {
  1526. sendAndApply(static_cast<CPackForClient *>(pack));
  1527. checkVictoryLossConditionsForAll();
  1528. }
  1529. void CGameHandler::sendAndApply(SetResources * pack)
  1530. {
  1531. sendAndApply(static_cast<CPackForClient *>(pack));
  1532. checkVictoryLossConditionsForPlayer(pack->player);
  1533. }
  1534. void CGameHandler::sendAndApply(NewStructures * pack)
  1535. {
  1536. sendAndApply(static_cast<CPackForClient *>(pack));
  1537. checkVictoryLossConditionsForPlayer(getTown(pack->tid)->tempOwner);
  1538. }
  1539. bool CGameHandler::isPlayerOwns(CPackForServer * pack, ObjectInstanceID id)
  1540. {
  1541. return getPlayerAt(pack->c) == getOwner(id);
  1542. }
  1543. void CGameHandler::throwNotAllowedAction(CPackForServer * pack)
  1544. {
  1545. if(pack->c)
  1546. playerMessages->sendSystemMessage(pack->c, "You are not allowed to perform this action!");
  1547. logNetwork->error("Player is not allowed to perform this action!");
  1548. throw ExceptionNotAllowedAction();
  1549. }
  1550. void CGameHandler::wrongPlayerMessage(CPackForServer * pack, PlayerColor expectedplayer)
  1551. {
  1552. std::ostringstream oss;
  1553. oss << "You were identified as player " << getPlayerAt(pack->c) << " while expecting " << expectedplayer;
  1554. logNetwork->error(oss.str());
  1555. if(pack->c)
  1556. playerMessages->sendSystemMessage(pack->c, oss.str());
  1557. }
  1558. void CGameHandler::throwOnWrongOwner(CPackForServer * pack, ObjectInstanceID id)
  1559. {
  1560. if(!isPlayerOwns(pack, id))
  1561. {
  1562. wrongPlayerMessage(pack, getOwner(id));
  1563. throwNotAllowedAction(pack);
  1564. }
  1565. }
  1566. void CGameHandler::throwOnWrongPlayer(CPackForServer * pack, PlayerColor player)
  1567. {
  1568. if(!hasPlayerAt(player, pack->c) && player != getPlayerAt(pack->c))
  1569. {
  1570. wrongPlayerMessage(pack, player);
  1571. throwNotAllowedAction(pack);
  1572. }
  1573. }
  1574. void CGameHandler::throwAndComplain(CPackForServer * pack, std::string txt)
  1575. {
  1576. complain(txt);
  1577. throwNotAllowedAction(pack);
  1578. }
  1579. void CGameHandler::save(const std::string & filename)
  1580. {
  1581. logGlobal->info("Saving to %s", filename);
  1582. const auto stem = FileInfo::GetPathStem(filename);
  1583. const auto savefname = stem.to_string() + ".vsgm1";
  1584. CResourceHandler::get("local")->createResource(savefname);
  1585. try
  1586. {
  1587. {
  1588. CSaveFile save(*CResourceHandler::get("local")->getResourceName(ResourceID(stem.to_string(), EResType::SAVEGAME)));
  1589. saveCommonState(save);
  1590. logGlobal->info("Saving server state");
  1591. save << *this;
  1592. }
  1593. logGlobal->info("Game has been successfully saved!");
  1594. }
  1595. catch(std::exception &e)
  1596. {
  1597. logGlobal->error("Failed to save game: %s", e.what());
  1598. }
  1599. }
  1600. bool CGameHandler::load(const std::string & filename)
  1601. {
  1602. logGlobal->info("Loading from %s", filename);
  1603. const auto stem = FileInfo::GetPathStem(filename);
  1604. reinitScripting();
  1605. try
  1606. {
  1607. {
  1608. CLoadFile lf(*CResourceHandler::get()->getResourceName(ResourceID(stem.to_string(), EResType::SAVEGAME)), MINIMAL_SERIALIZATION_VERSION);
  1609. loadCommonState(lf);
  1610. logGlobal->info("Loading server state");
  1611. lf >> *this;
  1612. }
  1613. logGlobal->info("Game has been successfully loaded!");
  1614. }
  1615. catch(const ModIncompatibility & e)
  1616. {
  1617. logGlobal->error("Failed to load game: %s", e.what());
  1618. auto errorMsg = VLC->generaltexth->translate("vcmi.server.errors.modsIncompatibility") + '\n';
  1619. errorMsg += e.what();
  1620. lobby->announceMessage(errorMsg);
  1621. return false;
  1622. }
  1623. catch(const std::exception & e)
  1624. {
  1625. logGlobal->error("Failed to load game: %s", e.what());
  1626. return false;
  1627. }
  1628. gs->preInit(VLC);
  1629. gs->updateOnLoad(lobby->si.get());
  1630. return true;
  1631. }
  1632. bool CGameHandler::bulkSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner, si32 howMany)
  1633. {
  1634. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  1635. return false;
  1636. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  1637. const CCreatureSet & creatureSet = *army;
  1638. if((!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  1639. || (howMany < 1 && complain("Invalid split parameter!")))
  1640. {
  1641. return false;
  1642. }
  1643. auto actualAmount = army->getStackCount(slotSrc);
  1644. if(actualAmount <= howMany && complain(complainNotEnoughCreatures)) // '<=' because it's not intended just for moving a stack
  1645. return false;
  1646. auto freeSlots = creatureSet.getFreeSlots();
  1647. if(freeSlots.empty() && complain("No empty stacks"))
  1648. return false;
  1649. BulkRebalanceStacks bulkRS;
  1650. for(auto slot : freeSlots)
  1651. {
  1652. RebalanceStacks rs;
  1653. rs.srcArmy = army->id;
  1654. rs.dstArmy = army->id;
  1655. rs.srcSlot = slotSrc;
  1656. rs.dstSlot = slot;
  1657. rs.count = howMany;
  1658. bulkRS.moves.push_back(rs);
  1659. actualAmount -= howMany;
  1660. if(actualAmount <= howMany)
  1661. break;
  1662. }
  1663. sendAndApply(&bulkRS);
  1664. return true;
  1665. }
  1666. bool CGameHandler::bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner)
  1667. {
  1668. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  1669. return false;
  1670. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  1671. const CCreatureSet & creatureSet = *army;
  1672. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  1673. return false;
  1674. auto actualAmount = creatureSet.getStackCount(slotSrc);
  1675. if(actualAmount < 1 && complain(complainNoCreatures))
  1676. return false;
  1677. auto currentCreature = creatureSet.getCreature(slotSrc);
  1678. if(!currentCreature && complain(complainNoCreatures))
  1679. return false;
  1680. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, slotSrc);
  1681. if(!creatureSlots.size())
  1682. return false;
  1683. BulkRebalanceStacks bulkRS;
  1684. for(auto slot : creatureSlots)
  1685. {
  1686. RebalanceStacks rs;
  1687. rs.srcArmy = army->id;
  1688. rs.dstArmy = army->id;
  1689. rs.srcSlot = slot;
  1690. rs.dstSlot = slotSrc;
  1691. rs.count = creatureSet.getStackCount(slot);
  1692. bulkRS.moves.push_back(rs);
  1693. }
  1694. sendAndApply(&bulkRS);
  1695. return true;
  1696. }
  1697. bool CGameHandler::bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot)
  1698. {
  1699. if(!srcSlot.validSlot() && complain(complainInvalidSlot))
  1700. return false;
  1701. const CArmedInstance * armySrc = static_cast<const CArmedInstance*>(getObjInstance(srcArmy));
  1702. const CCreatureSet & setSrc = *armySrc;
  1703. if(!vstd::contains(setSrc.stacks, srcSlot) && complain(complainNoCreatures))
  1704. return false;
  1705. const CArmedInstance * armyDest = static_cast<const CArmedInstance*>(getObjInstance(destArmy));
  1706. const CCreatureSet & setDest = *armyDest;
  1707. auto freeSlots = setDest.getFreeSlotsQueue();
  1708. typedef std::map<SlotID, std::pair<SlotID, TQuantity>> TRebalanceMap;
  1709. TRebalanceMap moves;
  1710. auto srcQueue = setSrc.getCreatureQueue(srcSlot); // Exclude srcSlot, it should be moved last
  1711. auto slotsLeft = setSrc.stacksCount();
  1712. auto destMap = setDest.getCreatureMap();
  1713. TMapCreatureSlot::key_compare keyComp = destMap.key_comp();
  1714. while(!srcQueue.empty())
  1715. {
  1716. auto pair = srcQueue.top();
  1717. srcQueue.pop();
  1718. auto currCreature = pair.first;
  1719. auto currSlot = pair.second;
  1720. const auto quantity = setSrc.getStackCount(currSlot);
  1721. TMapCreatureSlot::iterator lb = destMap.lower_bound(currCreature);
  1722. const bool alreadyExists = (lb != destMap.end() && !(keyComp(currCreature, lb->first)));
  1723. if(!alreadyExists)
  1724. {
  1725. if(freeSlots.empty())
  1726. continue;
  1727. auto currFreeSlot = freeSlots.front();
  1728. freeSlots.pop();
  1729. destMap.insert(lb, TMapCreatureSlot::value_type(currCreature, currFreeSlot));
  1730. }
  1731. moves.insert(std::make_pair(currSlot, std::make_pair(destMap[currCreature], quantity)));
  1732. slotsLeft--;
  1733. }
  1734. if(slotsLeft == 1)
  1735. {
  1736. auto lastCreature = setSrc.getCreature(srcSlot);
  1737. auto slotToMove = SlotID();
  1738. // Try to find a slot for last creature
  1739. if(destMap.find(lastCreature) == destMap.end())
  1740. {
  1741. if(!freeSlots.empty())
  1742. slotToMove = freeSlots.front();
  1743. }
  1744. else
  1745. {
  1746. slotToMove = destMap[lastCreature];
  1747. }
  1748. if(slotToMove != SlotID())
  1749. {
  1750. const bool needsLastStack = armySrc->needsLastStack();
  1751. const auto quantity = setSrc.getStackCount(srcSlot) - (needsLastStack ? 1 : 0);
  1752. moves.insert(std::make_pair(srcSlot, std::make_pair(slotToMove, quantity)));
  1753. }
  1754. }
  1755. BulkRebalanceStacks bulkRS;
  1756. for(auto & move : moves)
  1757. {
  1758. RebalanceStacks rs;
  1759. rs.srcArmy = armySrc->id;
  1760. rs.dstArmy = armyDest->id;
  1761. rs.srcSlot = move.first;
  1762. rs.dstSlot = move.second.first;
  1763. rs.count = move.second.second;
  1764. bulkRS.moves.push_back(rs);
  1765. }
  1766. sendAndApply(&bulkRS);
  1767. return true;
  1768. }
  1769. bool CGameHandler::bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner)
  1770. {
  1771. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  1772. return false;
  1773. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  1774. const CCreatureSet & creatureSet = *army;
  1775. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  1776. return false;
  1777. auto actualAmount = creatureSet.getStackCount(slotSrc);
  1778. if(actualAmount <= 1 && complain(complainNoCreatures))
  1779. return false;
  1780. auto freeSlot = creatureSet.getFreeSlot();
  1781. auto currentCreature = creatureSet.getCreature(slotSrc);
  1782. if(freeSlot == SlotID() && creatureSet.isCreatureBalanced(currentCreature))
  1783. return true;
  1784. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, SlotID(-1), 1); // Ignore slots where's only 1 creature, don't ignore slotSrc
  1785. TQuantity totalCreatures = 0;
  1786. for(auto slot : creatureSlots)
  1787. totalCreatures += creatureSet.getStackCount(slot);
  1788. if(totalCreatures <= 1 && complain("Total creatures number is invalid"))
  1789. return false;
  1790. if(freeSlot != SlotID())
  1791. creatureSlots.push_back(freeSlot);
  1792. if(creatureSlots.empty() && complain("No available slots for smart rebalancing"))
  1793. return false;
  1794. const auto totalCreatureSlots = creatureSlots.size();
  1795. const auto rem = totalCreatures % totalCreatureSlots;
  1796. const auto quotient = totalCreatures / totalCreatureSlots;
  1797. // totalCreatures == rem * (quotient + 1) + (totalCreatureSlots - rem) * quotient;
  1798. // Proof: r(q+1)+(s-r)q = rq+r+qs-rq = r+qs = total, where total/s = q+r/s
  1799. BulkSmartRebalanceStacks bulkSRS;
  1800. if(freeSlot != SlotID())
  1801. {
  1802. RebalanceStacks rs;
  1803. rs.srcArmy = rs.dstArmy = army->id;
  1804. rs.srcSlot = slotSrc;
  1805. rs.dstSlot = freeSlot;
  1806. rs.count = 1;
  1807. bulkSRS.moves.push_back(rs);
  1808. }
  1809. auto currSlot = 0;
  1810. auto check = 0;
  1811. for(auto slot : creatureSlots)
  1812. {
  1813. ChangeStackCount csc;
  1814. csc.army = army->id;
  1815. csc.slot = slot;
  1816. csc.count = (currSlot < rem)
  1817. ? quotient + 1
  1818. : quotient;
  1819. csc.absoluteValue = true;
  1820. bulkSRS.changes.push_back(csc);
  1821. currSlot++;
  1822. check += csc.count;
  1823. }
  1824. if(check != totalCreatures)
  1825. {
  1826. complain((boost::format("Failure: totalCreatures=%d but check=%d") % totalCreatures % check).str());
  1827. return false;
  1828. }
  1829. sendAndApply(&bulkSRS);
  1830. return true;
  1831. }
  1832. bool CGameHandler::arrangeStacks(ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player)
  1833. {
  1834. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id1)),
  1835. * s2 = static_cast<const CArmedInstance *>(getObjInstance(id2));
  1836. const CCreatureSet &S1 = *s1, &S2 = *s2;
  1837. StackLocation sl1(s1, p1), sl2(s2, p2);
  1838. if (!sl1.slot.validSlot() || !sl2.slot.validSlot())
  1839. {
  1840. complain(complainInvalidSlot);
  1841. return false;
  1842. }
  1843. if (!isAllowedExchange(id1,id2))
  1844. {
  1845. complain("Cannot exchange stacks between these two objects!\n");
  1846. return false;
  1847. }
  1848. // We can always put stacks into locked garrison, but not take them out of it
  1849. auto notRemovable = [&](const CArmedInstance * army)
  1850. {
  1851. if (id1 != id2) // Stack arrangement inside locked garrison is allowed
  1852. {
  1853. auto g = dynamic_cast<const CGGarrison *>(army);
  1854. if (g && !g->removableUnits)
  1855. {
  1856. complain("Stacks in this garrison are not removable!\n");
  1857. return true;
  1858. }
  1859. }
  1860. return false;
  1861. };
  1862. if (what==1) //swap
  1863. {
  1864. if (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s1->getStackCount(p1))
  1865. || ((s2->tempOwner != player && s2->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)))
  1866. {
  1867. complain("Can't take troops from another player!");
  1868. return false;
  1869. }
  1870. if (sl1.army == sl2.army && sl1.slot == sl2.slot)
  1871. {
  1872. complain("Cannot swap stacks - slots are the same!");
  1873. return false;
  1874. }
  1875. if (!s1->slotEmpty(p1) && !s2->slotEmpty(p2))
  1876. {
  1877. if (notRemovable(sl1.army) || notRemovable(sl2.army))
  1878. return false;
  1879. }
  1880. if (s1->slotEmpty(p1) && notRemovable(sl2.army))
  1881. return false;
  1882. else if (s2->slotEmpty(p2) && notRemovable(sl1.army))
  1883. return false;
  1884. swapStacks(sl1, sl2);
  1885. }
  1886. else if (what==2)//merge
  1887. {
  1888. if ((s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot merge different creatures stacks!"))
  1889. || (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)) && complain("Can't take troops from another player!")))
  1890. return false;
  1891. if (s1->slotEmpty(p1) || s2->slotEmpty(p2))
  1892. {
  1893. complain("Cannot merge empty stack!");
  1894. return false;
  1895. }
  1896. else if (notRemovable(sl1.army))
  1897. return false;
  1898. moveStack(sl1, sl2);
  1899. }
  1900. else if (what==3) //split
  1901. {
  1902. const int countToMove = val - s2->getStackCount(p2);
  1903. const int countLeftOnSrc = s1->getStackCount(p1) - countToMove;
  1904. if ( (s1->tempOwner != player && countLeftOnSrc < s1->getStackCount(p1))
  1905. || (s2->tempOwner != player && val < s2->getStackCount(p2)))
  1906. {
  1907. complain("Can't move troops of another player!");
  1908. return false;
  1909. }
  1910. //general conditions checking
  1911. if ((!vstd::contains(S1.stacks,p1) && complain(complainNoCreatures))
  1912. || (val<1 && complain(complainNoCreatures)) )
  1913. {
  1914. return false;
  1915. }
  1916. if (vstd::contains(S2.stacks,p2)) //dest. slot not free - it must be "rebalancing"...
  1917. {
  1918. int total = s1->getStackCount(p1) + s2->getStackCount(p2);
  1919. if ((total < val && complain("Cannot split that stack, not enough creatures!"))
  1920. || (s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot rebalance different creatures stacks!"))
  1921. )
  1922. {
  1923. return false;
  1924. }
  1925. if (notRemovable(sl1.army))
  1926. {
  1927. if (s1->getStackCount(p1) > countLeftOnSrc)
  1928. return false;
  1929. }
  1930. else if (notRemovable(sl2.army))
  1931. {
  1932. if (s2->getStackCount(p1) < countLeftOnSrc)
  1933. return false;
  1934. }
  1935. moveStack(sl1, sl2, countToMove);
  1936. //S2.slots[p2]->count = val;
  1937. //S1.slots[p1]->count = total - val;
  1938. }
  1939. else //split one stack to the two
  1940. {
  1941. if (s1->getStackCount(p1) < val)//not enough creatures
  1942. {
  1943. complain(complainNotEnoughCreatures);
  1944. return false;
  1945. }
  1946. if (notRemovable(sl1.army))
  1947. return false;
  1948. moveStack(sl1, sl2, val);
  1949. }
  1950. }
  1951. return true;
  1952. }
  1953. bool CGameHandler::hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const
  1954. {
  1955. return connections.at(player).count(c);
  1956. }
  1957. PlayerColor CGameHandler::getPlayerAt(std::shared_ptr<CConnection> c) const
  1958. {
  1959. std::set<PlayerColor> all;
  1960. for (auto i=connections.cbegin(); i!=connections.cend(); i++)
  1961. if(vstd::contains(i->second, c))
  1962. all.insert(i->first);
  1963. switch(all.size())
  1964. {
  1965. case 0:
  1966. return PlayerColor::NEUTRAL;
  1967. case 1:
  1968. return *all.begin();
  1969. default:
  1970. {
  1971. //if we have more than one player at this connection, try to pick active one
  1972. if (vstd::contains(all, gs->currentPlayer))
  1973. return gs->currentPlayer;
  1974. else
  1975. return PlayerColor::CANNOT_DETERMINE; //cannot say which player is it
  1976. }
  1977. }
  1978. }
  1979. bool CGameHandler::disbandCreature(ObjectInstanceID id, SlotID pos)
  1980. {
  1981. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id));
  1982. if (!vstd::contains(s1->stacks,pos))
  1983. {
  1984. complain("Illegal call to disbandCreature - no such stack in army!");
  1985. return false;
  1986. }
  1987. eraseStack(StackLocation(s1, pos));
  1988. return true;
  1989. }
  1990. bool CGameHandler::buildStructure(ObjectInstanceID tid, BuildingID requestedID, bool force)
  1991. {
  1992. const CGTownInstance * t = getTown(tid);
  1993. if(!t)
  1994. COMPLAIN_RETF("No such town (ID=%s)!", tid);
  1995. if(!t->town->buildings.count(requestedID))
  1996. COMPLAIN_RETF("Town of faction %s does not have info about building ID=%s!", t->town->faction->getNameTranslated() % requestedID);
  1997. if(t->hasBuilt(requestedID))
  1998. COMPLAIN_RETF("Building %s is already built in %s", t->town->buildings.at(requestedID)->getNameTranslated() % t->getNameTranslated());
  1999. const CBuilding * requestedBuilding = t->town->buildings.at(requestedID);
  2000. //Vector with future list of built building and buildings in auto-mode that are not yet built.
  2001. std::vector<const CBuilding*> remainingAutoBuildings;
  2002. std::set<BuildingID> buildingsThatWillBe;
  2003. //Check validity of request
  2004. if(!force)
  2005. {
  2006. switch(requestedBuilding->mode)
  2007. {
  2008. case CBuilding::BUILD_NORMAL :
  2009. if (canBuildStructure(t, requestedID) != EBuildingState::ALLOWED)
  2010. COMPLAIN_RET("Cannot build that building!");
  2011. break;
  2012. case CBuilding::BUILD_AUTO :
  2013. case CBuilding::BUILD_SPECIAL:
  2014. COMPLAIN_RET("This building can not be constructed normally!");
  2015. case CBuilding::BUILD_GRAIL :
  2016. if(requestedBuilding->mode == CBuilding::BUILD_GRAIL) //needs grail
  2017. {
  2018. if(!t->visitingHero || !t->visitingHero->hasArt(ArtifactID::GRAIL))
  2019. COMPLAIN_RET("Cannot build this without grail!")
  2020. else
  2021. removeArtifact(ArtifactLocation(t->visitingHero, t->visitingHero->getArtPos(ArtifactID::GRAIL, false)));
  2022. }
  2023. break;
  2024. }
  2025. }
  2026. //Performs stuff that has to be done before new building is built
  2027. auto processBeforeBuiltStructure = [t, this](const BuildingID buildingID)
  2028. {
  2029. if(buildingID >= BuildingID::DWELL_FIRST) //dwelling
  2030. {
  2031. int level = (buildingID - BuildingID::DWELL_FIRST) % GameConstants::CREATURES_PER_TOWN;
  2032. int upgradeNumber = (buildingID - BuildingID::DWELL_FIRST) / GameConstants::CREATURES_PER_TOWN;
  2033. if(upgradeNumber >= t->town->creatures.at(level).size())
  2034. {
  2035. complain(boost::str(boost::format("Error ecountered when building dwelling (bid=%s):"
  2036. "no creature found (upgrade number %d, level %d!")
  2037. % buildingID % upgradeNumber % level));
  2038. return;
  2039. }
  2040. CCreature * crea = VLC->creh->objects.at(t->town->creatures.at(level).at(upgradeNumber));
  2041. SetAvailableCreatures ssi;
  2042. ssi.tid = t->id;
  2043. ssi.creatures = t->creatures;
  2044. if (ssi.creatures[level].second.empty()) // first creature in a dwelling
  2045. ssi.creatures[level].first = crea->getGrowth();
  2046. ssi.creatures[level].second.push_back(crea->getId());
  2047. sendAndApply(&ssi);
  2048. }
  2049. if(t->town->buildings.at(buildingID)->subId == BuildingSubID::PORTAL_OF_SUMMONING)
  2050. {
  2051. setPortalDwelling(t);
  2052. }
  2053. };
  2054. //Performs stuff that has to be done after new building is built
  2055. auto processAfterBuiltStructure = [t, this](const BuildingID buildingID)
  2056. {
  2057. auto isMageGuild = (buildingID <= BuildingID::MAGES_GUILD_5 && buildingID >= BuildingID::MAGES_GUILD_1);
  2058. auto isLibrary = isMageGuild ? false
  2059. : t->town->buildings.at(buildingID)->subId == BuildingSubID::EBuildingSubID::LIBRARY;
  2060. if(isMageGuild || isLibrary || (t->subID == ETownType::CONFLUX && buildingID == BuildingID::GRAIL))
  2061. {
  2062. if(t->visitingHero)
  2063. giveSpells(t,t->visitingHero);
  2064. if(t->garrisonHero)
  2065. giveSpells(t,t->garrisonHero);
  2066. }
  2067. };
  2068. //Checks if all requirements will be met with expected building list "buildingsThatWillBe"
  2069. auto areRequirementsFullfilled = [&](const BuildingID & buildID)
  2070. {
  2071. return buildingsThatWillBe.count(buildID);
  2072. };
  2073. //Init the vectors
  2074. for(auto & build : t->town->buildings)
  2075. {
  2076. if(t->hasBuilt(build.first))
  2077. {
  2078. buildingsThatWillBe.insert(build.first);
  2079. }
  2080. else
  2081. {
  2082. if(build.second->mode == CBuilding::BUILD_AUTO) //not built auto building
  2083. remainingAutoBuildings.push_back(build.second);
  2084. }
  2085. }
  2086. //Prepare structure (list of building ids will be filled later)
  2087. NewStructures ns;
  2088. ns.tid = tid;
  2089. ns.builded = force ? t->builded : (t->builded+1);
  2090. std::queue<const CBuilding*> buildingsToAdd;
  2091. buildingsToAdd.push(requestedBuilding);
  2092. while(!buildingsToAdd.empty())
  2093. {
  2094. auto b = buildingsToAdd.front();
  2095. buildingsToAdd.pop();
  2096. ns.bid.insert(b->bid);
  2097. buildingsThatWillBe.insert(b->bid);
  2098. remainingAutoBuildings -= b;
  2099. for(auto autoBuilding : remainingAutoBuildings)
  2100. {
  2101. auto actualRequirements = t->genBuildingRequirements(autoBuilding->bid);
  2102. if(actualRequirements.test(areRequirementsFullfilled))
  2103. buildingsToAdd.push(autoBuilding);
  2104. }
  2105. }
  2106. // FIXME: it's done before NewStructures applied because otherwise town window wont be properly updated on client. That should be actually fixed on client and not on server.
  2107. for(auto builtID : ns.bid)
  2108. processBeforeBuiltStructure(builtID);
  2109. //Take cost
  2110. if(!force)
  2111. giveResources(t->tempOwner, -requestedBuilding->resources);
  2112. //We know what has been built, apply changes. Do this as final step to properly update town window
  2113. sendAndApply(&ns);
  2114. //Other post-built events. To some logic like giving spells to work gamestate changes for new building must be already in place!
  2115. for(auto builtID : ns.bid)
  2116. processAfterBuiltStructure(builtID);
  2117. // now when everything is built - reveal tiles for lookout tower
  2118. FoWChange fw;
  2119. fw.player = t->tempOwner;
  2120. fw.mode = 1;
  2121. getTilesInRange(fw.tiles, t->getSightCenter(), t->getSightRadius(), t->tempOwner, 1);
  2122. sendAndApply(&fw);
  2123. if(t->visitingHero)
  2124. visitCastleObjects(t, t->visitingHero);
  2125. if(t->garrisonHero)
  2126. visitCastleObjects(t, t->garrisonHero);
  2127. checkVictoryLossConditionsForPlayer(t->tempOwner);
  2128. return true;
  2129. }
  2130. bool CGameHandler::razeStructure (ObjectInstanceID tid, BuildingID bid)
  2131. {
  2132. ///incomplete, simply erases target building
  2133. const CGTownInstance * t = getTown(tid);
  2134. if (!vstd::contains(t->builtBuildings, bid))
  2135. return false;
  2136. RazeStructures rs;
  2137. rs.tid = tid;
  2138. rs.bid.insert(bid);
  2139. rs.destroyed = t->destroyed + 1;
  2140. sendAndApply(&rs);
  2141. //TODO: Remove dwellers
  2142. // if (t->subID == 4 && bid == 17) //Veil of Darkness
  2143. // {
  2144. // RemoveBonus rb(RemoveBonus::TOWN);
  2145. // rb.whoID = t->id;
  2146. // rb.source = BonusSource::TOWN_STRUCTURE;
  2147. // rb.id = 17;
  2148. // sendAndApply(&rb);
  2149. // }
  2150. return true;
  2151. }
  2152. bool CGameHandler::recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dstid, CreatureID crid, ui32 cram, si32 fromLvl)
  2153. {
  2154. const CGDwelling * dw = static_cast<const CGDwelling *>(getObj(objid));
  2155. const CArmedInstance *dst = nullptr;
  2156. const CCreature *c = VLC->creh->objects.at(crid);
  2157. const bool warMachine = c->warMachine != ArtifactID::NONE;
  2158. //TODO: test for owning
  2159. //TODO: check if dst can recruit objects (e.g. hero is actually visiting object, town and source are same, etc)
  2160. dst = dynamic_cast<const CArmedInstance*>(getObj(dstid));
  2161. assert(dw && dst);
  2162. //verify
  2163. bool found = false;
  2164. int level = 0;
  2165. for (; level < dw->creatures.size(); level++) //iterate through all levels
  2166. {
  2167. if ((fromLvl != -1) && (level !=fromLvl))
  2168. continue;
  2169. const auto &cur = dw->creatures.at(level); //current level info <amount, list of cr. ids>
  2170. int i = 0;
  2171. for (; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  2172. if (cur.second.at(i) == crid)
  2173. break;
  2174. if (i < cur.second.size())
  2175. {
  2176. found = true;
  2177. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  2178. break;
  2179. }
  2180. }
  2181. SlotID slot = dst->getSlotFor(crid);
  2182. if ((!found && complain("Cannot recruit: no such creatures!"))
  2183. || ((si32)cram > VLC->creh->objects.at(crid)->maxAmount(getPlayerState(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!"))
  2184. || (cram<=0 && complain("Cannot recruit: cram <= 0!"))
  2185. || (!slot.validSlot() && !warMachine && complain("Cannot recruit: no available slot!")))
  2186. {
  2187. return false;
  2188. }
  2189. //recruit
  2190. giveResources(dst->tempOwner, -(c->getFullRecruitCost() * cram));
  2191. SetAvailableCreatures sac;
  2192. sac.tid = objid;
  2193. sac.creatures = dw->creatures;
  2194. sac.creatures[level].first -= cram;
  2195. sendAndApply(&sac);
  2196. if (warMachine)
  2197. {
  2198. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(dst);
  2199. COMPLAIN_RET_FALSE_IF(!h, "Only hero can buy war machines");
  2200. ArtifactID artId = c->warMachine;
  2201. COMPLAIN_RET_FALSE_IF(artId == ArtifactID::CATAPULT, "Catapult cannot be recruited!");
  2202. const CArtifact * art = artId.toArtifact();
  2203. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid war machine artifact");
  2204. return giveHeroNewArtifact(h, art);
  2205. }
  2206. else
  2207. {
  2208. addToSlot(StackLocation(dst, slot), c, cram);
  2209. }
  2210. return true;
  2211. }
  2212. bool CGameHandler::upgradeCreature(ObjectInstanceID objid, SlotID pos, CreatureID upgID)
  2213. {
  2214. const CArmedInstance * obj = static_cast<const CArmedInstance *>(getObjInstance(objid));
  2215. if (!obj->hasStackAtSlot(pos))
  2216. {
  2217. COMPLAIN_RET("Cannot upgrade, no stack at slot " + boost::to_string(pos));
  2218. }
  2219. UpgradeInfo ui;
  2220. fillUpgradeInfo(obj, pos, ui);
  2221. PlayerColor player = obj->tempOwner;
  2222. const PlayerState *p = getPlayerState(player);
  2223. int crQuantity = obj->stacks.at(pos)->count;
  2224. int newIDpos= vstd::find_pos(ui.newID, upgID);//get position of new id in UpgradeInfo
  2225. //check if upgrade is possible
  2226. if ((ui.oldID<0 || newIDpos == -1) && complain("That upgrade is not possible!"))
  2227. {
  2228. return false;
  2229. }
  2230. TResources totalCost = ui.cost.at(newIDpos) * crQuantity;
  2231. //check if player has enough resources
  2232. if (!p->resources.canAfford(totalCost))
  2233. COMPLAIN_RET("Cannot upgrade, not enough resources!");
  2234. //take resources
  2235. giveResources(player, -totalCost);
  2236. //upgrade creature
  2237. changeStackType(StackLocation(obj, pos), VLC->creh->objects.at(upgID));
  2238. return true;
  2239. }
  2240. bool CGameHandler::changeStackType(const StackLocation &sl, const CCreature *c)
  2241. {
  2242. if (!sl.army->hasStackAtSlot(sl.slot))
  2243. COMPLAIN_RET("Cannot find a stack to change type");
  2244. SetStackType sst;
  2245. sst.army = sl.army->id;
  2246. sst.slot = sl.slot;
  2247. sst.type = c->getId();
  2248. sendAndApply(&sst);
  2249. return true;
  2250. }
  2251. void CGameHandler::moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging)
  2252. {
  2253. assert(src->canBeMergedWith(*dst, allowMerging));
  2254. while(src->stacksCount())//while there are unmoved creatures
  2255. {
  2256. auto i = src->Slots().begin(); //iterator to stack to move
  2257. StackLocation sl(src, i->first); //location of stack to move
  2258. SlotID pos = dst->getSlotFor(i->second->type);
  2259. if (!pos.validSlot())
  2260. {
  2261. //try to merge two other stacks to make place
  2262. std::pair<SlotID, SlotID> toMerge;
  2263. if (dst->mergableStacks(toMerge, i->first) && allowMerging)
  2264. {
  2265. moveStack(StackLocation(dst, toMerge.first), StackLocation(dst, toMerge.second)); //merge toMerge.first into toMerge.second
  2266. assert(!dst->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  2267. moveStack(sl, StackLocation(dst, toMerge.first)); //move stack to freed slot
  2268. }
  2269. else
  2270. {
  2271. complain("Unexpected failure during an attempt to move army from " + src->nodeName() + " to " + dst->nodeName() + "!");
  2272. return;
  2273. }
  2274. }
  2275. else
  2276. {
  2277. moveStack(sl, StackLocation(dst, pos));
  2278. }
  2279. }
  2280. }
  2281. bool CGameHandler::swapGarrisonOnSiege(ObjectInstanceID tid)
  2282. {
  2283. const CGTownInstance * town = getTown(tid);
  2284. if(!town->garrisonHero == !town->visitingHero)
  2285. return false;
  2286. SetHeroesInTown intown;
  2287. intown.tid = tid;
  2288. if(town->garrisonHero) //garrison -> vising
  2289. {
  2290. intown.garrison = ObjectInstanceID();
  2291. intown.visiting = town->garrisonHero->id;
  2292. }
  2293. else //visiting -> garrison
  2294. {
  2295. if(town->armedGarrison())
  2296. town->mergeGarrisonOnSiege();
  2297. intown.visiting = ObjectInstanceID();
  2298. intown.garrison = town->visitingHero->id;
  2299. }
  2300. sendAndApply(&intown);
  2301. return true;
  2302. }
  2303. bool CGameHandler::garrisonSwap(ObjectInstanceID tid)
  2304. {
  2305. const CGTownInstance * town = getTown(tid);
  2306. if (!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2307. {
  2308. if (!town->visitingHero->canBeMergedWith(*town))
  2309. {
  2310. complain("Cannot make garrison swap, not enough free slots!");
  2311. return false;
  2312. }
  2313. moveArmy(town, town->visitingHero, true);
  2314. SetHeroesInTown intown;
  2315. intown.tid = tid;
  2316. intown.visiting = ObjectInstanceID();
  2317. intown.garrison = town->visitingHero->id;
  2318. sendAndApply(&intown);
  2319. return true;
  2320. }
  2321. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2322. {
  2323. //check if moving hero out of town will break 8 wandering heroes limit
  2324. if (getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2325. {
  2326. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2327. return false;
  2328. }
  2329. SetHeroesInTown intown;
  2330. intown.tid = tid;
  2331. intown.garrison = ObjectInstanceID();
  2332. intown.visiting = town->garrisonHero->id;
  2333. sendAndApply(&intown);
  2334. return true;
  2335. }
  2336. else if (!!town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2337. {
  2338. SetHeroesInTown intown;
  2339. intown.tid = tid;
  2340. intown.garrison = town->visitingHero->id;
  2341. intown.visiting = town->garrisonHero->id;
  2342. sendAndApply(&intown);
  2343. return true;
  2344. }
  2345. else
  2346. {
  2347. complain("Cannot swap garrison hero!");
  2348. return false;
  2349. }
  2350. }
  2351. // With the amount of changes done to the function, it's more like transferArtifacts.
  2352. // Function moves artifact from src to dst. If dst is not a backpack and is already occupied, old dst art goes to backpack and is replaced.
  2353. bool CGameHandler::moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2)
  2354. {
  2355. ArtifactLocation src = al1, dst = al2;
  2356. const PlayerColor srcPlayer = src.owningPlayer(), dstPlayer = dst.owningPlayer();
  2357. const CArmedInstance *srcObj = src.relatedObj(), *dstObj = dst.relatedObj();
  2358. // Make sure exchange is even possible between the two heroes.
  2359. if(!isAllowedExchange(srcObj->id, dstObj->id))
  2360. COMPLAIN_RET("That heroes cannot make any exchange!");
  2361. const CArtifactInstance *srcArtifact = src.getArt();
  2362. const CArtifactInstance *destArtifact = dst.getArt();
  2363. const bool isDstSlotBackpack = ArtifactUtils::isSlotBackpack(dst.slot);
  2364. if(srcArtifact == nullptr)
  2365. COMPLAIN_RET("No artifact to move!");
  2366. if(destArtifact && srcPlayer != dstPlayer && !isDstSlotBackpack)
  2367. COMPLAIN_RET("Can't touch artifact on hero of another player!");
  2368. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2369. // Moving to the backpack is always allowed.
  2370. if((!srcArtifact || !isDstSlotBackpack)
  2371. && srcArtifact && !srcArtifact->canBePutAt(dst, true))
  2372. COMPLAIN_RET("Cannot move artifact!");
  2373. auto srcSlot = src.getSlot();
  2374. auto dstSlot = dst.getSlot();
  2375. if((srcSlot && srcSlot->locked) || (dstSlot && dstSlot->locked))
  2376. COMPLAIN_RET("Cannot move artifact locks.");
  2377. if(isDstSlotBackpack && srcArtifact->artType->isBig())
  2378. COMPLAIN_RET("Cannot put big artifacts in backpack!");
  2379. if(src.slot == ArtifactPosition::MACH4 || dst.slot == ArtifactPosition::MACH4)
  2380. COMPLAIN_RET("Cannot move catapult!");
  2381. if(isDstSlotBackpack)
  2382. {
  2383. if(!ArtifactUtils::isBackpackFreeSlots(dst.getHolderArtSet()))
  2384. COMPLAIN_RET("Backpack is full!");
  2385. vstd::amin(dst.slot, GameConstants::BACKPACK_START + dst.getHolderArtSet()->artifactsInBackpack.size());
  2386. }
  2387. if(!(src.slot == ArtifactPosition::TRANSITION_POS && dst.slot == ArtifactPosition::TRANSITION_POS))
  2388. {
  2389. if(src.slot == dst.slot && src.artHolder == dst.artHolder)
  2390. COMPLAIN_RET("Won't move artifact: Dest same as source!");
  2391. // Check if dst slot is occupied
  2392. if(!isDstSlotBackpack && destArtifact)
  2393. {
  2394. // Previous artifact must be removed first
  2395. moveArtifact(dst, ArtifactLocation(dst.artHolder, ArtifactPosition::TRANSITION_POS));
  2396. }
  2397. try
  2398. {
  2399. auto hero = std::get<ConstTransitivePtr<CGHeroInstance>>(dst.artHolder);
  2400. if(ArtifactUtils::checkSpellbookIsNeeded(hero, srcArtifact->artType->getId(), dst.slot))
  2401. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  2402. }
  2403. catch(const std::bad_variant_access &)
  2404. {
  2405. // object other than hero received an art - ignore
  2406. }
  2407. MoveArtifact ma(&src, &dst);
  2408. if(dst.slot == ArtifactPosition::TRANSITION_POS)
  2409. ma.askAssemble = false;
  2410. sendAndApply(&ma);
  2411. }
  2412. return true;
  2413. }
  2414. bool CGameHandler::bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap)
  2415. {
  2416. // Make sure exchange is even possible between the two heroes.
  2417. if(!isAllowedExchange(srcHero, dstHero))
  2418. COMPLAIN_RET("That heroes cannot make any exchange!");
  2419. auto psrcHero = getHero(srcHero);
  2420. auto pdstHero = getHero(dstHero);
  2421. if((!psrcHero) || (!pdstHero))
  2422. COMPLAIN_RET("bulkMoveArtifacts: wrong hero's ID");
  2423. BulkMoveArtifacts ma(static_cast<ConstTransitivePtr<CGHeroInstance>>(psrcHero),
  2424. static_cast<ConstTransitivePtr<CGHeroInstance>>(pdstHero), swap);
  2425. auto & slotsSrcDst = ma.artsPack0;
  2426. auto & slotsDstSrc = ma.artsPack1;
  2427. // Temporary fitting set for artifacts. Used to select available slots before sending data.
  2428. CArtifactFittingSet artFittingSet(pdstHero->bearerType());
  2429. auto moveArtifact = [this, &artFittingSet](const CArtifactInstance * artifact,
  2430. ArtifactPosition srcSlot, const CGHeroInstance * dstHero,
  2431. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  2432. {
  2433. assert(artifact);
  2434. auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, artifact->getTypeId());
  2435. if(dstSlot != ArtifactPosition::PRE_FIRST)
  2436. {
  2437. artFittingSet.putArtifact(dstSlot, static_cast<ConstTransitivePtr<CArtifactInstance>>(artifact));
  2438. slots.push_back(BulkMoveArtifacts::LinkedSlots(srcSlot, dstSlot));
  2439. if(ArtifactUtils::checkSpellbookIsNeeded(dstHero, artifact->getTypeId(), dstSlot))
  2440. giveHeroNewArtifact(dstHero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  2441. }
  2442. };
  2443. if(swap)
  2444. {
  2445. auto moveArtsWorn = [moveArtifact](const CGHeroInstance * srcHero, const CGHeroInstance * dstHero,
  2446. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  2447. {
  2448. for(auto & artifact : srcHero->artifactsWorn)
  2449. {
  2450. if(ArtifactUtils::isArtRemovable(artifact))
  2451. moveArtifact(artifact.second.getArt(), artifact.first, dstHero, slots);
  2452. }
  2453. };
  2454. auto moveArtsInBackpack = [](const CArtifactSet * artSet,
  2455. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  2456. {
  2457. for(auto & slotInfo : artSet->artifactsInBackpack)
  2458. {
  2459. auto slot = artSet->getArtPos(slotInfo.artifact);
  2460. slots.push_back(BulkMoveArtifacts::LinkedSlots(slot, slot));
  2461. }
  2462. };
  2463. // Move over artifacts that are worn srcHero -> dstHero
  2464. moveArtsWorn(psrcHero, pdstHero, slotsSrcDst);
  2465. artFittingSet.artifactsWorn.clear();
  2466. // Move over artifacts that are worn dstHero -> srcHero
  2467. moveArtsWorn(pdstHero, psrcHero, slotsDstSrc);
  2468. // Move over artifacts that are in backpack srcHero -> dstHero
  2469. moveArtsInBackpack(psrcHero, slotsSrcDst);
  2470. // Move over artifacts that are in backpack dstHero -> srcHero
  2471. moveArtsInBackpack(pdstHero, slotsDstSrc);
  2472. }
  2473. else
  2474. {
  2475. artFittingSet.artifactsInBackpack = pdstHero->artifactsInBackpack;
  2476. artFittingSet.artifactsWorn = pdstHero->artifactsWorn;
  2477. // Move over artifacts that are worn
  2478. for(auto & artInfo : psrcHero->artifactsWorn)
  2479. {
  2480. if(ArtifactUtils::isArtRemovable(artInfo))
  2481. {
  2482. moveArtifact(psrcHero->getArt(artInfo.first), artInfo.first, pdstHero, slotsSrcDst);
  2483. }
  2484. }
  2485. // Move over artifacts that are in backpack
  2486. for(auto & slotInfo : psrcHero->artifactsInBackpack)
  2487. {
  2488. moveArtifact(psrcHero->getArt(psrcHero->getArtPos(slotInfo.artifact)),
  2489. psrcHero->getArtPos(slotInfo.artifact), pdstHero, slotsSrcDst);
  2490. }
  2491. }
  2492. sendAndApply(&ma);
  2493. return true;
  2494. }
  2495. /**
  2496. * Assembles or disassembles a combination artifact.
  2497. * @param heroID ID of hero holding the artifact(s).
  2498. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  2499. * @param assemble True for assembly operation, false for disassembly.
  2500. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  2501. * artifact to assemble to. Otherwise it's not used.
  2502. */
  2503. bool CGameHandler::assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  2504. {
  2505. const CGHeroInstance * hero = getHero(heroID);
  2506. const CArtifactInstance * destArtifact = hero->getArt(artifactSlot);
  2507. if(!destArtifact)
  2508. COMPLAIN_RET("assembleArtifacts: there is no such artifact instance!");
  2509. if(assemble)
  2510. {
  2511. CArtifact * combinedArt = VLC->arth->objects[assembleTo];
  2512. if(!combinedArt->isCombined())
  2513. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to assemble is not a combined artifacts!");
  2514. if (!vstd::contains(ArtifactUtils::assemblyPossibilities(hero, destArtifact->getTypeId(),
  2515. ArtifactUtils::isSlotEquipment(artifactSlot)), combinedArt))
  2516. {
  2517. COMPLAIN_RET("assembleArtifacts: It's impossible to assemble requested artifact!");
  2518. }
  2519. if(ArtifactUtils::checkSpellbookIsNeeded(hero, assembleTo, artifactSlot))
  2520. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  2521. AssembledArtifact aa;
  2522. aa.al = ArtifactLocation(hero, artifactSlot);
  2523. aa.builtArt = combinedArt;
  2524. sendAndApply(&aa);
  2525. }
  2526. else
  2527. {
  2528. if(!destArtifact->isCombined())
  2529. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble is not a combined artifact!");
  2530. if(ArtifactUtils::isSlotBackpack(artifactSlot)
  2531. && !ArtifactUtils::isBackpackFreeSlots(hero, destArtifact->artType->getConstituents().size() - 1))
  2532. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble but backpack is full!");
  2533. DisassembledArtifact da;
  2534. da.al = ArtifactLocation(hero, artifactSlot);
  2535. sendAndApply(&da);
  2536. }
  2537. return true;
  2538. }
  2539. bool CGameHandler::eraseArtifactByClient(const ArtifactLocation & al)
  2540. {
  2541. const auto * hero = getHero(al.relatedObj()->id);
  2542. if(hero == nullptr)
  2543. COMPLAIN_RET("eraseArtifactByClient: wrong hero's ID");
  2544. const auto * art = al.getArt();
  2545. if(art == nullptr)
  2546. COMPLAIN_RET("Cannot remove artifact!");
  2547. if(al.getArt()->artType->canBePutAt(hero) || al.slot != ArtifactPosition::TRANSITION_POS)
  2548. COMPLAIN_RET("Illegal artifact removal request");
  2549. removeArtifact(al);
  2550. return true;
  2551. }
  2552. bool CGameHandler::buyArtifact(ObjectInstanceID hid, ArtifactID aid)
  2553. {
  2554. const CGHeroInstance * hero = getHero(hid);
  2555. COMPLAIN_RET_FALSE_IF(nullptr == hero, "Invalid hero index");
  2556. const CGTownInstance * town = hero->visitedTown;
  2557. COMPLAIN_RET_FALSE_IF(nullptr == town, "Hero not in town");
  2558. if (aid==ArtifactID::SPELLBOOK)
  2559. {
  2560. if ((!town->hasBuilt(BuildingID::MAGES_GUILD_1) && complain("Cannot buy a spellbook, no mage guild in the town!"))
  2561. || (getResource(hero->getOwner(), EGameResID::GOLD) < GameConstants::SPELLBOOK_GOLD_COST && complain("Cannot buy a spellbook, not enough gold!"))
  2562. || (hero->getArt(ArtifactPosition::SPELLBOOK) && complain("Cannot buy a spellbook, hero already has a one!"))
  2563. )
  2564. return false;
  2565. giveResource(hero->getOwner(),EGameResID::GOLD,-GameConstants::SPELLBOOK_GOLD_COST);
  2566. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  2567. assert(hero->getArt(ArtifactPosition::SPELLBOOK));
  2568. giveSpells(town,hero);
  2569. return true;
  2570. }
  2571. else
  2572. {
  2573. const CArtifact * art = aid.toArtifact();
  2574. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid artifact index to buy");
  2575. COMPLAIN_RET_FALSE_IF(art->getWarMachine() == CreatureID::NONE, "War machine artifact required");
  2576. COMPLAIN_RET_FALSE_IF(hero->hasArt(aid),"Hero already has this machine!");
  2577. const int price = art->getPrice();
  2578. COMPLAIN_RET_FALSE_IF(getPlayerState(hero->getOwner())->resources[EGameResID::GOLD] < price, "Not enough gold!");
  2579. if ((town->hasBuilt(BuildingID::BLACKSMITH) && town->town->warMachine == aid)
  2580. || (town->hasBuilt(BuildingSubID::BALLISTA_YARD) && aid == ArtifactID::BALLISTA))
  2581. {
  2582. giveResource(hero->getOwner(),EGameResID::GOLD,-price);
  2583. return giveHeroNewArtifact(hero, art);
  2584. }
  2585. else
  2586. COMPLAIN_RET("This machine is unavailable here!");
  2587. }
  2588. }
  2589. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, GameResID rid, ArtifactID aid)
  2590. {
  2591. if(!h)
  2592. COMPLAIN_RET("Only hero can buy artifacts!");
  2593. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_ARTIFACT), aid))
  2594. COMPLAIN_RET("That artifact is unavailable!");
  2595. int b1, b2;
  2596. m->getOffer(rid, aid, b1, b2, EMarketMode::RESOURCE_ARTIFACT);
  2597. if (getResource(h->tempOwner, rid) < b1)
  2598. COMPLAIN_RET("You can't afford to buy this artifact!");
  2599. giveResource(h->tempOwner, rid, -b1);
  2600. SetAvailableArtifacts saa;
  2601. if(dynamic_cast<const CGTownInstance *>(m))
  2602. {
  2603. saa.id = -1;
  2604. saa.arts = CGTownInstance::merchantArtifacts;
  2605. }
  2606. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m)) //black market
  2607. {
  2608. saa.id = bm->id.getNum();
  2609. saa.arts = bm->artifacts;
  2610. }
  2611. else
  2612. COMPLAIN_RET("Wrong marktet...");
  2613. bool found = false;
  2614. for (const CArtifact *&art : saa.arts)
  2615. {
  2616. if (art && art->getId() == aid)
  2617. {
  2618. art = nullptr;
  2619. found = true;
  2620. break;
  2621. }
  2622. }
  2623. if (!found)
  2624. COMPLAIN_RET("Cannot find selected artifact on the list");
  2625. sendAndApply(&saa);
  2626. giveHeroNewArtifact(h, VLC->arth->objects[aid], ArtifactPosition::FIRST_AVAILABLE);
  2627. return true;
  2628. }
  2629. bool CGameHandler::sellArtifact(const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid)
  2630. {
  2631. COMPLAIN_RET_FALSE_IF((!h), "Only hero can sell artifacts!");
  2632. const CArtifactInstance *art = h->getArtByInstanceId(aid);
  2633. COMPLAIN_RET_FALSE_IF((!art), "There is no artifact to sell!");
  2634. COMPLAIN_RET_FALSE_IF((!art->artType->isTradable()), "Cannot sell a war machine or spellbook!");
  2635. int resVal = 0, dump = 1;
  2636. m->getOffer(art->artType->getId(), rid, dump, resVal, EMarketMode::ARTIFACT_RESOURCE);
  2637. removeArtifact(ArtifactLocation(h, h->getArtPos(art)));
  2638. giveResource(h->tempOwner, rid, resVal);
  2639. return true;
  2640. }
  2641. bool CGameHandler::buySecSkill(const IMarket *m, const CGHeroInstance *h, SecondarySkill skill)
  2642. {
  2643. if (!h)
  2644. COMPLAIN_RET("You need hero to buy a skill!");
  2645. if (h->getSecSkillLevel(SecondarySkill(skill)))
  2646. COMPLAIN_RET("Hero already know this skill");
  2647. if (!h->canLearnSkill())
  2648. COMPLAIN_RET("Hero can't learn any more skills");
  2649. if (!h->canLearnSkill(skill))
  2650. COMPLAIN_RET("The hero can't learn this skill!");
  2651. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_SKILL), skill))
  2652. COMPLAIN_RET("That skill is unavailable!");
  2653. if (getResource(h->tempOwner, EGameResID::GOLD) < GameConstants::SKILL_GOLD_COST)//TODO: remove hardcoded resource\summ?
  2654. COMPLAIN_RET("You can't afford to buy this skill");
  2655. giveResource(h->tempOwner, EGameResID::GOLD, -GameConstants::SKILL_GOLD_COST);
  2656. changeSecSkill(h, skill, 1, true);
  2657. return true;
  2658. }
  2659. bool CGameHandler::tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2)
  2660. {
  2661. TResourceCap r1 = getPlayerState(player)->resources[id1];
  2662. vstd::amin(val, r1); //can't trade more resources than have
  2663. int b1, b2; //base quantities for trade
  2664. market->getOffer(id1, id2, b1, b2, EMarketMode::RESOURCE_RESOURCE);
  2665. int units = val / b1; //how many base quantities we trade
  2666. if (val%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2667. {
  2668. COMPLAIN_RET("Invalid deal, not all offered units of resource were used.");
  2669. }
  2670. giveResource(player, GameResID(id1), - b1 * units);
  2671. giveResource(player, GameResID(id2), b2 * units);
  2672. return true;
  2673. }
  2674. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID)
  2675. {
  2676. if(!hero)
  2677. COMPLAIN_RET("Only hero can sell creatures!");
  2678. if (!vstd::contains(hero->Slots(), slot))
  2679. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  2680. const CStackInstance &s = hero->getStack(slot);
  2681. if (s.count < (TQuantity)count //can't sell more creatures than have
  2682. || (hero->stacksCount() == 1 && hero->needsLastStack() && s.count == count)) //can't sell last stack
  2683. {
  2684. COMPLAIN_RET("Not enough creatures in army!");
  2685. }
  2686. int b1, b2; //base quantities for trade
  2687. market->getOffer(s.type->getId(), resourceID, b1, b2, EMarketMode::CREATURE_RESOURCE);
  2688. int units = count / b1; //how many base quantities we trade
  2689. if (count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2690. {
  2691. //TODO: complain?
  2692. assert(0);
  2693. }
  2694. changeStackCount(StackLocation(hero, slot), -(TQuantity)count);
  2695. giveResource(hero->tempOwner, resourceID, b2 * units);
  2696. return true;
  2697. }
  2698. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot)
  2699. {
  2700. const CArmedInstance *army = nullptr;
  2701. if (hero)
  2702. army = hero;
  2703. else
  2704. army = dynamic_cast<const CGTownInstance *>(market);
  2705. if (!army)
  2706. COMPLAIN_RET("Incorrect call to transform in undead!");
  2707. if (!army->hasStackAtSlot(slot))
  2708. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  2709. const CStackInstance &s = army->getStack(slot);
  2710. //resulting creature - bone dragons or skeletons
  2711. CreatureID resCreature = CreatureID::SKELETON;
  2712. if ((s.hasBonusOfType(BonusType::DRAGON_NATURE)
  2713. && !(s.hasBonusOfType(BonusType::UNDEAD)))
  2714. || (s.getCreatureID() == CreatureID::HYDRA)
  2715. || (s.getCreatureID() == CreatureID::CHAOS_HYDRA))
  2716. resCreature = CreatureID::BONE_DRAGON;
  2717. changeStackType(StackLocation(army, slot), resCreature.toCreature());
  2718. return true;
  2719. }
  2720. bool CGameHandler::sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2)
  2721. {
  2722. const PlayerState *p2 = getPlayerState(r2, false);
  2723. if (!p2 || p2->status != EPlayerStatus::INGAME)
  2724. {
  2725. complain("Dest player must be in game!");
  2726. return false;
  2727. }
  2728. TResourceCap curRes1 = getPlayerState(player)->resources[r1];
  2729. vstd::amin(val, curRes1);
  2730. giveResource(player, r1, -(int)val);
  2731. giveResource(r2, r1, val);
  2732. return true;
  2733. }
  2734. bool CGameHandler::setFormation(ObjectInstanceID hid, ui8 formation)
  2735. {
  2736. const CGHeroInstance *h = getHero(hid);
  2737. if (!h)
  2738. {
  2739. logGlobal->error("Hero doesn't exist!");
  2740. return false;
  2741. }
  2742. ChangeFormation cf;
  2743. cf.hid = hid;
  2744. cf.formation = formation;
  2745. sendAndApply(&cf);
  2746. return true;
  2747. }
  2748. bool CGameHandler::queryReply(QueryID qid, const JsonNode & answer, PlayerColor player)
  2749. {
  2750. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2751. logGlobal->trace("Player %s attempts answering query %d with answer:", player, qid);
  2752. logGlobal->trace(answer.toJson());
  2753. auto topQuery = queries->topQuery(player);
  2754. COMPLAIN_RET_FALSE_IF(!topQuery, "This player doesn't have any queries!");
  2755. if(topQuery->queryID != qid)
  2756. {
  2757. auto currentQuery = queries->getQuery(qid);
  2758. if(currentQuery != nullptr && currentQuery->endsByPlayerAnswer())
  2759. currentQuery->setReply(answer);
  2760. COMPLAIN_RET("This player top query has different ID!"); //topQuery->queryID != qid
  2761. }
  2762. COMPLAIN_RET_FALSE_IF(!topQuery->endsByPlayerAnswer(), "This query cannot be ended by player's answer!");
  2763. topQuery->setReply(answer);
  2764. queries->popQuery(topQuery);
  2765. return true;
  2766. }
  2767. void CGameHandler::handleTimeEvents()
  2768. {
  2769. gs->map->events.sort(evntCmp);
  2770. while(gs->map->events.size() && gs->map->events.front().firstOccurence+1 == gs->day)
  2771. {
  2772. CMapEvent ev = gs->map->events.front();
  2773. for (int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
  2774. {
  2775. auto color = PlayerColor(player);
  2776. const PlayerState * pinfo = getPlayerState(color, false); //do not output error if player does not exist
  2777. if (pinfo //player exists
  2778. && (ev.players & 1<<player) //event is enabled to this player
  2779. && ((ev.computerAffected && !pinfo->human)
  2780. || (ev.humanAffected && pinfo->human)
  2781. )
  2782. )
  2783. {
  2784. //give resources
  2785. giveResources(color, ev.resources);
  2786. //prepare dialog
  2787. InfoWindow iw;
  2788. iw.player = color;
  2789. iw.text.appendRawString(ev.message);
  2790. for (int i=0; i<ev.resources.size(); i++)
  2791. {
  2792. if (ev.resources[i]) //if resource is changed, we add it to the dialog
  2793. iw.components.emplace_back(Component::EComponentType::RESOURCE,i,ev.resources[i],0);
  2794. }
  2795. sendAndApply(&iw); //show dialog
  2796. }
  2797. } //PLAYERS LOOP
  2798. if (ev.nextOccurence)
  2799. {
  2800. gs->map->events.pop_front();
  2801. ev.firstOccurence += ev.nextOccurence;
  2802. auto it = gs->map->events.begin();
  2803. while(it != gs->map->events.end() && it->earlierThanOrEqual(ev))
  2804. it++;
  2805. gs->map->events.insert(it, ev);
  2806. }
  2807. else
  2808. {
  2809. gs->map->events.pop_front();
  2810. }
  2811. }
  2812. //TODO send only if changed
  2813. UpdateMapEvents ume;
  2814. ume.events = gs->map->events;
  2815. sendAndApply(&ume);
  2816. }
  2817. void CGameHandler::handleTownEvents(CGTownInstance * town, NewTurn &n)
  2818. {
  2819. town->events.sort(evntCmp);
  2820. while(town->events.size() && town->events.front().firstOccurence == gs->day)
  2821. {
  2822. PlayerColor player = town->tempOwner;
  2823. CCastleEvent ev = town->events.front();
  2824. const PlayerState * pinfo = getPlayerState(player, false);
  2825. if (pinfo //player exists
  2826. && (ev.players & 1<<player.getNum()) //event is enabled to this player
  2827. && ((ev.computerAffected && !pinfo->human)
  2828. || (ev.humanAffected && pinfo->human)))
  2829. {
  2830. // dialog
  2831. InfoWindow iw;
  2832. iw.player = player;
  2833. iw.text.appendRawString(ev.message);
  2834. if (ev.resources.nonZero())
  2835. {
  2836. TResources was = n.res[player];
  2837. n.res[player] += ev.resources;
  2838. n.res[player].amax(0);
  2839. for (int i=0; i<ev.resources.size(); i++)
  2840. if (ev.resources[i] && pinfo->resources[i] != n.res.at(player)[i]) //if resource had changed, we add it to the dialog
  2841. iw.components.emplace_back(Component::EComponentType::RESOURCE,i,n.res.at(player)[i]-was[i],0);
  2842. }
  2843. for (auto & i : ev.buildings)
  2844. {
  2845. if (!town->hasBuilt(i))
  2846. {
  2847. buildStructure(town->id, i, true);
  2848. iw.components.emplace_back(Component::EComponentType::BUILDING, town->subID, i, 0);
  2849. }
  2850. }
  2851. if (!ev.creatures.empty() && !vstd::contains(n.cres, town->id))
  2852. {
  2853. n.cres[town->id].tid = town->id;
  2854. n.cres[town->id].creatures = town->creatures;
  2855. }
  2856. auto & sac = n.cres[town->id];
  2857. for (si32 i=0;i<ev.creatures.size();i++) //creature growths
  2858. {
  2859. if (!town->creatures.at(i).second.empty() && ev.creatures.at(i) > 0)//there is dwelling
  2860. {
  2861. sac.creatures[i].first += ev.creatures.at(i);
  2862. iw.components.emplace_back(Component::EComponentType::CREATURE,
  2863. town->creatures.at(i).second.back(), ev.creatures.at(i), 0);
  2864. }
  2865. }
  2866. sendAndApply(&iw); //show dialog
  2867. }
  2868. if (ev.nextOccurence)
  2869. {
  2870. town->events.pop_front();
  2871. ev.firstOccurence += ev.nextOccurence;
  2872. auto it = town->events.begin();
  2873. while(it != town->events.end() && it->earlierThanOrEqual(ev))
  2874. it++;
  2875. town->events.insert(it, ev);
  2876. }
  2877. else
  2878. {
  2879. town->events.pop_front();
  2880. }
  2881. }
  2882. //TODO send only if changed
  2883. UpdateCastleEvents uce;
  2884. uce.town = town->id;
  2885. uce.events = town->events;
  2886. sendAndApply(&uce);
  2887. }
  2888. bool CGameHandler::complain(const std::string &problem)
  2889. {
  2890. playerMessages->broadcastSystemMessage("Server encountered a problem: " + problem);
  2891. logGlobal->error(problem);
  2892. return true;
  2893. }
  2894. void CGameHandler::showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits)
  2895. {
  2896. //PlayerColor player = getOwner(hid);
  2897. auto upperArmy = dynamic_cast<const CArmedInstance*>(getObj(upobj));
  2898. auto lowerArmy = dynamic_cast<const CArmedInstance*>(getObj(hid));
  2899. assert(lowerArmy);
  2900. assert(upperArmy);
  2901. auto garrisonQuery = std::make_shared<CGarrisonDialogQuery>(this, upperArmy, lowerArmy);
  2902. queries->addQuery(garrisonQuery);
  2903. GarrisonDialog gd;
  2904. gd.hid = hid;
  2905. gd.objid = upobj;
  2906. gd.removableUnits = removableUnits;
  2907. gd.queryID = garrisonQuery->queryID;
  2908. sendAndApply(&gd);
  2909. }
  2910. void CGameHandler::showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId)
  2911. {
  2912. OpenWindow ow;
  2913. ow.window = EOpenWindowMode::THIEVES_GUILD;
  2914. ow.id1 = player.getNum();
  2915. ow.id2 = requestingObjId.getNum();
  2916. sendAndApply(&ow);
  2917. }
  2918. bool CGameHandler::isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2)
  2919. {
  2920. if (id1 == id2)
  2921. return true;
  2922. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  2923. if (!o1 || !o2)
  2924. return true; //arranging stacks within an object should be always allowed
  2925. if (o1 && o2)
  2926. {
  2927. if (o1->ID == Obj::TOWN)
  2928. {
  2929. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  2930. if (t->visitingHero == o2 || t->garrisonHero == o2)
  2931. return true;
  2932. }
  2933. if (o2->ID == Obj::TOWN)
  2934. {
  2935. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  2936. if (t->visitingHero == o1 || t->garrisonHero == o1)
  2937. return true;
  2938. }
  2939. if (o1->ID == Obj::HERO && o2->ID == Obj::HERO)
  2940. {
  2941. const CGHeroInstance *h1 = static_cast<const CGHeroInstance*>(o1);
  2942. const CGHeroInstance *h2 = static_cast<const CGHeroInstance*>(o2);
  2943. // two heroes in same town (garrisoned and visiting)
  2944. if (h1->visitedTown != nullptr && h2->visitedTown != nullptr && h1->visitedTown == h2->visitedTown)
  2945. return true;
  2946. }
  2947. //Ongoing garrison exchange - usually picking from top garison (from o1 to o2), but who knows
  2948. auto dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries->topQuery(o1->tempOwner));
  2949. if (!dialog)
  2950. {
  2951. dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries->topQuery(o2->tempOwner));
  2952. }
  2953. if (dialog)
  2954. {
  2955. auto topArmy = dialog->exchangingArmies.at(0);
  2956. auto bottomArmy = dialog->exchangingArmies.at(1);
  2957. if ((topArmy == o1 && bottomArmy == o2) || (bottomArmy == o1 && topArmy == o2))
  2958. return true;
  2959. }
  2960. }
  2961. return false;
  2962. }
  2963. void CGameHandler::objectVisited(const CGObjectInstance * obj, const CGHeroInstance * h)
  2964. {
  2965. using events::ObjectVisitStarted;
  2966. logGlobal->debug("%s visits %s (%d:%d)", h->nodeName(), obj->getObjectName(), obj->ID, obj->subID);
  2967. std::shared_ptr<CObjectVisitQuery> visitQuery;
  2968. auto startVisit = [&](ObjectVisitStarted & event)
  2969. {
  2970. auto visitedObject = obj;
  2971. if(obj->ID == Obj::HERO)
  2972. {
  2973. auto visitedHero = static_cast<const CGHeroInstance *>(obj);
  2974. const auto visitedTown = visitedHero->visitedTown;
  2975. if(visitedTown)
  2976. {
  2977. const bool isEnemy = visitedHero->getOwner() != h->getOwner();
  2978. if(isEnemy && !visitedTown->isBattleOutsideTown(visitedHero))
  2979. visitedObject = visitedTown;
  2980. }
  2981. }
  2982. visitQuery = std::make_shared<CObjectVisitQuery>(this, visitedObject, h, visitedObject->visitablePos());
  2983. queries->addQuery(visitQuery); //TODO real visit pos
  2984. HeroVisit hv;
  2985. hv.objId = obj->id;
  2986. hv.heroId = h->id;
  2987. hv.player = h->tempOwner;
  2988. hv.starting = true;
  2989. sendAndApply(&hv);
  2990. obj->onHeroVisit(h);
  2991. };
  2992. ObjectVisitStarted::defaultExecute(serverEventBus.get(), startVisit, h->tempOwner, h->id, obj->id);
  2993. if(visitQuery)
  2994. queries->popIfTop(visitQuery); //visit ends here if no queries were created
  2995. }
  2996. void CGameHandler::objectVisitEnded(const CObjectVisitQuery & query)
  2997. {
  2998. using events::ObjectVisitEnded;
  2999. logGlobal->debug("%s visit ends.\n", query.visitingHero->nodeName());
  3000. auto endVisit = [&](ObjectVisitEnded & event)
  3001. {
  3002. HeroVisit hv;
  3003. hv.player = event.getPlayer();
  3004. hv.heroId = event.getHero();
  3005. hv.starting = false;
  3006. sendAndApply(&hv);
  3007. };
  3008. //TODO: ObjectVisitEnded should also have id of visited object,
  3009. //but this requires object being deleted only by `removeAfterVisit()` but not `removeObject()`
  3010. ObjectVisitEnded::defaultExecute(serverEventBus.get(), endVisit, query.players.front(), query.visitingHero->id);
  3011. }
  3012. bool CGameHandler::buildBoat(ObjectInstanceID objid, PlayerColor playerID)
  3013. {
  3014. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  3015. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  3016. {
  3017. complain("Cannot build boat in this shipyard!");
  3018. return false;
  3019. }
  3020. TResources boatCost;
  3021. obj->getBoatCost(boatCost);
  3022. TResources aviable = getPlayerState(playerID)->resources;
  3023. if (!aviable.canAfford(boatCost))
  3024. {
  3025. complain("Not enough resources to build a boat!");
  3026. return false;
  3027. }
  3028. int3 tile = obj->bestLocation();
  3029. if (!gs->map->isInTheMap(tile))
  3030. {
  3031. complain("Cannot find appropriate tile for a boat!");
  3032. return false;
  3033. }
  3034. giveResources(playerID, -boatCost);
  3035. createObject(tile, Obj::BOAT, obj->getBoatType().getNum());
  3036. return true;
  3037. }
  3038. void CGameHandler::checkVictoryLossConditions(const std::set<PlayerColor> & playerColors)
  3039. {
  3040. for (auto playerColor : playerColors)
  3041. {
  3042. if (getPlayerState(playerColor, false))
  3043. checkVictoryLossConditionsForPlayer(playerColor);
  3044. }
  3045. }
  3046. void CGameHandler::checkVictoryLossConditionsForAll()
  3047. {
  3048. std::set<PlayerColor> playerColors;
  3049. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  3050. {
  3051. playerColors.insert(PlayerColor(i));
  3052. }
  3053. checkVictoryLossConditions(playerColors);
  3054. }
  3055. void CGameHandler::checkVictoryLossConditionsForPlayer(PlayerColor player)
  3056. {
  3057. const PlayerState * p = getPlayerState(player);
  3058. if(!p || p->status != EPlayerStatus::INGAME) return;
  3059. auto victoryLossCheckResult = gs->checkForVictoryAndLoss(player);
  3060. if (victoryLossCheckResult.victory() || victoryLossCheckResult.loss())
  3061. {
  3062. InfoWindow iw;
  3063. getVictoryLossMessage(player, victoryLossCheckResult, iw);
  3064. sendAndApply(&iw);
  3065. PlayerEndsGame peg;
  3066. peg.player = player;
  3067. peg.victoryLossCheckResult = victoryLossCheckResult;
  3068. sendAndApply(&peg);
  3069. if (victoryLossCheckResult.victory())
  3070. {
  3071. //one player won -> all enemies lost
  3072. for (auto i = gs->players.cbegin(); i!=gs->players.cend(); i++)
  3073. {
  3074. if (i->first != player && getPlayerState(i->first)->status == EPlayerStatus::INGAME)
  3075. {
  3076. peg.player = i->first;
  3077. peg.victoryLossCheckResult = getPlayerRelations(player, i->first) == PlayerRelations::ALLIES ?
  3078. victoryLossCheckResult : victoryLossCheckResult.invert(); // ally of winner
  3079. InfoWindow iw;
  3080. getVictoryLossMessage(player, peg.victoryLossCheckResult, iw);
  3081. iw.player = i->first;
  3082. sendAndApply(&iw);
  3083. sendAndApply(&peg);
  3084. }
  3085. }
  3086. if(p->human)
  3087. {
  3088. lobby->state = EServerState::GAMEPLAY_ENDED;
  3089. }
  3090. }
  3091. else
  3092. {
  3093. //copy heroes vector to avoid iterator invalidation as removal change PlayerState
  3094. auto hlp = p->heroes;
  3095. for (auto h : hlp) //eliminate heroes
  3096. {
  3097. if (h.get())
  3098. removeObject(h);
  3099. }
  3100. //player lost -> all his objects become unflagged (neutral)
  3101. for (auto obj : gs->map->objects) //unflag objs
  3102. {
  3103. if (obj.get() && obj->tempOwner == player)
  3104. setOwner(obj, PlayerColor::NEUTRAL);
  3105. }
  3106. //eliminating one player may cause victory of another:
  3107. std::set<PlayerColor> playerColors;
  3108. //do not copy player state (CBonusSystemNode) by value
  3109. for (auto &p : gs->players) //players may have different colors, iterate over players and not integers
  3110. {
  3111. if (p.first != player)
  3112. playerColors.insert(p.first);
  3113. }
  3114. //notify all players
  3115. for (auto pc : playerColors)
  3116. {
  3117. if (getPlayerState(pc)->status == EPlayerStatus::INGAME)
  3118. {
  3119. InfoWindow iw;
  3120. getVictoryLossMessage(player, victoryLossCheckResult.invert(), iw);
  3121. iw.player = pc;
  3122. sendAndApply(&iw);
  3123. }
  3124. }
  3125. checkVictoryLossConditions(playerColors);
  3126. }
  3127. auto playerInfo = getPlayerState(gs->currentPlayer, false);
  3128. // If we are called before the actual game start, there might be no current player
  3129. if (playerInfo && playerInfo->status != EPlayerStatus::INGAME)
  3130. {
  3131. // If player making turn has lost his turn must be over as well
  3132. states.setFlag(gs->currentPlayer, &PlayerStatus::makingTurn, false);
  3133. }
  3134. }
  3135. }
  3136. void CGameHandler::getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const
  3137. {
  3138. out.player = player;
  3139. out.text = victoryLossCheckResult.messageToSelf;
  3140. out.text.replaceLocalString(EMetaText::COLOR, player.getNum());
  3141. out.components.emplace_back(Component::EComponentType::FLAG, player.getNum(), 0, 0);
  3142. }
  3143. bool CGameHandler::dig(const CGHeroInstance *h)
  3144. {
  3145. if (h->diggingStatus() != EDiggingStatus::CAN_DIG) //checks for terrain and movement
  3146. COMPLAIN_RETF("Hero cannot dig (error code %d)!", h->diggingStatus());
  3147. createObject(h->visitablePos(), Obj::HOLE, 0 );
  3148. //take MPs
  3149. SetMovePoints smp;
  3150. smp.hid = h->id;
  3151. smp.val = 0;
  3152. sendAndApply(&smp);
  3153. InfoWindow iw;
  3154. iw.type = EInfoWindowMode::AUTO;
  3155. iw.player = h->tempOwner;
  3156. if (gs->map->grailPos == h->visitablePos())
  3157. {
  3158. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  3159. iw.text.appendLocalString(EMetaText::ART_NAMES, ArtifactID::GRAIL);
  3160. iw.soundID = soundBase::ULTIMATEARTIFACT;
  3161. giveHeroNewArtifact(h, VLC->arth->objects[ArtifactID::GRAIL], ArtifactPosition::FIRST_AVAILABLE); //give grail
  3162. sendAndApply(&iw);
  3163. iw.soundID = soundBase::invalid;
  3164. iw.components.emplace_back(Component::EComponentType::ARTIFACT, ArtifactID::GRAIL, 0, 0);
  3165. iw.text.clear();
  3166. iw.text.appendLocalString(EMetaText::ART_DESCR, ArtifactID::GRAIL);
  3167. sendAndApply(&iw);
  3168. }
  3169. else
  3170. {
  3171. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  3172. iw.soundID = soundBase::Dig;
  3173. sendAndApply(&iw);
  3174. }
  3175. return true;
  3176. }
  3177. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  3178. {
  3179. if (!t.visitableObjects.empty())
  3180. {
  3181. //to prevent self-visiting heroes on space press
  3182. if (t.visitableObjects.back() != h)
  3183. objectVisited(t.visitableObjects.back(), h);
  3184. else if (t.visitableObjects.size() > 1)
  3185. objectVisited(*(t.visitableObjects.end()-2),h);
  3186. }
  3187. }
  3188. bool CGameHandler::sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count)
  3189. {
  3190. if (!hero)
  3191. COMPLAIN_RET("You need hero to sacrifice creature!");
  3192. int expSum = 0;
  3193. auto finish = [this, &hero, &expSum]()
  3194. {
  3195. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(expSum));
  3196. };
  3197. for(int i = 0; i < slot.size(); ++i)
  3198. {
  3199. int oldCount = hero->getStackCount(slot[i]);
  3200. if(oldCount < (int)count[i])
  3201. {
  3202. finish();
  3203. COMPLAIN_RET("Not enough creatures to sacrifice!")
  3204. }
  3205. else if(oldCount == count[i] && hero->stacksCount() == 1 && hero->needsLastStack())
  3206. {
  3207. finish();
  3208. COMPLAIN_RET("Cannot sacrifice last creature!");
  3209. }
  3210. int crid = hero->getStack(slot[i]).type->getId();
  3211. changeStackCount(StackLocation(hero, slot[i]), -(TQuantity)count[i]);
  3212. int dump, exp;
  3213. market->getOffer(crid, 0, dump, exp, EMarketMode::CREATURE_EXP);
  3214. exp *= count[i];
  3215. expSum += exp;
  3216. }
  3217. finish();
  3218. return true;
  3219. }
  3220. bool CGameHandler::sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, const std::vector<ArtifactPosition> & slot)
  3221. {
  3222. if (!hero)
  3223. COMPLAIN_RET("You need hero to sacrifice artifact!");
  3224. int expSum = 0;
  3225. auto finish = [this, &hero, &expSum]()
  3226. {
  3227. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(expSum));
  3228. };
  3229. for(int i = 0; i < slot.size(); ++i)
  3230. {
  3231. ArtifactLocation al(hero, slot[i]);
  3232. const CArtifactInstance * a = al.getArt();
  3233. if(!a)
  3234. {
  3235. finish();
  3236. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  3237. }
  3238. const CArtifactInstance * art = hero->getArt(slot[i]);
  3239. if(!art)
  3240. {
  3241. finish();
  3242. COMPLAIN_RET("No artifact at position to sacrifice!");
  3243. }
  3244. si32 typId = art->artType->getId();
  3245. int dmp, expToGive;
  3246. m->getOffer(typId, 0, dmp, expToGive, EMarketMode::ARTIFACT_EXP);
  3247. expSum += expToGive;
  3248. removeArtifact(al);
  3249. }
  3250. finish();
  3251. return true;
  3252. }
  3253. bool CGameHandler::insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count)
  3254. {
  3255. if (sl.army->hasStackAtSlot(sl.slot))
  3256. COMPLAIN_RET("Slot is already taken!");
  3257. if (!sl.slot.validSlot())
  3258. COMPLAIN_RET("Cannot insert stack to that slot!");
  3259. InsertNewStack ins;
  3260. ins.army = sl.army->id;
  3261. ins.slot = sl.slot;
  3262. ins.type = c->getId();
  3263. ins.count = count;
  3264. sendAndApply(&ins);
  3265. return true;
  3266. }
  3267. bool CGameHandler::eraseStack(const StackLocation &sl, bool forceRemoval)
  3268. {
  3269. if (!sl.army->hasStackAtSlot(sl.slot))
  3270. COMPLAIN_RET("Cannot find a stack to erase");
  3271. if (sl.army->stacksCount() == 1 //from the last stack
  3272. && sl.army->needsLastStack() //that must be left
  3273. && !forceRemoval) //ignore above conditions if we are forcing removal
  3274. {
  3275. COMPLAIN_RET("Cannot erase the last stack!");
  3276. }
  3277. EraseStack es;
  3278. es.army = sl.army->id;
  3279. es.slot = sl.slot;
  3280. sendAndApply(&es);
  3281. return true;
  3282. }
  3283. bool CGameHandler::changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue)
  3284. {
  3285. TQuantity currentCount = sl.army->getStackCount(sl.slot);
  3286. if ((absoluteValue && count < 0)
  3287. || (!absoluteValue && -count > currentCount))
  3288. {
  3289. COMPLAIN_RET("Cannot take more stacks than present!");
  3290. }
  3291. if ((currentCount == -count && !absoluteValue)
  3292. || (!count && absoluteValue))
  3293. {
  3294. eraseStack(sl);
  3295. }
  3296. else
  3297. {
  3298. ChangeStackCount csc;
  3299. csc.army = sl.army->id;
  3300. csc.slot = sl.slot;
  3301. csc.count = count;
  3302. csc.absoluteValue = absoluteValue;
  3303. sendAndApply(&csc);
  3304. }
  3305. return true;
  3306. }
  3307. bool CGameHandler::addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count)
  3308. {
  3309. const CCreature *slotC = sl.army->getCreature(sl.slot);
  3310. if (!slotC) //slot is empty
  3311. insertNewStack(sl, c, count);
  3312. else if (c == slotC)
  3313. changeStackCount(sl, count);
  3314. else
  3315. {
  3316. COMPLAIN_RET("Cannot add " + c->getNamePluralTranslated() + " to slot " + boost::lexical_cast<std::string>(sl.slot) + "!");
  3317. }
  3318. return true;
  3319. }
  3320. void CGameHandler::tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging)
  3321. {
  3322. if (removeObjWhenFinished)
  3323. removeAfterVisit(src);
  3324. if (!src->canBeMergedWith(*dst, allowMerging))
  3325. {
  3326. if (allowMerging) //do that, add all matching creatures.
  3327. {
  3328. bool cont = true;
  3329. while (cont)
  3330. {
  3331. for (auto i = src->stacks.begin(); i != src->stacks.end(); i++)//while there are unmoved creatures
  3332. {
  3333. SlotID pos = dst->getSlotFor(i->second->type);
  3334. if (pos.validSlot())
  3335. {
  3336. moveStack(StackLocation(src, i->first), StackLocation(dst, pos));
  3337. cont = true;
  3338. break; //or iterator crashes
  3339. }
  3340. cont = false;
  3341. }
  3342. }
  3343. }
  3344. showGarrisonDialog(src->id, dst->id, true); //show garrison window and optionally remove ourselves from map when player ends
  3345. }
  3346. else //merge
  3347. {
  3348. moveArmy(src, dst, allowMerging);
  3349. }
  3350. }
  3351. bool CGameHandler::moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count)
  3352. {
  3353. if (!src.army->hasStackAtSlot(src.slot))
  3354. COMPLAIN_RET("No stack to move!");
  3355. if (dst.army->hasStackAtSlot(dst.slot) && dst.army->getCreature(dst.slot) != src.army->getCreature(src.slot))
  3356. COMPLAIN_RET("Cannot move: stack of different type at destination pos!");
  3357. if (!dst.slot.validSlot())
  3358. COMPLAIN_RET("Cannot move stack to that slot!");
  3359. if (count == -1)
  3360. {
  3361. count = src.army->getStackCount(src.slot);
  3362. }
  3363. if (src.army != dst.army //moving away
  3364. && count == src.army->getStackCount(src.slot) //all creatures
  3365. && src.army->stacksCount() == 1 //from the last stack
  3366. && src.army->needsLastStack()) //that must be left
  3367. {
  3368. COMPLAIN_RET("Cannot move away the last creature!");
  3369. }
  3370. RebalanceStacks rs;
  3371. rs.srcArmy = src.army->id;
  3372. rs.dstArmy = dst.army->id;
  3373. rs.srcSlot = src.slot;
  3374. rs.dstSlot = dst.slot;
  3375. rs.count = count;
  3376. sendAndApply(&rs);
  3377. return true;
  3378. }
  3379. void CGameHandler::castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos)
  3380. {
  3381. const CSpell * s = spellID.toSpell();
  3382. if(!s)
  3383. return;
  3384. AdventureSpellCastParameters p;
  3385. p.caster = caster;
  3386. p.pos = pos;
  3387. s->adventureCast(spellEnv, p);
  3388. }
  3389. bool CGameHandler::swapStacks(const StackLocation & sl1, const StackLocation & sl2)
  3390. {
  3391. if(!sl1.army->hasStackAtSlot(sl1.slot))
  3392. {
  3393. return moveStack(sl2, sl1);
  3394. }
  3395. else if(!sl2.army->hasStackAtSlot(sl2.slot))
  3396. {
  3397. return moveStack(sl1, sl2);
  3398. }
  3399. else
  3400. {
  3401. SwapStacks ss;
  3402. ss.srcArmy = sl1.army->id;
  3403. ss.dstArmy = sl2.army->id;
  3404. ss.srcSlot = sl1.slot;
  3405. ss.dstSlot = sl2.slot;
  3406. sendAndApply(&ss);
  3407. return true;
  3408. }
  3409. }
  3410. bool CGameHandler::giveHeroArtifact(const CGHeroInstance * h, const CArtifactInstance * a, ArtifactPosition pos)
  3411. {
  3412. assert(a->artType);
  3413. ArtifactLocation al(h, ArtifactPosition::PRE_FIRST);
  3414. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  3415. {
  3416. al.slot = ArtifactUtils::getArtAnyPosition(h, a->getTypeId());
  3417. }
  3418. else if(ArtifactUtils::isSlotBackpack(pos))
  3419. {
  3420. al.slot = ArtifactUtils::getArtBackpackPosition(h, a->getTypeId());
  3421. }
  3422. else
  3423. {
  3424. al.slot = pos;
  3425. }
  3426. if(a->canBePutAt(al))
  3427. putArtifact(al, a);
  3428. else
  3429. return false;
  3430. return true;
  3431. }
  3432. void CGameHandler::putArtifact(const ArtifactLocation &al, const CArtifactInstance *a)
  3433. {
  3434. PutArtifact pa;
  3435. pa.art = a;
  3436. pa.al = al;
  3437. sendAndApply(&pa);
  3438. }
  3439. bool CGameHandler::giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos)
  3440. {
  3441. assert(artType);
  3442. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  3443. {
  3444. if(!artType->canBePutAt(h, ArtifactUtils::getArtAnyPosition(h, artType->getId())))
  3445. COMPLAIN_RET("Cannot put artifact in that slot!");
  3446. }
  3447. else if(ArtifactUtils::isSlotBackpack(pos))
  3448. {
  3449. if(!artType->canBePutAt(h, ArtifactUtils::getArtBackpackPosition(h, artType->getId())))
  3450. COMPLAIN_RET("Cannot put artifact in that slot!");
  3451. }
  3452. else
  3453. {
  3454. COMPLAIN_RET_FALSE_IF(!artType->canBePutAt(h, pos, false), "Cannot put artifact in that slot!");
  3455. }
  3456. auto * newArtInst = new CArtifactInstance();
  3457. newArtInst->artType = artType; // *NOT* via settype -> all bonus-related stuff must be done by NewArtifact apply
  3458. NewArtifact na;
  3459. na.art = newArtInst;
  3460. sendAndApply(&na); // -> updates newArtInst!!!
  3461. if(giveHeroArtifact(h, newArtInst, pos))
  3462. return true;
  3463. else
  3464. return false;
  3465. }
  3466. void CGameHandler::spawnWanderingMonsters(CreatureID creatureID)
  3467. {
  3468. std::vector<int3>::iterator tile;
  3469. std::vector<int3> tiles;
  3470. getFreeTiles(tiles);
  3471. ui32 amount = (ui32)tiles.size() / 200; //Chance is 0.5% for each tile
  3472. RandomGeneratorUtil::randomShuffle(tiles, getRandomGenerator());
  3473. logGlobal->trace("Spawning wandering monsters. Found %d free tiles. Creature type: %d", tiles.size(), creatureID.num);
  3474. const CCreature *cre = VLC->creh->objects.at(creatureID);
  3475. for (int i = 0; i < (int)amount; ++i)
  3476. {
  3477. tile = tiles.begin();
  3478. logGlobal->trace("\tSpawning monster at %s", tile->toString());
  3479. {
  3480. auto count = cre->getRandomAmount(std::rand);
  3481. createObject(*tile, Obj::MONSTER, creatureID);
  3482. auto monsterId = getTopObj(*tile)->id;
  3483. setObjProperty(monsterId, ObjProperty::MONSTER_COUNT, count);
  3484. setObjProperty(monsterId, ObjProperty::MONSTER_POWER, (si64)1000*count);
  3485. }
  3486. tiles.erase(tile); //not use it again
  3487. }
  3488. }
  3489. void CGameHandler::synchronizeArtifactHandlerLists()
  3490. {
  3491. UpdateArtHandlerLists uahl;
  3492. uahl.treasures = VLC->arth->treasures;
  3493. uahl.minors = VLC->arth->minors;
  3494. uahl.majors = VLC->arth->majors;
  3495. uahl.relics = VLC->arth->relics;
  3496. sendAndApply(&uahl);
  3497. }
  3498. bool CGameHandler::isValidObject(const CGObjectInstance *obj) const
  3499. {
  3500. return vstd::contains(gs->map->objects, obj);
  3501. }
  3502. bool CGameHandler::isBlockedByQueries(const CPack *pack, PlayerColor player)
  3503. {
  3504. if (!strcmp(typeid(*pack).name(), typeid(PlayerMessage).name()))
  3505. return false;
  3506. auto query = queries->topQuery(player);
  3507. if (query && query->blocksPack(pack))
  3508. {
  3509. complain(boost::str(boost::format(
  3510. "\r\n| Player \"%s\" has to answer queries before attempting any further actions.\r\n| Top Query: \"%s\"\r\n")
  3511. % boost::to_upper_copy<std::string>(player.getStr())
  3512. % query->toString()
  3513. ));
  3514. return true;
  3515. }
  3516. return false;
  3517. }
  3518. void CGameHandler::removeAfterVisit(const CGObjectInstance *object)
  3519. {
  3520. //If the object is being visited, there must be a matching query
  3521. for (const auto &query : queries->allQueries())
  3522. {
  3523. if (auto someVistQuery = std::dynamic_pointer_cast<CObjectVisitQuery>(query))
  3524. {
  3525. if (someVistQuery->visitedObject == object)
  3526. {
  3527. someVistQuery->removeObjectAfterVisit = true;
  3528. return;
  3529. }
  3530. }
  3531. }
  3532. //If we haven't returned so far, there is no query and no visit, call was wrong
  3533. assert("This function needs to be called during the object visit!");
  3534. }
  3535. void CGameHandler::changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide)
  3536. {
  3537. std::unordered_set<int3> tiles;
  3538. getTilesInRange(tiles, center, radius, player, hide? -1 : 1);
  3539. if (hide)
  3540. {
  3541. std::unordered_set<int3> observedTiles; //do not hide tiles observed by heroes. May lead to disastrous AI problems
  3542. auto p = getPlayerState(player);
  3543. for (auto h : p->heroes)
  3544. {
  3545. getTilesInRange(observedTiles, h->getSightCenter(), h->getSightRadius(), h->tempOwner, -1);
  3546. }
  3547. for (auto t : p->towns)
  3548. {
  3549. getTilesInRange(observedTiles, t->getSightCenter(), t->getSightRadius(), t->tempOwner, -1);
  3550. }
  3551. for (auto tile : observedTiles)
  3552. vstd::erase_if_present (tiles, tile);
  3553. }
  3554. changeFogOfWar(tiles, player, hide);
  3555. }
  3556. void CGameHandler::changeFogOfWar(std::unordered_set<int3> &tiles, PlayerColor player, bool hide)
  3557. {
  3558. FoWChange fow;
  3559. fow.tiles = tiles;
  3560. fow.player = player;
  3561. fow.mode = hide? 0 : 1;
  3562. sendAndApply(&fow);
  3563. }
  3564. bool CGameHandler::isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero)
  3565. {
  3566. if (auto topQuery = queries->topQuery(hero->getOwner()))
  3567. if (auto visit = std::dynamic_pointer_cast<const CObjectVisitQuery>(topQuery))
  3568. return !(visit->visitedObject == obj && visit->visitingHero == hero);
  3569. return true;
  3570. }
  3571. void CGameHandler::setObjProperty(ObjectInstanceID objid, int prop, si64 val)
  3572. {
  3573. SetObjectProperty sob;
  3574. sob.id = objid;
  3575. sob.what = prop;
  3576. sob.val = static_cast<ui32>(val);
  3577. sendAndApply(&sob);
  3578. }
  3579. void CGameHandler::showInfoDialog(InfoWindow * iw)
  3580. {
  3581. sendAndApply(iw);
  3582. }
  3583. void CGameHandler::showInfoDialog(const std::string & msg, PlayerColor player)
  3584. {
  3585. InfoWindow iw;
  3586. iw.player = player;
  3587. iw.text.appendRawString(msg);
  3588. showInfoDialog(&iw);
  3589. }
  3590. CRandomGenerator & CGameHandler::getRandomGenerator()
  3591. {
  3592. return CRandomGenerator::getDefault();
  3593. }
  3594. #if SCRIPTING_ENABLED
  3595. scripting::Pool * CGameHandler::getGlobalContextPool() const
  3596. {
  3597. return serverScripts.get();
  3598. }
  3599. scripting::Pool * CGameHandler::getContextPool() const
  3600. {
  3601. return serverScripts.get();
  3602. }
  3603. #endif
  3604. void CGameHandler::createObject(const int3 & visitablePosition, Obj type, int32_t subtype)
  3605. {
  3606. NewObject no;
  3607. no.ID = type;
  3608. no.subID= subtype;
  3609. no.targetPos = visitablePosition;
  3610. sendAndApply(&no);
  3611. }
  3612. void CGameHandler::deserializationFix()
  3613. {
  3614. //FIXME: pointer to GameHandler itself can't be deserialized at the moment since GameHandler is top-level entity in serialization
  3615. // restore any places that requires such pointer manually
  3616. heroPool->gameHandler = this;
  3617. battles->setGameHandler(this);
  3618. playerMessages->gameHandler = this;
  3619. }
  3620. void CGameHandler::startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, const CGTownInstance *town)
  3621. {
  3622. battles->startBattlePrimary(army1, army2, tile, hero1, hero2, creatureBank, town);
  3623. }
  3624. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank )
  3625. {
  3626. battles->startBattleI(army1, army2, tile, creatureBank);
  3627. }
  3628. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank )
  3629. {
  3630. battles->startBattleI(army1, army2, creatureBank);
  3631. }