CGameState.cpp 85 KB

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