CGameHandler.cpp 124 KB

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