CGameHandler.cpp 129 KB

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