CGameState.cpp 85 KB

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