CGameState.cpp 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729
  1. #define VCMI_DLL
  2. #include <algorithm>
  3. #include <queue>
  4. #include <fstream>
  5. #include "CGameState.h"
  6. #include <boost/random/linear_congruential.hpp>
  7. #include "../hch/CDefObjInfoHandler.h"
  8. #include "../hch/CArtHandler.h"
  9. #include "../hch/CBuildingHandler.h"
  10. #include "../hch/CGeneralTextHandler.h"
  11. #include "../hch/CTownHandler.h"
  12. #include "../hch/CSpellHandler.h"
  13. #include "../hch/CHeroHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CCreatureHandler.h"
  16. #include "VCMI_Lib.h"
  17. #include "Connection.h"
  18. #include "map.h"
  19. #include "../StartInfo.h"
  20. #include "NetPacks.h"
  21. #include <boost/foreach.hpp>
  22. #include <boost/lexical_cast.hpp>
  23. #include <boost/thread.hpp>
  24. #include <boost/thread/shared_mutex.hpp>
  25. #include "RegisterTypes.cpp"
  26. boost::rand48 ran;
  27. #ifdef min
  28. #undef min
  29. #endif
  30. #ifdef max
  31. #undef max
  32. #endif
  33. /*
  34. * CGameState.cpp, part of VCMI engine
  35. *
  36. * Authors: listed in file AUTHORS in main folder
  37. *
  38. * License: GNU General Public License v2.0 or later
  39. * Full text of license available in license.txt file, in main folder
  40. *
  41. */
  42. void foofoofoo()
  43. {
  44. //never called function to force instantation of templates
  45. int *ccc = NULL;
  46. registerTypes((CISer<CConnection>&)*ccc);
  47. registerTypes((COSer<CConnection>&)*ccc);
  48. registerTypes((CSaveFile&)*ccc);
  49. registerTypes((CLoadFile&)*ccc);
  50. registerTypes((CTypeList&)*ccc);
  51. }
  52. class CBaseForGSApply
  53. {
  54. public:
  55. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  56. };
  57. template <typename T> class CApplyOnGS : public CBaseForGSApply
  58. {
  59. public:
  60. void applyOnGS(CGameState *gs, void *pack) const
  61. {
  62. T *ptr = static_cast<T*>(pack);
  63. while(!gs->mx->try_lock())
  64. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  65. ptr->applyGs(gs);
  66. gs->mx->unlock();
  67. }
  68. };
  69. class CGSApplier
  70. {
  71. public:
  72. std::map<ui16,CBaseForGSApply*> apps;
  73. CGSApplier()
  74. {
  75. registerTypes2(*this);
  76. }
  77. template<typename T> void registerType(const T * t=NULL)
  78. {
  79. ui16 ID = typeList.registerType(t);
  80. apps[ID] = new CApplyOnGS<T>;
  81. }
  82. } *applierGs = NULL;
  83. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  84. {
  85. int type = txt.first, ser = txt.second;
  86. if(type == ART_NAMES)
  87. {
  88. dst = VLC->arth->artifacts[ser].Name();
  89. }
  90. else if(type == CRE_PL_NAMES)
  91. {
  92. dst = VLC->creh->creatures[ser].namePl;
  93. }
  94. else if(type == MINE_NAMES)
  95. {
  96. dst = VLC->generaltexth->mines[ser].first;
  97. }
  98. else if(type == MINE_EVNTS)
  99. {
  100. dst = VLC->generaltexth->mines[ser].second;
  101. }
  102. else if(type == SPELL_NAME)
  103. {
  104. dst = VLC->spellh->spells[ser].name;
  105. }
  106. else if(type == CRE_SING_NAMES)
  107. {
  108. dst = VLC->creh->creatures[ser].nameSing;
  109. }
  110. else
  111. {
  112. std::vector<std::string> *vec;
  113. switch(type)
  114. {
  115. case GENERAL_TXT:
  116. vec = &VLC->generaltexth->allTexts;
  117. break;
  118. case XTRAINFO_TXT:
  119. vec = &VLC->generaltexth->xtrainfo;
  120. break;
  121. case OBJ_NAMES:
  122. vec = &VLC->generaltexth->names;
  123. break;
  124. case RES_NAMES:
  125. vec = &VLC->generaltexth->restypes;
  126. break;
  127. case ARRAY_TXT:
  128. vec = &VLC->generaltexth->arraytxt;
  129. break;
  130. case CREGENS:
  131. vec = &VLC->generaltexth->creGens;
  132. break;
  133. case CREGENS4:
  134. vec = &VLC->generaltexth->creGens4;
  135. break;
  136. case ADVOB_TXT:
  137. vec = &VLC->generaltexth->advobtxt;
  138. break;
  139. case ART_EVNTS:
  140. vec = &VLC->generaltexth->artifEvents;
  141. break;
  142. case SEC_SKILL_NAME:
  143. vec = &VLC->generaltexth->skillName;
  144. break;
  145. }
  146. dst = (*vec)[ser];
  147. }
  148. }
  149. DLL_EXPORT void MetaString::toString(std::string &dst) const
  150. {
  151. size_t exSt = 0, loSt = 0, nums = 0;
  152. dst.clear();
  153. for(size_t i=0;i<message.size();++i)
  154. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  155. switch(message[i])
  156. {
  157. case TEXACT_STRING:
  158. dst += exactStrings[exSt++];
  159. break;
  160. case TLOCAL_STRING:
  161. {
  162. std::string hlp;
  163. getLocalString(localStrings[loSt++], hlp);
  164. dst += hlp;
  165. }
  166. break;
  167. case TNUMBER:
  168. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  169. break;
  170. case TREPLACE_ESTRING:
  171. dst.replace(dst.find("%s"), 2, exactStrings[exSt++]);
  172. break;
  173. case TREPLACE_LSTRING:
  174. {
  175. std::string hlp;
  176. getLocalString(localStrings[loSt++], hlp);
  177. dst.replace(dst.find("%s"), 2, hlp);
  178. }
  179. break;
  180. case TREPLACE_NUMBER:
  181. dst.replace(dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  182. break;
  183. default:
  184. tlog1 << "MetaString processing error!\n";
  185. break;
  186. }
  187. }
  188. }
  189. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  190. {
  191. CGObjectInstance * nobj;
  192. switch(id)
  193. {
  194. case HEROI_TYPE: //hero
  195. {
  196. CGHeroInstance * nobj = new CGHeroInstance();
  197. nobj->pos = pos;
  198. nobj->tempOwner = owner;
  199. nobj->subID = subid;
  200. //nobj->initHero(ran);
  201. return nobj;
  202. }
  203. case TOWNI_TYPE: //town
  204. nobj = new CGTownInstance;
  205. break;
  206. default: //rest of objects
  207. nobj = new CGObjectInstance;
  208. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  209. break;
  210. }
  211. nobj->ID = id;
  212. nobj->subID = subid;
  213. if(!nobj->defInfo)
  214. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  215. nobj->pos = pos;
  216. //nobj->state = NULL;//new CLuaObjectScript();
  217. nobj->tempOwner = owner;
  218. nobj->info = NULL;
  219. nobj->defInfo->id = id;
  220. nobj->defInfo->subid = subid;
  221. //assigning defhandler
  222. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  223. return nobj;
  224. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  225. return nobj;
  226. }
  227. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  228. {
  229. for(unsigned int g=0; g<stacks.size(); ++g)
  230. {
  231. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  232. return stacks[g];
  233. }
  234. return NULL;
  235. }
  236. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  237. {
  238. for(unsigned int g=0; g<stacks.size(); ++g)
  239. {
  240. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  241. return stacks[g];
  242. }
  243. return NULL;
  244. }
  245. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  246. {
  247. for(unsigned int g=0; g<stacks.size(); ++g)
  248. {
  249. if(stacks[g]->position == tileID
  250. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  251. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  252. {
  253. if(!onlyAlive || stacks[g]->alive())
  254. {
  255. return stacks[g];
  256. }
  257. }
  258. }
  259. return NULL;
  260. }
  261. const CStack * BattleInfo::getStackT(int tileID, bool onlyAlive) const
  262. {
  263. for(unsigned int g=0; g<stacks.size(); ++g)
  264. {
  265. if(stacks[g]->position == tileID
  266. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  267. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  268. {
  269. if(!onlyAlive || stacks[g]->alive())
  270. {
  271. return stacks[g];
  272. }
  273. }
  274. }
  275. return NULL;
  276. }
  277. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit) const
  278. {
  279. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  280. //removing accessibility for side columns of hexes
  281. for(int v = 0; v < BFIELD_SIZE; ++v)
  282. {
  283. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  284. accessibility[v] = false;
  285. }
  286. for(unsigned int g=0; g<stacks.size(); ++g)
  287. {
  288. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit) //we don't want to lock position of this stack
  289. continue;
  290. accessibility[stacks[g]->position] = false;
  291. if(stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)) //if it's a double hex creature
  292. {
  293. if(stacks[g]->attackerOwned)
  294. accessibility[stacks[g]->position-1] = false;
  295. else
  296. accessibility[stacks[g]->position+1] = false;
  297. }
  298. }
  299. //obstacles
  300. for(unsigned int b=0; b<obstacles.size(); ++b)
  301. {
  302. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  303. for(unsigned int c=0; c<blocked.size(); ++c)
  304. {
  305. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  306. accessibility[blocked[c]] = false;
  307. }
  308. }
  309. //walls
  310. if(siege > 0)
  311. {
  312. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  313. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  314. {
  315. accessibility[permanentlyLocked[b]] = false;
  316. }
  317. static const std::pair<int, int> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  318. {std::make_pair(2, 182), std::make_pair(3, 130), std::make_pair(4, 62), std::make_pair(5, 29)};
  319. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  320. {
  321. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  322. {
  323. accessibility[lockedIfNotDestroyed[b].second] = false;
  324. }
  325. }
  326. //gate
  327. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  328. {
  329. accessibility[95] = accessibility[96] = false; //block gate's hexes
  330. }
  331. }
  332. //occupyability
  333. if(addOccupiable && twoHex)
  334. {
  335. std::set<int> rem; //tiles to unlock
  336. for(int h=0; h<BFIELD_HEIGHT; ++h)
  337. {
  338. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  339. {
  340. int hex = h * BFIELD_WIDTH + w;
  341. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  342. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  343. )
  344. rem.insert(hex);
  345. }
  346. }
  347. occupyable = rem;
  348. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  349. {
  350. accessibility[*it] = true;
  351. }*/
  352. }
  353. }
  354. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  355. {
  356. if(flying && !lastPos)
  357. return true;
  358. if(twoHex)
  359. {
  360. //if given hex is accessible and appropriate adjacent one is free too
  361. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  362. }
  363. else
  364. {
  365. return accessibility[hex];
  366. }
  367. }
  368. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying) const //both pointers must point to the at least 187-elements int arrays
  369. {
  370. //inits
  371. for(int b=0; b<BFIELD_SIZE; ++b)
  372. predecessor[b] = -1;
  373. for(int g=0; g<BFIELD_SIZE; ++g)
  374. dists[g] = 100000000;
  375. std::queue<int> hexq; //bfs queue
  376. hexq.push(start);
  377. dists[hexq.front()] = 0;
  378. int curNext = -1; //for bfs loop only (helper var)
  379. while(!hexq.empty()) //bfs loop
  380. {
  381. int curHex = hexq.front();
  382. std::vector<int> neighbours = neighbouringTiles(curHex);
  383. hexq.pop();
  384. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  385. {
  386. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  387. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex]+1 == dists[curNext]);
  388. if( dists[curHex]+1 >= dists[curNext] )
  389. continue;
  390. if(accessible)
  391. {
  392. hexq.push(curNext);
  393. dists[curNext] = dists[curHex] + 1;
  394. }
  395. predecessor[curNext] = curHex;
  396. }
  397. }
  398. };
  399. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable) const
  400. {
  401. std::vector<int> ret;
  402. bool ac[BFIELD_SIZE];
  403. const CStack *s = getStack(stackID);
  404. std::set<int> occupyable;
  405. getAccessibilityMap(ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, addOccupiable, occupyable, s->hasFeatureOfType(StackFeature::FLYING), stackID);
  406. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  407. makeBFS(s->position, ac, pr, dist, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING));
  408. if(s->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  409. {
  410. if(!addOccupiable)
  411. {
  412. std::vector<int> rem;
  413. for(int b=0; b<BFIELD_SIZE; ++b)
  414. {
  415. //don't take into account most left and most right columns of hexes
  416. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  417. continue;
  418. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  419. {
  420. rem.push_back(b);
  421. }
  422. }
  423. for(unsigned int g=0; g<rem.size(); ++g)
  424. {
  425. ac[rem[g]] = false;
  426. }
  427. //removing accessibility for side hexes
  428. for(int v=0; v<BFIELD_SIZE; ++v)
  429. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  430. ac[v] = false;
  431. }
  432. }
  433. for (int i=0; i < BFIELD_SIZE ; ++i) {
  434. if(
  435. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), true) ) )//we can reach it
  436. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  437. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  438. )
  439. {
  440. ret.push_back(i);
  441. }
  442. }
  443. return ret;
  444. }
  445. bool BattleInfo::isStackBlocked(int ID)
  446. {
  447. CStack *our = getStack(ID);
  448. if(our->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //siege weapons cannot be blocked
  449. return false;
  450. for(unsigned int i=0; i<stacks.size();i++)
  451. {
  452. if( !stacks[i]->alive()
  453. || stacks[i]->owner==our->owner
  454. )
  455. continue; //we omit dead and allied stacks
  456. if(stacks[i]->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  457. {
  458. if( mutualPosition(stacks[i]->position, our->position) >= 0
  459. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  460. return true;
  461. }
  462. else
  463. {
  464. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  465. return true;
  466. }
  467. }
  468. return false;
  469. }
  470. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  471. {
  472. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  473. return 0;
  474. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  475. return 1;
  476. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  477. return 5;
  478. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  479. return 2;
  480. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  481. return 4;
  482. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  483. return 3;
  484. return -1;
  485. }
  486. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  487. {
  488. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  489. std::vector<int> ret;
  490. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  491. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  492. CHECK_AND_PUSH(hex - 1);
  493. CHECK_AND_PUSH(hex + 1);
  494. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  495. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  496. #undef CHECK_AND_PUSH
  497. return ret;
  498. }
  499. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  500. {
  501. int predecessor[BFIELD_SIZE]; //for getting the Path
  502. int dist[BFIELD_SIZE]; //calculated distances
  503. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature);
  504. if(predecessor[dest] == -1) //cannot reach destination
  505. {
  506. return std::make_pair(std::vector<int>(), 0);
  507. }
  508. //making the Path
  509. std::vector<int> path;
  510. int curElem = dest;
  511. while(curElem != start)
  512. {
  513. path.push_back(curElem);
  514. curElem = predecessor[curElem];
  515. }
  516. return std::make_pair(path, dist[dest]);
  517. }
  518. int CStack::valOfFeatures(StackFeature::ECombatFeatures type, int subtype) const
  519. {
  520. int ret = 0;
  521. if(subtype == -1024) //any subtype
  522. {
  523. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  524. if(i->type == type)
  525. ret += i->value;
  526. }
  527. else //given subtype
  528. {
  529. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  530. if(i->type == type && i->subtype == subtype)
  531. ret += i->value;
  532. }
  533. return ret;
  534. }
  535. bool CStack::hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype) const
  536. {
  537. if(subtype == -1024) //any subtype
  538. {
  539. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  540. if(i->type == type)
  541. return true;
  542. }
  543. else //given subtype
  544. {
  545. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  546. if(i->type == type && i->subtype == subtype)
  547. return true;
  548. }
  549. return false;
  550. }
  551. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  552. :ID(I), creature(C), amount(A), baseAmount(A), firstHPleft(C->hitPoints), owner(O), slot(S), attackerOwned(AO), position(-1),
  553. counterAttacks(1), shots(C->shots), features(C->abilities)
  554. {
  555. //additional retaliations
  556. for(int h=0; h<C->abilities.size(); ++h)
  557. {
  558. if(C->abilities[h].type == StackFeature::ADDITIONAL_RETALIATION)
  559. {
  560. counterAttacks += C->abilities[h].value;
  561. }
  562. }
  563. //alive state indication
  564. state.insert(ALIVE);
  565. }
  566. ui32 CStack::Speed() const
  567. {
  568. if(hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //war machnes cannot move
  569. return 0;
  570. int speed = creature->speed;
  571. speed += valOfFeatures(StackFeature::SPEED_BONUS);
  572. int percentBonus = 0;
  573. for(int g=0; g<features.size(); ++g)
  574. {
  575. if(features[g].type == StackFeature::SPEED_BONUS)
  576. {
  577. percentBonus += features[g].additionalInfo;
  578. }
  579. }
  580. if(percentBonus < 0)
  581. {
  582. speed = (abs(percentBonus) * speed)/100;
  583. }
  584. else
  585. {
  586. speed = ((100 + percentBonus) * speed)/100;
  587. }
  588. //bind effect check
  589. if(getEffect(72))
  590. {
  591. return 0;
  592. }
  593. return speed;
  594. }
  595. const CStack::StackEffect * CStack::getEffect(ui16 id) const
  596. {
  597. for (unsigned int i=0; i< effects.size(); i++)
  598. if(effects[i].id == id)
  599. return &effects[i];
  600. return NULL;
  601. }
  602. ui8 CStack::howManyEffectsSet(ui16 id) const
  603. {
  604. ui8 ret = 0;
  605. for (unsigned int i=0; i< effects.size(); i++)
  606. if(effects[i].id == id) //effect found
  607. {
  608. ++ret;
  609. }
  610. return ret;
  611. }
  612. si8 CStack::Morale() const
  613. {
  614. si8 ret = morale;
  615. if(hasFeatureOfType(StackFeature::NON_LIVING) || hasFeatureOfType(StackFeature::UNDEAD) || hasFeatureOfType(StackFeature::NO_MORALE))
  616. return 0;
  617. ret += valOfFeatures(StackFeature::MORALE_BONUS); //mirth & sorrow & other
  618. if(hasFeatureOfType(StackFeature::SELF_MORALE)) //eg. minotaur
  619. {
  620. ret = std::max<si8>(ret, +1);
  621. }
  622. if(ret > 3) ret = 3;
  623. if(ret < -3) ret = -3;
  624. return ret;
  625. }
  626. si8 CStack::Luck() const
  627. {
  628. si8 ret = luck;
  629. if(hasFeatureOfType(StackFeature::NO_LUCK))
  630. return 0;
  631. ret += valOfFeatures(StackFeature::LUCK_BONUS); //fortune & misfortune & other
  632. if(hasFeatureOfType(StackFeature::SELF_LUCK)) //eg. halfling
  633. {
  634. ret = std::max<si8>(ret, +1);
  635. }
  636. if(ret > 3) ret = 3;
  637. if(ret < -3) ret = -3;
  638. return ret;
  639. }
  640. si32 CStack::Attack() const
  641. {
  642. si32 ret = creature->attack; //value to be returned
  643. if(hasFeatureOfType(StackFeature::IN_FRENZY)) //frenzy for attacker
  644. {
  645. ret += (VLC->spellh->spells[56].powers[getEffect(56)->level]/100.0) * Defense(false);
  646. }
  647. ret += valOfFeatures(StackFeature::ATTACK_BONUS);
  648. return ret;
  649. }
  650. si32 CStack::Defense(bool withFrenzy /*= true*/) const
  651. {
  652. si32 ret = creature->defence;
  653. if(withFrenzy && getEffect(56)) //frenzy for defender
  654. {
  655. return 0;
  656. }
  657. ret += valOfFeatures(StackFeature::DEFENCE_BONUS);
  658. return ret;
  659. }
  660. ui16 CStack::MaxHealth() const
  661. {
  662. return creature->hitPoints + valOfFeatures(StackFeature::HP_BONUS);
  663. }
  664. bool CStack::willMove()
  665. {
  666. return !vstd::contains(state, DEFENDING)
  667. && !vstd::contains(state, MOVED)
  668. && alive()
  669. && ! hasFeatureOfType(StackFeature::NOT_ACTIVE); //eg. Ammo Cart
  670. }
  671. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const
  672. {
  673. CGHeroInstance *ret = NULL;
  674. if(player<0 || player>=PLAYER_LIMIT)
  675. {
  676. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  677. return NULL;
  678. }
  679. std::vector<CGHeroInstance *> pool;
  680. if(native)
  681. {
  682. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  683. {
  684. if(pavailable.find(i->first)->second & 1<<player
  685. && i->second->type->heroType/2 == town->typeID)
  686. {
  687. pool.push_back(i->second);
  688. }
  689. }
  690. if(!pool.size())
  691. {
  692. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  693. return pickHeroFor(false, player, town, available);
  694. }
  695. else
  696. {
  697. ret = pool[rand()%pool.size()];
  698. }
  699. }
  700. else
  701. {
  702. int sum=0, r;
  703. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  704. {
  705. if(pavailable.find(i->first)->second & 1<<player)
  706. {
  707. pool.push_back(i->second);
  708. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  709. }
  710. }
  711. if(!pool.size())
  712. {
  713. tlog1 << "There are no heroes available for player " << player<<"!\n";
  714. return NULL;
  715. }
  716. r = rand()%sum;
  717. for(unsigned int i=0; i<pool.size(); i++)
  718. {
  719. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  720. if(r<0)
  721. ret = pool[i];
  722. }
  723. if(!ret)
  724. ret = pool.back();
  725. }
  726. available.erase(ret->subID);
  727. return ret;
  728. }
  729. //void CGameState::apply(CPack * pack)
  730. //{
  731. // while(!mx->try_lock())
  732. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  733. // //applyNL(pack);
  734. // mx->unlock();
  735. //}
  736. int CGameState::pickHero(int owner)
  737. {
  738. int h=-1;
  739. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  740. return h;
  741. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  742. int i=0;
  743. do //try to find free hero of our faction
  744. {
  745. i++;
  746. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  747. } while( map->getHero(h) && i<175);
  748. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  749. {
  750. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  751. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  752. if(!map->getHero(j))
  753. h=j;
  754. }
  755. return h;
  756. }
  757. CGHeroInstance *CGameState::getHero(int objid)
  758. {
  759. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  760. return NULL;
  761. return static_cast<CGHeroInstance *>(map->objects[objid]);
  762. }
  763. CGTownInstance *CGameState::getTown(int objid)
  764. {
  765. if(objid<0 || objid>=map->objects.size())
  766. return NULL;
  767. return static_cast<CGTownInstance *>(map->objects[objid]);
  768. }
  769. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  770. {
  771. switch(obj->ID)
  772. {
  773. case 65: //random artifact
  774. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  775. case 66: //random treasure artifact
  776. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  777. case 67: //random minor artifact
  778. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  779. case 68: //random major artifact
  780. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  781. case 69: //random relic artifact
  782. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  783. case 70: //random hero
  784. {
  785. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  786. }
  787. case 71: //random monster
  788. {
  789. int r;
  790. do
  791. {
  792. r = ran()%197;
  793. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  794. return std::pair<int,int>(54,r);
  795. }
  796. case 72: //random monster lvl1
  797. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  798. case 73: //random monster lvl2
  799. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  800. case 74: //random monster lvl3
  801. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  802. case 75: //random monster lvl4
  803. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  804. case 76: //random resource
  805. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  806. case 77: //random town
  807. {
  808. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  809. f;
  810. if(align>PLAYER_LIMIT-1)//same as owner / random
  811. {
  812. if(obj->tempOwner > PLAYER_LIMIT-1)
  813. f = -1; //random
  814. else
  815. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  816. }
  817. else
  818. {
  819. f = scenarioOps->getIthPlayersSettings(align).castle;
  820. }
  821. if(f<0) f = ran()%VLC->townh->towns.size();
  822. return std::pair<int,int>(TOWNI_TYPE,f);
  823. }
  824. case 162: //random monster lvl5
  825. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  826. case 163: //random monster lvl6
  827. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  828. case 164: //random monster lvl7
  829. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  830. case 216: //random dwelling
  831. {
  832. int faction = ran()%F_NUMBER;
  833. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(obj->info);
  834. if (info->asCastle)
  835. {
  836. for(unsigned int i=0;i<map->objects.size();i++)
  837. {
  838. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  839. {
  840. randomizeObject(map->objects[i]); //we have to randomize the castle first
  841. faction = map->objects[i]->subID;
  842. break;
  843. }
  844. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  845. {
  846. faction = map->objects[i]->subID;
  847. break;
  848. }
  849. }
  850. }
  851. else
  852. {
  853. while((!(info->castles[0]&(1<<faction))))
  854. {
  855. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  856. break;
  857. faction = ran()%F_NUMBER;
  858. }
  859. }
  860. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  861. int cid = VLC->townh->towns[faction].basicCreatures[level];
  862. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  863. if(VLC->objh->cregens[i]==cid)
  864. return std::pair<int,int>(17,i);
  865. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  866. return std::pair<int,int>(17,0);
  867. }
  868. case 217:
  869. {
  870. int faction = ran()%F_NUMBER;
  871. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(obj->info);
  872. if (info->asCastle)
  873. {
  874. for(unsigned int i=0;i<map->objects.size();i++)
  875. {
  876. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  877. {
  878. randomizeObject(map->objects[i]); //we have to randomize the castle first
  879. faction = map->objects[i]->subID;
  880. break;
  881. }
  882. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  883. {
  884. faction = map->objects[i]->subID;
  885. break;
  886. }
  887. }
  888. }
  889. else
  890. {
  891. while((!(info->castles[0]&(1<<faction))))
  892. {
  893. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  894. break;
  895. faction = ran()%F_NUMBER;
  896. }
  897. }
  898. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  899. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  900. if(VLC->objh->cregens[i]==cid)
  901. return std::pair<int,int>(17,i);
  902. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  903. return std::pair<int,int>(17,0);
  904. }
  905. case 218:
  906. {
  907. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(obj->info);
  908. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  909. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  910. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  911. if(VLC->objh->cregens[i]==cid)
  912. return std::pair<int,int>(17,i);
  913. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  914. return std::pair<int,int>(17,0);
  915. }
  916. }
  917. return std::pair<int,int>(-1,-1);
  918. }
  919. void CGameState::randomizeObject(CGObjectInstance *cur)
  920. {
  921. std::pair<int,int> ran = pickObject(cur);
  922. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  923. {
  924. if(cur->ID==TOWNI_TYPE) //town - set def
  925. {
  926. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  927. if(t->hasCapitol())
  928. t->defInfo = capitols[t->subID];
  929. else if(t->hasFort())
  930. t->defInfo = forts[t->subID];
  931. else
  932. t->defInfo = villages[t->subID];
  933. }
  934. return;
  935. }
  936. else if(ran.first==HEROI_TYPE)//special code for hero
  937. {
  938. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  939. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  940. cur->ID = ran.first;
  941. h->portrait = cur->subID = ran.second;
  942. h->type = VLC->heroh->heroes[ran.second];
  943. map->heroes.push_back(h);
  944. return; //TODO: maybe we should do something with definfo?
  945. }
  946. else if(ran.first==TOWNI_TYPE)//special code for town
  947. {
  948. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  949. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  950. cur->ID = ran.first;
  951. cur->subID = ran.second;
  952. t->town = &VLC->townh->towns[ran.second];
  953. if(t->hasCapitol())
  954. t->defInfo = capitols[t->subID];
  955. else if(t->hasFort())
  956. t->defInfo = forts[t->subID];
  957. else
  958. t->defInfo = villages[t->subID];
  959. map->towns.push_back(t);
  960. return;
  961. }
  962. //we have to replace normal random object
  963. cur->ID = ran.first;
  964. cur->subID = ran.second;
  965. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  966. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  967. if(!cur->defInfo)
  968. {
  969. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  970. return;
  971. }
  972. map->addBlockVisTiles(cur);
  973. }
  974. int CGameState::getDate(int mode) const
  975. {
  976. int temp;
  977. switch (mode)
  978. {
  979. case 0:
  980. return day;
  981. break;
  982. case 1:
  983. temp = (day)%7;
  984. if (temp)
  985. return temp;
  986. else return 7;
  987. break;
  988. case 2:
  989. temp = ((day-1)/7)+1;
  990. if (!(temp%4))
  991. return 4;
  992. else
  993. return (temp%4);
  994. break;
  995. case 3:
  996. return ((day-1)/28)+1;
  997. break;
  998. }
  999. return 0;
  1000. }
  1001. CGameState::CGameState()
  1002. {
  1003. mx = new boost::shared_mutex();
  1004. map = NULL;
  1005. curB = NULL;
  1006. scenarioOps = NULL;
  1007. applierGs = new CGSApplier;
  1008. }
  1009. CGameState::~CGameState()
  1010. {
  1011. delete mx;
  1012. delete map;
  1013. delete curB;
  1014. delete scenarioOps;
  1015. delete applierGs;
  1016. }
  1017. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  1018. {
  1019. day = 0;
  1020. seed = Seed;
  1021. ran.seed((boost::int32_t)seed);
  1022. scenarioOps = si;
  1023. this->map = map;
  1024. loadTownDInfos();
  1025. //picking random factions for players
  1026. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  1027. {
  1028. if(scenarioOps->playerInfos[i].castle==-1)
  1029. {
  1030. int f;
  1031. do
  1032. {
  1033. f = ran()%F_NUMBER;
  1034. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1035. scenarioOps->playerInfos[i].castle = f;
  1036. }
  1037. }
  1038. //randomizing objects
  1039. for(unsigned int no=0; no<map->objects.size(); ++no)
  1040. {
  1041. randomizeObject(map->objects[no]);
  1042. if(map->objects[no]->ID==26)
  1043. {
  1044. map->objects[no]->defInfo->handler=NULL;
  1045. }
  1046. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1047. }
  1048. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1049. /*********give starting hero****************************************/
  1050. for(int i=0;i<PLAYER_LIMIT;i++)
  1051. {
  1052. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1053. {
  1054. int3 hpos = map->players[i].posOfMainTown;
  1055. hpos.x+=1;// hpos.y+=1;
  1056. int j;
  1057. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1058. if(scenarioOps->playerInfos[j].color == i)
  1059. break;
  1060. if(j == scenarioOps->playerInfos.size())
  1061. continue;
  1062. int h=pickHero(i);
  1063. if(scenarioOps->playerInfos[j].hero == -1)
  1064. scenarioOps->playerInfos[j].hero = h;
  1065. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1066. nnn->id = map->objects.size();
  1067. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1068. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1069. {
  1070. if(map->towns[o]->pos == hpos)
  1071. {
  1072. map->towns[o]->visitingHero = nnn;
  1073. nnn->visitedTown = map->towns[o];
  1074. nnn->inTownGarrison = false;
  1075. break;
  1076. }
  1077. }
  1078. nnn->initHero();
  1079. map->heroes.push_back(nnn);
  1080. map->objects.push_back(nnn);
  1081. map->addBlockVisTiles(nnn);
  1082. }
  1083. }
  1084. /*********creating players entries in gs****************************************/
  1085. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1086. {
  1087. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1088. ins.second.color=ins.first;
  1089. ins.second.serial=i;
  1090. ins.second.human = scenarioOps->playerInfos[i].human;
  1091. players.insert(ins);
  1092. }
  1093. /******************RESOURCES****************************************************/
  1094. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1095. std::vector<int> startres;
  1096. std::ifstream tis("config/startres.txt");
  1097. int k;
  1098. for (int j=0;j<scenarioOps->difficulty;j++)
  1099. {
  1100. tis >> k;
  1101. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1102. tis>>k;
  1103. }
  1104. tis >> k;
  1105. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1106. {
  1107. tis >> k;
  1108. startres.push_back(k);
  1109. }
  1110. tis.close();
  1111. tis.clear();
  1112. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1113. {
  1114. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1115. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1116. (*i).second.resources[x] = startres[x];
  1117. }
  1118. tis.open("config/resources.txt");
  1119. tis >> k;
  1120. int pom;
  1121. for(int i=0;i<k;i++)
  1122. {
  1123. tis >> pom;
  1124. resVals.push_back(pom);
  1125. }
  1126. /*************************HEROES************************************************/
  1127. std::set<int> hids;
  1128. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1129. if(map->allowedHeroes[i])
  1130. hids.insert(i);
  1131. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1132. {
  1133. if (map->heroes[i]->getOwner()<0)
  1134. {
  1135. tlog2 << "Warning - hero with uninitialized owner!\n";
  1136. continue;
  1137. }
  1138. CGHeroInstance * vhi = (map->heroes[i]);
  1139. vhi->initHero();
  1140. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1141. hids.erase(vhi->subID);
  1142. }
  1143. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1144. {
  1145. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1146. continue;
  1147. map->predefinedHeroes[i]->initHero();
  1148. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1149. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1150. hids.erase(map->predefinedHeroes[i]->subID);
  1151. }
  1152. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1153. {
  1154. CGHeroInstance * vhi = new CGHeroInstance();
  1155. vhi->initHero(hid);
  1156. hpool.heroesPool[hid] = vhi;
  1157. hpool.pavailable[hid] = 0xff;
  1158. }
  1159. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1160. {
  1161. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1162. }
  1163. /*************************FOG**OF**WAR******************************************/
  1164. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1165. {
  1166. k->second.fogOfWarMap.resize(map->width);
  1167. for(int g=0; g<map->width; ++g)
  1168. k->second.fogOfWarMap[g].resize(map->height);
  1169. for(int g=-0; g<map->width; ++g)
  1170. for(int h=0; h<map->height; ++h)
  1171. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1172. for(int g=0; g<map->width; ++g)
  1173. for(int h=0; h<map->height; ++h)
  1174. for(int v=0; v<map->twoLevel+1; ++v)
  1175. k->second.fogOfWarMap[g][h][v] = 0;
  1176. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1177. {
  1178. if(obj->tempOwner != k->first) continue; //not a flagged object
  1179. int3 objCenter = obj->getSightCenter();
  1180. int radious = obj->getSightRadious();
  1181. for (int xd = std::max<int>(objCenter.x - radious , 0); xd <= std::min<int>(objCenter.x + radious, map->width - 1); xd++)
  1182. {
  1183. for (int yd = std::max<int>(objCenter.y - radious, 0); yd <= std::min<int>(objCenter.y + radious, map->height - 1); yd++)
  1184. {
  1185. double distance = objCenter.dist2d(int3(xd,yd,objCenter.z)) - 0.5;
  1186. if(distance <= radious)
  1187. k->second.fogOfWarMap[xd][yd][objCenter.z] = 1;
  1188. }
  1189. }
  1190. }
  1191. //for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1192. //{
  1193. // for(int yd=0; yd<map->height; ++yd)
  1194. // {
  1195. // for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1196. // {
  1197. // int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1198. // int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1199. // if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1200. // k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1201. // }
  1202. // }
  1203. //}
  1204. //starting bonus
  1205. if(si->playerInfos[k->second.serial].bonus==brandom)
  1206. si->playerInfos[k->second.serial].bonus = ran()%3;
  1207. switch(si->playerInfos[k->second.serial].bonus)
  1208. {
  1209. case bgold:
  1210. k->second.resources[6] += 500 + (ran()%6)*100;
  1211. break;
  1212. case bresource:
  1213. {
  1214. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1215. if(res == 127)
  1216. {
  1217. k->second.resources[0] += 5 + ran()%6;
  1218. k->second.resources[2] += 5 + ran()%6;
  1219. }
  1220. else
  1221. {
  1222. k->second.resources[res] += 3 + ran()%4;
  1223. }
  1224. break;
  1225. }
  1226. case bartifact:
  1227. {
  1228. if(!k->second.heroes.size())
  1229. {
  1230. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1231. break;
  1232. }
  1233. CArtifact *toGive;
  1234. do
  1235. {
  1236. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1237. } while (!map->allowedArtifact[toGive->id]);
  1238. CGHeroInstance *hero = k->second.heroes[0];
  1239. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1240. if(slot!=toGive->possibleSlots.end())
  1241. {
  1242. hero->artifWorn[*slot] = toGive->id;
  1243. hero->recreateArtBonuses();
  1244. }
  1245. else
  1246. hero->artifacts.push_back(toGive->id);
  1247. }
  1248. }
  1249. }
  1250. /****************************TOWNS************************************************/
  1251. for (unsigned int i=0;i<map->towns.size();i++)
  1252. {
  1253. CGTownInstance * vti =(map->towns[i]);
  1254. if(!vti->town)
  1255. vti->town = &VLC->townh->towns[vti->subID];
  1256. if (vti->name.length()==0) // if town hasn't name we draw it
  1257. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1258. //init buildings
  1259. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1260. {
  1261. vti->builtBuildings.erase(-50);
  1262. vti->builtBuildings.insert(10);
  1263. vti->builtBuildings.insert(5);
  1264. vti->builtBuildings.insert(30);
  1265. if(ran()%2)
  1266. vti->builtBuildings.insert(31);
  1267. }
  1268. //init spells
  1269. vti->spells.resize(SPELL_LEVELS);
  1270. CSpell *s;
  1271. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1272. {
  1273. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1274. vti->spells[s->level-1].push_back(s->id);
  1275. vti->possibleSpells -= s->id;
  1276. }
  1277. while(vti->possibleSpells.size())
  1278. {
  1279. ui32 total=0, sel=-1;
  1280. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1281. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1282. int r = (total)? ran()%total : -1;
  1283. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1284. {
  1285. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1286. if(r<0)
  1287. {
  1288. sel = ps;
  1289. break;
  1290. }
  1291. }
  1292. if(sel<0)
  1293. sel=0;
  1294. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1295. vti->spells[s->level-1].push_back(s->id);
  1296. vti->possibleSpells -= s->id;
  1297. }
  1298. //init garrisons
  1299. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1300. {
  1301. if(j->second.first > 196 && j->second.first < 211)
  1302. {
  1303. if(j->second.first%2)
  1304. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1305. else
  1306. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1307. }
  1308. }
  1309. if(vti->getOwner() != 255)
  1310. getPlayer(vti->getOwner())->towns.push_back(vti);
  1311. }
  1312. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1313. {
  1314. if(k->first==-1 || k->first==255)
  1315. continue;
  1316. //init visiting and garrisoned heroes
  1317. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1318. {
  1319. for(unsigned int m=0; m<k->second.towns.size();m++)
  1320. {
  1321. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1322. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1323. {
  1324. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1325. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1326. k->second.heroes[l]->inTownGarrison = false;
  1327. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1328. k->second.heroes[l]->pos.x -= 1;
  1329. break;
  1330. }
  1331. }
  1332. }
  1333. }
  1334. for(unsigned int i=0; i<map->defy.size(); i++)
  1335. {
  1336. map->defy[i]->serial = i;
  1337. }
  1338. for(unsigned int i=0; i<map->objects.size(); i++)
  1339. {
  1340. map->objects[i]->initObj();
  1341. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1342. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1343. }
  1344. }
  1345. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1346. {
  1347. return true;
  1348. }
  1349. bool CGameState::battleCanFlee(int player)
  1350. {
  1351. if(!curB) //there is no battle
  1352. return false;
  1353. const CGHeroInstance *h1 = getHero(curB->hero1);
  1354. const CGHeroInstance *h2 = getHero(curB->hero2);
  1355. if(h1 && h1->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1356. || h2 && h2->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE))
  1357. return false;
  1358. return true;
  1359. }
  1360. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1361. {
  1362. if(!curB)
  1363. return -1;
  1364. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1365. {
  1366. if((curB->stacks[g]->position == pos
  1367. || (curB->stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  1368. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1369. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1370. ))
  1371. && (!onlyAlive || curB->stacks[g]->alive())
  1372. )
  1373. return curB->stacks[g]->ID;
  1374. }
  1375. return -1;
  1376. }
  1377. int CGameState::battleGetBattlefieldType(int3 tile)
  1378. {
  1379. if(tile==int3() && curB)
  1380. tile = curB->tile;
  1381. else if(tile==int3() && !curB)
  1382. return -1;
  1383. const std::vector <CGObjectInstance*> & objs = map->objects;
  1384. for(int g=0; g<objs.size(); ++g)
  1385. {
  1386. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1387. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1388. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1389. ) //look only for objects covering given tile
  1390. continue;
  1391. switch(objs[g]->ID)
  1392. {
  1393. case 222: //clover field
  1394. return 19;
  1395. case 21: case 223: //cursed ground
  1396. return 22;
  1397. case 224: //evil fog
  1398. return 20;
  1399. case 225: //favourable winds
  1400. return 21;
  1401. case 226: //fiery fields
  1402. return 14;
  1403. case 227: //holy ground
  1404. return 18;
  1405. case 228: //lucid pools
  1406. return 17;
  1407. case 229: //magic clouds
  1408. return 16;
  1409. case 46: case 230: //magic plains
  1410. return 9;
  1411. case 231: //rocklands
  1412. return 15;
  1413. }
  1414. }
  1415. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1416. {
  1417. case TerrainTile::dirt:
  1418. return rand()%3+3;
  1419. case TerrainTile::sand:
  1420. return 2; //TODO: coast support
  1421. case TerrainTile::grass:
  1422. return rand()%2+6;
  1423. case TerrainTile::snow:
  1424. return rand()%2+10;
  1425. case TerrainTile::swamp:
  1426. return 13;
  1427. case TerrainTile::rough:
  1428. return 23;
  1429. case TerrainTile::subterranean:
  1430. return 12;
  1431. case TerrainTile::lava:
  1432. return 8;
  1433. case TerrainTile::water:
  1434. return 25;
  1435. case TerrainTile::rock:
  1436. return 15;
  1437. default:
  1438. return -1;
  1439. }
  1440. }
  1441. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1442. {
  1443. UpgradeInfo ret;
  1444. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1445. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1446. {
  1447. CGTownInstance * t;
  1448. if(obj->ID == TOWNI_TYPE)
  1449. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1450. else
  1451. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1452. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1453. {
  1454. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1455. {
  1456. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1457. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1458. {
  1459. ret.newID.push_back(nid);
  1460. ret.cost.push_back(std::set<std::pair<int,int> >());
  1461. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1462. {
  1463. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1464. if(dif)
  1465. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1466. }
  1467. }
  1468. }
  1469. }//end for
  1470. }
  1471. //TODO: check if hero ability makes some upgrades possible
  1472. if(ret.newID.size())
  1473. ret.oldID = base->idNumber;
  1474. return ret;
  1475. }
  1476. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1477. {
  1478. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1479. if(mode) return -1; //todo - support other modes
  1480. int mcount = 0;
  1481. for(unsigned int i=0;i<getPlayer(player)->towns.size();i++)
  1482. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1483. mcount++;
  1484. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1485. return ret;
  1486. }
  1487. void CGameState::loadTownDInfos()
  1488. {
  1489. for(int i=0;i<F_NUMBER;i++)
  1490. {
  1491. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1492. forts[i] = VLC->dobjinfo->castles[i];
  1493. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1494. }
  1495. }
  1496. void CGameState::getNeighbours( const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand )
  1497. {
  1498. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1499. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1500. vec.clear();
  1501. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1502. {
  1503. const int3 hlp = tile + dirs[i];
  1504. if(!map->isInTheMap(hlp))
  1505. continue;
  1506. const TerrainTile &hlpt = map->getTile(hlp);
  1507. if((indeterminate(onLand) || onLand == (hlpt.tertype!=8) )
  1508. && hlpt.tertype!=9)
  1509. {
  1510. vec.push_back(hlp);
  1511. }
  1512. }
  1513. }
  1514. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1515. {
  1516. if(src == dest) //same tile
  1517. return 0;
  1518. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1519. &d = map->terrain[dest.x][dest.y][dest.z];
  1520. //get basic cost
  1521. int ret = h->getTileCost(d,s);
  1522. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1523. {
  1524. int old = ret;
  1525. ret *= 1.414213;
  1526. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1527. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1528. {
  1529. return remainingMovePoints;
  1530. }
  1531. }
  1532. int left = remainingMovePoints-ret;
  1533. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1534. {
  1535. std::vector<int3> vec;
  1536. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water);
  1537. for(size_t i=0; i < vec.size(); i++)
  1538. {
  1539. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1540. if(fcost <= left)
  1541. {
  1542. return ret;
  1543. }
  1544. }
  1545. ret = remainingMovePoints;
  1546. }
  1547. return ret;
  1548. }
  1549. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1550. {
  1551. int ret = 7; //allowed by default
  1552. //checking resources
  1553. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1554. if(!pom)return 8;
  1555. if(pom->Name().size()==0||pom->resources.size()==0)return 2;//TODO: why does this happen?
  1556. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1557. {
  1558. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1559. ret = 6; //lack of res
  1560. }
  1561. //checking for requirements
  1562. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][ID].begin();
  1563. ri != VLC->townh->requirements[t->subID][ID].end();
  1564. ri++ )
  1565. {
  1566. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1567. ret = 8; //lack of requirements - cannot build
  1568. }
  1569. //can we build it?
  1570. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1571. ret = 2; //forbidden
  1572. else if(t->builded >= MAX_BUILDING_PER_TURN)
  1573. ret = 5; //building limit
  1574. if(ID == 13) //capitol
  1575. {
  1576. for(unsigned int in = 0; in < map->towns.size(); in++)
  1577. {
  1578. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1579. {
  1580. ret = 0; //no more than one capitol
  1581. break;
  1582. }
  1583. }
  1584. }
  1585. else if(ID == 6) //shipyard
  1586. {
  1587. int3 t1(t->pos + int3(-1,3,0)),
  1588. t2(t->pos + int3(-3,3,0));
  1589. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1590. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1591. ret = 1; //lack of water
  1592. }
  1593. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1594. ret = 4;
  1595. return ret;
  1596. }
  1597. void CGameState::apply(CPack *pack)
  1598. {
  1599. ui16 typ = typeList.getTypeID(pack);
  1600. assert(typ >= 0);
  1601. applierGs->apps[typ]->applyOnGS(this,pack);
  1602. }
  1603. PlayerState * CGameState::getPlayer( ui8 color )
  1604. {
  1605. if(vstd::contains(players,color))
  1606. {
  1607. return &players[color];
  1608. }
  1609. else
  1610. {
  1611. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1612. return NULL;
  1613. }
  1614. }
  1615. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1616. {
  1617. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1618. return false;
  1619. int3 hpos = hero->getPosition(false);
  1620. tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1621. if (!hero->canWalkOnSea())
  1622. blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1623. else
  1624. blockLandSea = boost::logic::indeterminate;
  1625. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1626. //graph initialization
  1627. std::vector< std::vector<CPathNode> > graph;
  1628. graph.resize(map->width);
  1629. for(size_t i=0; i<graph.size(); ++i)
  1630. {
  1631. graph[i].resize(map->height);
  1632. for(size_t j=0; j<graph[i].size(); ++j)
  1633. {
  1634. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1635. CPathNode &node = graph[i][j];
  1636. node.accesible = !tinfo->blocked;
  1637. node.dist = -1;
  1638. node.theNodeBefore = NULL;
  1639. node.visited = false;
  1640. node.coord.x = i;
  1641. node.coord.y = j;
  1642. node.coord.z = dest.z;
  1643. if ((tinfo->tertype == TerrainTile::rock) //it's rock
  1644. || ((blockLandSea) && (tinfo->tertype == TerrainTile::water)) //it's sea and we cannot walk on sea
  1645. || ((!blockLandSea) && (tinfo->tertype != TerrainTile::water)) //it's land and we cannot walk on land
  1646. || !FoW[i][j][src.z] //tile is covered by the FoW
  1647. )
  1648. {
  1649. node.accesible = false;
  1650. }
  1651. }
  1652. }
  1653. //Special rules for the destination tile
  1654. {
  1655. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1656. CPathNode &d = graph[dest.x][dest.y];
  1657. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1658. if(t->visitable)
  1659. {
  1660. d.accesible = true; //for allowing visiting objects
  1661. }
  1662. if(blockLandSea && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1663. {
  1664. size_t i = 0;
  1665. for(; i < t->visitableObjects.size(); i++)
  1666. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1667. break;
  1668. d.accesible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1669. }
  1670. else if(!blockLandSea && t->tertype != TerrainTile::water) //hero is moving by water
  1671. {
  1672. d.accesible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1673. }
  1674. }
  1675. //graph initialized
  1676. //initial tile - set cost on 0 and add to the queue
  1677. graph[src.x][src.y].dist = 0;
  1678. std::queue<CPathNode> mq;
  1679. mq.push(graph[src.x][src.y]);
  1680. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1681. std::vector<int3> neighbours;
  1682. neighbours.reserve(8);
  1683. while(!mq.empty())
  1684. {
  1685. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1686. mq.pop();
  1687. if (cp.coord == dest) //it's destination tile
  1688. {
  1689. if (cp.dist < curDist) //that path is better than previous one
  1690. curDist = cp.dist;
  1691. continue;
  1692. }
  1693. else
  1694. {
  1695. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1696. continue;
  1697. }
  1698. //add accessible neighbouring nodes to the queue
  1699. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate);
  1700. for(unsigned int i=0; i < neighbours.size(); i++)
  1701. {
  1702. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1703. if(dp.accesible)
  1704. {
  1705. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1706. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accesible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1707. {
  1708. dp.dist = cp.dist + cost;
  1709. dp.theNodeBefore = &cp;
  1710. mq.push(dp);
  1711. }
  1712. }
  1713. }
  1714. }
  1715. CPathNode *curNode = &graph[dest.x][dest.y];
  1716. if(!curNode->theNodeBefore) //destination is not accessible
  1717. return false;
  1718. //fill ret with found path
  1719. ret.nodes.clear();
  1720. while(curNode->coord != graph[src.x][src.y].coord)
  1721. {
  1722. ret.nodes.push_back(*curNode);
  1723. curNode = curNode->theNodeBefore;
  1724. }
  1725. ret.nodes.push_back(graph[src.x][src.y]);
  1726. return true;
  1727. }
  1728. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1729. {
  1730. if(src.x < 0)
  1731. src = hero->getPosition(false);
  1732. if(movement < 0)
  1733. movement = hero->movement;
  1734. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1735. {
  1736. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1737. return;
  1738. }
  1739. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1740. if (!hero->canWalkOnSea())
  1741. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1742. else
  1743. onLand = boost::logic::indeterminate;
  1744. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1745. //graph initialization
  1746. CGPathNode ***graph = out.nodes;
  1747. for(size_t i=0; i < out.sizes.x; ++i)
  1748. {
  1749. for(size_t j=0; j < out.sizes.y; ++j)
  1750. {
  1751. for(size_t k=0; k < out.sizes.z; ++k)
  1752. {
  1753. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1754. CGPathNode &node = graph[i][j][k];
  1755. node.accessible = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  1756. node.turns = 0xff;
  1757. node.moveRemains = 0;
  1758. node.coord.x = i;
  1759. node.coord.y = j;
  1760. node.coord.z = k;
  1761. node.land = tinfo->tertype != TerrainTile::water;
  1762. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1763. || onLand && !node.land //it's sea and we cannot walk on sea
  1764. || !onLand && node.land //it's land and we cannot walk on land
  1765. || !FoW[i][j][k] //tile is covered by the FoW
  1766. )
  1767. {
  1768. node.accessible = CGPathNode::BLOCKED;
  1769. }
  1770. else if(tinfo->visitable)
  1771. {
  1772. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1773. {
  1774. if(tinfo->visitableObjects[ii]->blockVisit)
  1775. {
  1776. node.accessible = CGPathNode::BLOCKVIS;
  1777. break;
  1778. }
  1779. else
  1780. node.accessible = CGPathNode::VISITABLE;
  1781. }
  1782. }
  1783. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  1784. {
  1785. size_t i = 0;
  1786. for(; i < tinfo->visitableObjects.size(); i++)
  1787. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1788. break;
  1789. if(i < tinfo->visitableObjects.size())
  1790. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  1791. }
  1792. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  1793. {
  1794. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  1795. node.accessible = CGPathNode::ACCESSIBLE; //tile is accessible if it's coastal and not blocked
  1796. }
  1797. }
  1798. }
  1799. }
  1800. //graph initialized
  1801. //initial tile - set cost on 0 and add to the queue
  1802. graph[src.x][src.y][src.z].turns = 0;
  1803. graph[src.x][src.y][src.z].moveRemains = movement;
  1804. std::queue<CGPathNode*> mq;
  1805. mq.push(&graph[src.x][src.y][src.z]);
  1806. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1807. std::vector<int3> neighbours;
  1808. neighbours.reserve(8);
  1809. while(!mq.empty())
  1810. {
  1811. CGPathNode *cp = mq.front();
  1812. mq.pop();
  1813. const TerrainTile &ct = map->getTile(cp->coord);
  1814. int movement = cp->moveRemains, turn = cp->turns;
  1815. if(!movement)
  1816. {
  1817. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  1818. turn++;
  1819. }
  1820. //add accessible neighbouring nodes to the queue
  1821. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate);
  1822. for(unsigned int i=0; i < neighbours.size(); i++)
  1823. {
  1824. const int3 &n = neighbours[i]; //current neighbor
  1825. CGPathNode & dp = graph[n.x][n.y][n.z];
  1826. if( !checkForVisitableDir(cp->coord, dp.coord)
  1827. || !checkForVisitableDir(dp.coord, cp->coord)
  1828. || dp.accessible == CGPathNode::BLOCKED )
  1829. {
  1830. continue;
  1831. }
  1832. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  1833. int remains = movement - cost;
  1834. if(dp.turns==0xff //we haven't been here before
  1835. || dp.turns > turn
  1836. || (dp.turns >= turn && dp.moveRemains < remains)) //this route is faster
  1837. {
  1838. dp.moveRemains = remains;
  1839. dp.turns = turn;
  1840. dp.theNodeBefore = cp;
  1841. if(dp.accessible == CGPathNode::ACCESSIBLE)
  1842. {
  1843. mq.push(&dp);
  1844. }
  1845. }
  1846. } //neighbours loop
  1847. } //queue loop
  1848. }
  1849. bool CGameState::isVisible(int3 pos, int player)
  1850. {
  1851. if(player == 255) //neutral player
  1852. return false;
  1853. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  1854. }
  1855. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1856. {
  1857. if(player == 255) //neutral player
  1858. return false;
  1859. //object is visible when at least one blocked tile is visible
  1860. for(int fx=0; fx<8; ++fx)
  1861. {
  1862. for(int fy=0; fy<6; ++fy)
  1863. {
  1864. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1865. if(map->isInTheMap(pos)
  1866. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1867. && isVisible(pos, player) )
  1868. return true;
  1869. }
  1870. }
  1871. return false;
  1872. }
  1873. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1874. {
  1875. const TerrainTile * pom = &map->getTile(dst);
  1876. return checkForVisitableDir(src, pom, dst);
  1877. }
  1878. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  1879. {
  1880. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1881. {
  1882. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1883. continue;
  1884. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1885. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1886. {
  1887. return false;
  1888. }
  1889. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1890. {
  1891. return false;
  1892. }
  1893. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1894. {
  1895. return false;
  1896. }
  1897. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1898. {
  1899. return false;
  1900. }
  1901. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1902. {
  1903. return false;
  1904. }
  1905. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1906. {
  1907. return false;
  1908. }
  1909. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1910. {
  1911. return false;
  1912. }
  1913. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1914. {
  1915. return false;
  1916. }
  1917. }
  1918. return true;
  1919. }
  1920. std::pair<ui32, ui32> BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  1921. {
  1922. int attackDefenseBonus,
  1923. minDmg = attacker->creature->damageMin * attacker->amount,
  1924. maxDmg = attacker->creature->damageMax * attacker->amount;
  1925. if(attacker->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //any siege weapon, but only ballista can attack
  1926. { //minDmg and maxDmg are multiplied by hero attack + 1
  1927. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  1928. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  1929. }
  1930. if(attacker->hasFeatureOfType(StackFeature::GENERAL_ATTACK_REDUCTION))
  1931. {
  1932. attackDefenseBonus = attacker->Attack() * (attacker->valOfFeatures(StackFeature::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f) - defender->Defense();
  1933. }
  1934. else
  1935. {
  1936. attackDefenseBonus = attacker->Attack() - defender->Defense();
  1937. }
  1938. //calculating total attack/defense skills modifier
  1939. if(!shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 0)) //bloodlust handling (etc.)
  1940. {
  1941. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 0);
  1942. }
  1943. if(shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 1)) //precision handling (etc.)
  1944. {
  1945. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 1);
  1946. }
  1947. if(attacker->getEffect(55)) //slayer handling
  1948. {
  1949. std::vector<int> affectedIds;
  1950. switch(attacker->getEffect(55)->level)
  1951. {
  1952. case 3: //expert
  1953. {
  1954. affectedIds.push_back(40); //giant
  1955. affectedIds.push_back(41); //titan
  1956. affectedIds.push_back(152); //lord of thunder
  1957. } //continue adding ...
  1958. case 2: //advanced
  1959. {
  1960. affectedIds.push_back(12); //angel
  1961. affectedIds.push_back(13); //archangel
  1962. affectedIds.push_back(54); //devil
  1963. affectedIds.push_back(55); //arch devil
  1964. affectedIds.push_back(150); //supreme archangel
  1965. affectedIds.push_back(153); //antichrist
  1966. } //continue adding ...
  1967. case 0: case 1: //none and basic
  1968. {
  1969. affectedIds.push_back(26); //green dragon
  1970. affectedIds.push_back(27); //gold dragon
  1971. affectedIds.push_back(82); //red dragon
  1972. affectedIds.push_back(83); //black dragon
  1973. affectedIds.push_back(96); //behemot
  1974. affectedIds.push_back(97); //ancient behemot
  1975. affectedIds.push_back(110); //hydra
  1976. affectedIds.push_back(111); //chaos hydra
  1977. affectedIds.push_back(132); //azure dragon
  1978. affectedIds.push_back(133); //crystal dragon
  1979. affectedIds.push_back(134); //faerie dragon
  1980. affectedIds.push_back(135); //rust dragon
  1981. affectedIds.push_back(151); //diamond dragon
  1982. affectedIds.push_back(154); //blood dragon
  1983. affectedIds.push_back(155); //darkness dragon
  1984. affectedIds.push_back(156); //ghost behemot
  1985. affectedIds.push_back(157); //hell hydra
  1986. break;
  1987. }
  1988. }
  1989. for(unsigned int g=0; g<affectedIds.size(); ++g)
  1990. {
  1991. if(defender->creature->idNumber == affectedIds[g])
  1992. {
  1993. attackDefenseBonus += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  1994. break;
  1995. }
  1996. }
  1997. }
  1998. float dmgBonusMultiplier = 1.0f;
  1999. //applying jousting bonus
  2000. if( attacker->hasFeatureOfType(StackFeature::JOUSTING) && !defender->hasFeatureOfType(StackFeature::CHARGE_IMMUNITY) )
  2001. dmgBonusMultiplier += charge * 0.05f;
  2002. //bonus from attack/defense skills
  2003. if(attackDefenseBonus < 0) //decreasing dmg
  2004. {
  2005. if(0.02f * (-attackDefenseBonus) > 0.3f)
  2006. {
  2007. dmgBonusMultiplier += -0.3f;
  2008. }
  2009. else
  2010. {
  2011. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  2012. }
  2013. }
  2014. else //increasing dmg
  2015. {
  2016. if(0.05f * attackDefenseBonus > 4.0f)
  2017. {
  2018. dmgBonusMultiplier += 4.0f;
  2019. }
  2020. else
  2021. {
  2022. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  2023. }
  2024. }
  2025. //handling secondary abilities and artifacts giving premies to them
  2026. if(attackerHero)
  2027. {
  2028. if(shooting)
  2029. {
  2030. switch(attackerHero->getSecSkillLevel(1)) //archery
  2031. {
  2032. case 1: //basic
  2033. dmgBonusMultiplier += 0.1f;
  2034. break;
  2035. case 2: //advanced
  2036. dmgBonusMultiplier += 0.25f;
  2037. break;
  2038. case 3: //expert
  2039. dmgBonusMultiplier += 0.5f;
  2040. break;
  2041. }
  2042. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  2043. {
  2044. //apply artifact premy to archery
  2045. dmgBonusMultiplier += attackerHero->valOfBonuses(HeroBonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2046. }
  2047. }
  2048. else
  2049. {
  2050. switch(attackerHero->getSecSkillLevel(22)) //offense
  2051. {
  2052. case 1: //basic
  2053. dmgBonusMultiplier += 0.1f;
  2054. break;
  2055. case 2: //advanced
  2056. dmgBonusMultiplier += 0.2f;
  2057. break;
  2058. case 3: //expert
  2059. dmgBonusMultiplier += 0.3f;
  2060. break;
  2061. }
  2062. }
  2063. }
  2064. if(defendingHero)
  2065. {
  2066. switch(defendingHero->getSecSkillLevel(23)) //armorer
  2067. {
  2068. case 1: //basic
  2069. dmgBonusMultiplier *= 0.95f;
  2070. break;
  2071. case 2: //advanced
  2072. dmgBonusMultiplier *= 0.9f;
  2073. break;
  2074. case 3: //expert
  2075. dmgBonusMultiplier *= 0.85f;
  2076. break;
  2077. }
  2078. }
  2079. //handling hate effect
  2080. if( attacker->hasFeatureOfType(StackFeature::HATE, defender->creature->idNumber) )
  2081. dmgBonusMultiplier += 0.5f;
  2082. //handling spell effects
  2083. if(!shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2084. {
  2085. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2086. }
  2087. else if(shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2088. {
  2089. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2090. }
  2091. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2092. {
  2093. dmgBonusMultiplier *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2094. }
  2095. minDmg *= dmgBonusMultiplier;
  2096. maxDmg *= dmgBonusMultiplier;
  2097. if(attacker->getEffect(42)) //curse handling (rest)
  2098. {
  2099. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2100. return std::make_pair(minDmg, minDmg);
  2101. }
  2102. else if(attacker->getEffect(41)) //bless handling
  2103. {
  2104. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2105. return std::make_pair(maxDmg, maxDmg);
  2106. }
  2107. else
  2108. {
  2109. return std::make_pair(minDmg, maxDmg);
  2110. }
  2111. tlog1 << "We are too far in calculateDmg...\n";
  2112. return std::make_pair(0, 0);
  2113. }
  2114. ui32 BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2115. {
  2116. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge);
  2117. if(range.first != range.second)
  2118. return range.first + rand() % (range.second - range.first + 1);
  2119. else
  2120. return range.first;
  2121. }
  2122. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties ) const
  2123. {
  2124. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2125. {
  2126. if(!stacks[i]->alive())
  2127. {
  2128. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  2129. }
  2130. else if(stacks[i]->amount != stacks[i]->baseAmount)
  2131. {
  2132. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  2133. }
  2134. }
  2135. }
  2136. si8 CGameState::battleMaxSpellLevel()
  2137. {
  2138. if(!curB) //there is not battle
  2139. {
  2140. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2141. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2142. }
  2143. si8 levelLimit = SPELL_LEVELS;
  2144. const CGHeroInstance *h1 = getHero(curB->hero1);
  2145. if(h1)
  2146. {
  2147. for(std::list<HeroBonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2148. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2149. amin(levelLimit, i->val);
  2150. }
  2151. const CGHeroInstance *h2 = getHero(curB->hero2);
  2152. if(h2)
  2153. {
  2154. for(std::list<HeroBonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2155. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2156. amin(levelLimit, i->val);
  2157. }
  2158. return levelLimit;
  2159. }
  2160. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile)
  2161. {
  2162. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, caster->getSpellSchoolLevel(s));
  2163. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurences of two hex creatures*/
  2164. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2165. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and armageddon
  2166. {
  2167. for(int it=0; it<stacks.size(); ++it)
  2168. {
  2169. if((s->id == 24 && !stacks[it]->creature->isUndead()) //death ripple
  2170. || (s->id == 25 && stacks[it]->creature->isUndead()) //destroy undead
  2171. || (s->id == 26) //armageddon
  2172. )
  2173. {
  2174. attackedCres.insert(stacks[it]);
  2175. }
  2176. }
  2177. }
  2178. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2179. || VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  2180. {
  2181. if(caster->getSpellSchoolLevel(s) < 3) /*not expert */
  2182. {
  2183. CStack * st = getStackT(destinationTile, onlyAlive);
  2184. if(st)
  2185. attackedCres.insert(st);
  2186. }
  2187. else
  2188. {
  2189. for(int it=0; it<stacks.size(); ++it)
  2190. {
  2191. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2192. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == caster->tempOwner)
  2193. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != caster->tempOwner )
  2194. )
  2195. {
  2196. if(!onlyAlive || stacks[it]->alive())
  2197. attackedCres.insert(stacks[it]);
  2198. }
  2199. }
  2200. } //if(caster->getSpellSchoolLevel(s) < 3)
  2201. }
  2202. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2203. {
  2204. CStack * st = getStackT(destinationTile, onlyAlive);
  2205. if(st)
  2206. attackedCres.insert(st);
  2207. }
  2208. else //custom range from attackedHexes
  2209. {
  2210. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2211. {
  2212. CStack * st = getStackT(*it, onlyAlive);
  2213. if(st)
  2214. attackedCres.insert(st);
  2215. }
  2216. }
  2217. return attackedCres;
  2218. }
  2219. int BattleInfo::calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster)
  2220. {
  2221. switch(spell->id)
  2222. {
  2223. case 56: //frenzy
  2224. return 1;
  2225. default: //other spells
  2226. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(HeroBonus::SPELL_DURATION);
  2227. }
  2228. }
  2229. CStack * BattleInfo::generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2230. {
  2231. CStack * ret = new CStack(&VLC->creh->creatures[creatureID], amount, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2232. if(owner)
  2233. {
  2234. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACKS_SPEED), StackFeature::BONUS_FROM_HERO));
  2235. //base luck/morale calculations
  2236. ret->morale = owner->getCurrentMorale(slot, false);
  2237. ret->luck = owner->getCurrentLuck(slot, false);
  2238. //other bonuses
  2239. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(0), StackFeature::BONUS_FROM_HERO));
  2240. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(1), StackFeature::BONUS_FROM_HERO));
  2241. if ( owner->hasBonusOfType(HeroBonus::STACK_HEALTH_PERCENT) ) // e.g. Elixir of Life
  2242. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0,
  2243. (ret->creature->hitPoints * owner->valOfBonuses(HeroBonus::STACK_HEALTH_PERCENT)) / 100,
  2244. StackFeature::BONUS_FROM_HERO));
  2245. if (owner->hasBonusOfType(HeroBonus::HP_REGENERATION)) // e.g. Elixir of Life
  2246. ret->features.push_back(makeFeature(StackFeature::HP_REGENERATION, StackFeature::WHOLE_BATTLE, 0,
  2247. owner->valOfBonuses(HeroBonus::HP_REGENERATION), StackFeature::BONUS_FROM_HERO));
  2248. if (owner->hasBonusOfType(HeroBonus::LEVEL_SPELL_IMMUNITY)) // e.g. Power of the Dragon Father
  2249. ret->features.push_back(makeFeature(StackFeature::LEVEL_SPELL_IMMUNITY, StackFeature::WHOLE_BATTLE, 0,
  2250. owner->valOfBonuses(HeroBonus::LEVEL_SPELL_IMMUNITY), StackFeature::BONUS_FROM_HERO));
  2251. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACK_HEALTH), StackFeature::BONUS_FROM_HERO));
  2252. ret->firstHPleft = ret->MaxHealth();
  2253. }
  2254. else
  2255. {
  2256. ret->morale = 0;
  2257. ret->luck = 0;
  2258. }
  2259. //native terrain bonuses
  2260. int faction = ret->creature->faction;
  2261. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2262. {
  2263. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2264. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2265. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2266. }
  2267. ret->position = position;
  2268. return ret;
  2269. }
  2270. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2271. {
  2272. ui32 ret = VLC->spellh->spells[sp->id].costs[caster->getSpellSchoolLevel(sp)];
  2273. //checking for friendly stacks reducing cost of the spell
  2274. si32 manaReduction = 0;
  2275. for(int g=0; g<stacks.size(); ++g)
  2276. {
  2277. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasFeatureOfType(StackFeature::CHANGES_SPELL_COST_FOR_ALLY) )
  2278. {
  2279. amin(manaReduction, stacks[g]->valOfFeatures(StackFeature::CHANGES_SPELL_COST_FOR_ALLY));
  2280. }
  2281. }
  2282. return ret + manaReduction;
  2283. }
  2284. int BattleInfo::hexToWallPart(int hex) const
  2285. {
  2286. if(siege == 0) //there is no battle!
  2287. return -1;
  2288. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2289. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2290. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7)};
  2291. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2292. {
  2293. if(attackable[g].first == hex)
  2294. return attackable[g].second;
  2295. }
  2296. return -1; //not found!
  2297. }
  2298. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2299. {
  2300. bool ac[BFIELD_SIZE];
  2301. std::set<int> occupyable;
  2302. getAccessibilityMap(ac, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, false, occupyable, closest->hasFeatureOfType(StackFeature::FLYING), closest->ID);
  2303. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2304. makeBFS(closest->position, ac, predecessor, dist, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, closest->hasFeatureOfType(StackFeature::FLYING));
  2305. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2306. for(int g=0; g<BFIELD_SIZE; ++g)
  2307. {
  2308. const CStack * atG = getStackT(g);
  2309. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2310. continue;
  2311. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2312. {
  2313. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2314. continue;
  2315. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2316. }
  2317. }
  2318. if(stackPairs.size() > 0)
  2319. {
  2320. std::pair< std::pair<int, int>, const CStack *> minimalPair = stackPairs[0];
  2321. for(int b=1; b<stackPairs.size(); ++b)
  2322. {
  2323. if(stackPairs[b].first.first < minimalPair.first.first)
  2324. minimalPair = stackPairs[b];
  2325. }
  2326. return std::make_pair(minimalPair.second, predecessor[minimalPair.first.second]);
  2327. }
  2328. return std::make_pair<const CStack * , int>(NULL, -1);
  2329. }
  2330. CStack * BattleInfo::getNextStack()
  2331. {
  2332. CStack *current = getStack(activeStack);
  2333. for (unsigned int i = 0; i < stacks.size(); i++) //find fastest not moved/waited stack (stacks vector is sorted by speed)
  2334. {
  2335. if(stacks[i]->willMove() && !vstd::contains(stacks[i]->state,WAITING))
  2336. return stacks[i];
  2337. }
  2338. for (int i = stacks.size() - 1; i >= 0 ; i--) //find slowest waiting stack
  2339. {
  2340. if(stacks[i]->willMove())
  2341. return stacks[i];
  2342. }
  2343. return NULL; //all stacks moved or defending!
  2344. }
  2345. std::vector<CStack> BattleInfo::getStackQueue()
  2346. {
  2347. std::vector<CStack> ret;
  2348. std::vector<int> taken; //if non-zero value, corresponding stack has been placed in ret
  2349. taken.resize(stacks.size());
  2350. for(unsigned int g=0; g<taken.size(); ++g)
  2351. {
  2352. taken[g] = 0;
  2353. }
  2354. for(int moved=0; moved<2; ++moved) //in first cycle we add stacks that can act in current turn, in second one the rest of them
  2355. {
  2356. for(unsigned int gc=0; gc<stacks.size(); ++gc)
  2357. {
  2358. int id = -1, speed = -1;
  2359. for(unsigned int i=0; i<stacks.size(); ++i) //find not waited stacks only
  2360. {
  2361. if((moved == 1 ||!vstd::contains(stacks[i]->state, DEFENDING))
  2362. && stacks[i]->alive()
  2363. && (moved == 1 || !vstd::contains(stacks[i]->state, MOVED))
  2364. && !vstd::contains(stacks[i]->state,WAITING)
  2365. && taken[i]==0
  2366. && !stacks[i]->hasFeatureOfType(StackFeature::NOT_ACTIVE)) //eg. Ammo Cart
  2367. {
  2368. if(speed == -1 || stacks[i]->Speed() > speed)
  2369. {
  2370. id = i;
  2371. speed = stacks[i]->Speed();
  2372. }
  2373. }
  2374. }
  2375. if(id != -1)
  2376. {
  2377. ret.push_back(*stacks[id]);
  2378. taken[id] = 1;
  2379. }
  2380. else //choose something from not moved stacks
  2381. {
  2382. int id = -1, speed = 10000; //infinite speed
  2383. for(unsigned int i=0; i<stacks.size(); ++i) //find waited stacks only
  2384. {
  2385. if((moved == 1 ||!vstd::contains(stacks[i]->state, DEFENDING))
  2386. && stacks[i]->alive()
  2387. && (moved == 1 || !vstd::contains(stacks[i]->state, MOVED))
  2388. && vstd::contains(stacks[i]->state,WAITING)
  2389. && taken[i]==0
  2390. && !stacks[i]->hasFeatureOfType(StackFeature::NOT_ACTIVE)) //eg. Ammo Cart
  2391. {
  2392. if(stacks[i]->Speed() < speed) //slowest one
  2393. {
  2394. id = i;
  2395. speed = stacks[i]->Speed();
  2396. }
  2397. }
  2398. }
  2399. if(id != -1)
  2400. {
  2401. ret.push_back(*stacks[id]);
  2402. taken[id] = 1;
  2403. }
  2404. else
  2405. {
  2406. break; //no stacks have been found, so none of them will be found in next iterations
  2407. }
  2408. }
  2409. }
  2410. }
  2411. return ret;
  2412. }
  2413. int3 CPath::startPos() const
  2414. {
  2415. return nodes[nodes.size()-1].coord;
  2416. }
  2417. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2418. {
  2419. if (mode==0)
  2420. {
  2421. for (unsigned int i=0;i<nodes.size();i++)
  2422. {
  2423. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2424. }
  2425. }
  2426. }
  2427. int3 CPath::endPos() const
  2428. {
  2429. return nodes[0].coord;
  2430. }
  2431. CGPathNode::CGPathNode()
  2432. :coord(-1,-1,-1)
  2433. {
  2434. accessible = 0;
  2435. land = 0;
  2436. moveRemains = 0;
  2437. turns = 255;
  2438. theNodeBefore = NULL;
  2439. }
  2440. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2441. {
  2442. out.nodes.clear();
  2443. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2444. if(!curnode->theNodeBefore)
  2445. return false;
  2446. while(curnode->theNodeBefore)
  2447. {
  2448. out.nodes.push_back(*curnode);
  2449. curnode = curnode->theNodeBefore;
  2450. }
  2451. return true;
  2452. }
  2453. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2454. :sizes(Sizes)
  2455. {
  2456. nodes = new CGPathNode**[sizes.x];
  2457. for(int i = 0; i < sizes.x; i++)
  2458. {
  2459. nodes[i] = new CGPathNode*[sizes.y];
  2460. for (int j = 0; j < sizes.y; j++)
  2461. {
  2462. nodes[i][j] = new CGPathNode[sizes.z];
  2463. }
  2464. }
  2465. }
  2466. CPathsInfo::~CPathsInfo()
  2467. {
  2468. for(int i = 0; i < sizes.x; i++)
  2469. {
  2470. for (int j = 0; j < sizes.y; j++)
  2471. {
  2472. delete [] nodes[i][j];
  2473. }
  2474. delete [] nodes[i];
  2475. }
  2476. delete [] nodes;
  2477. }