CGameState.cpp 84 KB

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