CGameHandler.cpp 130 KB

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