CGameHandler.cpp 130 KB

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