CGameState.cpp 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260
  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(int i = 0; i < map->players.size(); ++i)
  828. {
  829. const PlayerInfo & pInfo = map->players[i];
  830. if(pInfo.canComputerPlay || pInfo.canHumanPlay)
  831. {
  832. PlayerSettings & pSettings = scenarioOps->playerInfos[i];
  833. pSettings.compOnly = !pInfo.canHumanPlay;
  834. pSettings.team = pInfo.team;
  835. pSettings.castle = pInfo.defaultCastle();
  836. if(pSettings.playerID == PlayerSettings::PLAYER_AI && pSettings.name.empty())
  837. {
  838. pSettings.name = VLC->generaltexth->allTexts[468];
  839. }
  840. pSettings.color = i;
  841. }
  842. else
  843. {
  844. scenarioOps->playerInfos.erase(i);
  845. }
  846. }
  847. }
  848. else
  849. {
  850. tlog0 << "Open map file: " << scenarioOps->mapname << std::endl;
  851. map = CMapService::loadMap(scenarioOps->mapname).release();
  852. }
  853. }
  854. break;
  855. case StartInfo::CAMPAIGN:
  856. {
  857. tlog0 << "Open campaign map file: " << scenarioOps->campState->currentMap << std::endl;
  858. auto campaign = scenarioOps->campState;
  859. assert(vstd::contains(campaign->camp->mapPieces, scenarioOps->campState->currentMap));
  860. std::string & mapContent = campaign->camp->mapPieces[scenarioOps->campState->currentMap];
  861. auto buffer = reinterpret_cast<const ui8 *>(mapContent.data());
  862. map = CMapService::loadMap(buffer, mapContent.size()).release();
  863. }
  864. break;
  865. case StartInfo::DUEL:
  866. initDuel();
  867. return;
  868. default:
  869. tlog1 << "Wrong mode: " << (int)scenarioOps->mode << std::endl;
  870. return;
  871. }
  872. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  873. tlog0 << "Map loaded!" << std::endl;
  874. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  875. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  876. if(scenarioOps->mapfileChecksum)
  877. {
  878. tlog0 << "\tServer checksum for " << scenarioOps->mapname <<": "<< scenarioOps->mapfileChecksum << std::endl;
  879. if(map->checksum != scenarioOps->mapfileChecksum)
  880. {
  881. tlog1 << "Wrong map checksum!!!" << std::endl;
  882. throw std::runtime_error("Wrong checksum");
  883. }
  884. }
  885. else
  886. scenarioOps->mapfileChecksum = map->checksum;
  887. day = 0;
  888. tlog4 << "Initialization:";
  889. tlog4 << "\tPicking grail position";
  890. //pick grail location
  891. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  892. {
  893. if(!map->grailRadious) //radius not given -> anywhere on map
  894. map->grailRadious = map->width * 2;
  895. std::vector<int3> allowedPos;
  896. // add all not blocked tiles in range
  897. for (int i = 0; i < map->width ; i++)
  898. {
  899. for (int j = 0; j < map->height ; j++)
  900. {
  901. for (int k = 0; k < (map->twoLevel ? 2 : 1); k++)
  902. {
  903. const TerrainTile &t = map->terrain[i][j][k];
  904. if(!t.blocked
  905. && !t.visitable
  906. && t.terType != ETerrainType::WATER
  907. && t.terType != ETerrainType::ROCK
  908. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  909. allowedPos.push_back(int3(i,j,k));
  910. }
  911. }
  912. }
  913. //remove tiles with holes
  914. for(ui32 no=0; no<map->objects.size(); ++no)
  915. if(map->objects[no]->ID == Obj::HOLE)
  916. allowedPos -= map->objects[no]->pos;
  917. if(allowedPos.size())
  918. map->grailPos = allowedPos[ran() % allowedPos.size()];
  919. else
  920. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  921. }
  922. //picking random factions for players
  923. tlog4 << "\tPicking random factions for players";
  924. for(auto it = scenarioOps->playerInfos.begin();
  925. it != scenarioOps->playerInfos.end(); ++it)
  926. {
  927. if(it->second.castle==-1)
  928. {
  929. int randomID = ran() % map->players[it->first].allowedFactions.size();
  930. auto iter = map->players[it->first].allowedFactions.begin();
  931. std::advance(iter, randomID);
  932. it->second.castle = *iter;
  933. }
  934. }
  935. //randomizing objects
  936. tlog4 << "\tRandomizing objects";
  937. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  938. {
  939. randomizeObject(obj);
  940. obj->hoverName = VLC->generaltexth->names[obj->ID];
  941. //handle Favouring Winds - mark tiles under it
  942. if(obj->ID == Obj::FAVORABLE_WINDS)
  943. for (int i = 0; i < obj->getWidth() ; i++)
  944. for (int j = 0; j < obj->getHeight() ; j++)
  945. {
  946. int3 pos = obj->pos - int3(i,j,0);
  947. if(map->isInTheMap(pos))
  948. map->getTile(pos).extTileFlags |= 128;
  949. }
  950. }
  951. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  952. /*********creating players entries in gs****************************************/
  953. tlog4 << "\tCreating player entries in gs";
  954. for(auto it = scenarioOps->playerInfos.begin();
  955. it != scenarioOps->playerInfos.end(); ++it)
  956. {
  957. std::pair<TPlayerColor,PlayerState> ins(it->first,PlayerState());
  958. ins.second.color=ins.first;
  959. ins.second.human = it->second.playerID;
  960. ins.second.team = map->players[ins.first].team;
  961. teams[ins.second.team].id = ins.second.team;//init team
  962. teams[ins.second.team].players.insert(ins.first);//add player to team
  963. players.insert(ins);
  964. }
  965. /*********give starting hero****************************************/
  966. tlog4 << "\tGiving starting hero";
  967. {
  968. bool campaignGiveHero = false;
  969. if(scenarioOps->campState)
  970. {
  971. auto bonus = scenarioOps->campState->getBonusForCurrentMap();
  972. if(bonus.is_initialized())
  973. {
  974. campaignGiveHero = scenarioOps->mode == StartInfo::CAMPAIGN &&
  975. bonus.get().type == CScenarioTravel::STravelBonus::HERO;
  976. }
  977. }
  978. for(auto it = scenarioOps->playerInfos.begin(); it != scenarioOps->playerInfos.end(); ++it)
  979. {
  980. const PlayerInfo &p = map->players[it->first];
  981. bool generateHero = (p.generateHeroAtMainTown ||
  982. (it->second.playerID != PlayerSettings::PLAYER_AI && campaignGiveHero)) && p.hasMainTown;
  983. if(generateHero && vstd::contains(scenarioOps->playerInfos, it->first))
  984. {
  985. int3 hpos = p.posOfMainTown;
  986. hpos.x+=1;
  987. int h = pickHero(it->first);
  988. if(it->second.hero == -1)
  989. it->second.hero = h;
  990. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(Obj::HERO,h,hpos,it->first));
  991. nnn->id = map->objects.size();
  992. nnn->initHero();
  993. map->heroes.push_back(nnn);
  994. map->objects.push_back(nnn);
  995. map->addBlockVisTiles(nnn);
  996. }
  997. }
  998. }
  999. /*************************replace hero placeholders*****************************/
  1000. tlog4 << "\tReplacing hero placeholders";
  1001. if (scenarioOps->campState)
  1002. {
  1003. auto campaign = scenarioOps->campState;
  1004. auto bonus = campaign->getBonusForCurrentMap();
  1005. if(bonus.is_initialized())
  1006. {
  1007. std::vector<CGHeroInstance *> Xheroes;
  1008. if (bonus->type == CScenarioTravel::STravelBonus::PLAYER_PREV_SCENARIO)
  1009. {
  1010. Xheroes = campaign->camp->scenarios[bonus->info2].crossoverHeroes;
  1011. }
  1012. //selecting heroes by type
  1013. for(int g=0; g<map->objects.size(); ++g)
  1014. {
  1015. CGObjectInstance * obj = map->objects[g];
  1016. if (obj->ID != Obj::HERO_PLACEHOLDER)
  1017. {
  1018. continue;
  1019. }
  1020. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1021. if(hp->subID != 0xFF) //select by type
  1022. {
  1023. bool found = false;
  1024. BOOST_FOREACH(CGHeroInstance * ghi, Xheroes)
  1025. {
  1026. if (ghi->subID == hp->subID)
  1027. {
  1028. found = true;
  1029. replaceHero(g, ghi);
  1030. Xheroes -= ghi;
  1031. break;
  1032. }
  1033. }
  1034. if (!found)
  1035. {
  1036. //TODO: create new hero of this type
  1037. }
  1038. }
  1039. }
  1040. //selecting heroes by power
  1041. std::sort(Xheroes.begin(), Xheroes.end(), [](const CGHeroInstance * a, const CGHeroInstance * b)
  1042. {
  1043. return a->getHeroStrength() > b->getHeroStrength();
  1044. }); //sort, descending strength
  1045. for(int g=0; g<map->objects.size(); ++g)
  1046. {
  1047. CGObjectInstance * obj = map->objects[g];
  1048. if (obj->ID != Obj::HERO_PLACEHOLDER)
  1049. {
  1050. continue;
  1051. }
  1052. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1053. if (hp->subID == 0xFF) //select by power
  1054. {
  1055. if(Xheroes.size() > hp->power - 1)
  1056. replaceHero(g, Xheroes[hp->power - 1]);
  1057. else
  1058. tlog2 << "Warning, to hero to replace!\n";
  1059. //we don't have to remove hero from Xheroes because it would destroy the order and duplicates shouldn't happen
  1060. }
  1061. }
  1062. }
  1063. }
  1064. /******************RESOURCES****************************************************/
  1065. tlog4 << "\tSetting up resources";
  1066. const JsonNode config(ResourceID("config/startres.json"));
  1067. const JsonVector &vector = config["difficulty"].Vector();
  1068. const JsonNode &level = vector[scenarioOps->difficulty];
  1069. TResources startresAI(level["ai"]);
  1070. TResources startresHuman(level["human"]);
  1071. for (auto i = players.begin(); i!=players.end(); i++)
  1072. {
  1073. PlayerState &p = i->second;
  1074. if (p.human)
  1075. p.resources = startresHuman;
  1076. else
  1077. p.resources = startresAI;
  1078. }
  1079. //give start resource bonus in case of campaign
  1080. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1081. {
  1082. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1083. if(chosenBonus.is_initialized() && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1084. {
  1085. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1086. BOOST_FOREACH(const PlayerSettings *ps, people)
  1087. {
  1088. std::vector<int> res; //resources we will give
  1089. switch (chosenBonus->info1)
  1090. {
  1091. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1092. res.push_back(chosenBonus->info1);
  1093. break;
  1094. case 0xFD: //wood+ore
  1095. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1096. break;
  1097. case 0xFE: //rare
  1098. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1099. break;
  1100. default:
  1101. assert(0);
  1102. break;
  1103. }
  1104. //increasing resource quantity
  1105. for (int n=0; n<res.size(); ++n)
  1106. {
  1107. players[ps->color].resources[res[n]] += chosenBonus->info2;
  1108. }
  1109. }
  1110. }
  1111. }
  1112. /*************************HEROES************************************************/
  1113. tlog4 << "\tSetting up heroes";
  1114. std::set<int> hids; //hero ids to create pool
  1115. for(ui32 i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1116. if(map->allowedHeroes[i])
  1117. hids.insert(i);
  1118. for (ui32 i=0; i<map->heroes.size();i++) //heroes instances initialization
  1119. {
  1120. if (map->heroes[i]->getOwner()<0)
  1121. {
  1122. tlog2 << "Warning - hero with uninitialized owner!\n";
  1123. continue;
  1124. }
  1125. CGHeroInstance * vhi = (map->heroes[i]);
  1126. vhi->initHero();
  1127. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1128. hids.erase(vhi->subID);
  1129. }
  1130. for (ui32 i=0; i<map->objects.size();i++) //prisons
  1131. {
  1132. if (map->objects[i]->ID == Obj::PRISON)
  1133. hids.erase(map->objects[i]->subID);
  1134. }
  1135. for(ui32 i=0; i<map->predefinedHeroes.size(); i++)
  1136. {
  1137. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1138. continue;
  1139. map->predefinedHeroes[i]->initHero();
  1140. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1141. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1142. hids.erase(map->predefinedHeroes[i]->subID);
  1143. }
  1144. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1145. {
  1146. CGHeroInstance * vhi = new CGHeroInstance();
  1147. vhi->initHero(hid);
  1148. hpool.heroesPool[hid] = vhi;
  1149. hpool.pavailable[hid] = 0xff;
  1150. }
  1151. for(ui32 i=0; i<map->disposedHeroes.size(); i++)
  1152. {
  1153. hpool.pavailable[map->disposedHeroes[i].heroId] = map->disposedHeroes[i].players;
  1154. }
  1155. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1156. {
  1157. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1158. if (chosenBonus.is_initialized() && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1159. {
  1160. //find human player
  1161. int humanPlayer=GameConstants::NEUTRAL_PLAYER;
  1162. for (auto it=players.begin(); it != players.end(); ++it)
  1163. {
  1164. if(it->second.human)
  1165. {
  1166. humanPlayer = it->first;
  1167. break;
  1168. }
  1169. }
  1170. assert(humanPlayer != GameConstants::NEUTRAL_PLAYER);
  1171. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1172. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1173. {
  1174. int maxB = -1;
  1175. for (int b=0; b<heroes.size(); ++b)
  1176. {
  1177. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1178. {
  1179. maxB = b;
  1180. }
  1181. }
  1182. if(maxB < 0)
  1183. tlog2 << "Warning - cannot give bonus to hero cause there are no heroes!\n";
  1184. else
  1185. giveCampaignBonusToHero(heroes[maxB]);
  1186. }
  1187. else //specific hero
  1188. {
  1189. for (int b=0; b<heroes.size(); ++b)
  1190. {
  1191. if (heroes[b]->subID == chosenBonus->info1)
  1192. {
  1193. giveCampaignBonusToHero(heroes[b]);
  1194. break;
  1195. }
  1196. }
  1197. }
  1198. }
  1199. }
  1200. /*************************FOG**OF**WAR******************************************/
  1201. tlog4 << "\tFog of war";
  1202. for(auto k=teams.begin(); k!=teams.end(); ++k)
  1203. {
  1204. k->second.fogOfWarMap.resize(map->width);
  1205. for(int g=0; g<map->width; ++g)
  1206. k->second.fogOfWarMap[g].resize(map->height);
  1207. for(int g=-0; g<map->width; ++g)
  1208. for(int h=0; h<map->height; ++h)
  1209. k->second.fogOfWarMap[g][h].resize(map->twoLevel ? 2 : 1, 0);
  1210. for(int g=0; g<map->width; ++g)
  1211. for(int h=0; h<map->height; ++h)
  1212. for(int v = 0; v < (map->twoLevel ? 2 : 1); ++v)
  1213. k->second.fogOfWarMap[g][h][v] = 0;
  1214. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1215. {
  1216. if( !vstd::contains(k->second.players, obj->tempOwner)) continue; //not a flagged object
  1217. boost::unordered_set<int3, ShashInt3> tiles;
  1218. obj->getSightTiles(tiles);
  1219. BOOST_FOREACH(int3 tile, tiles)
  1220. {
  1221. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1222. }
  1223. }
  1224. }
  1225. tlog4 << "\tStarting bonuses";
  1226. for(auto k=players.begin(); k!=players.end(); ++k)
  1227. {
  1228. //starting bonus
  1229. if(scenarioOps->playerInfos[k->first].bonus==PlayerSettings::RANDOM)
  1230. scenarioOps->playerInfos[k->first].bonus = ran()%3;
  1231. switch(scenarioOps->playerInfos[k->first].bonus)
  1232. {
  1233. case PlayerSettings::GOLD:
  1234. k->second.resources[Res::GOLD] += 500 + (ran()%6)*100;
  1235. break;
  1236. case PlayerSettings::RESOURCE:
  1237. {
  1238. int res = VLC->townh->towns[scenarioOps->playerInfos[k->first].castle].primaryRes;
  1239. if(res == 127)
  1240. {
  1241. k->second.resources[Res::WOOD] += 5 + ran()%6;
  1242. k->second.resources[Res::ORE] += 5 + ran()%6;
  1243. }
  1244. else
  1245. {
  1246. k->second.resources[res] += 3 + ran()%4;
  1247. }
  1248. break;
  1249. }
  1250. case PlayerSettings::ARTIFACT:
  1251. {
  1252. if(!k->second.heroes.size())
  1253. {
  1254. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1255. break;
  1256. }
  1257. CArtifact *toGive;
  1258. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1259. CGHeroInstance *hero = k->second.heroes[0];
  1260. giveHeroArtifact(hero, toGive->id);
  1261. }
  1262. break;
  1263. }
  1264. }
  1265. /****************************TOWNS************************************************/
  1266. tlog4 << "\tTowns";
  1267. CGTownInstance::universitySkills.clear();
  1268. for ( int i=0; i<4; i++)
  1269. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1270. for (ui32 i=0;i<map->towns.size();i++)
  1271. {
  1272. CGTownInstance * vti =(map->towns[i]);
  1273. if(!vti->town)
  1274. vti->town = &VLC->townh->towns[vti->subID];
  1275. if (vti->name.length()==0) // if town hasn't name we draw it
  1276. vti->name = vti->town->names[ran()%vti->town->names.size()];
  1277. //init buildings
  1278. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1279. {
  1280. vti->builtBuildings.erase(-50);
  1281. vti->builtBuildings.insert(EBuilding::VILLAGE_HALL);
  1282. vti->builtBuildings.insert(EBuilding::TAVERN);
  1283. vti->builtBuildings.insert(EBuilding::DWELL_FIRST);
  1284. if(ran()%2)
  1285. vti->builtBuildings.insert(EBuilding::DWELL_FIRST+1);
  1286. }
  1287. if (vstd::contains(vti->builtBuildings, EBuilding::SHIPYARD) && vti->state()==IBoatGenerator::TILE_BLOCKED)
  1288. vti->builtBuildings.erase(EBuilding::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1289. //init hordes
  1290. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1291. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1292. {
  1293. vti->builtBuildings.erase(-31-i);//remove old ID
  1294. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1295. {
  1296. vti->builtBuildings.insert(EBuilding::HORDE_1);//add it
  1297. if (vstd::contains(vti->builtBuildings,(EBuilding::DWELL_UP_FIRST+i)))//if we have upgraded dwelling as well
  1298. vti->builtBuildings.insert(EBuilding::HORDE_1_UPGR);//add it as well
  1299. }
  1300. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1301. {
  1302. vti->builtBuildings.insert(EBuilding::HORDE_2);
  1303. if (vstd::contains(vti->builtBuildings,(EBuilding::DWELL_UP_FIRST+i)))
  1304. vti->builtBuildings.insert(EBuilding::HORDE_2_UPGR);
  1305. }
  1306. }
  1307. //town events
  1308. BOOST_FOREACH(CCastleEvent *ev, vti->events)
  1309. {
  1310. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1311. if (vstd::contains(ev->buildings,(-31-i))) //if we have horde for this level
  1312. {
  1313. ev->buildings.erase(-31-i);
  1314. if (vti->town->hordeLvl[0] == i)
  1315. ev->buildings.insert(EBuilding::HORDE_1);
  1316. if (vti->town->hordeLvl[1] == i)
  1317. ev->buildings.insert(EBuilding::HORDE_2);
  1318. }
  1319. }
  1320. //init spells
  1321. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1322. CSpell *s;
  1323. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1324. {
  1325. s = VLC->spellh->spells[vti->obligatorySpells[z]];
  1326. vti->spells[s->level-1].push_back(s->id);
  1327. vti->possibleSpells -= s->id;
  1328. }
  1329. while(vti->possibleSpells.size())
  1330. {
  1331. ui32 total=0;
  1332. int sel = -1;
  1333. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1334. total += VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1335. if (total == 0) // remaining spells have 0 probability
  1336. break;
  1337. int r = ran()%total;
  1338. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1339. {
  1340. r -= VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1341. if(r<0)
  1342. {
  1343. sel = ps;
  1344. break;
  1345. }
  1346. }
  1347. if(sel<0)
  1348. sel=0;
  1349. CSpell *s = VLC->spellh->spells[vti->possibleSpells[sel]];
  1350. vti->spells[s->level-1].push_back(s->id);
  1351. vti->possibleSpells -= s->id;
  1352. }
  1353. vti->possibleSpells.clear();
  1354. if(vti->getOwner() != 255)
  1355. getPlayer(vti->getOwner())->towns.push_back(vti);
  1356. }
  1357. //campaign bonuses for towns
  1358. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1359. {
  1360. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1361. if (chosenBonus.is_initialized() && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1362. {
  1363. for (int g=0; g<map->towns.size(); ++g)
  1364. {
  1365. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1366. if (owner)
  1367. {
  1368. PlayerInfo & pi = map->players[owner->color];
  1369. if (owner->human && //human-owned
  1370. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1371. {
  1372. map->towns[g]->builtBuildings.insert(
  1373. CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->town->typeID, map->towns[g]->builtBuildings));
  1374. break;
  1375. }
  1376. }
  1377. }
  1378. }
  1379. }
  1380. tlog4 << "\tObject initialization";
  1381. objCaller->preInit();
  1382. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1383. {
  1384. obj->initObj();
  1385. if(obj->ID == Obj::PRISON) //prison also needs to initialize hero
  1386. static_cast<CGHeroInstance*>(obj)->initHero();
  1387. }
  1388. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1389. {
  1390. switch (obj->ID)
  1391. {
  1392. case Obj::QUEST_GUARD:
  1393. case Obj::SEER_HUT:
  1394. {
  1395. auto q = static_cast<CGSeerHut*>(obj);
  1396. assert (q);
  1397. q->setObjToKill();
  1398. }
  1399. }
  1400. }
  1401. CGTeleport::postInit(); //pairing subterranean gates
  1402. buildBonusSystemTree();
  1403. for(auto k=players.begin(); k!=players.end(); ++k)
  1404. {
  1405. if(k->first==255)
  1406. continue;
  1407. //init visiting and garrisoned heroes
  1408. BOOST_FOREACH(CGHeroInstance *h, k->second.heroes)
  1409. {
  1410. BOOST_FOREACH(CGTownInstance *t, k->second.towns)
  1411. {
  1412. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1413. if(vistile == h->pos || h->pos==t->pos)
  1414. {
  1415. t->setVisitingHero(h);
  1416. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1417. {
  1418. map->removeBlockVisTiles(h);
  1419. h->pos.x -= 1;
  1420. map->addBlockVisTiles(h);
  1421. }
  1422. break;
  1423. }
  1424. }
  1425. }
  1426. }
  1427. tlog4 << "\tChecking objectives";
  1428. map->checkForObjectives(); //needs to be run when all objects are properly placed
  1429. int seedAfterInit = ran();
  1430. tlog0 << "Seed after init is " << seedAfterInit << " (before was " << scenarioOps->seedToBeUsed << ")" << std::endl;
  1431. if(scenarioOps->seedPostInit > 0)
  1432. {
  1433. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  1434. assert(scenarioOps->seedPostInit == seedAfterInit);
  1435. }
  1436. else
  1437. {
  1438. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  1439. }
  1440. }
  1441. void CGameState::initDuel()
  1442. {
  1443. DuelParameters dp;
  1444. try //CLoadFile likes throwing
  1445. {
  1446. if(boost::algorithm::ends_with(scenarioOps->mapname, ".json"))
  1447. {
  1448. tlog0 << "Loading duel settings from JSON file: " << scenarioOps->mapname << std::endl;
  1449. dp = DuelParameters::fromJSON(scenarioOps->mapname);
  1450. tlog0 << "JSON file has been successfully read!\n";
  1451. }
  1452. else
  1453. {
  1454. CLoadFile lf(scenarioOps->mapname);
  1455. lf >> dp;
  1456. }
  1457. }
  1458. catch(...)
  1459. {
  1460. tlog1 << "Cannot load duel settings from " << scenarioOps->mapname << std::endl;
  1461. throw;
  1462. }
  1463. const CArmedInstance *armies[2] = {0};
  1464. const CGHeroInstance *heroes[2] = {0};
  1465. CGTownInstance *town = NULL;
  1466. for(int i = 0; i < 2; i++)
  1467. {
  1468. CArmedInstance *obj = NULL;
  1469. if(dp.sides[i].heroId >= 0)
  1470. {
  1471. const DuelParameters::SideSettings &ss = dp.sides[i];
  1472. CGHeroInstance *h = new CGHeroInstance();
  1473. armies[i] = heroes[i] = h;
  1474. obj = h;
  1475. h->subID = ss.heroId;
  1476. for(int i = 0; i < ss.heroPrimSkills.size(); i++)
  1477. h->pushPrimSkill(i, ss.heroPrimSkills[i]);
  1478. if(ss.spells.size())
  1479. {
  1480. h->putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  1481. boost::copy(ss.spells, std::inserter(h->spells, h->spells.begin()));
  1482. }
  1483. BOOST_FOREACH(auto &parka, ss.artifacts)
  1484. {
  1485. h->putArtifact(parka.first, parka.second);
  1486. }
  1487. typedef const std::pair<si32, si8> &TSecSKill;
  1488. BOOST_FOREACH(TSecSKill secSkill, ss.heroSecSkills)
  1489. h->setSecSkillLevel((CGHeroInstance::SecondarySkill)secSkill.first, secSkill.second, 1);
  1490. h->initHero(h->subID);
  1491. obj->initObj();
  1492. }
  1493. else
  1494. {
  1495. CGCreature *c = new CGCreature();
  1496. armies[i] = obj = c;
  1497. //c->subID = 34;
  1498. }
  1499. obj->setOwner(i);
  1500. for(int j = 0; j < ARRAY_COUNT(dp.sides[i].stacks); j++)
  1501. {
  1502. TCreature cre = dp.sides[i].stacks[j].type;
  1503. TQuantity count = dp.sides[i].stacks[j].count;
  1504. if(count || obj->hasStackAtSlot(j))
  1505. obj->setCreature(j, cre, count);
  1506. }
  1507. BOOST_FOREACH(const DuelParameters::CusomCreature &cc, dp.creatures)
  1508. {
  1509. CCreature *c = VLC->creh->creatures[cc.id];
  1510. if(cc.attack >= 0)
  1511. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK))->val = cc.attack;
  1512. if(cc.defense >= 0)
  1513. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE))->val = cc.defense;
  1514. if(cc.speed >= 0)
  1515. c->getBonusLocalFirst(Selector::type(Bonus::STACKS_SPEED))->val = cc.speed;
  1516. if(cc.HP >= 0)
  1517. c->getBonusLocalFirst(Selector::type(Bonus::STACK_HEALTH))->val = cc.HP;
  1518. if(cc.dmg >= 0)
  1519. {
  1520. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1))->val = cc.dmg;
  1521. c->getBonusLocalFirst(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2))->val = cc.dmg;
  1522. }
  1523. if(cc.shoots >= 0)
  1524. c->getBonusLocalFirst(Selector::type(Bonus::SHOTS))->val = cc.shoots;
  1525. }
  1526. }
  1527. curB = BattleInfo::setupBattle(int3(), dp.bfieldType, dp.terType, armies, heroes, false, town);
  1528. curB->obstacles = dp.obstacles;
  1529. curB->localInit();
  1530. return;
  1531. }
  1532. int CGameState::battleGetBattlefieldType(int3 tile) const
  1533. {
  1534. if(tile==int3() && curB)
  1535. tile = curB->tile;
  1536. else if(tile==int3() && !curB)
  1537. return -1;
  1538. const TerrainTile &t = map->getTile(tile);
  1539. //fight in mine -> subterranean
  1540. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1541. return 12;
  1542. BOOST_FOREACH(auto &obj, map->objects)
  1543. {
  1544. //look only for objects covering given tile
  1545. if( !obj || obj->pos.z != tile.z
  1546. || !obj->coveringAt(tile.x - obj->pos.x, tile.y - obj->pos.y))
  1547. continue;
  1548. switch(obj->ID)
  1549. {
  1550. case Obj::CLOVER_FIELD:
  1551. return 19;
  1552. case Obj::CURSED_GROUND1: case Obj::CURSED_GROUND2:
  1553. return 22;
  1554. case Obj::EVIL_FOG:
  1555. return 20;
  1556. case Obj::FAVORABLE_WINDS:
  1557. return 21;
  1558. case Obj::FIERY_FIELDS:
  1559. return 14;
  1560. case Obj::HOLY_GROUNDS:
  1561. return 18;
  1562. case Obj::LUCID_POOLS:
  1563. return 17;
  1564. case Obj::MAGIC_CLOUDS:
  1565. return 16;
  1566. case Obj::MAGIC_PLAINS1: case Obj::MAGIC_PLAINS2:
  1567. return 9;
  1568. case Obj::ROCKLANDS:
  1569. return 15;
  1570. }
  1571. }
  1572. if(!t.isWater() && t.isCoastal())
  1573. return 1; //sand/beach
  1574. switch(t.terType)
  1575. {
  1576. case ETerrainType::DIRT:
  1577. return rand()%3+3;
  1578. case ETerrainType::SAND:
  1579. return 2; //TODO: coast support
  1580. case ETerrainType::GRASS:
  1581. return rand()%2+6;
  1582. case ETerrainType::SNOW:
  1583. return rand()%2+10;
  1584. case ETerrainType::SWAMP:
  1585. return 13;
  1586. case ETerrainType::ROUGH:
  1587. return 23;
  1588. case ETerrainType::SUBTERRANEAN:
  1589. return 12;
  1590. case ETerrainType::LAVA:
  1591. return 8;
  1592. case ETerrainType::WATER:
  1593. return 25;
  1594. case ETerrainType::ROCK:
  1595. return 15;
  1596. default:
  1597. return -1;
  1598. }
  1599. }
  1600. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1601. {
  1602. UpgradeInfo ret;
  1603. const CCreature *base = stack.type;
  1604. const CGHeroInstance *h = stack.armyObj->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  1605. const CGTownInstance *t = NULL;
  1606. if(stack.armyObj->ID == Obj::TOWN)
  1607. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1608. else if(h)
  1609. { //hero specialty
  1610. TBonusListPtr lista = h->getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1611. BOOST_FOREACH(const Bonus *it, *lista)
  1612. {
  1613. ui16 nid = it->additionalInfo;
  1614. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1615. {
  1616. ret.newID.push_back(nid);
  1617. ret.cost.push_back(VLC->creh->creatures[nid]->cost - base->cost);
  1618. }
  1619. }
  1620. t = h->visitedTown;
  1621. }
  1622. if(t)
  1623. {
  1624. BOOST_FOREACH(const CGTownInstance::TCreaturesSet::value_type & dwelling, t->creatures)
  1625. {
  1626. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1627. {
  1628. BOOST_FOREACH(ui32 upgrID, dwelling.second)
  1629. {
  1630. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1631. {
  1632. ret.newID.push_back(upgrID);
  1633. ret.cost.push_back(VLC->creh->creatures[upgrID]->cost - base->cost);
  1634. }
  1635. }
  1636. }
  1637. }
  1638. }
  1639. //hero is visiting Hill Fort
  1640. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  1641. {
  1642. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1643. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1644. BOOST_FOREACH(si32 nid, base->upgrades)
  1645. {
  1646. ret.newID.push_back(nid);
  1647. ret.cost.push_back((VLC->creh->creatures[nid]->cost - base->cost) * costModifier / 100);
  1648. }
  1649. }
  1650. if(ret.newID.size())
  1651. ret.oldID = base->idNumber;
  1652. return ret;
  1653. }
  1654. int CGameState::getPlayerRelations( ui8 color1, ui8 color2 )
  1655. {
  1656. if ( color1 == color2 )
  1657. return 2;
  1658. if(color1 == 255 || color2 == 255) //neutral player has no friends
  1659. return 0;
  1660. const TeamState * ts = getPlayerTeam(color1);
  1661. if (ts && vstd::contains(ts->players, color2))
  1662. return 1;
  1663. return 0;
  1664. }
  1665. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1666. {
  1667. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1668. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1669. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1670. {
  1671. const int3 hlp = tile + dirs[i];
  1672. if(!map->isInTheMap(hlp))
  1673. continue;
  1674. const TerrainTile &hlpt = map->getTile(hlp);
  1675. // //we cannot visit things from blocked tiles
  1676. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1677. // {
  1678. // continue;
  1679. // }
  1680. if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dirs[i].x && dirs[i].y) //diagonal move through water
  1681. {
  1682. int3 hlp1 = tile,
  1683. hlp2 = tile;
  1684. hlp1.x += dirs[i].x;
  1685. hlp2.y += dirs[i].y;
  1686. if(map->getTile(hlp1).terType != ETerrainType::WATER || map->getTile(hlp2).terType != ETerrainType::WATER)
  1687. continue;
  1688. }
  1689. if((indeterminate(onLand) || onLand == (hlpt.terType!=ETerrainType::WATER) )
  1690. && hlpt.terType != ETerrainType::ROCK)
  1691. {
  1692. vec.push_back(hlp);
  1693. }
  1694. }
  1695. }
  1696. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1697. {
  1698. if(src == dest) //same tile
  1699. return 0;
  1700. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1701. &d = map->terrain[dest.x][dest.y][dest.z];
  1702. //get basic cost
  1703. int ret = h->getTileCost(d,s);
  1704. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1705. {
  1706. bool freeFlying = h->getBonusesCount(Selector::typeSubtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1707. if(!freeFlying)
  1708. {
  1709. ret *= 1.4; //40% penalty for movement over blocked tile
  1710. }
  1711. }
  1712. else if (d.terType == ETerrainType::WATER)
  1713. {
  1714. if(h->boat && s.hasFavourableWinds() && d.hasFavourableWinds()) //Favourable Winds
  1715. ret *= 0.666;
  1716. else if (!h->boat && h->getBonusesCount(Selector::typeSubtype(Bonus::WATER_WALKING, 1)) > 0)
  1717. ret *= 1.4; //40% penalty for water walking
  1718. }
  1719. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1720. {
  1721. int old = ret;
  1722. ret *= 1.414213;
  1723. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1724. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1725. {
  1726. return remainingMovePoints;
  1727. }
  1728. }
  1729. int left = remainingMovePoints-ret;
  1730. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1731. {
  1732. std::vector<int3> vec;
  1733. getNeighbours(d, dest, vec, s.terType != ETerrainType::WATER, true);
  1734. for(size_t i=0; i < vec.size(); i++)
  1735. {
  1736. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1737. if(fcost <= left)
  1738. {
  1739. return ret;
  1740. }
  1741. }
  1742. ret = remainingMovePoints;
  1743. }
  1744. return ret;
  1745. }
  1746. void CGameState::apply(CPack *pack)
  1747. {
  1748. ui16 typ = typeList.getTypeID(pack);
  1749. applierGs->apps[typ]->applyOnGS(this,pack);
  1750. }
  1751. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1752. {
  1753. //the old pathfinder is not supported anymore!
  1754. assert(0);
  1755. return false;
  1756. }
  1757. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1758. {
  1759. CPathfinder pathfinder(out, this, hero);
  1760. pathfinder.calculatePaths(src, movement);
  1761. }
  1762. /**
  1763. * Tells if the tile is guarded by a monster as well as the position
  1764. * of the monster that will attack on it.
  1765. *
  1766. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1767. * the monster guarding the tile.
  1768. */
  1769. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1770. {
  1771. std::vector<CGObjectInstance*> guards;
  1772. const int3 originalPos = pos;
  1773. if (!map->isInTheMap(pos))
  1774. return guards;
  1775. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  1776. if (posTile.visitable)
  1777. {
  1778. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  1779. {
  1780. if(obj->blockVisit)
  1781. {
  1782. if (obj->ID == Obj::MONSTER) // Monster
  1783. guards.push_back(obj);
  1784. }
  1785. }
  1786. }
  1787. pos -= int3(1, 1, 0); // Start with top left.
  1788. for (int dx = 0; dx < 3; dx++)
  1789. {
  1790. for (int dy = 0; dy < 3; dy++)
  1791. {
  1792. if (map->isInTheMap(pos))
  1793. {
  1794. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  1795. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1796. {
  1797. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  1798. {
  1799. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1800. {
  1801. guards.push_back(obj);
  1802. }
  1803. }
  1804. }
  1805. }
  1806. pos.y++;
  1807. }
  1808. pos.y -= 3;
  1809. pos.x++;
  1810. }
  1811. return guards;
  1812. }
  1813. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1814. {
  1815. const int3 originalPos = pos;
  1816. // Give monster at position priority.
  1817. if (!map->isInTheMap(pos))
  1818. return int3(-1, -1, -1);
  1819. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  1820. if (posTile.visitable)
  1821. {
  1822. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  1823. {
  1824. if(obj->blockVisit)
  1825. {
  1826. if (obj->ID == Obj::MONSTER) // Monster
  1827. return pos;
  1828. else
  1829. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  1830. }
  1831. }
  1832. }
  1833. // See if there are any monsters adjacent.
  1834. pos -= int3(1, 1, 0); // Start with top left.
  1835. for (int dx = 0; dx < 3; dx++)
  1836. {
  1837. for (int dy = 0; dy < 3; dy++)
  1838. {
  1839. if (map->isInTheMap(pos))
  1840. {
  1841. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  1842. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1843. {
  1844. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  1845. {
  1846. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1847. {
  1848. return pos;
  1849. }
  1850. }
  1851. }
  1852. }
  1853. pos.y++;
  1854. }
  1855. pos.y -= 3;
  1856. pos.x++;
  1857. }
  1858. return int3(-1, -1, -1);
  1859. }
  1860. bool CGameState::isVisible(int3 pos, int player)
  1861. {
  1862. if(player == 255) //neutral player
  1863. return false;
  1864. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  1865. }
  1866. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1867. {
  1868. if(player == -1)
  1869. return true;
  1870. if(player == 255) //neutral player -> TODO ??? needed?
  1871. return false;
  1872. //object is visible when at least one blocked tile is visible
  1873. for(int fx=0; fx<8; ++fx)
  1874. {
  1875. for(int fy=0; fy<6; ++fy)
  1876. {
  1877. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1878. if(map->isInTheMap(pos)
  1879. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1880. && isVisible(pos, player) )
  1881. return true;
  1882. }
  1883. }
  1884. return false;
  1885. }
  1886. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1887. {
  1888. const TerrainTile * pom = &map->getTile(dst);
  1889. return checkForVisitableDir(src, pom, dst);
  1890. }
  1891. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  1892. {
  1893. for(ui32 b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1894. {
  1895. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1896. continue;
  1897. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1898. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1899. {
  1900. return false;
  1901. }
  1902. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1903. {
  1904. return false;
  1905. }
  1906. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1907. {
  1908. return false;
  1909. }
  1910. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1911. {
  1912. return false;
  1913. }
  1914. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1915. {
  1916. return false;
  1917. }
  1918. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1919. {
  1920. return false;
  1921. }
  1922. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1923. {
  1924. return false;
  1925. }
  1926. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1927. {
  1928. return false;
  1929. }
  1930. }
  1931. return true;
  1932. }
  1933. int CGameState::victoryCheck( ui8 player ) const
  1934. {
  1935. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  1936. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD || map->victoryCondition.allowNormalVictory
  1937. || (!p->human && !map->victoryCondition.appliesToAI)) //if the special victory condition applies only to human, AI has the standard)
  1938. {
  1939. if(player == checkForStandardWin())
  1940. return -1;
  1941. }
  1942. if (p->enteredWinningCheatCode)
  1943. { //cheater or tester, but has entered the code...
  1944. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD)
  1945. return -1;
  1946. else
  1947. return 1;
  1948. }
  1949. if(p->human || map->victoryCondition.appliesToAI)
  1950. {
  1951. switch(map->victoryCondition.condition)
  1952. {
  1953. case EVictoryConditionType::ARTIFACT:
  1954. //check if any hero has winning artifact
  1955. for(size_t i = 0; i < p->heroes.size(); i++)
  1956. if(p->heroes[i]->hasArt(map->victoryCondition.objectId))
  1957. return 1;
  1958. break;
  1959. case EVictoryConditionType::GATHERTROOP:
  1960. {
  1961. //check if in players armies there is enough creatures
  1962. int total = 0; //creature counter
  1963. for(size_t i = 0; i < map->objects.size(); i++)
  1964. {
  1965. const CArmedInstance *ai = NULL;
  1966. if(map->objects[i]
  1967. && map->objects[i]->tempOwner == player //object controlled by player
  1968. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  1969. {
  1970. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  1971. if(i->second->type->idNumber == map->victoryCondition.objectId) //it's searched creature
  1972. total += i->second->count;
  1973. }
  1974. }
  1975. if(total >= map->victoryCondition.count)
  1976. return 1;
  1977. }
  1978. break;
  1979. case EVictoryConditionType::GATHERRESOURCE:
  1980. if(p->resources[map->victoryCondition.objectId] >= map->victoryCondition.count)
  1981. return 1;
  1982. break;
  1983. case EVictoryConditionType::BUILDCITY:
  1984. {
  1985. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  1986. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.objectId && t->hallLevel()-1 >= map->victoryCondition.count)
  1987. return 1;
  1988. }
  1989. break;
  1990. case EVictoryConditionType::BUILDGRAIL:
  1991. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  1992. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  1993. && t->tempOwner == player
  1994. && t->hasBuilt(EBuilding::GRAIL))
  1995. return 1;
  1996. break;
  1997. case EVictoryConditionType::BEATHERO:
  1998. if(map->victoryCondition.obj->tempOwner >= GameConstants::PLAYER_LIMIT) //target hero not present on map
  1999. return 1;
  2000. break;
  2001. case EVictoryConditionType::CAPTURECITY:
  2002. {
  2003. if(map->victoryCondition.obj->tempOwner == player)
  2004. return 1;
  2005. }
  2006. break;
  2007. case EVictoryConditionType::BEATMONSTER:
  2008. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  2009. return 1;
  2010. break;
  2011. case EVictoryConditionType::TAKEDWELLINGS:
  2012. for(size_t i = 0; i < map->objects.size(); i++)
  2013. {
  2014. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2015. {
  2016. switch(map->objects[i]->ID)
  2017. {
  2018. case 17: case 18: case 19: case 20: //dwellings
  2019. case 216: case 217: case 218:
  2020. return 0; //found not flagged dwelling - player not won
  2021. }
  2022. }
  2023. }
  2024. return 1;
  2025. break;
  2026. case EVictoryConditionType::TAKEMINES:
  2027. for(size_t i = 0; i < map->objects.size(); i++)
  2028. {
  2029. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2030. {
  2031. switch(map->objects[i]->ID)
  2032. {
  2033. case 53: case 220:
  2034. return 0; //found not flagged mine - player not won
  2035. }
  2036. }
  2037. }
  2038. return 1;
  2039. break;
  2040. case EVictoryConditionType::TRANSPORTITEM:
  2041. {
  2042. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2043. if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.objectId))
  2044. || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.objectId)))
  2045. {
  2046. return 1;
  2047. }
  2048. }
  2049. break;
  2050. }
  2051. }
  2052. return 0;
  2053. }
  2054. ui8 CGameState::checkForStandardWin() const
  2055. {
  2056. //std victory condition is:
  2057. //all enemies lost
  2058. TPlayerColor supposedWinner = 255, winnerTeam = 255;
  2059. for(auto i = players.begin(); i != players.end(); i++)
  2060. {
  2061. if(i->second.status == PlayerState::INGAME && i->first < GameConstants::PLAYER_LIMIT)
  2062. {
  2063. if(supposedWinner == 255)
  2064. {
  2065. //first player remaining ingame - candidate for victory
  2066. supposedWinner = i->second.color;
  2067. winnerTeam = i->second.team;
  2068. }
  2069. else if(winnerTeam != i->second.team)
  2070. {
  2071. //current candidate has enemy remaining in game -> no vicotry
  2072. return 255;
  2073. }
  2074. }
  2075. }
  2076. return supposedWinner;
  2077. }
  2078. bool CGameState::checkForStandardLoss( ui8 player ) const
  2079. {
  2080. //std loss condition is: player lost all towns and heroes
  2081. const PlayerState &p = *CGameInfoCallback::getPlayer(player);
  2082. return !p.heroes.size() && !p.towns.size();
  2083. }
  2084. struct statsHLP
  2085. {
  2086. typedef std::pair< TPlayerColor, si64 > TStat;
  2087. //converts [<player's color, value>] to vec[place] -> platers
  2088. static std::vector< std::vector< TPlayerColor > > getRank( std::vector<TStat> stats )
  2089. {
  2090. std::sort(stats.begin(), stats.end(), statsHLP());
  2091. //put first element
  2092. std::vector< std::vector<TPlayerColor> > ret;
  2093. std::vector<TPlayerColor> tmp;
  2094. tmp.push_back( stats[0].first );
  2095. ret.push_back( tmp );
  2096. //the rest of elements
  2097. for(int g=1; g<stats.size(); ++g)
  2098. {
  2099. if(stats[g].second == stats[g-1].second)
  2100. {
  2101. (ret.end()-1)->push_back( stats[g].first );
  2102. }
  2103. else
  2104. {
  2105. //create next occupied rank
  2106. std::vector<TPlayerColor> tmp;
  2107. tmp.push_back(stats[g].first);
  2108. ret.push_back(tmp);
  2109. }
  2110. }
  2111. return ret;
  2112. }
  2113. bool operator()(const TStat & a, const TStat & b) const
  2114. {
  2115. return a.second > b.second;
  2116. }
  2117. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2118. {
  2119. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2120. if(!h.size())
  2121. return NULL;
  2122. //best hero will be that with highest exp
  2123. int best = 0;
  2124. for(int b=1; b<h.size(); ++b)
  2125. {
  2126. if(h[b]->exp > h[best]->exp)
  2127. {
  2128. best = b;
  2129. }
  2130. }
  2131. return h[best];
  2132. }
  2133. //calculates total number of artifacts that belong to given player
  2134. static int getNumberOfArts(const PlayerState * ps)
  2135. {
  2136. int ret = 0;
  2137. BOOST_FOREACH(auto h, ps->heroes)
  2138. {
  2139. ret += h->artifactsInBackpack.size() + h->artifactsWorn.size();
  2140. }
  2141. return ret;
  2142. }
  2143. // get total strength of player army
  2144. static si64 getArmyStrength(const PlayerState * ps)
  2145. {
  2146. si64 str = 0;
  2147. BOOST_FOREACH(auto h, ps->heroes)
  2148. {
  2149. if(!h->inTownGarrison) //original h3 behavior
  2150. str += h->getArmyStrength();
  2151. }
  2152. return str;
  2153. }
  2154. };
  2155. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2156. {
  2157. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2158. { \
  2159. std::vector< std::pair< TPlayerColor, si64 > > stats; \
  2160. for(auto g = players.begin(); g != players.end(); ++g) \
  2161. { \
  2162. if(g->second.color == 255) \
  2163. continue; \
  2164. std::pair< ui8, si64 > stat; \
  2165. stat.first = g->second.color; \
  2166. stat.second = VAL_GETTER; \
  2167. stats.push_back(stat); \
  2168. } \
  2169. tgi.FIELD = statsHLP::getRank(stats); \
  2170. }
  2171. for(auto g = players.begin(); g != players.end(); ++g)
  2172. {
  2173. if(g->second.color != 255)
  2174. tgi.playerColors.push_back(g->second.color);
  2175. }
  2176. if(level >= 1) //num of towns & num of heroes
  2177. {
  2178. //num of towns
  2179. FILL_FIELD(numOfTowns, g->second.towns.size())
  2180. //num of heroes
  2181. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2182. //best hero's portrait
  2183. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2184. {
  2185. if(g->second.color == 255)
  2186. continue;
  2187. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2188. InfoAboutHero iah;
  2189. iah.initFromHero(best, level >= 8);
  2190. iah.army.clear();
  2191. tgi.colorToBestHero[g->second.color] = iah;
  2192. }
  2193. }
  2194. if(level >= 2) //gold
  2195. {
  2196. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2197. }
  2198. if(level >= 2) //wood & ore
  2199. {
  2200. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2201. }
  2202. if(level >= 3) //mercury, sulfur, crystal, gems
  2203. {
  2204. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2205. }
  2206. if(level >= 4) //obelisks found
  2207. {
  2208. //TODO: obtainPlayersStats - obelisks found
  2209. }
  2210. if(level >= 5) //artifacts
  2211. {
  2212. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2213. }
  2214. if(level >= 6) //army strength
  2215. {
  2216. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  2217. }
  2218. if(level >= 7) //income
  2219. {
  2220. //TODO:obtainPlayersStats - income
  2221. }
  2222. if(level >= 8) //best hero's stats
  2223. {
  2224. //already set in lvl 1 handling
  2225. }
  2226. if(level >= 9) //personality
  2227. {
  2228. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2229. {
  2230. if(g->second.color == 255) //do nothing for neutral player
  2231. continue;
  2232. if(g->second.human)
  2233. {
  2234. tgi.personality[g->second.color] = EAiTactic::NONE;
  2235. }
  2236. else //AI
  2237. {
  2238. tgi.personality[g->second.color] = map->players[g->second.color].aiTactic;
  2239. }
  2240. }
  2241. }
  2242. if(level >= 10) //best creature
  2243. {
  2244. //best creatures belonging to player (highest AI value)
  2245. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2246. {
  2247. if(g->second.color == 255) //do nothing for neutral player
  2248. continue;
  2249. int bestCre = -1; //best creature's ID
  2250. for(int b=0; b<g->second.heroes.size(); ++b)
  2251. {
  2252. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  2253. {
  2254. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2255. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2256. {
  2257. bestCre = toCmp;
  2258. }
  2259. }
  2260. }
  2261. tgi.bestCreature[g->second.color] = bestCre;
  2262. }
  2263. }
  2264. #undef FILL_FIELD
  2265. }
  2266. int CGameState::lossCheck( ui8 player ) const
  2267. {
  2268. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  2269. //if(map->lossCondition.typeOfLossCon == lossStandard)
  2270. if(checkForStandardLoss(player))
  2271. return -1;
  2272. if (p->enteredLosingCheatCode)
  2273. {
  2274. return 1;
  2275. }
  2276. if(p->human) //special loss condition applies only to human player
  2277. {
  2278. switch(map->lossCondition.typeOfLossCon)
  2279. {
  2280. case ELossConditionType::LOSSCASTLE:
  2281. case ELossConditionType::LOSSHERO:
  2282. {
  2283. const CGObjectInstance *obj = map->lossCondition.obj;
  2284. assert(obj);
  2285. if(obj->tempOwner != player)
  2286. return 1;
  2287. }
  2288. break;
  2289. case ELossConditionType::TIMEEXPIRES:
  2290. if(map->lossCondition.timeLimit < day)
  2291. return 1;
  2292. break;
  2293. }
  2294. }
  2295. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  2296. return 2;
  2297. return false;
  2298. }
  2299. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2300. {
  2301. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2302. for ( auto i = players.cbegin() ; i != players.cend();i++)
  2303. for(auto j = i->second.availableHeroes.cbegin(); j != i->second.availableHeroes.cend(); j++)
  2304. if(*j)
  2305. pool.erase((**j).subID);
  2306. return pool;
  2307. }
  2308. void CGameState::buildBonusSystemTree()
  2309. {
  2310. buildGlobalTeamPlayerTree();
  2311. attachArmedObjects();
  2312. BOOST_FOREACH(CGTownInstance *t, map->towns)
  2313. {
  2314. t->deserializationFix();
  2315. }
  2316. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2317. // are provided on initializing / deserializing
  2318. }
  2319. void CGameState::deserializationFix()
  2320. {
  2321. buildGlobalTeamPlayerTree();
  2322. attachArmedObjects();
  2323. }
  2324. void CGameState::buildGlobalTeamPlayerTree()
  2325. {
  2326. for(auto k=teams.begin(); k!=teams.end(); ++k)
  2327. {
  2328. TeamState *t = &k->second;
  2329. t->attachTo(&globalEffects);
  2330. BOOST_FOREACH(ui8 teamMember, k->second.players)
  2331. {
  2332. PlayerState *p = getPlayer(teamMember);
  2333. assert(p);
  2334. p->attachTo(t);
  2335. }
  2336. }
  2337. }
  2338. void CGameState::attachArmedObjects()
  2339. {
  2340. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  2341. {
  2342. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2343. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2344. }
  2345. }
  2346. void CGameState::giveHeroArtifact(CGHeroInstance *h, int aid)
  2347. {
  2348. CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  2349. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2350. map->addNewArtifactInstance(ai);
  2351. ai->putAt(ArtifactLocation(h, ai->firstAvailableSlot(h)));
  2352. }
  2353. int3 CPath::startPos() const
  2354. {
  2355. return nodes[nodes.size()-1].coord;
  2356. }
  2357. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2358. {
  2359. if (mode==0)
  2360. {
  2361. for (ui32 i=0;i<nodes.size();i++)
  2362. {
  2363. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2364. }
  2365. }
  2366. }
  2367. int3 CPath::endPos() const
  2368. {
  2369. return nodes[0].coord;
  2370. }
  2371. CGPathNode::CGPathNode()
  2372. :coord(-1,-1,-1)
  2373. {
  2374. accessible = 0;
  2375. land = 0;
  2376. moveRemains = 0;
  2377. turns = 255;
  2378. theNodeBefore = NULL;
  2379. }
  2380. bool CGPathNode::reachable() const
  2381. {
  2382. return turns < 255;
  2383. }
  2384. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2385. {
  2386. assert(isValid);
  2387. out.nodes.clear();
  2388. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2389. if(!curnode->theNodeBefore)
  2390. return false;
  2391. while(curnode)
  2392. {
  2393. CGPathNode cpn = *curnode;
  2394. curnode = curnode->theNodeBefore;
  2395. out.nodes.push_back(cpn);
  2396. }
  2397. return true;
  2398. }
  2399. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2400. :sizes(Sizes)
  2401. {
  2402. hero = NULL;
  2403. nodes = new CGPathNode**[sizes.x];
  2404. for(int i = 0; i < sizes.x; i++)
  2405. {
  2406. nodes[i] = new CGPathNode*[sizes.y];
  2407. for (int j = 0; j < sizes.y; j++)
  2408. {
  2409. nodes[i][j] = new CGPathNode[sizes.z];
  2410. }
  2411. }
  2412. }
  2413. CPathsInfo::~CPathsInfo()
  2414. {
  2415. for(int i = 0; i < sizes.x; i++)
  2416. {
  2417. for (int j = 0; j < sizes.y; j++)
  2418. {
  2419. delete [] nodes[i][j];
  2420. }
  2421. delete [] nodes[i];
  2422. }
  2423. delete [] nodes;
  2424. }
  2425. int3 CGPath::startPos() const
  2426. {
  2427. return nodes[nodes.size()-1].coord;
  2428. }
  2429. int3 CGPath::endPos() const
  2430. {
  2431. return nodes[0].coord;
  2432. }
  2433. void CGPath::convert( ui8 mode )
  2434. {
  2435. if(mode==0)
  2436. {
  2437. for(ui32 i=0;i<nodes.size();i++)
  2438. {
  2439. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2440. }
  2441. }
  2442. }
  2443. PlayerState::PlayerState()
  2444. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  2445. enteredLosingCheatCode(0), status(INGAME), daysWithoutCastle(0)
  2446. {
  2447. setNodeType(PLAYER);
  2448. }
  2449. std::string PlayerState::nodeName() const
  2450. {
  2451. return "Player " + (color < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color] : boost::lexical_cast<std::string>(color));
  2452. }
  2453. // void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  2454. // {
  2455. // return; //no loops possible
  2456. // }
  2457. //
  2458. // void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  2459. // {
  2460. // for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); it++)
  2461. // {
  2462. // if (*it != root)
  2463. // (*it)->getBonuses(out, selector, this);
  2464. // }
  2465. // }
  2466. InfoAboutArmy::InfoAboutArmy():
  2467. owner(GameConstants::NEUTRAL_PLAYER)
  2468. {}
  2469. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2470. {
  2471. initFromArmy(Army, detailed);
  2472. }
  2473. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2474. {
  2475. army = ArmyDescriptor(Army, detailed);
  2476. owner = Army->tempOwner;
  2477. name = Army->getHoverText();
  2478. }
  2479. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2480. {
  2481. InfoAboutArmy::operator = (iah);
  2482. details = (iah.details ? new Details(*iah.details) : NULL);
  2483. hclass = iah.hclass;
  2484. portrait = iah.portrait;
  2485. }
  2486. InfoAboutHero::InfoAboutHero():
  2487. details(nullptr),
  2488. hclass(nullptr),
  2489. portrait(-1)
  2490. {}
  2491. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah):
  2492. InfoAboutArmy()
  2493. {
  2494. assign(iah);
  2495. }
  2496. InfoAboutHero::InfoAboutHero(const CGHeroInstance *h, bool detailed)
  2497. : details(nullptr),
  2498. hclass(nullptr),
  2499. portrait(-1)
  2500. {
  2501. initFromHero(h, detailed);
  2502. }
  2503. InfoAboutHero::~InfoAboutHero()
  2504. {
  2505. delete details;
  2506. }
  2507. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2508. {
  2509. assign(iah);
  2510. return *this;
  2511. }
  2512. void InfoAboutHero::initFromHero(const CGHeroInstance *h, bool detailed)
  2513. {
  2514. if(!h)
  2515. return;
  2516. initFromArmy(h, detailed);
  2517. hclass = h->type->heroClass;
  2518. name = h->name;
  2519. portrait = h->portrait;
  2520. if(detailed)
  2521. {
  2522. //include details about hero
  2523. details = new Details;
  2524. details->luck = h->LuckVal();
  2525. details->morale = h->MoraleVal();
  2526. details->mana = h->mana;
  2527. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2528. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2529. {
  2530. details->primskills[i] = h->getPrimSkillLevel(i);
  2531. }
  2532. }
  2533. }
  2534. InfoAboutTown::InfoAboutTown():
  2535. details(nullptr),
  2536. tType(nullptr),
  2537. built(0),
  2538. fortLevel(0)
  2539. {
  2540. }
  2541. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed)
  2542. {
  2543. initFromTown(t, detailed);
  2544. }
  2545. InfoAboutTown::~InfoAboutTown()
  2546. {
  2547. delete details;
  2548. }
  2549. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2550. {
  2551. initFromArmy(t, detailed);
  2552. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2553. built = t->builded;
  2554. fortLevel = t->fortLevel();
  2555. name = t->name;
  2556. tType = t->town;
  2557. if(detailed)
  2558. {
  2559. //include details about hero
  2560. details = new Details;
  2561. details->goldIncome = t->dailyIncome();
  2562. details->customRes = t->hasBuilt(EBuilding::RESOURCE_SILO);
  2563. details->hallLevel = t->hallLevel();
  2564. details->garrisonedHero = t->garrisonHero;
  2565. }
  2566. }
  2567. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2568. : isDetailed(detailed)
  2569. {
  2570. for(TSlots::const_iterator i = army->Slots().begin(); i != army->Slots().end(); i++)
  2571. {
  2572. if(detailed)
  2573. (*this)[i->first] = *i->second;
  2574. else
  2575. (*this)[i->first] = CStackBasicDescriptor(i->second->type, i->second->getQuantityID());
  2576. }
  2577. }
  2578. ArmyDescriptor::ArmyDescriptor()
  2579. : isDetailed(false)
  2580. {
  2581. }
  2582. int ArmyDescriptor::getStrength() const
  2583. {
  2584. ui64 ret = 0;
  2585. if(isDetailed)
  2586. {
  2587. for(const_iterator i = begin(); i != end(); i++)
  2588. ret += i->second.type->AIValue * i->second.count;
  2589. }
  2590. else
  2591. {
  2592. for(const_iterator i = begin(); i != end(); i++)
  2593. ret += i->second.type->AIValue * CCreature::estimateCreatureCount(i->second.count);
  2594. }
  2595. return ret;
  2596. }
  2597. DuelParameters::SideSettings::StackSettings::StackSettings()
  2598. : type(-1), count(0)
  2599. {
  2600. }
  2601. DuelParameters::SideSettings::StackSettings::StackSettings(si32 Type, si32 Count)
  2602. : type(Type), count(Count)
  2603. {
  2604. }
  2605. DuelParameters::SideSettings::SideSettings()
  2606. {
  2607. heroId = -1;
  2608. }
  2609. DuelParameters::DuelParameters()
  2610. {
  2611. terType = ETerrainType::DIRT;
  2612. bfieldType = 15;
  2613. }
  2614. DuelParameters DuelParameters::fromJSON(const std::string &fname)
  2615. {
  2616. DuelParameters ret;
  2617. const JsonNode duelData(ResourceID("DATA/" + fname, EResType::TEXT));
  2618. ret.terType = duelData["terType"].Float();
  2619. ret.bfieldType = duelData["bfieldType"].Float();
  2620. BOOST_FOREACH(const JsonNode &n, duelData["sides"].Vector())
  2621. {
  2622. SideSettings &ss = ret.sides[(int)n["side"].Float()];
  2623. int i = 0;
  2624. BOOST_FOREACH(const JsonNode &stackNode, n["army"].Vector())
  2625. {
  2626. ss.stacks[i].type = stackNode.Vector()[0].Float();
  2627. ss.stacks[i].count = stackNode.Vector()[1].Float();
  2628. i++;
  2629. }
  2630. if(n["heroid"].getType() == JsonNode::DATA_FLOAT)
  2631. ss.heroId = n["heroid"].Float();
  2632. else
  2633. ss.heroId = -1;
  2634. BOOST_FOREACH(const JsonNode &n, n["heroPrimSkills"].Vector())
  2635. ss.heroPrimSkills.push_back(n.Float());
  2636. BOOST_FOREACH(const JsonNode &skillNode, n["heroSecSkills"].Vector())
  2637. {
  2638. std::pair<si32, si8> secSkill;
  2639. secSkill.first = skillNode.Vector()[0].Float();
  2640. secSkill.second = skillNode.Vector()[1].Float();
  2641. ss.heroSecSkills.push_back(secSkill);
  2642. }
  2643. assert(ss.heroPrimSkills.empty() || ss.heroPrimSkills.size() == GameConstants::PRIMARY_SKILLS);
  2644. if(ss.heroId != -1)
  2645. {
  2646. const JsonNode & spells = n["spells"];
  2647. if(spells.getType() == JsonNode::DATA_STRING && spells.String() == "all")
  2648. {
  2649. BOOST_FOREACH(auto spell, VLC->spellh->spells)
  2650. if(spell->id <= Spells::SUMMON_AIR_ELEMENTAL)
  2651. ss.spells.insert(spell->id);
  2652. }
  2653. else
  2654. BOOST_FOREACH(const JsonNode &spell, n["spells"].Vector())
  2655. ss.spells.insert(spell.Float());
  2656. }
  2657. }
  2658. BOOST_FOREACH(const JsonNode &n, duelData["obstacles"].Vector())
  2659. {
  2660. auto oi = make_shared<CObstacleInstance>();
  2661. if(n.getType() == JsonNode::DATA_VECTOR)
  2662. {
  2663. oi->ID = n.Vector()[0].Float();
  2664. oi->pos = n.Vector()[1].Float();
  2665. }
  2666. else
  2667. {
  2668. assert(n.getType() == JsonNode::DATA_FLOAT);
  2669. oi->ID = 21;
  2670. oi->pos = n.Float();
  2671. }
  2672. oi->uniqueID = ret.obstacles.size();
  2673. ret.obstacles.push_back(oi);
  2674. }
  2675. BOOST_FOREACH(const JsonNode &n, duelData["creatures"].Vector())
  2676. {
  2677. CusomCreature cc;
  2678. cc.id = n["id"].Float();
  2679. #define retreive(name) \
  2680. if(n[ #name ].getType() == JsonNode::DATA_FLOAT)\
  2681. cc.name = n[ #name ].Float(); \
  2682. else \
  2683. cc.name = -1;
  2684. retreive(attack);
  2685. retreive(defense);
  2686. retreive(HP);
  2687. retreive(dmg);
  2688. retreive(shoots);
  2689. retreive(speed);
  2690. ret.creatures.push_back(cc);
  2691. }
  2692. return ret;
  2693. }
  2694. TeamState::TeamState()
  2695. {
  2696. setNodeType(TEAM);
  2697. }
  2698. void CPathfinder::initializeGraph()
  2699. {
  2700. CGPathNode ***graph = out.nodes;
  2701. for(size_t i=0; i < out.sizes.x; ++i)
  2702. {
  2703. for(size_t j=0; j < out.sizes.y; ++j)
  2704. {
  2705. for(size_t k=0; k < out.sizes.z; ++k)
  2706. {
  2707. curPos = int3(i,j,k);
  2708. const TerrainTile *tinfo = &gs->map->terrain[i][j][k];
  2709. CGPathNode &node = graph[i][j][k];
  2710. node.accessible = evaluateAccessibility(tinfo);
  2711. node.turns = 0xff;
  2712. node.moveRemains = 0;
  2713. node.coord.x = i;
  2714. node.coord.y = j;
  2715. node.coord.z = k;
  2716. node.land = tinfo->terType != ETerrainType::WATER;
  2717. node.theNodeBefore = NULL;
  2718. }
  2719. }
  2720. }
  2721. }
  2722. void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*= -1*/)
  2723. {
  2724. assert(hero);
  2725. assert(hero == getHero(hero->id));
  2726. if(src.x < 0)
  2727. src = hero->getPosition(false);
  2728. if(movement < 0)
  2729. movement = hero->movement;
  2730. out.hero = hero;
  2731. out.hpos = src;
  2732. if(!gs->map->isInTheMap(src)/* || !gs->map->isInTheMap(dest)*/) //check input
  2733. {
  2734. tlog1 << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...\n";
  2735. return;
  2736. }
  2737. initializeGraph();
  2738. //initial tile - set cost on 0 and add to the queue
  2739. CGPathNode &initialNode = *getNode(src);
  2740. initialNode.turns = 0;
  2741. initialNode.moveRemains = movement;
  2742. mq.push_back(&initialNode);
  2743. std::vector<int3> neighbours;
  2744. neighbours.reserve(16);
  2745. while(!mq.empty())
  2746. {
  2747. cp = mq.front();
  2748. mq.pop_front();
  2749. const int3 sourceGuardPosition = guardingCreaturePosition(cp->coord);
  2750. bool guardedSource = (sourceGuardPosition != int3(-1, -1, -1) && cp->coord != src);
  2751. ct = &gs->map->getTile(cp->coord);
  2752. int movement = cp->moveRemains, turn = cp->turns;
  2753. if(!movement)
  2754. {
  2755. movement = hero->maxMovePoints(cp->land);
  2756. turn++;
  2757. }
  2758. //add accessible neighbouring nodes to the queue
  2759. neighbours.clear();
  2760. //handling subterranean gate => it's exit is the only neighbour
  2761. bool subterraneanEntry = (ct->topVisitableId() == Obj::SUBTERRANEAN_GATE && useSubterraneanGates);
  2762. if(subterraneanEntry)
  2763. {
  2764. //try finding the exit gate
  2765. if(const CGObjectInstance *outGate = getObj(CGTeleport::getMatchingGate(ct->visitableObjects.back()->id), false))
  2766. {
  2767. const int3 outPos = outGate->visitablePos();
  2768. //gs->getNeighbours(*getTile(outPos), outPos, neighbours, boost::logic::indeterminate, !cp->land);
  2769. neighbours.push_back(outPos);
  2770. }
  2771. else
  2772. {
  2773. //gate with no exit (blocked) -> do nothing with this node
  2774. continue;
  2775. }
  2776. }
  2777. gs->getNeighbours(*ct, cp->coord, neighbours, boost::logic::indeterminate, !cp->land);
  2778. for(ui32 i=0; i < neighbours.size(); i++)
  2779. {
  2780. const int3 &n = neighbours[i]; //current neighbor
  2781. dp = getNode(n);
  2782. dt = &gs->map->getTile(n);
  2783. destTopVisObjID = dt->topVisitableId();
  2784. useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
  2785. int turnAtNextTile = turn;
  2786. const bool destIsGuardian = sourceGuardPosition == n;
  2787. if(!goodForLandSeaTransition())
  2788. continue;
  2789. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED )
  2790. continue;
  2791. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  2792. if(cp->accessible == CGPathNode::VISITABLE && guardedSource && cp->theNodeBefore->land && ct->topVisitableId() == Obj::BOAT)
  2793. guardedSource = false;
  2794. int cost = gs->getMovementCost(hero, cp->coord, dp->coord, movement);
  2795. //special case -> moving from src Subterranean gate to dest gate -> it's free
  2796. if(subterraneanEntry && destTopVisObjID == Obj::SUBTERRANEAN_GATE && cp->coord.z != dp->coord.z)
  2797. cost = 0;
  2798. int remains = movement - cost;
  2799. if(useEmbarkCost)
  2800. {
  2801. remains = hero->movementPointsAfterEmbark(movement, cost, useEmbarkCost - 1);
  2802. cost = movement - remains;
  2803. }
  2804. if(remains < 0)
  2805. {
  2806. //occurs rarely, when hero with low movepoints tries to leave the road
  2807. turnAtNextTile++;
  2808. int moveAtNextTile = hero->maxMovePoints(cp->land);
  2809. cost = gs->getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2810. remains = moveAtNextTile - cost;
  2811. }
  2812. if((dp->turns==0xff //we haven't been here before
  2813. || dp->turns > turnAtNextTile
  2814. || (dp->turns >= turnAtNextTile && dp->moveRemains < remains)) //this route is faster
  2815. && (!guardedSource || destIsGuardian)) // Can step into tile of guard
  2816. {
  2817. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  2818. dp->moveRemains = remains;
  2819. dp->turns = turnAtNextTile;
  2820. dp->theNodeBefore = cp;
  2821. const bool guardedDst = guardingCreaturePosition(dp->coord) != int3(-1, -1, -1)
  2822. && dp->accessible == CGPathNode::BLOCKVIS;
  2823. if (dp->accessible == CGPathNode::ACCESSIBLE
  2824. || (useEmbarkCost && allowEmbarkAndDisembark)
  2825. || destTopVisObjID == Obj::SUBTERRANEAN_GATE
  2826. || (guardedDst && !guardedSource)) // Can step into a hostile tile once.
  2827. {
  2828. mq.push_back(dp);
  2829. }
  2830. }
  2831. } //neighbours loop
  2832. } //queue loop
  2833. out.isValid = true;
  2834. }
  2835. CGPathNode *CPathfinder::getNode(const int3 &coord)
  2836. {
  2837. return &out.nodes[coord.x][coord.y][coord.z];
  2838. }
  2839. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  2840. {
  2841. return gs->checkForVisitableDir(a, b) && gs->checkForVisitableDir(b, a);
  2842. }
  2843. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const TerrainTile *tinfo) const
  2844. {
  2845. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  2846. if(tinfo->terType == ETerrainType::ROCK || !FoW[curPos.x][curPos.y][curPos.z])
  2847. return CGPathNode::BLOCKED;
  2848. if(tinfo->visitable)
  2849. {
  2850. 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
  2851. {
  2852. return CGPathNode::BLOCKED;
  2853. }
  2854. else
  2855. {
  2856. BOOST_FOREACH(const CGObjectInstance *obj, tinfo->visitableObjects)
  2857. {
  2858. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  2859. {
  2860. ret = CGPathNode::ACCESSIBLE;
  2861. }
  2862. else if(obj->blockVisit)
  2863. {
  2864. return CGPathNode::BLOCKVIS;
  2865. }
  2866. else if(obj->ID != Obj::EVENT) //pathfinder should ignore placed events
  2867. {
  2868. ret = CGPathNode::VISITABLE;
  2869. }
  2870. }
  2871. }
  2872. }
  2873. else if (gs->map->isInTheMap(guardingCreaturePosition(curPos))
  2874. && !tinfo->blocked)
  2875. {
  2876. // Monster close by; blocked visit for battle.
  2877. return CGPathNode::BLOCKVIS;
  2878. }
  2879. return ret;
  2880. }
  2881. bool CPathfinder::goodForLandSeaTransition()
  2882. {
  2883. if(cp->land != dp->land) //hero can traverse land<->sea only in special circumstances
  2884. {
  2885. if(cp->land) //from land to sea -> embark or assault hero on boat
  2886. {
  2887. if(dp->accessible == CGPathNode::ACCESSIBLE || destTopVisObjID < 0) //cannot enter empty water tile from land -> it has to be visitable
  2888. return false;
  2889. if(destTopVisObjID != Obj::HERO && destTopVisObjID != Obj::BOAT) //only boat or hero can be accessed from land
  2890. return false;
  2891. if(destTopVisObjID == Obj::BOAT)
  2892. useEmbarkCost = 1;
  2893. }
  2894. else //disembark
  2895. {
  2896. //can disembark only on coastal tiles
  2897. if(!dt->isCoastal())
  2898. return false;
  2899. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  2900. if( (dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  2901. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  2902. return false;;
  2903. useEmbarkCost = 2;
  2904. }
  2905. }
  2906. return true;
  2907. }
  2908. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero) : CGameInfoCallback(_gs, -1), out(_out), hero(_hero), FoW(getPlayerTeam(hero->tempOwner)->fogOfWarMap)
  2909. {
  2910. useSubterraneanGates = true;
  2911. allowEmbarkAndDisembark = true;
  2912. }