CGameState.cpp 86 KB

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