CGameHandler.cpp 134 KB

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