CGameHandler.cpp 121 KB

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