CGameState.cpp 82 KB

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