CGameState.cpp 86 KB

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