CGameState.cpp 86 KB

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