CGameHandler.cpp 134 KB

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