CGameState.cpp 82 KB

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