CGameHandler.cpp 134 KB

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