CGameState.cpp 92 KB

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