CGameHandler.cpp 133 KB

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