CGameState.cpp 89 KB

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