CGameState.cpp 84 KB

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