CGameState.cpp 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995
  1. #include "StdInc.h"
  2. #include "CGameState.h"
  3. #include <boost/random/linear_congruential.hpp>
  4. #include "CCampaignHandler.h"
  5. #include "CDefObjInfoHandler.h"
  6. #include "CArtHandler.h"
  7. #include "CBuildingHandler.h"
  8. #include "CGeneralTextHandler.h"
  9. #include "CTownHandler.h"
  10. #include "CSpellHandler.h"
  11. #include "CHeroHandler.h"
  12. #include "CObjectHandler.h"
  13. #include "CCreatureHandler.h"
  14. #include "VCMI_Lib.h"
  15. #include "Connection.h"
  16. #include "map.h"
  17. #include "StartInfo.h"
  18. #include "NetPacks.h"
  19. #include "RegisterTypes.h"
  20. #include "CMapInfo.h"
  21. #include "BattleState.h"
  22. #include "../lib/JsonNode.h"
  23. #include "GameConstants.h"
  24. DLL_LINKAGE boost::rand48 ran;
  25. class CGObjectInstance;
  26. #ifdef min
  27. #undef min
  28. #endif
  29. #ifdef max
  30. #undef max
  31. #endif
  32. /*
  33. * CGameState.cpp, part of VCMI engine
  34. *
  35. * Authors: listed in file AUTHORS in main folder
  36. *
  37. * License: GNU General Public License v2.0 or later
  38. * Full text of license available in license.txt file, in main folder
  39. *
  40. */
  41. void foofoofoo()
  42. {
  43. //never called function to force instantation of templates
  44. int *ccc = NULL;
  45. registerTypes((CISer<CConnection>&)*ccc);
  46. registerTypes((COSer<CConnection>&)*ccc);
  47. registerTypes((CSaveFile&)*ccc);
  48. registerTypes((CLoadFile&)*ccc);
  49. registerTypes((CTypeList&)*ccc);
  50. }
  51. template <typename T> class CApplyOnGS;
  52. class CBaseForGSApply
  53. {
  54. public:
  55. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  56. virtual ~CBaseForGSApply(){};
  57. template<typename U> static CBaseForGSApply *getApplier(const U * t=NULL)
  58. {
  59. return new CApplyOnGS<U>;
  60. }
  61. };
  62. template <typename T> class CApplyOnGS : public CBaseForGSApply
  63. {
  64. public:
  65. void applyOnGS(CGameState *gs, void *pack) const
  66. {
  67. T *ptr = static_cast<T*>(pack);
  68. boost::unique_lock<boost::shared_mutex> lock(*gs->mx);
  69. ptr->applyGs(gs);
  70. }
  71. };
  72. static CApplier<CBaseForGSApply> *applierGs = NULL;
  73. class IObjectCaller
  74. {
  75. public:
  76. virtual ~IObjectCaller(){};
  77. virtual void preInit()=0;
  78. virtual void postInit()=0;
  79. };
  80. template <typename T>
  81. class CObjectCaller : public IObjectCaller
  82. {
  83. public:
  84. void preInit()
  85. {
  86. //T::preInit();
  87. }
  88. void postInit()
  89. {
  90. //T::postInit();
  91. }
  92. };
  93. class CObjectCallersHandler
  94. {
  95. public:
  96. std::vector<IObjectCaller*> apps;
  97. template<typename T> void registerType(const T * t=NULL)
  98. {
  99. apps.push_back(new CObjectCaller<T>);
  100. }
  101. CObjectCallersHandler()
  102. {
  103. registerTypes1(*this);
  104. }
  105. ~CObjectCallersHandler()
  106. {
  107. for (size_t i = 0; i < apps.size(); i++)
  108. delete apps[i];
  109. }
  110. void preInit()
  111. {
  112. // for (size_t i = 0; i < apps.size(); i++)
  113. // apps[i]->preInit();
  114. }
  115. void postInit()
  116. {
  117. //for (size_t i = 0; i < apps.size(); i++)
  118. //apps[i]->postInit();
  119. }
  120. } *objCaller = NULL;
  121. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  122. {
  123. int type = txt.first, ser = txt.second;
  124. if(type == ART_NAMES)
  125. {
  126. dst = VLC->arth->artifacts[ser]->Name();
  127. }
  128. else if(type == CRE_PL_NAMES)
  129. {
  130. dst = VLC->creh->creatures[ser]->namePl;
  131. }
  132. else if(type == MINE_NAMES)
  133. {
  134. dst = VLC->generaltexth->mines[ser].first;
  135. }
  136. else if(type == MINE_EVNTS)
  137. {
  138. dst = VLC->generaltexth->mines[ser].second;
  139. }
  140. else if(type == SPELL_NAME)
  141. {
  142. dst = VLC->spellh->spells[ser]->name;
  143. }
  144. else if(type == CRE_SING_NAMES)
  145. {
  146. dst = VLC->creh->creatures[ser]->nameSing;
  147. }
  148. else if(type == ART_DESCR)
  149. {
  150. dst = VLC->arth->artifacts[ser]->Description();
  151. }
  152. else
  153. {
  154. std::vector<std::string> *vec;
  155. switch(type)
  156. {
  157. case GENERAL_TXT:
  158. vec = &VLC->generaltexth->allTexts;
  159. break;
  160. case XTRAINFO_TXT:
  161. vec = &VLC->generaltexth->xtrainfo;
  162. break;
  163. case OBJ_NAMES:
  164. vec = &VLC->generaltexth->names;
  165. break;
  166. case RES_NAMES:
  167. vec = &VLC->generaltexth->restypes;
  168. break;
  169. case ARRAY_TXT:
  170. vec = &VLC->generaltexth->arraytxt;
  171. break;
  172. case CREGENS:
  173. vec = &VLC->generaltexth->creGens;
  174. break;
  175. case CREGENS4:
  176. vec = &VLC->generaltexth->creGens4;
  177. break;
  178. case ADVOB_TXT:
  179. vec = &VLC->generaltexth->advobtxt;
  180. break;
  181. case ART_EVNTS:
  182. vec = &VLC->generaltexth->artifEvents;
  183. break;
  184. case SEC_SKILL_NAME:
  185. vec = &VLC->generaltexth->skillName;
  186. break;
  187. case COLOR:
  188. vec = &VLC->generaltexth->capColors;
  189. break;
  190. default:
  191. tlog1 << "Failed string substitution because type is " << type << std::endl;
  192. dst = "#@#";
  193. return;
  194. }
  195. if(vec->size() <= ser)
  196. {
  197. tlog1 << "Failed string substitution with type " << type << " because index " << ser << " is out of bounds!\n";
  198. dst = "#!#";
  199. }
  200. else
  201. dst = (*vec)[ser];
  202. }
  203. }
  204. DLL_LINKAGE void MetaString::toString(std::string &dst) const
  205. {
  206. size_t exSt = 0, loSt = 0, nums = 0;
  207. dst.clear();
  208. for(size_t i=0;i<message.size();++i)
  209. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  210. switch(message[i])
  211. {
  212. case TEXACT_STRING:
  213. dst += exactStrings[exSt++];
  214. break;
  215. case TLOCAL_STRING:
  216. {
  217. std::string hlp;
  218. getLocalString(localStrings[loSt++], hlp);
  219. dst += hlp;
  220. }
  221. break;
  222. case TNUMBER:
  223. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  224. break;
  225. case TREPLACE_ESTRING:
  226. boost::replace_first(dst, "%s", exactStrings[exSt++]);
  227. break;
  228. case TREPLACE_LSTRING:
  229. {
  230. std::string hlp;
  231. getLocalString(localStrings[loSt++], hlp);
  232. boost::replace_first(dst, "%s", hlp);
  233. }
  234. break;
  235. case TREPLACE_NUMBER:
  236. boost::replace_first(dst, "%d", boost::lexical_cast<std::string>(numbers[nums++]));
  237. break;
  238. case TREPLACE_PLUSNUMBER:
  239. boost::replace_first(dst, "%+d", '+' + boost::lexical_cast<std::string>(numbers[nums++]));
  240. break;
  241. default:
  242. tlog1 << "MetaString processing error!\n";
  243. break;
  244. }
  245. }
  246. }
  247. DLL_LINKAGE std::string MetaString::toString() const
  248. {
  249. std::string ret;
  250. toString(ret);
  251. return ret;
  252. }
  253. DLL_LINKAGE std::string MetaString::buildList () const
  254. ///used to handle loot from creature bank
  255. {
  256. size_t exSt = 0, loSt = 0, nums = 0;
  257. std::string lista;
  258. for (int i = 0; i < message.size(); ++i)
  259. {
  260. if (i > 0 && (message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING))
  261. {
  262. if (exSt == exactStrings.size() - 1)
  263. lista += VLC->generaltexth->allTexts[141]; //" and "
  264. else
  265. lista += ", ";
  266. }
  267. switch (message[i])
  268. {
  269. case TEXACT_STRING:
  270. lista += exactStrings[exSt++];
  271. break;
  272. case TLOCAL_STRING:
  273. {
  274. std::string hlp;
  275. getLocalString (localStrings[loSt++], hlp);
  276. lista += hlp;
  277. }
  278. break;
  279. case TNUMBER:
  280. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  281. break;
  282. case TREPLACE_ESTRING:
  283. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  284. break;
  285. case TREPLACE_LSTRING:
  286. {
  287. std::string hlp;
  288. getLocalString (localStrings[loSt++], hlp);
  289. lista.replace (lista.find("%s"), 2, hlp);
  290. }
  291. break;
  292. case TREPLACE_NUMBER:
  293. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  294. break;
  295. default:
  296. tlog1 << "MetaString processing error!\n";
  297. }
  298. }
  299. return lista;
  300. }
  301. void MetaString::addCreReplacement(TCreature id, TQuantity count) //adds sing or plural name;
  302. {
  303. assert(count);
  304. if (count == 1)
  305. addReplacement (CRE_SING_NAMES, id);
  306. else
  307. addReplacement (CRE_PL_NAMES, id);
  308. }
  309. void MetaString::addReplacement(const CStackBasicDescriptor &stack)
  310. {
  311. assert(stack.count); //valid count
  312. assert(stack.type); //valid type
  313. addCreReplacement(stack.type->idNumber, stack.count);
  314. }
  315. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  316. {
  317. CGObjectInstance * nobj;
  318. switch(id)
  319. {
  320. case GameConstants::HEROI_TYPE: //hero
  321. {
  322. CGHeroInstance * nobj = new CGHeroInstance();
  323. nobj->pos = pos;
  324. nobj->tempOwner = owner;
  325. nobj->subID = subid;
  326. //nobj->initHero(ran);
  327. return nobj;
  328. }
  329. case GameConstants::TOWNI_TYPE: //town
  330. nobj = new CGTownInstance;
  331. break;
  332. default: //rest of objects
  333. nobj = new CGObjectInstance;
  334. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  335. break;
  336. }
  337. nobj->ID = id;
  338. nobj->subID = subid;
  339. if(!nobj->defInfo)
  340. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  341. nobj->pos = pos;
  342. //nobj->state = NULL;//new CLuaObjectScript();
  343. nobj->tempOwner = owner;
  344. nobj->defInfo->id = id;
  345. nobj->defInfo->subid = subid;
  346. //assigning defhandler
  347. if(nobj->ID==GameConstants::HEROI_TYPE || nobj->ID==GameConstants::TOWNI_TYPE)
  348. return nobj;
  349. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  350. return nobj;
  351. }
  352. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, bmap<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass /*= NULL*/) const
  353. {
  354. CGHeroInstance *ret = NULL;
  355. if(player<0 || player>=GameConstants::PLAYER_LIMIT)
  356. {
  357. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  358. return NULL;
  359. }
  360. std::vector<CGHeroInstance *> pool;
  361. if(native)
  362. {
  363. for(bmap<ui32, ConstTransitivePtr<CGHeroInstance> >::iterator i=available.begin(); i!=available.end(); i++)
  364. {
  365. if(pavailable.find(i->first)->second & 1<<player
  366. && i->second->type->heroType/2 == town->typeID)
  367. {
  368. pool.push_back(i->second); //get all available heroes
  369. }
  370. }
  371. if(!pool.size())
  372. {
  373. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  374. return pickHeroFor(false, player, town, available);
  375. }
  376. else
  377. {
  378. ret = pool[rand()%pool.size()];
  379. }
  380. }
  381. else
  382. {
  383. int sum=0, r;
  384. for(bmap<ui32, ConstTransitivePtr<CGHeroInstance> >::iterator i=available.begin(); i!=available.end(); i++)
  385. {
  386. if ((!bannedClass && (pavailable.find(i->first)->second & (1<<player))) ||
  387. i->second->type->heroClass != bannedClass)
  388. {
  389. pool.push_back(i->second);
  390. sum += i->second->type->heroClass->selectionProbability[town->typeID]; //total weight
  391. }
  392. }
  393. if(!pool.size())
  394. {
  395. tlog1 << "There are no heroes available for player " << player<<"!\n";
  396. return NULL;
  397. }
  398. r = rand()%sum;
  399. for (ui32 i=0; i<pool.size(); i++)
  400. {
  401. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  402. if(r < 0)
  403. {
  404. ret = pool[i];
  405. break;
  406. }
  407. }
  408. if(!ret)
  409. ret = pool.back();
  410. }
  411. available.erase(ret->subID);
  412. return ret;
  413. }
  414. //void CGameState::apply(CPack * pack)
  415. //{
  416. // while(!mx->try_lock())
  417. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  418. // //applyNL(pack);
  419. // mx->unlock();
  420. //}
  421. int CGameState::pickHero(int owner)
  422. {
  423. int h=-1;
  424. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  425. if(!map->getHero(h = ps.hero,0) && h>=0) //we haven't used selected hero
  426. return h;
  427. int i=0;
  428. do //try to find free hero of our faction
  429. {
  430. i++;
  431. h = ps.castle*GameConstants::HEROES_PER_TYPE*2+(ran()%(GameConstants::HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  432. } while( map->getHero(h) && i<175);
  433. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  434. {
  435. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  436. for(int j=0; j<GameConstants::HEROES_PER_TYPE * 2 * GameConstants::F_NUMBER; j++)
  437. if(!map->getHero(j))
  438. h=j;
  439. }
  440. return h;
  441. }
  442. std::pair<int,int> CGameState::pickObject (CGObjectInstance *obj)
  443. {
  444. switch(obj->ID)
  445. {
  446. case 65:
  447. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  448. case 66: //random treasure artifact
  449. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE));
  450. case 67: //random minor artifact
  451. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MINOR));
  452. case 68: //random major artifact
  453. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MAJOR));
  454. case 69: //random relic artifact
  455. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_RELIC));
  456. case 70: //random hero
  457. return std::pair<int,int>(GameConstants::HEROI_TYPE,pickHero(obj->tempOwner));
  458. case 71: //random monster
  459. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran)));
  460. case 72: //random monster lvl1
  461. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran), 1));
  462. case 73: //random monster lvl2
  463. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran), 2));
  464. case 74: //random monster lvl3
  465. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran), 3));
  466. case 75: //random monster lvl4
  467. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 4));
  468. case 76: //random resource
  469. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  470. case 77: //random town
  471. {
  472. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  473. f;
  474. if(align>GameConstants::PLAYER_LIMIT-1)//same as owner / random
  475. {
  476. if(obj->tempOwner > GameConstants::PLAYER_LIMIT-1)
  477. f = -1; //random
  478. else
  479. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  480. }
  481. else
  482. {
  483. f = scenarioOps->getIthPlayersSettings(align).castle;
  484. }
  485. if(f<0) f = ran()%VLC->townh->towns.size();
  486. return std::pair<int,int>(GameConstants::TOWNI_TYPE,f);
  487. }
  488. case 162: //random monster lvl5
  489. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 5));
  490. case 163: //random monster lvl6
  491. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 6));
  492. case 164: //random monster lvl7
  493. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 7));
  494. case 216: //random dwellings
  495. case 217:
  496. case 218:
  497. {
  498. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  499. int faction;
  500. //if castle alignment available
  501. if (auto info = dynamic_cast<CCreGenAsCastleInfo*>(dwl->info))
  502. {
  503. faction = ran()%GameConstants::F_NUMBER;
  504. if (info->asCastle)
  505. {
  506. for(ui32 i=0;i<map->objects.size();i++)
  507. {
  508. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  509. {
  510. randomizeObject(map->objects[i]); //we have to randomize the castle first
  511. faction = map->objects[i]->subID;
  512. break;
  513. }
  514. else if(map->objects[i]->ID==GameConstants::TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  515. {
  516. faction = map->objects[i]->subID;
  517. break;
  518. }
  519. }
  520. }
  521. else
  522. {
  523. while((!(info->castles[0]&(1<<faction))))
  524. {
  525. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  526. break;
  527. faction = ran()%GameConstants::F_NUMBER;
  528. }
  529. }
  530. }
  531. else // castle alignment fixed
  532. faction = obj->subID;
  533. int level;
  534. //if level set to range
  535. if (auto info = dynamic_cast<CCreGenLeveledInfo*>(dwl->info))
  536. level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  537. else // fixed level
  538. level = obj->subID;
  539. delete dwl->info;
  540. dwl->info = nullptr;
  541. std::pair<int,int> result(-1, -1);
  542. int cid = VLC->townh->towns[faction].basicCreatures[level];
  543. //golem factory is not in list of cregens but can be placed as random object
  544. static const int factoryCreatures[] = {32, 33, 116, 117};
  545. std::vector<int> factory(factoryCreatures, factoryCreatures + ARRAY_COUNT(factoryCreatures));
  546. if (vstd::contains(factory, cid))
  547. result = std::pair<int,int>(20, 1);
  548. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  549. //check for block map equality is better but more complex solution
  550. BOOST_FOREACH(auto &iter, VLC->objh->cregens)
  551. if (iter.second == cid)
  552. result = std::pair<int,int>(17, iter.first);
  553. if (result.first == -1)
  554. tlog0 << "Error: failed to find creature for dwelling of "<< int(faction) << " of level " << int(level) << "\n";
  555. return result;
  556. }
  557. }
  558. return std::pair<int,int>(-1,-1);
  559. }
  560. void CGameState::randomizeObject(CGObjectInstance *cur)
  561. {
  562. std::pair<int,int> ran = pickObject(cur);
  563. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  564. {
  565. if(cur->ID==GameConstants::TOWNI_TYPE) //town - set def
  566. {
  567. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  568. t->town = &VLC->townh->towns[t->subID];
  569. if(t->hasCapitol())
  570. t->defInfo = capitols[t->subID];
  571. else if(t->hasFort())
  572. t->defInfo = forts[t->subID];
  573. else
  574. t->defInfo = villages[t->subID];
  575. }
  576. return;
  577. }
  578. else if(ran.first==GameConstants::HEROI_TYPE)//special code for hero
  579. {
  580. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  581. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  582. cur->ID = ran.first;
  583. h->portrait = cur->subID = ran.second;
  584. h->type = VLC->heroh->heroes[ran.second];
  585. h->randomizeArmy(h->type->heroType/2);
  586. map->heroes.push_back(h);
  587. return; //TODO: maybe we should do something with definfo?
  588. }
  589. else if(ran.first==GameConstants::TOWNI_TYPE)//special code for town
  590. {
  591. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  592. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  593. cur->ID = ran.first;
  594. cur->subID = ran.second;
  595. t->town = &VLC->townh->towns[ran.second];
  596. if(t->hasCapitol())
  597. t->defInfo = capitols[t->subID];
  598. else if(t->hasFort())
  599. t->defInfo = forts[t->subID];
  600. else
  601. t->defInfo = villages[t->subID];
  602. t->randomizeArmy(t->subID);
  603. map->towns.push_back(t);
  604. return;
  605. }
  606. //we have to replace normal random object
  607. cur->ID = ran.first;
  608. cur->subID = ran.second;
  609. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  610. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  611. if(!cur->defInfo)
  612. {
  613. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  614. return;
  615. }
  616. map->addBlockVisTiles(cur);
  617. }
  618. int CGameState::getDate(int mode) const
  619. {
  620. int temp;
  621. switch (mode)
  622. {
  623. case 0: //day number
  624. return day;
  625. break;
  626. case 1: //day of week
  627. temp = (day)%7; // 1 - Monday, 7 - Sunday
  628. if (temp)
  629. return temp;
  630. else return 7;
  631. break;
  632. case 2: //current week
  633. temp = ((day-1)/7)+1;
  634. if (!(temp%4))
  635. return 4;
  636. else
  637. return (temp%4);
  638. break;
  639. case 3: //current month
  640. return ((day-1)/28)+1;
  641. break;
  642. case 4: //day of month
  643. temp = (day)%28;
  644. if (temp)
  645. return temp;
  646. else return 28;
  647. break;
  648. }
  649. return 0;
  650. }
  651. CGameState::CGameState()
  652. {
  653. gs = this;
  654. mx = new boost::shared_mutex();
  655. applierGs = new CApplier<CBaseForGSApply>;
  656. registerTypes2(*applierGs);
  657. objCaller = new CObjectCallersHandler;
  658. globalEffects.setDescription("Global effects");
  659. }
  660. CGameState::~CGameState()
  661. {
  662. //delete mx;//TODO: crash on Linux (mutex must be unlocked before destruction)
  663. map.dellNull();
  664. curB.dellNull();
  665. //delete scenarioOps; //TODO: fix for loading ind delete
  666. //delete initialOpts;
  667. delete applierGs;
  668. delete objCaller;
  669. //TODO: delete properly that definfos
  670. villages.clear();
  671. capitols.clear();
  672. }
  673. BattleInfo * CGameState::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town)
  674. {
  675. const TerrainTile &t = map->getTile(tile);
  676. int terrain = t.tertype;
  677. if(t.isCoastal() && !t.isWater())
  678. terrain = TerrainTile::sand;
  679. int terType = battleGetBattlefieldType(tile);
  680. return BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  681. }
  682. void CGameState::init(StartInfo * si)
  683. {
  684. struct HLP
  685. {
  686. //it's assumed that given hero should receive the bonus
  687. static void giveCampaignBonusToHero(CGHeroInstance * hero, const StartInfo * si, const CScenarioTravel & st, CGameState *gs )
  688. {
  689. const CScenarioTravel::STravelBonus & curBonus = st.bonusesToChoose[si->choosenCampaignBonus];
  690. if(curBonus.isBonusForHero())
  691. {
  692. //apply bonus
  693. switch (curBonus.type)
  694. {
  695. case 0: //spell
  696. hero->spells.insert(curBonus.info2);
  697. break;
  698. case 1: //monster
  699. {
  700. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  701. {
  702. if(hero->slotEmpty(i))
  703. {
  704. hero->addToSlot(i, curBonus.info2, curBonus.info3);
  705. break;
  706. }
  707. }
  708. }
  709. break;
  710. case 3: //artifact
  711. gs->giveHeroArtifact(hero, curBonus.info2);
  712. break;
  713. case 4: //spell scroll
  714. {
  715. CArtifactInstance * scroll = CArtifactInstance::createScroll(VLC->spellh->spells[curBonus.info2]);
  716. scroll->putAt(ArtifactLocation(hero, scroll->firstAvailableSlot(hero)));
  717. }
  718. break;
  719. case 5: //prim skill
  720. {
  721. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus.info2);
  722. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  723. {
  724. int val = ptr[g];
  725. if (val == 0)
  726. {
  727. continue;
  728. }
  729. Bonus *bb = new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, si->whichMapInCampaign, g);
  730. hero->addNewBonus(bb);
  731. }
  732. }
  733. break;
  734. case 6: //sec skills
  735. hero->setSecSkillLevel(static_cast<CGHeroInstance::SecondarySkill>(curBonus.info2), curBonus.info3, true);
  736. break;
  737. }
  738. }
  739. }
  740. static std::vector<const PlayerSettings *> getHumanPlayerInfo(const StartInfo * si)
  741. {
  742. std::vector<const PlayerSettings *> ret;
  743. for(std::map<int, PlayerSettings>::const_iterator it = si->playerInfos.begin();
  744. it != si->playerInfos.end(); ++it)
  745. {
  746. if(it->second.human)
  747. ret.push_back(&it->second);
  748. }
  749. return ret;
  750. }
  751. static void replaceHero( CGameState * gs, int objId, CGHeroInstance * ghi )
  752. {
  753. ghi->id = objId;
  754. gs->map->objects[objId] = ghi;
  755. gs->map->heroes.push_back(ghi);
  756. }
  757. //sort in descending order by power
  758. static bool heroPowerSorter(const CGHeroInstance * a, const CGHeroInstance * b)
  759. {
  760. return a->getHeroStrength() > b->getHeroStrength();
  761. }
  762. };
  763. tlog0 << "\tUsing random seed: "<< si->seedToBeUsed << std::endl;
  764. ran.seed((boost::int32_t)si->seedToBeUsed);
  765. scenarioOps = new StartInfo(*si);
  766. initialOpts = new StartInfo(*si);
  767. si = NULL;
  768. switch(scenarioOps->mode)
  769. {
  770. case StartInfo::NEW_GAME:
  771. map = new Mapa(scenarioOps->mapname);
  772. break;
  773. case StartInfo::CAMPAIGN:
  774. {
  775. campaign = new CCampaignState();
  776. campaign->initNewCampaign(*scenarioOps);
  777. assert(vstd::contains(campaign->camp->mapPieces, scenarioOps->whichMapInCampaign));
  778. std::string &mapContent = campaign->camp->mapPieces[scenarioOps->whichMapInCampaign];
  779. map = new Mapa();
  780. map->initFromBytes((const ui8*)mapContent.c_str(), mapContent.size());
  781. }
  782. break;
  783. case StartInfo::DUEL:
  784. {
  785. DuelParameters dp;
  786. try
  787. {
  788. CLoadFile lf(scenarioOps->mapname);
  789. lf >> dp;
  790. }
  791. catch(...)
  792. {}
  793. const CArmedInstance *armies[2] = {0};
  794. const CGHeroInstance *heroes[2] = {0};
  795. CGTownInstance *town = NULL;
  796. for(int i = 0; i < 2; i++)
  797. {
  798. CArmedInstance *obj = NULL;
  799. if(dp.sides[i].heroId >= 0)
  800. {
  801. CGHeroInstance *h = new CGHeroInstance();
  802. armies[i] = heroes[i] = h;
  803. obj = h;
  804. h->subID = dp.sides[i].heroId;
  805. h->initHero(h->subID);
  806. }
  807. else
  808. {
  809. CGCreature *c = new CGCreature();
  810. armies[i] = obj = c;
  811. c->subID = 34;
  812. }
  813. obj->initObj();
  814. obj->setOwner(i);
  815. for(int j = 0; j < ARRAY_COUNT(dp.sides[i].stacks); j++)
  816. {
  817. int cre = dp.sides[i].stacks[j].type, count = dp.sides[i].stacks[j].count;
  818. if(count || obj->hasStackAtSlot(j))
  819. obj->setCreature(j, cre, count);
  820. }
  821. }
  822. curB = BattleInfo::setupBattle(int3(), dp.bfieldType, dp.terType, armies, heroes, false, town);
  823. curB->localInit();
  824. return;
  825. }
  826. break;
  827. default:
  828. tlog1 << "Wrong mode: " << (int)scenarioOps->mode << std::endl;
  829. return;
  830. }
  831. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  832. tlog0 << "Map loaded!" << std::endl;
  833. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  834. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  835. if(scenarioOps->mapfileChecksum)
  836. {
  837. tlog0 << "\tServer checksum for " << scenarioOps->mapname <<": "<< scenarioOps->mapfileChecksum << std::endl;
  838. if(map->checksum != scenarioOps->mapfileChecksum)
  839. {
  840. tlog1 << "Wrong map checksum!!!" << std::endl;
  841. throw std::runtime_error("Wrong checksum");
  842. }
  843. }
  844. else
  845. scenarioOps->mapfileChecksum = map->checksum;
  846. day = 0;
  847. loadTownDInfos();
  848. //pick grail location
  849. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  850. {
  851. if(!map->grailRadious) //radius not given -> anywhere on map
  852. map->grailRadious = map->width * 2;
  853. std::vector<int3> allowedPos;
  854. // add all not blocked tiles in range
  855. for (int i = 0; i < map->width ; i++)
  856. {
  857. for (int j = 0; j < map->height ; j++)
  858. {
  859. for (int k = 0; k <= map->twoLevel ; k++)
  860. {
  861. const TerrainTile &t = map->terrain[i][j][k];
  862. if(!t.blocked
  863. && !t.visitable
  864. && t.tertype != TerrainTile::water
  865. && t.tertype != TerrainTile::rock
  866. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  867. allowedPos.push_back(int3(i,j,k));
  868. }
  869. }
  870. }
  871. //remove tiles with holes
  872. for(ui32 no=0; no<map->objects.size(); ++no)
  873. if(map->objects[no]->ID == 124)
  874. allowedPos -= map->objects[no]->pos;
  875. if(allowedPos.size())
  876. map->grailPos = allowedPos[ran() % allowedPos.size()];
  877. else
  878. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  879. }
  880. //picking random factions for players
  881. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  882. it != scenarioOps->playerInfos.end(); ++it)
  883. {
  884. if(it->second.castle==-1)
  885. {
  886. int f;
  887. do
  888. {
  889. f = ran()%GameConstants::F_NUMBER;
  890. }while(!(map->players[it->first].allowedFactions & 1<<f));
  891. it->second.castle = f;
  892. }
  893. }
  894. //randomizing objects
  895. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  896. {
  897. randomizeObject(obj);
  898. obj->hoverName = VLC->generaltexth->names[obj->ID];
  899. //handle Favouring Winds - mark tiles under it
  900. if(obj->ID == 225)
  901. for (int i = 0; i < obj->getWidth() ; i++)
  902. for (int j = 0; j < obj->getHeight() ; j++)
  903. {
  904. int3 pos = obj->pos - int3(i,j,0);
  905. if(map->isInTheMap(pos))
  906. map->getTile(pos).siodmyTajemniczyBajt |= 128;
  907. }
  908. }
  909. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  910. /*********creating players entries in gs****************************************/
  911. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  912. it != scenarioOps->playerInfos.end(); ++it)
  913. {
  914. std::pair<int,PlayerState> ins(it->first,PlayerState());
  915. ins.second.color=ins.first;
  916. ins.second.human = it->second.human;
  917. ins.second.team = map->players[ins.first].team;
  918. teams[ins.second.team].id = ins.second.team;//init team
  919. teams[ins.second.team].players.insert(ins.first);//add player to team
  920. players.insert(ins);
  921. }
  922. /*********give starting hero****************************************/
  923. for(int i=0;i<GameConstants::PLAYER_LIMIT;i++)
  924. {
  925. const PlayerInfo &p = map->players[i];
  926. bool generateHero = (p.generateHeroAtMainTown && p.hasMainTown);
  927. if(generateHero && vstd::contains(scenarioOps->playerInfos, i))
  928. {
  929. int3 hpos = p.posOfMainTown;
  930. hpos.x+=1;
  931. int h = pickHero(i);
  932. if(scenarioOps->playerInfos[i].hero == -1)
  933. scenarioOps->playerInfos[i].hero = h;
  934. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(GameConstants::HEROI_TYPE,h,hpos,i));
  935. nnn->id = map->objects.size();
  936. nnn->initHero();
  937. map->heroes.push_back(nnn);
  938. map->objects.push_back(nnn);
  939. map->addBlockVisTiles(nnn);
  940. }
  941. }
  942. /*************************replace hero placeholders*****************************/
  943. if (campaign)
  944. {
  945. CScenarioTravel::STravelBonus bonus =
  946. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  947. std::vector<CGHeroInstance *> Xheroes;
  948. if (bonus.type == 8) //hero crossover
  949. {
  950. Xheroes = campaign->camp->scenarios[bonus.info2].crossoverHeroes;
  951. }
  952. //selecting heroes by type
  953. for(int g=0; g<map->objects.size(); ++g)
  954. {
  955. CGObjectInstance * obj = map->objects[g];
  956. if (obj->ID != 214) //not a placeholder
  957. {
  958. continue;
  959. }
  960. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  961. if(hp->subID != 0xFF) //select by type
  962. {
  963. bool found = false;
  964. BOOST_FOREACH(CGHeroInstance * ghi, Xheroes)
  965. {
  966. if (ghi->subID == hp->subID)
  967. {
  968. found = true;
  969. HLP::replaceHero(this, g, ghi);
  970. Xheroes -= ghi;
  971. break;
  972. }
  973. }
  974. if (!found)
  975. {
  976. //TODO: create new hero of this type
  977. }
  978. }
  979. }
  980. //selecting heroes by power
  981. std::sort(Xheroes.begin(), Xheroes.end(), HLP::heroPowerSorter);
  982. for(int g=0; g<map->objects.size(); ++g)
  983. {
  984. CGObjectInstance * obj = map->objects[g];
  985. if (obj->ID != 214) //not a placeholder
  986. {
  987. continue;
  988. }
  989. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  990. if (hp->subID == 0xFF) //select by power
  991. {
  992. if(Xheroes.size() > hp->power - 1)
  993. HLP::replaceHero(this, g, Xheroes[hp->power - 1]);
  994. else
  995. tlog2 << "Warning, to hero to replace!\n";
  996. //we don't have to remove hero from Xheroes because it would destroy the order and duplicates shouldn't happen
  997. }
  998. }
  999. }
  1000. /******************RESOURCES****************************************************/
  1001. TResources startresAI, startresHuman;
  1002. const JsonNode config(GameConstants::DATA_DIR + "/config/startres.json");
  1003. const JsonVector &vector = config["difficulty"].Vector();
  1004. const JsonNode &level = vector[scenarioOps->difficulty];
  1005. const JsonNode &human = level["human"];
  1006. const JsonNode &ai = level["ai"];
  1007. startresHuman[0] = human["wood"].Float();
  1008. startresHuman[1] = human["mercury"].Float();
  1009. startresHuman[2] = human["ore"].Float();
  1010. startresHuman[3] = human["sulfur"].Float();
  1011. startresHuman[4] = human["crystal"].Float();
  1012. startresHuman[5] = human["gems"].Float();
  1013. startresHuman[6] = human["gold"].Float();
  1014. startresHuman[7] = human["mithril"].Float();
  1015. startresAI[0] = ai["wood"].Float();
  1016. startresAI[1] = ai["mercury"].Float();
  1017. startresAI[2] = ai["ore"].Float();
  1018. startresAI[3] = ai["sulfur"].Float();
  1019. startresAI[4] = ai["crystal"].Float();
  1020. startresAI[5] = ai["gems"].Float();
  1021. startresAI[6] = ai["gold"].Float();
  1022. startresAI[7] = ai["mithril"].Float();
  1023. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1024. {
  1025. PlayerState &p = i->second;
  1026. if (p.human)
  1027. p.resources = startresHuman;
  1028. else
  1029. p.resources = startresAI;
  1030. }
  1031. //give start resource bonus in case of campaign
  1032. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1033. {
  1034. CScenarioTravel::STravelBonus chosenBonus =
  1035. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1036. if(chosenBonus.type == 7) //resource
  1037. {
  1038. std::vector<const PlayerSettings *> people = HLP::getHumanPlayerInfo(scenarioOps); //players we will give resource bonus
  1039. BOOST_FOREACH(const PlayerSettings *ps, people)
  1040. {
  1041. std::vector<int> res; //resources we will give
  1042. switch (chosenBonus.info1)
  1043. {
  1044. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1045. res.push_back(chosenBonus.info1);
  1046. break;
  1047. case 0xFD: //wood+ore
  1048. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1049. break;
  1050. case 0xFE: //rare
  1051. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1052. break;
  1053. default:
  1054. assert(0);
  1055. break;
  1056. }
  1057. //increasing resource quantity
  1058. for (int n=0; n<res.size(); ++n)
  1059. {
  1060. players[ps->color].resources[res[n]] += chosenBonus.info2;
  1061. }
  1062. }
  1063. }
  1064. }
  1065. /*************************HEROES************************************************/
  1066. std::set<int> hids; //hero ids to create pool
  1067. for(ui32 i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1068. if(map->allowedHeroes[i])
  1069. hids.insert(i);
  1070. for (ui32 i=0; i<map->heroes.size();i++) //heroes instances initialization
  1071. {
  1072. if (map->heroes[i]->getOwner()<0)
  1073. {
  1074. tlog2 << "Warning - hero with uninitialized owner!\n";
  1075. continue;
  1076. }
  1077. CGHeroInstance * vhi = (map->heroes[i]);
  1078. vhi->initHero();
  1079. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1080. hids.erase(vhi->subID);
  1081. }
  1082. for (ui32 i=0; i<map->objects.size();i++) //prisons
  1083. {
  1084. if (map->objects[i]->ID == 62)
  1085. hids.erase(map->objects[i]->subID);
  1086. }
  1087. for(ui32 i=0; i<map->predefinedHeroes.size(); i++)
  1088. {
  1089. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1090. continue;
  1091. map->predefinedHeroes[i]->initHero();
  1092. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1093. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1094. hids.erase(map->predefinedHeroes[i]->subID);
  1095. }
  1096. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1097. {
  1098. CGHeroInstance * vhi = new CGHeroInstance();
  1099. vhi->initHero(hid);
  1100. hpool.heroesPool[hid] = vhi;
  1101. hpool.pavailable[hid] = 0xff;
  1102. }
  1103. for(ui32 i=0; i<map->disposedHeroes.size(); i++)
  1104. {
  1105. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1106. }
  1107. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1108. {
  1109. CScenarioTravel::STravelBonus chosenBonus =
  1110. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1111. if (chosenBonus.isBonusForHero() && chosenBonus.info1 != 0xFFFE) //exclude generated heroes
  1112. {
  1113. //find human player
  1114. int humanPlayer=GameConstants::NEUTRAL_PLAYER;
  1115. for (std::map<ui8, PlayerState>::iterator it=players.begin(); it != players.end(); ++it)
  1116. {
  1117. if(it->second.human)
  1118. {
  1119. humanPlayer = it->first;
  1120. break;
  1121. }
  1122. }
  1123. assert(humanPlayer != GameConstants::NEUTRAL_PLAYER);
  1124. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1125. if (chosenBonus.info1 == 0xFFFD) //most powerful
  1126. {
  1127. int maxB = -1;
  1128. for (int b=0; b<heroes.size(); ++b)
  1129. {
  1130. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1131. {
  1132. maxB = b;
  1133. }
  1134. }
  1135. if(maxB < 0)
  1136. tlog2 << "Warning - cannot give bonus to hero cause there are no heroes!\n";
  1137. else
  1138. HLP::giveCampaignBonusToHero(heroes[maxB], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions, this);
  1139. }
  1140. else //specific hero
  1141. {
  1142. for (int b=0; b<heroes.size(); ++b)
  1143. {
  1144. if (heroes[b]->subID == chosenBonus.info1)
  1145. {
  1146. HLP::giveCampaignBonusToHero(heroes[b], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions, this);
  1147. break;
  1148. }
  1149. }
  1150. }
  1151. }
  1152. }
  1153. /*************************FOG**OF**WAR******************************************/
  1154. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  1155. {
  1156. k->second.fogOfWarMap.resize(map->width);
  1157. for(int g=0; g<map->width; ++g)
  1158. k->second.fogOfWarMap[g].resize(map->height);
  1159. for(int g=-0; g<map->width; ++g)
  1160. for(int h=0; h<map->height; ++h)
  1161. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1162. for(int g=0; g<map->width; ++g)
  1163. for(int h=0; h<map->height; ++h)
  1164. for(int v=0; v<map->twoLevel+1; ++v)
  1165. k->second.fogOfWarMap[g][h][v] = 0;
  1166. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1167. {
  1168. if( !vstd::contains(k->second.players, obj->tempOwner)) continue; //not a flagged object
  1169. boost::unordered_set<int3, ShashInt3> tiles;
  1170. obj->getSightTiles(tiles);
  1171. BOOST_FOREACH(int3 tile, tiles)
  1172. {
  1173. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1174. }
  1175. }
  1176. }
  1177. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1178. {
  1179. //starting bonus
  1180. if(scenarioOps->playerInfos[k->first].bonus==PlayerSettings::brandom)
  1181. scenarioOps->playerInfos[k->first].bonus = ran()%3;
  1182. switch(scenarioOps->playerInfos[k->first].bonus)
  1183. {
  1184. case PlayerSettings::bgold:
  1185. k->second.resources[Res::GOLD] += 500 + (ran()%6)*100;
  1186. break;
  1187. case PlayerSettings::bresource:
  1188. {
  1189. int res = VLC->townh->towns[scenarioOps->playerInfos[k->first].castle].primaryRes;
  1190. if(res == 127)
  1191. {
  1192. k->second.resources[Res::WOOD] += 5 + ran()%6;
  1193. k->second.resources[Res::ORE] += 5 + ran()%6;
  1194. }
  1195. else
  1196. {
  1197. k->second.resources[res] += 3 + ran()%4;
  1198. }
  1199. break;
  1200. }
  1201. case PlayerSettings::bartifact:
  1202. {
  1203. if(!k->second.heroes.size())
  1204. {
  1205. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1206. break;
  1207. }
  1208. CArtifact *toGive;
  1209. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1210. CGHeroInstance *hero = k->second.heroes[0];
  1211. giveHeroArtifact(hero, toGive->id);
  1212. }
  1213. break;
  1214. }
  1215. }
  1216. /****************************TOWNS************************************************/
  1217. for ( int i=0; i<4; i++)
  1218. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1219. for (ui32 i=0;i<map->towns.size();i++)
  1220. {
  1221. CGTownInstance * vti =(map->towns[i]);
  1222. if(!vti->town)
  1223. vti->town = &VLC->townh->towns[vti->subID];
  1224. if (vti->name.length()==0) // if town hasn't name we draw it
  1225. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1226. //init buildings
  1227. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1228. {
  1229. vti->builtBuildings.erase(-50);
  1230. vti->builtBuildings.insert(10);
  1231. vti->builtBuildings.insert(5);
  1232. vti->builtBuildings.insert(30);
  1233. if(ran()%2)
  1234. vti->builtBuildings.insert(31);
  1235. }
  1236. if (vstd::contains(vti->builtBuildings,(6)) && vti->state()==2)
  1237. vti->builtBuildings.erase(6);//if we have harbor without water - erase it (this is H3 behaviour)
  1238. //init hordes
  1239. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1240. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1241. {
  1242. vti->builtBuildings.erase(-31-i);//remove old ID
  1243. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1244. {
  1245. vti->builtBuildings.insert(18);//add it
  1246. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1247. vti->builtBuildings.insert(19);//add it as well
  1248. }
  1249. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1250. {
  1251. vti->builtBuildings.insert(24);
  1252. if (vstd::contains(vti->builtBuildings,(37+i)))
  1253. vti->builtBuildings.insert(25);
  1254. }
  1255. }
  1256. //town events
  1257. BOOST_FOREACH(CCastleEvent *ev, vti->events)
  1258. {
  1259. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1260. if (vstd::contains(ev->buildings,(-31-i))) //if we have horde for this level
  1261. {
  1262. ev->buildings.erase(-31-i);
  1263. if (vti->town->hordeLvl[0] == i)
  1264. ev->buildings.insert(18);
  1265. if (vti->town->hordeLvl[1] == i)
  1266. ev->buildings.insert(24);
  1267. }
  1268. }
  1269. //init spells
  1270. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1271. CSpell *s;
  1272. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1273. {
  1274. s = VLC->spellh->spells[vti->obligatorySpells[z]];
  1275. vti->spells[s->level-1].push_back(s->id);
  1276. vti->possibleSpells -= s->id;
  1277. }
  1278. while(vti->possibleSpells.size())
  1279. {
  1280. ui32 total=0;
  1281. int sel = -1;
  1282. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1283. total += VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1284. int r = (total)? ran()%total : -1;
  1285. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1286. {
  1287. r -= VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1288. if(r<0)
  1289. {
  1290. sel = ps;
  1291. break;
  1292. }
  1293. }
  1294. if(sel<0)
  1295. sel=0;
  1296. CSpell *s = VLC->spellh->spells[vti->possibleSpells[sel]];
  1297. vti->spells[s->level-1].push_back(s->id);
  1298. vti->possibleSpells -= s->id;
  1299. }
  1300. if(vti->getOwner() != 255)
  1301. getPlayer(vti->getOwner())->towns.push_back(vti);
  1302. }
  1303. //campaign bonuses for towns
  1304. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1305. {
  1306. CScenarioTravel::STravelBonus chosenBonus =
  1307. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1308. if (chosenBonus.type == 2)
  1309. {
  1310. for (int g=0; g<map->towns.size(); ++g)
  1311. {
  1312. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1313. if (owner)
  1314. {
  1315. PlayerInfo & pi = map->players[owner->color];
  1316. if (owner->human && //human-owned
  1317. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1318. {
  1319. map->towns[g]->builtBuildings.insert(
  1320. CBuildingHandler::campToERMU(chosenBonus.info1, map->towns[g]->town->typeID, map->towns[g]->builtBuildings));
  1321. break;
  1322. }
  1323. }
  1324. }
  1325. }
  1326. }
  1327. objCaller->preInit();
  1328. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1329. {
  1330. obj->initObj();
  1331. if(obj->ID == 62) //prison also needs to initialize hero
  1332. static_cast<CGHeroInstance*>(obj)->initHero();
  1333. }
  1334. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1335. {
  1336. switch (obj->ID)
  1337. {
  1338. case Obj::QUEST_GUARD:
  1339. case Obj::SEER_HUT:
  1340. {
  1341. auto q = static_cast<CGSeerHut*>(obj);
  1342. assert (q);
  1343. q->setObjToKill();
  1344. }
  1345. }
  1346. }
  1347. CGTeleport::postInit(); //pairing subterranean gates
  1348. buildBonusSystemTree();
  1349. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1350. {
  1351. if(k->first==255)
  1352. continue;
  1353. //init visiting and garrisoned heroes
  1354. BOOST_FOREACH(CGHeroInstance *h, k->second.heroes)
  1355. {
  1356. BOOST_FOREACH(CGTownInstance *t, k->second.towns)
  1357. {
  1358. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1359. if(vistile == h->pos || h->pos==t->pos)
  1360. {
  1361. t->setVisitingHero(h);
  1362. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1363. {
  1364. map->removeBlockVisTiles(h);
  1365. h->pos.x -= 1;
  1366. map->addBlockVisTiles(h);
  1367. }
  1368. break;
  1369. }
  1370. }
  1371. }
  1372. }
  1373. map->checkForObjectives(); //needs to be run when all objects are properly placed
  1374. int seedAfterInit = ran();
  1375. tlog0 << "Seed after init is " << seedAfterInit << " (before was " << scenarioOps->seedToBeUsed << ")" << std::endl;
  1376. if(scenarioOps->seedPostInit > 0)
  1377. {
  1378. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  1379. assert(scenarioOps->seedPostInit == seedAfterInit);
  1380. }
  1381. else
  1382. {
  1383. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  1384. }
  1385. }
  1386. int CGameState::battleGetBattlefieldType(int3 tile) const
  1387. {
  1388. if(tile==int3() && curB)
  1389. tile = curB->tile;
  1390. else if(tile==int3() && !curB)
  1391. return -1;
  1392. const TerrainTile &t = map->getTile(tile);
  1393. //fight in mine -> subterranean
  1394. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1395. return 12;
  1396. BOOST_FOREACH(auto &obj, map->objects)
  1397. {
  1398. //look only for objects covering given tile
  1399. if( !obj || obj->pos.z != tile.z
  1400. || !obj->coveringAt(tile.x - obj->pos.x, tile.y - obj->pos.y))
  1401. continue;
  1402. switch(obj->ID)
  1403. {
  1404. case Obj::CLOVER_FIELD:
  1405. return 19;
  1406. case Obj::CURSED_GROUND1: case Obj::CURSED_GROUND2:
  1407. return 22;
  1408. case Obj::EVIL_FOG:
  1409. return 20;
  1410. case Obj::FAVORABLE_WINDS:
  1411. return 21;
  1412. case Obj::FIERY_FIELDS:
  1413. return 14;
  1414. case Obj::HOLY_GROUNDS:
  1415. return 18;
  1416. case Obj::LUCID_POOLS:
  1417. return 17;
  1418. case Obj::MAGIC_CLOUDS:
  1419. return 16;
  1420. case Obj::MAGIC_PLAINS1: case Obj::MAGIC_PLAINS2:
  1421. return 9;
  1422. case Obj::ROCKLANDS:
  1423. return 15;
  1424. }
  1425. }
  1426. if(!t.isWater() && t.isCoastal())
  1427. return 1; //sand/beach
  1428. switch(t.tertype)
  1429. {
  1430. case TerrainTile::dirt:
  1431. return rand()%3+3;
  1432. case TerrainTile::sand:
  1433. return 2; //TODO: coast support
  1434. case TerrainTile::grass:
  1435. return rand()%2+6;
  1436. case TerrainTile::snow:
  1437. return rand()%2+10;
  1438. case TerrainTile::swamp:
  1439. return 13;
  1440. case TerrainTile::rough:
  1441. return 23;
  1442. case TerrainTile::subterranean:
  1443. return 12;
  1444. case TerrainTile::lava:
  1445. return 8;
  1446. case TerrainTile::water:
  1447. return 25;
  1448. case TerrainTile::rock:
  1449. return 15;
  1450. default:
  1451. return -1;
  1452. }
  1453. }
  1454. std::set<std::pair<int, int> > costDiff(const std::vector<ui32> &a, const std::vector<ui32> &b, const int modifier = 100) //modifer %
  1455. {
  1456. std::set<std::pair<int, int> > ret;
  1457. for(int j=0;j<GameConstants::RESOURCE_QUANTITY;j++)
  1458. {
  1459. assert(a[j] >= b[j]);
  1460. if(int dif = modifier * (a[j] - b[j]) / 100)
  1461. ret.insert(std::make_pair(j,dif));
  1462. }
  1463. return ret;
  1464. }
  1465. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1466. {
  1467. UpgradeInfo ret;
  1468. const CCreature *base = stack.type;
  1469. const CGHeroInstance *h = stack.armyObj->ID == GameConstants::HEROI_TYPE ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  1470. const CGTownInstance *t = NULL;
  1471. if(stack.armyObj->ID == GameConstants::TOWNI_TYPE)
  1472. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1473. else if(h)
  1474. { //hero speciality
  1475. TBonusListPtr lista = h->speciality.getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1476. BOOST_FOREACH(const Bonus *it, *lista)
  1477. {
  1478. ui16 nid = it->additionalInfo;
  1479. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1480. {
  1481. ret.newID.push_back(nid);
  1482. ret.cost.push_back(VLC->creh->creatures[nid]->cost - base->cost);
  1483. }
  1484. }
  1485. t = h->visitedTown;
  1486. }
  1487. if(t)
  1488. {
  1489. BOOST_FOREACH(const CGTownInstance::TCreaturesSet::value_type & dwelling, t->creatures)
  1490. {
  1491. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1492. {
  1493. BOOST_FOREACH(ui32 upgrID, dwelling.second)
  1494. {
  1495. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1496. {
  1497. ret.newID.push_back(upgrID);
  1498. ret.cost.push_back(VLC->creh->creatures[upgrID]->cost - base->cost);
  1499. }
  1500. }
  1501. }
  1502. }
  1503. }
  1504. //hero is visiting Hill Fort
  1505. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  1506. {
  1507. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1508. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1509. BOOST_FOREACH(si32 nid, base->upgrades)
  1510. {
  1511. ret.newID.push_back(nid);
  1512. ret.cost.push_back((VLC->creh->creatures[nid]->cost - base->cost) * costModifier / 100);
  1513. }
  1514. }
  1515. if(ret.newID.size())
  1516. ret.oldID = base->idNumber;
  1517. return ret;
  1518. }
  1519. int CGameState::getPlayerRelations( ui8 color1, ui8 color2 )
  1520. {
  1521. if ( color1 == color2 )
  1522. return 2;
  1523. if(color1 == 255 || color2 == 255) //neutral player has no friends
  1524. return 0;
  1525. const TeamState * ts = getPlayerTeam(color1);
  1526. if (ts && vstd::contains(ts->players, color2))
  1527. return 1;
  1528. return 0;
  1529. }
  1530. void CGameState::loadTownDInfos()
  1531. {
  1532. int i;
  1533. const JsonNode config(GameConstants::DATA_DIR + "/config/towns_defs.json");
  1534. assert(config["town_defnames"].Vector().size() == GameConstants::F_NUMBER);
  1535. i = 0;
  1536. BOOST_FOREACH(const JsonNode &t, config["town_defnames"].Vector())
  1537. {
  1538. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1539. villages[i]->name = t["village"].String();
  1540. map->defy.push_back(villages[i]);
  1541. forts[i] = VLC->dobjinfo->castles[i];
  1542. map->defy.push_back(forts[i]);
  1543. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1544. capitols[i]->name = t["capitol"].String();
  1545. map->defy.push_back(capitols[i]);
  1546. ++i;
  1547. }
  1548. }
  1549. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1550. {
  1551. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1552. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1553. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1554. {
  1555. const int3 hlp = tile + dirs[i];
  1556. if(!map->isInTheMap(hlp))
  1557. continue;
  1558. const TerrainTile &hlpt = map->getTile(hlp);
  1559. // //we cannot visit things from blocked tiles
  1560. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1561. // {
  1562. // continue;
  1563. // }
  1564. if(srct.tertype == TerrainTile::water && limitCoastSailing && hlpt.tertype == TerrainTile::water && dirs[i].x && dirs[i].y) //diagonal move through water
  1565. {
  1566. int3 hlp1 = tile,
  1567. hlp2 = tile;
  1568. hlp1.x += dirs[i].x;
  1569. hlp2.y += dirs[i].y;
  1570. if(map->getTile(hlp1).tertype != TerrainTile::water || map->getTile(hlp2).tertype != TerrainTile::water)
  1571. continue;
  1572. }
  1573. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  1574. && hlpt.tertype != TerrainTile::rock)
  1575. {
  1576. vec.push_back(hlp);
  1577. }
  1578. }
  1579. }
  1580. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1581. {
  1582. if(src == dest) //same tile
  1583. return 0;
  1584. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1585. &d = map->terrain[dest.x][dest.y][dest.z];
  1586. //get basic cost
  1587. int ret = h->getTileCost(d,s);
  1588. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1589. {
  1590. bool freeFlying = h->getBonusesCount(Selector::typeSubtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1591. if(!freeFlying)
  1592. {
  1593. ret *= 1.4; //40% penalty for movement over blocked tile
  1594. }
  1595. }
  1596. else if (d.tertype == TerrainTile::water)
  1597. {
  1598. if(h->boat && s.hasFavourableWinds() && d.hasFavourableWinds()) //Favourable Winds
  1599. ret *= 0.666;
  1600. else if (!h->boat && h->getBonusesCount(Selector::typeSubtype(Bonus::WATER_WALKING, 1)) > 0)
  1601. ret *= 1.4; //40% penalty for water walking
  1602. }
  1603. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1604. {
  1605. int old = ret;
  1606. ret *= 1.414213;
  1607. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1608. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1609. {
  1610. return remainingMovePoints;
  1611. }
  1612. }
  1613. int left = remainingMovePoints-ret;
  1614. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1615. {
  1616. std::vector<int3> vec;
  1617. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water, true);
  1618. for(size_t i=0; i < vec.size(); i++)
  1619. {
  1620. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1621. if(fcost <= left)
  1622. {
  1623. return ret;
  1624. }
  1625. }
  1626. ret = remainingMovePoints;
  1627. }
  1628. return ret;
  1629. }
  1630. void CGameState::apply(CPack *pack)
  1631. {
  1632. ui16 typ = typeList.getTypeID(pack);
  1633. applierGs->apps[typ]->applyOnGS(this,pack);
  1634. }
  1635. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1636. {
  1637. //the old pathfinder is not supported anymore!
  1638. assert(0);
  1639. return false;
  1640. }
  1641. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1642. {
  1643. CPathfinder pathfinder(out, this, hero);
  1644. pathfinder.calculatePaths(src, movement);
  1645. }
  1646. /**
  1647. * Tells if the tile is guarded by a monster as well as the position
  1648. * of the monster that will attack on it.
  1649. *
  1650. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1651. * the monster guarding the tile.
  1652. */
  1653. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1654. {
  1655. const int3 originalPos = pos;
  1656. // Give monster at position priority.
  1657. if (!map->isInTheMap(pos))
  1658. return int3(-1, -1, -1);
  1659. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  1660. if (posTile.visitable)
  1661. {
  1662. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  1663. {
  1664. if(obj->blockVisit)
  1665. {
  1666. if (obj->ID == 54) // Monster
  1667. return pos;
  1668. else
  1669. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  1670. }
  1671. }
  1672. }
  1673. // See if there are any monsters adjacent.
  1674. pos -= int3(1, 1, 0); // Start with top left.
  1675. for (int dx = 0; dx < 3; dx++)
  1676. {
  1677. for (int dy = 0; dy < 3; dy++)
  1678. {
  1679. if (map->isInTheMap(pos))
  1680. {
  1681. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  1682. if (tile.visitable && (tile.tertype == TerrainTile::water) == (posTile.tertype == TerrainTile::water))
  1683. {
  1684. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  1685. {
  1686. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1687. {
  1688. return pos;
  1689. }
  1690. }
  1691. }
  1692. }
  1693. pos.y++;
  1694. }
  1695. pos.y -= 3;
  1696. pos.x++;
  1697. }
  1698. return int3(-1, -1, -1);
  1699. }
  1700. bool CGameState::isVisible(int3 pos, int player)
  1701. {
  1702. if(player == 255) //neutral player
  1703. return false;
  1704. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  1705. }
  1706. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1707. {
  1708. if(player == -1)
  1709. return true;
  1710. if(player == 255) //neutral player -> TODO ??? needed?
  1711. return false;
  1712. //object is visible when at least one blocked tile is visible
  1713. for(int fx=0; fx<8; ++fx)
  1714. {
  1715. for(int fy=0; fy<6; ++fy)
  1716. {
  1717. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1718. if(map->isInTheMap(pos)
  1719. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1720. && isVisible(pos, player) )
  1721. return true;
  1722. }
  1723. }
  1724. return false;
  1725. }
  1726. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1727. {
  1728. const TerrainTile * pom = &map->getTile(dst);
  1729. return checkForVisitableDir(src, pom, dst);
  1730. }
  1731. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  1732. {
  1733. for(ui32 b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1734. {
  1735. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1736. continue;
  1737. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1738. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1739. {
  1740. return false;
  1741. }
  1742. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1743. {
  1744. return false;
  1745. }
  1746. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1747. {
  1748. return false;
  1749. }
  1750. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1751. {
  1752. return false;
  1753. }
  1754. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1755. {
  1756. return false;
  1757. }
  1758. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1759. {
  1760. return false;
  1761. }
  1762. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1763. {
  1764. return false;
  1765. }
  1766. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1767. {
  1768. return false;
  1769. }
  1770. }
  1771. return true;
  1772. }
  1773. int CGameState::victoryCheck( ui8 player ) const
  1774. {
  1775. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  1776. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD || map->victoryCondition.allowNormalVictory
  1777. || (!p->human && !map->victoryCondition.appliesToAI)) //if the special victory condition applies only to human, AI has the standard)
  1778. {
  1779. if(player == checkForStandardWin())
  1780. return -1;
  1781. }
  1782. if (p->enteredWinningCheatCode)
  1783. { //cheater or tester, but has entered the code...
  1784. return 1;
  1785. }
  1786. if(p->human || map->victoryCondition.appliesToAI)
  1787. {
  1788. switch(map->victoryCondition.condition)
  1789. {
  1790. case EVictoryConditionType::ARTIFACT:
  1791. //check if any hero has winning artifact
  1792. for(size_t i = 0; i < p->heroes.size(); i++)
  1793. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  1794. return 1;
  1795. break;
  1796. case EVictoryConditionType::GATHERTROOP:
  1797. {
  1798. //check if in players armies there is enough creatures
  1799. int total = 0; //creature counter
  1800. for(size_t i = 0; i < map->objects.size(); i++)
  1801. {
  1802. const CArmedInstance *ai = NULL;
  1803. if(map->objects[i]
  1804. && map->objects[i]->tempOwner == player //object controlled by player
  1805. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  1806. {
  1807. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  1808. if(i->second->type->idNumber == map->victoryCondition.ID) //it's searched creature
  1809. total += i->second->count;
  1810. }
  1811. }
  1812. if(total >= map->victoryCondition.count)
  1813. return 1;
  1814. }
  1815. break;
  1816. case EVictoryConditionType::GATHERRESOURCE:
  1817. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  1818. return 1;
  1819. break;
  1820. case EVictoryConditionType::BUILDCITY:
  1821. {
  1822. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  1823. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  1824. return 1;
  1825. }
  1826. break;
  1827. case EVictoryConditionType::BUILDGRAIL:
  1828. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  1829. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  1830. && t->tempOwner == player
  1831. && vstd::contains(t->builtBuildings, EBuilding::GRAIL))
  1832. return 1;
  1833. break;
  1834. case EVictoryConditionType::BEATHERO:
  1835. if(map->victoryCondition.obj->tempOwner >= GameConstants::PLAYER_LIMIT) //target hero not present on map
  1836. return 1;
  1837. break;
  1838. case EVictoryConditionType::CAPTURECITY:
  1839. {
  1840. if(map->victoryCondition.obj->tempOwner == player)
  1841. return 1;
  1842. }
  1843. break;
  1844. case EVictoryConditionType::BEATMONSTER:
  1845. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  1846. return 1;
  1847. break;
  1848. case EVictoryConditionType::TAKEDWELLINGS:
  1849. for(size_t i = 0; i < map->objects.size(); i++)
  1850. {
  1851. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  1852. {
  1853. switch(map->objects[i]->ID)
  1854. {
  1855. case 17: case 18: case 19: case 20: //dwellings
  1856. case 216: case 217: case 218:
  1857. return 0; //found not flagged dwelling - player not won
  1858. }
  1859. }
  1860. }
  1861. return 1;
  1862. break;
  1863. case EVictoryConditionType::TAKEMINES:
  1864. for(size_t i = 0; i < map->objects.size(); i++)
  1865. {
  1866. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  1867. {
  1868. switch(map->objects[i]->ID)
  1869. {
  1870. case 53: case 220:
  1871. return 0; //found not flagged mine - player not won
  1872. }
  1873. }
  1874. }
  1875. return 1;
  1876. break;
  1877. case EVictoryConditionType::TRANSPORTITEM:
  1878. {
  1879. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  1880. if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID))
  1881. || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID)))
  1882. {
  1883. return 1;
  1884. }
  1885. }
  1886. break;
  1887. }
  1888. }
  1889. return 0;
  1890. }
  1891. ui8 CGameState::checkForStandardWin() const
  1892. {
  1893. //std victory condition is:
  1894. //all enemies lost
  1895. ui8 supposedWinner = 255, winnerTeam = 255;
  1896. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  1897. {
  1898. if(i->second.status == PlayerState::INGAME && i->first < GameConstants::PLAYER_LIMIT)
  1899. {
  1900. if(supposedWinner == 255)
  1901. {
  1902. //first player remaining ingame - candidate for victory
  1903. supposedWinner = i->second.color;
  1904. winnerTeam = i->second.team;
  1905. }
  1906. else if(winnerTeam != i->second.team)
  1907. {
  1908. //current candidate has enemy remaining in game -> no vicotry
  1909. return 255;
  1910. }
  1911. }
  1912. }
  1913. return supposedWinner;
  1914. }
  1915. bool CGameState::checkForStandardLoss( ui8 player ) const
  1916. {
  1917. //std loss condition is: player lost all towns and heroes
  1918. const PlayerState &p = *CGameInfoCallback::getPlayer(player);
  1919. return !p.heroes.size() && !p.towns.size();
  1920. }
  1921. struct statsHLP
  1922. {
  1923. typedef std::pair< ui8, si64 > TStat;
  1924. //converts [<player's color, value>] to vec[place] -> platers
  1925. static std::vector< std::vector< ui8 > > getRank( std::vector<TStat> stats )
  1926. {
  1927. std::sort(stats.begin(), stats.end(), statsHLP());
  1928. //put first element
  1929. std::vector< std::vector<ui8> > ret;
  1930. std::vector<ui8> tmp;
  1931. tmp.push_back( stats[0].first );
  1932. ret.push_back( tmp );
  1933. //the rest of elements
  1934. for(int g=1; g<stats.size(); ++g)
  1935. {
  1936. if(stats[g].second == stats[g-1].second)
  1937. {
  1938. (ret.end()-1)->push_back( stats[g].first );
  1939. }
  1940. else
  1941. {
  1942. //create next occupied rank
  1943. std::vector<ui8> tmp;
  1944. tmp.push_back(stats[g].first);
  1945. ret.push_back(tmp);
  1946. }
  1947. }
  1948. return ret;
  1949. }
  1950. bool operator()(const TStat & a, const TStat & b) const
  1951. {
  1952. return a.second > b.second;
  1953. }
  1954. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  1955. {
  1956. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  1957. if(!h.size())
  1958. return NULL;
  1959. //best hero will be that with highest exp
  1960. int best = 0;
  1961. for(int b=1; b<h.size(); ++b)
  1962. {
  1963. if(h[b]->exp > h[best]->exp)
  1964. {
  1965. best = b;
  1966. }
  1967. }
  1968. return h[best];
  1969. }
  1970. //calculates total number of artifacts that belong to given player
  1971. static int getNumberOfArts(const PlayerState * ps)
  1972. {
  1973. int ret = 0;
  1974. for(int g=0; g<ps->heroes.size(); ++g)
  1975. {
  1976. ret += ps->heroes[g]->artifactsInBackpack.size() + ps->heroes[g]->artifactsWorn.size();
  1977. }
  1978. return ret;
  1979. }
  1980. };
  1981. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  1982. {
  1983. #define FILL_FIELD(FIELD, VAL_GETTER) \
  1984. { \
  1985. std::vector< std::pair< ui8, si64 > > stats; \
  1986. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  1987. { \
  1988. if(g->second.color == 255) \
  1989. continue; \
  1990. std::pair< ui8, si64 > stat; \
  1991. stat.first = g->second.color; \
  1992. stat.second = VAL_GETTER; \
  1993. stats.push_back(stat); \
  1994. } \
  1995. tgi.FIELD = statsHLP::getRank(stats); \
  1996. }
  1997. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  1998. {
  1999. if(g->second.color != 255)
  2000. tgi.playerColors.push_back(g->second.color);
  2001. }
  2002. if(level >= 1) //num of towns & num of heroes
  2003. {
  2004. //num of towns
  2005. FILL_FIELD(numOfTowns, g->second.towns.size())
  2006. //num of heroes
  2007. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2008. //best hero's portrait
  2009. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2010. {
  2011. if(g->second.color == 255)
  2012. continue;
  2013. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2014. InfoAboutHero iah;
  2015. iah.initFromHero(best, level >= 8);
  2016. iah.army.clear();
  2017. tgi.colorToBestHero[g->second.color] = iah;
  2018. }
  2019. }
  2020. if(level >= 2) //gold
  2021. {
  2022. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2023. }
  2024. if(level >= 2) //wood & ore
  2025. {
  2026. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2027. }
  2028. if(level >= 3) //mercury, sulfur, crystal, gems
  2029. {
  2030. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2031. }
  2032. if(level >= 4) //obelisks found
  2033. {
  2034. //TODO
  2035. }
  2036. if(level >= 5) //artifacts
  2037. {
  2038. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2039. }
  2040. if(level >= 6) //army strength
  2041. {
  2042. //TODO
  2043. }
  2044. if(level >= 7) //income
  2045. {
  2046. //TODO
  2047. }
  2048. if(level >= 8) //best hero's stats
  2049. {
  2050. //already set in lvl 1 handling
  2051. }
  2052. if(level >= 9) //personality
  2053. {
  2054. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2055. {
  2056. if(g->second.color == 255) //do nothing for neutral player
  2057. continue;
  2058. if(g->second.human)
  2059. {
  2060. tgi.personality[g->second.color] = -1;
  2061. }
  2062. else //AI
  2063. {
  2064. tgi.personality[g->second.color] = map->players[g->second.color].AITactic;
  2065. }
  2066. }
  2067. }
  2068. if(level >= 10) //best creature
  2069. {
  2070. //best creatures belonging to player (highest AI value)
  2071. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2072. {
  2073. if(g->second.color == 255) //do nothing for neutral player
  2074. continue;
  2075. int bestCre = -1; //best creature's ID
  2076. for(int b=0; b<g->second.heroes.size(); ++b)
  2077. {
  2078. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  2079. {
  2080. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2081. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2082. {
  2083. bestCre = toCmp;
  2084. }
  2085. }
  2086. }
  2087. tgi.bestCreature[g->second.color] = bestCre;
  2088. }
  2089. }
  2090. #undef FILL_FIELD
  2091. }
  2092. int CGameState::lossCheck( ui8 player ) const
  2093. {
  2094. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  2095. //if(map->lossCondition.typeOfLossCon == lossStandard)
  2096. if(checkForStandardLoss(player))
  2097. return -1;
  2098. if (p->enteredLosingCheatCode)
  2099. {
  2100. return 1;
  2101. }
  2102. if(p->human) //special loss condition applies only to human player
  2103. {
  2104. switch(map->lossCondition.typeOfLossCon)
  2105. {
  2106. case ELossConditionType::LOSSCASTLE:
  2107. {
  2108. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  2109. assert(t);
  2110. if(t->tempOwner != player)
  2111. return 1;
  2112. }
  2113. break;
  2114. case ELossConditionType::LOSSHERO:
  2115. {
  2116. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  2117. assert(h);
  2118. if(h->tempOwner != player)
  2119. return 1;
  2120. }
  2121. break;
  2122. case ELossConditionType::TIMEEXPIRES:
  2123. if(map->lossCondition.timeLimit < day)
  2124. return 1;
  2125. break;
  2126. }
  2127. }
  2128. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  2129. return 2;
  2130. return false;
  2131. }
  2132. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2133. {
  2134. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2135. for ( std::map<ui8, PlayerState>::iterator i = players.begin() ; i != players.end();i++)
  2136. for(std::vector< ConstTransitivePtr<CGHeroInstance> >::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2137. if(*j)
  2138. pool.erase((**j).subID);
  2139. return pool;
  2140. }
  2141. void CGameState::buildBonusSystemTree()
  2142. {
  2143. buildGlobalTeamPlayerTree();
  2144. attachArmedObjects();
  2145. BOOST_FOREACH(CGTownInstance *t, map->towns)
  2146. {
  2147. t->deserializationFix();
  2148. }
  2149. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2150. // are provided on initializing / deserializing
  2151. }
  2152. void CGameState::deserializationFix()
  2153. {
  2154. buildGlobalTeamPlayerTree();
  2155. attachArmedObjects();
  2156. }
  2157. void CGameState::buildGlobalTeamPlayerTree()
  2158. {
  2159. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  2160. {
  2161. TeamState *t = &k->second;
  2162. t->attachTo(&globalEffects);
  2163. BOOST_FOREACH(ui8 teamMember, k->second.players)
  2164. {
  2165. PlayerState *p = getPlayer(teamMember);
  2166. assert(p);
  2167. p->attachTo(t);
  2168. }
  2169. }
  2170. }
  2171. void CGameState::attachArmedObjects()
  2172. {
  2173. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  2174. {
  2175. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2176. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2177. }
  2178. }
  2179. void CGameState::giveHeroArtifact(CGHeroInstance *h, int aid)
  2180. {
  2181. CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  2182. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2183. map->addNewArtifactInstance(ai);
  2184. ai->putAt(ArtifactLocation(h, ai->firstAvailableSlot(h)));
  2185. }
  2186. int3 CPath::startPos() const
  2187. {
  2188. return nodes[nodes.size()-1].coord;
  2189. }
  2190. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2191. {
  2192. if (mode==0)
  2193. {
  2194. for (ui32 i=0;i<nodes.size();i++)
  2195. {
  2196. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2197. }
  2198. }
  2199. }
  2200. int3 CPath::endPos() const
  2201. {
  2202. return nodes[0].coord;
  2203. }
  2204. CGPathNode::CGPathNode()
  2205. :coord(-1,-1,-1)
  2206. {
  2207. accessible = 0;
  2208. land = 0;
  2209. moveRemains = 0;
  2210. turns = 255;
  2211. theNodeBefore = NULL;
  2212. }
  2213. bool CGPathNode::reachable() const
  2214. {
  2215. return turns < 255;
  2216. }
  2217. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2218. {
  2219. assert(isValid);
  2220. out.nodes.clear();
  2221. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2222. if(!curnode->theNodeBefore)
  2223. return false;
  2224. while(curnode)
  2225. {
  2226. CGPathNode cpn = *curnode;
  2227. curnode = curnode->theNodeBefore;
  2228. out.nodes.push_back(cpn);
  2229. }
  2230. return true;
  2231. }
  2232. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2233. :sizes(Sizes)
  2234. {
  2235. hero = NULL;
  2236. nodes = new CGPathNode**[sizes.x];
  2237. for(int i = 0; i < sizes.x; i++)
  2238. {
  2239. nodes[i] = new CGPathNode*[sizes.y];
  2240. for (int j = 0; j < sizes.y; j++)
  2241. {
  2242. nodes[i][j] = new CGPathNode[sizes.z];
  2243. }
  2244. }
  2245. }
  2246. CPathsInfo::~CPathsInfo()
  2247. {
  2248. for(int i = 0; i < sizes.x; i++)
  2249. {
  2250. for (int j = 0; j < sizes.y; j++)
  2251. {
  2252. delete [] nodes[i][j];
  2253. }
  2254. delete [] nodes[i];
  2255. }
  2256. delete [] nodes;
  2257. }
  2258. int3 CGPath::startPos() const
  2259. {
  2260. return nodes[nodes.size()-1].coord;
  2261. }
  2262. int3 CGPath::endPos() const
  2263. {
  2264. return nodes[0].coord;
  2265. }
  2266. void CGPath::convert( ui8 mode )
  2267. {
  2268. if(mode==0)
  2269. {
  2270. for(ui32 i=0;i<nodes.size();i++)
  2271. {
  2272. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2273. }
  2274. }
  2275. }
  2276. PlayerState::PlayerState()
  2277. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  2278. enteredLosingCheatCode(0), status(INGAME), daysWithoutCastle(0)
  2279. {
  2280. setNodeType(PLAYER);
  2281. }
  2282. std::string PlayerState::nodeName() const
  2283. {
  2284. return "Player " + (color < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color] : boost::lexical_cast<std::string>(color));
  2285. }
  2286. // void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  2287. // {
  2288. // return; //no loops possible
  2289. // }
  2290. //
  2291. // void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  2292. // {
  2293. // for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); it++)
  2294. // {
  2295. // if (*it != root)
  2296. // (*it)->getBonuses(out, selector, this);
  2297. // }
  2298. // }
  2299. InfoAboutArmy::InfoAboutArmy():
  2300. owner(GameConstants::NEUTRAL_PLAYER)
  2301. {}
  2302. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2303. {
  2304. initFromArmy(Army, detailed);
  2305. }
  2306. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2307. {
  2308. army = ArmyDescriptor(Army, detailed);
  2309. owner = Army->tempOwner;
  2310. name = Army->getHoverText();
  2311. }
  2312. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2313. {
  2314. InfoAboutArmy::operator = (iah);
  2315. details = (iah.details ? new Details(*iah.details) : NULL);
  2316. hclass = iah.hclass;
  2317. portrait = iah.portrait;
  2318. }
  2319. InfoAboutHero::InfoAboutHero():
  2320. details(nullptr),
  2321. hclass(nullptr),
  2322. portrait(-1)
  2323. {}
  2324. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah):
  2325. InfoAboutArmy()
  2326. {
  2327. assign(iah);
  2328. }
  2329. InfoAboutHero::InfoAboutHero(const CGHeroInstance *h, bool detailed)
  2330. {
  2331. initFromHero(h, detailed);
  2332. }
  2333. InfoAboutHero::~InfoAboutHero()
  2334. {
  2335. delete details;
  2336. }
  2337. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2338. {
  2339. assign(iah);
  2340. return *this;
  2341. }
  2342. void InfoAboutHero::initFromHero(const CGHeroInstance *h, bool detailed)
  2343. {
  2344. if(!h)
  2345. return;
  2346. initFromArmy(h, detailed);
  2347. hclass = h->type->heroClass;
  2348. name = h->name;
  2349. portrait = h->portrait;
  2350. if(detailed)
  2351. {
  2352. //include details about hero
  2353. details = new Details;
  2354. details->luck = h->LuckVal();
  2355. details->morale = h->MoraleVal();
  2356. details->mana = h->mana;
  2357. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2358. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2359. {
  2360. details->primskills[i] = h->getPrimSkillLevel(i);
  2361. }
  2362. }
  2363. }
  2364. InfoAboutTown::InfoAboutTown():
  2365. details(nullptr),
  2366. tType(nullptr),
  2367. built(0),
  2368. fortLevel(0)
  2369. {
  2370. }
  2371. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed)
  2372. {
  2373. initFromTown(t, detailed);
  2374. }
  2375. InfoAboutTown::~InfoAboutTown()
  2376. {
  2377. delete details;
  2378. }
  2379. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2380. {
  2381. initFromArmy(t, detailed);
  2382. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2383. built = t->builded;
  2384. fortLevel = t->fortLevel();
  2385. name = t->name;
  2386. tType = t->town;
  2387. if(detailed)
  2388. {
  2389. //include details about hero
  2390. details = new Details;
  2391. details->goldIncome = t->dailyIncome();
  2392. details->customRes = vstd::contains(t->builtBuildings, 15);
  2393. details->hallLevel = t->hallLevel();
  2394. details->garrisonedHero = t->garrisonHero;
  2395. }
  2396. }
  2397. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2398. : isDetailed(detailed)
  2399. {
  2400. for(TSlots::const_iterator i = army->Slots().begin(); i != army->Slots().end(); i++)
  2401. {
  2402. if(detailed)
  2403. (*this)[i->first] = *i->second;
  2404. else
  2405. (*this)[i->first] = CStackBasicDescriptor(i->second->type, i->second->getQuantityID());
  2406. }
  2407. }
  2408. ArmyDescriptor::ArmyDescriptor()
  2409. : isDetailed(false)
  2410. {
  2411. }
  2412. int ArmyDescriptor::getStrength() const
  2413. {
  2414. ui64 ret = 0;
  2415. if(isDetailed)
  2416. {
  2417. for(const_iterator i = begin(); i != end(); i++)
  2418. ret += i->second.type->AIValue * i->second.count;
  2419. }
  2420. else
  2421. {
  2422. for(const_iterator i = begin(); i != end(); i++)
  2423. ret += i->second.type->AIValue * CCreature::estimateCreatureCount(i->second.count);
  2424. }
  2425. return ret;
  2426. }
  2427. DuelParameters::SideSettings::StackSettings::StackSettings()
  2428. : type(-1), count(0)
  2429. {
  2430. }
  2431. DuelParameters::SideSettings::StackSettings::StackSettings(si32 Type, si32 Count)
  2432. : type(Type), count(Count)
  2433. {
  2434. }
  2435. DuelParameters::SideSettings::SideSettings()
  2436. {
  2437. heroId = -1;
  2438. }
  2439. DuelParameters::DuelParameters()
  2440. {
  2441. terType = TerrainTile::dirt;
  2442. bfieldType = 15;
  2443. }
  2444. TeamState::TeamState()
  2445. {
  2446. setNodeType(TEAM);
  2447. }
  2448. void CPathfinder::initializeGraph()
  2449. {
  2450. CGPathNode ***graph = out.nodes;
  2451. for(size_t i=0; i < out.sizes.x; ++i)
  2452. {
  2453. for(size_t j=0; j < out.sizes.y; ++j)
  2454. {
  2455. for(size_t k=0; k < out.sizes.z; ++k)
  2456. {
  2457. curPos = int3(i,j,k);
  2458. const TerrainTile *tinfo = &gs->map->terrain[i][j][k];
  2459. CGPathNode &node = graph[i][j][k];
  2460. node.accessible = evaluateAccessibility(tinfo);
  2461. node.turns = 0xff;
  2462. node.moveRemains = 0;
  2463. node.coord.x = i;
  2464. node.coord.y = j;
  2465. node.coord.z = k;
  2466. node.land = tinfo->tertype != TerrainTile::water;
  2467. node.theNodeBefore = NULL;
  2468. }
  2469. }
  2470. }
  2471. }
  2472. void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*= -1*/)
  2473. {
  2474. assert(hero);
  2475. assert(hero == getHero(hero->id));
  2476. if(src.x < 0)
  2477. src = hero->getPosition(false);
  2478. if(movement < 0)
  2479. movement = hero->movement;
  2480. out.hero = hero;
  2481. out.hpos = src;
  2482. if(!gs->map->isInTheMap(src)/* || !gs->map->isInTheMap(dest)*/) //check input
  2483. {
  2484. tlog1 << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...\n";
  2485. return;
  2486. }
  2487. initializeGraph();
  2488. //initial tile - set cost on 0 and add to the queue
  2489. CGPathNode &initialNode = *getNode(src);
  2490. initialNode.turns = 0;
  2491. initialNode.moveRemains = movement;
  2492. mq.push_back(&initialNode);
  2493. std::vector<int3> neighbours;
  2494. neighbours.reserve(16);
  2495. while(!mq.empty())
  2496. {
  2497. cp = mq.front();
  2498. mq.pop_front();
  2499. const int3 sourceGuardPosition = guardingCreaturePosition(cp->coord);
  2500. bool guardedSource = (sourceGuardPosition != int3(-1, -1, -1) && cp->coord != src);
  2501. ct = &gs->map->getTile(cp->coord);
  2502. int movement = cp->moveRemains, turn = cp->turns;
  2503. if(!movement)
  2504. {
  2505. movement = hero->maxMovePoints(cp->land);
  2506. turn++;
  2507. }
  2508. //add accessible neighbouring nodes to the queue
  2509. neighbours.clear();
  2510. //handling subterranean gate => it's exit is the only neighbour
  2511. bool subterraneanEntry = (ct->topVisitableID() == GameConstants::SUBTERRANEAN_GATE_TYPE && useSubterraneanGates);
  2512. if(subterraneanEntry)
  2513. {
  2514. //try finding the exit gate
  2515. if(const CGObjectInstance *outGate = getObj(CGTeleport::getMatchingGate(ct->visitableObjects.back()->id), false))
  2516. {
  2517. const int3 outPos = outGate->visitablePos();
  2518. //gs->getNeighbours(*getTile(outPos), outPos, neighbours, boost::logic::indeterminate, !cp->land);
  2519. neighbours.push_back(outPos);
  2520. }
  2521. else
  2522. {
  2523. //gate with no exit (blocked) -> do nothing with this node
  2524. continue;
  2525. }
  2526. }
  2527. gs->getNeighbours(*ct, cp->coord, neighbours, boost::logic::indeterminate, !cp->land);
  2528. for(ui32 i=0; i < neighbours.size(); i++)
  2529. {
  2530. const int3 &n = neighbours[i]; //current neighbor
  2531. dp = getNode(n);
  2532. dt = &gs->map->getTile(n);
  2533. destTopVisObjID = dt->topVisitableID();
  2534. useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
  2535. int turnAtNextTile = turn;
  2536. const bool destIsGuardian = sourceGuardPosition == n;
  2537. if(!goodForLandSeaTransition())
  2538. continue;
  2539. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED )
  2540. continue;
  2541. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  2542. if(cp->accessible == CGPathNode::VISITABLE && guardedSource && cp->theNodeBefore->land && ct->topVisitableID() == GameConstants::BOATI_TYPE)
  2543. guardedSource = false;
  2544. int cost = gs->getMovementCost(hero, cp->coord, dp->coord, movement);
  2545. //special case -> moving from src Subterranean gate to dest gate -> it's free
  2546. if(subterraneanEntry && destTopVisObjID == GameConstants::SUBTERRANEAN_GATE_TYPE && cp->coord.z != dp->coord.z)
  2547. cost = 0;
  2548. int remains = movement - cost;
  2549. if(useEmbarkCost)
  2550. {
  2551. remains = hero->movementPointsAfterEmbark(movement, cost, useEmbarkCost - 1);
  2552. cost = movement - remains;
  2553. }
  2554. if(remains < 0)
  2555. {
  2556. //occurs rarely, when hero with low movepoints tries to leave the road
  2557. turnAtNextTile++;
  2558. int moveAtNextTile = hero->maxMovePoints(cp->land);
  2559. cost = gs->getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2560. remains = moveAtNextTile - cost;
  2561. }
  2562. if((dp->turns==0xff //we haven't been here before
  2563. || dp->turns > turnAtNextTile
  2564. || (dp->turns >= turnAtNextTile && dp->moveRemains < remains)) //this route is faster
  2565. && (!guardedSource || destIsGuardian)) // Can step into tile of guard
  2566. {
  2567. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  2568. dp->moveRemains = remains;
  2569. dp->turns = turnAtNextTile;
  2570. dp->theNodeBefore = cp;
  2571. const bool guardedDst = guardingCreaturePosition(dp->coord) != int3(-1, -1, -1)
  2572. && dp->accessible == CGPathNode::BLOCKVIS;
  2573. if (dp->accessible == CGPathNode::ACCESSIBLE
  2574. || (useEmbarkCost && allowEmbarkAndDisembark)
  2575. || destTopVisObjID == GameConstants::SUBTERRANEAN_GATE_TYPE
  2576. || (guardedDst && !guardedSource)) // Can step into a hostile tile once.
  2577. {
  2578. mq.push_back(dp);
  2579. }
  2580. }
  2581. } //neighbours loop
  2582. } //queue loop
  2583. out.isValid = true;
  2584. }
  2585. CGPathNode *CPathfinder::getNode(const int3 &coord)
  2586. {
  2587. return &out.nodes[coord.x][coord.y][coord.z];
  2588. }
  2589. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  2590. {
  2591. return gs->checkForVisitableDir(a, b) && gs->checkForVisitableDir(b, a);
  2592. }
  2593. bool CPathfinder::canStepOntoDst() const
  2594. {
  2595. //TODO remove
  2596. assert(0);
  2597. return false;
  2598. }
  2599. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const TerrainTile *tinfo) const
  2600. {
  2601. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  2602. if(tinfo->tertype == TerrainTile::rock || !FoW[curPos.x][curPos.y][curPos.z])
  2603. return CGPathNode::BLOCKED;
  2604. if(tinfo->visitable)
  2605. {
  2606. if(tinfo->visitableObjects.front()->ID == 80 && tinfo->visitableObjects.back()->ID == GameConstants::HEROI_TYPE && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner) //non-owned hero stands on Sanctuary
  2607. {
  2608. return CGPathNode::BLOCKED;
  2609. }
  2610. else
  2611. {
  2612. BOOST_FOREACH(const CGObjectInstance *obj, tinfo->visitableObjects)
  2613. {
  2614. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  2615. {
  2616. ret = CGPathNode::ACCESSIBLE;
  2617. }
  2618. else if(obj->blockVisit)
  2619. {
  2620. return CGPathNode::BLOCKVIS;
  2621. }
  2622. else if(obj->ID != GameConstants::EVENTI_TYPE) //pathfinder should ignore placed events
  2623. {
  2624. ret = CGPathNode::VISITABLE;
  2625. }
  2626. }
  2627. }
  2628. }
  2629. else if (gs->map->isInTheMap(guardingCreaturePosition(curPos))
  2630. && !tinfo->blocked)
  2631. {
  2632. // Monster close by; blocked visit for battle.
  2633. return CGPathNode::BLOCKVIS;
  2634. }
  2635. return ret;
  2636. }
  2637. bool CPathfinder::goodForLandSeaTransition()
  2638. {
  2639. if(cp->land != dp->land) //hero can traverse land<->sea only in special circumstances
  2640. {
  2641. if(cp->land) //from land to sea -> embark or assault hero on boat
  2642. {
  2643. if(dp->accessible == CGPathNode::ACCESSIBLE || destTopVisObjID < 0) //cannot enter empty water tile from land -> it has to be visitable
  2644. return false;
  2645. if(destTopVisObjID != GameConstants::HEROI_TYPE && destTopVisObjID != GameConstants::BOATI_TYPE) //only boat or hero can be accessed from land
  2646. return false;
  2647. if(destTopVisObjID == GameConstants::BOATI_TYPE)
  2648. useEmbarkCost = 1;
  2649. }
  2650. else //disembark
  2651. {
  2652. //can disembark only on coastal tiles
  2653. if(!dt->isCoastal())
  2654. return false;
  2655. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  2656. if( (dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  2657. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  2658. return false;;
  2659. useEmbarkCost = 2;
  2660. }
  2661. }
  2662. return true;
  2663. }
  2664. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero) : CGameInfoCallback(_gs, -1), out(_out), hero(_hero), FoW(getPlayerTeam(hero->tempOwner)->fogOfWarMap)
  2665. {
  2666. useSubterraneanGates = true;
  2667. allowEmbarkAndDisembark = true;
  2668. }