2
0

CGameState.cpp 92 KB

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