CGameHandler.cpp 133 KB

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