CGameHandler.cpp 130 KB

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