CGameHandler.cpp 130 KB

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