CGameHandler.cpp 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305
  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/VCMI_Lib.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/mapping/CMap.h"
  51. #include "../lib/mapping/CMapService.h"
  52. #include "../lib/mapObjects/CGCreature.h"
  53. #include "../lib/mapObjects/CGMarket.h"
  54. #include "../lib/mapObjects/TownBuildingInstance.h"
  55. #include "../lib/mapObjects/CGTownInstance.h"
  56. #include "../lib/mapObjects/MiscObjects.h"
  57. #include "../lib/mapObjectConstructors/AObjectTypeHandler.h"
  58. #include "../lib/mapObjectConstructors/CObjectClassesHandler.h"
  59. #include "../lib/modding/ModIncompatibility.h"
  60. #include "../lib/networkPacks/StackLocation.h"
  61. #include "../lib/pathfinder/CPathfinder.h"
  62. #include "../lib/pathfinder/PathfinderOptions.h"
  63. #include "../lib/pathfinder/TurnInfo.h"
  64. #include "../lib/rmg/CMapGenOptions.h"
  65. #include "../lib/serializer/CSaveFile.h"
  66. #include "../lib/serializer/CLoadFile.h"
  67. #include "../lib/serializer/Connection.h"
  68. #include "../lib/spells/CSpellHandler.h"
  69. #include <vstd/RNG.h>
  70. #include <vstd/CLoggerBase.h>
  71. #include <vcmi/events/EventBus.h>
  72. #include <vcmi/events/GenericEvents.h>
  73. #include <vcmi/events/AdventureEvents.h>
  74. #define COMPLAIN_RET_IF(cond, txt) do {if (cond){complain(txt); return;}} while(0)
  75. #define COMPLAIN_RET_FALSE_IF(cond, txt) do {if (cond){complain(txt); return false;}} while(0)
  76. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  77. #define COMPLAIN_RETF(txt, FORMAT) {complain(boost::str(boost::format(txt) % FORMAT)); return false;}
  78. static inline double distance(int3 a, int3 b)
  79. {
  80. return std::sqrt((double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
  81. }
  82. template <typename T>
  83. void callWith(std::vector<T> args, std::function<void(T)> fun, ui32 which)
  84. {
  85. fun(args[which]);
  86. }
  87. const Services * CGameHandler::services() const
  88. {
  89. return VLC;
  90. }
  91. const CGameHandler::BattleCb * CGameHandler::battle(const BattleID & battleID) const
  92. {
  93. return gs->getBattle(battleID);
  94. }
  95. const CGameHandler::GameCb * CGameHandler::game() const
  96. {
  97. return this;
  98. }
  99. vstd::CLoggerBase * CGameHandler::logger() const
  100. {
  101. return logGlobal;
  102. }
  103. events::EventBus * CGameHandler::eventBus() const
  104. {
  105. return serverEventBus.get();
  106. }
  107. CVCMIServer * CGameHandler::gameLobby() const
  108. {
  109. return lobby;
  110. }
  111. void CGameHandler::levelUpHero(const CGHeroInstance * hero, SecondarySkill skill)
  112. {
  113. changeSecSkill(hero, skill, 1, 0);
  114. expGiven(hero);
  115. }
  116. void CGameHandler::levelUpHero(const CGHeroInstance * hero)
  117. {
  118. // required exp for at least 1 lvl-up hasn't been reached
  119. if (!hero->gainsLevel())
  120. {
  121. return;
  122. }
  123. // give primary skill
  124. logGlobal->trace("%s got level %d", hero->getNameTranslated(), hero->level);
  125. auto primarySkill = hero->nextPrimarySkill(getRandomGenerator());
  126. SetPrimSkill sps;
  127. sps.id = hero->id;
  128. sps.which = primarySkill;
  129. sps.abs = false;
  130. sps.val = 1;
  131. sendAndApply(sps);
  132. HeroLevelUp hlu;
  133. hlu.player = hero->tempOwner;
  134. hlu.heroId = hero->id;
  135. hlu.primskill = primarySkill;
  136. hlu.skills = hero->getLevelUpProposedSecondarySkills(heroPool->getHeroSkillsRandomGenerator(hero->getHeroTypeID()));
  137. if (hlu.skills.size() == 0)
  138. {
  139. sendAndApply(hlu);
  140. levelUpHero(hero);
  141. }
  142. else if (hlu.skills.size() == 1 || !hero->getOwner().isValidPlayer())
  143. {
  144. sendAndApply(hlu);
  145. levelUpHero(hero, hlu.skills.front());
  146. }
  147. else if (hlu.skills.size() > 1)
  148. {
  149. auto levelUpQuery = std::make_shared<CHeroLevelUpDialogQuery>(this, hlu, hero);
  150. hlu.queryID = levelUpQuery->queryID;
  151. queries->addQuery(levelUpQuery);
  152. sendAndApply(hlu);
  153. //level up will be called on query reply
  154. }
  155. }
  156. void CGameHandler::levelUpCommander (const CCommanderInstance * c, int skill)
  157. {
  158. SetCommanderProperty scp;
  159. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  160. if (hero)
  161. scp.heroid = hero->id;
  162. else
  163. {
  164. complain ("Commander is not led by hero!");
  165. return;
  166. }
  167. scp.accumulatedBonus.additionalInfo = 0;
  168. scp.accumulatedBonus.duration = BonusDuration::PERMANENT;
  169. scp.accumulatedBonus.turnsRemain = 0;
  170. scp.accumulatedBonus.source = BonusSource::COMMANDER;
  171. scp.accumulatedBonus.valType = BonusValueType::BASE_NUMBER;
  172. if (skill <= ECommander::SPELL_POWER)
  173. {
  174. scp.which = SetCommanderProperty::BONUS;
  175. auto difference = [](std::vector< std::vector <ui8> > skillLevels, std::vector <ui8> secondarySkills, int skill)->int
  176. {
  177. int s = std::min (skill, (int)ECommander::SPELL_POWER); //spell power level controls also casts and resistance
  178. return skillLevels.at(skill).at(secondarySkills.at(s)) - (secondarySkills.at(s) ? skillLevels.at(skill).at(secondarySkills.at(s)-1) : 0);
  179. };
  180. switch (skill)
  181. {
  182. case ECommander::ATTACK:
  183. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  184. scp.accumulatedBonus.subtype = BonusSubtypeID(PrimarySkill::ATTACK);
  185. break;
  186. case ECommander::DEFENSE:
  187. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  188. scp.accumulatedBonus.subtype = BonusSubtypeID(PrimarySkill::DEFENSE);
  189. break;
  190. case ECommander::HEALTH:
  191. scp.accumulatedBonus.type = BonusType::STACK_HEALTH;
  192. 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.
  193. break;
  194. case ECommander::DAMAGE:
  195. scp.accumulatedBonus.type = BonusType::CREATURE_DAMAGE;
  196. scp.accumulatedBonus.subtype = BonusCustomSubtype::creatureDamageBoth;
  197. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_ALL;
  198. break;
  199. case ECommander::SPEED:
  200. scp.accumulatedBonus.type = BonusType::STACKS_SPEED;
  201. break;
  202. case ECommander::SPELL_POWER:
  203. scp.accumulatedBonus.type = BonusType::SPELL_DAMAGE_REDUCTION;
  204. scp.accumulatedBonus.subtype = BonusSubtypeID(SpellSchool::ANY);
  205. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::RESISTANCE);
  206. sendAndApply(scp); //additional pack
  207. scp.accumulatedBonus.type = BonusType::CREATURE_SPELL_POWER;
  208. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::SPELL_POWER) * 100; //like hero with spellpower = ability level
  209. sendAndApply(scp); //additional pack
  210. scp.accumulatedBonus.type = BonusType::CASTS;
  211. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::CASTS);
  212. sendAndApply(scp); //additional pack
  213. scp.accumulatedBonus.type = BonusType::CREATURE_ENCHANT_POWER; //send normally
  214. break;
  215. }
  216. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, skill);
  217. sendAndApply(scp);
  218. scp.which = SetCommanderProperty::SECONDARY_SKILL;
  219. scp.additionalInfo = skill;
  220. scp.amount = c->secondarySkills.at(skill) + 1;
  221. sendAndApply(scp);
  222. }
  223. else if (skill >= 100)
  224. {
  225. for(auto & bonus : VLC->creh->skillRequirements.at(skill - 100).first)
  226. {
  227. scp.which = SetCommanderProperty::SPECIAL_SKILL;
  228. scp.accumulatedBonus = *bonus;
  229. scp.additionalInfo = skill; //unnormalized
  230. sendAndApply(scp);
  231. }
  232. }
  233. expGiven(hero);
  234. }
  235. void CGameHandler::levelUpCommander(const CCommanderInstance * c)
  236. {
  237. if (!c->gainsLevel())
  238. {
  239. return;
  240. }
  241. CommanderLevelUp clu;
  242. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  243. if(hero)
  244. {
  245. clu.heroId = hero->id;
  246. clu.player = hero->tempOwner;
  247. }
  248. else
  249. {
  250. complain ("Commander is not led by hero!");
  251. return;
  252. }
  253. //picking sec. skills for choice
  254. for (int i = 0; i <= ECommander::SPELL_POWER; ++i)
  255. {
  256. if (c->secondarySkills.at(i) < ECommander::MAX_SKILL_LEVEL)
  257. clu.skills.push_back(i);
  258. }
  259. int i = 100;
  260. for (auto specialSkill : VLC->creh->skillRequirements)
  261. {
  262. if (c->secondarySkills.at(specialSkill.second.first) >= ECommander::MAX_SKILL_LEVEL - 1
  263. && c->secondarySkills.at(specialSkill.second.second) >= ECommander::MAX_SKILL_LEVEL - 1
  264. && !vstd::contains (c->specialSkills, i))
  265. clu.skills.push_back (i);
  266. ++i;
  267. }
  268. int skillAmount = static_cast<int>(clu.skills.size());
  269. if (!skillAmount)
  270. {
  271. sendAndApply(clu);
  272. levelUpCommander(c);
  273. }
  274. else if (skillAmount == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  275. {
  276. sendAndApply(clu);
  277. levelUpCommander(c, *RandomGeneratorUtil::nextItem(clu.skills, getRandomGenerator()));
  278. }
  279. else if (skillAmount > 1) //apply and ask for secondary skill
  280. {
  281. auto commanderLevelUp = std::make_shared<CCommanderLevelUpDialogQuery>(this, clu, hero);
  282. clu.queryID = commanderLevelUp->queryID;
  283. queries->addQuery(commanderLevelUp);
  284. sendAndApply(clu);
  285. }
  286. }
  287. void CGameHandler::expGiven(const CGHeroInstance *hero)
  288. {
  289. if (hero->gainsLevel())
  290. levelUpHero(hero);
  291. else if (hero->commander && hero->commander->gainsLevel())
  292. levelUpCommander(hero->commander);
  293. //if (hero->commander && hero->level > hero->commander->level && hero->commander->gainsLevel())
  294. // levelUpCommander(hero->commander);
  295. // else
  296. // levelUpHero(hero);
  297. }
  298. void CGameHandler::giveExperience(const CGHeroInstance * hero, TExpType amountToGain)
  299. {
  300. TExpType maxExp = VLC->heroh->reqExp(VLC->heroh->maxSupportedLevel());
  301. TExpType currExp = hero->exp;
  302. if (gs->map->levelLimit != 0)
  303. maxExp = VLC->heroh->reqExp(gs->map->levelLimit);
  304. TExpType canGainExp = 0;
  305. if (maxExp > currExp)
  306. canGainExp = maxExp - currExp;
  307. if (amountToGain > canGainExp)
  308. {
  309. // set given experience to max possible, but don't decrease if hero already over top
  310. amountToGain = canGainExp;
  311. InfoWindow iw;
  312. iw.player = hero->tempOwner;
  313. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 1); //can gain no more XP
  314. iw.text.replaceTextID(hero->getNameTextID());
  315. sendAndApply(iw);
  316. }
  317. SetPrimSkill sps;
  318. sps.id = hero->id;
  319. sps.which = PrimarySkill::EXPERIENCE;
  320. sps.abs = false;
  321. sps.val = amountToGain;
  322. sendAndApply(sps);
  323. //hero may level up
  324. if (hero->commander && hero->commander->alive)
  325. {
  326. //FIXME: trim experience according to map limit?
  327. SetCommanderProperty scp;
  328. scp.heroid = hero->id;
  329. scp.which = SetCommanderProperty::EXPERIENCE;
  330. scp.amount = amountToGain;
  331. sendAndApply(scp);
  332. CBonusSystemNode::treeHasChanged();
  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(lobby->getState() == EServerState::SHUTDOWN || !gs || !gs->scenarioOps)
  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->scenarioOps->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(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. pack.c->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);
  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(VLC, 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->map->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(VLC)->getGrowth())/2);
  512. }
  513. else
  514. {
  515. ssi.creatures[town->getTown()->creatures.size()].first = creatureId.toEntity(VLC)->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->map->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->map->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->map->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->map->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 : lobby->activeConnections)
  608. {
  609. auto players = lobby->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(); //eg if monster escaped (removing objs after battle is done dircetly 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->map->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 = pathfinderHelper->hasBonusOfType(BonusType::FLYING_MOVEMENT) || (h->boat && h->boat->layer == EPathfindingLayer::AIR);
  728. const bool canWalkOnSea = pathfinderHelper->hasBonusOfType(BonusType::WATER_WALKING) || (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 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->map->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 = std::make_optional(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, 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, 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 : lobby->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(CPackForServer * pack, ObjectInstanceID id)
  1245. {
  1246. return pack->player == getOwner(id) && hasPlayerAt(getOwner(id), pack->c);
  1247. }
  1248. void CGameHandler::throwNotAllowedAction(CPackForServer * pack)
  1249. {
  1250. if(pack->c)
  1251. playerMessages->sendSystemMessage(pack->c, "You are not allowed to perform this action!");
  1252. logNetwork->error("Player is not allowed to perform this action!");
  1253. throw ExceptionNotAllowedAction();
  1254. }
  1255. void CGameHandler::wrongPlayerMessage(CPackForServer * pack, PlayerColor expectedplayer)
  1256. {
  1257. std::ostringstream oss;
  1258. oss << "You were identified as player " << pack->player << " while expecting " << expectedplayer;
  1259. logNetwork->error(oss.str());
  1260. if(pack->c)
  1261. playerMessages->sendSystemMessage(pack->c, oss.str());
  1262. }
  1263. void CGameHandler::throwIfWrongOwner(CPackForServer * pack, ObjectInstanceID id)
  1264. {
  1265. if(!isPlayerOwns(pack, id))
  1266. {
  1267. wrongPlayerMessage(pack, getOwner(id));
  1268. throwNotAllowedAction(pack);
  1269. }
  1270. }
  1271. void CGameHandler::throwIfPlayerNotActive(CPackForServer * pack)
  1272. {
  1273. if (!turnOrder->isPlayerMakingTurn(pack->player))
  1274. throwNotAllowedAction(pack);
  1275. }
  1276. void CGameHandler::throwIfWrongPlayer(CPackForServer * pack)
  1277. {
  1278. throwIfWrongPlayer(pack, pack->player);
  1279. }
  1280. void CGameHandler::throwIfWrongPlayer(CPackForServer * pack, PlayerColor player)
  1281. {
  1282. if(!hasPlayerAt(player, pack->c) || pack->player != player)
  1283. {
  1284. wrongPlayerMessage(pack, player);
  1285. throwNotAllowedAction(pack);
  1286. }
  1287. }
  1288. void CGameHandler::throwAndComplain(CPackForServer * pack, std::string txt)
  1289. {
  1290. complain(txt);
  1291. throwNotAllowedAction(pack);
  1292. }
  1293. void CGameHandler::save(const std::string & filename)
  1294. {
  1295. logGlobal->info("Saving to %s", filename);
  1296. const auto stem = FileInfo::GetPathStem(filename);
  1297. const auto savefname = stem.to_string() + ".vsgm1";
  1298. ResourcePath savePath(stem.to_string(), EResType::SAVEGAME);
  1299. CResourceHandler::get("local")->createResource(savefname);
  1300. try
  1301. {
  1302. {
  1303. CSaveFile save(*CResourceHandler::get("local")->getResourceName(savePath));
  1304. saveCommonState(save);
  1305. logGlobal->info("Saving server state");
  1306. save << *this;
  1307. }
  1308. logGlobal->info("Game has been successfully saved!");
  1309. }
  1310. catch(std::exception &e)
  1311. {
  1312. logGlobal->error("Failed to save game: %s", e.what());
  1313. }
  1314. }
  1315. bool CGameHandler::load(const std::string & filename)
  1316. {
  1317. logGlobal->info("Loading from %s", filename);
  1318. const auto stem = FileInfo::GetPathStem(filename);
  1319. reinitScripting();
  1320. try
  1321. {
  1322. {
  1323. CLoadFile lf(*CResourceHandler::get()->getResourceName(ResourcePath(stem.to_string(), EResType::SAVEGAME)), ESerializationVersion::MINIMAL);
  1324. lf.serializer.cb = this;
  1325. loadCommonState(lf);
  1326. logGlobal->info("Loading server state");
  1327. lf >> *this;
  1328. }
  1329. logGlobal->info("Game has been successfully loaded!");
  1330. }
  1331. catch(const ModIncompatibility & e)
  1332. {
  1333. logGlobal->error("Failed to load game: %s", e.what());
  1334. std::string errorMsg;
  1335. if(!e.whatMissing().empty())
  1336. {
  1337. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToEnable") + '\n';
  1338. errorMsg += e.whatMissing();
  1339. }
  1340. if(!e.whatExcessive().empty())
  1341. {
  1342. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToDisable") + '\n';
  1343. errorMsg += e.whatExcessive();
  1344. }
  1345. lobby->announceMessage(errorMsg);
  1346. return false;
  1347. }
  1348. catch(const IdentifierResolutionException & e)
  1349. {
  1350. logGlobal->error("Failed to load game: %s", e.what());
  1351. MetaString errorMsg;
  1352. errorMsg.appendTextID("vcmi.server.errors.unknownEntity");
  1353. errorMsg.replaceRawString(e.identifierName);
  1354. lobby->announceMessage(errorMsg.toString());//FIXME: should be localized on client side
  1355. return false;
  1356. }
  1357. catch(const std::exception & e)
  1358. {
  1359. logGlobal->error("Failed to load game: %s", e.what());
  1360. lobby->announceMessage(std::string("Failed to load game: ") + e.what());
  1361. return false;
  1362. }
  1363. gs->preInit(VLC, this);
  1364. gs->updateOnLoad(lobby->si.get());
  1365. return true;
  1366. }
  1367. bool CGameHandler::bulkSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner, si32 howMany)
  1368. {
  1369. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  1370. return false;
  1371. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  1372. const CCreatureSet & creatureSet = *army;
  1373. if((!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  1374. || (howMany < 1 && complain("Invalid split parameter!")))
  1375. {
  1376. return false;
  1377. }
  1378. auto actualAmount = army->getStackCount(slotSrc);
  1379. if(actualAmount <= howMany && complain(complainNotEnoughCreatures)) // '<=' because it's not intended just for moving a stack
  1380. return false;
  1381. auto freeSlots = creatureSet.getFreeSlots();
  1382. if(freeSlots.empty() && complain("No empty stacks"))
  1383. return false;
  1384. BulkRebalanceStacks bulkRS;
  1385. for(auto slot : freeSlots)
  1386. {
  1387. RebalanceStacks rs;
  1388. rs.srcArmy = army->id;
  1389. rs.dstArmy = army->id;
  1390. rs.srcSlot = slotSrc;
  1391. rs.dstSlot = slot;
  1392. rs.count = howMany;
  1393. bulkRS.moves.push_back(rs);
  1394. actualAmount -= howMany;
  1395. if(actualAmount <= howMany)
  1396. break;
  1397. }
  1398. sendAndApply(bulkRS);
  1399. return true;
  1400. }
  1401. bool CGameHandler::bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner)
  1402. {
  1403. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  1404. return false;
  1405. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  1406. const CCreatureSet & creatureSet = *army;
  1407. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  1408. return false;
  1409. auto actualAmount = creatureSet.getStackCount(slotSrc);
  1410. if(actualAmount < 1 && complain(complainNoCreatures))
  1411. return false;
  1412. auto currentCreature = creatureSet.getCreature(slotSrc);
  1413. if(!currentCreature && complain(complainNoCreatures))
  1414. return false;
  1415. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, slotSrc);
  1416. if(!creatureSlots.size())
  1417. return false;
  1418. BulkRebalanceStacks bulkRS;
  1419. for(auto slot : creatureSlots)
  1420. {
  1421. RebalanceStacks rs;
  1422. rs.srcArmy = army->id;
  1423. rs.dstArmy = army->id;
  1424. rs.srcSlot = slot;
  1425. rs.dstSlot = slotSrc;
  1426. rs.count = creatureSet.getStackCount(slot);
  1427. bulkRS.moves.push_back(rs);
  1428. }
  1429. sendAndApply(bulkRS);
  1430. return true;
  1431. }
  1432. bool CGameHandler::bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot)
  1433. {
  1434. if(!srcSlot.validSlot() && complain(complainInvalidSlot))
  1435. return false;
  1436. const CArmedInstance * armySrc = static_cast<const CArmedInstance*>(getObjInstance(srcArmy));
  1437. const CCreatureSet & setSrc = *armySrc;
  1438. if(!vstd::contains(setSrc.stacks, srcSlot) && complain(complainNoCreatures))
  1439. return false;
  1440. const CArmedInstance * armyDest = static_cast<const CArmedInstance*>(getObjInstance(destArmy));
  1441. const CCreatureSet & setDest = *armyDest;
  1442. auto freeSlots = setDest.getFreeSlotsQueue();
  1443. typedef std::map<SlotID, std::pair<SlotID, TQuantity>> TRebalanceMap;
  1444. TRebalanceMap moves;
  1445. auto srcQueue = setSrc.getCreatureQueue(srcSlot); // Exclude srcSlot, it should be moved last
  1446. auto slotsLeft = setSrc.stacksCount();
  1447. auto destMap = setDest.getCreatureMap();
  1448. TMapCreatureSlot::key_compare keyComp = destMap.key_comp();
  1449. while(!srcQueue.empty())
  1450. {
  1451. auto pair = srcQueue.top();
  1452. srcQueue.pop();
  1453. auto currCreature = pair.first;
  1454. auto currSlot = pair.second;
  1455. const auto quantity = setSrc.getStackCount(currSlot);
  1456. TMapCreatureSlot::iterator lb = destMap.lower_bound(currCreature);
  1457. const bool alreadyExists = (lb != destMap.end() && !(keyComp(currCreature, lb->first)));
  1458. if(!alreadyExists)
  1459. {
  1460. if(freeSlots.empty())
  1461. continue;
  1462. auto currFreeSlot = freeSlots.front();
  1463. freeSlots.pop();
  1464. destMap.insert(lb, TMapCreatureSlot::value_type(currCreature, currFreeSlot));
  1465. }
  1466. moves.insert(std::make_pair(currSlot, std::make_pair(destMap[currCreature], quantity)));
  1467. slotsLeft--;
  1468. }
  1469. if(slotsLeft == 1)
  1470. {
  1471. auto lastCreature = setSrc.getCreature(srcSlot);
  1472. auto slotToMove = SlotID();
  1473. // Try to find a slot for last creature
  1474. if(destMap.find(lastCreature) == destMap.end())
  1475. {
  1476. if(!freeSlots.empty())
  1477. slotToMove = freeSlots.front();
  1478. }
  1479. else
  1480. {
  1481. slotToMove = destMap[lastCreature];
  1482. }
  1483. if(slotToMove != SlotID())
  1484. {
  1485. const bool needsLastStack = armySrc->needsLastStack();
  1486. const auto quantity = setSrc.getStackCount(srcSlot) - (needsLastStack ? 1 : 0);
  1487. 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
  1488. moves.insert(std::make_pair(srcSlot, std::make_pair(slotToMove, quantity)));
  1489. }
  1490. }
  1491. BulkRebalanceStacks bulkRS;
  1492. for(auto & move : moves)
  1493. {
  1494. RebalanceStacks rs;
  1495. rs.srcArmy = armySrc->id;
  1496. rs.dstArmy = armyDest->id;
  1497. rs.srcSlot = move.first;
  1498. rs.dstSlot = move.second.first;
  1499. rs.count = move.second.second;
  1500. bulkRS.moves.push_back(rs);
  1501. }
  1502. sendAndApply(bulkRS);
  1503. return true;
  1504. }
  1505. bool CGameHandler::bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner)
  1506. {
  1507. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  1508. return false;
  1509. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  1510. const CCreatureSet & creatureSet = *army;
  1511. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  1512. return false;
  1513. auto actualAmount = creatureSet.getStackCount(slotSrc);
  1514. if(actualAmount <= 1 && complain(complainNoCreatures))
  1515. return false;
  1516. auto freeSlot = creatureSet.getFreeSlot();
  1517. auto currentCreature = creatureSet.getCreature(slotSrc);
  1518. if(freeSlot == SlotID() && creatureSet.isCreatureBalanced(currentCreature))
  1519. return true;
  1520. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, SlotID(-1), 1); // Ignore slots where's only 1 creature, don't ignore slotSrc
  1521. TQuantity totalCreatures = 0;
  1522. for(auto slot : creatureSlots)
  1523. totalCreatures += creatureSet.getStackCount(slot);
  1524. if(totalCreatures <= 1 && complain("Total creatures number is invalid"))
  1525. return false;
  1526. if(freeSlot != SlotID())
  1527. creatureSlots.push_back(freeSlot);
  1528. if(creatureSlots.empty() && complain("No available slots for smart rebalancing"))
  1529. return false;
  1530. const auto totalCreatureSlots = creatureSlots.size();
  1531. const auto rem = totalCreatures % totalCreatureSlots;
  1532. const auto quotient = totalCreatures / totalCreatureSlots;
  1533. // totalCreatures == rem * (quotient + 1) + (totalCreatureSlots - rem) * quotient;
  1534. // Proof: r(q+1)+(s-r)q = rq+r+qs-rq = r+qs = total, where total/s = q+r/s
  1535. BulkSmartRebalanceStacks bulkSRS;
  1536. if(freeSlot != SlotID())
  1537. {
  1538. RebalanceStacks rs;
  1539. rs.srcArmy = rs.dstArmy = army->id;
  1540. rs.srcSlot = slotSrc;
  1541. rs.dstSlot = freeSlot;
  1542. rs.count = 1;
  1543. bulkSRS.moves.push_back(rs);
  1544. }
  1545. auto currSlot = 0;
  1546. auto check = 0;
  1547. for(auto slot : creatureSlots)
  1548. {
  1549. ChangeStackCount csc;
  1550. csc.army = army->id;
  1551. csc.slot = slot;
  1552. csc.count = (currSlot < rem)
  1553. ? quotient + 1
  1554. : quotient;
  1555. csc.absoluteValue = true;
  1556. bulkSRS.changes.push_back(csc);
  1557. currSlot++;
  1558. check += csc.count;
  1559. }
  1560. if(check != totalCreatures)
  1561. {
  1562. complain((boost::format("Failure: totalCreatures=%d but check=%d") % totalCreatures % check).str());
  1563. return false;
  1564. }
  1565. sendAndApply(bulkSRS);
  1566. return true;
  1567. }
  1568. bool CGameHandler::arrangeStacks(ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player)
  1569. {
  1570. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObj(id1));
  1571. const CArmedInstance * s2 = static_cast<const CArmedInstance *>(getObj(id2));
  1572. if (s1 == nullptr || s2 == nullptr)
  1573. {
  1574. complain("Cannot exchange stacks between non-existing objects!!\n");
  1575. return false;
  1576. }
  1577. const CCreatureSet & S1 = *s1;
  1578. const CCreatureSet & S2 = *s2;
  1579. StackLocation sl1(s1, p1);
  1580. StackLocation sl2(s2, p2);
  1581. if (!sl1.slot.validSlot() || !sl2.slot.validSlot())
  1582. {
  1583. complain(complainInvalidSlot);
  1584. return false;
  1585. }
  1586. if (!isAllowedExchange(id1,id2))
  1587. {
  1588. complain("Cannot exchange stacks between these two objects!\n");
  1589. return false;
  1590. }
  1591. // We can always put stacks into locked garrison, but not take them out of it
  1592. auto notRemovable = [&](const CArmedInstance * army)
  1593. {
  1594. if (id1 != id2) // Stack arrangement inside locked garrison is allowed
  1595. {
  1596. auto g = dynamic_cast<const CGGarrison *>(army);
  1597. if (g && !g->removableUnits)
  1598. {
  1599. complain("Stacks in this garrison are not removable!\n");
  1600. return true;
  1601. }
  1602. }
  1603. return false;
  1604. };
  1605. if (what==1) //swap
  1606. {
  1607. if (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s1->getStackCount(p1))
  1608. || ((s2->tempOwner != player && s2->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)))
  1609. {
  1610. complain("Can't take troops from another player!");
  1611. return false;
  1612. }
  1613. if (sl1.army == sl2.army && sl1.slot == sl2.slot)
  1614. {
  1615. complain("Cannot swap stacks - slots are the same!");
  1616. return false;
  1617. }
  1618. if (!s1->slotEmpty(p1) && !s2->slotEmpty(p2))
  1619. {
  1620. if (notRemovable(sl1.army) || notRemovable(sl2.army))
  1621. return false;
  1622. }
  1623. if (s1->slotEmpty(p1) && notRemovable(sl2.army))
  1624. return false;
  1625. else if (s2->slotEmpty(p2) && notRemovable(sl1.army))
  1626. return false;
  1627. swapStacks(sl1, sl2);
  1628. }
  1629. else if (what==2)//merge
  1630. {
  1631. if ((s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot merge different creatures stacks!"))
  1632. || (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)) && complain("Can't take troops from another player!")))
  1633. return false;
  1634. if (s1->slotEmpty(p1) || s2->slotEmpty(p2))
  1635. {
  1636. complain("Cannot merge empty stack!");
  1637. return false;
  1638. }
  1639. else if (notRemovable(sl1.army))
  1640. return false;
  1641. moveStack(sl1, sl2);
  1642. }
  1643. else if (what==3) //split
  1644. {
  1645. const int countToMove = val - s2->getStackCount(p2);
  1646. const int countLeftOnSrc = s1->getStackCount(p1) - countToMove;
  1647. if ( (s1->tempOwner != player && countLeftOnSrc < s1->getStackCount(p1))
  1648. || (s2->tempOwner != player && val < s2->getStackCount(p2)))
  1649. {
  1650. complain("Can't move troops of another player!");
  1651. return false;
  1652. }
  1653. //general conditions checking
  1654. if ((!vstd::contains(S1.stacks,p1) && complain(complainNoCreatures))
  1655. || (val<1 && complain(complainNoCreatures)) )
  1656. {
  1657. return false;
  1658. }
  1659. if (vstd::contains(S2.stacks,p2)) //dest. slot not free - it must be "rebalancing"...
  1660. {
  1661. int total = s1->getStackCount(p1) + s2->getStackCount(p2);
  1662. if ((total < val && complain("Cannot split that stack, not enough creatures!"))
  1663. || (s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot rebalance different creatures stacks!"))
  1664. )
  1665. {
  1666. return false;
  1667. }
  1668. if (notRemovable(sl1.army))
  1669. {
  1670. if (s1->getStackCount(p1) > countLeftOnSrc)
  1671. return false;
  1672. }
  1673. else if (notRemovable(sl2.army))
  1674. {
  1675. if (s2->getStackCount(p1) < countLeftOnSrc)
  1676. return false;
  1677. }
  1678. moveStack(sl1, sl2, countToMove);
  1679. //S2.slots[p2]->count = val;
  1680. //S1.slots[p1]->count = total - val;
  1681. }
  1682. else //split one stack to the two
  1683. {
  1684. if (s1->getStackCount(p1) < val)//not enough creatures
  1685. {
  1686. complain(complainNotEnoughCreatures);
  1687. return false;
  1688. }
  1689. if (notRemovable(sl1.army))
  1690. return false;
  1691. moveStack(sl1, sl2, val);
  1692. }
  1693. }
  1694. return true;
  1695. }
  1696. bool CGameHandler::hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const
  1697. {
  1698. return connections.count(player) && connections.at(player).count(c);
  1699. }
  1700. bool CGameHandler::hasBothPlayersAtSameConnection(PlayerColor left, PlayerColor right) const
  1701. {
  1702. return connections.count(left) && connections.count(right) && connections.at(left) == connections.at(right);
  1703. }
  1704. bool CGameHandler::disbandCreature(ObjectInstanceID id, SlotID pos)
  1705. {
  1706. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id));
  1707. if (!vstd::contains(s1->stacks,pos))
  1708. {
  1709. complain("Illegal call to disbandCreature - no such stack in army!");
  1710. return false;
  1711. }
  1712. eraseStack(StackLocation(s1, pos));
  1713. return true;
  1714. }
  1715. bool CGameHandler::buildStructure(ObjectInstanceID tid, BuildingID requestedID, bool force)
  1716. {
  1717. const CGTownInstance * t = getTown(tid);
  1718. if(!t)
  1719. COMPLAIN_RETF("No such town (ID=%s)!", tid);
  1720. if(!t->getTown()->buildings.count(requestedID))
  1721. COMPLAIN_RETF("Town of faction %s does not have info about building ID=%s!", t->getFaction()->getNameTranslated() % requestedID);
  1722. if(t->hasBuilt(requestedID))
  1723. COMPLAIN_RETF("Building %s is already built in %s", t->getTown()->buildings.at(requestedID)->getNameTranslated() % t->getNameTranslated());
  1724. const CBuilding * requestedBuilding = t->getTown()->buildings.at(requestedID);
  1725. //Vector with future list of built building and buildings in auto-mode that are not yet built.
  1726. std::vector<const CBuilding*> remainingAutoBuildings;
  1727. std::set<BuildingID> buildingsThatWillBe;
  1728. //Check validity of request
  1729. if(!force)
  1730. {
  1731. switch(requestedBuilding->mode)
  1732. {
  1733. case CBuilding::BUILD_NORMAL :
  1734. if (canBuildStructure(t, requestedID) != EBuildingState::ALLOWED)
  1735. COMPLAIN_RET("Cannot build that building!");
  1736. break;
  1737. case CBuilding::BUILD_AUTO :
  1738. case CBuilding::BUILD_SPECIAL:
  1739. COMPLAIN_RET("This building can not be constructed normally!");
  1740. case CBuilding::BUILD_GRAIL :
  1741. if(requestedBuilding->mode == CBuilding::BUILD_GRAIL) //needs grail
  1742. {
  1743. if(!t->visitingHero || !t->visitingHero->hasArt(ArtifactID::GRAIL))
  1744. COMPLAIN_RET("Cannot build this without grail!")
  1745. else
  1746. removeArtifact(ArtifactLocation(t->visitingHero->id, t->visitingHero->getArtPos(ArtifactID::GRAIL, false)));
  1747. }
  1748. break;
  1749. }
  1750. }
  1751. //Performs stuff that has to be done before new building is built
  1752. auto processBeforeBuiltStructure = [t, this](const BuildingID buildingID)
  1753. {
  1754. if(buildingID >= BuildingID::DWELL_FIRST) //dwelling
  1755. {
  1756. int level = BuildingID::getLevelFromDwelling(buildingID);
  1757. int upgradeNumber = BuildingID::getUpgradedFromDwelling(buildingID);
  1758. if(upgradeNumber >= t->getTown()->creatures.at(level).size())
  1759. {
  1760. complain(boost::str(boost::format("Error encountered when building dwelling (bid=%s):"
  1761. "no creature found (upgrade number %d, level %d!")
  1762. % buildingID % upgradeNumber % level));
  1763. return;
  1764. }
  1765. const CCreature * crea = t->getTown()->creatures.at(level).at(upgradeNumber).toCreature();
  1766. SetAvailableCreatures ssi;
  1767. ssi.tid = t->id;
  1768. ssi.creatures = t->creatures;
  1769. if (ssi.creatures[level].second.empty()) // first creature in a dwelling
  1770. ssi.creatures[level].first = crea->getGrowth();
  1771. ssi.creatures[level].second.push_back(crea->getId());
  1772. sendAndApply(ssi);
  1773. }
  1774. if(t->getTown()->buildings.at(buildingID)->subId == BuildingSubID::PORTAL_OF_SUMMONING)
  1775. {
  1776. setPortalDwelling(t);
  1777. }
  1778. };
  1779. //Performs stuff that has to be done after new building is built
  1780. auto processAfterBuiltStructure = [t, this](const BuildingID buildingID)
  1781. {
  1782. auto isMageGuild = (buildingID <= BuildingID::MAGES_GUILD_5 && buildingID >= BuildingID::MAGES_GUILD_1);
  1783. auto isLibrary = isMageGuild ? false
  1784. : t->getTown()->buildings.at(buildingID)->subId == BuildingSubID::EBuildingSubID::LIBRARY;
  1785. if(isMageGuild || isLibrary || (t->getFactionID() == ETownType::CONFLUX && buildingID == BuildingID::GRAIL))
  1786. {
  1787. if(t->visitingHero)
  1788. giveSpells(t,t->visitingHero);
  1789. if(t->garrisonHero)
  1790. giveSpells(t,t->garrisonHero);
  1791. }
  1792. };
  1793. //Checks if all requirements will be met with expected building list "buildingsThatWillBe"
  1794. auto areRequirementsFulfilled = [&](const BuildingID & buildID)
  1795. {
  1796. return buildingsThatWillBe.count(buildID);
  1797. };
  1798. //Init the vectors
  1799. for(auto & build : t->getTown()->buildings)
  1800. {
  1801. if(t->hasBuilt(build.first))
  1802. {
  1803. buildingsThatWillBe.insert(build.first);
  1804. }
  1805. else
  1806. {
  1807. if(build.second->mode == CBuilding::BUILD_AUTO) //not built auto building
  1808. remainingAutoBuildings.push_back(build.second);
  1809. }
  1810. }
  1811. //Prepare structure (list of building ids will be filled later)
  1812. NewStructures ns;
  1813. ns.tid = tid;
  1814. ns.built = force ? t->built : (t->built+1);
  1815. std::queue<const CBuilding*> buildingsToAdd;
  1816. buildingsToAdd.push(requestedBuilding);
  1817. while(!buildingsToAdd.empty())
  1818. {
  1819. auto b = buildingsToAdd.front();
  1820. buildingsToAdd.pop();
  1821. ns.bid.insert(b->bid);
  1822. buildingsThatWillBe.insert(b->bid);
  1823. remainingAutoBuildings -= b;
  1824. for(auto autoBuilding : remainingAutoBuildings)
  1825. {
  1826. auto actualRequirements = t->genBuildingRequirements(autoBuilding->bid);
  1827. if(actualRequirements.test(areRequirementsFulfilled))
  1828. buildingsToAdd.push(autoBuilding);
  1829. }
  1830. }
  1831. // 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.
  1832. for(auto builtID : ns.bid)
  1833. processBeforeBuiltStructure(builtID);
  1834. //Take cost
  1835. if(!force)
  1836. {
  1837. giveResources(t->tempOwner, -requestedBuilding->resources);
  1838. gs->statistic.accumulatedValues[t->tempOwner].spentResourcesForBuildings += requestedBuilding->resources;
  1839. }
  1840. //We know what has been built, apply changes. Do this as final step to properly update town window
  1841. sendAndApply(ns);
  1842. //Other post-built events. To some logic like giving spells to work gamestate changes for new building must be already in place!
  1843. for(auto builtID : ns.bid)
  1844. processAfterBuiltStructure(builtID);
  1845. // now when everything is built - reveal tiles for lookout tower
  1846. changeFogOfWar(t->getSightCenter(), t->getSightRadius(), t->getOwner(), ETileVisibility::REVEALED);
  1847. if (!force)
  1848. {
  1849. //garrison hero first - consistent with original H3 Mana Vortex and Battle Scholar Academy levelup windows order
  1850. std::vector<const CGHeroInstance *> visitors;
  1851. if (t->garrisonHero)
  1852. visitors.push_back(t->garrisonHero);
  1853. if (t->visitingHero)
  1854. visitors.push_back(t->visitingHero);
  1855. if (!visitors.empty())
  1856. visitCastleObjects(t, visitors);
  1857. }
  1858. checkVictoryLossConditionsForPlayer(t->tempOwner);
  1859. return true;
  1860. }
  1861. bool CGameHandler::visitTownBuilding(ObjectInstanceID tid, BuildingID bid)
  1862. {
  1863. const CGTownInstance * t = getTown(tid);
  1864. if(!t->hasBuilt(bid))
  1865. return false;
  1866. auto subID = t->getTown()->buildings.at(bid)->subId;
  1867. if(subID == BuildingSubID::EBuildingSubID::BANK)
  1868. {
  1869. TResources res;
  1870. res[EGameResID::GOLD] = 2500;
  1871. giveResources(t->getOwner(), res);
  1872. setObjPropertyValue(t->id, ObjProperty::BONUS_VALUE_SECOND, 2500);
  1873. return true;
  1874. }
  1875. if (t->rewardableBuildings.count(bid) && t->visitingHero && t->getTown()->buildings.at(bid)->manualHeroVisit)
  1876. {
  1877. std::vector<BuildingID> buildingsToVisit;
  1878. std::vector<const CGHeroInstance*> visitors;
  1879. buildingsToVisit.push_back(bid);
  1880. visitors.push_back(t->visitingHero);
  1881. auto visitQuery = std::make_shared<TownBuildingVisitQuery>(this, t, visitors, buildingsToVisit);
  1882. queries->addQuery(visitQuery);
  1883. return true;
  1884. }
  1885. return true;
  1886. }
  1887. bool CGameHandler::razeStructure (ObjectInstanceID tid, BuildingID bid)
  1888. {
  1889. ///incomplete, simply erases target building
  1890. const CGTownInstance * t = getTown(tid);
  1891. if(!t->hasBuilt(bid))
  1892. return false;
  1893. RazeStructures rs;
  1894. rs.tid = tid;
  1895. rs.bid.insert(bid);
  1896. rs.destroyed = t->destroyed + 1;
  1897. sendAndApply(rs);
  1898. //TODO: Remove dwellers
  1899. // if (t->subID == 4 && bid == 17) //Veil of Darkness
  1900. // {
  1901. // RemoveBonus rb(RemoveBonus::TOWN);
  1902. // rb.whoID = t->id;
  1903. // rb.source = BonusSource::TOWN_STRUCTURE;
  1904. // rb.id = 17;
  1905. // sendAndApply(rb);
  1906. // }
  1907. return true;
  1908. }
  1909. bool CGameHandler::spellResearch(ObjectInstanceID tid, SpellID spellAtSlot, bool accepted)
  1910. {
  1911. CGTownInstance *t = gs->getTown(tid);
  1912. if(!getSettings().getBoolean(EGameSettings::TOWNS_SPELL_RESEARCH) && complain("Spell research not allowed!"))
  1913. return false;
  1914. if (!t->spellResearchAllowed && complain("Spell research not allowed in this town!"))
  1915. return false;
  1916. int level = -1;
  1917. for(int i = 0; i < t->spells.size(); i++)
  1918. if(vstd::find_pos(t->spells[i], spellAtSlot) != -1)
  1919. level = i;
  1920. if(level == -1 && complain("Spell for replacement not found!"))
  1921. return false;
  1922. auto spells = t->spells.at(level);
  1923. bool researchLimitExceeded = t->spellResearchCounterDay >= getSettings().getValue(EGameSettings::TOWNS_SPELL_RESEARCH_PER_DAY).Vector()[level].Float();
  1924. if(researchLimitExceeded && complain("Already researched today!"))
  1925. return false;
  1926. if(!accepted)
  1927. {
  1928. auto it = spells.begin() + t->spellsAtLevel(level, false);
  1929. std::rotate(it, it + 1, spells.end()); // move to end
  1930. setResearchedSpells(t, level, spells, accepted);
  1931. return true;
  1932. }
  1933. auto costBase = TResources(getSettings().getValue(EGameSettings::TOWNS_SPELL_RESEARCH_COST).Vector()[level]);
  1934. auto costExponent = getSettings().getValue(EGameSettings::TOWNS_SPELL_RESEARCH_COST_EXPONENT_PER_RESEARCH).Vector()[level].Float();
  1935. auto cost = costBase * std::pow(t->spellResearchAcceptedCounter + 1, costExponent);
  1936. if(!getPlayerState(t->getOwner())->resources.canAfford(cost) && complain("Spell replacement cannot be afforded!"))
  1937. return false;
  1938. giveResources(t->getOwner(), -cost);
  1939. std::swap(spells.at(t->spellsAtLevel(level, false)), spells.at(vstd::find_pos(spells, spellAtSlot)));
  1940. auto it = spells.begin() + t->spellsAtLevel(level, false);
  1941. std::rotate(it, it + 1, spells.end()); // move to end
  1942. setResearchedSpells(t, level, spells, accepted);
  1943. if(t->visitingHero)
  1944. giveSpells(t, t->visitingHero);
  1945. if(t->garrisonHero)
  1946. giveSpells(t, t->garrisonHero);
  1947. return true;
  1948. }
  1949. bool CGameHandler::recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dstid, CreatureID crid, ui32 cram, si32 fromLvl, PlayerColor player)
  1950. {
  1951. const CGDwelling * dwelling = dynamic_cast<const CGDwelling *>(getObj(objid));
  1952. const CGTownInstance * town = dynamic_cast<const CGTownInstance *>(getObj(objid));
  1953. const CArmedInstance * army = dynamic_cast<const CArmedInstance *>(getObj(dstid));
  1954. const CGHeroInstance * hero = dynamic_cast<const CGHeroInstance *>(getObj(dstid));
  1955. const CCreature * c = crid.toCreature();
  1956. const bool warMachine = c->warMachine != ArtifactID::NONE;
  1957. //TODO: check if hero is actually visiting object
  1958. COMPLAIN_RET_FALSE_IF(!dwelling || !army, "Cannot recruit: invalid object!");
  1959. COMPLAIN_RET_FALSE_IF(dwelling->getOwner() != player && dwelling->getOwner() != PlayerColor::UNFLAGGABLE, "Cannot recruit: dwelling not owned!");
  1960. if (town)
  1961. {
  1962. COMPLAIN_RET_FALSE_IF(town != army && !hero, "Cannot recruit: invalid destination!");
  1963. COMPLAIN_RET_FALSE_IF(hero != town->garrisonHero && hero != town->visitingHero, "Cannot recruit: can only recruit to town or hero in town!!");
  1964. }
  1965. else
  1966. {
  1967. COMPLAIN_RET_FALSE_IF(getVisitingHero(dwelling) != hero, "Cannot recruit: can only recruit by visiting hero!");
  1968. COMPLAIN_RET_FALSE_IF(!hero || hero->getOwner() != player, "Cannot recruit: can only recruit to owned hero!");
  1969. }
  1970. //verify
  1971. bool found = false;
  1972. int level = 0;
  1973. for (; level < dwelling->creatures.size(); level++) //iterate through all levels
  1974. {
  1975. if ((fromLvl != -1) && (level !=fromLvl))
  1976. continue;
  1977. const auto &cur = dwelling->creatures.at(level); //current level info <amount, list of cr. ids>
  1978. int i = 0;
  1979. for (; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  1980. if (cur.second.at(i) == crid)
  1981. break;
  1982. if (i < cur.second.size())
  1983. {
  1984. found = true;
  1985. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  1986. break;
  1987. }
  1988. }
  1989. SlotID slot = army->getSlotFor(crid);
  1990. if ((!found && complain("Cannot recruit: no such creatures!"))
  1991. || ((si32)cram > VLC->creh->objects.at(crid)->maxAmount(getPlayerState(army->tempOwner)->resources) && complain("Cannot recruit: lack of resources!"))
  1992. || (cram<=0 && complain("Cannot recruit: cram <= 0!"))
  1993. || (!slot.validSlot() && !warMachine && complain("Cannot recruit: no available slot!")))
  1994. {
  1995. return false;
  1996. }
  1997. //recruit
  1998. TResources cost = (c->getFullRecruitCost() * cram);
  1999. giveResources(army->tempOwner, -cost);
  2000. gs->statistic.accumulatedValues[army->tempOwner].spentResourcesForArmy += cost;
  2001. SetAvailableCreatures sac;
  2002. sac.tid = objid;
  2003. sac.creatures = dwelling->creatures;
  2004. sac.creatures[level].first -= cram;
  2005. sendAndApply(sac);
  2006. if (warMachine)
  2007. {
  2008. ArtifactID artId = c->warMachine;
  2009. const CArtifact * art = artId.toArtifact();
  2010. COMPLAIN_RET_FALSE_IF(!hero, "Only hero can buy war machines");
  2011. COMPLAIN_RET_FALSE_IF(artId == ArtifactID::CATAPULT, "Catapult cannot be recruited!");
  2012. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid war machine artifact");
  2013. return giveHeroNewArtifact(hero, artId, ArtifactPosition::FIRST_AVAILABLE);
  2014. }
  2015. else
  2016. {
  2017. addToSlot(StackLocation(army, slot), c, cram);
  2018. }
  2019. return true;
  2020. }
  2021. bool CGameHandler::upgradeCreature(ObjectInstanceID objid, SlotID pos, CreatureID upgID)
  2022. {
  2023. const CArmedInstance * obj = static_cast<const CArmedInstance *>(getObjInstance(objid));
  2024. if (!obj->hasStackAtSlot(pos))
  2025. {
  2026. COMPLAIN_RET("Cannot upgrade, no stack at slot " + std::to_string(pos));
  2027. }
  2028. UpgradeInfo ui;
  2029. fillUpgradeInfo(obj, pos, ui);
  2030. PlayerColor player = obj->tempOwner;
  2031. const PlayerState *p = getPlayerState(player);
  2032. int crQuantity = obj->stacks.at(pos)->count;
  2033. int newIDpos= vstd::find_pos(ui.newID, upgID);//get position of new id in UpgradeInfo
  2034. //check if upgrade is possible
  2035. if ((ui.oldID == CreatureID::NONE || newIDpos == -1) && complain("That upgrade is not possible!"))
  2036. {
  2037. return false;
  2038. }
  2039. TResources totalCost = ui.cost.at(newIDpos) * crQuantity;
  2040. //check if player has enough resources
  2041. if (!p->resources.canAfford(totalCost))
  2042. COMPLAIN_RET("Cannot upgrade, not enough resources!");
  2043. //take resources
  2044. giveResources(player, -totalCost);
  2045. gs->statistic.accumulatedValues[player].spentResourcesForArmy += totalCost;
  2046. //upgrade creature
  2047. changeStackType(StackLocation(obj, pos), upgID.toCreature());
  2048. return true;
  2049. }
  2050. bool CGameHandler::changeStackType(const StackLocation &sl, const CCreature *c)
  2051. {
  2052. if (!sl.army->hasStackAtSlot(sl.slot))
  2053. COMPLAIN_RET("Cannot find a stack to change type");
  2054. SetStackType sst;
  2055. sst.army = sl.army->id;
  2056. sst.slot = sl.slot;
  2057. sst.type = c->getId();
  2058. sendAndApply(sst);
  2059. return true;
  2060. }
  2061. void CGameHandler::moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging)
  2062. {
  2063. assert(src->canBeMergedWith(*dst, allowMerging));
  2064. while(src->stacksCount())//while there are unmoved creatures
  2065. {
  2066. auto i = src->Slots().begin(); //iterator to stack to move
  2067. StackLocation sl(src, i->first); //location of stack to move
  2068. SlotID pos = dst->getSlotFor(i->second->getCreature());
  2069. if (!pos.validSlot())
  2070. {
  2071. //try to merge two other stacks to make place
  2072. std::pair<SlotID, SlotID> toMerge;
  2073. if (dst->mergeableStacks(toMerge, i->first) && allowMerging)
  2074. {
  2075. moveStack(StackLocation(dst, toMerge.first), StackLocation(dst, toMerge.second)); //merge toMerge.first into toMerge.second
  2076. assert(!dst->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  2077. moveStack(sl, StackLocation(dst, toMerge.first)); //move stack to freed slot
  2078. }
  2079. else
  2080. {
  2081. complain("Unexpected failure during an attempt to move army from " + src->nodeName() + " to " + dst->nodeName() + "!");
  2082. return;
  2083. }
  2084. }
  2085. else
  2086. {
  2087. moveStack(sl, StackLocation(dst, pos));
  2088. }
  2089. }
  2090. }
  2091. bool CGameHandler::swapGarrisonOnSiege(ObjectInstanceID tid)
  2092. {
  2093. const CGTownInstance * town = getTown(tid);
  2094. if(!town->garrisonHero == !town->visitingHero)
  2095. return false;
  2096. SetHeroesInTown intown;
  2097. intown.tid = tid;
  2098. if(town->garrisonHero) //garrison -> vising
  2099. {
  2100. intown.garrison = ObjectInstanceID();
  2101. intown.visiting = town->garrisonHero->id;
  2102. }
  2103. else //visiting -> garrison
  2104. {
  2105. if(town->armedGarrison())
  2106. town->mergeGarrisonOnSiege();
  2107. intown.visiting = ObjectInstanceID();
  2108. intown.garrison = town->visitingHero->id;
  2109. }
  2110. sendAndApply(intown);
  2111. return true;
  2112. }
  2113. bool CGameHandler::garrisonSwap(ObjectInstanceID tid)
  2114. {
  2115. const CGTownInstance * town = getTown(tid);
  2116. if (!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2117. {
  2118. if (!town->visitingHero->canBeMergedWith(*town))
  2119. {
  2120. complain("Cannot make garrison swap, not enough free slots!");
  2121. return false;
  2122. }
  2123. moveArmy(town, town->visitingHero, true);
  2124. SetHeroesInTown intown;
  2125. intown.tid = tid;
  2126. intown.visiting = ObjectInstanceID();
  2127. intown.garrison = town->visitingHero->id;
  2128. sendAndApply(intown);
  2129. return true;
  2130. }
  2131. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2132. {
  2133. int mapCap = getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP);
  2134. //check if moving hero out of town will break wandering heroes limit
  2135. if (getHeroCount(town->garrisonHero->tempOwner,false) >= mapCap)
  2136. {
  2137. complain("Cannot move hero out of the garrison, there are already " + std::to_string(mapCap) + " wandering heroes!");
  2138. return false;
  2139. }
  2140. SetHeroesInTown intown;
  2141. intown.tid = tid;
  2142. intown.garrison = ObjectInstanceID();
  2143. intown.visiting = town->garrisonHero->id;
  2144. sendAndApply(intown);
  2145. return true;
  2146. }
  2147. else if (!!town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2148. {
  2149. SetHeroesInTown intown;
  2150. intown.tid = tid;
  2151. intown.garrison = town->visitingHero->id;
  2152. intown.visiting = town->garrisonHero->id;
  2153. sendAndApply(intown);
  2154. return true;
  2155. }
  2156. else
  2157. {
  2158. complain("Cannot swap garrison hero!");
  2159. return false;
  2160. }
  2161. }
  2162. // With the amount of changes done to the function, it's more like transferArtifacts.
  2163. // 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.
  2164. bool CGameHandler::moveArtifact(const PlayerColor & player, const ArtifactLocation & src, const ArtifactLocation & dst)
  2165. {
  2166. const auto srcArtSet = getArtSet(src);
  2167. const auto dstArtSet = getArtSet(dst);
  2168. assert(srcArtSet);
  2169. assert(dstArtSet);
  2170. // Make sure exchange is even possible between the two heroes.
  2171. if(!isAllowedExchange(src.artHolder, dst.artHolder))
  2172. COMPLAIN_RET("That heroes cannot make any exchange!");
  2173. COMPLAIN_RET_FALSE_IF(!ArtifactUtils::checkIfSlotValid(*srcArtSet, src.slot), "moveArtifact: wrong artifact source slot");
  2174. const auto srcArtifact = srcArtSet->getArt(src.slot);
  2175. auto dstSlot = dst.slot;
  2176. if(dstSlot == ArtifactPosition::FIRST_AVAILABLE)
  2177. dstSlot = ArtifactUtils::getArtAnyPosition(dstArtSet, srcArtifact->getTypeId());
  2178. if(!ArtifactUtils::checkIfSlotValid(*dstArtSet, dstSlot))
  2179. return true;
  2180. const auto dstArtifact = dstArtSet->getArt(dstSlot);
  2181. const bool isDstSlotOccupied = dstArtSet->bearerType() == ArtBearer::ALTAR ? false : dstArtifact != nullptr;
  2182. const bool isDstSlotBackpack = dstArtSet->bearerType() == ArtBearer::HERO ? ArtifactUtils::isSlotBackpack(dstSlot) : false;
  2183. if(srcArtifact == nullptr)
  2184. COMPLAIN_RET("No artifact to move!");
  2185. if(isDstSlotOccupied && getOwner(src.artHolder) != getOwner(dst.artHolder) && !isDstSlotBackpack)
  2186. COMPLAIN_RET("Can't touch artifact on hero of another player!");
  2187. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2188. // Moving to the backpack is always allowed.
  2189. if((!srcArtifact || !isDstSlotBackpack) && !srcArtifact->canBePutAt(dstArtSet, dstSlot, true))
  2190. COMPLAIN_RET("Cannot move artifact!");
  2191. auto srcSlotInfo = srcArtSet->getSlot(src.slot);
  2192. auto dstSlotInfo = dstArtSet->getSlot(dstSlot);
  2193. if((srcSlotInfo && srcSlotInfo->locked) || (dstSlotInfo && dstSlotInfo->locked))
  2194. COMPLAIN_RET("Cannot move artifact locks.");
  2195. if(isDstSlotBackpack && srcArtifact->getType()->isBig())
  2196. COMPLAIN_RET("Cannot put big artifacts in backpack!");
  2197. if(src.slot == ArtifactPosition::MACH4 || dstSlot == ArtifactPosition::MACH4)
  2198. COMPLAIN_RET("Cannot move catapult!");
  2199. if(isDstSlotBackpack && !ArtifactUtils::isBackpackFreeSlots(dstArtSet))
  2200. COMPLAIN_RET("Backpack is full!");
  2201. dstSlot = std::min(dstSlot, ArtifactPosition(ArtifactPosition::BACKPACK_START + dstArtSet->artifactsInBackpack.size()));
  2202. if(src.slot == dstSlot && src.artHolder == dst.artHolder)
  2203. COMPLAIN_RET("Won't move artifact: Dest same as source!");
  2204. BulkMoveArtifacts ma(player, src.artHolder, dst.artHolder, false);
  2205. ma.srcCreature = src.creature;
  2206. ma.dstCreature = dst.creature;
  2207. // Check if dst slot is occupied
  2208. if(!isDstSlotBackpack && isDstSlotOccupied)
  2209. {
  2210. // Previous artifact must be swapped
  2211. COMPLAIN_RET_FALSE_IF(!dstArtifact->canBePutAt(srcArtSet, src.slot, true), "Cannot swap artifacts!");
  2212. ma.artsPack1.push_back(BulkMoveArtifacts::LinkedSlots(dstSlot, src.slot));
  2213. }
  2214. auto hero = getHero(dst.artHolder);
  2215. if(ArtifactUtils::checkSpellbookIsNeeded(hero, srcArtifact->getTypeId(), dstSlot))
  2216. giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
  2217. ma.artsPack0.push_back(BulkMoveArtifacts::LinkedSlots(src.slot, dstSlot));
  2218. if(src.artHolder != dst.artHolder && !isDstSlotBackpack)
  2219. ma.artsPack0.back().askAssemble = true;
  2220. sendAndApply(ma);
  2221. return true;
  2222. }
  2223. bool CGameHandler::bulkMoveArtifacts(const PlayerColor & player, ObjectInstanceID srcId, ObjectInstanceID dstId, bool swap, bool equipped, bool backpack)
  2224. {
  2225. // Make sure exchange is even possible between the two heroes.
  2226. if(!isAllowedExchange(srcId, dstId))
  2227. COMPLAIN_RET("That heroes cannot make any exchange!");
  2228. auto psrcSet = getArtSet(srcId);
  2229. auto pdstSet = getArtSet(dstId);
  2230. if((!psrcSet) || (!pdstSet))
  2231. COMPLAIN_RET("bulkMoveArtifacts: wrong hero's ID");
  2232. BulkMoveArtifacts ma(player, srcId, dstId, swap);
  2233. auto & slotsSrcDst = ma.artsPack0;
  2234. auto & slotsDstSrc = ma.artsPack1;
  2235. // Temporary fitting set for artifacts. Used to select available slots before sending data.
  2236. CArtifactFittingSet artFittingSet(pdstSet->bearerType());
  2237. auto moveArtifact = [this, &artFittingSet, dstId](const CArtifactInstance * artifact,
  2238. ArtifactPosition srcSlot, std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  2239. {
  2240. assert(artifact);
  2241. auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, artifact->getTypeId());
  2242. if(dstSlot != ArtifactPosition::PRE_FIRST)
  2243. {
  2244. artFittingSet.putArtifact(dstSlot, static_cast<ConstTransitivePtr<CArtifactInstance>>(artifact));
  2245. slots.push_back(BulkMoveArtifacts::LinkedSlots(srcSlot, dstSlot));
  2246. // TODO Shouldn't be here. Possibly in callback after equipping the artifact
  2247. if(auto dstHero = getHero(dstId))
  2248. {
  2249. if(ArtifactUtils::checkSpellbookIsNeeded(dstHero, artifact->getTypeId(), dstSlot))
  2250. giveHeroNewArtifact(dstHero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
  2251. }
  2252. }
  2253. };
  2254. if(swap)
  2255. {
  2256. auto moveArtsWorn = [moveArtifact](const CArtifactSet * srcArtSet, std::vector<BulkMoveArtifacts::LinkedSlots> & slots)
  2257. {
  2258. for(auto & artifact : srcArtSet->artifactsWorn)
  2259. {
  2260. if(ArtifactUtils::isArtRemovable(artifact))
  2261. moveArtifact(artifact.second.getArt(), artifact.first, slots);
  2262. }
  2263. };
  2264. auto moveArtsInBackpack = [](const CArtifactSet * artSet,
  2265. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  2266. {
  2267. for(auto & slotInfo : artSet->artifactsInBackpack)
  2268. {
  2269. auto slot = artSet->getArtPos(slotInfo.artifact);
  2270. slots.push_back(BulkMoveArtifacts::LinkedSlots(slot, slot));
  2271. }
  2272. };
  2273. if(equipped)
  2274. {
  2275. // Move over artifacts that are worn srcHero -> dstHero
  2276. moveArtsWorn(psrcSet, slotsSrcDst);
  2277. artFittingSet.artifactsWorn.clear();
  2278. // Move over artifacts that are worn dstHero -> srcHero
  2279. moveArtsWorn(pdstSet, slotsDstSrc);
  2280. }
  2281. if(backpack)
  2282. {
  2283. // Move over artifacts that are in backpack srcHero -> dstHero
  2284. moveArtsInBackpack(psrcSet, slotsSrcDst);
  2285. // Move over artifacts that are in backpack dstHero -> srcHero
  2286. moveArtsInBackpack(pdstSet, slotsDstSrc);
  2287. }
  2288. }
  2289. else
  2290. {
  2291. artFittingSet.artifactsInBackpack = pdstSet->artifactsInBackpack;
  2292. artFittingSet.artifactsWorn = pdstSet->artifactsWorn;
  2293. if(equipped)
  2294. {
  2295. // Move over artifacts that are worn
  2296. for(auto & artInfo : psrcSet->artifactsWorn)
  2297. {
  2298. if(ArtifactUtils::isArtRemovable(artInfo))
  2299. {
  2300. moveArtifact(psrcSet->getArt(artInfo.first), artInfo.first, slotsSrcDst);
  2301. }
  2302. }
  2303. }
  2304. if(backpack)
  2305. {
  2306. // Move over artifacts that are in backpack
  2307. for(auto & slotInfo : psrcSet->artifactsInBackpack)
  2308. {
  2309. moveArtifact(psrcSet->getArt(psrcSet->getArtPos(slotInfo.artifact)),
  2310. psrcSet->getArtPos(slotInfo.artifact), slotsSrcDst);
  2311. }
  2312. }
  2313. }
  2314. sendAndApply(ma);
  2315. return true;
  2316. }
  2317. bool CGameHandler::manageBackpackArtifacts(const PlayerColor & player, const ObjectInstanceID heroID, const ManageBackpackArtifacts::ManageCmd & sortType)
  2318. {
  2319. const auto artSet = getArtSet(heroID);
  2320. COMPLAIN_RET_FALSE_IF(artSet == nullptr, "manageBackpackArtifacts: wrong hero's ID");
  2321. BulkMoveArtifacts bma(player, heroID, heroID, false);
  2322. const auto makeSortBackpackRequest = [artSet, &bma](const std::function<int32_t(const ArtSlotInfo&)> & getSortId)
  2323. {
  2324. std::map<int32_t, std::vector<BulkMoveArtifacts::LinkedSlots>> packsSorted;
  2325. ArtifactPosition backpackSlot = ArtifactPosition::BACKPACK_START;
  2326. for(const auto & backpackSlotInfo : artSet->artifactsInBackpack)
  2327. packsSorted.try_emplace(getSortId(backpackSlotInfo)).first->second.emplace_back(backpackSlot++, ArtifactPosition::PRE_FIRST);
  2328. for(auto & [sortId, pack] : packsSorted)
  2329. {
  2330. // Each pack of artifacts is also sorted by ArtifactID. Scrolls by SpellID
  2331. std::sort(pack.begin(), pack.end(), [artSet](const auto & slots0, const auto & slots1) -> bool
  2332. {
  2333. const auto art0 = artSet->getArt(slots0.srcPos);
  2334. const auto art1 = artSet->getArt(slots1.srcPos);
  2335. if(art0->isScroll() && art1->isScroll())
  2336. return art0->getScrollSpellID() > art1->getScrollSpellID();
  2337. return art0->getTypeId().num > art1->getTypeId().num;
  2338. });
  2339. bma.artsPack0.insert(bma.artsPack0.end(), pack.begin(), pack.end());
  2340. }
  2341. backpackSlot = ArtifactPosition::BACKPACK_START;
  2342. for(auto & slots : bma.artsPack0)
  2343. slots.dstPos = backpackSlot++;
  2344. };
  2345. if(sortType == ManageBackpackArtifacts::ManageCmd::SORT_BY_SLOT)
  2346. {
  2347. makeSortBackpackRequest([](const ArtSlotInfo & inf) -> int32_t
  2348. {
  2349. auto possibleSlots = inf.getArt()->getType()->getPossibleSlots();
  2350. if (possibleSlots.find(ArtBearer::CREATURE) != possibleSlots.end() && !possibleSlots.at(ArtBearer::CREATURE).empty())
  2351. {
  2352. return -2;
  2353. }
  2354. else if (possibleSlots.find(ArtBearer::COMMANDER) != possibleSlots.end() && !possibleSlots.at(ArtBearer::COMMANDER).empty())
  2355. {
  2356. return -1;
  2357. }
  2358. else if (possibleSlots.find(ArtBearer::HERO) != possibleSlots.end() && !possibleSlots.at(ArtBearer::HERO).empty())
  2359. {
  2360. return inf.getArt()->getType()->getPossibleSlots().at(ArtBearer::HERO).front().num;
  2361. }
  2362. else
  2363. {
  2364. // for grail
  2365. return -3;
  2366. }
  2367. });
  2368. }
  2369. else if(sortType == ManageBackpackArtifacts::ManageCmd::SORT_BY_COST)
  2370. {
  2371. makeSortBackpackRequest([](const ArtSlotInfo & inf) -> int32_t
  2372. {
  2373. return inf.getArt()->getType()->getPrice();
  2374. });
  2375. }
  2376. else if(sortType == ManageBackpackArtifacts::ManageCmd::SORT_BY_CLASS)
  2377. {
  2378. makeSortBackpackRequest([](const ArtSlotInfo & inf) -> int32_t
  2379. {
  2380. return inf.getArt()->getType()->aClass;
  2381. });
  2382. }
  2383. else
  2384. {
  2385. const auto backpackEnd = ArtifactPosition(ArtifactPosition::BACKPACK_START + artSet->artifactsInBackpack.size() - 1);
  2386. if(backpackEnd > ArtifactPosition::BACKPACK_START)
  2387. {
  2388. if(sortType == ManageBackpackArtifacts::ManageCmd::SCROLL_LEFT)
  2389. bma.artsPack0.emplace_back(backpackEnd, ArtifactPosition::BACKPACK_START);
  2390. else
  2391. bma.artsPack0.emplace_back(ArtifactPosition::BACKPACK_START, backpackEnd);
  2392. }
  2393. }
  2394. sendAndApply(bma);
  2395. return true;
  2396. }
  2397. bool CGameHandler::saveArtifactsCostume(const PlayerColor & player, const ObjectInstanceID heroID, uint32_t costumeIdx)
  2398. {
  2399. auto artSet = getArtSet(heroID);
  2400. COMPLAIN_RET_FALSE_IF(artSet == nullptr, "saveArtifactsCostume: wrong hero's ID");
  2401. ChangeArtifactsCostume costume(player, costumeIdx);
  2402. for(const auto & slot : ArtifactUtils::commonWornSlots())
  2403. {
  2404. if(const auto slotInfo = artSet->getSlot(slot); slotInfo != nullptr && !slotInfo->locked)
  2405. costume.costumeSet.emplace(slot, slotInfo->getArt()->getTypeId());
  2406. }
  2407. sendAndApply(costume);
  2408. return true;
  2409. }
  2410. bool CGameHandler::switchArtifactsCostume(const PlayerColor & player, const ObjectInstanceID heroID, uint32_t costumeIdx)
  2411. {
  2412. const auto artSet = getArtSet(heroID);
  2413. COMPLAIN_RET_FALSE_IF(artSet == nullptr, "switchArtifactsCostume: wrong hero's ID");
  2414. const auto playerState = getPlayerState(player);
  2415. COMPLAIN_RET_FALSE_IF(playerState == nullptr, "switchArtifactsCostume: wrong player");
  2416. if(auto costume = playerState->costumesArtifacts.find(costumeIdx); costume != playerState->costumesArtifacts.end())
  2417. {
  2418. CArtifactFittingSet artFittingSet(*artSet);
  2419. BulkMoveArtifacts bma(player, heroID, heroID, false);
  2420. auto costumeArtMap = costume->second;
  2421. auto estimateBackpackSize = artSet->artifactsInBackpack.size();
  2422. // First, find those artifacts that are already in place
  2423. for(const auto & slot : ArtifactUtils::commonWornSlots())
  2424. {
  2425. if(const auto * slotInfo = artFittingSet.getSlot(slot); slotInfo != nullptr && !slotInfo->locked)
  2426. if(const auto artPos = costumeArtMap.find(slot); artPos != costumeArtMap.end() && artPos->second == slotInfo->getArt()->getTypeId())
  2427. {
  2428. costumeArtMap.erase(artPos);
  2429. artFittingSet.removeArtifact(slot);
  2430. }
  2431. }
  2432. // Second, find the necessary artifacts for the costume
  2433. for(const auto & artPos : costumeArtMap)
  2434. {
  2435. if(const auto slot = artFittingSet.getArtPos(artPos.second, false, false); slot != ArtifactPosition::PRE_FIRST)
  2436. {
  2437. bma.artsPack0.emplace_back(BulkMoveArtifacts::LinkedSlots
  2438. {
  2439. artSet->getArtPos(artFittingSet.getArt(slot)),
  2440. artPos.first
  2441. });
  2442. artFittingSet.removeArtifact(slot);
  2443. if(ArtifactUtils::isSlotBackpack(slot))
  2444. estimateBackpackSize--;
  2445. }
  2446. }
  2447. // Third, put unnecessary artifacts into backpack
  2448. for(const auto & slot : ArtifactUtils::commonWornSlots())
  2449. if(artFittingSet.getArt(slot))
  2450. {
  2451. bma.artsPack0.emplace_back(BulkMoveArtifacts::LinkedSlots{slot, ArtifactPosition::BACKPACK_START});
  2452. estimateBackpackSize++;
  2453. }
  2454. const auto backpackCap = getSettings().getInteger(EGameSettings::HEROES_BACKPACK_CAP);
  2455. if((backpackCap < 0 || estimateBackpackSize <= backpackCap) && !bma.artsPack0.empty())
  2456. sendAndApply(bma);
  2457. }
  2458. return true;
  2459. }
  2460. /**
  2461. * Assembles or disassembles a combination artifact.
  2462. * @param heroID ID of hero holding the artifact(s).
  2463. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  2464. * @param assemble True for assembly operation, false for disassembly.
  2465. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  2466. * artifact to assemble to. Otherwise it's not used.
  2467. */
  2468. bool CGameHandler::assembleArtifacts(ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  2469. {
  2470. const CGHeroInstance * hero = getHero(heroID);
  2471. const CArtifactInstance * destArtifact = hero->getArt(artifactSlot);
  2472. if(!destArtifact)
  2473. COMPLAIN_RET("assembleArtifacts: there is no such artifact instance!");
  2474. const auto dstLoc = ArtifactLocation(hero->id, artifactSlot);
  2475. if(assemble)
  2476. {
  2477. const CArtifact * combinedArt = assembleTo.toArtifact();
  2478. if(!combinedArt->isCombined())
  2479. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to assemble is not a combined artifacts!");
  2480. if(!vstd::contains(ArtifactUtils::assemblyPossibilities(hero, destArtifact->getTypeId()), combinedArt))
  2481. {
  2482. COMPLAIN_RET("assembleArtifacts: It's impossible to assemble requested artifact!");
  2483. }
  2484. if(!destArtifact->canBePutAt(hero, artifactSlot, true)
  2485. && !destArtifact->canBePutAt(hero, ArtifactPosition::BACKPACK_START, true))
  2486. {
  2487. COMPLAIN_RET("assembleArtifacts: It's impossible to give the artholder requested artifact!");
  2488. }
  2489. if(ArtifactUtils::checkSpellbookIsNeeded(hero, assembleTo, artifactSlot))
  2490. giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
  2491. AssembledArtifact aa;
  2492. aa.al = dstLoc;
  2493. aa.artId = assembleTo;
  2494. sendAndApply(aa);
  2495. }
  2496. else
  2497. {
  2498. if(!destArtifact->isCombined())
  2499. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble is not a combined artifact!");
  2500. if(!destArtifact->hasParts())
  2501. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble is fused combined artifact!");
  2502. if(ArtifactUtils::isSlotBackpack(artifactSlot)
  2503. && !ArtifactUtils::isBackpackFreeSlots(hero, destArtifact->getType()->getConstituents().size() - 1))
  2504. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble but backpack is full!");
  2505. DisassembledArtifact da;
  2506. da.al = dstLoc;
  2507. sendAndApply(da);
  2508. }
  2509. return true;
  2510. }
  2511. bool CGameHandler::eraseArtifactByClient(const ArtifactLocation & al)
  2512. {
  2513. const auto * hero = getHero(al.artHolder);
  2514. if(hero == nullptr)
  2515. COMPLAIN_RET("eraseArtifactByClient: wrong hero's ID");
  2516. const auto * art = hero->getArt(al.slot);
  2517. if(art == nullptr)
  2518. COMPLAIN_RET("Cannot remove artifact!");
  2519. if(art->canBePutAt(hero) || al.slot != ArtifactPosition::TRANSITION_POS)
  2520. COMPLAIN_RET("Illegal artifact removal request");
  2521. removeArtifact(al);
  2522. return true;
  2523. }
  2524. bool CGameHandler::buyArtifact(ObjectInstanceID hid, ArtifactID aid)
  2525. {
  2526. const CGHeroInstance * hero = getHero(hid);
  2527. COMPLAIN_RET_FALSE_IF(nullptr == hero, "Invalid hero index");
  2528. const CGTownInstance * town = hero->visitedTown;
  2529. COMPLAIN_RET_FALSE_IF(nullptr == town, "Hero not in town");
  2530. if (aid==ArtifactID::SPELLBOOK)
  2531. {
  2532. if ((!town->hasBuilt(BuildingID::MAGES_GUILD_1) && complain("Cannot buy a spellbook, no mage guild in the town!"))
  2533. || (getResource(hero->getOwner(), EGameResID::GOLD) < GameConstants::SPELLBOOK_GOLD_COST && complain("Cannot buy a spellbook, not enough gold!"))
  2534. || (hero->getArt(ArtifactPosition::SPELLBOOK) && complain("Cannot buy a spellbook, hero already has a one!"))
  2535. )
  2536. return false;
  2537. giveResource(hero->getOwner(),EGameResID::GOLD,-GameConstants::SPELLBOOK_GOLD_COST);
  2538. giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
  2539. assert(hero->getArt(ArtifactPosition::SPELLBOOK));
  2540. giveSpells(town,hero);
  2541. return true;
  2542. }
  2543. else
  2544. {
  2545. const CArtifact * art = aid.toArtifact();
  2546. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid artifact index to buy");
  2547. COMPLAIN_RET_FALSE_IF(art->getWarMachine() == CreatureID::NONE, "War machine artifact required");
  2548. COMPLAIN_RET_FALSE_IF(hero->hasArt(aid),"Hero already has this machine!");
  2549. const int price = art->getPrice();
  2550. COMPLAIN_RET_FALSE_IF(getPlayerState(hero->getOwner())->resources[EGameResID::GOLD] < price, "Not enough gold!");
  2551. if(town->isWarMachineAvailable(aid))
  2552. {
  2553. bool hasFreeSlot = false;
  2554. for(auto slot : art->getPossibleSlots().at(ArtBearer::HERO))
  2555. if (hero->getArt(slot) == nullptr)
  2556. hasFreeSlot = true;
  2557. if (!hasFreeSlot)
  2558. {
  2559. auto slot = art->getPossibleSlots().at(ArtBearer::HERO).front();
  2560. removeArtifact(ArtifactLocation(hero->id, slot));
  2561. }
  2562. giveResource(hero->getOwner(),EGameResID::GOLD,-price);
  2563. return giveHeroNewArtifact(hero, aid, ArtifactPosition::FIRST_AVAILABLE);
  2564. }
  2565. else
  2566. COMPLAIN_RET("This machine is unavailable here!");
  2567. }
  2568. }
  2569. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, GameResID rid, ArtifactID aid)
  2570. {
  2571. if(!h)
  2572. COMPLAIN_RET("Only hero can buy artifacts!");
  2573. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_ARTIFACT), aid))
  2574. COMPLAIN_RET("That artifact is unavailable!");
  2575. int b1;
  2576. int b2;
  2577. m->getOffer(rid, aid, b1, b2, EMarketMode::RESOURCE_ARTIFACT);
  2578. if (getResource(h->tempOwner, rid) < b1)
  2579. COMPLAIN_RET("You can't afford to buy this artifact!");
  2580. giveResource(h->tempOwner, rid, -b1);
  2581. SetAvailableArtifacts saa;
  2582. if(dynamic_cast<const CGTownInstance *>(m))
  2583. {
  2584. saa.id = ObjectInstanceID::NONE;
  2585. saa.arts = gs->map->townMerchantArtifacts;
  2586. }
  2587. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m)) //black market
  2588. {
  2589. saa.id = bm->id;
  2590. saa.arts = bm->artifacts;
  2591. }
  2592. else
  2593. COMPLAIN_RET("Wrong marktet...");
  2594. bool found = false;
  2595. for (ArtifactID & art : saa.arts)
  2596. {
  2597. if (art == aid)
  2598. {
  2599. art = ArtifactID();
  2600. found = true;
  2601. break;
  2602. }
  2603. }
  2604. if (!found)
  2605. COMPLAIN_RET("Cannot find selected artifact on the list");
  2606. sendAndApply(saa);
  2607. giveHeroNewArtifact(h, aid, ArtifactPosition::FIRST_AVAILABLE);
  2608. return true;
  2609. }
  2610. bool CGameHandler::sellArtifact(const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid)
  2611. {
  2612. COMPLAIN_RET_FALSE_IF((!h), "Only hero can sell artifacts!");
  2613. const CArtifactInstance *art = h->getArtByInstanceId(aid);
  2614. COMPLAIN_RET_FALSE_IF((!art), "There is no artifact to sell!");
  2615. COMPLAIN_RET_FALSE_IF((!art->getType()->isTradable()), "Cannot sell a war machine or spellbook!");
  2616. int resVal = 0;
  2617. int dump = 1;
  2618. m->getOffer(art->getType()->getId(), rid, dump, resVal, EMarketMode::ARTIFACT_RESOURCE);
  2619. removeArtifact(ArtifactLocation(h->id, h->getArtPos(art)));
  2620. giveResource(h->tempOwner, rid, resVal);
  2621. return true;
  2622. }
  2623. bool CGameHandler::buySecSkill(const IMarket *m, const CGHeroInstance *h, SecondarySkill skill)
  2624. {
  2625. if (!h)
  2626. COMPLAIN_RET("You need hero to buy a skill!");
  2627. if (h->getSecSkillLevel(SecondarySkill(skill)))
  2628. COMPLAIN_RET("Hero already know this skill");
  2629. if (!h->canLearnSkill())
  2630. COMPLAIN_RET("Hero can't learn any more skills");
  2631. if (!h->canLearnSkill(skill))
  2632. COMPLAIN_RET("The hero can't learn this skill!");
  2633. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_SKILL), skill))
  2634. COMPLAIN_RET("That skill is unavailable!");
  2635. if (getResource(h->tempOwner, EGameResID::GOLD) < GameConstants::SKILL_GOLD_COST)//TODO: remove hardcoded resource\summ?
  2636. COMPLAIN_RET("You can't afford to buy this skill");
  2637. giveResource(h->tempOwner, EGameResID::GOLD, -GameConstants::SKILL_GOLD_COST);
  2638. changeSecSkill(h, skill, 1, true);
  2639. return true;
  2640. }
  2641. bool CGameHandler::tradeResources(const IMarket *market, ui32 amountToSell, PlayerColor player, GameResID toSell, GameResID toBuy)
  2642. {
  2643. TResourceCap haveToSell = getPlayerState(player)->resources[toSell];
  2644. vstd::amin(amountToSell, haveToSell); //can't trade more resources than have
  2645. int b1; //base quantities for trade
  2646. int b2;
  2647. market->getOffer(toSell, toBuy, b1, b2, EMarketMode::RESOURCE_RESOURCE);
  2648. int amountToBoy = amountToSell / b1; //how many base quantities we trade
  2649. if (amountToSell % b1 != 0) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2650. {
  2651. COMPLAIN_RET("Invalid deal, not all offered units of resource were used.");
  2652. }
  2653. giveResource(player, toSell, -b1 * amountToBoy);
  2654. giveResource(player, toBuy, b2 * amountToBoy);
  2655. gs->statistic.accumulatedValues[player].tradeVolume[toSell] += -b1 * amountToBoy;
  2656. gs->statistic.accumulatedValues[player].tradeVolume[toBuy] += b2 * amountToBoy;
  2657. return true;
  2658. }
  2659. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID)
  2660. {
  2661. if(!hero)
  2662. COMPLAIN_RET("Only hero can sell creatures!");
  2663. if (!vstd::contains(hero->Slots(), slot))
  2664. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  2665. const CStackInstance &s = hero->getStack(slot);
  2666. if (s.count < (TQuantity)count //can't sell more creatures than have
  2667. || (hero->stacksCount() == 1 && hero->needsLastStack() && s.count == count)) //can't sell last stack
  2668. {
  2669. COMPLAIN_RET("Not enough creatures in army!");
  2670. }
  2671. int b1; //base quantities for trade
  2672. int b2;
  2673. market->getOffer(s.getId(), resourceID, b1, b2, EMarketMode::CREATURE_RESOURCE);
  2674. int units = count / b1; //how many base quantities we trade
  2675. if (count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2676. {
  2677. //TODO: complain?
  2678. assert(0);
  2679. }
  2680. changeStackCount(StackLocation(hero, slot), -(TQuantity)count);
  2681. giveResource(hero->tempOwner, resourceID, b2 * units);
  2682. return true;
  2683. }
  2684. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot)
  2685. {
  2686. const CArmedInstance *army = nullptr;
  2687. if (hero)
  2688. army = hero;
  2689. else
  2690. army = dynamic_cast<const CGTownInstance *>(market);
  2691. if (!army)
  2692. COMPLAIN_RET("Incorrect call to transform in undead!");
  2693. if (!army->hasStackAtSlot(slot))
  2694. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  2695. const CStackInstance &s = army->getStack(slot);
  2696. //resulting creature - bone dragons or skeletons
  2697. CreatureID resCreature = CreatureID::SKELETON;
  2698. if ((s.hasBonusOfType(BonusType::DRAGON_NATURE)
  2699. && !(s.hasBonusOfType(BonusType::UNDEAD)))
  2700. || (s.getCreatureID() == CreatureID::HYDRA)
  2701. || (s.getCreatureID() == CreatureID::CHAOS_HYDRA))
  2702. resCreature = CreatureID::BONE_DRAGON;
  2703. changeStackType(StackLocation(army, slot), resCreature.toCreature());
  2704. return true;
  2705. }
  2706. bool CGameHandler::sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2)
  2707. {
  2708. const PlayerState *p2 = getPlayerState(r2, false);
  2709. if (!p2 || p2->status != EPlayerStatus::INGAME)
  2710. {
  2711. complain("Dest player must be in game!");
  2712. return false;
  2713. }
  2714. TResourceCap curRes1 = getPlayerState(player)->resources[r1];
  2715. vstd::amin(val, curRes1);
  2716. giveResource(player, r1, -(int)val);
  2717. giveResource(r2, r1, val);
  2718. return true;
  2719. }
  2720. bool CGameHandler::setFormation(ObjectInstanceID hid, EArmyFormation formation)
  2721. {
  2722. const CGHeroInstance *h = getHero(hid);
  2723. if (!h)
  2724. {
  2725. logGlobal->error("Hero doesn't exist!");
  2726. return false;
  2727. }
  2728. ChangeFormation cf;
  2729. cf.hid = hid;
  2730. cf.formation = formation;
  2731. sendAndApply(cf);
  2732. return true;
  2733. }
  2734. bool CGameHandler::queryReply(QueryID qid, std::optional<int32_t> answer, PlayerColor player)
  2735. {
  2736. logGlobal->trace("Player %s attempts answering query %d with answer:", player, qid);
  2737. if (answer)
  2738. logGlobal->trace("%d", *answer);
  2739. auto topQuery = queries->topQuery(player);
  2740. COMPLAIN_RET_FALSE_IF(!topQuery, "This player doesn't have any queries!");
  2741. if(topQuery->queryID != qid)
  2742. {
  2743. auto currentQuery = queries->getQuery(qid);
  2744. if(currentQuery != nullptr && currentQuery->endsByPlayerAnswer())
  2745. currentQuery->setReply(answer);
  2746. COMPLAIN_RET("This player top query has different ID!"); //topQuery->queryID != qid
  2747. }
  2748. COMPLAIN_RET_FALSE_IF(!topQuery->endsByPlayerAnswer(), "This query cannot be ended by player's answer!");
  2749. topQuery->setReply(answer);
  2750. queries->popQuery(topQuery);
  2751. return true;
  2752. }
  2753. bool CGameHandler::complain(const std::string &problem)
  2754. {
  2755. #ifndef ENABLE_GOLDMASTER
  2756. playerMessages->broadcastSystemMessage("Server encountered a problem: " + problem);
  2757. #endif
  2758. logGlobal->error(problem);
  2759. return true;
  2760. }
  2761. void CGameHandler::showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits)
  2762. {
  2763. //PlayerColor player = getOwner(hid);
  2764. auto upperArmy = dynamic_cast<const CArmedInstance*>(getObj(upobj));
  2765. auto lowerArmy = dynamic_cast<const CArmedInstance*>(getObj(hid));
  2766. assert(lowerArmy);
  2767. assert(upperArmy);
  2768. auto garrisonQuery = std::make_shared<CGarrisonDialogQuery>(this, upperArmy, lowerArmy);
  2769. queries->addQuery(garrisonQuery);
  2770. GarrisonDialog gd;
  2771. gd.hid = hid;
  2772. gd.objid = upobj;
  2773. gd.removableUnits = removableUnits;
  2774. gd.queryID = garrisonQuery->queryID;
  2775. sendAndApply(gd);
  2776. }
  2777. void CGameHandler::showObjectWindow(const CGObjectInstance * object, EOpenWindowMode window, const CGHeroInstance * visitor, bool addQuery)
  2778. {
  2779. OpenWindow pack;
  2780. pack.window = window;
  2781. pack.object = object->id;
  2782. pack.visitor = visitor->id;
  2783. if (addQuery)
  2784. {
  2785. auto windowQuery = std::make_shared<OpenWindowQuery>(this, visitor, window);
  2786. pack.queryID = windowQuery->queryID;
  2787. queries->addQuery(windowQuery);
  2788. }
  2789. sendAndApply(pack);
  2790. }
  2791. bool CGameHandler::isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2)
  2792. {
  2793. if (id1 == id2)
  2794. return true;
  2795. const CGObjectInstance *o1 = getObj(id1);
  2796. const CGObjectInstance *o2 = getObj(id2);
  2797. if (!o1 || !o2)
  2798. return true; //arranging stacks within an object should be always allowed
  2799. if (o1 && o2)
  2800. {
  2801. if (o1->ID == Obj::TOWN)
  2802. {
  2803. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  2804. if (t->visitingHero == o2 || t->garrisonHero == o2)
  2805. return true;
  2806. }
  2807. if (o2->ID == Obj::TOWN)
  2808. {
  2809. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  2810. if (t->visitingHero == o1 || t->garrisonHero == o1)
  2811. return true;
  2812. }
  2813. auto market = getMarket(id1);
  2814. if(market == nullptr)
  2815. market = getMarket(id2);
  2816. if(market)
  2817. return market->allowsTrade(EMarketMode::ARTIFACT_EXP);
  2818. if (o1->ID == Obj::HERO && o2->ID == Obj::HERO)
  2819. {
  2820. const CGHeroInstance *h1 = static_cast<const CGHeroInstance*>(o1);
  2821. const CGHeroInstance *h2 = static_cast<const CGHeroInstance*>(o2);
  2822. // two heroes in same town (garrisoned and visiting)
  2823. if (h1->visitedTown != nullptr && h2->visitedTown != nullptr && h1->visitedTown == h2->visitedTown)
  2824. return true;
  2825. }
  2826. //Ongoing garrison exchange - usually picking from top garison (from o1 to o2), but who knows
  2827. auto dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries->topQuery(o1->tempOwner));
  2828. if (!dialog)
  2829. {
  2830. dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries->topQuery(o2->tempOwner));
  2831. }
  2832. if (dialog)
  2833. {
  2834. auto topArmy = dialog->exchangingArmies.at(0);
  2835. auto bottomArmy = dialog->exchangingArmies.at(1);
  2836. if ((topArmy == o1 && bottomArmy == o2) || (bottomArmy == o1 && topArmy == o2))
  2837. return true;
  2838. }
  2839. }
  2840. return false;
  2841. }
  2842. void CGameHandler::objectVisited(const CGObjectInstance * obj, const CGHeroInstance * h)
  2843. {
  2844. using events::ObjectVisitStarted;
  2845. logGlobal->debug("%s visits %s (%d)", h->nodeName(), obj->getObjectName(), obj->ID);
  2846. if (getVisitingHero(obj) != nullptr)
  2847. {
  2848. logGlobal->error("Attempt to visit object that is being visited by another hero!");
  2849. throw std::runtime_error("Can not visit object that is being visited");
  2850. }
  2851. std::shared_ptr<MapObjectVisitQuery> visitQuery;
  2852. auto startVisit = [&](ObjectVisitStarted & event)
  2853. {
  2854. auto visitedObject = obj;
  2855. if(obj->ID == Obj::HERO)
  2856. {
  2857. auto visitedHero = static_cast<const CGHeroInstance *>(obj);
  2858. const auto visitedTown = visitedHero->visitedTown;
  2859. if(visitedTown)
  2860. {
  2861. const bool isEnemy = visitedHero->getOwner() != h->getOwner();
  2862. if(isEnemy && !visitedTown->isBattleOutsideTown(visitedHero))
  2863. visitedObject = visitedTown;
  2864. }
  2865. }
  2866. visitQuery = std::make_shared<MapObjectVisitQuery>(this, visitedObject, h);
  2867. queries->addQuery(visitQuery); //TODO real visit pos
  2868. HeroVisit hv;
  2869. hv.objId = obj->id;
  2870. hv.heroId = h->id;
  2871. hv.player = h->tempOwner;
  2872. hv.starting = true;
  2873. sendAndApply(hv);
  2874. obj->onHeroVisit(h);
  2875. };
  2876. ObjectVisitStarted::defaultExecute(serverEventBus.get(), startVisit, h->tempOwner, h->id, obj->id);
  2877. if(visitQuery)
  2878. queries->popIfTop(visitQuery); //visit ends here if no queries were created
  2879. }
  2880. void CGameHandler::objectVisitEnded(const CGHeroInstance *h, PlayerColor player)
  2881. {
  2882. using events::ObjectVisitEnded;
  2883. logGlobal->debug("%s visit ends.\n", h->nodeName());
  2884. auto endVisit = [&](ObjectVisitEnded & event)
  2885. {
  2886. HeroVisit hv;
  2887. hv.player = event.getPlayer();
  2888. hv.heroId = event.getHero();
  2889. hv.starting = false;
  2890. sendAndApply(hv);
  2891. };
  2892. //TODO: ObjectVisitEnded should also have id of visited object,
  2893. //but this requires object being deleted only by `removeAfterVisit()` but not `removeObject()`
  2894. ObjectVisitEnded::defaultExecute(serverEventBus.get(), endVisit, player, h->id);
  2895. }
  2896. bool CGameHandler::buildBoat(ObjectInstanceID objid, PlayerColor playerID)
  2897. {
  2898. const auto *obj = dynamic_cast<const IShipyard *>(getObj(objid));
  2899. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  2900. {
  2901. complain("Cannot build boat in this shipyard!");
  2902. return false;
  2903. }
  2904. TResources boatCost;
  2905. obj->getBoatCost(boatCost);
  2906. TResources available = getPlayerState(playerID)->resources;
  2907. if (!available.canAfford(boatCost))
  2908. {
  2909. complain("Not enough resources to build a boat!");
  2910. return false;
  2911. }
  2912. int3 tile = obj->bestLocation();
  2913. if (!gs->map->isInTheMap(tile))
  2914. {
  2915. complain("Cannot find appropriate tile for a boat!");
  2916. return false;
  2917. }
  2918. giveResources(playerID, -boatCost);
  2919. createBoat(tile, obj->getBoatType(), playerID);
  2920. return true;
  2921. }
  2922. void CGameHandler::checkVictoryLossConditions(const std::set<PlayerColor> & playerColors)
  2923. {
  2924. for (auto playerColor : playerColors)
  2925. {
  2926. if (getPlayerState(playerColor, false))
  2927. checkVictoryLossConditionsForPlayer(playerColor);
  2928. }
  2929. }
  2930. void CGameHandler::checkVictoryLossConditionsForAll()
  2931. {
  2932. std::set<PlayerColor> playerColors;
  2933. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  2934. {
  2935. playerColors.insert(PlayerColor(i));
  2936. }
  2937. checkVictoryLossConditions(playerColors);
  2938. }
  2939. void CGameHandler::checkVictoryLossConditionsForPlayer(PlayerColor player)
  2940. {
  2941. const PlayerState * p = getPlayerState(player);
  2942. if(!p || p->status != EPlayerStatus::INGAME) return;
  2943. auto victoryLossCheckResult = gs->checkForVictoryAndLoss(player);
  2944. if (victoryLossCheckResult.victory() || victoryLossCheckResult.loss())
  2945. {
  2946. InfoWindow iw;
  2947. getVictoryLossMessage(player, victoryLossCheckResult, iw);
  2948. sendAndApply(iw);
  2949. PlayerEndsGame peg;
  2950. peg.player = player;
  2951. peg.victoryLossCheckResult = victoryLossCheckResult;
  2952. peg.statistic = StatisticDataSet(gameState()->statistic);
  2953. addStatistics(peg.statistic); // add last turn befor win / loss
  2954. sendAndApply(peg);
  2955. turnOrder->onPlayerEndsGame(player);
  2956. if (victoryLossCheckResult.victory())
  2957. {
  2958. //one player won -> all enemies lost
  2959. for (auto i = gs->players.cbegin(); i!=gs->players.cend(); i++)
  2960. {
  2961. if (i->first != player && getPlayerState(i->first)->status == EPlayerStatus::INGAME)
  2962. {
  2963. peg.player = i->first;
  2964. peg.victoryLossCheckResult = getPlayerRelations(player, i->first) == PlayerRelations::ALLIES ?
  2965. victoryLossCheckResult : victoryLossCheckResult.invert(); // ally of winner
  2966. InfoWindow iw;
  2967. getVictoryLossMessage(player, peg.victoryLossCheckResult, iw);
  2968. iw.player = i->first;
  2969. sendAndApply(iw);
  2970. sendAndApply(peg);
  2971. }
  2972. }
  2973. if(p->human)
  2974. {
  2975. lobby->setState(EServerState::SHUTDOWN);
  2976. }
  2977. }
  2978. else
  2979. {
  2980. //copy heroes vector to avoid iterator invalidation as removal change PlayerState
  2981. auto hlp = p->getHeroes();
  2982. for (auto h : hlp) //eliminate heroes
  2983. {
  2984. if (h)
  2985. removeObject(h, player);
  2986. }
  2987. //player lost -> all his objects become unflagged (neutral)
  2988. for (auto obj : gs->map->objects) //unflag objs
  2989. {
  2990. if (obj.get() && obj->tempOwner == player)
  2991. setOwner(obj, PlayerColor::NEUTRAL);
  2992. }
  2993. //eliminating one player may cause victory of another:
  2994. std::set<PlayerColor> playerColors;
  2995. //do not copy player state (CBonusSystemNode) by value
  2996. for (auto &p : gs->players) //players may have different colors, iterate over players and not integers
  2997. {
  2998. if (p.first != player)
  2999. playerColors.insert(p.first);
  3000. }
  3001. //notify all players
  3002. for (auto pc : playerColors)
  3003. {
  3004. if (getPlayerState(pc)->status == EPlayerStatus::INGAME)
  3005. {
  3006. InfoWindow iw;
  3007. getVictoryLossMessage(player, victoryLossCheckResult.invert(), iw);
  3008. iw.player = pc;
  3009. sendAndApply(iw);
  3010. }
  3011. }
  3012. checkVictoryLossConditions(playerColors);
  3013. }
  3014. }
  3015. }
  3016. void CGameHandler::getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const
  3017. {
  3018. out.player = player;
  3019. out.text = victoryLossCheckResult.messageToSelf;
  3020. out.text.replaceName(player);
  3021. out.components.emplace_back(ComponentType::FLAG, player);
  3022. }
  3023. bool CGameHandler::dig(const CGHeroInstance *h)
  3024. {
  3025. if (h->diggingStatus() != EDiggingStatus::CAN_DIG) //checks for terrain and movement
  3026. COMPLAIN_RETF("Hero cannot dig (error code %d)!", static_cast<int>(h->diggingStatus()));
  3027. createHole(h->visitablePos(), h->getOwner());
  3028. //take MPs
  3029. SetMovePoints smp;
  3030. smp.hid = h->id;
  3031. smp.val = 0;
  3032. sendAndApply(smp);
  3033. InfoWindow iw;
  3034. iw.type = EInfoWindowMode::AUTO;
  3035. iw.player = h->tempOwner;
  3036. if (gs->map->grailPos == h->visitablePos())
  3037. {
  3038. ArtifactID grail = ArtifactID::GRAIL;
  3039. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the " ...
  3040. iw.text.appendName(grail); // ... " The Grail"
  3041. iw.soundID = soundBase::ULTIMATEARTIFACT;
  3042. giveHeroNewArtifact(h, grail, ArtifactPosition::FIRST_AVAILABLE); //give grail
  3043. sendAndApply(iw);
  3044. iw.soundID = soundBase::invalid;
  3045. iw.components.emplace_back(ComponentType::ARTIFACT, grail);
  3046. iw.text.clear();
  3047. iw.text.appendTextID(grail.toArtifact()->getDescriptionTextID());
  3048. sendAndApply(iw);
  3049. }
  3050. else
  3051. {
  3052. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  3053. iw.soundID = soundBase::Dig;
  3054. sendAndApply(iw);
  3055. }
  3056. return true;
  3057. }
  3058. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  3059. {
  3060. if (!t.visitableObjects.empty())
  3061. {
  3062. //to prevent self-visiting heroes on space press
  3063. if (t.visitableObjects.back() != h)
  3064. objectVisited(t.visitableObjects.back(), h);
  3065. else if (t.visitableObjects.size() > 1)
  3066. objectVisited(*(t.visitableObjects.end()-2),h);
  3067. }
  3068. }
  3069. bool CGameHandler::sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count)
  3070. {
  3071. if (!hero)
  3072. COMPLAIN_RET("You need hero to sacrifice creature!");
  3073. int expSum = 0;
  3074. auto finish = [this, &hero, &expSum]()
  3075. {
  3076. giveExperience(hero, hero->calculateXp(expSum));
  3077. };
  3078. for(int i = 0; i < slot.size(); ++i)
  3079. {
  3080. int oldCount = hero->getStackCount(slot[i]);
  3081. if(oldCount < (int)count[i])
  3082. {
  3083. finish();
  3084. COMPLAIN_RET("Not enough creatures to sacrifice!")
  3085. }
  3086. else if(oldCount == count[i] && hero->stacksCount() == 1 && hero->needsLastStack())
  3087. {
  3088. finish();
  3089. COMPLAIN_RET("Cannot sacrifice last creature!");
  3090. }
  3091. int crid = hero->getStack(slot[i]).getId();
  3092. changeStackCount(StackLocation(hero, slot[i]), -(TQuantity)count[i]);
  3093. int dump;
  3094. int exp;
  3095. market->getOffer(crid, 0, dump, exp, EMarketMode::CREATURE_EXP);
  3096. exp *= count[i];
  3097. expSum += exp;
  3098. }
  3099. finish();
  3100. return true;
  3101. }
  3102. bool CGameHandler::sacrificeArtifact(const IMarket * market, const CGHeroInstance * hero, const std::vector<ArtifactInstanceID> & arts)
  3103. {
  3104. if (!hero)
  3105. COMPLAIN_RET("You need hero to sacrifice artifact!");
  3106. if(hero->getAlignment() == EAlignment::EVIL)
  3107. COMPLAIN_RET("Evil hero can't sacrifice artifact!");
  3108. assert(market);
  3109. const auto artSet = market->getArtifactsStorage();
  3110. int expSum = 0;
  3111. std::vector<ArtifactPosition> artPack;
  3112. auto finish = [this, &hero, &expSum, &artPack, market]()
  3113. {
  3114. removeArtifact(market->getObjInstanceID(), artPack);
  3115. giveExperience(hero, hero->calculateXp(expSum));
  3116. };
  3117. for(const auto & artInstId : arts)
  3118. {
  3119. if(auto art = artSet->getArtByInstanceId(artInstId))
  3120. {
  3121. if(art->getType()->isTradable())
  3122. {
  3123. int dmp;
  3124. int expToGive;
  3125. market->getOffer(art->getTypeId(), 0, dmp, expToGive, EMarketMode::ARTIFACT_EXP);
  3126. expSum += expToGive;
  3127. artPack.push_back(artSet->getArtPos(art));
  3128. }
  3129. else
  3130. {
  3131. COMPLAIN_RET("Cannot sacrifice not tradable artifact!");
  3132. }
  3133. }
  3134. else
  3135. {
  3136. finish();
  3137. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  3138. }
  3139. }
  3140. finish();
  3141. return true;
  3142. }
  3143. bool CGameHandler::insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count)
  3144. {
  3145. if (sl.army->hasStackAtSlot(sl.slot))
  3146. COMPLAIN_RET("Slot is already taken!");
  3147. if (!sl.slot.validSlot())
  3148. COMPLAIN_RET("Cannot insert stack to that slot!");
  3149. InsertNewStack ins;
  3150. ins.army = sl.army->id;
  3151. ins.slot = sl.slot;
  3152. ins.type = c->getId();
  3153. ins.count = count;
  3154. sendAndApply(ins);
  3155. return true;
  3156. }
  3157. bool CGameHandler::eraseStack(const StackLocation &sl, bool forceRemoval)
  3158. {
  3159. if (!sl.army->hasStackAtSlot(sl.slot))
  3160. COMPLAIN_RET("Cannot find a stack to erase");
  3161. if (sl.army->stacksCount() == 1 //from the last stack
  3162. && sl.army->needsLastStack() //that must be left
  3163. && !forceRemoval) //ignore above conditions if we are forcing removal
  3164. {
  3165. COMPLAIN_RET("Cannot erase the last stack!");
  3166. }
  3167. EraseStack es;
  3168. es.army = sl.army->id;
  3169. es.slot = sl.slot;
  3170. sendAndApply(es);
  3171. return true;
  3172. }
  3173. bool CGameHandler::changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue)
  3174. {
  3175. TQuantity currentCount = sl.army->getStackCount(sl.slot);
  3176. if ((absoluteValue && count < 0)
  3177. || (!absoluteValue && -count > currentCount))
  3178. {
  3179. COMPLAIN_RET("Cannot take more stacks than present!");
  3180. }
  3181. if ((currentCount == -count && !absoluteValue)
  3182. || (!count && absoluteValue))
  3183. {
  3184. eraseStack(sl);
  3185. }
  3186. else
  3187. {
  3188. ChangeStackCount csc;
  3189. csc.army = sl.army->id;
  3190. csc.slot = sl.slot;
  3191. csc.count = count;
  3192. csc.absoluteValue = absoluteValue;
  3193. sendAndApply(csc);
  3194. }
  3195. return true;
  3196. }
  3197. bool CGameHandler::addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count)
  3198. {
  3199. const CCreature *slotC = sl.army->getCreature(sl.slot);
  3200. if (!slotC) //slot is empty
  3201. insertNewStack(sl, c, count);
  3202. else if (c == slotC)
  3203. changeStackCount(sl, count);
  3204. else
  3205. {
  3206. COMPLAIN_RET("Cannot add " + c->getNamePluralTranslated() + " to slot " + boost::lexical_cast<std::string>(sl.slot) + "!");
  3207. }
  3208. return true;
  3209. }
  3210. void CGameHandler::tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging)
  3211. {
  3212. if (removeObjWhenFinished)
  3213. removeAfterVisit(src);
  3214. if (!src->canBeMergedWith(*dst, allowMerging))
  3215. {
  3216. if (allowMerging) //do that, add all matching creatures.
  3217. {
  3218. bool cont = true;
  3219. while (cont)
  3220. {
  3221. for (auto i = src->stacks.begin(); i != src->stacks.end(); i++)//while there are unmoved creatures
  3222. {
  3223. SlotID pos = dst->getSlotFor(i->second->getCreature());
  3224. if (pos.validSlot())
  3225. {
  3226. moveStack(StackLocation(src, i->first), StackLocation(dst, pos));
  3227. cont = true;
  3228. break; //or iterator crashes
  3229. }
  3230. cont = false;
  3231. }
  3232. }
  3233. }
  3234. showGarrisonDialog(src->id, dst->id, true); //show garrison window and optionally remove ourselves from map when player ends
  3235. }
  3236. else //merge
  3237. {
  3238. moveArmy(src, dst, allowMerging);
  3239. }
  3240. }
  3241. bool CGameHandler::moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count)
  3242. {
  3243. if (!src.army->hasStackAtSlot(src.slot))
  3244. COMPLAIN_RET("No stack to move!");
  3245. if (dst.army->hasStackAtSlot(dst.slot) && dst.army->getCreature(dst.slot) != src.army->getCreature(src.slot))
  3246. COMPLAIN_RET("Cannot move: stack of different type at destination pos!");
  3247. if (!dst.slot.validSlot())
  3248. COMPLAIN_RET("Cannot move stack to that slot!");
  3249. if (count == -1)
  3250. {
  3251. count = src.army->getStackCount(src.slot);
  3252. }
  3253. if (src.army != dst.army //moving away
  3254. && count == src.army->getStackCount(src.slot) //all creatures
  3255. && src.army->stacksCount() == 1 //from the last stack
  3256. && src.army->needsLastStack()) //that must be left
  3257. {
  3258. COMPLAIN_RET("Cannot move away the last creature!");
  3259. }
  3260. RebalanceStacks rs;
  3261. rs.srcArmy = src.army->id;
  3262. rs.dstArmy = dst.army->id;
  3263. rs.srcSlot = src.slot;
  3264. rs.dstSlot = dst.slot;
  3265. rs.count = count;
  3266. sendAndApply(rs);
  3267. return true;
  3268. }
  3269. void CGameHandler::castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos)
  3270. {
  3271. if (!spellID.hasValue())
  3272. return;
  3273. AdventureSpellCastParameters p;
  3274. p.caster = caster;
  3275. p.pos = pos;
  3276. const CSpell * s = spellID.toSpell();
  3277. s->adventureCast(spellEnv, p);
  3278. }
  3279. bool CGameHandler::swapStacks(const StackLocation & sl1, const StackLocation & sl2)
  3280. {
  3281. if(!sl1.army->hasStackAtSlot(sl1.slot))
  3282. {
  3283. return moveStack(sl2, sl1);
  3284. }
  3285. else if(!sl2.army->hasStackAtSlot(sl2.slot))
  3286. {
  3287. return moveStack(sl1, sl2);
  3288. }
  3289. else
  3290. {
  3291. SwapStacks ss;
  3292. ss.srcArmy = sl1.army->id;
  3293. ss.dstArmy = sl2.army->id;
  3294. ss.srcSlot = sl1.slot;
  3295. ss.dstSlot = sl2.slot;
  3296. sendAndApply(ss);
  3297. return true;
  3298. }
  3299. }
  3300. bool CGameHandler::putArtifact(const ArtifactLocation & al, const ArtifactInstanceID & id, std::optional<bool> askAssemble)
  3301. {
  3302. const auto artInst = getArtInstance(id);
  3303. assert(artInst && artInst->getType());
  3304. ArtifactLocation dst(al.artHolder, ArtifactPosition::PRE_FIRST);
  3305. dst.creature = al.creature;
  3306. auto putTo = getArtSet(al);
  3307. assert(putTo);
  3308. if(al.slot == ArtifactPosition::FIRST_AVAILABLE)
  3309. {
  3310. dst.slot = ArtifactUtils::getArtAnyPosition(putTo, artInst->getTypeId());
  3311. }
  3312. else if(ArtifactUtils::isSlotBackpack(al.slot) && !al.creature.has_value())
  3313. {
  3314. dst.slot = ArtifactUtils::getArtBackpackPosition(putTo, artInst->getTypeId());
  3315. }
  3316. else
  3317. {
  3318. dst.slot = al.slot;
  3319. }
  3320. if(!askAssemble.has_value())
  3321. {
  3322. if(!dst.creature.has_value() && ArtifactUtils::isSlotEquipment(dst.slot))
  3323. askAssemble = true;
  3324. else
  3325. askAssemble = false;
  3326. }
  3327. if(artInst->canBePutAt(putTo, dst.slot))
  3328. {
  3329. PutArtifact pa(id, dst, askAssemble.value());
  3330. sendAndApply(pa);
  3331. return true;
  3332. }
  3333. else
  3334. {
  3335. return false;
  3336. }
  3337. }
  3338. bool CGameHandler::giveHeroNewArtifact(
  3339. const CGHeroInstance * h, const CArtifact * artType, const SpellID & spellId, const ArtifactPosition & pos)
  3340. {
  3341. assert(artType);
  3342. NewArtifact na;
  3343. na.artHolder = h->id;
  3344. na.artId = artType->getId();
  3345. na.spellId = spellId;
  3346. na.pos = pos;
  3347. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  3348. {
  3349. na.pos = ArtifactUtils::getArtAnyPosition(h, artType->getId());
  3350. if(!artType->canBePutAt(h, na.pos))
  3351. COMPLAIN_RET("Cannot put artifact in that slot!");
  3352. }
  3353. else if(ArtifactUtils::isSlotBackpack(pos))
  3354. {
  3355. if(!artType->canBePutAt(h, ArtifactUtils::getArtBackpackPosition(h, artType->getId())))
  3356. COMPLAIN_RET("Cannot put artifact in that slot!");
  3357. }
  3358. else
  3359. {
  3360. COMPLAIN_RET_FALSE_IF(!artType->canBePutAt(h, pos, false), "Cannot put artifact in that slot!");
  3361. }
  3362. sendAndApply(na);
  3363. return true;
  3364. }
  3365. bool CGameHandler::giveHeroNewArtifact(const CGHeroInstance * h, const ArtifactID & artId, const ArtifactPosition & pos)
  3366. {
  3367. return giveHeroNewArtifact(h, artId.toArtifact(), SpellID::NONE, pos);
  3368. }
  3369. bool CGameHandler::giveHeroNewScroll(const CGHeroInstance * h, const SpellID & spellId, const ArtifactPosition & pos)
  3370. {
  3371. return giveHeroNewArtifact(h, ArtifactID(ArtifactID::SPELL_SCROLL).toArtifact(), spellId, pos);
  3372. }
  3373. void CGameHandler::spawnWanderingMonsters(CreatureID creatureID)
  3374. {
  3375. std::vector<int3>::iterator tile;
  3376. std::vector<int3> tiles;
  3377. getFreeTiles(tiles);
  3378. ui32 amount = (ui32)tiles.size() / 200; //Chance is 0.5% for each tile
  3379. RandomGeneratorUtil::randomShuffle(tiles, getRandomGenerator());
  3380. logGlobal->trace("Spawning wandering monsters. Found %d free tiles. Creature type: %d", tiles.size(), creatureID.num);
  3381. const CCreature *cre = creatureID.toCreature();
  3382. for (int i = 0; i < (int)amount; ++i)
  3383. {
  3384. tile = tiles.begin();
  3385. logGlobal->trace("\tSpawning monster at %s", tile->toString());
  3386. {
  3387. auto count = cre->getRandomAmount(std::rand);
  3388. createWanderingMonster(*tile, creatureID);
  3389. auto monsterId = getTopObj(*tile)->id;
  3390. setObjPropertyValue(monsterId, ObjProperty::MONSTER_COUNT, count);
  3391. setObjPropertyValue(monsterId, ObjProperty::MONSTER_POWER, (si64)1000*count);
  3392. }
  3393. tiles.erase(tile); //not use it again
  3394. }
  3395. }
  3396. void CGameHandler::synchronizeArtifactHandlerLists()
  3397. {
  3398. UpdateArtHandlerLists uahl;
  3399. uahl.allocatedArtifacts = gs->allocatedArtifacts;
  3400. sendAndApply(uahl);
  3401. }
  3402. bool CGameHandler::isValidObject(const CGObjectInstance *obj) const
  3403. {
  3404. return vstd::contains(gs->map->objects, obj);
  3405. }
  3406. bool CGameHandler::isBlockedByQueries(const CPackForServer *pack, PlayerColor player)
  3407. {
  3408. if (dynamic_cast<const PlayerMessage *>(pack) != nullptr)
  3409. return false;
  3410. if (dynamic_cast<const SaveLocalState *>(pack) != nullptr)
  3411. return false;
  3412. auto query = queries->topQuery(player);
  3413. if (query && query->blocksPack(pack))
  3414. {
  3415. complain(boost::str(boost::format(
  3416. "\r\n| Player \"%s\" has to answer queries before attempting any further actions.\r\n| Top Query: \"%s\"\r\n")
  3417. % boost::to_upper_copy<std::string>(player.toString())
  3418. % query->toString()
  3419. ));
  3420. return true;
  3421. }
  3422. return false;
  3423. }
  3424. void CGameHandler::removeAfterVisit(const CGObjectInstance *object)
  3425. {
  3426. //If the object is being visited, there must be a matching query
  3427. for (const auto &query : queries->allQueries())
  3428. {
  3429. if (auto someVistQuery = std::dynamic_pointer_cast<MapObjectVisitQuery>(query))
  3430. {
  3431. if (someVistQuery->visitedObject == object)
  3432. {
  3433. someVistQuery->removeObjectAfterVisit = true;
  3434. return;
  3435. }
  3436. }
  3437. }
  3438. //If we haven't returned so far, there is no query and no visit, call was wrong
  3439. assert("This function needs to be called during the object visit!");
  3440. }
  3441. void CGameHandler::changeFogOfWar(int3 center, ui32 radius, PlayerColor player, ETileVisibility mode)
  3442. {
  3443. std::unordered_set<int3> tiles;
  3444. if (mode == ETileVisibility::HIDDEN)
  3445. {
  3446. getTilesInRange(tiles, center, radius, ETileVisibility::REVEALED, player);
  3447. }
  3448. else
  3449. {
  3450. getTilesInRange(tiles, center, radius, ETileVisibility::HIDDEN, player);
  3451. }
  3452. changeFogOfWar(tiles, player, mode);
  3453. }
  3454. void CGameHandler::changeFogOfWar(const std::unordered_set<int3> &tiles, PlayerColor player, ETileVisibility mode)
  3455. {
  3456. if (tiles.empty())
  3457. return;
  3458. FoWChange fow;
  3459. fow.tiles = tiles;
  3460. fow.player = player;
  3461. fow.mode = mode;
  3462. if (mode == ETileVisibility::HIDDEN)
  3463. {
  3464. // do not hide tiles observed by owned objects. May lead to disastrous AI problems
  3465. // FIXME: this leads to a bug - shroud of darkness from Necropolis does can not override Skyship from Tower
  3466. std::unordered_set<int3> observedTiles;
  3467. auto p = getPlayerState(player);
  3468. for (auto obj : p->getOwnedObjects())
  3469. getTilesInRange(observedTiles, obj->getSightCenter(), obj->getSightRadius(), ETileVisibility::REVEALED, obj->getOwner());
  3470. for (auto tile : observedTiles)
  3471. vstd::erase_if_present (fow.tiles, tile);
  3472. if (fow.tiles.empty())
  3473. return;
  3474. }
  3475. sendAndApply(fow);
  3476. }
  3477. const CGHeroInstance * CGameHandler::getVisitingHero(const CGObjectInstance *obj)
  3478. {
  3479. assert(obj);
  3480. for(const auto & query : queries->allQueries())
  3481. {
  3482. auto visit = std::dynamic_pointer_cast<const VisitQuery>(query);
  3483. if (visit && visit->visitedObject == obj)
  3484. return visit->visitingHero;
  3485. }
  3486. return nullptr;
  3487. }
  3488. const CGObjectInstance * CGameHandler::getVisitingObject(const CGHeroInstance *hero)
  3489. {
  3490. assert(hero);
  3491. for(const auto & query : queries->allQueries())
  3492. {
  3493. auto visit = std::dynamic_pointer_cast<const VisitQuery>(query);
  3494. if (visit && visit->visitingHero == hero)
  3495. return visit->visitedObject;
  3496. }
  3497. return nullptr;
  3498. }
  3499. bool CGameHandler::isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero)
  3500. {
  3501. assert(obj);
  3502. assert(hero);
  3503. assert(getVisitingHero(obj) == hero);
  3504. // Check top query of targeted player:
  3505. // If top query is NOT visit to targeted object then we assume that
  3506. // visitation query is covered by other query that must be answered first
  3507. if (auto topQuery = queries->topQuery(hero->getOwner()))
  3508. if (auto visit = std::dynamic_pointer_cast<const VisitQuery>(topQuery))
  3509. return !(visit->visitedObject == obj && visit->visitingHero == hero);
  3510. return true;
  3511. }
  3512. void CGameHandler::setObjPropertyValue(ObjectInstanceID objid, ObjProperty prop, int32_t value)
  3513. {
  3514. SetObjectProperty sob;
  3515. sob.id = objid;
  3516. sob.what = prop;
  3517. sob.identifier = NumericID(value);
  3518. sendAndApply(sob);
  3519. }
  3520. void CGameHandler::setObjPropertyID(ObjectInstanceID objid, ObjProperty prop, ObjPropertyID identifier)
  3521. {
  3522. SetObjectProperty sob;
  3523. sob.id = objid;
  3524. sob.what = prop;
  3525. sob.identifier = identifier;
  3526. sendAndApply(sob);
  3527. }
  3528. void CGameHandler::setBankObjectConfiguration(ObjectInstanceID objid, const BankConfig & configuration)
  3529. {
  3530. SetBankConfiguration srb;
  3531. srb.objectID = objid;
  3532. srb.configuration = configuration;
  3533. sendAndApply(srb);
  3534. }
  3535. void CGameHandler::setRewardableObjectConfiguration(ObjectInstanceID objid, const Rewardable::Configuration & configuration)
  3536. {
  3537. SetRewardableConfiguration srb;
  3538. srb.objectID = objid;
  3539. srb.configuration = configuration;
  3540. sendAndApply(srb);
  3541. }
  3542. void CGameHandler::setRewardableObjectConfiguration(ObjectInstanceID townInstanceID, BuildingID buildingID, const Rewardable::Configuration & configuration)
  3543. {
  3544. SetRewardableConfiguration srb;
  3545. srb.objectID = townInstanceID;
  3546. srb.buildingID = buildingID;
  3547. srb.configuration = configuration;
  3548. sendAndApply(srb);
  3549. }
  3550. void CGameHandler::showInfoDialog(InfoWindow * iw)
  3551. {
  3552. sendAndApply(*iw);
  3553. }
  3554. vstd::RNG & CGameHandler::getRandomGenerator()
  3555. {
  3556. return *randomNumberGenerator;
  3557. }
  3558. #if SCRIPTING_ENABLED
  3559. scripting::Pool * CGameHandler::getGlobalContextPool() const
  3560. {
  3561. return serverScripts.get();
  3562. }
  3563. //scripting::Pool * CGameHandler::getContextPool() const
  3564. //{
  3565. // return serverScripts.get();
  3566. //}
  3567. #endif
  3568. CGObjectInstance * CGameHandler::createNewObject(const int3 & visitablePosition, MapObjectID objectID, MapObjectSubID subID)
  3569. {
  3570. TerrainId terrainType = ETerrainId::NONE;
  3571. if (!gs->isInTheMap(visitablePosition))
  3572. throw std::runtime_error("Attempt to create object outside map at " + visitablePosition.toString());
  3573. const TerrainTile & t = gs->map->getTile(visitablePosition);
  3574. terrainType = t.getTerrainID();
  3575. auto handler = VLC->objtypeh->getHandlerFor(objectID, subID);
  3576. CGObjectInstance * o = handler->create(gs->callback, nullptr);
  3577. handler->configureObject(o, getRandomGenerator());
  3578. assert(o->ID == objectID);
  3579. assert(!handler->getTemplates(terrainType).empty());
  3580. if (handler->getTemplates().empty())
  3581. throw std::runtime_error("Attempt to create object (" + std::to_string(objectID) + ", " + std::to_string(subID.getNum()) + ") with no templates!");
  3582. if (!handler->getTemplates(terrainType).empty())
  3583. o->appearance = handler->getTemplates(terrainType).front();
  3584. else
  3585. o->appearance = handler->getTemplates().front();
  3586. if (o->isVisitable())
  3587. o->setAnchorPos(visitablePosition + o->getVisitableOffset());
  3588. else
  3589. o->setAnchorPos(visitablePosition);
  3590. return o;
  3591. }
  3592. void CGameHandler::createWanderingMonster(const int3 & visitablePosition, CreatureID creature)
  3593. {
  3594. auto createdObject = createNewObject(visitablePosition, Obj::MONSTER, creature);
  3595. auto * cre = dynamic_cast<CGCreature *>(createdObject);
  3596. assert(cre);
  3597. cre->notGrowingTeam = cre->neverFlees = false;
  3598. cre->character = 2;
  3599. cre->gainedArtifact = ArtifactID::NONE;
  3600. cre->identifier = -1;
  3601. cre->addToSlot(SlotID(0), new CStackInstance(creature, -1)); //add placeholder stack
  3602. newObject(createdObject, PlayerColor::NEUTRAL);
  3603. }
  3604. void CGameHandler::createBoat(const int3 & visitablePosition, BoatId type, PlayerColor initiator)
  3605. {
  3606. auto createdObject = createNewObject(visitablePosition, Obj::BOAT, type);
  3607. newObject(createdObject, initiator);
  3608. }
  3609. void CGameHandler::createHole(const int3 & visitablePosition, PlayerColor initiator)
  3610. {
  3611. auto createdObject = createNewObject(visitablePosition, Obj::HOLE, 0);
  3612. newObject(createdObject, initiator);
  3613. }
  3614. void CGameHandler::newObject(CGObjectInstance * object, PlayerColor initiator)
  3615. {
  3616. object->initObj(gs->getRandomGenerator());
  3617. NewObject no;
  3618. no.newObject = object;
  3619. no.initiator = initiator;
  3620. sendAndApply(no);
  3621. }
  3622. void CGameHandler::startBattle(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, const BattleLayout & layout, const CGTownInstance *town)
  3623. {
  3624. battles->startBattle(army1, army2, tile, hero1, hero2, layout, town);
  3625. }
  3626. void CGameHandler::startBattle(const CArmedInstance *army1, const CArmedInstance *army2 )
  3627. {
  3628. battles->startBattle(army1, army2);
  3629. }