CGameHandler.cpp 132 KB

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