CGameHandler.cpp 134 KB

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