CGameState.cpp 85 KB

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