CGameHandler.cpp 127 KB

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