CGameHandler.cpp 127 KB

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