CGameState.cpp 89 KB

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