CGameState.cpp 93 KB

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