CGameState.cpp 85 KB

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