CGameHandler.cpp 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311
  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. if(!isAllowedExchange(srcArmy, destArmy))
  1443. COMPLAIN_RET("That heroes cannot make any exchange!");
  1444. const auto * armySrc = dynamic_cast<const CArmedInstance*>(gameInfo().getObjInstance(srcArmy));
  1445. const auto * armyDest = dynamic_cast<const CArmedInstance*>(gameInfo().getObjInstance(destArmy));
  1446. if(!vstd::contains(armySrc->stacks, srcSlot) && complain(complainNoCreatures))
  1447. return false;
  1448. auto freeSlots = armyDest->getFreeSlots();
  1449. bool allTroopsMoved = true;
  1450. BulkRebalanceStacks bulkRS;
  1451. for (const auto & slot : armySrc->Slots())
  1452. {
  1453. auto targetSlot = armyDest->getSlotFor(slot.second->getCreature());
  1454. if (armyDest->slotEmpty(targetSlot))
  1455. {
  1456. if (freeSlots.empty())
  1457. {
  1458. allTroopsMoved = false;
  1459. continue; // no more free slots, but we might still have units that are present in both armies
  1460. }
  1461. targetSlot = freeSlots.front();
  1462. freeSlots.erase(freeSlots.begin());
  1463. }
  1464. RebalanceStacks rs;
  1465. rs.srcArmy = armySrc->id;
  1466. rs.dstArmy = armyDest->id;
  1467. rs.srcSlot = slot.first;
  1468. rs.dstSlot = targetSlot;
  1469. rs.count = slot.second->getCount();
  1470. bulkRS.moves.push_back(rs);
  1471. }
  1472. // all troops were moved, but we can't leave source hero without troops - undo movement of 1 unit from srcSlot
  1473. if (allTroopsMoved)
  1474. {
  1475. if (armySrc->getStack(srcSlot).getCount() == 1)
  1476. {
  1477. // slot only had 1 unit - remove this move completely
  1478. vstd::erase_if(bulkRS.moves, [srcSlot](const RebalanceStacks & move)
  1479. {
  1480. return move.srcSlot == srcSlot;
  1481. });
  1482. }
  1483. else
  1484. {
  1485. // slot has multiple units - move all but one
  1486. for (auto & move : bulkRS.moves)
  1487. {
  1488. if (move.srcSlot == srcSlot)
  1489. move.count -= 1;
  1490. }
  1491. }
  1492. }
  1493. sendAndApply(bulkRS);
  1494. return true;
  1495. }
  1496. bool CGameHandler::bulkSplitAndRebalanceStack(SlotID slotSrc, ObjectInstanceID srcOwner)
  1497. {
  1498. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  1499. return false;
  1500. const auto * army = dynamic_cast<const CArmedInstance*>(gameInfo().getObjInstance(srcOwner));
  1501. const CCreatureSet & creatureSet = *army;
  1502. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  1503. return false;
  1504. auto actualAmount = creatureSet.getStackCount(slotSrc);
  1505. if(actualAmount <= 1 && complain(complainNoCreatures))
  1506. return false;
  1507. auto freeSlot = creatureSet.getFreeSlot();
  1508. const auto * currentCreature = creatureSet.getCreature(slotSrc);
  1509. if(freeSlot == SlotID() && creatureSet.isCreatureBalanced(currentCreature))
  1510. return true;
  1511. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, slotSrc, 1); // Ignore slots where's only 1 creature
  1512. TQuantity totalCreatures = creatureSet.getStackCount(slotSrc);
  1513. for(auto slot : creatureSlots)
  1514. totalCreatures += creatureSet.getStackCount(slot);
  1515. if(totalCreatures <= 1 && complain("Total creatures number is invalid"))
  1516. return false;
  1517. BulkRebalanceStacks bulkSRS;
  1518. // 1) merge all but one creatures back into source slot
  1519. // single creature needs to be kept, to avoid stack artifact dropping to hero backpack
  1520. for(auto slot : creatureSlots)
  1521. {
  1522. RebalanceStacks rs;
  1523. rs.srcArmy = army->id;
  1524. rs.dstArmy = army->id;
  1525. rs.srcSlot = slot;
  1526. rs.dstSlot = slotSrc;
  1527. rs.count = creatureSet.getStackCount(slot) - 1;
  1528. if (rs.count > 0)
  1529. bulkSRS.moves.push_back(rs);
  1530. }
  1531. // 2) split off single creature into new slot, if any
  1532. // strictly speaking, not needed, but more convenient
  1533. if(freeSlot != SlotID())
  1534. {
  1535. RebalanceStacks rs;
  1536. rs.srcArmy = army->id;
  1537. rs.dstArmy = army->id;
  1538. rs.srcSlot = slotSrc;
  1539. rs.dstSlot = freeSlot;
  1540. rs.count = 1;
  1541. bulkSRS.moves.push_back(rs);
  1542. creatureSlots.push_back(freeSlot);
  1543. }
  1544. if(creatureSlots.empty() && complain("No available slots for smart rebalancing"))
  1545. return false;
  1546. int slotsLeft = creatureSlots.size() + 1; // + srcSlot
  1547. TQuantity unitsToMove = totalCreatures - slotsLeft;
  1548. // 3) re-split creatures in a balanced way
  1549. for(auto slot : creatureSlots)
  1550. {
  1551. RebalanceStacks rs;
  1552. rs.srcArmy = army->id;
  1553. rs.dstArmy = army->id;
  1554. rs.srcSlot = slotSrc;
  1555. rs.dstSlot = slot;
  1556. rs.count = vstd::divideAndCeil(unitsToMove, slotsLeft);
  1557. bulkSRS.moves.push_back(rs);
  1558. unitsToMove -= rs.count;
  1559. slotsLeft -= 1;
  1560. }
  1561. sendAndApply(bulkSRS);
  1562. return true;
  1563. }
  1564. bool CGameHandler::arrangeStacks(ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player)
  1565. {
  1566. const auto * s1 = dynamic_cast<const CArmedInstance *>(gameInfo().getObj(id1));
  1567. const auto * s2 = dynamic_cast<const CArmedInstance *>(gameInfo().getObj(id2));
  1568. if (s1 == nullptr || s2 == nullptr)
  1569. {
  1570. complain("Cannot exchange stacks between non-existing objects!!\n");
  1571. return false;
  1572. }
  1573. const CCreatureSet & S1 = *s1;
  1574. const CCreatureSet & S2 = *s2;
  1575. StackLocation sl1(s1->id, p1);
  1576. StackLocation sl2(s2->id, p2);
  1577. if (!sl1.slot.validSlot() || !sl2.slot.validSlot())
  1578. {
  1579. complain(complainInvalidSlot);
  1580. return false;
  1581. }
  1582. if (!isAllowedExchange(id1,id2))
  1583. {
  1584. complain("Cannot exchange stacks between these two objects!\n");
  1585. return false;
  1586. }
  1587. // We can always put stacks into locked garrison, but not take them out of it
  1588. auto notRemovable = [&](const CArmedInstance * army)
  1589. {
  1590. if (id1 != id2) // Stack arrangement inside locked garrison is allowed
  1591. {
  1592. const auto * g = dynamic_cast<const CGGarrison *>(army);
  1593. if (g && !g->removableUnits)
  1594. {
  1595. complain("Stacks in this garrison are not removable!\n");
  1596. return true;
  1597. }
  1598. }
  1599. return false;
  1600. };
  1601. if (what==1) //swap
  1602. {
  1603. if (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s1->getStackCount(p1))
  1604. || ((s2->tempOwner != player && s2->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)))
  1605. {
  1606. complain("Can't take troops from another player!");
  1607. return false;
  1608. }
  1609. if (sl1.army == sl2.army && sl1.slot == sl2.slot)
  1610. {
  1611. complain("Cannot swap stacks - slots are the same!");
  1612. return false;
  1613. }
  1614. if (!s1->slotEmpty(p1) && !s2->slotEmpty(p2))
  1615. {
  1616. if (notRemovable(s1) || notRemovable(s2))
  1617. return false;
  1618. }
  1619. if (s1->slotEmpty(p1) && notRemovable(s2))
  1620. return false;
  1621. else if (s2->slotEmpty(p2) && notRemovable(s1))
  1622. return false;
  1623. swapStacks(sl1, sl2);
  1624. }
  1625. else if (what==2)//merge
  1626. {
  1627. if ((s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot merge different creatures stacks!"))
  1628. || (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)) && complain("Can't take troops from another player!")))
  1629. return false;
  1630. if (s1->slotEmpty(p1) || s2->slotEmpty(p2))
  1631. {
  1632. complain("Cannot merge empty stack!");
  1633. return false;
  1634. }
  1635. else if (notRemovable(s1))
  1636. return false;
  1637. moveStack(sl1, sl2);
  1638. }
  1639. else if (what==3) //split
  1640. {
  1641. const int countToMove = val - s2->getStackCount(p2);
  1642. const int countLeftOnSrc = s1->getStackCount(p1) - countToMove;
  1643. if ( (s1->tempOwner != player && countLeftOnSrc < s1->getStackCount(p1))
  1644. || (s2->tempOwner != player && val < s2->getStackCount(p2)))
  1645. {
  1646. complain("Can't move troops of another player!");
  1647. return false;
  1648. }
  1649. //general conditions checking
  1650. if ((!vstd::contains(S1.stacks,p1) && complain(complainNoCreatures))
  1651. || (val<1 && complain(complainNoCreatures)) )
  1652. {
  1653. return false;
  1654. }
  1655. if (vstd::contains(S2.stacks,p2)) //dest. slot not free - it must be "rebalancing"...
  1656. {
  1657. int total = s1->getStackCount(p1) + s2->getStackCount(p2);
  1658. if ((total < val && complain("Cannot split that stack, not enough creatures!"))
  1659. || (s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot rebalance different creatures stacks!"))
  1660. )
  1661. {
  1662. return false;
  1663. }
  1664. if (notRemovable(s1))
  1665. {
  1666. if (s1->getStackCount(p1) > countLeftOnSrc)
  1667. return false;
  1668. }
  1669. else if (notRemovable(s2))
  1670. {
  1671. if (s2->getStackCount(p1) < countLeftOnSrc)
  1672. return false;
  1673. }
  1674. moveStack(sl1, sl2, countToMove);
  1675. //S2.slots[p2]->count = val;
  1676. //S1.slots[p1]->count = total - val;
  1677. }
  1678. else //split one stack to the two
  1679. {
  1680. if (s1->getStackCount(p1) < val)//not enough creatures
  1681. {
  1682. complain(complainNotEnoughCreatures);
  1683. return false;
  1684. }
  1685. if (notRemovable(s1))
  1686. return false;
  1687. moveStack(sl1, sl2, val);
  1688. }
  1689. }
  1690. return true;
  1691. }
  1692. bool CGameHandler::hasPlayerAt(PlayerColor player, GameConnectionID connectionID) const
  1693. {
  1694. return gameServer().hasPlayerAt(player, connectionID);
  1695. }
  1696. bool CGameHandler::hasBothPlayersAtSameConnection(PlayerColor left, PlayerColor right) const
  1697. {
  1698. return gameServer().hasBothPlayersAtSameConnection(left, right);
  1699. }
  1700. bool CGameHandler::disbandCreature(ObjectInstanceID id, SlotID pos)
  1701. {
  1702. const auto * s1 = dynamic_cast<const CArmedInstance *>(gameInfo().getObjInstance(id));
  1703. if (!vstd::contains(s1->stacks,pos))
  1704. {
  1705. complain("Illegal call to disbandCreature - no such stack in army!");
  1706. return false;
  1707. }
  1708. eraseStack(StackLocation(s1->id, pos));
  1709. return true;
  1710. }
  1711. bool CGameHandler::buildStructure(ObjectInstanceID tid, BuildingID requestedID, bool force)
  1712. {
  1713. const CGTownInstance * t = gameInfo().getTown(tid);
  1714. if(!t)
  1715. COMPLAIN_RETF("No such town (ID=%s)!", tid);
  1716. if(!t->getTown()->buildings.count(requestedID))
  1717. COMPLAIN_RETF("Town of faction %s does not have info about building ID=%s!", t->getFaction()->getNameTranslated() % requestedID);
  1718. if(t->hasBuilt(requestedID))
  1719. COMPLAIN_RETF("Building %s is already built in %s", t->getTown()->buildings.at(requestedID)->getNameTranslated() % t->getNameTranslated());
  1720. const auto & requestedBuilding = t->getTown()->buildings.at(requestedID);
  1721. //Vector with future list of built building and buildings in auto-mode that are not yet built.
  1722. std::vector<const CBuilding*> remainingAutoBuildings;
  1723. std::set<BuildingID> buildingsThatWillBe;
  1724. //Check validity of request
  1725. if(!force)
  1726. {
  1727. switch(requestedBuilding->mode)
  1728. {
  1729. case CBuilding::BUILD_NORMAL :
  1730. if (gameState().canBuildStructure(t, requestedID) != EBuildingState::ALLOWED)
  1731. COMPLAIN_RET("Cannot build that building!");
  1732. break;
  1733. case CBuilding::BUILD_AUTO :
  1734. case CBuilding::BUILD_SPECIAL:
  1735. COMPLAIN_RET("This building can not be constructed normally!");
  1736. case CBuilding::BUILD_GRAIL :
  1737. if(requestedBuilding->mode == CBuilding::BUILD_GRAIL) //needs grail
  1738. {
  1739. if(!t->getVisitingHero() || !t->getVisitingHero()->hasArt(ArtifactID::GRAIL))
  1740. COMPLAIN_RET("Cannot build this without grail!")
  1741. else
  1742. removeArtifact(ArtifactLocation(t->getVisitingHero()->id, t->getVisitingHero()->getArtPos(ArtifactID::GRAIL, false)));
  1743. }
  1744. break;
  1745. }
  1746. }
  1747. //Performs stuff that has to be done before new building is built
  1748. auto processBeforeBuiltStructure = [t, this](const BuildingID buildingID)
  1749. {
  1750. if(buildingID.isDwelling())
  1751. {
  1752. int level = BuildingID::getLevelFromDwelling(buildingID);
  1753. int upgradeNumber = BuildingID::getUpgradedFromDwelling(buildingID);
  1754. if(upgradeNumber >= t->getTown()->creatures.at(level).size())
  1755. {
  1756. complain(boost::str(boost::format("Error encountered when building dwelling (bid=%s):"
  1757. "no creature found (upgrade number %d, level %d!")
  1758. % buildingID % upgradeNumber % level));
  1759. return;
  1760. }
  1761. const CCreature * crea = t->getTown()->creatures.at(level).at(upgradeNumber).toCreature();
  1762. SetAvailableCreatures ssi;
  1763. ssi.tid = t->id;
  1764. ssi.creatures = t->creatures;
  1765. if (ssi.creatures[level].second.empty()) // first creature in a dwelling
  1766. ssi.creatures[level].first = crea->getGrowth();
  1767. ssi.creatures[level].second.push_back(crea->getId());
  1768. sendAndApply(ssi);
  1769. }
  1770. if(t->getTown()->buildings.at(buildingID)->subId == BuildingSubID::PORTAL_OF_SUMMONING)
  1771. {
  1772. setPortalDwelling(t);
  1773. }
  1774. };
  1775. //Performs stuff that has to be done after new building is built
  1776. auto processAfterBuiltStructure = [t, this](const BuildingID buildingID)
  1777. {
  1778. auto isMageGuild = (buildingID <= BuildingID::MAGES_GUILD_5 && buildingID >= BuildingID::MAGES_GUILD_1);
  1779. auto isLibrary = isMageGuild ? false
  1780. : t->getTown()->buildings.at(buildingID)->subId == BuildingSubID::EBuildingSubID::LIBRARY;
  1781. if(isMageGuild || isLibrary || (t->getFactionID() == ETownType::CONFLUX && buildingID == BuildingID::GRAIL))
  1782. {
  1783. if(t->getVisitingHero())
  1784. giveSpells(t,t->getVisitingHero());
  1785. if(t->getGarrisonHero())
  1786. giveSpells(t,t->getGarrisonHero());
  1787. }
  1788. };
  1789. //Checks if all requirements will be met with expected building list "buildingsThatWillBe"
  1790. auto areRequirementsFulfilled = [&buildingsThatWillBe](const BuildingID & buildID)
  1791. {
  1792. return buildingsThatWillBe.count(buildID);
  1793. };
  1794. //Init the vectors
  1795. for(const auto & build : t->getTown()->buildings)
  1796. {
  1797. if(t->hasBuilt(build.first))
  1798. {
  1799. buildingsThatWillBe.insert(build.first);
  1800. }
  1801. else
  1802. {
  1803. if(build.second->mode == CBuilding::BUILD_AUTO) //not built auto building
  1804. remainingAutoBuildings.push_back(build.second.get());
  1805. }
  1806. }
  1807. //Prepare structure (list of building ids will be filled later)
  1808. NewStructures ns;
  1809. ns.tid = tid;
  1810. ns.built = force ? t->built : (t->built+1);
  1811. std::queue<const CBuilding*> buildingsToAdd;
  1812. buildingsToAdd.push(requestedBuilding.get());
  1813. while(!buildingsToAdd.empty())
  1814. {
  1815. const auto * b = buildingsToAdd.front();
  1816. buildingsToAdd.pop();
  1817. ns.bid.insert(b->bid);
  1818. buildingsThatWillBe.insert(b->bid);
  1819. remainingAutoBuildings -= b;
  1820. for(const auto * autoBuilding : remainingAutoBuildings)
  1821. {
  1822. auto actualRequirements = t->genBuildingRequirements(autoBuilding->bid);
  1823. if(actualRequirements.test(areRequirementsFulfilled))
  1824. buildingsToAdd.push(autoBuilding);
  1825. }
  1826. }
  1827. // 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.
  1828. for(auto builtID : ns.bid)
  1829. processBeforeBuiltStructure(builtID);
  1830. //Take cost
  1831. if(!force)
  1832. {
  1833. giveResources(t->tempOwner, -requestedBuilding->resources);
  1834. statistics->accumulatedValues[t->tempOwner].spentResourcesForBuildings += requestedBuilding->resources;
  1835. }
  1836. //We know what has been built, apply changes. Do this as final step to properly update town window
  1837. sendAndApply(ns);
  1838. //Other post-built events. To some logic like giving spells to work gamestate changes for new building must be already in place!
  1839. for(auto builtID : ns.bid)
  1840. processAfterBuiltStructure(builtID);
  1841. // now when everything is built - reveal tiles for lookout tower
  1842. changeFogOfWar(t->getSightCenter(), t->getSightRadius(), t->getOwner(), ETileVisibility::REVEALED);
  1843. if (!force)
  1844. {
  1845. //garrison hero first - consistent with original H3 Mana Vortex and Battle Scholar Academy levelup windows order
  1846. std::vector<const CGHeroInstance *> visitors;
  1847. if (t->getGarrisonHero())
  1848. visitors.push_back(t->getGarrisonHero());
  1849. if (t->getVisitingHero())
  1850. visitors.push_back(t->getVisitingHero());
  1851. if (!visitors.empty())
  1852. visitCastleObjects(t, visitors);
  1853. }
  1854. checkVictoryLossConditionsForPlayer(t->tempOwner);
  1855. return true;
  1856. }
  1857. bool CGameHandler::visitTownBuilding(ObjectInstanceID tid, BuildingID bid)
  1858. {
  1859. const CGTownInstance * t = gameInfo().getTown(tid);
  1860. if(!t->hasBuilt(bid))
  1861. return false;
  1862. auto subID = t->getTown()->buildings.at(bid)->subId;
  1863. if(subID == BuildingSubID::EBuildingSubID::BANK)
  1864. {
  1865. TResources res;
  1866. res[EGameResID::GOLD] = 2500;
  1867. giveResources(t->getOwner(), res);
  1868. setObjPropertyValue(t->id, ObjProperty::BONUS_VALUE_SECOND, 2500);
  1869. return true;
  1870. }
  1871. if (t->rewardableBuildings.count(bid) && t->getVisitingHero() && t->getTown()->buildings.at(bid)->manualHeroVisit)
  1872. {
  1873. std::vector<BuildingID> buildingsToVisit;
  1874. std::vector<const CGHeroInstance*> visitors;
  1875. buildingsToVisit.push_back(bid);
  1876. visitors.push_back(t->getVisitingHero());
  1877. auto visitQuery = std::make_shared<TownBuildingVisitQuery>(this, t, visitors, buildingsToVisit);
  1878. queries->addQuery(visitQuery);
  1879. return true;
  1880. }
  1881. return true;
  1882. }
  1883. bool CGameHandler::razeStructure (ObjectInstanceID tid, BuildingID bid)
  1884. {
  1885. ///incomplete, simply erases target building
  1886. const CGTownInstance * t = gameInfo().getTown(tid);
  1887. if(!t->hasBuilt(bid))
  1888. return false;
  1889. RazeStructures rs;
  1890. rs.tid = tid;
  1891. rs.bid.insert(bid);
  1892. rs.destroyed = t->destroyed + 1;
  1893. sendAndApply(rs);
  1894. return true;
  1895. }
  1896. bool CGameHandler::spellResearch(ObjectInstanceID tid, SpellID spellAtSlot, bool accepted)
  1897. {
  1898. const CGTownInstance * t = gameState().getTown(tid);
  1899. if(!gameInfo().getSettings().getBoolean(EGameSettings::TOWNS_SPELL_RESEARCH) && complain("Spell research not allowed!"))
  1900. return false;
  1901. if (!t->spellResearchAllowed && complain("Spell research not allowed in this town!"))
  1902. return false;
  1903. int level = -1;
  1904. for(int i = 0; i < t->spells.size(); i++)
  1905. if(vstd::find_pos(t->spells[i], spellAtSlot) != -1)
  1906. level = i;
  1907. if(level == -1 && complain("Spell for replacement not found!"))
  1908. return false;
  1909. auto spells = t->spells.at(level);
  1910. bool researchLimitExceeded = t->spellResearchCounterDay >= gameInfo().getSettings().getValue(EGameSettings::TOWNS_SPELL_RESEARCH_PER_DAY).Vector()[level].Float();
  1911. if(researchLimitExceeded && complain("Already researched today!"))
  1912. return false;
  1913. if(!accepted)
  1914. {
  1915. auto it = spells.begin() + t->spellsAtLevel(level, false);
  1916. std::rotate(it, it + 1, spells.end()); // move to end
  1917. setResearchedSpells(t, level, spells, accepted);
  1918. return true;
  1919. }
  1920. auto costBase = TResources(gameInfo().getSettings().getValue(EGameSettings::TOWNS_SPELL_RESEARCH_COST).Vector()[level]);
  1921. auto costExponent = gameInfo().getSettings().getValue(EGameSettings::TOWNS_SPELL_RESEARCH_COST_EXPONENT_PER_RESEARCH).Vector()[level].Float();
  1922. auto cost = costBase * std::pow(t->spellResearchAcceptedCounter + 1, costExponent);
  1923. if(!gameInfo().getPlayerState(t->getOwner())->resources.canAfford(cost) && complain("Spell replacement cannot be afforded!"))
  1924. return false;
  1925. giveResources(t->getOwner(), -cost);
  1926. std::swap(spells.at(t->spellsAtLevel(level, false)), spells.at(vstd::find_pos(spells, spellAtSlot)));
  1927. auto it = spells.begin() + t->spellsAtLevel(level, false);
  1928. std::rotate(it, it + 1, spells.end()); // move to end
  1929. setResearchedSpells(t, level, spells, accepted);
  1930. if(t->getVisitingHero())
  1931. giveSpells(t, t->getVisitingHero());
  1932. if(t->getGarrisonHero())
  1933. giveSpells(t, t->getGarrisonHero());
  1934. return true;
  1935. }
  1936. bool CGameHandler::recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dstid, CreatureID crid, int32_t cram, int32_t fromLvl, PlayerColor player)
  1937. {
  1938. const auto * dwelling = dynamic_cast<const CGDwelling *>(gameInfo().getObj(objid));
  1939. const auto * town = dynamic_cast<const CGTownInstance *>(gameInfo().getObj(objid));
  1940. const auto * army = dynamic_cast<const CArmedInstance *>(gameInfo().getObj(dstid));
  1941. const auto * hero = dynamic_cast<const CGHeroInstance *>(gameInfo().getObj(dstid));
  1942. const auto * c = crid.toCreature();
  1943. const bool warMachine = c->warMachine != ArtifactID::NONE;
  1944. //TODO: check if hero is actually visiting object
  1945. COMPLAIN_RET_FALSE_IF(!dwelling || !army, "Cannot recruit: invalid object!");
  1946. COMPLAIN_RET_FALSE_IF(dwelling->getOwner() != player && dwelling->getOwner() != PlayerColor::UNFLAGGABLE, "Cannot recruit: dwelling not owned!");
  1947. if (town)
  1948. {
  1949. COMPLAIN_RET_FALSE_IF(town != army && !hero, "Cannot recruit: invalid destination!");
  1950. COMPLAIN_RET_FALSE_IF(hero != town->getGarrisonHero() && hero != town->getVisitingHero(), "Cannot recruit: can only recruit to town or hero in town!!");
  1951. }
  1952. else
  1953. {
  1954. COMPLAIN_RET_FALSE_IF(getVisitingHero(dwelling) != hero, "Cannot recruit: can only recruit by visiting hero!");
  1955. COMPLAIN_RET_FALSE_IF(!hero || hero->getOwner() != player, "Cannot recruit: can only recruit to owned hero!");
  1956. }
  1957. //verify
  1958. bool found = false;
  1959. int level = 0;
  1960. for (; level < dwelling->creatures.size(); level++) //iterate through all levels
  1961. {
  1962. if ((fromLvl != -1) && (level !=fromLvl))
  1963. continue;
  1964. const auto &cur = dwelling->creatures.at(level); //current level info <amount, list of cr. ids>
  1965. int i = 0;
  1966. for (; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  1967. if (cur.second.at(i) == crid)
  1968. break;
  1969. if (i < cur.second.size())
  1970. {
  1971. found = true;
  1972. cram = std::min<int32_t>(cram, cur.first); //reduce recruited amount up to available amount
  1973. break;
  1974. }
  1975. }
  1976. SlotID slot = army->getSlotFor(crid);
  1977. if((!found && complain("Cannot recruit: no such creatures!"))
  1978. || (cram > LIBRARY->creh->objects.at(crid)->maxAmount(gameInfo().getPlayerState(army->tempOwner)->resources) && complain("Cannot recruit: lack of resources!"))
  1979. || (cram <= 0 && complain("Cannot recruit: cram <= 0!"))
  1980. || (!slot.validSlot() && !warMachine && complain("Cannot recruit: no available slot!")))
  1981. {
  1982. return false;
  1983. }
  1984. //recruit
  1985. TResources cost = (c->getFullRecruitCost() * cram);
  1986. giveResources(army->tempOwner, -cost);
  1987. statistics->accumulatedValues[army->tempOwner].spentResourcesForArmy += cost;
  1988. SetAvailableCreatures sac;
  1989. sac.tid = objid;
  1990. sac.creatures = dwelling->creatures;
  1991. sac.creatures[level].first -= cram;
  1992. sendAndApply(sac);
  1993. if (warMachine)
  1994. {
  1995. ArtifactID artId = c->warMachine;
  1996. const CArtifact * art = artId.toArtifact();
  1997. COMPLAIN_RET_FALSE_IF(!hero, "Only hero can buy war machines");
  1998. COMPLAIN_RET_FALSE_IF(artId == ArtifactID::CATAPULT, "Catapult cannot be recruited!");
  1999. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid war machine artifact");
  2000. COMPLAIN_RET_FALSE_IF(hero->hasArt(artId),"Hero already has this machine!");
  2001. bool hasFreeSlot = false;
  2002. for(auto possibleSlot : art->getPossibleSlots().at(ArtBearer::HERO))
  2003. if (hero->getArt(possibleSlot) == nullptr)
  2004. hasFreeSlot = true;
  2005. if (!hasFreeSlot)
  2006. {
  2007. auto possibleSlot = art->getPossibleSlots().at(ArtBearer::HERO).front();
  2008. removeArtifact(ArtifactLocation(hero->id, possibleSlot));
  2009. }
  2010. return giveHeroNewArtifact(hero, artId, ArtifactPosition::FIRST_AVAILABLE);
  2011. }
  2012. else
  2013. {
  2014. addToSlot(StackLocation(army->id, slot), c, cram);
  2015. }
  2016. return true;
  2017. }
  2018. bool CGameHandler::upgradeCreature(ObjectInstanceID objid, SlotID pos, CreatureID upgID)
  2019. {
  2020. const auto * obj = dynamic_cast<const CArmedInstance *>(gameInfo().getObjInstance(objid));
  2021. if (!obj->hasStackAtSlot(pos))
  2022. {
  2023. COMPLAIN_RET("Cannot upgrade, no stack at slot " + std::to_string(pos));
  2024. }
  2025. UpgradeInfo upgradeInfo(obj->getStackPtr(pos)->getId());
  2026. gameState().fillUpgradeInfo(obj, pos, upgradeInfo);
  2027. PlayerColor player = obj->tempOwner;
  2028. const PlayerState *p = gameInfo().getPlayerState(player);
  2029. int crQuantity = obj->stacks.at(pos)->getCount();
  2030. //check if upgrade is possible
  2031. if (!upgradeInfo.hasUpgrades() && complain("That upgrade is not possible!"))
  2032. {
  2033. return false;
  2034. }
  2035. TResources totalCost = upgradeInfo.getUpgradeCostsFor(upgID) * crQuantity;
  2036. //check if player has enough resources
  2037. if (!p->resources.canAfford(totalCost))
  2038. COMPLAIN_RET("Cannot upgrade, not enough resources!");
  2039. //take resources
  2040. giveResources(player, -totalCost);
  2041. statistics->accumulatedValues[player].spentResourcesForArmy += totalCost;
  2042. //upgrade creature
  2043. changeStackType(StackLocation(obj->id, pos), upgID.toCreature());
  2044. return true;
  2045. }
  2046. bool CGameHandler::changeStackType(const StackLocation &sl, const CCreature *c)
  2047. {
  2048. const auto * obj = dynamic_cast<const CArmedInstance *>(gameInfo().getObjInstance(sl.army));
  2049. if (!obj->hasStackAtSlot(sl.slot))
  2050. COMPLAIN_RET("Cannot find a stack to change type");
  2051. SetStackType sst;
  2052. sst.army = obj->id;
  2053. sst.slot = sl.slot;
  2054. sst.type = c->getId();
  2055. sendAndApply(sst);
  2056. return true;
  2057. }
  2058. void CGameHandler::moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging)
  2059. {
  2060. assert(src->canBeMergedWith(*dst, allowMerging));
  2061. while(src->stacksCount())//while there are unmoved creatures
  2062. {
  2063. auto i = src->Slots().begin(); //iterator to stack to move
  2064. StackLocation sl(src->id, i->first); //location of stack to move
  2065. SlotID pos = dst->getSlotFor(i->second->getCreature());
  2066. if (!pos.validSlot())
  2067. {
  2068. //try to merge two other stacks to make place
  2069. std::pair<SlotID, SlotID> toMerge;
  2070. if (dst->mergeableStacks(toMerge, i->first) && allowMerging)
  2071. {
  2072. moveStack(StackLocation(dst->id, toMerge.first), StackLocation(dst->id, toMerge.second)); //merge toMerge.first into toMerge.second
  2073. assert(!dst->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  2074. moveStack(sl, StackLocation(dst->id, toMerge.first)); //move stack to freed slot
  2075. }
  2076. else
  2077. {
  2078. complain("Unexpected failure during an attempt to move army from " + src->nodeName() + " to " + dst->nodeName() + "!");
  2079. return;
  2080. }
  2081. }
  2082. else
  2083. {
  2084. moveStack(sl, StackLocation(dst->id, pos));
  2085. }
  2086. }
  2087. }
  2088. bool CGameHandler::garrisonSwap(ObjectInstanceID tid)
  2089. {
  2090. const CGTownInstance * town = gameInfo().getTown(tid);
  2091. if (!town->getGarrisonHero() && town->getVisitingHero()) //visiting => garrison, merge armies: town army => hero army
  2092. {
  2093. if (!town->getVisitingHero()->canBeMergedWith(*town))
  2094. {
  2095. complain("Cannot make garrison swap, not enough free slots!");
  2096. return false;
  2097. }
  2098. moveArmy(town, town->getVisitingHero(), true);
  2099. SetHeroesInTown intown;
  2100. intown.tid = tid;
  2101. intown.visiting = ObjectInstanceID();
  2102. intown.garrison = town->getVisitingHero()->id;
  2103. sendAndApply(intown);
  2104. return true;
  2105. }
  2106. else if (town->getGarrisonHero() && !town->getVisitingHero()) //move hero out of the garrison
  2107. {
  2108. int mapCap = gameInfo().getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP);
  2109. //check if moving hero out of town will break wandering heroes limit
  2110. if (gameInfo().getHeroCount(town->getGarrisonHero()->tempOwner,false) >= mapCap)
  2111. {
  2112. complain("Cannot move hero out of the garrison, there are already " + std::to_string(mapCap) + " wandering heroes!");
  2113. return false;
  2114. }
  2115. SetHeroesInTown intown;
  2116. intown.tid = tid;
  2117. intown.garrison = ObjectInstanceID();
  2118. intown.visiting = town->getGarrisonHero()->id;
  2119. sendAndApply(intown);
  2120. return true;
  2121. }
  2122. else if (!!town->getGarrisonHero() && town->getVisitingHero()) //swap visiting and garrison hero
  2123. {
  2124. SetHeroesInTown intown;
  2125. intown.tid = tid;
  2126. intown.garrison = town->getVisitingHero()->id;
  2127. intown.visiting = town->getGarrisonHero()->id;
  2128. sendAndApply(intown);
  2129. return true;
  2130. }
  2131. else
  2132. {
  2133. complain("Cannot swap garrison hero!");
  2134. return false;
  2135. }
  2136. }
  2137. // With the amount of changes done to the function, it's more like transferArtifacts.
  2138. // 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.
  2139. bool CGameHandler::moveArtifact(const PlayerColor & player, const ArtifactLocation & src, const ArtifactLocation & dst)
  2140. {
  2141. const auto * srcArtSet = gameState().getArtSet(src);
  2142. const auto * dstArtSet = gameState().getArtSet(dst);
  2143. assert(srcArtSet);
  2144. assert(dstArtSet);
  2145. // Make sure exchange is even possible between the two heroes.
  2146. if(!isAllowedExchange(src.artHolder, dst.artHolder))
  2147. COMPLAIN_RET("That heroes cannot make any exchange!");
  2148. COMPLAIN_RET_FALSE_IF(!ArtifactUtils::checkIfSlotValid(*srcArtSet, src.slot), "moveArtifact: wrong artifact source slot");
  2149. const auto * srcArtifact = srcArtSet->getArt(src.slot);
  2150. auto dstSlot = dst.slot;
  2151. if(dstSlot == ArtifactPosition::FIRST_AVAILABLE)
  2152. dstSlot = ArtifactUtils::getArtAnyPosition(dstArtSet, srcArtifact->getTypeId());
  2153. if(!ArtifactUtils::checkIfSlotValid(*dstArtSet, dstSlot))
  2154. return true;
  2155. const auto * dstArtifact = dstArtSet->getArt(dstSlot);
  2156. const bool isDstSlotOccupied = dstArtSet->bearerType() == ArtBearer::ALTAR ? false : dstArtifact != nullptr;
  2157. const bool isDstSlotBackpack = dstArtSet->bearerType() == ArtBearer::HERO ? ArtifactUtils::isSlotBackpack(dstSlot) : false;
  2158. if(srcArtifact == nullptr)
  2159. COMPLAIN_RET("No artifact to move!");
  2160. if(isDstSlotOccupied && gameState().getOwner(src.artHolder) != gameState().getOwner(dst.artHolder) && !isDstSlotBackpack)
  2161. COMPLAIN_RET("Can't touch artifact on hero of another player!");
  2162. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2163. // Moving to the backpack is always allowed.
  2164. if((!srcArtifact || !isDstSlotBackpack) && !srcArtifact->canBePutAt(dstArtSet, dstSlot, true))
  2165. COMPLAIN_RET("Cannot move artifact!");
  2166. const auto * srcSlotInfo = srcArtSet->getSlot(src.slot);
  2167. const auto * dstSlotInfo = dstArtSet->getSlot(dstSlot);
  2168. if((srcSlotInfo && srcSlotInfo->locked) || (dstSlotInfo && dstSlotInfo->locked))
  2169. COMPLAIN_RET("Cannot move artifact locks.");
  2170. if(isDstSlotBackpack && srcArtifact->getType()->isBig())
  2171. COMPLAIN_RET("Cannot put big artifacts in backpack!");
  2172. if(src.slot == ArtifactPosition::MACH4 || dstSlot == ArtifactPosition::MACH4)
  2173. COMPLAIN_RET("Cannot move catapult!");
  2174. if(isDstSlotBackpack && !ArtifactUtils::isBackpackFreeSlots(dstArtSet))
  2175. COMPLAIN_RET("Backpack is full!");
  2176. dstSlot = std::min(dstSlot, ArtifactPosition(ArtifactPosition::BACKPACK_START + dstArtSet->artifactsInBackpack.size()));
  2177. if(src.slot == dstSlot && src.artHolder == dst.artHolder)
  2178. COMPLAIN_RET("Won't move artifact: Dest same as source!");
  2179. BulkMoveArtifacts ma(player, src.artHolder, dst.artHolder, false);
  2180. ma.srcCreature = src.creature;
  2181. ma.dstCreature = dst.creature;
  2182. // Check if dst slot is occupied
  2183. if(!isDstSlotBackpack && isDstSlotOccupied)
  2184. {
  2185. // Previous artifact must be swapped
  2186. COMPLAIN_RET_FALSE_IF(!dstArtifact->canBePutAt(srcArtSet, src.slot, true), "Cannot swap artifacts!");
  2187. ma.artsPack1.emplace_back(dstSlot, src.slot);
  2188. }
  2189. const auto * hero = gameInfo().getHero(dst.artHolder);
  2190. if(ArtifactUtils::checkSpellbookIsNeeded(hero, srcArtifact->getTypeId(), dstSlot))
  2191. giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
  2192. ma.artsPack0.emplace_back(src.slot, dstSlot);
  2193. if(src.artHolder != dst.artHolder && !isDstSlotBackpack)
  2194. ma.artsPack0.back().askAssemble = true;
  2195. sendAndApply(ma);
  2196. return true;
  2197. }
  2198. bool CGameHandler::bulkMoveArtifacts(const PlayerColor & player, ObjectInstanceID srcId, ObjectInstanceID dstId, bool swap, bool equipped, bool backpack)
  2199. {
  2200. // Make sure exchange is even possible between the two heroes.
  2201. if(!isAllowedExchange(srcId, dstId))
  2202. COMPLAIN_RET("That heroes cannot make any exchange!");
  2203. const auto * psrcSet = gameState().getArtSet(srcId);
  2204. const auto * pdstSet = gameState().getArtSet(dstId);
  2205. if((!psrcSet) || (!pdstSet))
  2206. COMPLAIN_RET("bulkMoveArtifacts: wrong hero's ID");
  2207. BulkMoveArtifacts ma(player, srcId, dstId, swap);
  2208. auto & slotsSrcDst = ma.artsPack0;
  2209. auto & slotsDstSrc = ma.artsPack1;
  2210. // Temporary fitting set for artifacts. Used to select available slots before sending data.
  2211. CArtifactFittingSet artFittingSet(&gameInfo(), pdstSet->bearerType());
  2212. auto moveArtifact = [this, &artFittingSet, dstId](const CArtifactInstance * artifact,
  2213. ArtifactPosition srcSlot, std::vector<MoveArtifactInfo> & slots) -> void
  2214. {
  2215. assert(artifact);
  2216. auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, artifact->getTypeId());
  2217. if(dstSlot != ArtifactPosition::PRE_FIRST)
  2218. {
  2219. artFittingSet.putArtifact(dstSlot, artifact);
  2220. slots.emplace_back(srcSlot, dstSlot);
  2221. // TODO Shouldn't be here. Possibly in callback after equipping the artifact
  2222. if(const auto * dstHero = gameInfo().getHero(dstId))
  2223. {
  2224. if(ArtifactUtils::checkSpellbookIsNeeded(dstHero, artifact->getTypeId(), dstSlot))
  2225. giveHeroNewArtifact(dstHero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
  2226. }
  2227. }
  2228. };
  2229. if(swap)
  2230. {
  2231. auto moveArtsWorn = [moveArtifact](const CArtifactSet * srcArtSet, std::vector<MoveArtifactInfo> & slots)
  2232. {
  2233. for(const auto & artifact : srcArtSet->artifactsWorn)
  2234. {
  2235. if(ArtifactUtils::isArtRemovable(artifact))
  2236. moveArtifact(artifact.second.getArt(), artifact.first, slots);
  2237. }
  2238. };
  2239. auto moveArtsInBackpack = [](const CArtifactSet * artSet,
  2240. std::vector<MoveArtifactInfo> & slots) -> void
  2241. {
  2242. for(const auto & slotInfo : artSet->artifactsInBackpack)
  2243. {
  2244. auto slot = artSet->getArtPos(slotInfo.getArt());
  2245. slots.emplace_back(slot, slot);
  2246. }
  2247. };
  2248. if(equipped)
  2249. {
  2250. // Move over artifacts that are worn srcHero -> dstHero
  2251. moveArtsWorn(psrcSet, slotsSrcDst);
  2252. artFittingSet.artifactsWorn.clear();
  2253. // Move over artifacts that are worn dstHero -> srcHero
  2254. moveArtsWorn(pdstSet, slotsDstSrc);
  2255. }
  2256. if(backpack)
  2257. {
  2258. // Move over artifacts that are in backpack srcHero -> dstHero
  2259. moveArtsInBackpack(psrcSet, slotsSrcDst);
  2260. // Move over artifacts that are in backpack dstHero -> srcHero
  2261. moveArtsInBackpack(pdstSet, slotsDstSrc);
  2262. }
  2263. }
  2264. else
  2265. {
  2266. artFittingSet.artifactsInBackpack = pdstSet->artifactsInBackpack;
  2267. artFittingSet.artifactsWorn = pdstSet->artifactsWorn;
  2268. if(equipped)
  2269. {
  2270. // Move over artifacts that are worn
  2271. for(const auto & artInfo : psrcSet->artifactsWorn)
  2272. {
  2273. if(ArtifactUtils::isArtRemovable(artInfo))
  2274. {
  2275. moveArtifact(psrcSet->getArt(artInfo.first), artInfo.first, slotsSrcDst);
  2276. }
  2277. }
  2278. }
  2279. if(backpack)
  2280. {
  2281. // Move over artifacts that are in backpack
  2282. for(const auto & slotInfo : psrcSet->artifactsInBackpack)
  2283. {
  2284. moveArtifact(psrcSet->getArt(psrcSet->getArtPos(slotInfo.getArt())),
  2285. psrcSet->getArtPos(slotInfo.getArt()), slotsSrcDst);
  2286. }
  2287. }
  2288. }
  2289. sendAndApply(ma);
  2290. return true;
  2291. }
  2292. bool CGameHandler::manageBackpackArtifacts(const PlayerColor & player, const ObjectInstanceID & heroID, const ManageBackpackArtifacts::ManageCmd & sortType)
  2293. {
  2294. const auto * artSet = gameState().getArtSet(heroID);
  2295. COMPLAIN_RET_FALSE_IF(artSet == nullptr, "manageBackpackArtifacts: wrong hero's ID");
  2296. BulkMoveArtifacts bma(player, heroID, heroID, false);
  2297. const auto makeSortBackpackRequest = [artSet, &bma](const std::function<int32_t(const ArtSlotInfo&)> & getSortId)
  2298. {
  2299. std::map<int32_t, std::vector<MoveArtifactInfo>> packsSorted;
  2300. ArtifactPosition backpackSlot = ArtifactPosition::BACKPACK_START;
  2301. for(const auto & backpackSlotInfo : artSet->artifactsInBackpack)
  2302. packsSorted.try_emplace(getSortId(backpackSlotInfo)).first->second.emplace_back(backpackSlot++, ArtifactPosition::PRE_FIRST);
  2303. for(auto & [sortId, pack] : packsSorted)
  2304. {
  2305. // Each pack of artifacts is also sorted by ArtifactID. Scrolls by SpellID
  2306. std::sort(pack.begin(), pack.end(), [artSet](const auto & slots0, const auto & slots1) -> bool
  2307. {
  2308. const auto art0 = artSet->getArt(slots0.srcPos);
  2309. const auto art1 = artSet->getArt(slots1.srcPos);
  2310. if(art0->isScroll() && art1->isScroll())
  2311. return art0->getScrollSpellID() > art1->getScrollSpellID();
  2312. return art0->getTypeId().num > art1->getTypeId().num;
  2313. });
  2314. bma.artsPack0.insert(bma.artsPack0.end(), pack.begin(), pack.end());
  2315. }
  2316. backpackSlot = ArtifactPosition::BACKPACK_START;
  2317. for(auto & slots : bma.artsPack0)
  2318. slots.dstPos = backpackSlot++;
  2319. };
  2320. if(sortType == ManageBackpackArtifacts::ManageCmd::SORT_BY_SLOT)
  2321. {
  2322. makeSortBackpackRequest([](const ArtSlotInfo & inf) -> int32_t
  2323. {
  2324. auto possibleSlots = inf.getArt()->getType()->getPossibleSlots();
  2325. if (possibleSlots.find(ArtBearer::CREATURE) != possibleSlots.end() && !possibleSlots.at(ArtBearer::CREATURE).empty())
  2326. {
  2327. return -2;
  2328. }
  2329. else if (possibleSlots.find(ArtBearer::COMMANDER) != possibleSlots.end() && !possibleSlots.at(ArtBearer::COMMANDER).empty())
  2330. {
  2331. return -1;
  2332. }
  2333. else if (possibleSlots.find(ArtBearer::HERO) != possibleSlots.end() && !possibleSlots.at(ArtBearer::HERO).empty())
  2334. {
  2335. return inf.getArt()->getType()->getPossibleSlots().at(ArtBearer::HERO).front().num;
  2336. }
  2337. else
  2338. {
  2339. // for grail
  2340. return -3;
  2341. }
  2342. });
  2343. }
  2344. else if(sortType == ManageBackpackArtifacts::ManageCmd::SORT_BY_COST)
  2345. {
  2346. makeSortBackpackRequest([](const ArtSlotInfo & inf) -> int32_t
  2347. {
  2348. return inf.getArt()->getType()->getPrice();
  2349. });
  2350. }
  2351. else if(sortType == ManageBackpackArtifacts::ManageCmd::SORT_BY_CLASS)
  2352. {
  2353. makeSortBackpackRequest([](const ArtSlotInfo & inf) -> int32_t
  2354. {
  2355. return static_cast<int32_t>(inf.getArt()->getType()->aClass);
  2356. });
  2357. }
  2358. else
  2359. {
  2360. const auto backpackEnd = ArtifactPosition(ArtifactPosition::BACKPACK_START + artSet->artifactsInBackpack.size() - 1);
  2361. if(backpackEnd > ArtifactPosition::BACKPACK_START)
  2362. {
  2363. if(sortType == ManageBackpackArtifacts::ManageCmd::SCROLL_LEFT)
  2364. bma.artsPack0.emplace_back(backpackEnd, ArtifactPosition::BACKPACK_START);
  2365. else
  2366. bma.artsPack0.emplace_back(ArtifactPosition::BACKPACK_START, backpackEnd);
  2367. }
  2368. }
  2369. sendAndApply(bma);
  2370. return true;
  2371. }
  2372. bool CGameHandler::saveArtifactsCostume(const PlayerColor & player, const ObjectInstanceID & heroID, uint32_t costumeIdx)
  2373. {
  2374. const auto * artSet = gameState().getArtSet(heroID);
  2375. COMPLAIN_RET_FALSE_IF(artSet == nullptr, "saveArtifactsCostume: wrong hero's ID");
  2376. ChangeArtifactsCostume costume(player, costumeIdx);
  2377. for(const auto & slot : ArtifactUtils::commonWornSlots())
  2378. {
  2379. if(const auto slotInfo = artSet->getSlot(slot); slotInfo != nullptr && !slotInfo->locked)
  2380. costume.costumeSet.emplace(slot, slotInfo->getArt()->getTypeId());
  2381. }
  2382. sendAndApply(costume);
  2383. return true;
  2384. }
  2385. bool CGameHandler::switchArtifactsCostume(const PlayerColor & player, const ObjectInstanceID & heroID, uint32_t costumeIdx)
  2386. {
  2387. const auto * artSet = gameState().getArtSet(heroID);
  2388. COMPLAIN_RET_FALSE_IF(artSet == nullptr, "switchArtifactsCostume: wrong hero's ID");
  2389. const auto * playerState = gameInfo().getPlayerState(player);
  2390. COMPLAIN_RET_FALSE_IF(playerState == nullptr, "switchArtifactsCostume: wrong player");
  2391. if(auto costume = playerState->costumesArtifacts.find(costumeIdx); costume != playerState->costumesArtifacts.end())
  2392. {
  2393. CArtifactFittingSet artFittingSet(*artSet);
  2394. BulkMoveArtifacts bma(player, heroID, heroID, false);
  2395. auto costumeArtMap = costume->second;
  2396. auto estimateBackpackSize = artSet->artifactsInBackpack.size();
  2397. // First, find those artifacts that are already in place
  2398. for(const auto & slot : ArtifactUtils::commonWornSlots())
  2399. {
  2400. if(const auto * slotInfo = artFittingSet.getSlot(slot); slotInfo != nullptr && !slotInfo->locked)
  2401. if(const auto artPos = costumeArtMap.find(slot); artPos != costumeArtMap.end() && artPos->second == slotInfo->getArt()->getTypeId())
  2402. {
  2403. costumeArtMap.erase(artPos);
  2404. artFittingSet.removeArtifact(slot);
  2405. }
  2406. }
  2407. // Second, find the necessary artifacts for the costume
  2408. for(const auto & artPos : costumeArtMap)
  2409. {
  2410. if(const auto slot = artFittingSet.getArtPos(artPos.second, false, false); slot != ArtifactPosition::PRE_FIRST)
  2411. {
  2412. bma.artsPack0.emplace_back(artSet->getArtPos(artFittingSet.getArt(slot)), artPos.first);
  2413. artFittingSet.removeArtifact(slot);
  2414. if(ArtifactUtils::isSlotBackpack(slot))
  2415. estimateBackpackSize--;
  2416. }
  2417. }
  2418. // Third, put unnecessary artifacts into backpack
  2419. for(const auto & slot : ArtifactUtils::commonWornSlots())
  2420. if(artFittingSet.getArt(slot))
  2421. {
  2422. bma.artsPack0.emplace_back(slot, ArtifactPosition::BACKPACK_START);
  2423. estimateBackpackSize++;
  2424. }
  2425. const auto backpackCap = gameInfo().getSettings().getInteger(EGameSettings::HEROES_BACKPACK_CAP);
  2426. if((backpackCap < 0 || estimateBackpackSize <= backpackCap) && !bma.artsPack0.empty())
  2427. sendAndApply(bma);
  2428. }
  2429. return true;
  2430. }
  2431. /**
  2432. * Assembles or disassembles a combination artifact.
  2433. * @param heroID ID of hero holding the artifact(s).
  2434. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  2435. * @param assemble True for assembly operation, false for disassembly.
  2436. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  2437. * artifact to assemble to. Otherwise it's not used.
  2438. */
  2439. bool CGameHandler::assembleArtifacts(ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  2440. {
  2441. const CGHeroInstance * hero = gameInfo().getHero(heroID);
  2442. const CArtifactInstance * destArtifact = hero->getArt(artifactSlot);
  2443. if(!destArtifact)
  2444. COMPLAIN_RET("assembleArtifacts: there is no such artifact instance!");
  2445. const auto dstLoc = ArtifactLocation(hero->id, artifactSlot);
  2446. if(assemble)
  2447. {
  2448. const CArtifact * combinedArt = assembleTo.toArtifact();
  2449. if(!combinedArt->isCombined())
  2450. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to assemble is not a combined artifacts!");
  2451. if(!vstd::contains(ArtifactUtils::assemblyPossibilities(hero, destArtifact->getTypeId()), combinedArt))
  2452. {
  2453. COMPLAIN_RET("assembleArtifacts: It's impossible to assemble requested artifact!");
  2454. }
  2455. if(!destArtifact->canBePutAt(hero, artifactSlot, true)
  2456. && !destArtifact->canBePutAt(hero, ArtifactPosition::BACKPACK_START, true))
  2457. {
  2458. COMPLAIN_RET("assembleArtifacts: It's impossible to give the artholder requested artifact!");
  2459. }
  2460. if(ArtifactUtils::checkSpellbookIsNeeded(hero, assembleTo, artifactSlot))
  2461. giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
  2462. AssembledArtifact aa;
  2463. aa.al = dstLoc;
  2464. aa.artId = assembleTo;
  2465. sendAndApply(aa);
  2466. }
  2467. else
  2468. {
  2469. if(!destArtifact->isCombined())
  2470. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble is not a combined artifact!");
  2471. if(!destArtifact->hasParts())
  2472. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble is fused combined artifact!");
  2473. if(ArtifactUtils::isSlotBackpack(artifactSlot)
  2474. && !ArtifactUtils::isBackpackFreeSlots(hero, destArtifact->getType()->getConstituents().size() - 1))
  2475. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble but backpack is full!");
  2476. DisassembledArtifact da;
  2477. da.al = dstLoc;
  2478. sendAndApply(da);
  2479. }
  2480. checkVictoryLossConditionsForPlayer(hero->getOwner());
  2481. return true;
  2482. }
  2483. bool CGameHandler::eraseArtifactByClient(const ArtifactLocation & al)
  2484. {
  2485. const auto * hero = gameInfo().getHero(al.artHolder);
  2486. if(hero == nullptr)
  2487. COMPLAIN_RET("eraseArtifactByClient: wrong hero's ID");
  2488. const auto * art = hero->getArt(al.slot);
  2489. if(art == nullptr)
  2490. COMPLAIN_RET("Cannot remove artifact!");
  2491. if(art->canBePutAt(hero) || al.slot != ArtifactPosition::TRANSITION_POS)
  2492. COMPLAIN_RET("Illegal artifact removal request");
  2493. removeArtifact(al);
  2494. return true;
  2495. }
  2496. bool CGameHandler::buyArtifact(ObjectInstanceID hid, ArtifactID aid)
  2497. {
  2498. const CGHeroInstance * hero = gameInfo().getHero(hid);
  2499. COMPLAIN_RET_FALSE_IF(nullptr == hero, "Invalid hero index");
  2500. const CGTownInstance * town = hero->getVisitedTown();
  2501. COMPLAIN_RET_FALSE_IF(nullptr == town, "Hero not in town");
  2502. if (aid==ArtifactID::SPELLBOOK)
  2503. {
  2504. if ((!town->hasBuilt(BuildingID::MAGES_GUILD_1) && complain("Cannot buy a spellbook, no mage guild in the town!"))
  2505. || (gameInfo().getResource(hero->getOwner(), EGameResID::GOLD) < GameConstants::SPELLBOOK_GOLD_COST && complain("Cannot buy a spellbook, not enough gold!"))
  2506. || (hero->getArt(ArtifactPosition::SPELLBOOK) && complain("Cannot buy a spellbook, hero already has a one!"))
  2507. )
  2508. return false;
  2509. giveResource(hero->getOwner(),EGameResID::GOLD,-GameConstants::SPELLBOOK_GOLD_COST);
  2510. giveHeroNewArtifact(hero, ArtifactID::SPELLBOOK, ArtifactPosition::SPELLBOOK);
  2511. assert(hero->getArt(ArtifactPosition::SPELLBOOK));
  2512. giveSpells(town,hero);
  2513. return true;
  2514. }
  2515. else
  2516. {
  2517. const CArtifact * art = aid.toArtifact();
  2518. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid artifact index to buy");
  2519. COMPLAIN_RET_FALSE_IF(art->getWarMachine() == CreatureID::NONE, "War machine artifact required");
  2520. COMPLAIN_RET_FALSE_IF(hero->hasArt(aid),"Hero already has this machine!");
  2521. const int price = art->getPrice();
  2522. COMPLAIN_RET_FALSE_IF(gameInfo().getPlayerState(hero->getOwner())->resources[EGameResID::GOLD] < price, "Not enough gold!");
  2523. if(town->isWarMachineAvailable(aid))
  2524. {
  2525. bool hasFreeSlot = false;
  2526. for(auto slot : art->getPossibleSlots().at(ArtBearer::HERO))
  2527. if (hero->getArt(slot) == nullptr)
  2528. hasFreeSlot = true;
  2529. if (!hasFreeSlot)
  2530. {
  2531. auto slot = art->getPossibleSlots().at(ArtBearer::HERO).front();
  2532. removeArtifact(ArtifactLocation(hero->id, slot));
  2533. }
  2534. giveResource(hero->getOwner(),EGameResID::GOLD,-price);
  2535. return giveHeroNewArtifact(hero, aid, ArtifactPosition::FIRST_AVAILABLE);
  2536. }
  2537. else
  2538. COMPLAIN_RET("This machine is unavailable here!");
  2539. }
  2540. }
  2541. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, GameResID rid, ArtifactID aid)
  2542. {
  2543. if(!h)
  2544. COMPLAIN_RET("Only hero can buy artifacts!");
  2545. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_ARTIFACT), aid))
  2546. COMPLAIN_RET("That artifact is unavailable!");
  2547. int b1;
  2548. int b2;
  2549. m->getOffer(rid, aid, b1, b2, EMarketMode::RESOURCE_ARTIFACT);
  2550. if (gameInfo().getResource(h->tempOwner, rid) < b1)
  2551. COMPLAIN_RET("You can't afford to buy this artifact!");
  2552. giveResource(h->tempOwner, rid, -b1);
  2553. SetAvailableArtifacts saa;
  2554. if(dynamic_cast<const CGTownInstance *>(m))
  2555. {
  2556. saa.id = ObjectInstanceID::NONE;
  2557. saa.arts = gameState().getMap().townMerchantArtifacts;
  2558. }
  2559. else if(const auto *bm = dynamic_cast<const CGBlackMarket *>(m)) //black market
  2560. {
  2561. saa.id = bm->id;
  2562. saa.arts = bm->artifacts;
  2563. }
  2564. else
  2565. COMPLAIN_RET("Wrong marktet...");
  2566. bool found = false;
  2567. for (ArtifactID & art : saa.arts)
  2568. {
  2569. if (art == aid)
  2570. {
  2571. art = ArtifactID();
  2572. found = true;
  2573. break;
  2574. }
  2575. }
  2576. if (!found)
  2577. COMPLAIN_RET("Cannot find selected artifact on the list");
  2578. sendAndApply(saa);
  2579. giveHeroNewArtifact(h, aid, ArtifactPosition::FIRST_AVAILABLE);
  2580. return true;
  2581. }
  2582. bool CGameHandler::sellArtifact(const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid)
  2583. {
  2584. COMPLAIN_RET_FALSE_IF((!h), "Only hero can sell artifacts!");
  2585. const CArtifactInstance *art = h->getArtByInstanceId(aid);
  2586. COMPLAIN_RET_FALSE_IF((!art), "There is no artifact to sell!");
  2587. COMPLAIN_RET_FALSE_IF((!art->getType()->isTradable()), "Cannot sell a war machine or spellbook!");
  2588. int resVal = 0;
  2589. int dump = 1;
  2590. m->getOffer(art->getType()->getId(), rid, dump, resVal, EMarketMode::ARTIFACT_RESOURCE);
  2591. removeArtifact(ArtifactLocation(h->id, h->getArtPos(art)));
  2592. giveResource(h->tempOwner, rid, resVal);
  2593. return true;
  2594. }
  2595. bool CGameHandler::buySecSkill(const IMarket *m, const CGHeroInstance *h, SecondarySkill skill)
  2596. {
  2597. if (!h)
  2598. COMPLAIN_RET("You need hero to buy a skill!");
  2599. if (h->getSecSkillLevel(SecondarySkill(skill)))
  2600. COMPLAIN_RET("Hero already know this skill");
  2601. if (!h->canLearnSkill())
  2602. COMPLAIN_RET("Hero can't learn any more skills");
  2603. if (!h->canLearnSkill(skill))
  2604. COMPLAIN_RET("The hero can't learn this skill!");
  2605. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_SKILL), skill))
  2606. COMPLAIN_RET("That skill is unavailable!");
  2607. if (gameInfo().getResource(h->tempOwner, EGameResID::GOLD) < GameConstants::SKILL_GOLD_COST)//TODO: remove hardcoded resource\summ?
  2608. COMPLAIN_RET("You can't afford to buy this skill");
  2609. giveResource(h->tempOwner, EGameResID::GOLD, -GameConstants::SKILL_GOLD_COST);
  2610. changeSecSkill(h, skill, 1, ChangeValueMode::ABSOLUTE);
  2611. return true;
  2612. }
  2613. bool CGameHandler::tradeResources(const IMarket *market, ui32 amountToSell, PlayerColor player, GameResID toSell, GameResID toBuy)
  2614. {
  2615. TResourceCap haveToSell = gameInfo().getPlayerState(player)->resources[toSell];
  2616. vstd::amin(amountToSell, haveToSell); //can't trade more resources than have
  2617. int b1; //base quantities for trade
  2618. int b2;
  2619. market->getOffer(toSell, toBuy, b1, b2, EMarketMode::RESOURCE_RESOURCE);
  2620. int amountToBoy = amountToSell / b1; //how many base quantities we trade
  2621. if (amountToSell % b1 != 0) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2622. {
  2623. COMPLAIN_RET("Invalid deal, not all offered units of resource were used.");
  2624. }
  2625. giveResource(player, toSell, -b1 * amountToBoy);
  2626. giveResource(player, toBuy, b2 * amountToBoy);
  2627. statistics->accumulatedValues[player].tradeVolume[toSell] += -b1 * amountToBoy;
  2628. statistics->accumulatedValues[player].tradeVolume[toBuy] += b2 * amountToBoy;
  2629. return true;
  2630. }
  2631. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID)
  2632. {
  2633. if(!hero)
  2634. COMPLAIN_RET("Only hero can sell creatures!");
  2635. if (!vstd::contains(hero->Slots(), slot))
  2636. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  2637. const CStackInstance &s = hero->getStack(slot);
  2638. if (s.getCount() < static_cast<TQuantity>(count) //can't sell more creatures than have
  2639. || (hero->stacksCount() == 1 && hero->needsLastStack() && s.getCount() == count)) //can't sell last stack
  2640. {
  2641. COMPLAIN_RET("Not enough creatures in army!");
  2642. }
  2643. int b1; //base quantities for trade
  2644. int b2;
  2645. market->getOffer(s.getId(), resourceID, b1, b2, EMarketMode::CREATURE_RESOURCE);
  2646. int units = count / b1; //how many base quantities we trade
  2647. if (count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2648. {
  2649. //TODO: complain?
  2650. assert(0);
  2651. }
  2652. changeStackCount(StackLocation(hero->id, slot), -static_cast<int>(count), ChangeValueMode::RELATIVE);
  2653. giveResource(hero->tempOwner, resourceID, b2 * units);
  2654. return true;
  2655. }
  2656. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot)
  2657. {
  2658. const CArmedInstance *army = nullptr;
  2659. if (hero)
  2660. army = hero;
  2661. else
  2662. army = dynamic_cast<const CGTownInstance *>(market);
  2663. if (!army)
  2664. COMPLAIN_RET("Incorrect call to transform in undead!");
  2665. if (!army->hasStackAtSlot(slot))
  2666. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  2667. const CStackInstance &s = army->getStack(slot);
  2668. //resulting creature - bone dragons or skeletons
  2669. CreatureID resCreature = CreatureID::SKELETON;
  2670. auto customTargerBonus = s.getBonusesOfType(BonusType::SKELETON_TRANSFORMER_TARGET);
  2671. if (!customTargerBonus->empty())
  2672. resCreature = customTargerBonus->front()->subtype.as<CreatureID>();
  2673. changeStackType(StackLocation(army->id, slot), resCreature.toCreature());
  2674. return true;
  2675. }
  2676. bool CGameHandler::sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2)
  2677. {
  2678. const PlayerState *p2 = gameInfo().getPlayerState(r2, false);
  2679. if (!p2 || p2->status != EPlayerStatus::INGAME)
  2680. {
  2681. complain("Dest player must be in game!");
  2682. return false;
  2683. }
  2684. TResourceCap curRes1 = gameInfo().getPlayerState(player)->resources[r1];
  2685. vstd::amin(val, curRes1);
  2686. giveResource(player, r1, -static_cast<int>(val));
  2687. giveResource(r2, r1, val);
  2688. return true;
  2689. }
  2690. bool CGameHandler::setFormation(ObjectInstanceID hid, EArmyFormation formation)
  2691. {
  2692. const CGHeroInstance *h = gameInfo().getHero(hid);
  2693. if (!h)
  2694. {
  2695. logGlobal->error("Hero doesn't exist!");
  2696. return false;
  2697. }
  2698. ChangeFormation cf;
  2699. cf.hid = hid;
  2700. cf.formation = formation;
  2701. sendAndApply(cf);
  2702. return true;
  2703. }
  2704. bool CGameHandler::queryReply(QueryID qid, std::optional<int32_t> answer, PlayerColor player)
  2705. {
  2706. logGlobal->trace("Player %s attempts answering query %d with answer:", player, qid);
  2707. if (answer)
  2708. logGlobal->trace("%d", *answer);
  2709. auto topQuery = queries->topQuery(player);
  2710. COMPLAIN_RET_FALSE_IF(!topQuery, "This player doesn't have any queries!");
  2711. if(topQuery->queryID != qid)
  2712. {
  2713. auto currentQuery = queries->getQuery(qid);
  2714. if(currentQuery != nullptr && currentQuery->endsByPlayerAnswer())
  2715. currentQuery->setReply(answer);
  2716. COMPLAIN_RET("This player top query has different ID!"); //topQuery->queryID != qid
  2717. }
  2718. COMPLAIN_RET_FALSE_IF(!topQuery->endsByPlayerAnswer(), "This query cannot be ended by player's answer!");
  2719. topQuery->setReply(answer);
  2720. queries->popQuery(topQuery);
  2721. return true;
  2722. }
  2723. bool CGameHandler::complain(const std::string &problem)
  2724. {
  2725. #ifndef ENABLE_GOLDMASTER
  2726. MetaString str;
  2727. str.appendTextID("vcmi.broadcast.serverProblem");
  2728. str.appendRawString(": ");
  2729. str.appendRawString(problem);
  2730. playerMessages->broadcastSystemMessage(str);
  2731. #endif
  2732. logGlobal->error(problem);
  2733. return true;
  2734. }
  2735. void CGameHandler::showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits)
  2736. {
  2737. const auto * upperArmy = dynamic_cast<const CArmedInstance*>(gameInfo().getObj(upobj));
  2738. const auto * lowerArmy = dynamic_cast<const CArmedInstance*>(gameInfo().getObj(hid));
  2739. assert(lowerArmy);
  2740. assert(upperArmy);
  2741. auto garrisonQuery = std::make_shared<CGarrisonDialogQuery>(this, upperArmy, lowerArmy);
  2742. queries->addQuery(garrisonQuery);
  2743. GarrisonDialog gd;
  2744. gd.hid = hid;
  2745. gd.objid = upobj;
  2746. gd.removableUnits = removableUnits;
  2747. gd.queryID = garrisonQuery->queryID;
  2748. sendAndApply(gd);
  2749. }
  2750. void CGameHandler::showObjectWindow(const CGObjectInstance * object, EOpenWindowMode window, const CGHeroInstance * visitor, bool addQuery)
  2751. {
  2752. OpenWindow pack;
  2753. pack.window = window;
  2754. pack.object = object->id;
  2755. pack.visitor = visitor->id;
  2756. if (addQuery)
  2757. {
  2758. auto windowQuery = std::make_shared<OpenWindowQuery>(this, visitor, window);
  2759. pack.queryID = windowQuery->queryID;
  2760. queries->addQuery(windowQuery);
  2761. }
  2762. sendAndApply(pack);
  2763. }
  2764. bool CGameHandler::isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2)
  2765. {
  2766. if (id1 == id2)
  2767. return true;
  2768. const CGObjectInstance *o1 = gameInfo().getObj(id1);
  2769. const CGObjectInstance *o2 = gameInfo().getObj(id2);
  2770. if (!o1 || !o2)
  2771. return true; //arranging stacks within an object should be always allowed
  2772. if (o1 && o2)
  2773. {
  2774. if (o1->ID == Obj::TOWN)
  2775. {
  2776. const auto *t = dynamic_cast<const CGTownInstance*>(o1);
  2777. if (t->getVisitingHero() == o2 || t->getGarrisonHero() == o2)
  2778. return true;
  2779. }
  2780. if (o2->ID == Obj::TOWN)
  2781. {
  2782. const auto *t = dynamic_cast<const CGTownInstance*>(o2);
  2783. if (t->getVisitingHero() == o1 || t->getGarrisonHero() == o1)
  2784. return true;
  2785. }
  2786. const auto * market = gameState().getMarket(id1);
  2787. if(market == nullptr)
  2788. market = gameState().getMarket(id2);
  2789. if(market)
  2790. return market->allowsTrade(EMarketMode::ARTIFACT_EXP);
  2791. if (o1->ID == Obj::HERO && o2->ID == Obj::HERO)
  2792. {
  2793. const auto *h1 = dynamic_cast<const CGHeroInstance*>(o1);
  2794. const auto *h2 = dynamic_cast<const CGHeroInstance*>(o2);
  2795. // two heroes in same town (garrisoned and visiting)
  2796. if (h1->getVisitedTown() != nullptr && h2->getVisitedTown() != nullptr && h1->getVisitedTown() == h2->getVisitedTown())
  2797. return true;
  2798. }
  2799. //Ongoing garrison exchange - usually picking from top garison (from o1 to o2), but who knows
  2800. auto dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries->topQuery(o1->tempOwner));
  2801. if (!dialog)
  2802. {
  2803. dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries->topQuery(o2->tempOwner));
  2804. }
  2805. if (dialog)
  2806. {
  2807. const auto * topArmy = dialog->exchangingArmies.at(0);
  2808. const auto * bottomArmy = dialog->exchangingArmies.at(1);
  2809. if ((topArmy == o1 && bottomArmy == o2) || (bottomArmy == o1 && topArmy == o2))
  2810. return true;
  2811. }
  2812. }
  2813. return false;
  2814. }
  2815. void CGameHandler::objectVisited(const CGObjectInstance * obj, const CGHeroInstance * h)
  2816. {
  2817. using events::ObjectVisitStarted;
  2818. logGlobal->debug("%s visits %s (%d)", h->nodeName(), obj->getObjectName(), obj->ID);
  2819. if (getVisitingHero(obj) != nullptr)
  2820. {
  2821. logGlobal->error("Attempt to visit object that is being visited by another hero!");
  2822. throw std::runtime_error("Can not visit object that is being visited");
  2823. }
  2824. std::shared_ptr<MapObjectVisitQuery> visitQuery;
  2825. auto startVisit = [&](ObjectVisitStarted & event)
  2826. {
  2827. const auto * visitedObject = obj;
  2828. if(obj->ID == Obj::HERO)
  2829. {
  2830. const auto * visitedHero = dynamic_cast<const CGHeroInstance *>(obj);
  2831. const auto * visitedTown = visitedHero->getVisitedTown();
  2832. if(visitedTown)
  2833. {
  2834. const bool isEnemy = visitedHero->getOwner() != h->getOwner();
  2835. if(isEnemy && !visitedTown->isBattleOutsideTown(visitedHero))
  2836. visitedObject = visitedTown;
  2837. }
  2838. }
  2839. visitQuery = std::make_shared<MapObjectVisitQuery>(this, visitedObject, h);
  2840. queries->addQuery(visitQuery); //TODO real visit pos
  2841. HeroVisit hv;
  2842. hv.objId = obj->id;
  2843. hv.heroId = h->id;
  2844. hv.player = h->tempOwner;
  2845. hv.starting = true;
  2846. sendAndApply(hv);
  2847. obj->onHeroVisit(*this, h);
  2848. };
  2849. ObjectVisitStarted::defaultExecute(serverEventBus.get(), startVisit, h->tempOwner, h->id, obj->id);
  2850. if(visitQuery)
  2851. queries->popIfTop(visitQuery); //visit ends here if no queries were created
  2852. }
  2853. void CGameHandler::objectVisitEnded(const ObjectInstanceID & heroObjectID, PlayerColor player)
  2854. {
  2855. using events::ObjectVisitEnded;
  2856. auto endVisit = [&](ObjectVisitEnded & event)
  2857. {
  2858. HeroVisit hv;
  2859. hv.player = event.getPlayer();
  2860. hv.heroId = event.getHero();
  2861. hv.starting = false;
  2862. sendAndApply(hv);
  2863. };
  2864. //TODO: ObjectVisitEnded should also have id of visited object,
  2865. //but this requires object being deleted only by `removeAfterVisit()` but not `removeObject()`
  2866. ObjectVisitEnded::defaultExecute(serverEventBus.get(), endVisit, player, heroObjectID);
  2867. }
  2868. bool CGameHandler::buildBoat(ObjectInstanceID objid, PlayerColor playerID)
  2869. {
  2870. const auto *obj = dynamic_cast<const IShipyard *>(gameInfo().getObj(objid));
  2871. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  2872. {
  2873. complain("Cannot build boat in this shipyard!");
  2874. return false;
  2875. }
  2876. TResources boatCost;
  2877. obj->getBoatCost(boatCost);
  2878. TResources available = gameInfo().getPlayerState(playerID)->resources;
  2879. if (!available.canAfford(boatCost))
  2880. {
  2881. complain("Not enough resources to build a boat!");
  2882. return false;
  2883. }
  2884. int3 tile = obj->bestLocation();
  2885. if (!gameState().getMap().isInTheMap(tile))
  2886. {
  2887. complain("Cannot find appropriate tile for a boat!");
  2888. return false;
  2889. }
  2890. giveResources(playerID, -boatCost);
  2891. createBoat(tile, obj->getBoatType(), playerID);
  2892. return true;
  2893. }
  2894. void CGameHandler::checkVictoryLossConditions(const std::set<PlayerColor> & playerColors)
  2895. {
  2896. for (auto playerColor : playerColors)
  2897. {
  2898. if (gameInfo().getPlayerState(playerColor, false))
  2899. checkVictoryLossConditionsForPlayer(playerColor);
  2900. }
  2901. }
  2902. void CGameHandler::checkVictoryLossConditionsForAll()
  2903. {
  2904. std::set<PlayerColor> playerColors;
  2905. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  2906. {
  2907. playerColors.insert(PlayerColor(i));
  2908. }
  2909. checkVictoryLossConditions(playerColors);
  2910. }
  2911. void CGameHandler::checkVictoryLossConditionsForPlayer(PlayerColor player)
  2912. {
  2913. const PlayerState * p = gameInfo().getPlayerState(player);
  2914. if(!p || p->status != EPlayerStatus::INGAME) return;
  2915. auto victoryLossCheckResult = gameState().checkForVictoryAndLoss(player);
  2916. if (victoryLossCheckResult.victory() || victoryLossCheckResult.loss())
  2917. {
  2918. InfoWindow iw;
  2919. getVictoryLossMessage(player, victoryLossCheckResult, iw);
  2920. sendAndApply(iw);
  2921. PlayerEndsGame peg;
  2922. peg.player = player;
  2923. peg.victoryLossCheckResult = victoryLossCheckResult;
  2924. peg.statistic = *statistics;
  2925. addStatistics(peg.statistic); // add last turn befor win / loss
  2926. sendAndApply(peg);
  2927. if (victoryLossCheckResult.victory())
  2928. {
  2929. //one player won -> all enemies lost
  2930. for (const auto & playerIt : gameState().players)
  2931. {
  2932. if (playerIt.first != player && gameInfo().getPlayerState(playerIt.first)->status == EPlayerStatus::INGAME)
  2933. {
  2934. peg.player = playerIt.first;
  2935. peg.victoryLossCheckResult = gameInfo().getPlayerRelations(player, playerIt.first) == PlayerRelations::ALLIES ?
  2936. victoryLossCheckResult : victoryLossCheckResult.invert(); // ally of winner
  2937. InfoWindow iwOthers;
  2938. getVictoryLossMessage(player, peg.victoryLossCheckResult, iwOthers);
  2939. iwOthers.player = playerIt.first;
  2940. sendAndApply(iwOthers);
  2941. sendAndApply(peg);
  2942. }
  2943. }
  2944. if(p->human)
  2945. {
  2946. gameServer().setState(EServerState::SHUTDOWN);
  2947. }
  2948. }
  2949. else
  2950. {
  2951. // give turn to next player(s)
  2952. turnOrder->onPlayerEndsGame(player);
  2953. //copy heroes vector to avoid iterator invalidation as removal change PlayerState
  2954. auto hlp = p->getHeroes();
  2955. for (const auto * h : hlp) //eliminate heroes
  2956. {
  2957. if (h)
  2958. removeObject(h, player);
  2959. }
  2960. //player lost -> all his objects become unflagged (neutral)
  2961. for (const auto * obj : gameState().getMap().getObjects()) //unflag objs
  2962. {
  2963. if (obj && obj->tempOwner == player)
  2964. setOwner(obj, PlayerColor::NEUTRAL);
  2965. }
  2966. //eliminating one player may cause victory of another:
  2967. std::set<PlayerColor> playerColors;
  2968. //do not copy player state (CBonusSystemNode) by value
  2969. for (const auto &playerState : gameState().players) //players may have different colors, iterate over players and not integers
  2970. {
  2971. if (playerState.first != player)
  2972. playerColors.insert(playerState.first);
  2973. }
  2974. //notify all players
  2975. for (auto pc : playerColors)
  2976. {
  2977. if (gameInfo().getPlayerState(pc)->status == EPlayerStatus::INGAME)
  2978. {
  2979. InfoWindow iwOthers;
  2980. getVictoryLossMessage(player, victoryLossCheckResult.invert(), iwOthers);
  2981. iwOthers.player = pc;
  2982. sendAndApply(iwOthers);
  2983. }
  2984. }
  2985. checkVictoryLossConditions(playerColors);
  2986. }
  2987. }
  2988. }
  2989. void CGameHandler::getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const
  2990. {
  2991. out.player = player;
  2992. out.text = victoryLossCheckResult.messageToSelf;
  2993. out.text.replaceName(player);
  2994. out.components.emplace_back(ComponentType::FLAG, player);
  2995. }
  2996. bool CGameHandler::dig(const CGHeroInstance *h)
  2997. {
  2998. if (h->diggingStatus() != EDiggingStatus::CAN_DIG) //checks for terrain and movement
  2999. COMPLAIN_RETF("Hero cannot dig (error code %d)!", static_cast<int>(h->diggingStatus()));
  3000. createHole(h->visitablePos(), h->getOwner());
  3001. //take MPs
  3002. SetMovePoints smp;
  3003. smp.hid = h->id;
  3004. smp.val = 0;
  3005. sendAndApply(smp);
  3006. InfoWindow iw;
  3007. iw.type = EInfoWindowMode::AUTO;
  3008. iw.player = h->tempOwner;
  3009. if (gameState().getMap().grailPos == h->visitablePos())
  3010. {
  3011. ArtifactID grail = ArtifactID::GRAIL;
  3012. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the " ...
  3013. iw.text.appendName(grail); // ... " The Grail"
  3014. iw.soundID = soundBase::ULTIMATEARTIFACT;
  3015. giveHeroNewArtifact(h, grail, ArtifactPosition::FIRST_AVAILABLE); //give grail
  3016. sendAndApply(iw);
  3017. iw.soundID = soundBase::invalid;
  3018. iw.components.emplace_back(ComponentType::ARTIFACT, grail);
  3019. iw.text.clear();
  3020. iw.text.appendTextID(grail.toArtifact()->getDescriptionTextID());
  3021. sendAndApply(iw);
  3022. }
  3023. else
  3024. {
  3025. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  3026. iw.soundID = soundBase::Dig;
  3027. sendAndApply(iw);
  3028. }
  3029. return true;
  3030. }
  3031. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  3032. {
  3033. if (!t.visitableObjects.empty())
  3034. {
  3035. //to prevent self-visiting heroes on space press
  3036. if (t.visitableObjects.back() != h->id)
  3037. objectVisited(gameState().getObjInstance(t.visitableObjects.back()), h);
  3038. else if (t.visitableObjects.size() > 1)
  3039. objectVisited(gameState().getObjInstance(*(t.visitableObjects.end()-2)),h);
  3040. }
  3041. }
  3042. bool CGameHandler::sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count)
  3043. {
  3044. if (!hero)
  3045. COMPLAIN_RET("You need hero to sacrifice creature!");
  3046. int expSum = 0;
  3047. auto finish = [this, &hero, &expSum]()
  3048. {
  3049. giveExperience(hero, hero->calculateXp(expSum));
  3050. };
  3051. for(int i = 0; i < slot.size(); ++i)
  3052. {
  3053. int oldCount = hero->getStackCount(slot[i]);
  3054. if(oldCount < static_cast<int>(count[i]))
  3055. {
  3056. finish();
  3057. COMPLAIN_RET("Not enough creatures to sacrifice!")
  3058. }
  3059. else if(oldCount == count[i] && hero->stacksCount() == 1 && hero->needsLastStack())
  3060. {
  3061. finish();
  3062. COMPLAIN_RET("Cannot sacrifice last creature!");
  3063. }
  3064. int crid = hero->getStack(slot[i]).getId();
  3065. changeStackCount(StackLocation(hero->id, slot[i]), -(TQuantity)count[i], ChangeValueMode::RELATIVE);
  3066. int dump;
  3067. int exp;
  3068. market->getOffer(crid, 0, dump, exp, EMarketMode::CREATURE_EXP);
  3069. exp *= count[i];
  3070. expSum += exp;
  3071. }
  3072. finish();
  3073. return true;
  3074. }
  3075. bool CGameHandler::sacrificeArtifact(const IMarket * market, const CGHeroInstance * hero, const std::vector<ArtifactInstanceID> & arts)
  3076. {
  3077. if (!hero)
  3078. COMPLAIN_RET("You need hero to sacrifice artifact!");
  3079. if(hero->getAlignment() == EAlignment::EVIL)
  3080. COMPLAIN_RET("Evil hero can't sacrifice artifact!");
  3081. assert(market);
  3082. const auto * artSet = market->getArtifactsStorage();
  3083. int expSum = 0;
  3084. std::vector<ArtifactPosition> artPack;
  3085. auto finish = [this, &hero, &expSum, &artPack, market]()
  3086. {
  3087. removeArtifact(market->getObjInstanceID(), artPack);
  3088. giveExperience(hero, hero->calculateXp(expSum));
  3089. };
  3090. for(const auto & artInstId : arts)
  3091. {
  3092. if(const auto * art = artSet->getArtByInstanceId(artInstId))
  3093. {
  3094. if(art->getType()->isTradable())
  3095. {
  3096. int dmp;
  3097. int expToGive;
  3098. market->getOffer(art->getTypeId(), 0, dmp, expToGive, EMarketMode::ARTIFACT_EXP);
  3099. expSum += expToGive;
  3100. artPack.push_back(artSet->getArtPos(art));
  3101. }
  3102. else
  3103. {
  3104. COMPLAIN_RET("Cannot sacrifice not tradable artifact!");
  3105. }
  3106. }
  3107. else
  3108. {
  3109. finish();
  3110. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  3111. }
  3112. }
  3113. finish();
  3114. return true;
  3115. }
  3116. bool CGameHandler::insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count)
  3117. {
  3118. const auto * army = dynamic_cast<const CArmedInstance*>(gameInfo().getObj(sl.army));
  3119. if (army->hasStackAtSlot(sl.slot))
  3120. COMPLAIN_RET("Slot is already taken!");
  3121. if (!sl.slot.validSlot())
  3122. COMPLAIN_RET("Cannot insert stack to that slot!");
  3123. InsertNewStack ins;
  3124. ins.army = army->id;
  3125. ins.slot = sl.slot;
  3126. ins.type = c->getId();
  3127. ins.count = count;
  3128. sendAndApply(ins);
  3129. return true;
  3130. }
  3131. bool CGameHandler::eraseStack(const StackLocation &sl, bool forceRemoval)
  3132. {
  3133. const auto * army = dynamic_cast<const CArmedInstance*>(gameInfo().getObj(sl.army));
  3134. if (!army->hasStackAtSlot(sl.slot))
  3135. COMPLAIN_RET("Cannot find a stack to erase");
  3136. if (army->stacksCount() == 1 //from the last stack
  3137. && army->needsLastStack() //that must be left
  3138. && !forceRemoval) //ignore above conditions if we are forcing removal
  3139. {
  3140. COMPLAIN_RET("Cannot erase the last stack!");
  3141. }
  3142. EraseStack es;
  3143. es.army = army->id;
  3144. es.slot = sl.slot;
  3145. sendAndApply(es);
  3146. return true;
  3147. }
  3148. bool CGameHandler::changeStackCount(const StackLocation &sl, TQuantity count, ChangeValueMode mode)
  3149. {
  3150. const auto * army = dynamic_cast<const CArmedInstance*>(gameInfo().getObj(sl.army));
  3151. TQuantity currentCount = army->getStackCount(sl.slot);
  3152. if ((mode == ChangeValueMode::ABSOLUTE && count < 0)
  3153. || (mode == ChangeValueMode::RELATIVE && -count > currentCount))
  3154. {
  3155. COMPLAIN_RET("Cannot take more stacks than present!");
  3156. }
  3157. if ((currentCount == -count && mode == ChangeValueMode::RELATIVE)
  3158. || (count == 0 && mode == ChangeValueMode::ABSOLUTE))
  3159. {
  3160. eraseStack(sl);
  3161. }
  3162. else
  3163. {
  3164. ChangeStackCount csc;
  3165. csc.army = army->id;
  3166. csc.slot = sl.slot;
  3167. csc.count = count;
  3168. csc.mode = mode;
  3169. sendAndApply(csc);
  3170. }
  3171. return true;
  3172. }
  3173. bool CGameHandler::addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count)
  3174. {
  3175. const auto * army = dynamic_cast<const CArmedInstance*>(gameInfo().getObj(sl.army));
  3176. const CCreature *slotC = army->getCreature(sl.slot);
  3177. if (!slotC) //slot is empty
  3178. insertNewStack(sl, c, count);
  3179. else if (c == slotC)
  3180. changeStackCount(sl, count, ChangeValueMode::RELATIVE);
  3181. else
  3182. {
  3183. COMPLAIN_RET("Cannot add " + c->getNamePluralTranslated() + " to slot " + boost::lexical_cast<std::string>(sl.slot) + "!");
  3184. }
  3185. return true;
  3186. }
  3187. void CGameHandler::tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging)
  3188. {
  3189. if (removeObjWhenFinished)
  3190. removeAfterVisit(src->id);
  3191. if (!src->canBeMergedWith(*dst, allowMerging))
  3192. {
  3193. if (allowMerging) //do that, add all matching creatures.
  3194. {
  3195. bool cont = true;
  3196. while (cont)
  3197. {
  3198. for (auto i = src->stacks.begin(); i != src->stacks.end(); i++)//while there are unmoved creatures
  3199. {
  3200. SlotID pos = dst->getSlotFor(i->second->getCreature());
  3201. if (pos.validSlot())
  3202. {
  3203. moveStack(StackLocation(src->id, i->first), StackLocation(dst->id, pos));
  3204. cont = true;
  3205. break; //or iterator crashes
  3206. }
  3207. cont = false;
  3208. }
  3209. }
  3210. }
  3211. showGarrisonDialog(src->id, dst->id, true); //show garrison window and optionally remove ourselves from map when player ends
  3212. }
  3213. else //merge
  3214. {
  3215. moveArmy(src, dst, allowMerging);
  3216. }
  3217. }
  3218. bool CGameHandler::moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count)
  3219. {
  3220. const auto * srcArmy = dynamic_cast<const CArmedInstance*>(gameInfo().getObj(src.army));
  3221. const auto * dstArmy = dynamic_cast<const CArmedInstance*>(gameInfo().getObj(dst.army));
  3222. if (!srcArmy->hasStackAtSlot(src.slot))
  3223. COMPLAIN_RET("No stack to move!");
  3224. if (dstArmy->hasStackAtSlot(dst.slot) && dstArmy->getCreature(dst.slot) != srcArmy->getCreature(src.slot))
  3225. COMPLAIN_RET("Cannot move: stack of different type at destination pos!");
  3226. if (!dst.slot.validSlot())
  3227. COMPLAIN_RET("Cannot move stack to that slot!");
  3228. if (count == -1)
  3229. {
  3230. count = srcArmy->getStackCount(src.slot);
  3231. }
  3232. if (srcArmy != dstArmy //moving away
  3233. && count == srcArmy->getStackCount(src.slot) //all creatures
  3234. && srcArmy->stacksCount() == 1 //from the last stack
  3235. && srcArmy->needsLastStack()) //that must be left
  3236. {
  3237. COMPLAIN_RET("Cannot move away the last creature!");
  3238. }
  3239. RebalanceStacks rs;
  3240. rs.srcArmy = srcArmy->id;
  3241. rs.dstArmy = dstArmy->id;
  3242. rs.srcSlot = src.slot;
  3243. rs.dstSlot = dst.slot;
  3244. rs.count = count;
  3245. sendAndApply(rs);
  3246. return true;
  3247. }
  3248. void CGameHandler::castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos)
  3249. {
  3250. if (!spellID.hasValue())
  3251. return;
  3252. AdventureSpellCastParameters p;
  3253. p.caster = caster;
  3254. p.pos = pos;
  3255. const CSpell * s = spellID.toSpell();
  3256. s->adventureCast(spellEnv.get(), p);
  3257. if(const auto * hero = caster->getHeroCaster())
  3258. useChargeBasedSpell(hero->id, spellID);
  3259. }
  3260. bool CGameHandler::swapStacks(const StackLocation & sl1, const StackLocation & sl2)
  3261. {
  3262. const auto * army1 = dynamic_cast<const CArmedInstance*>(gameInfo().getObj(sl1.army));
  3263. const auto * army2 = dynamic_cast<const CArmedInstance*>(gameInfo().getObj(sl2.army));
  3264. if(!army1->hasStackAtSlot(sl1.slot))
  3265. {
  3266. return moveStack(sl2, sl1);
  3267. }
  3268. else if(!army2->hasStackAtSlot(sl2.slot))
  3269. {
  3270. return moveStack(sl1, sl2);
  3271. }
  3272. else
  3273. {
  3274. SwapStacks ss;
  3275. ss.srcArmy = army1->id;
  3276. ss.dstArmy = army2->id;
  3277. ss.srcSlot = sl1.slot;
  3278. ss.dstSlot = sl2.slot;
  3279. sendAndApply(ss);
  3280. return true;
  3281. }
  3282. }
  3283. bool CGameHandler::putArtifact(const ArtifactLocation & al, const ArtifactInstanceID & id, std::optional<bool> askAssemble)
  3284. {
  3285. const auto * artInst = gameInfo().getArtInstance(id);
  3286. assert(artInst && artInst->getType());
  3287. ArtifactLocation dst(al.artHolder, ArtifactPosition::PRE_FIRST);
  3288. dst.creature = al.creature;
  3289. const auto * putTo = gameState().getArtSet(al);
  3290. assert(putTo);
  3291. if(al.slot == ArtifactPosition::FIRST_AVAILABLE)
  3292. {
  3293. dst.slot = ArtifactUtils::getArtAnyPosition(putTo, artInst->getTypeId());
  3294. }
  3295. else if(ArtifactUtils::isSlotBackpack(al.slot) && !al.creature.has_value())
  3296. {
  3297. dst.slot = ArtifactUtils::getArtBackpackPosition(putTo, artInst->getTypeId());
  3298. }
  3299. else
  3300. {
  3301. dst.slot = al.slot;
  3302. }
  3303. if(!askAssemble.has_value())
  3304. {
  3305. if(!dst.creature.has_value() && ArtifactUtils::isSlotEquipment(dst.slot))
  3306. askAssemble = true;
  3307. else
  3308. askAssemble = false;
  3309. }
  3310. if(artInst->canBePutAt(putTo, dst.slot))
  3311. {
  3312. PutArtifact pa(id, dst, askAssemble.value());
  3313. sendAndApply(pa);
  3314. return true;
  3315. }
  3316. else
  3317. {
  3318. return false;
  3319. }
  3320. }
  3321. bool CGameHandler::giveHeroNewArtifact(
  3322. const CGHeroInstance * h, const CArtifact * artType, const SpellID & spellId, const ArtifactPosition & pos)
  3323. {
  3324. assert(artType);
  3325. NewArtifact na;
  3326. na.artHolder = h->id;
  3327. na.artId = artType->getId();
  3328. na.spellId = spellId;
  3329. na.pos = pos;
  3330. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  3331. {
  3332. na.pos = ArtifactUtils::getArtAnyPosition(h, artType->getId());
  3333. if(!artType->canBePutAt(h, na.pos))
  3334. COMPLAIN_RET("Cannot put artifact in that slot!");
  3335. }
  3336. else if(ArtifactUtils::isSlotBackpack(pos))
  3337. {
  3338. if(!artType->canBePutAt(h, ArtifactUtils::getArtBackpackPosition(h, artType->getId())))
  3339. COMPLAIN_RET("Cannot put artifact in that slot!");
  3340. }
  3341. else
  3342. {
  3343. COMPLAIN_RET_FALSE_IF(!artType->canBePutAt(h, pos, false), "Cannot put artifact in that slot!");
  3344. }
  3345. sendAndApply(na);
  3346. return true;
  3347. }
  3348. bool CGameHandler::giveHeroNewArtifact(const CGHeroInstance * h, const ArtifactID & artId, const ArtifactPosition & pos)
  3349. {
  3350. return giveHeroNewArtifact(h, artId.toArtifact(), SpellID::NONE, pos);
  3351. }
  3352. bool CGameHandler::giveHeroNewScroll(const CGHeroInstance * h, const SpellID & spellId, const ArtifactPosition & pos)
  3353. {
  3354. return giveHeroNewArtifact(h, ArtifactID(ArtifactID::SPELL_SCROLL).toArtifact(), spellId, pos);
  3355. }
  3356. void CGameHandler::spawnWanderingMonsters(CreatureID creatureID)
  3357. {
  3358. std::vector<int3>::iterator tile;
  3359. std::vector<int3> tiles;
  3360. gameState().getFreeTiles(tiles, true);
  3361. ui32 amount = tiles.size() / 100; //Chance is 1% for each tile. Higher than the original 0.5% because there are fewer with nearby unguarded
  3362. RandomGeneratorUtil::randomShuffle(tiles, getRandomGenerator());
  3363. logGlobal->trace("Spawning wandering monsters. Found %d free tiles. Creature type: %d", tiles.size(), creatureID.num);
  3364. const CCreature *cre = creatureID.toCreature();
  3365. for (int i = 0; i < amount; ++i)
  3366. {
  3367. tile = tiles.begin();
  3368. logGlobal->trace("\tSpawning monster at %s", tile->toString());
  3369. auto count = cre->getRandomAmount(getRandomGenerator());
  3370. createWanderingMonster(*tile, creatureID, count);
  3371. tiles.erase(tile); //not use it again
  3372. }
  3373. }
  3374. bool CGameHandler::isBlockedByQueries(const CPackForServer *pack, PlayerColor player)
  3375. {
  3376. if (dynamic_cast<const PlayerMessage *>(pack) != nullptr)
  3377. return false;
  3378. if (dynamic_cast<const SaveLocalState *>(pack) != nullptr)
  3379. return false;
  3380. auto query = queries->topQuery(player);
  3381. if (query && query->blocksPack(pack))
  3382. {
  3383. complain(boost::str(boost::format(
  3384. "\r\n| Player \"%s\" has to answer queries before attempting any further actions.\r\n| Top Query: \"%s\"\r\n")
  3385. % boost::to_upper_copy<std::string>(player.toString())
  3386. % query->toString()
  3387. ));
  3388. return true;
  3389. }
  3390. return false;
  3391. }
  3392. void CGameHandler::removeAfterVisit(const ObjectInstanceID & id)
  3393. {
  3394. //If the object is being visited, there must be a matching query
  3395. for (const auto &query : queries->allQueries())
  3396. {
  3397. if (auto someVistQuery = std::dynamic_pointer_cast<MapObjectVisitQuery>(query))
  3398. {
  3399. if (someVistQuery->visitedObject == id)
  3400. {
  3401. someVistQuery->removeObjectAfterVisit = true;
  3402. return;
  3403. }
  3404. }
  3405. }
  3406. //If we haven't returned so far, there is no query and no visit, call was wrong
  3407. throw std::runtime_error("This function needs to be called during the object visit!");
  3408. }
  3409. void CGameHandler::changeFogOfWar(int3 center, ui32 radius, PlayerColor player, ETileVisibility mode)
  3410. {
  3411. FowTilesType tiles;
  3412. if (mode == ETileVisibility::HIDDEN)
  3413. {
  3414. gameInfo().getTilesInRange(tiles, center, radius, ETileVisibility::REVEALED, player);
  3415. }
  3416. else
  3417. {
  3418. gameInfo().getTilesInRange(tiles, center, radius, ETileVisibility::HIDDEN, player);
  3419. }
  3420. changeFogOfWar(tiles, player, mode);
  3421. }
  3422. void CGameHandler::changeFogOfWar(const FowTilesType &tiles, PlayerColor player, ETileVisibility mode)
  3423. {
  3424. if (tiles.empty())
  3425. return;
  3426. FoWChange fow;
  3427. fow.tiles = tiles;
  3428. fow.player = player;
  3429. fow.mode = mode;
  3430. if (mode == ETileVisibility::HIDDEN)
  3431. {
  3432. // do not hide tiles observed by owned objects. May lead to disastrous AI problems
  3433. FowTilesType observedTiles;
  3434. const auto * p = gameInfo().getPlayerState(player);
  3435. for (const auto * obj : p->getOwnedObjects())
  3436. gameInfo().getTilesInRange(observedTiles, obj->getSightCenter(), obj->getSightRadius(), ETileVisibility::REVEALED, obj->getOwner());
  3437. for (auto tile : observedTiles)
  3438. vstd::erase_if_present (fow.tiles, tile);
  3439. }
  3440. if (!fow.tiles.empty())
  3441. sendAndApply(fow);
  3442. }
  3443. const CGHeroInstance * CGameHandler::getVisitingHero(const CGObjectInstance *obj)
  3444. {
  3445. assert(obj);
  3446. for(const auto & query : queries->allQueries())
  3447. {
  3448. auto visit = std::dynamic_pointer_cast<const VisitQuery>(query);
  3449. if (visit && visit->visitedObject == obj->id)
  3450. return gameInfo().getHero(visit->visitingHero);
  3451. }
  3452. return nullptr;
  3453. }
  3454. const CGObjectInstance * CGameHandler::getVisitingObject(const CGHeroInstance *hero)
  3455. {
  3456. assert(hero);
  3457. for(const auto & query : queries->allQueries())
  3458. {
  3459. auto visit = std::dynamic_pointer_cast<const VisitQuery>(query);
  3460. if (visit && visit->visitingHero == hero->id)
  3461. return gameInfo().getObjInstance(visit->visitedObject);
  3462. }
  3463. return nullptr;
  3464. }
  3465. bool CGameHandler::isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero)
  3466. {
  3467. assert(obj);
  3468. assert(hero);
  3469. assert(getVisitingHero(obj) == hero);
  3470. // Check top query of targeted player:
  3471. // If top query is NOT visit to targeted object then we assume that
  3472. // visitation query is covered by other query that must be answered first
  3473. if (auto topQuery = queries->topQuery(hero->getOwner()))
  3474. if (auto visit = std::dynamic_pointer_cast<const VisitQuery>(topQuery))
  3475. return !(visit->visitedObject == obj->id && visit->visitingHero == hero->id);
  3476. return true;
  3477. }
  3478. void CGameHandler::setObjPropertyValue(ObjectInstanceID objid, ObjProperty prop, int32_t value)
  3479. {
  3480. SetObjectProperty sob;
  3481. sob.id = objid;
  3482. sob.what = prop;
  3483. sob.identifier = NumericID(value);
  3484. sendAndApply(sob);
  3485. }
  3486. void CGameHandler::setObjPropertyID(ObjectInstanceID objid, ObjProperty prop, ObjPropertyID identifier)
  3487. {
  3488. SetObjectProperty sob;
  3489. sob.id = objid;
  3490. sob.what = prop;
  3491. sob.identifier = identifier;
  3492. sendAndApply(sob);
  3493. }
  3494. void CGameHandler::setRewardableObjectConfiguration(ObjectInstanceID objid, const Rewardable::Configuration & configuration)
  3495. {
  3496. SetRewardableConfiguration srb;
  3497. srb.objectID = objid;
  3498. srb.configuration = configuration;
  3499. sendAndApply(srb);
  3500. }
  3501. void CGameHandler::setRewardableObjectConfiguration(ObjectInstanceID townInstanceID, BuildingID buildingID, const Rewardable::Configuration & configuration)
  3502. {
  3503. SetRewardableConfiguration srb;
  3504. srb.objectID = townInstanceID;
  3505. srb.buildingID = buildingID;
  3506. srb.configuration = configuration;
  3507. sendAndApply(srb);
  3508. }
  3509. void CGameHandler::showInfoDialog(InfoWindow * iw)
  3510. {
  3511. sendAndApply(*iw);
  3512. }
  3513. vstd::RNG & CGameHandler::getRandomGenerator()
  3514. {
  3515. return randomizer->getDefault();
  3516. }
  3517. //#if SCRIPTING_ENABLED
  3518. //scripting::Pool * CGameHandler::getGlobalContextPool() const
  3519. //{
  3520. // return serverScripts.get();
  3521. //}
  3522. //scripting::Pool * CGameHandler::getContextPool() const
  3523. //{
  3524. // return serverScripts.get();
  3525. //}
  3526. //#endif
  3527. std::shared_ptr<CGObjectInstance> CGameHandler::createNewObject(const int3 & visitablePosition, MapObjectID objectID, MapObjectSubID subID)
  3528. {
  3529. TerrainId terrainType = ETerrainId::NONE;
  3530. if (!gameState().isInTheMap(visitablePosition))
  3531. throw std::runtime_error("Attempt to create object outside map at " + visitablePosition.toString());
  3532. const TerrainTile & t = gameState().getMap().getTile(visitablePosition);
  3533. terrainType = t.getTerrainID();
  3534. auto handler = LIBRARY->objtypeh->getHandlerFor(objectID, subID);
  3535. auto o = handler->create(&gameInfo(), nullptr);
  3536. handler->configureObject(o.get(), *randomizer);
  3537. assert(o->ID == objectID);
  3538. gs->getMap().generateUniqueInstanceName(o.get());
  3539. assert(!handler->getTemplates(terrainType).empty());
  3540. if (handler->getTemplates().empty())
  3541. throw std::runtime_error("Attempt to create object (" + std::to_string(objectID) + ", " + std::to_string(subID.getNum()) + ") with no templates!");
  3542. if (!handler->getTemplates(terrainType).empty())
  3543. o->appearance = handler->getTemplates(terrainType).front();
  3544. else
  3545. o->appearance = handler->getTemplates().front();
  3546. if (o->isVisitable())
  3547. o->setAnchorPos(visitablePosition + o->getVisitableOffset());
  3548. else
  3549. o->setAnchorPos(visitablePosition);
  3550. return o;
  3551. }
  3552. void CGameHandler::createWanderingMonster(const int3 & visitablePosition, CreatureID creature, int unitSize)
  3553. {
  3554. auto createdObject = createNewObject(visitablePosition, Obj::MONSTER, creature);
  3555. auto cre = std::dynamic_pointer_cast<CGCreature>(createdObject);
  3556. assert(cre);
  3557. cre->notGrowingTeam = cre->neverFlees = false;
  3558. cre->character = 2;
  3559. cre->gainedArtifact = ArtifactID::NONE;
  3560. cre->identifier = -1;
  3561. cre->temppower = static_cast<int64_t>(unitSize) * 1000;
  3562. cre->addToSlot(SlotID(0), std::make_unique<CStackInstance>(&gameInfo(), creature, unitSize));
  3563. newObject(createdObject, PlayerColor::NEUTRAL);
  3564. }
  3565. void CGameHandler::createBoat(const int3 & visitablePosition, BoatId type, PlayerColor initiator)
  3566. {
  3567. auto createdObject = createNewObject(visitablePosition, Obj::BOAT, type);
  3568. newObject(createdObject, initiator);
  3569. }
  3570. void CGameHandler::createHole(const int3 & visitablePosition, PlayerColor initiator)
  3571. {
  3572. auto createdObject = createNewObject(visitablePosition, Obj::HOLE, 0);
  3573. newObject(createdObject, initiator);
  3574. }
  3575. void CGameHandler::newObject(std::shared_ptr<CGObjectInstance> object, PlayerColor initiator)
  3576. {
  3577. object->initObj(*randomizer);
  3578. NewObject no;
  3579. no.newObject = object;
  3580. no.initiator = initiator;
  3581. sendAndApply(no);
  3582. }
  3583. void CGameHandler::startBattle(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, const BattleLayout & layout, const CGTownInstance *town)
  3584. {
  3585. battles->startBattle(army1, army2, tile, hero1, hero2, layout, town);
  3586. }
  3587. void CGameHandler::startBattle(const CArmedInstance *army1, const CArmedInstance *army2 )
  3588. {
  3589. battles->startBattle(army1, army2);
  3590. }
  3591. void CGameHandler::useChargeBasedSpell(const ObjectInstanceID & heroObjectID, const SpellID & spellID)
  3592. {
  3593. const auto * hero = gameInfo().getHero(heroObjectID);
  3594. assert(hero);
  3595. assert(hero->canCastThisSpell(spellID.toSpell()));
  3596. // Check if hero used charge based spell
  3597. // Try to find other sources of the spell besides the charged artifacts. If there are any, we use them.
  3598. std::optional<std::tuple<ArtifactPosition, ArtifactInstanceID, uint16_t>> chargedArt;
  3599. for(const auto & source : hero->getSourcesForSpell(spellID))
  3600. {
  3601. if(const auto * artInst = hero->getArtByInstanceId(source.as<ArtifactInstanceID>()))
  3602. {
  3603. const auto * artType = artInst->getType();
  3604. const auto spellCost = artType->getChargeCost(spellID);
  3605. if(spellCost.has_value() && spellCost.value() <= artInst->getCharges() && artType->getDischargeCondition() == DischargeArtifactCondition::SPELLCAST)
  3606. {
  3607. chargedArt.emplace(hero->getArtPos(artInst), artInst->getId(), spellCost.value());
  3608. }
  3609. else
  3610. {
  3611. return;
  3612. }
  3613. }
  3614. else
  3615. {
  3616. return;
  3617. }
  3618. }
  3619. assert(chargedArt.has_value());
  3620. DischargeArtifact msg(std::get<1>(chargedArt.value()), std::get<2>(chargedArt.value()));
  3621. msg.artLoc.emplace(hero->id, std::get<0>(chargedArt.value()));
  3622. sendAndApply(msg);
  3623. }