CGameHandler.cpp 134 KB

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