CGameState.cpp 82 KB

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