CGameHandler.cpp 122 KB

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