CGameState.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160
  1. /*
  2. * CGameState.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 "CGameState.h"
  12. #include "mapping/CCampaignHandler.h"
  13. #include "mapObjects/CObjectClassesHandler.h"
  14. #include "CArtHandler.h"
  15. #include "CBuildingHandler.h"
  16. #include "CGeneralTextHandler.h"
  17. #include "CTownHandler.h"
  18. #include "spells/CSpellHandler.h"
  19. #include "CHeroHandler.h"
  20. #include "mapObjects/CObjectHandler.h"
  21. #include "CModHandler.h"
  22. #include "CSkillHandler.h"
  23. #include "mapping/CMap.h"
  24. #include "mapping/CMapService.h"
  25. #include "StartInfo.h"
  26. #include "NetPacks.h"
  27. #include "registerTypes/RegisterTypes.h"
  28. #include "battle/BattleInfo.h"
  29. #include "JsonNode.h"
  30. #include "filesystem/Filesystem.h"
  31. #include "GameConstants.h"
  32. #include "rmg/CMapGenerator.h"
  33. #include "CStopWatch.h"
  34. #include "mapping/CMapEditManager.h"
  35. #include "serializer/CTypeList.h"
  36. #include "serializer/CMemorySerializer.h"
  37. #include "VCMIDirs.h"
  38. VCMI_LIB_NAMESPACE_BEGIN
  39. boost::shared_mutex CGameState::mutex;
  40. template <typename T> class CApplyOnGS;
  41. class CBaseForGSApply
  42. {
  43. public:
  44. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  45. virtual ~CBaseForGSApply(){};
  46. template<typename U> static CBaseForGSApply *getApplier(const U * t=nullptr)
  47. {
  48. return new CApplyOnGS<U>();
  49. }
  50. };
  51. template <typename T> class CApplyOnGS : public CBaseForGSApply
  52. {
  53. public:
  54. void applyOnGS(CGameState *gs, void *pack) const override
  55. {
  56. T *ptr = static_cast<T*>(pack);
  57. boost::unique_lock<boost::shared_mutex> lock(CGameState::mutex);
  58. ptr->applyGs(gs);
  59. }
  60. };
  61. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  62. {
  63. int type = txt.first, ser = txt.second;
  64. if(type == ART_NAMES)
  65. {
  66. auto art = ArtifactID(ser).toArtifact(VLC->artifacts());
  67. if(art)
  68. dst = art->getName();
  69. else
  70. dst = "#!#";
  71. }
  72. else if(type == ART_DESCR)
  73. {
  74. auto art = ArtifactID(ser).toArtifact(VLC->artifacts());
  75. if(art)
  76. dst = art->getDescription();
  77. else
  78. dst = "#!#";
  79. }
  80. else if (type == ART_EVNTS)
  81. {
  82. auto art = ArtifactID(ser).toArtifact(VLC->artifacts());
  83. if(art)
  84. dst = art->getEventText();
  85. else
  86. dst = "#!#";
  87. }
  88. else if(type == CRE_PL_NAMES)
  89. {
  90. auto cre = CreatureID(ser).toCreature(VLC->creatures());
  91. if(cre)
  92. dst = cre->getPluralName();
  93. else
  94. dst = "#!#";
  95. }
  96. else if(type == CRE_SING_NAMES)
  97. {
  98. auto cre = CreatureID(ser).toCreature(VLC->creatures());
  99. if(cre)
  100. dst = cre->getSingularName();
  101. else
  102. dst = "#!#";
  103. }
  104. else if(type == MINE_NAMES)
  105. {
  106. dst = VLC->generaltexth->mines[ser].first;
  107. }
  108. else if(type == MINE_EVNTS)
  109. {
  110. dst = VLC->generaltexth->mines[ser].second;
  111. }
  112. else if(type == SPELL_NAME)
  113. {
  114. auto spell = SpellID(ser).toSpell(VLC->spells());
  115. if(spell)
  116. dst = spell->getName();
  117. else
  118. dst = "#!#";
  119. }
  120. else if(type == OBJ_NAMES)
  121. {
  122. dst = VLC->objtypeh->getObjectName(ser);
  123. }
  124. else if(type == SEC_SKILL_NAME)
  125. {
  126. dst = VLC->skillh->skillName(ser);
  127. }
  128. else
  129. {
  130. std::vector<std::string> *vec;
  131. switch(type)
  132. {
  133. case GENERAL_TXT:
  134. vec = &VLC->generaltexth->allTexts;
  135. break;
  136. case XTRAINFO_TXT:
  137. vec = &VLC->generaltexth->xtrainfo;
  138. break;
  139. case RES_NAMES:
  140. vec = &VLC->generaltexth->restypes;
  141. break;
  142. case ARRAY_TXT:
  143. vec = &VLC->generaltexth->arraytxt;
  144. break;
  145. case CREGENS:
  146. vec = &VLC->generaltexth->creGens;
  147. break;
  148. case CREGENS4:
  149. vec = &VLC->generaltexth->creGens4;
  150. break;
  151. case ADVOB_TXT:
  152. vec = &VLC->generaltexth->advobtxt;
  153. break;
  154. case COLOR:
  155. vec = &VLC->generaltexth->capColors;
  156. break;
  157. case JK_TXT:
  158. vec = &VLC->generaltexth->jktexts;
  159. break;
  160. default:
  161. logGlobal->error("Failed string substitution because type is %d", type);
  162. dst = "#@#";
  163. return;
  164. }
  165. if(vec->size() <= ser)
  166. {
  167. logGlobal->error("Failed string substitution with type %d because index %d is out of bounds!", type, ser);
  168. dst = "#!#";
  169. }
  170. else
  171. dst = (*vec)[ser];
  172. }
  173. }
  174. DLL_LINKAGE void MetaString::toString(std::string &dst) const
  175. {
  176. size_t exSt = 0, loSt = 0, nums = 0;
  177. dst.clear();
  178. for(auto & elem : message)
  179. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  180. switch(elem)
  181. {
  182. case TEXACT_STRING:
  183. dst += exactStrings[exSt++];
  184. break;
  185. case TLOCAL_STRING:
  186. {
  187. std::string hlp;
  188. getLocalString(localStrings[loSt++], hlp);
  189. dst += hlp;
  190. }
  191. break;
  192. case TNUMBER:
  193. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  194. break;
  195. case TREPLACE_ESTRING:
  196. boost::replace_first(dst, "%s", exactStrings[exSt++]);
  197. break;
  198. case TREPLACE_LSTRING:
  199. {
  200. std::string hlp;
  201. getLocalString(localStrings[loSt++], hlp);
  202. boost::replace_first(dst, "%s", hlp);
  203. }
  204. break;
  205. case TREPLACE_NUMBER:
  206. boost::replace_first(dst, "%d", boost::lexical_cast<std::string>(numbers[nums++]));
  207. break;
  208. case TREPLACE_PLUSNUMBER:
  209. boost::replace_first(dst, "%+d", '+' + boost::lexical_cast<std::string>(numbers[nums++]));
  210. break;
  211. default:
  212. logGlobal->error("MetaString processing error! Received message of type %d", int(elem));
  213. break;
  214. }
  215. }
  216. }
  217. DLL_LINKAGE std::string MetaString::toString() const
  218. {
  219. std::string ret;
  220. toString(ret);
  221. return ret;
  222. }
  223. DLL_LINKAGE std::string MetaString::buildList () const
  224. ///used to handle loot from creature bank
  225. {
  226. size_t exSt = 0, loSt = 0, nums = 0;
  227. std::string lista;
  228. for (int i = 0; i < message.size(); ++i)
  229. {
  230. if (i > 0 && (message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING))
  231. {
  232. if (exSt == exactStrings.size() - 1)
  233. lista += VLC->generaltexth->allTexts[141]; //" and "
  234. else
  235. lista += ", ";
  236. }
  237. switch (message[i])
  238. {
  239. case TEXACT_STRING:
  240. lista += exactStrings[exSt++];
  241. break;
  242. case TLOCAL_STRING:
  243. {
  244. std::string hlp;
  245. getLocalString (localStrings[loSt++], hlp);
  246. lista += hlp;
  247. }
  248. break;
  249. case TNUMBER:
  250. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  251. break;
  252. case TREPLACE_ESTRING:
  253. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  254. break;
  255. case TREPLACE_LSTRING:
  256. {
  257. std::string hlp;
  258. getLocalString (localStrings[loSt++], hlp);
  259. lista.replace (lista.find("%s"), 2, hlp);
  260. }
  261. break;
  262. case TREPLACE_NUMBER:
  263. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  264. break;
  265. default:
  266. logGlobal->error("MetaString processing error! Received message of type %d",int(message[i]));
  267. }
  268. }
  269. return lista;
  270. }
  271. void MetaString::addCreReplacement(CreatureID id, TQuantity count) //adds sing or plural name;
  272. {
  273. if (!count)
  274. addReplacement (CRE_PL_NAMES, id); //no creatures - just empty name (eg. defeat Angels)
  275. else if (count == 1)
  276. addReplacement (CRE_SING_NAMES, id);
  277. else
  278. addReplacement (CRE_PL_NAMES, id);
  279. }
  280. void MetaString::addReplacement(const CStackBasicDescriptor & stack)
  281. {
  282. assert(stack.type); //valid type
  283. addCreReplacement(stack.type->idNumber, stack.count);
  284. }
  285. static CGObjectInstance * createObject(Obj id, int subid, int3 pos, PlayerColor owner)
  286. {
  287. CGObjectInstance * nobj;
  288. switch(id)
  289. {
  290. case Obj::HERO:
  291. {
  292. auto handler = VLC->objtypeh->getHandlerFor(id, VLC->heroh->objects[subid]->heroClass->getIndex());
  293. nobj = handler->create(handler->getTemplates().front());
  294. break;
  295. }
  296. case Obj::TOWN:
  297. nobj = new CGTownInstance();
  298. break;
  299. default: //rest of objects
  300. nobj = new CGObjectInstance();
  301. break;
  302. }
  303. nobj->ID = id;
  304. nobj->subID = subid;
  305. nobj->pos = pos;
  306. nobj->tempOwner = owner;
  307. if (id != Obj::HERO)
  308. nobj->appearance = VLC->objtypeh->getHandlerFor(id, subid)->getTemplates().front();
  309. return nobj;
  310. }
  311. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, PlayerColor player, const CTown *town,
  312. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, CRandomGenerator & rand, const CHeroClass * bannedClass) const
  313. {
  314. CGHeroInstance *ret = nullptr;
  315. if(player>=PlayerColor::PLAYER_LIMIT)
  316. {
  317. logGlobal->error("Cannot pick hero for faction %d. Wrong owner!", town->faction->index);
  318. return nullptr;
  319. }
  320. std::vector<CGHeroInstance *> pool;
  321. if(native)
  322. {
  323. for(auto & elem : available)
  324. {
  325. if(pavailable.find(elem.first)->second & 1<<player.getNum()
  326. && elem.second->type->heroClass->faction == town->faction->index)
  327. {
  328. pool.push_back(elem.second); //get all available heroes
  329. }
  330. }
  331. if(!pool.size())
  332. {
  333. logGlobal->error("Cannot pick native hero for %s. Picking any...", player.getStr());
  334. return pickHeroFor(false, player, town, available, rand);
  335. }
  336. else
  337. {
  338. ret = *RandomGeneratorUtil::nextItem(pool, rand);
  339. }
  340. }
  341. else
  342. {
  343. int sum=0, r;
  344. for(auto & elem : available)
  345. {
  346. if (pavailable.find(elem.first)->second & (1<<player.getNum()) && // hero is available
  347. ( !bannedClass || elem.second->type->heroClass != bannedClass) ) // and his class is not same as other hero
  348. {
  349. pool.push_back(elem.second);
  350. sum += elem.second->type->heroClass->selectionProbability[town->faction->index]; //total weight
  351. }
  352. }
  353. if(!pool.size() || sum == 0)
  354. {
  355. logGlobal->error("There are no heroes available for player %s!", player.getStr());
  356. return nullptr;
  357. }
  358. r = rand.nextInt(sum - 1);
  359. for (auto & elem : pool)
  360. {
  361. r -= elem->type->heroClass->selectionProbability[town->faction->index];
  362. if(r < 0)
  363. {
  364. ret = elem;
  365. break;
  366. }
  367. }
  368. if(!ret)
  369. ret = pool.back();
  370. }
  371. available.erase(ret->subID);
  372. return ret;
  373. }
  374. void CGameState::CrossoverHeroesList::addHeroToBothLists(CGHeroInstance * hero)
  375. {
  376. heroesFromPreviousScenario.push_back(hero);
  377. heroesFromAnyPreviousScenarios.push_back(hero);
  378. }
  379. void CGameState::CrossoverHeroesList::removeHeroFromBothLists(CGHeroInstance * hero)
  380. {
  381. heroesFromPreviousScenario -= hero;
  382. heroesFromAnyPreviousScenarios -= hero;
  383. }
  384. CGameState::CampaignHeroReplacement::CampaignHeroReplacement(CGHeroInstance * hero, ObjectInstanceID heroPlaceholderId) : hero(hero), heroPlaceholderId(heroPlaceholderId)
  385. {
  386. }
  387. int CGameState::pickNextHeroType(PlayerColor owner)
  388. {
  389. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  390. if(ps.hero >= 0 && !isUsedHero(HeroTypeID(ps.hero))) //we haven't used selected hero
  391. {
  392. return ps.hero;
  393. }
  394. return pickUnusedHeroTypeRandomly(owner);
  395. }
  396. int CGameState::pickUnusedHeroTypeRandomly(PlayerColor owner)
  397. {
  398. //list of available heroes for this faction and others
  399. std::vector<HeroTypeID> factionHeroes, otherHeroes;
  400. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  401. for(HeroTypeID hid : getUnusedAllowedHeroes())
  402. {
  403. if(VLC->heroh->objects[hid.getNum()]->heroClass->faction == ps.castle)
  404. factionHeroes.push_back(hid);
  405. else
  406. otherHeroes.push_back(hid);
  407. }
  408. // select random hero native to "our" faction
  409. if(!factionHeroes.empty())
  410. {
  411. return RandomGeneratorUtil::nextItem(factionHeroes, getRandomGenerator())->getNum();
  412. }
  413. logGlobal->warn("Cannot find free hero of appropriate faction for player %s - trying to get first available...", owner.getStr());
  414. if(!otherHeroes.empty())
  415. {
  416. return RandomGeneratorUtil::nextItem(otherHeroes, getRandomGenerator())->getNum();
  417. }
  418. logGlobal->error("No free allowed heroes!");
  419. auto notAllowedHeroesButStillBetterThanCrash = getUnusedAllowedHeroes(true);
  420. if(notAllowedHeroesButStillBetterThanCrash.size())
  421. return notAllowedHeroesButStillBetterThanCrash.begin()->getNum();
  422. logGlobal->error("No free heroes at all!");
  423. assert(0); //current code can't handle this situation
  424. return -1; // no available heroes at all
  425. }
  426. std::pair<Obj,int> CGameState::pickObject (CGObjectInstance *obj)
  427. {
  428. switch(obj->ID)
  429. {
  430. case Obj::RANDOM_ART:
  431. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  432. case Obj::RANDOM_TREASURE_ART:
  433. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE));
  434. case Obj::RANDOM_MINOR_ART:
  435. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MINOR));
  436. case Obj::RANDOM_MAJOR_ART:
  437. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MAJOR));
  438. case Obj::RANDOM_RELIC_ART:
  439. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_RELIC));
  440. case Obj::RANDOM_HERO:
  441. return std::make_pair(Obj::HERO, pickNextHeroType(obj->tempOwner));
  442. case Obj::RANDOM_MONSTER:
  443. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator()));
  444. case Obj::RANDOM_MONSTER_L1:
  445. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 1));
  446. case Obj::RANDOM_MONSTER_L2:
  447. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 2));
  448. case Obj::RANDOM_MONSTER_L3:
  449. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 3));
  450. case Obj::RANDOM_MONSTER_L4:
  451. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 4));
  452. case Obj::RANDOM_RESOURCE:
  453. return std::make_pair(Obj::RESOURCE,getRandomGenerator().nextInt(6)); //now it's OH3 style, use %8 for mithril
  454. case Obj::RANDOM_TOWN:
  455. {
  456. PlayerColor align = PlayerColor((static_cast<CGTownInstance*>(obj))->alignment);
  457. si32 f; // can be negative (for random)
  458. if(align >= PlayerColor::PLAYER_LIMIT)//same as owner / random
  459. {
  460. if(obj->tempOwner >= PlayerColor::PLAYER_LIMIT)
  461. f = -1; //random
  462. else
  463. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  464. }
  465. else
  466. {
  467. f = scenarioOps->getIthPlayersSettings(align).castle;
  468. }
  469. if(f<0)
  470. {
  471. do
  472. {
  473. f = getRandomGenerator().nextInt((int)VLC->townh->size() - 1);
  474. }
  475. while ((*VLC->townh)[f]->town == nullptr); // find playable faction
  476. }
  477. return std::make_pair(Obj::TOWN,f);
  478. }
  479. case Obj::RANDOM_MONSTER_L5:
  480. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 5));
  481. case Obj::RANDOM_MONSTER_L6:
  482. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 6));
  483. case Obj::RANDOM_MONSTER_L7:
  484. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 7));
  485. case Obj::RANDOM_DWELLING:
  486. case Obj::RANDOM_DWELLING_LVL:
  487. case Obj::RANDOM_DWELLING_FACTION:
  488. {
  489. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  490. int faction;
  491. //if castle alignment available
  492. if (auto info = dynamic_cast<CCreGenAsCastleInfo*>(dwl->info))
  493. {
  494. faction = getRandomGenerator().nextInt((int)VLC->townh->size() - 1);
  495. if(info->asCastle && !info->instanceId.empty())
  496. {
  497. auto iter = map->instanceNames.find(info->instanceId);
  498. if(iter == map->instanceNames.end())
  499. logGlobal->error("Map object not found: %s", info->instanceId);
  500. else
  501. {
  502. auto elem = iter->second;
  503. if(elem->ID==Obj::RANDOM_TOWN)
  504. {
  505. randomizeObject(elem.get()); //we have to randomize the castle first
  506. faction = elem->subID;
  507. }
  508. else if(elem->ID==Obj::TOWN)
  509. faction = elem->subID;
  510. else
  511. logGlobal->error("Map object must be town: %s", info->instanceId);
  512. }
  513. }
  514. else if(info->asCastle)
  515. {
  516. for(auto & elem : map->objects)
  517. {
  518. if(!elem)
  519. continue;
  520. if(elem->ID==Obj::RANDOM_TOWN
  521. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  522. {
  523. randomizeObject(elem); //we have to randomize the castle first
  524. faction = elem->subID;
  525. break;
  526. }
  527. else if(elem->ID==Obj::TOWN
  528. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  529. {
  530. faction = elem->subID;
  531. break;
  532. }
  533. }
  534. }
  535. else
  536. {
  537. std::set<int> temp;
  538. for(int i = 0; i < info->allowedFactions.size(); i++)
  539. if(info->allowedFactions[i])
  540. temp.insert(i);
  541. if(temp.empty())
  542. logGlobal->error("Random faction selection failed. Nothing is allowed. Fall back to random.");
  543. else
  544. faction = *RandomGeneratorUtil::nextItem(temp, getRandomGenerator());
  545. }
  546. }
  547. else // castle alignment fixed
  548. faction = obj->subID;
  549. int level;
  550. //if level set to range
  551. if (auto info = dynamic_cast<CCreGenLeveledInfo*>(dwl->info))
  552. {
  553. level = getRandomGenerator().nextInt(info->minLevel, info->maxLevel);
  554. }
  555. else // fixed level
  556. {
  557. level = obj->subID;
  558. }
  559. delete dwl->info;
  560. dwl->info = nullptr;
  561. std::pair<Obj, int> result(Obj::NO_OBJ, -1);
  562. CreatureID cid = (*VLC->townh)[faction]->town->creatures[level][0];
  563. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  564. //check for block map equality is better but more complex solution
  565. auto testID = [&](Obj primaryID) -> void
  566. {
  567. auto dwellingIDs = VLC->objtypeh->knownSubObjects(primaryID);
  568. for (si32 entry : dwellingIDs)
  569. {
  570. auto handler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(primaryID, entry).get());
  571. if (handler->producesCreature(VLC->creh->objects[cid]))
  572. result = std::make_pair(primaryID, entry);
  573. }
  574. };
  575. testID(Obj::CREATURE_GENERATOR1);
  576. if (result.first == Obj::NO_OBJ)
  577. testID(Obj::CREATURE_GENERATOR4);
  578. if (result.first == Obj::NO_OBJ)
  579. {
  580. logGlobal->error("Error: failed to find dwelling for %s of level %d", (*VLC->townh)[faction]->name, int(level));
  581. result = std::make_pair(Obj::CREATURE_GENERATOR1, *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1), getRandomGenerator()));
  582. }
  583. return result;
  584. }
  585. }
  586. return std::make_pair(Obj::NO_OBJ,-1);
  587. }
  588. void CGameState::randomizeObject(CGObjectInstance *cur)
  589. {
  590. std::pair<Obj,int> ran = pickObject(cur);
  591. if(ran.first == Obj::NO_OBJ || ran.second<0) //this is not a random object, or we couldn't find anything
  592. {
  593. if(cur->ID==Obj::TOWN)
  594. cur->setType(cur->ID, cur->subID); // update def, if necessary
  595. }
  596. else if(ran.first==Obj::HERO)//special code for hero
  597. {
  598. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  599. cur->setType(ran.first, ran.second);
  600. map->heroesOnMap.push_back(h);
  601. }
  602. else if(ran.first==Obj::TOWN)//special code for town
  603. {
  604. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  605. cur->setType(ran.first, ran.second);
  606. map->towns.push_back(t);
  607. }
  608. else
  609. {
  610. cur->setType(ran.first, ran.second);
  611. }
  612. }
  613. int CGameState::getDate(Date::EDateType mode) const
  614. {
  615. int temp;
  616. switch (mode)
  617. {
  618. case Date::DAY:
  619. return day;
  620. case Date::DAY_OF_WEEK: //day of week
  621. temp = (day)%7; // 1 - Monday, 7 - Sunday
  622. return temp ? temp : 7;
  623. case Date::WEEK: //current week
  624. temp = ((day-1)/7)+1;
  625. if (!(temp%4))
  626. return 4;
  627. else
  628. return (temp%4);
  629. case Date::MONTH: //current month
  630. return ((day-1)/28)+1;
  631. case Date::DAY_OF_MONTH: //day of month
  632. temp = (day)%28;
  633. if (temp)
  634. return temp;
  635. else return 28;
  636. }
  637. return 0;
  638. }
  639. CGameState::CGameState()
  640. {
  641. gs = this;
  642. applier = std::make_shared<CApplier<CBaseForGSApply>>();
  643. registerTypesClientPacks1(*applier);
  644. registerTypesClientPacks2(*applier);
  645. //objCaller = new CObjectCallersHandler();
  646. globalEffects.setDescription("Global effects");
  647. globalEffects.setNodeType(CBonusSystemNode::GLOBAL_EFFECTS);
  648. day = 0;
  649. services = nullptr;
  650. }
  651. CGameState::~CGameState()
  652. {
  653. map.dellNull();
  654. curB.dellNull();
  655. for(auto ptr : hpool.heroesPool) // clean hero pool
  656. ptr.second.dellNull();
  657. }
  658. void CGameState::preInit(Services * services)
  659. {
  660. this->services = services;
  661. }
  662. void CGameState::init(const IMapService * mapService, StartInfo * si, bool allowSavingRandomMap)
  663. {
  664. preInitAuto();
  665. logGlobal->info("\tUsing random seed: %d", si->seedToBeUsed);
  666. getRandomGenerator().setSeed(si->seedToBeUsed);
  667. scenarioOps = CMemorySerializer::deepCopy(*si).release();
  668. initialOpts = CMemorySerializer::deepCopy(*si).release();
  669. si = nullptr;
  670. switch(scenarioOps->mode)
  671. {
  672. case StartInfo::NEW_GAME:
  673. initNewGame(mapService, allowSavingRandomMap);
  674. break;
  675. case StartInfo::CAMPAIGN:
  676. initCampaign();
  677. break;
  678. default:
  679. logGlobal->error("Wrong mode: %d", static_cast<int>(scenarioOps->mode));
  680. return;
  681. }
  682. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  683. logGlobal->info("Map loaded!");
  684. checkMapChecksum();
  685. day = 0;
  686. logGlobal->debug("Initialization:");
  687. initPlayerStates();
  688. placeCampaignHeroes();
  689. initGrailPosition();
  690. initRandomFactionsForPlayers();
  691. randomizeMapObjects();
  692. placeStartingHeroes();
  693. initStartingResources();
  694. initHeroes();
  695. initStartingBonus();
  696. initTowns();
  697. placeHeroesInTowns();
  698. initMapObjects();
  699. buildBonusSystemTree();
  700. initVisitingAndGarrisonedHeroes();
  701. initFogOfWar();
  702. // Explicitly initialize static variables
  703. for(auto & elem : players)
  704. {
  705. CGKeys::playerKeyMap[elem.first] = std::set<ui8>();
  706. }
  707. for(auto & elem : teams)
  708. {
  709. CGObelisk::visited[elem.first] = 0;
  710. }
  711. logGlobal->debug("\tChecking objectives");
  712. map->checkForObjectives(); //needs to be run when all objects are properly placed
  713. auto seedAfterInit = getRandomGenerator().nextInt();
  714. logGlobal->info("Seed after init is %d (before was %d)", seedAfterInit, scenarioOps->seedToBeUsed);
  715. if(scenarioOps->seedPostInit > 0)
  716. {
  717. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  718. assert(scenarioOps->seedPostInit == seedAfterInit);
  719. }
  720. else
  721. {
  722. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  723. }
  724. }
  725. void CGameState::updateEntity(Metatype metatype, int32_t index, const JsonNode & data)
  726. {
  727. switch(metatype)
  728. {
  729. case Metatype::ARTIFACT_INSTANCE:
  730. logGlobal->error("Artifact instance update is not implemented");
  731. break;
  732. case Metatype::CREATURE_INSTANCE:
  733. logGlobal->error("Creature instance update is not implemented");
  734. break;
  735. case Metatype::HERO_INSTANCE:
  736. //index is hero type
  737. if(index >= 0 && index < map->allHeroes.size())
  738. {
  739. CGHeroInstance * hero = map->allHeroes.at(index);
  740. hero->updateFrom(data);
  741. }
  742. else
  743. {
  744. logGlobal->error("Update entity: hero index %s is out of range [%d,%d]", index, 0, map->allHeroes.size());
  745. }
  746. break;
  747. case Metatype::MAP_OBJECT_INSTANCE:
  748. if(index >= 0 && index < map->objects.size())
  749. {
  750. CGObjectInstance * obj = getObjInstance(ObjectInstanceID(index));
  751. obj->updateFrom(data);
  752. }
  753. else
  754. {
  755. logGlobal->error("Update entity: object index %s is out of range [%d,%d]", index, 0, map->objects.size());
  756. }
  757. break;
  758. default:
  759. services->updateEntity(metatype, index, data);
  760. break;
  761. }
  762. }
  763. void CGameState::updateOnLoad(StartInfo * si)
  764. {
  765. preInitAuto();
  766. scenarioOps->playerInfos = si->playerInfos;
  767. for(auto & i : si->playerInfos)
  768. gs->players[i.first].human = i.second.isControlledByHuman();
  769. }
  770. void CGameState::preInitAuto()
  771. {
  772. if(services == nullptr)
  773. {
  774. logGlobal->error("Game state preinit missing");
  775. preInit(VLC);
  776. }
  777. }
  778. void CGameState::initNewGame(const IMapService * mapService, bool allowSavingRandomMap)
  779. {
  780. if(scenarioOps->createRandomMap())
  781. {
  782. logGlobal->info("Create random map.");
  783. CStopWatch sw;
  784. // Gen map
  785. CMapGenerator mapGenerator(*scenarioOps->mapGenOptions, scenarioOps->seedToBeUsed);
  786. std::unique_ptr<CMap> randomMap = mapGenerator.generate();
  787. if(allowSavingRandomMap)
  788. {
  789. try
  790. {
  791. auto path = VCMIDirs::get().userCachePath() / "RandomMaps";
  792. boost::filesystem::create_directories(path);
  793. std::shared_ptr<CMapGenOptions> options = scenarioOps->mapGenOptions;
  794. const std::string templateName = options->getMapTemplate()->getName();
  795. const ui32 seed = scenarioOps->seedToBeUsed;
  796. const std::string fileName = boost::str(boost::format("%s_%d.vmap") % templateName % seed );
  797. const auto fullPath = path / fileName;
  798. mapService->saveMap(randomMap, fullPath);
  799. logGlobal->info("Random map has been saved to:");
  800. logGlobal->info(fullPath.string());
  801. }
  802. catch(...)
  803. {
  804. logGlobal->error("Saving random map failed with exception");
  805. handleException();
  806. }
  807. }
  808. map = randomMap.release();
  809. // Update starting options
  810. for(int i = 0; i < map->players.size(); ++i)
  811. {
  812. const auto & playerInfo = map->players[i];
  813. if(playerInfo.canAnyonePlay())
  814. {
  815. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  816. playerSettings.compOnly = !playerInfo.canHumanPlay;
  817. playerSettings.team = playerInfo.team;
  818. playerSettings.castle = playerInfo.defaultCastle();
  819. if(playerSettings.isControlledByAI() && playerSettings.name.empty())
  820. {
  821. playerSettings.name = VLC->generaltexth->allTexts[468];
  822. }
  823. playerSettings.color = PlayerColor(i);
  824. }
  825. else
  826. {
  827. scenarioOps->playerInfos.erase(PlayerColor(i));
  828. }
  829. }
  830. logGlobal->info("Generated random map in %i ms.", sw.getDiff());
  831. }
  832. else
  833. {
  834. logGlobal->info("Open map file: %s", scenarioOps->mapname);
  835. const ResourceID mapURI(scenarioOps->mapname, EResType::MAP);
  836. map = mapService->loadMap(mapURI).release();
  837. }
  838. }
  839. void CGameState::initCampaign()
  840. {
  841. logGlobal->info("Open campaign map file: %d", scenarioOps->campState->currentMap.get());
  842. map = scenarioOps->campState->getMap();
  843. }
  844. void CGameState::checkMapChecksum()
  845. {
  846. logGlobal->info("\tOur checksum for the map: %d", map->checksum);
  847. if(scenarioOps->mapfileChecksum)
  848. {
  849. logGlobal->info("\tServer checksum for %s: %d", scenarioOps->mapname, scenarioOps->mapfileChecksum);
  850. if(map->checksum != scenarioOps->mapfileChecksum)
  851. {
  852. logGlobal->error("Wrong map checksum!!!");
  853. throw std::runtime_error("Wrong checksum");
  854. }
  855. }
  856. else
  857. {
  858. scenarioOps->mapfileChecksum = map->checksum;
  859. }
  860. }
  861. void CGameState::initGrailPosition()
  862. {
  863. logGlobal->debug("\tPicking grail position");
  864. //pick grail location
  865. if(map->grailPos.x < 0 || map->grailRadius) //grail not set or set within a radius around some place
  866. {
  867. if(!map->grailRadius) //radius not given -> anywhere on map
  868. map->grailRadius = map->width * 2;
  869. std::vector<int3> allowedPos;
  870. static const int BORDER_WIDTH = 9; // grail must be at least 9 tiles away from border
  871. // add all not blocked tiles in range
  872. for (int z = 0; z < map->levels(); z++)
  873. {
  874. for(int x = BORDER_WIDTH; x < map->width - BORDER_WIDTH ; x++)
  875. {
  876. for(int y = BORDER_WIDTH; y < map->height - BORDER_WIDTH; y++)
  877. {
  878. const TerrainTile &t = map->getTile(int3(x, y, z));
  879. if(!t.blocked
  880. && !t.visitable
  881. && t.terType->isLand()
  882. && t.terType->isPassable()
  883. && (int)map->grailPos.dist2dSQ(int3(x, y, z)) <= (map->grailRadius * map->grailRadius))
  884. allowedPos.push_back(int3(x,y,z));
  885. }
  886. }
  887. }
  888. //remove tiles with holes
  889. for(auto & elem : map->objects)
  890. if(elem && elem->ID == Obj::HOLE)
  891. allowedPos -= elem->pos;
  892. if(!allowedPos.empty())
  893. {
  894. map->grailPos = *RandomGeneratorUtil::nextItem(allowedPos, getRandomGenerator());
  895. }
  896. else
  897. {
  898. logGlobal->warn("Grail cannot be placed, no appropriate tile found!");
  899. }
  900. }
  901. }
  902. void CGameState::initRandomFactionsForPlayers()
  903. {
  904. logGlobal->debug("\tPicking random factions for players");
  905. for(auto & elem : scenarioOps->playerInfos)
  906. {
  907. if(elem.second.castle==-1)
  908. {
  909. auto randomID = getRandomGenerator().nextInt((int)map->players[elem.first.getNum()].allowedFactions.size() - 1);
  910. auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
  911. std::advance(iter, randomID);
  912. elem.second.castle = *iter;
  913. }
  914. }
  915. }
  916. void CGameState::randomizeMapObjects()
  917. {
  918. logGlobal->debug("\tRandomizing objects");
  919. for(CGObjectInstance *obj : map->objects)
  920. {
  921. if(!obj) continue;
  922. randomizeObject(obj);
  923. //handle Favouring Winds - mark tiles under it
  924. if(obj->ID == Obj::FAVORABLE_WINDS)
  925. {
  926. for (int i = 0; i < obj->getWidth() ; i++)
  927. {
  928. for (int j = 0; j < obj->getHeight() ; j++)
  929. {
  930. int3 pos = obj->pos - int3(i,j,0);
  931. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  932. }
  933. }
  934. }
  935. }
  936. }
  937. void CGameState::initPlayerStates()
  938. {
  939. logGlobal->debug("\tCreating player entries in gs");
  940. for(auto & elem : scenarioOps->playerInfos)
  941. {
  942. PlayerState & p = players[elem.first];
  943. p.color=elem.first;
  944. p.human = elem.second.isControlledByHuman();
  945. p.team = map->players[elem.first.getNum()].team;
  946. teams[p.team].id = p.team;//init team
  947. teams[p.team].players.insert(elem.first);//add player to team
  948. }
  949. }
  950. void CGameState::placeCampaignHeroes()
  951. {
  952. if (scenarioOps->campState)
  953. {
  954. // place bonus hero
  955. auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap();
  956. bool campaignGiveHero = campaignBonus && campaignBonus.get().type == CScenarioTravel::STravelBonus::HERO;
  957. if(campaignGiveHero)
  958. {
  959. auto playerColor = PlayerColor(campaignBonus->info1);
  960. auto it = scenarioOps->playerInfos.find(playerColor);
  961. if(it != scenarioOps->playerInfos.end())
  962. {
  963. auto heroTypeId = campaignBonus->info2;
  964. if(heroTypeId == 0xffff) // random bonus hero
  965. {
  966. heroTypeId = pickUnusedHeroTypeRandomly(playerColor);
  967. }
  968. placeStartingHero(playerColor, HeroTypeID(heroTypeId), map->players[playerColor.getNum()].posOfMainTown);
  969. }
  970. }
  971. // replace heroes placeholders
  972. auto crossoverHeroes = getCrossoverHeroesFromPreviousScenarios();
  973. if(!crossoverHeroes.heroesFromAnyPreviousScenarios.empty())
  974. {
  975. logGlobal->debug("\tGenerate list of hero placeholders");
  976. auto campaignHeroReplacements = generateCampaignHeroesToReplace(crossoverHeroes);
  977. logGlobal->debug("\tPrepare crossover heroes");
  978. prepareCrossoverHeroes(campaignHeroReplacements, scenarioOps->campState->getCurrentScenario().travelOptions);
  979. // remove same heroes on the map which will be added through crossover heroes
  980. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  981. // with the same hero type id
  982. std::vector<CGHeroInstance *> removedHeroes;
  983. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  984. {
  985. auto hero = getUsedHero(HeroTypeID(campaignHeroReplacement.hero->subID));
  986. if(hero)
  987. {
  988. removedHeroes.push_back(hero);
  989. map->heroesOnMap -= hero;
  990. map->objects[hero->id.getNum()] = nullptr;
  991. map->removeBlockVisTiles(hero, true);
  992. }
  993. }
  994. logGlobal->debug("\tReplace placeholders with heroes");
  995. replaceHeroesPlaceholders(campaignHeroReplacements);
  996. // remove hero placeholders on map
  997. for(auto obj : map->objects)
  998. {
  999. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  1000. {
  1001. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  1002. map->removeBlockVisTiles(heroPlaceholder, true);
  1003. map->instanceNames.erase(obj->instanceName);
  1004. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  1005. delete heroPlaceholder;
  1006. }
  1007. }
  1008. // now add removed heroes again with unused type ID
  1009. for(auto hero : removedHeroes)
  1010. {
  1011. si32 heroTypeId = 0;
  1012. if(hero->ID == Obj::HERO)
  1013. {
  1014. heroTypeId = pickUnusedHeroTypeRandomly(hero->tempOwner);
  1015. }
  1016. else if(hero->ID == Obj::PRISON)
  1017. {
  1018. auto unusedHeroTypeIds = getUnusedAllowedHeroes();
  1019. if(!unusedHeroTypeIds.empty())
  1020. {
  1021. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, getRandomGenerator())).getNum();
  1022. }
  1023. else
  1024. {
  1025. logGlobal->error("No free hero type ID found to replace prison.");
  1026. assert(0);
  1027. }
  1028. }
  1029. else
  1030. {
  1031. assert(0); // should not happen
  1032. }
  1033. hero->subID = heroTypeId;
  1034. hero->portrait = hero->subID;
  1035. map->getEditManager()->insertObject(hero);
  1036. }
  1037. }
  1038. }
  1039. }
  1040. void CGameState::placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos)
  1041. {
  1042. for(auto town : map->towns)
  1043. {
  1044. if(town->getPosition() == townPos)
  1045. {
  1046. townPos = town->visitablePos();
  1047. break;
  1048. }
  1049. }
  1050. CGObjectInstance * hero = createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor);
  1051. hero->pos += hero->getVisitableOffset();
  1052. map->getEditManager()->insertObject(hero);
  1053. }
  1054. CGameState::CrossoverHeroesList CGameState::getCrossoverHeroesFromPreviousScenarios() const
  1055. {
  1056. CrossoverHeroesList crossoverHeroes;
  1057. auto campaignState = scenarioOps->campState;
  1058. auto bonus = campaignState->getBonusForCurrentMap();
  1059. if(bonus && bonus->type == CScenarioTravel::STravelBonus::HEROES_FROM_PREVIOUS_SCENARIO)
  1060. {
  1061. std::vector<CGHeroInstance *> heroes;
  1062. for(auto & node : campaignState->camp->scenarios[bonus->info2].crossoverHeroes)
  1063. {
  1064. auto h = CCampaignState::crossoverDeserialize(node);
  1065. heroes.push_back(h);
  1066. }
  1067. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = heroes;
  1068. }
  1069. else
  1070. {
  1071. if(!campaignState->mapsConquered.empty())
  1072. {
  1073. std::vector<CGHeroInstance *> heroes = {};
  1074. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = heroes;
  1075. crossoverHeroes.heroesFromPreviousScenario = heroes;
  1076. for(auto mapNr : campaignState->mapsConquered)
  1077. {
  1078. // create a list of deleted heroes
  1079. auto & scenario = campaignState->camp->scenarios[mapNr];
  1080. auto lostCrossoverHeroes = scenario.getLostCrossoverHeroes();
  1081. // remove heroes which didn't reached the end of the scenario, but were available at the start
  1082. for(auto hero : lostCrossoverHeroes)
  1083. {
  1084. // auto hero = CCampaignState::crossoverDeserialize(node);
  1085. vstd::erase_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [hero](CGHeroInstance * h)
  1086. {
  1087. return hero->subID == h->subID;
  1088. });
  1089. }
  1090. // now add heroes which completed the scenario
  1091. for(auto node : scenario.crossoverHeroes)
  1092. {
  1093. auto hero = CCampaignState::crossoverDeserialize(node);
  1094. // add new heroes and replace old heroes with newer ones
  1095. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [hero](CGHeroInstance * h)
  1096. {
  1097. return hero->subID == h->subID;
  1098. });
  1099. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  1100. {
  1101. // replace old hero with newer one
  1102. crossoverHeroes.heroesFromAnyPreviousScenarios[it - crossoverHeroes.heroesFromAnyPreviousScenarios.begin()] = hero;
  1103. }
  1104. else
  1105. {
  1106. // add new hero
  1107. crossoverHeroes.heroesFromAnyPreviousScenarios.push_back(hero);
  1108. }
  1109. if(mapNr == campaignState->mapsConquered.back())
  1110. {
  1111. crossoverHeroes.heroesFromPreviousScenario.push_back(hero);
  1112. }
  1113. }
  1114. }
  1115. }
  1116. }
  1117. return crossoverHeroes;
  1118. }
  1119. void CGameState::prepareCrossoverHeroes(std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions)
  1120. {
  1121. // create heroes list for convenience iterating
  1122. std::vector<CGHeroInstance *> crossoverHeroes;
  1123. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  1124. {
  1125. crossoverHeroes.push_back(campaignHeroReplacement.hero);
  1126. }
  1127. // TODO replace magic numbers with named constants
  1128. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  1129. if(!(travelOptions.whatHeroKeeps & 1))
  1130. {
  1131. //trimming experience
  1132. for(CGHeroInstance * cgh : crossoverHeroes)
  1133. {
  1134. cgh->initExp(getRandomGenerator());
  1135. }
  1136. }
  1137. if(!(travelOptions.whatHeroKeeps & 2))
  1138. {
  1139. //trimming prim skills
  1140. for(CGHeroInstance * cgh : crossoverHeroes)
  1141. {
  1142. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1143. {
  1144. auto sel = Selector::type()(Bonus::PRIMARY_SKILL)
  1145. .And(Selector::subtype()(g))
  1146. .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL));
  1147. cgh->getBonusLocalFirst(sel)->val = cgh->type->heroClass->primarySkillInitial[g];
  1148. }
  1149. }
  1150. }
  1151. if(!(travelOptions.whatHeroKeeps & 4))
  1152. {
  1153. //trimming sec skills
  1154. for(CGHeroInstance * cgh : crossoverHeroes)
  1155. {
  1156. cgh->secSkills = cgh->type->secSkillsInit;
  1157. cgh->recreateSecondarySkillsBonuses();
  1158. }
  1159. }
  1160. if(!(travelOptions.whatHeroKeeps & 8))
  1161. {
  1162. for(CGHeroInstance * cgh : crossoverHeroes)
  1163. {
  1164. cgh->removeSpellbook();
  1165. }
  1166. }
  1167. if(!(travelOptions.whatHeroKeeps & 16))
  1168. {
  1169. //trimming artifacts
  1170. for(CGHeroInstance * hero : crossoverHeroes)
  1171. {
  1172. size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
  1173. for (size_t i = 0; i < totalArts; i++ )
  1174. {
  1175. auto artifactPosition = ArtifactPosition((si32)i);
  1176. if(artifactPosition == ArtifactPosition::SPELLBOOK) continue; // do not handle spellbook this way
  1177. const ArtSlotInfo *info = hero->getSlot(artifactPosition);
  1178. if(!info)
  1179. continue;
  1180. // TODO: why would there be nullptr artifacts?
  1181. const CArtifactInstance *art = info->artifact;
  1182. if(!art)
  1183. continue;
  1184. int id = art->artType->id;
  1185. assert( 8*18 > id );//number of arts that fits into h3m format
  1186. bool takeable = travelOptions.artifsKeptByHero[id / 8] & ( 1 << (id%8) );
  1187. ArtifactLocation al(hero, artifactPosition);
  1188. if(!takeable && !al.getSlot()->locked) //don't try removing locked artifacts -> it crashes #1719
  1189. al.removeArtifact();
  1190. }
  1191. }
  1192. }
  1193. //trimming creatures
  1194. for(CGHeroInstance * cgh : crossoverHeroes)
  1195. {
  1196. auto shouldSlotBeErased = [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  1197. {
  1198. CreatureID::ECreatureID crid = j.second->getCreatureID().toEnum();
  1199. return !(travelOptions.monstersKeptByHero[crid / 8] & (1 << (crid % 8)));
  1200. };
  1201. auto stacksCopy = cgh->stacks; //copy of the map, so we can iterate iover it and remove stacks
  1202. for(auto &slotPair : stacksCopy)
  1203. if(shouldSlotBeErased(slotPair))
  1204. cgh->eraseStack(slotPair.first);
  1205. }
  1206. // Removing short-term bonuses
  1207. for(CGHeroInstance * cgh : crossoverHeroes)
  1208. {
  1209. cgh->removeBonusesRecursive(CSelector(Bonus::OneDay)
  1210. .Or(CSelector(Bonus::OneWeek))
  1211. .Or(CSelector(Bonus::NTurns))
  1212. .Or(CSelector(Bonus::NDays))
  1213. .Or(CSelector(Bonus::OneBattle)));
  1214. }
  1215. }
  1216. void CGameState::placeStartingHeroes()
  1217. {
  1218. logGlobal->debug("\tGiving starting hero");
  1219. for(auto & playerSettingPair : scenarioOps->playerInfos)
  1220. {
  1221. auto playerColor = playerSettingPair.first;
  1222. auto & playerInfo = map->players[playerColor.getNum()];
  1223. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  1224. {
  1225. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  1226. if(scenarioOps->campState)
  1227. {
  1228. if(auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap())
  1229. {
  1230. if(campaignBonus->type == CScenarioTravel::STravelBonus::HERO && playerColor == PlayerColor(campaignBonus->info1))
  1231. continue;
  1232. }
  1233. }
  1234. int heroTypeId = pickNextHeroType(playerColor);
  1235. if(playerSettingPair.second.hero == -1)
  1236. playerSettingPair.second.hero = heroTypeId;
  1237. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  1238. }
  1239. }
  1240. }
  1241. void CGameState::initStartingResources()
  1242. {
  1243. logGlobal->debug("\tSetting up resources");
  1244. const JsonNode config(ResourceID("config/startres.json"));
  1245. const JsonVector &vector = config["difficulty"].Vector();
  1246. const JsonNode &level = vector[scenarioOps->difficulty];
  1247. TResources startresAI(level["ai"]);
  1248. TResources startresHuman(level["human"]);
  1249. for (auto & elem : players)
  1250. {
  1251. PlayerState &p = elem.second;
  1252. if (p.human)
  1253. p.resources = startresHuman;
  1254. else
  1255. p.resources = startresAI;
  1256. }
  1257. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  1258. {
  1259. std::vector<const PlayerSettings *> ret;
  1260. for(auto it = scenarioOps->playerInfos.cbegin();
  1261. it != scenarioOps->playerInfos.cend(); ++it)
  1262. {
  1263. if(it->second.isControlledByHuman())
  1264. ret.push_back(&it->second);
  1265. }
  1266. return ret;
  1267. };
  1268. //give start resource bonus in case of campaign
  1269. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1270. {
  1271. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1272. if(chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1273. {
  1274. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1275. for(const PlayerSettings *ps : people)
  1276. {
  1277. std::vector<int> res; //resources we will give
  1278. switch (chosenBonus->info1)
  1279. {
  1280. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1281. res.push_back(chosenBonus->info1);
  1282. break;
  1283. case 0xFD: //wood+ore
  1284. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1285. break;
  1286. case 0xFE: //rare
  1287. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1288. break;
  1289. default:
  1290. assert(0);
  1291. break;
  1292. }
  1293. //increasing resource quantity
  1294. for (auto & re : res)
  1295. {
  1296. players[ps->color].resources[re] += chosenBonus->info2;
  1297. }
  1298. }
  1299. }
  1300. }
  1301. }
  1302. void CGameState::initHeroes()
  1303. {
  1304. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1305. {
  1306. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  1307. {
  1308. logGlobal->warn("Hero with uninitialized owner!");
  1309. continue;
  1310. }
  1311. hero->initHero(getRandomGenerator());
  1312. getPlayerState(hero->getOwner())->heroes.push_back(hero);
  1313. map->allHeroes[hero->type->ID.getNum()] = hero;
  1314. }
  1315. for(auto obj : map->objects) //prisons
  1316. {
  1317. if(obj && obj->ID == Obj::PRISON)
  1318. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  1319. }
  1320. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  1321. for(auto ph : map->predefinedHeroes)
  1322. {
  1323. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  1324. continue;
  1325. ph->initHero(getRandomGenerator());
  1326. hpool.heroesPool[ph->subID] = ph;
  1327. hpool.pavailable[ph->subID] = 0xff;
  1328. heroesToCreate.erase(ph->type->ID);
  1329. map->allHeroes[ph->subID] = ph;
  1330. }
  1331. for(HeroTypeID htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  1332. {
  1333. auto vhi = new CGHeroInstance();
  1334. vhi->initHero(getRandomGenerator(), htype);
  1335. int typeID = htype.getNum();
  1336. map->allHeroes[typeID] = vhi;
  1337. hpool.heroesPool[typeID] = vhi;
  1338. hpool.pavailable[typeID] = 0xff;
  1339. }
  1340. for(auto & elem : map->disposedHeroes)
  1341. {
  1342. hpool.pavailable[elem.heroId] = elem.players;
  1343. }
  1344. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1345. {
  1346. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1347. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1348. {
  1349. //find human player
  1350. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  1351. for (auto & elem : players)
  1352. {
  1353. if(elem.second.human)
  1354. {
  1355. humanPlayer = elem.first;
  1356. break;
  1357. }
  1358. }
  1359. assert(humanPlayer != PlayerColor::NEUTRAL);
  1360. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1361. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1362. {
  1363. int maxB = -1;
  1364. for (int b=0; b<heroes.size(); ++b)
  1365. {
  1366. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1367. {
  1368. maxB = b;
  1369. }
  1370. }
  1371. if(maxB < 0)
  1372. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  1373. else
  1374. giveCampaignBonusToHero(heroes[maxB]);
  1375. }
  1376. else //specific hero
  1377. {
  1378. for (auto & heroe : heroes)
  1379. {
  1380. if (heroe->subID == chosenBonus->info1)
  1381. {
  1382. giveCampaignBonusToHero(heroe);
  1383. break;
  1384. }
  1385. }
  1386. }
  1387. }
  1388. }
  1389. }
  1390. void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero)
  1391. {
  1392. const boost::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap();
  1393. if(!curBonus)
  1394. return;
  1395. if(curBonus->isBonusForHero())
  1396. {
  1397. //apply bonus
  1398. switch (curBonus->type)
  1399. {
  1400. case CScenarioTravel::STravelBonus::SPELL:
  1401. hero->addSpellToSpellbook(SpellID(curBonus->info2));
  1402. break;
  1403. case CScenarioTravel::STravelBonus::MONSTER:
  1404. {
  1405. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  1406. {
  1407. if(hero->slotEmpty(SlotID(i)))
  1408. {
  1409. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  1410. break;
  1411. }
  1412. }
  1413. }
  1414. break;
  1415. case CScenarioTravel::STravelBonus::ARTIFACT:
  1416. gs->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2));
  1417. break;
  1418. case CScenarioTravel::STravelBonus::SPELL_SCROLL:
  1419. {
  1420. CArtifactInstance * scroll = CArtifactInstance::createScroll(SpellID(curBonus->info2));
  1421. scroll->putAt(ArtifactLocation(hero, scroll->firstAvailableSlot(hero)));
  1422. }
  1423. break;
  1424. case CScenarioTravel::STravelBonus::PRIMARY_SKILL:
  1425. {
  1426. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus->info2);
  1427. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1428. {
  1429. int val = ptr[g];
  1430. if (val == 0)
  1431. {
  1432. continue;
  1433. }
  1434. auto bb = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, *scenarioOps->campState->currentMap, g);
  1435. hero->addNewBonus(bb);
  1436. }
  1437. }
  1438. break;
  1439. case CScenarioTravel::STravelBonus::SECONDARY_SKILL:
  1440. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  1441. break;
  1442. }
  1443. }
  1444. }
  1445. void CGameState::initFogOfWar()
  1446. {
  1447. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  1448. int layers = map->levels();
  1449. for(auto & elem : teams)
  1450. {
  1451. auto fow = elem.second.fogOfWarMap;
  1452. fow->resize(boost::extents[layers][map->width][map->height]);
  1453. std::fill(fow->data(), fow->data() + fow->num_elements(), 0);
  1454. for(CGObjectInstance *obj : map->objects)
  1455. {
  1456. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  1457. std::unordered_set<int3, ShashInt3> tiles;
  1458. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius(), obj->tempOwner, 1);
  1459. for(int3 tile : tiles)
  1460. {
  1461. (*elem.second.fogOfWarMap)[tile.z][tile.x][tile.y] = 1;
  1462. }
  1463. }
  1464. }
  1465. }
  1466. void CGameState::initStartingBonus()
  1467. {
  1468. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1469. return;
  1470. // These are the single scenario bonuses; predefined
  1471. // campaign bonuses are spread out over other init* functions.
  1472. logGlobal->debug("\tStarting bonuses");
  1473. for(auto & elem : players)
  1474. {
  1475. //starting bonus
  1476. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  1477. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(getRandomGenerator().nextInt(2));
  1478. switch(scenarioOps->playerInfos[elem.first].bonus)
  1479. {
  1480. case PlayerSettings::GOLD:
  1481. elem.second.resources[Res::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  1482. break;
  1483. case PlayerSettings::RESOURCE:
  1484. {
  1485. int res = (*VLC->townh)[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  1486. if(res == Res::WOOD_AND_ORE)
  1487. {
  1488. int amount = getRandomGenerator().nextInt(5, 10);
  1489. elem.second.resources[Res::WOOD] += amount;
  1490. elem.second.resources[Res::ORE] += amount;
  1491. }
  1492. else
  1493. {
  1494. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  1495. }
  1496. break;
  1497. }
  1498. case PlayerSettings::ARTIFACT:
  1499. {
  1500. if(!elem.second.heroes.size())
  1501. {
  1502. logGlobal->error("Cannot give starting artifact - no heroes!");
  1503. break;
  1504. }
  1505. const Artifact * toGive = VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE).toArtifact(VLC->artifacts());
  1506. CGHeroInstance *hero = elem.second.heroes[0];
  1507. giveHeroArtifact(hero, toGive->getId());
  1508. }
  1509. break;
  1510. }
  1511. }
  1512. }
  1513. void CGameState::initTowns()
  1514. {
  1515. logGlobal->debug("\tTowns");
  1516. //campaign bonuses for towns
  1517. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1518. {
  1519. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1520. if (chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1521. {
  1522. for (int g=0; g<map->towns.size(); ++g)
  1523. {
  1524. PlayerState * owner = getPlayerState(map->towns[g]->getOwner());
  1525. if (owner)
  1526. {
  1527. PlayerInfo & pi = map->players[owner->color.getNum()];
  1528. if (owner->human && //human-owned
  1529. map->towns[g]->pos == pi.posOfMainTown)
  1530. {
  1531. map->towns[g]->builtBuildings.insert(
  1532. CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->subID, map->towns[g]->builtBuildings));
  1533. break;
  1534. }
  1535. }
  1536. }
  1537. }
  1538. }
  1539. CGTownInstance::universitySkills.clear();
  1540. for ( int i=0; i<4; i++)
  1541. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1542. for (auto & elem : map->towns)
  1543. {
  1544. CGTownInstance * vti =(elem);
  1545. if(!vti->town)
  1546. {
  1547. vti->town = (*VLC->townh)[vti->subID]->town;
  1548. }
  1549. if(vti->name.empty())
  1550. {
  1551. vti->name = *RandomGeneratorUtil::nextItem(vti->town->names, getRandomGenerator());
  1552. }
  1553. //init buildings
  1554. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  1555. {
  1556. vti->builtBuildings.erase(BuildingID::DEFAULT);
  1557. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1558. if(vti->tempOwner != PlayerColor::NEUTRAL)
  1559. vti->builtBuildings.insert(BuildingID::TAVERN);
  1560. vti->builtBuildings.insert(BuildingID::DWELL_FIRST);
  1561. if(getRandomGenerator().nextInt(1) == 1)
  1562. {
  1563. vti->builtBuildings.insert(BuildingID::DWELL_LVL_2);
  1564. }
  1565. }
  1566. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  1567. vstd::erase_if(vti->builtBuildings, [vti](BuildingID bid){
  1568. return !vti->town->buildings.count(bid) || !vti->town->buildings.at(bid); });
  1569. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  1570. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1571. //init hordes
  1572. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1573. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1574. {
  1575. vti->builtBuildings.erase(BuildingID(-31-i));//remove old ID
  1576. if (vti->town->hordeLvl.at(0) == i)//if town first horde is this one
  1577. {
  1578. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  1579. if (vstd::contains(vti->builtBuildings,(BuildingID::DWELL_UP_FIRST+i)))//if we have upgraded dwelling as well
  1580. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  1581. }
  1582. if (vti->town->hordeLvl.at(1) == i)//if town second horde is this one
  1583. {
  1584. vti->builtBuildings.insert(BuildingID::HORDE_2);
  1585. if (vstd::contains(vti->builtBuildings,(BuildingID::DWELL_UP_FIRST+i)))
  1586. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  1587. }
  1588. }
  1589. //Early check for #1444-like problems
  1590. for(auto building : vti->builtBuildings)
  1591. {
  1592. assert(vti->town->buildings.at(building) != nullptr);
  1593. MAYBE_UNUSED(building);
  1594. }
  1595. //town events
  1596. for(CCastleEvent &ev : vti->events)
  1597. {
  1598. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1599. if (vstd::contains(ev.buildings,(-31-i))) //if we have horde for this level
  1600. {
  1601. ev.buildings.erase(BuildingID(-31-i));
  1602. if (vti->town->hordeLvl.at(0) == i)
  1603. ev.buildings.insert(BuildingID::HORDE_1);
  1604. if (vti->town->hordeLvl.at(1) == i)
  1605. ev.buildings.insert(BuildingID::HORDE_2);
  1606. }
  1607. }
  1608. //init spells
  1609. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1610. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1611. {
  1612. auto s = vti->obligatorySpells[z].toSpell();
  1613. vti->spells[s->level-1].push_back(s->id);
  1614. vti->possibleSpells -= s->id;
  1615. }
  1616. while(vti->possibleSpells.size())
  1617. {
  1618. ui32 total=0;
  1619. int sel = -1;
  1620. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1621. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->subID);
  1622. if (total == 0) // remaining spells have 0 probability
  1623. break;
  1624. auto r = getRandomGenerator().nextInt(total - 1);
  1625. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1626. {
  1627. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->subID);
  1628. if(r<0)
  1629. {
  1630. sel = ps;
  1631. break;
  1632. }
  1633. }
  1634. if(sel<0)
  1635. sel=0;
  1636. auto s = vti->possibleSpells[sel].toSpell();
  1637. vti->spells[s->level-1].push_back(s->id);
  1638. vti->possibleSpells -= s->id;
  1639. }
  1640. vti->possibleSpells.clear();
  1641. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1642. getPlayerState(vti->getOwner())->towns.push_back(vti);
  1643. }
  1644. }
  1645. void CGameState::initMapObjects()
  1646. {
  1647. logGlobal->debug("\tObject initialization");
  1648. VLC->creh->removeBonusesFromAllCreatures();
  1649. // objCaller->preInit();
  1650. for(CGObjectInstance *obj : map->objects)
  1651. {
  1652. if(obj)
  1653. {
  1654. logGlobal->trace("Calling Init for object %d, %s, %s", obj->id.getNum(), obj->typeName, obj->subTypeName);
  1655. obj->initObj(getRandomGenerator());
  1656. }
  1657. }
  1658. for(CGObjectInstance *obj : map->objects)
  1659. {
  1660. if(!obj)
  1661. continue;
  1662. switch (obj->ID)
  1663. {
  1664. case Obj::QUEST_GUARD:
  1665. case Obj::SEER_HUT:
  1666. {
  1667. auto q = static_cast<CGSeerHut*>(obj);
  1668. assert (q);
  1669. q->setObjToKill();
  1670. }
  1671. }
  1672. }
  1673. CGSubterraneanGate::postInit(); //pairing subterranean gates
  1674. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  1675. }
  1676. void CGameState::placeHeroesInTowns()
  1677. {
  1678. for(auto k=players.begin(); k!=players.end(); ++k)
  1679. {
  1680. if(k->first==PlayerColor::NEUTRAL)
  1681. continue;
  1682. for(CGHeroInstance *h : k->second.heroes)
  1683. {
  1684. for(CGTownInstance *t : k->second.towns)
  1685. {
  1686. bool heroOnTownBlockableTile = t->blockingAt(h->visitablePos().x, h->visitablePos().y);
  1687. // current hero position is at one of blocking tiles of current town
  1688. // assume that this hero should be visiting the town (H3M format quirk) and move hero to correct position
  1689. if (heroOnTownBlockableTile)
  1690. {
  1691. int3 correctedPos = h->convertFromVisitablePos(t->visitablePos());
  1692. map->removeBlockVisTiles(h);
  1693. h->pos = correctedPos;
  1694. map->addBlockVisTiles(h);
  1695. assert(t->visitableAt(h->visitablePos().x, h->visitablePos().y));
  1696. }
  1697. }
  1698. }
  1699. }
  1700. }
  1701. void CGameState::initVisitingAndGarrisonedHeroes()
  1702. {
  1703. for(auto k=players.begin(); k!=players.end(); ++k)
  1704. {
  1705. if(k->first==PlayerColor::NEUTRAL)
  1706. continue;
  1707. //init visiting and garrisoned heroes
  1708. for(CGHeroInstance *h : k->second.heroes)
  1709. {
  1710. for(CGTownInstance *t : k->second.towns)
  1711. {
  1712. if (t->visitableAt(h->visitablePos().x, h->visitablePos().y))
  1713. {
  1714. assert(t->visitingHero == nullptr);
  1715. t->setVisitingHero(h);
  1716. }
  1717. }
  1718. }
  1719. }
  1720. for (auto hero : map->heroesOnMap)
  1721. {
  1722. if (hero->visitedTown)
  1723. {
  1724. assert (hero->visitedTown->visitingHero == hero);
  1725. }
  1726. }
  1727. }
  1728. BattleField CGameState::battleGetBattlefieldType(int3 tile, CRandomGenerator & rand)
  1729. {
  1730. if(!tile.valid() && curB)
  1731. tile = curB->tile;
  1732. else if(!tile.valid() && !curB)
  1733. return BattleField::NONE;
  1734. const TerrainTile &t = map->getTile(tile);
  1735. auto topObject = t.visitableObjects.front();
  1736. if(topObject && topObject->getBattlefield() != BattleField::NONE)
  1737. {
  1738. return topObject->getBattlefield();
  1739. }
  1740. for(auto &obj : map->objects)
  1741. {
  1742. //look only for objects covering given tile
  1743. if( !obj || obj->pos.z != tile.z || !obj->coveringAt(tile.x, tile.y))
  1744. continue;
  1745. auto customBattlefield = obj->getBattlefield();
  1746. if(customBattlefield != BattleField::NONE)
  1747. return customBattlefield;
  1748. }
  1749. if(map->isCoastalTile(tile)) //coastal tile is always ground
  1750. return BattleField::fromString("sand_shore");
  1751. return BattleField::fromString(
  1752. *RandomGeneratorUtil::nextItem(t.terType->battleFields, rand));
  1753. }
  1754. void CGameState::fillUpgradeInfo(const CArmedInstance *obj, SlotID stackPos, UpgradeInfo &out) const
  1755. {
  1756. assert(obj);
  1757. assert(obj->hasStackAtSlot(stackPos));
  1758. out = fillUpgradeInfo(obj->getStack(stackPos));
  1759. }
  1760. UpgradeInfo CGameState::fillUpgradeInfo(const CStackInstance &stack) const
  1761. {
  1762. UpgradeInfo ret;
  1763. const CCreature *base = stack.type;
  1764. const CGHeroInstance *h = stack.armyObj->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(stack.armyObj) : nullptr;
  1765. const CGTownInstance *t = nullptr;
  1766. if(stack.armyObj->ID == Obj::TOWN)
  1767. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1768. else if(h)
  1769. { //hero specialty
  1770. TConstBonusListPtr lista = h->getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1771. for(const auto & it : *lista)
  1772. {
  1773. auto nid = CreatureID(it->additionalInfo[0]);
  1774. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1775. {
  1776. ret.newID.push_back(nid);
  1777. ret.cost.push_back(VLC->creh->objects[nid]->cost - base->cost);
  1778. }
  1779. }
  1780. t = h->visitedTown;
  1781. }
  1782. if(t)
  1783. {
  1784. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : t->creatures)
  1785. {
  1786. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1787. {
  1788. for(auto upgrID : dwelling.second)
  1789. {
  1790. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1791. {
  1792. ret.newID.push_back(upgrID);
  1793. ret.cost.push_back(VLC->creh->objects[upgrID]->cost - base->cost);
  1794. }
  1795. }
  1796. }
  1797. }
  1798. }
  1799. //hero is visiting Hill Fort
  1800. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == Obj::HILL_FORT)
  1801. {
  1802. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1803. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1804. for(auto nid : base->upgrades)
  1805. {
  1806. ret.newID.push_back(nid);
  1807. ret.cost.push_back((VLC->creh->objects[nid]->cost - base->cost) * costModifier / 100);
  1808. }
  1809. }
  1810. if(ret.newID.size())
  1811. ret.oldID = base->idNumber;
  1812. for (Res::ResourceSet &cost : ret.cost)
  1813. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1814. return ret;
  1815. }
  1816. PlayerRelations::PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 ) const
  1817. {
  1818. if ( color1 == color2 )
  1819. return PlayerRelations::SAME_PLAYER;
  1820. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1821. return PlayerRelations::ENEMIES;
  1822. const TeamState * ts = getPlayerTeam(color1);
  1823. if (ts && vstd::contains(ts->players, color2))
  1824. return PlayerRelations::ALLIES;
  1825. return PlayerRelations::ENEMIES;
  1826. }
  1827. void CGameState::apply(CPack *pack)
  1828. {
  1829. ui16 typ = typeList.getTypeID(pack);
  1830. applier->getApplier(typ)->applyOnGS(this, pack);
  1831. }
  1832. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  1833. {
  1834. calculatePaths(std::make_shared<SingleHeroPathfinderConfig>(out, this, hero));
  1835. }
  1836. void CGameState::calculatePaths(std::shared_ptr<PathfinderConfig> config)
  1837. {
  1838. //FIXME: creating pathfinder is costly, maybe reset / clear is enough?
  1839. CPathfinder pathfinder(this, config);
  1840. pathfinder.calculatePaths();
  1841. }
  1842. /**
  1843. * Tells if the tile is guarded by a monster as well as the position
  1844. * of the monster that will attack on it.
  1845. *
  1846. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1847. * the monster guarding the tile.
  1848. */
  1849. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1850. {
  1851. std::vector<CGObjectInstance*> guards;
  1852. const int3 originalPos = pos;
  1853. if (!map->isInTheMap(pos))
  1854. return guards;
  1855. const TerrainTile &posTile = map->getTile(pos);
  1856. if (posTile.visitable)
  1857. {
  1858. for (CGObjectInstance* obj : posTile.visitableObjects)
  1859. {
  1860. if(obj->blockVisit)
  1861. {
  1862. if (obj->ID == Obj::MONSTER) // Monster
  1863. guards.push_back(obj);
  1864. }
  1865. }
  1866. }
  1867. pos -= int3(1, 1, 0); // Start with top left.
  1868. for (int dx = 0; dx < 3; dx++)
  1869. {
  1870. for (int dy = 0; dy < 3; dy++)
  1871. {
  1872. if (map->isInTheMap(pos))
  1873. {
  1874. const auto & tile = map->getTile(pos);
  1875. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1876. {
  1877. for (CGObjectInstance* obj : tile.visitableObjects)
  1878. {
  1879. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1880. {
  1881. guards.push_back(obj);
  1882. }
  1883. }
  1884. }
  1885. }
  1886. pos.y++;
  1887. }
  1888. pos.y -= 3;
  1889. pos.x++;
  1890. }
  1891. return guards;
  1892. }
  1893. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1894. {
  1895. return gs->map->guardingCreaturePositions[pos.z][pos.x][pos.y];
  1896. }
  1897. void CGameState::updateRumor()
  1898. {
  1899. static std::vector<RumorState::ERumorType> rumorTypes = {RumorState::TYPE_MAP, RumorState::TYPE_SPECIAL, RumorState::TYPE_RAND, RumorState::TYPE_RAND};
  1900. std::vector<RumorState::ERumorTypeSpecial> sRumorTypes = {
  1901. RumorState::RUMOR_OBELISKS, RumorState::RUMOR_ARTIFACTS, RumorState::RUMOR_ARMY, RumorState::RUMOR_INCOME};
  1902. if(map->grailPos.valid()) // Grail should always be on map, but I had related crash I didn't manage to reproduce
  1903. sRumorTypes.push_back(RumorState::RUMOR_GRAIL);
  1904. int rumorId = -1, rumorExtra = -1;
  1905. auto & rand = getRandomGenerator();
  1906. rumor.type = *RandomGeneratorUtil::nextItem(rumorTypes, rand);
  1907. do
  1908. {
  1909. switch(rumor.type)
  1910. {
  1911. case RumorState::TYPE_SPECIAL:
  1912. {
  1913. SThievesGuildInfo tgi;
  1914. obtainPlayersStats(tgi, 20);
  1915. rumorId = *RandomGeneratorUtil::nextItem(sRumorTypes, rand);
  1916. if(rumorId == RumorState::RUMOR_GRAIL)
  1917. {
  1918. rumorExtra = getTile(map->grailPos)->terType->id;
  1919. break;
  1920. }
  1921. std::vector<PlayerColor> players = {};
  1922. switch(rumorId)
  1923. {
  1924. case RumorState::RUMOR_OBELISKS:
  1925. players = tgi.obelisks[0];
  1926. break;
  1927. case RumorState::RUMOR_ARTIFACTS:
  1928. players = tgi.artifacts[0];
  1929. break;
  1930. case RumorState::RUMOR_ARMY:
  1931. players = tgi.army[0];
  1932. break;
  1933. case RumorState::RUMOR_INCOME:
  1934. players = tgi.income[0];
  1935. break;
  1936. }
  1937. rumorExtra = RandomGeneratorUtil::nextItem(players, rand)->getNum();
  1938. break;
  1939. }
  1940. case RumorState::TYPE_MAP:
  1941. // Makes sure that map rumors only used if there enough rumors too choose from
  1942. if(map->rumors.size() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
  1943. {
  1944. rumorId = rand.nextInt((int)map->rumors.size() - 1);
  1945. break;
  1946. }
  1947. else
  1948. rumor.type = RumorState::TYPE_RAND;
  1949. FALLTHROUGH
  1950. case RumorState::TYPE_RAND:
  1951. do
  1952. {
  1953. rumorId = rand.nextInt((int)VLC->generaltexth->tavernRumors.size() - 1);
  1954. }
  1955. while(!VLC->generaltexth->tavernRumors[rumorId].length());
  1956. break;
  1957. }
  1958. }
  1959. while(!rumor.update(rumorId, rumorExtra));
  1960. }
  1961. bool CGameState::isVisible(int3 pos, boost::optional<PlayerColor> player) const
  1962. {
  1963. if (!map->isInTheMap(pos))
  1964. return false;
  1965. if (!player)
  1966. return true;
  1967. if(player == PlayerColor::NEUTRAL)
  1968. return false;
  1969. if(player->isSpectator())
  1970. return true;
  1971. return (*getPlayerTeam(*player)->fogOfWarMap)[pos.z][pos.x][pos.y];
  1972. }
  1973. bool CGameState::isVisible( const CGObjectInstance *obj, boost::optional<PlayerColor> player ) const
  1974. {
  1975. if(!player)
  1976. return true;
  1977. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1978. if (player == obj->tempOwner)
  1979. return true;
  1980. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1981. return false;
  1982. //object is visible when at least one blocked tile is visible
  1983. for(int fy=0; fy < obj->getHeight(); ++fy)
  1984. {
  1985. for(int fx=0; fx < obj->getWidth(); ++fx)
  1986. {
  1987. int3 pos = obj->pos + int3(-fx, -fy, 0);
  1988. if ( map->isInTheMap(pos) &&
  1989. obj->coveringAt(pos.x, pos.y) &&
  1990. isVisible(pos, *player))
  1991. return true;
  1992. }
  1993. }
  1994. return false;
  1995. }
  1996. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1997. {
  1998. const TerrainTile * pom = &map->getTile(dst);
  1999. return map->checkForVisitableDir(src, pom, dst);
  2000. }
  2001. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(PlayerColor player) const
  2002. {
  2003. const std::string & messageWonSelf = VLC->generaltexth->allTexts[659];
  2004. const std::string & messageWonOther = VLC->generaltexth->allTexts[5];
  2005. const std::string & messageLostSelf = VLC->generaltexth->allTexts[7];
  2006. const std::string & messageLostOther = VLC->generaltexth->allTexts[8];
  2007. auto evaluateEvent = [=](const EventCondition & condition)
  2008. {
  2009. return this->checkForVictory(player, condition);
  2010. };
  2011. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  2012. //cheater or tester, but has entered the code...
  2013. if (p->enteredWinningCheatCode)
  2014. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  2015. if (p->enteredLosingCheatCode)
  2016. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  2017. for (const TriggeredEvent & event : map->triggeredEvents)
  2018. {
  2019. if (event.trigger.test(evaluateEvent))
  2020. {
  2021. if (event.effect.type == EventEffect::VICTORY)
  2022. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  2023. if (event.effect.type == EventEffect::DEFEAT)
  2024. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  2025. }
  2026. }
  2027. if (checkForStandardLoss(player))
  2028. {
  2029. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  2030. }
  2031. return EVictoryLossCheckResult();
  2032. }
  2033. bool CGameState::checkForVictory(PlayerColor player, const EventCondition & condition) const
  2034. {
  2035. const PlayerState *p = CGameInfoCallback::getPlayerState(player);
  2036. switch (condition.condition)
  2037. {
  2038. case EventCondition::STANDARD_WIN:
  2039. {
  2040. return player == checkForStandardWin();
  2041. }
  2042. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  2043. {
  2044. for(auto & elem : p->heroes)
  2045. if(elem->hasArt(ArtifactID(condition.objectType)))
  2046. return true;
  2047. return false;
  2048. }
  2049. case EventCondition::HAVE_CREATURES:
  2050. {
  2051. //check if in players armies there is enough creatures
  2052. int total = 0; //creature counter
  2053. for(size_t i = 0; i < map->objects.size(); i++)
  2054. {
  2055. const CArmedInstance *ai = nullptr;
  2056. if(map->objects[i]
  2057. && map->objects[i]->tempOwner == player //object controlled by player
  2058. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  2059. {
  2060. for(auto & elem : ai->Slots()) //iterate through army
  2061. if(elem.second->type->idNumber == condition.objectType) //it's searched creature
  2062. total += elem.second->count;
  2063. }
  2064. }
  2065. return total >= condition.value;
  2066. }
  2067. case EventCondition::HAVE_RESOURCES:
  2068. {
  2069. return p->resources[condition.objectType] >= condition.value;
  2070. }
  2071. case EventCondition::HAVE_BUILDING:
  2072. {
  2073. if (condition.object) // specific town
  2074. {
  2075. const CGTownInstance *t = static_cast<const CGTownInstance *>(condition.object);
  2076. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  2077. }
  2078. else // any town
  2079. {
  2080. for (const CGTownInstance * t : p->towns)
  2081. {
  2082. if (t->hasBuilt(BuildingID(condition.objectType)))
  2083. return true;
  2084. }
  2085. return false;
  2086. }
  2087. }
  2088. case EventCondition::DESTROY:
  2089. {
  2090. if (condition.object) // mode A - destroy specific object of this type
  2091. {
  2092. if (auto hero = dynamic_cast<const CGHeroInstance*>(condition.object))
  2093. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  2094. else
  2095. return getObj(condition.object->id) == nullptr;
  2096. }
  2097. else
  2098. {
  2099. for(auto & elem : map->objects) // mode B - destroy all objects of this type
  2100. {
  2101. if(elem && elem->ID == condition.objectType)
  2102. return false;
  2103. }
  2104. return true;
  2105. }
  2106. }
  2107. case EventCondition::CONTROL:
  2108. {
  2109. // list of players that need to control object to fulfull condition
  2110. // NOTE: cgameinfocallback specified explicitly in order to get const version
  2111. auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  2112. if (condition.object) // mode A - flag one specific object, like town
  2113. {
  2114. return team.count(condition.object->tempOwner) != 0;
  2115. }
  2116. else
  2117. {
  2118. for(auto & elem : map->objects) // mode B - flag all objects of this type
  2119. {
  2120. //check not flagged objs
  2121. if ( elem && elem->ID == condition.objectType && team.count(elem->tempOwner) == 0 )
  2122. return false;
  2123. }
  2124. return true;
  2125. }
  2126. }
  2127. case EventCondition::TRANSPORT:
  2128. {
  2129. const CGTownInstance *t = static_cast<const CGTownInstance *>(condition.object);
  2130. if((t->visitingHero && t->visitingHero->hasArt(ArtifactID(condition.objectType)))
  2131. || (t->garrisonHero && t->garrisonHero->hasArt(ArtifactID(condition.objectType))))
  2132. {
  2133. return true;
  2134. }
  2135. return false;
  2136. }
  2137. case EventCondition::DAYS_PASSED:
  2138. {
  2139. return (si32)gs->day > condition.value;
  2140. }
  2141. case EventCondition::IS_HUMAN:
  2142. {
  2143. return p->human ? condition.value == 1 : condition.value == 0;
  2144. }
  2145. case EventCondition::DAYS_WITHOUT_TOWN:
  2146. {
  2147. if (p->daysWithoutCastle)
  2148. return p->daysWithoutCastle.get() >= condition.value;
  2149. else
  2150. return false;
  2151. }
  2152. case EventCondition::CONST_VALUE:
  2153. {
  2154. return condition.value; // just convert to bool
  2155. }
  2156. case EventCondition::HAVE_0:
  2157. {
  2158. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2159. //TODO: support new condition format
  2160. return false;
  2161. }
  2162. case EventCondition::HAVE_BUILDING_0:
  2163. {
  2164. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2165. //TODO: support new condition format
  2166. return false;
  2167. }
  2168. case EventCondition::DESTROY_0:
  2169. {
  2170. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2171. //TODO: support new condition format
  2172. return false;
  2173. }
  2174. default:
  2175. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  2176. return false;
  2177. }
  2178. }
  2179. PlayerColor CGameState::checkForStandardWin() const
  2180. {
  2181. //std victory condition is:
  2182. //all enemies lost
  2183. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  2184. TeamID winnerTeam = TeamID::NO_TEAM;
  2185. for(auto & elem : players)
  2186. {
  2187. if(elem.second.status == EPlayerStatus::INGAME && elem.first < PlayerColor::PLAYER_LIMIT)
  2188. {
  2189. if(supposedWinner == PlayerColor::NEUTRAL)
  2190. {
  2191. //first player remaining ingame - candidate for victory
  2192. supposedWinner = elem.second.color;
  2193. winnerTeam = elem.second.team;
  2194. }
  2195. else if(winnerTeam != elem.second.team)
  2196. {
  2197. //current candidate has enemy remaining in game -> no vicotry
  2198. return PlayerColor::NEUTRAL;
  2199. }
  2200. }
  2201. }
  2202. return supposedWinner;
  2203. }
  2204. bool CGameState::checkForStandardLoss( PlayerColor player ) const
  2205. {
  2206. //std loss condition is: player lost all towns and heroes
  2207. const PlayerState & pState = *CGameInfoCallback::getPlayerState(player);
  2208. return pState.checkVanquished();
  2209. }
  2210. struct statsHLP
  2211. {
  2212. typedef std::pair< PlayerColor, si64 > TStat;
  2213. //converts [<player's color, value>] to vec[place] -> platers
  2214. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  2215. {
  2216. std::sort(stats.begin(), stats.end(), statsHLP());
  2217. //put first element
  2218. std::vector< std::vector<PlayerColor> > ret;
  2219. std::vector<PlayerColor> tmp;
  2220. tmp.push_back( stats[0].first );
  2221. ret.push_back( tmp );
  2222. //the rest of elements
  2223. for(int g=1; g<stats.size(); ++g)
  2224. {
  2225. if(stats[g].second == stats[g-1].second)
  2226. {
  2227. (ret.end()-1)->push_back( stats[g].first );
  2228. }
  2229. else
  2230. {
  2231. //create next occupied rank
  2232. std::vector<PlayerColor> tmp;
  2233. tmp.push_back(stats[g].first);
  2234. ret.push_back(tmp);
  2235. }
  2236. }
  2237. return ret;
  2238. }
  2239. bool operator()(const TStat & a, const TStat & b) const
  2240. {
  2241. return a.second > b.second;
  2242. }
  2243. static const CGHeroInstance * findBestHero(CGameState * gs, PlayerColor color)
  2244. {
  2245. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2246. if(!h.size())
  2247. return nullptr;
  2248. //best hero will be that with highest exp
  2249. int best = 0;
  2250. for(int b=1; b<h.size(); ++b)
  2251. {
  2252. if(h[b]->exp > h[best]->exp)
  2253. {
  2254. best = b;
  2255. }
  2256. }
  2257. return h[best];
  2258. }
  2259. //calculates total number of artifacts that belong to given player
  2260. static int getNumberOfArts(const PlayerState * ps)
  2261. {
  2262. int ret = 0;
  2263. for(auto h : ps->heroes)
  2264. {
  2265. ret += (int)h->artifactsInBackpack.size() + (int)h->artifactsWorn.size();
  2266. }
  2267. return ret;
  2268. }
  2269. // get total strength of player army
  2270. static si64 getArmyStrength(const PlayerState * ps)
  2271. {
  2272. si64 str = 0;
  2273. for(auto h : ps->heroes)
  2274. {
  2275. if(!h->inTownGarrison) //original h3 behavior
  2276. str += h->getArmyStrength();
  2277. }
  2278. return str;
  2279. }
  2280. // get total gold income
  2281. static int getIncome(const PlayerState * ps)
  2282. {
  2283. int totalIncome = 0;
  2284. const CGObjectInstance * heroOrTown = nullptr;
  2285. //Heroes can produce gold as well - skill, specialty or arts
  2286. for(auto & h : ps->heroes)
  2287. {
  2288. totalIncome += h->valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ESTATES));
  2289. totalIncome += h->valOfBonuses(Selector::typeSubtype(Bonus::GENERATE_RESOURCE, Res::GOLD));
  2290. if(!heroOrTown)
  2291. heroOrTown = h;
  2292. }
  2293. //Add town income of all towns
  2294. for(auto & t : ps->towns)
  2295. {
  2296. totalIncome += t->dailyIncome()[Res::GOLD];
  2297. if(!heroOrTown)
  2298. heroOrTown = t;
  2299. }
  2300. /// FIXME: Dirty dirty hack
  2301. /// Stats helper need some access to gamestate.
  2302. std::vector<const CGObjectInstance *> ownedObjects;
  2303. for(const CGObjectInstance * obj : heroOrTown->cb->gameState()->map->objects)
  2304. {
  2305. if(obj && obj->tempOwner == ps->color)
  2306. ownedObjects.push_back(obj);
  2307. }
  2308. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  2309. /// I'm really need to find out about callback interface design...
  2310. for(auto object : ownedObjects)
  2311. {
  2312. //Mines
  2313. if ( object->ID == Obj::MINE )
  2314. {
  2315. const CGMine *mine = dynamic_cast<const CGMine*>(object);
  2316. assert(mine);
  2317. if (mine->producedResource == Res::GOLD)
  2318. totalIncome += mine->producedQuantity;
  2319. }
  2320. }
  2321. return totalIncome;
  2322. }
  2323. };
  2324. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2325. {
  2326. auto playerInactive = [&](PlayerColor color)
  2327. {
  2328. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  2329. };
  2330. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2331. { \
  2332. std::vector< std::pair< PlayerColor, si64 > > stats; \
  2333. for(auto g = players.begin(); g != players.end(); ++g) \
  2334. { \
  2335. if(playerInactive(g->second.color)) \
  2336. continue; \
  2337. std::pair< PlayerColor, si64 > stat; \
  2338. stat.first = g->second.color; \
  2339. stat.second = VAL_GETTER; \
  2340. stats.push_back(stat); \
  2341. } \
  2342. tgi.FIELD = statsHLP::getRank(stats); \
  2343. }
  2344. for(auto & elem : players)
  2345. {
  2346. if(!playerInactive(elem.second.color))
  2347. tgi.playerColors.push_back(elem.second.color);
  2348. }
  2349. if(level >= 0) //num of towns & num of heroes
  2350. {
  2351. //num of towns
  2352. FILL_FIELD(numOfTowns, g->second.towns.size())
  2353. //num of heroes
  2354. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2355. }
  2356. if(level >= 1) //best hero's portrait
  2357. {
  2358. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2359. {
  2360. if(playerInactive(g->second.color))
  2361. continue;
  2362. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2363. InfoAboutHero iah;
  2364. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  2365. iah.army.clear();
  2366. tgi.colorToBestHero[g->second.color] = iah;
  2367. }
  2368. }
  2369. if(level >= 2) //gold
  2370. {
  2371. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2372. }
  2373. if(level >= 2) //wood & ore
  2374. {
  2375. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2376. }
  2377. if(level >= 3) //mercury, sulfur, crystal, gems
  2378. {
  2379. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2380. }
  2381. if(level >= 3) //obelisks found
  2382. {
  2383. auto getObeliskVisited = [](TeamID t)
  2384. {
  2385. if(CGObelisk::visited.count(t))
  2386. return CGObelisk::visited[t];
  2387. else
  2388. return ui8(0);
  2389. };
  2390. FILL_FIELD(obelisks, getObeliskVisited(gs->getPlayerTeam(g->second.color)->id))
  2391. }
  2392. if(level >= 4) //artifacts
  2393. {
  2394. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2395. }
  2396. if(level >= 4) //army strength
  2397. {
  2398. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  2399. }
  2400. if(level >= 5) //income
  2401. {
  2402. FILL_FIELD(income, statsHLP::getIncome(&g->second))
  2403. }
  2404. if(level >= 2) //best hero's stats
  2405. {
  2406. //already set in lvl 1 handling
  2407. }
  2408. if(level >= 3) //personality
  2409. {
  2410. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2411. {
  2412. if(playerInactive(g->second.color)) //do nothing for neutral player
  2413. continue;
  2414. if(g->second.human)
  2415. {
  2416. tgi.personality[g->second.color] = EAiTactic::NONE;
  2417. }
  2418. else //AI
  2419. {
  2420. tgi.personality[g->second.color] = map->players[g->second.color.getNum()].aiTactic;
  2421. }
  2422. }
  2423. }
  2424. if(level >= 4) //best creature
  2425. {
  2426. //best creatures belonging to player (highest AI value)
  2427. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2428. {
  2429. if(playerInactive(g->second.color)) //do nothing for neutral player
  2430. continue;
  2431. int bestCre = -1; //best creature's ID
  2432. for(auto & elem : g->second.heroes)
  2433. {
  2434. for(auto it = elem->Slots().begin(); it != elem->Slots().end(); ++it)
  2435. {
  2436. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2437. if(bestCre == -1 || VLC->creh->objects[bestCre]->AIValue < VLC->creh->objects[toCmp]->AIValue)
  2438. {
  2439. bestCre = toCmp;
  2440. }
  2441. }
  2442. }
  2443. tgi.bestCreature[g->second.color] = bestCre;
  2444. }
  2445. }
  2446. #undef FILL_FIELD
  2447. }
  2448. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2449. {
  2450. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2451. for ( auto i = players.cbegin() ; i != players.cend();i++)
  2452. for(auto j = i->second.availableHeroes.cbegin(); j != i->second.availableHeroes.cend(); j++)
  2453. if(*j)
  2454. pool.erase((**j).subID);
  2455. return pool;
  2456. }
  2457. void CGameState::buildBonusSystemTree()
  2458. {
  2459. buildGlobalTeamPlayerTree();
  2460. attachArmedObjects();
  2461. for(CGTownInstance *t : map->towns)
  2462. {
  2463. t->deserializationFix();
  2464. }
  2465. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2466. // are provided on initializing / deserializing
  2467. }
  2468. void CGameState::deserializationFix()
  2469. {
  2470. buildGlobalTeamPlayerTree();
  2471. attachArmedObjects();
  2472. }
  2473. void CGameState::buildGlobalTeamPlayerTree()
  2474. {
  2475. for(auto k=teams.begin(); k!=teams.end(); ++k)
  2476. {
  2477. TeamState *t = &k->second;
  2478. t->attachTo(globalEffects);
  2479. for(PlayerColor teamMember : k->second.players)
  2480. {
  2481. PlayerState *p = getPlayerState(teamMember);
  2482. assert(p);
  2483. p->attachTo(*t);
  2484. }
  2485. }
  2486. }
  2487. void CGameState::attachArmedObjects()
  2488. {
  2489. for(CGObjectInstance *obj : map->objects)
  2490. {
  2491. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2492. {
  2493. armed->whatShouldBeAttached().attachTo(armed->whereShouldBeAttached(this));
  2494. }
  2495. }
  2496. }
  2497. void CGameState::giveHeroArtifact(CGHeroInstance *h, ArtifactID aid)
  2498. {
  2499. CArtifact * const artifact = VLC->arth->objects[aid]; //pointer to constant object
  2500. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2501. map->addNewArtifactInstance(ai);
  2502. ai->putAt(ArtifactLocation(h, ai->firstAvailableSlot(h)));
  2503. }
  2504. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed) const
  2505. {
  2506. std::set<HeroTypeID> ret;
  2507. for(int i = 0; i < map->allowedHeroes.size(); i++)
  2508. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  2509. ret.insert(HeroTypeID(i));
  2510. for(auto & playerSettingPair : scenarioOps->playerInfos) //remove uninitialized yet heroes picked for start by other players
  2511. {
  2512. if(playerSettingPair.second.hero != PlayerSettings::RANDOM)
  2513. ret -= HeroTypeID(playerSettingPair.second.hero);
  2514. }
  2515. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2516. {
  2517. if(hero->type)
  2518. ret -= hero->type->ID;
  2519. else
  2520. ret -= HeroTypeID(hero->subID);
  2521. }
  2522. for(auto obj : map->objects) //prisons
  2523. if(obj && obj->ID == Obj::PRISON)
  2524. ret -= HeroTypeID(obj->subID);
  2525. return ret;
  2526. }
  2527. std::vector<CGameState::CampaignHeroReplacement> CGameState::generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes)
  2528. {
  2529. std::vector<CampaignHeroReplacement> campaignHeroReplacements;
  2530. //selecting heroes by type
  2531. for(auto obj : map->objects)
  2532. {
  2533. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2534. {
  2535. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2536. if(heroPlaceholder->subID != 0xFF) //select by type
  2537. {
  2538. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [heroPlaceholder](CGHeroInstance * hero)
  2539. {
  2540. return hero->subID == heroPlaceholder->subID;
  2541. });
  2542. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  2543. {
  2544. auto hero = *it;
  2545. crossoverHeroes.removeHeroFromBothLists(hero);
  2546. campaignHeroReplacements.push_back(CampaignHeroReplacement(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id));
  2547. }
  2548. }
  2549. }
  2550. }
  2551. //selecting heroes by power
  2552. range::sort(crossoverHeroes.heroesFromPreviousScenario, [](const CGHeroInstance * a, const CGHeroInstance * b)
  2553. {
  2554. return a->getHeroStrength() > b->getHeroStrength();
  2555. }); //sort, descending strength
  2556. // sort hero placeholders descending power
  2557. std::vector<CGHeroPlaceholder *> heroPlaceholders;
  2558. for(auto obj : map->objects)
  2559. {
  2560. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2561. {
  2562. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2563. if(heroPlaceholder->subID == 0xFF) //select by power
  2564. {
  2565. heroPlaceholders.push_back(heroPlaceholder);
  2566. }
  2567. }
  2568. }
  2569. range::sort(heroPlaceholders, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  2570. {
  2571. return a->power > b->power;
  2572. });
  2573. for(int i = 0; i < heroPlaceholders.size(); ++i)
  2574. {
  2575. auto heroPlaceholder = heroPlaceholders[i];
  2576. if(crossoverHeroes.heroesFromPreviousScenario.size() > i)
  2577. {
  2578. auto hero = crossoverHeroes.heroesFromPreviousScenario[i];
  2579. campaignHeroReplacements.push_back(CampaignHeroReplacement(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id));
  2580. }
  2581. }
  2582. return campaignHeroReplacements;
  2583. }
  2584. void CGameState::replaceHeroesPlaceholders(const std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements)
  2585. {
  2586. for(auto campaignHeroReplacement : campaignHeroReplacements)
  2587. {
  2588. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder*>(getObjInstance(campaignHeroReplacement.heroPlaceholderId));
  2589. CGHeroInstance *heroToPlace = campaignHeroReplacement.hero;
  2590. heroToPlace->id = campaignHeroReplacement.heroPlaceholderId;
  2591. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  2592. heroToPlace->pos = heroPlaceholder->pos;
  2593. heroToPlace->type = VLC->heroh->objects[heroToPlace->subID];
  2594. heroToPlace->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO,
  2595. heroToPlace->type->heroClass->getIndex())->getTemplates().front();
  2596. for(auto &&i : heroToPlace->stacks)
  2597. i.second->type = VLC->creh->objects[i.second->getCreatureID()];
  2598. auto fixArtifact = [&](CArtifactInstance * art)
  2599. {
  2600. art->artType = VLC->arth->objects[art->artType->id];
  2601. gs->map->artInstances.push_back(art);
  2602. art->id = ArtifactInstanceID((si32)gs->map->artInstances.size() - 1);
  2603. };
  2604. for(auto &&i : heroToPlace->artifactsWorn)
  2605. fixArtifact(i.second.artifact);
  2606. for(auto &&i : heroToPlace->artifactsInBackpack)
  2607. fixArtifact(i.artifact);
  2608. map->heroesOnMap.push_back(heroToPlace);
  2609. map->objects[heroToPlace->id.getNum()] = heroToPlace;
  2610. map->addBlockVisTiles(heroToPlace);
  2611. scenarioOps->campState->getCurrentScenario().placedCrossoverHeroes.push_back(CCampaignState::crossoverSerialize(heroToPlace));
  2612. }
  2613. }
  2614. bool CGameState::isUsedHero(HeroTypeID hid) const
  2615. {
  2616. return getUsedHero(hid);
  2617. }
  2618. CGHeroInstance * CGameState::getUsedHero(HeroTypeID hid) const
  2619. {
  2620. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2621. {
  2622. if(hero->type && hero->type->ID == hid)
  2623. {
  2624. return hero;
  2625. }
  2626. }
  2627. for(auto obj : map->objects) //prisons
  2628. {
  2629. if(obj && obj->ID == Obj::PRISON )
  2630. {
  2631. auto hero = dynamic_cast<CGHeroInstance *>(obj.get());
  2632. assert(hero);
  2633. if ( hero->type && hero->type->ID == hid )
  2634. return hero;
  2635. }
  2636. }
  2637. return nullptr;
  2638. }
  2639. bool RumorState::update(int id, int extra)
  2640. {
  2641. if(vstd::contains(last, type))
  2642. {
  2643. if(last[type].first != id)
  2644. {
  2645. last[type].first = id;
  2646. last[type].second = extra;
  2647. }
  2648. else
  2649. return false;
  2650. }
  2651. else
  2652. last[type] = std::make_pair(id, extra);
  2653. return true;
  2654. }
  2655. InfoAboutArmy::InfoAboutArmy():
  2656. owner(PlayerColor::NEUTRAL)
  2657. {}
  2658. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2659. {
  2660. initFromArmy(Army, detailed);
  2661. }
  2662. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2663. {
  2664. army = ArmyDescriptor(Army, detailed);
  2665. owner = Army->tempOwner;
  2666. name = Army->getObjectName();
  2667. }
  2668. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2669. {
  2670. vstd::clear_pointer(details);
  2671. InfoAboutArmy::operator = (iah);
  2672. details = (iah.details ? new Details(*iah.details) : nullptr);
  2673. hclass = iah.hclass;
  2674. portrait = iah.portrait;
  2675. }
  2676. InfoAboutHero::InfoAboutHero():
  2677. details(nullptr),
  2678. hclass(nullptr),
  2679. portrait(-1)
  2680. {}
  2681. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah):
  2682. InfoAboutArmy()
  2683. {
  2684. assign(iah);
  2685. }
  2686. InfoAboutHero::InfoAboutHero(const CGHeroInstance *h, InfoAboutHero::EInfoLevel infoLevel)
  2687. : details(nullptr),
  2688. hclass(nullptr),
  2689. portrait(-1)
  2690. {
  2691. initFromHero(h, infoLevel);
  2692. }
  2693. InfoAboutHero::~InfoAboutHero()
  2694. {
  2695. vstd::clear_pointer(details);
  2696. }
  2697. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2698. {
  2699. assign(iah);
  2700. return *this;
  2701. }
  2702. void InfoAboutHero::initFromHero(const CGHeroInstance *h, InfoAboutHero::EInfoLevel infoLevel)
  2703. {
  2704. vstd::clear_pointer(details);
  2705. if(!h)
  2706. return;
  2707. bool detailed = ( (infoLevel == EInfoLevel::DETAILED) || (infoLevel == EInfoLevel::INBATTLE) );
  2708. initFromArmy(h, detailed);
  2709. hclass = h->type->heroClass;
  2710. name = h->name;
  2711. portrait = h->portrait;
  2712. if(detailed)
  2713. {
  2714. //include details about hero
  2715. details = new Details();
  2716. details->luck = h->LuckVal();
  2717. details->morale = h->MoraleVal();
  2718. details->mana = h->mana;
  2719. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2720. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2721. {
  2722. details->primskills[i] = h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i));
  2723. }
  2724. if (infoLevel == EInfoLevel::INBATTLE)
  2725. details->manaLimit = h->manaLimit();
  2726. else
  2727. details->manaLimit = -1; //we do not want to leak max mana info outside battle so set to meaningless value
  2728. }
  2729. }
  2730. InfoAboutTown::InfoAboutTown():
  2731. details(nullptr),
  2732. tType(nullptr),
  2733. built(0),
  2734. fortLevel(0)
  2735. {
  2736. }
  2737. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed):
  2738. details(nullptr),
  2739. tType(nullptr),
  2740. built(0),
  2741. fortLevel(0)
  2742. {
  2743. initFromTown(t, detailed);
  2744. }
  2745. InfoAboutTown::~InfoAboutTown()
  2746. {
  2747. vstd::clear_pointer(details);
  2748. }
  2749. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2750. {
  2751. initFromArmy(t, detailed);
  2752. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2753. built = t->builded;
  2754. fortLevel = t->fortLevel();
  2755. name = t->name;
  2756. tType = t->town;
  2757. vstd::clear_pointer(details);
  2758. if(detailed)
  2759. {
  2760. //include details about hero
  2761. details = new Details();
  2762. TResources income = t->dailyIncome();
  2763. details->goldIncome = income[Res::GOLD];
  2764. details->customRes = t->hasBuilt(BuildingID::RESOURCE_SILO);
  2765. details->hallLevel = t->hallLevel();
  2766. details->garrisonedHero = t->garrisonHero;
  2767. }
  2768. }
  2769. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2770. : isDetailed(detailed)
  2771. {
  2772. for(auto & elem : army->Slots())
  2773. {
  2774. if(detailed)
  2775. (*this)[elem.first] = *elem.second;
  2776. else
  2777. (*this)[elem.first] = CStackBasicDescriptor(elem.second->type, elem.second->getQuantityID());
  2778. }
  2779. }
  2780. ArmyDescriptor::ArmyDescriptor()
  2781. : isDetailed(false)
  2782. {
  2783. }
  2784. int ArmyDescriptor::getStrength() const
  2785. {
  2786. ui64 ret = 0;
  2787. if(isDetailed)
  2788. {
  2789. for(auto & elem : *this)
  2790. ret += elem.second.type->AIValue * elem.second.count;
  2791. }
  2792. else
  2793. {
  2794. for(auto & elem : *this)
  2795. ret += elem.second.type->AIValue * CCreature::estimateCreatureCount(elem.second.count);
  2796. }
  2797. return static_cast<int>(ret);
  2798. }
  2799. TeamState::TeamState()
  2800. {
  2801. setNodeType(TEAM);
  2802. fogOfWarMap = std::make_shared<boost::multi_array<ui8, 3>>();
  2803. }
  2804. TeamState::TeamState(TeamState && other):
  2805. CBonusSystemNode(std::move(other)),
  2806. id(other.id)
  2807. {
  2808. std::swap(players, other.players);
  2809. std::swap(fogOfWarMap, other.fogOfWarMap);
  2810. }
  2811. CRandomGenerator & CGameState::getRandomGenerator()
  2812. {
  2813. return rand;
  2814. }
  2815. VCMI_LIB_NAMESPACE_END