CGameState.cpp 82 KB

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