CGameState.cpp 84 KB

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