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