CGameHandler.cpp 125 KB

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