CGameState.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970
  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 "lib/VCMI_Lib.h"
  17. #include "lib/Connection.h"
  18. #include "map.h"
  19. #include "StartInfo.h"
  20. #include "lib/NetPacks.h"
  21. #include <boost/foreach.hpp>
  22. #include <boost/thread.hpp>
  23. #include <boost/thread/shared_mutex.hpp>
  24. #include "lib/RegisterTypes.cpp"
  25. boost::rand48 ran;
  26. #ifdef min
  27. #undef min
  28. #endif
  29. #ifdef max
  30. #undef max
  31. #endif
  32. /*
  33. * CGameState.cpp, part of VCMI engine
  34. *
  35. * Authors: listed in file AUTHORS in main folder
  36. *
  37. * License: GNU General Public License v2.0 or later
  38. * Full text of license available in license.txt file, in main folder
  39. *
  40. */
  41. void foofoofoo()
  42. {
  43. //never called function to force instantation of templates
  44. int *ccc = NULL;
  45. registerTypes((CISer<CConnection>&)*ccc);
  46. registerTypes((COSer<CConnection>&)*ccc);
  47. registerTypes((CSaveFile&)*ccc);
  48. registerTypes((CLoadFile&)*ccc);
  49. registerTypes((CTypeList&)*ccc);
  50. }
  51. class CBaseForGSApply
  52. {
  53. public:
  54. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  55. };
  56. template <typename T> class CApplyOnGS : public CBaseForGSApply
  57. {
  58. public:
  59. void applyOnGS(CGameState *gs, void *pack) const
  60. {
  61. T *ptr = static_cast<T*>(pack);
  62. while(!gs->mx->try_lock())
  63. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  64. ptr->applyGs(gs);
  65. gs->mx->unlock();
  66. }
  67. };
  68. class CGSApplier
  69. {
  70. public:
  71. std::map<ui16,CBaseForGSApply*> apps;
  72. CGSApplier()
  73. {
  74. registerTypes2(*this);
  75. }
  76. template<typename T> void registerType(const T * t=NULL)
  77. {
  78. ui16 ID = typeList.registerType(t);
  79. apps[ID] = new CApplyOnGS<T>;
  80. }
  81. } *applierGs = NULL;
  82. std::string DLL_EXPORT toString(MetaString &ms)
  83. {
  84. std::string ret;
  85. for(size_t i=0;i<ms.message.size();++i)
  86. {
  87. if(ms.message[i]>0)
  88. {
  89. ret += ms.strings[ms.message[i]-1];
  90. }
  91. else
  92. {
  93. std::vector<std::string> *vec;
  94. int type = ms.texts[-ms.message[i]-1].first,
  95. ser = ms.texts[-ms.message[i]-1].second;
  96. if(type == 5)
  97. {
  98. ret += VLC->arth->artifacts[ser].Name();
  99. continue;
  100. }
  101. else if(type == 7)
  102. {
  103. ret += VLC->creh->creatures[ser].namePl;
  104. continue;
  105. }
  106. else if(type == 9)
  107. {
  108. ret += VLC->generaltexth->mines[ser].first;
  109. continue;
  110. }
  111. else if(type == 10)
  112. {
  113. ret += VLC->generaltexth->mines[ser].second;
  114. continue;
  115. }
  116. else if(type == MetaString::SPELL_NAME)
  117. {
  118. ret += VLC->spellh->spells[ser].name;
  119. continue;
  120. }
  121. else
  122. {
  123. switch(type)
  124. {
  125. case 1:
  126. vec = &VLC->generaltexth->allTexts;
  127. break;
  128. case 2:
  129. vec = &VLC->generaltexth->xtrainfo;
  130. break;
  131. case 3:
  132. vec = &VLC->generaltexth->names;
  133. break;
  134. case 4:
  135. vec = &VLC->generaltexth->restypes;
  136. break;
  137. case 6:
  138. vec = &VLC->generaltexth->arraytxt;
  139. break;
  140. case 8:
  141. vec = &VLC->generaltexth->creGens;
  142. break;
  143. case 11:
  144. vec = &VLC->generaltexth->advobtxt;
  145. break;
  146. case 12:
  147. vec = &VLC->generaltexth->artifEvents;
  148. break;
  149. }
  150. ret += (*vec)[ser];
  151. }
  152. }
  153. }
  154. for(size_t i=0; i < ms.replacements.size(); ++i)
  155. {
  156. ret.replace(ret.find("%s"),2,ms.replacements[i]);
  157. }
  158. return ret;
  159. }
  160. CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  161. {
  162. CGObjectInstance * nobj;
  163. switch(id)
  164. {
  165. case HEROI_TYPE: //hero
  166. {
  167. CGHeroInstance * nobj = new CGHeroInstance();
  168. nobj->pos = pos;
  169. nobj->tempOwner = owner;
  170. nobj->subID = subid;
  171. //nobj->initHero(ran);
  172. return nobj;
  173. }
  174. case TOWNI_TYPE: //town
  175. nobj = new CGTownInstance;
  176. break;
  177. default: //rest of objects
  178. nobj = new CGObjectInstance;
  179. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  180. break;
  181. }
  182. nobj->ID = id;
  183. nobj->subID = subid;
  184. if(!nobj->defInfo)
  185. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  186. nobj->pos = pos;
  187. //nobj->state = NULL;//new CLuaObjectScript();
  188. nobj->tempOwner = owner;
  189. nobj->info = NULL;
  190. nobj->defInfo->id = id;
  191. nobj->defInfo->subid = subid;
  192. //assigning defhandler
  193. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  194. return nobj;
  195. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  196. return nobj;
  197. }
  198. CStack * BattleInfo::getStack(int stackID)
  199. {
  200. for(int g=0; g<stacks.size(); ++g)
  201. {
  202. if(stacks[g]->ID == stackID)
  203. return stacks[g];
  204. }
  205. return NULL;
  206. }
  207. CStack * BattleInfo::getStackT(int tileID)
  208. {
  209. for(int g=0; g<stacks.size(); ++g)
  210. {
  211. if(stacks[g]->position == tileID
  212. || (stacks[g]->creature->isDoubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  213. || (stacks[g]->creature->isDoubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  214. {
  215. if(stacks[g]->alive())
  216. {
  217. return stacks[g];
  218. }
  219. }
  220. }
  221. return NULL;
  222. }
  223. void BattleInfo::getAccessibilityMap(bool *accessibility, int stackToOmmit)
  224. {
  225. memset(accessibility,1,BFIELD_SIZE); //initialize array with trues
  226. for(int g=0; g<stacks.size(); ++g)
  227. {
  228. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit) //we don't want to lock position of this stack
  229. continue;
  230. accessibility[stacks[g]->position] = false;
  231. if(stacks[g]->creature->isDoubleWide()) //if it's a double hex creature
  232. {
  233. if(stacks[g]->attackerOwned)
  234. accessibility[stacks[g]->position-1] = false;
  235. else
  236. accessibility[stacks[g]->position+1] = false;
  237. }
  238. }
  239. //obstacles
  240. for(int b=0; b<obstacles.size(); ++b)
  241. {
  242. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  243. for(int c=0; c<blocked.size(); ++c)
  244. {
  245. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  246. accessibility[blocked[c]] = false;
  247. }
  248. }
  249. }
  250. void BattleInfo::getAccessibilityMapForTwoHex(bool *accessibility, bool atackerSide, int stackToOmmit, bool addOccupiable) //send pointer to at least 187 allocated bytes
  251. {
  252. bool mac[BFIELD_SIZE];
  253. getAccessibilityMap(mac,stackToOmmit);
  254. memcpy(accessibility,mac,BFIELD_SIZE);
  255. }
  256. void BattleInfo::makeBFS(int start, bool*accessibility, int *predecessor, int *dists) //both pointers must point to the at least 187-elements int arrays
  257. {
  258. //inits
  259. for(int b=0; b<BFIELD_SIZE; ++b)
  260. predecessor[b] = -1;
  261. for(int g=0; g<BFIELD_SIZE; ++g)
  262. dists[g] = 100000000;
  263. std::queue<int> hexq; //bfs queue
  264. hexq.push(start);
  265. dists[hexq.front()] = 0;
  266. int curNext = -1; //for bfs loop only (helper var)
  267. while(!hexq.empty()) //bfs loop
  268. {
  269. int curHex = hexq.front();
  270. std::vector<int> neighbours = neighbouringTiles(curHex);
  271. hexq.pop();
  272. for(int nr=0; nr<neighbours.size(); nr++)
  273. {
  274. curNext = neighbours[nr];
  275. if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  276. continue;
  277. hexq.push(curNext);
  278. dists[curNext] = dists[curHex] + 1;
  279. predecessor[curNext] = curHex;
  280. }
  281. }
  282. };
  283. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable)
  284. {
  285. std::vector<int> ret;
  286. bool ac[BFIELD_SIZE];
  287. CStack *s = getStack(stackID);
  288. if(s->creature->isDoubleWide())
  289. getAccessibilityMapForTwoHex(ac,s->attackerOwned,stackID,addOccupiable);
  290. else
  291. getAccessibilityMap(ac,stackID);
  292. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  293. makeBFS(s->position,ac,pr,dist);
  294. if(s->creature->isDoubleWide())
  295. {
  296. if(!addOccupiable)
  297. {
  298. std::vector<int> rem;
  299. for(int b=0; b<BFIELD_SIZE; ++b)
  300. {
  301. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]))
  302. {
  303. rem.push_back(b);
  304. }
  305. }
  306. for(int g=0; g<rem.size(); ++g)
  307. {
  308. ac[rem[g]] = false;
  309. }
  310. //removing accessibility for side hexes
  311. for(int v=0; v<BFIELD_SIZE; ++v)
  312. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  313. ac[v] = false;
  314. }
  315. else
  316. {
  317. std::vector<int> rem;
  318. for(int b=0; b<BFIELD_SIZE; ++b)
  319. {
  320. if( ac[b] && (!ac[b-1] || dist[b-1] > s->Speed() ) && ( !ac[b+1] || dist[b+1] > s->Speed() ) && b%BFIELD_WIDTH != 0 && b%BFIELD_WIDTH != (BFIELD_WIDTH-1))
  321. {
  322. rem.push_back(b);
  323. }
  324. }
  325. for(int g=0; g<rem.size(); ++g)
  326. {
  327. ac[rem[g]] = false;
  328. }
  329. }
  330. }
  331. for(int i=0;i<BFIELD_SIZE;i++)
  332. if(dist[i] <= s->Speed() && ac[i])
  333. {
  334. ret.push_back(i);
  335. }
  336. return ret;
  337. }
  338. bool BattleInfo::isStackBlocked(int ID)
  339. {
  340. CStack *our = getStack(ID);
  341. for(int i=0; i<stacks.size();i++)
  342. {
  343. if( !stacks[i]->alive()
  344. || stacks[i]->owner==our->owner
  345. )
  346. continue; //we omit dead and allied stacks
  347. if(stacks[i]->creature->isDoubleWide())
  348. {
  349. if( mutualPosition(stacks[i]->position, our->position) >= 0
  350. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  351. return true;
  352. }
  353. else
  354. {
  355. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  356. return true;
  357. }
  358. }
  359. return false;
  360. }
  361. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  362. {
  363. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  364. return 0;
  365. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  366. return 1;
  367. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  368. return 5;
  369. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  370. return 2;
  371. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  372. return 4;
  373. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  374. return 3;
  375. return -1;
  376. }
  377. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  378. {
  379. #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);}
  380. std::vector<int> ret;
  381. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  382. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  383. CHECK_AND_PUSH(hex - 1);
  384. CHECK_AND_PUSH(hex + 1);
  385. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  386. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  387. #undef CHECK_AND_PUSH
  388. return ret;
  389. }
  390. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature)
  391. {
  392. int predecessor[BFIELD_SIZE]; //for getting the Path
  393. int dist[BFIELD_SIZE]; //calculated distances
  394. if(flyingCreature)
  395. {
  396. bool acc[BFIELD_SIZE]; //full accessibility table
  397. for(int b=0; b<BFIELD_SIZE; ++b) //initialization of acc
  398. {
  399. acc[b] = true;
  400. }
  401. makeBFS(start, acc, predecessor, dist);
  402. }
  403. else
  404. {
  405. makeBFS(start, accessibility, predecessor, dist);
  406. }
  407. //making the Path
  408. std::vector<int> path;
  409. int curElem = dest;
  410. while(curElem != start)
  411. {
  412. path.push_back(curElem);
  413. curElem = predecessor[curElem];
  414. }
  415. return std::make_pair(path, dist[dest]);
  416. }
  417. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  418. :ID(I), creature(C), amount(A), baseAmount(A), firstHPleft(C->hitPoints), owner(O), slot(S), attackerOwned(AO), position(-1),
  419. counterAttacks(1), shots(C->shots), state(), effects()
  420. {
  421. speed = creature->speed;
  422. abilities = C->abilities;
  423. state.insert(ALIVE);
  424. }
  425. ui32 CStack::Speed() const
  426. {
  427. int premy=0;
  428. const StackEffect *effect = 0;
  429. //haste effect check
  430. effect = getEffect(53);
  431. if(effect)
  432. premy += VLC->spellh->spells[effect->id].powers[effect->level];
  433. //slow effect check
  434. effect = getEffect(54);
  435. if(effect)
  436. premy -= (creature->speed * VLC->spellh->spells[effect->id].powers[effect->level])/100;
  437. //prayer effect check
  438. effect = getEffect(48);
  439. if(effect)
  440. premy += VLC->spellh->spells[effect->id].powers[effect->level];
  441. //bind effect check
  442. effect = getEffect(72);
  443. if(effect)
  444. {
  445. premy = creature->speed; //don't use '- creature->speed' - speed is unsigned!
  446. premy = -premy;
  447. }
  448. return speed + premy;
  449. }
  450. const CStack::StackEffect * CStack::getEffect(ui16 id) const
  451. {
  452. for (int i=0; i< effects.size(); i++)
  453. if(effects[i].id == id)
  454. return &effects[i];
  455. return NULL;
  456. }
  457. si8 CStack::Morale() const
  458. {
  459. si8 ret = morale;
  460. if(getEffect(49)) //mirth
  461. {
  462. ret += VLC->spellh->spells[49].powers[getEffect(49)->level];
  463. }
  464. if(getEffect(50)) //sorrow
  465. {
  466. ret -= VLC->spellh->spells[50].powers[getEffect(50)->level];
  467. }
  468. if(ret > 3) ret = 3;
  469. if(ret < -3) ret = -3;
  470. return ret;
  471. }
  472. si8 CStack::Luck() const
  473. {
  474. si8 ret = luck;
  475. if(getEffect(51)) //fortune
  476. {
  477. ret += VLC->spellh->spells[51].powers[getEffect(51)->level];
  478. }
  479. if(getEffect(52)) //misfortune
  480. {
  481. ret -= VLC->spellh->spells[52].powers[getEffect(52)->level];
  482. }
  483. if(ret > 3) ret = 3;
  484. if(ret < -3) ret = -3;
  485. return ret;
  486. }
  487. bool CStack::willMove()
  488. {
  489. return !vstd::contains(state,DEFENDING)
  490. && !vstd::contains(state,MOVED)
  491. && alive()
  492. && !vstd::contains(abilities,NOT_ACTIVE); //eg. Ammo Cart
  493. }
  494. CGHeroInstance* CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, int notThatOne)
  495. {
  496. if(player<0 || player>=PLAYER_LIMIT)
  497. {
  498. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  499. return NULL;
  500. }
  501. std::vector<CGHeroInstance *> pool;
  502. int sum=0, r;
  503. if(native)
  504. {
  505. for(std::map<ui32,CGHeroInstance *>::iterator i=heroesPool.begin(); i!=heroesPool.end(); i++)
  506. {
  507. if(pavailable[i->first] & 1<<player
  508. && i->second->type->heroType/2 == town->typeID
  509. && i->second->subID != notThatOne
  510. )
  511. {
  512. pool.push_back(i->second);
  513. }
  514. }
  515. if(!pool.size())
  516. return pickHeroFor(false,player,town,notThatOne);
  517. else
  518. return pool[rand()%pool.size()];
  519. }
  520. else
  521. {
  522. for(std::map<ui32,CGHeroInstance *>::iterator i=heroesPool.begin(); i!=heroesPool.end(); i++)
  523. {
  524. if(pavailable[i->first] & 1<<player
  525. && i->second->subID != notThatOne
  526. )
  527. {
  528. pool.push_back(i->second);
  529. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  530. }
  531. }
  532. if(!pool.size())
  533. {
  534. tlog1 << "There are no heroes available for player " << player<<"!\n";
  535. return NULL;
  536. }
  537. r = rand()%sum;
  538. for(int i=0; i<pool.size(); i++)
  539. {
  540. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  541. if(r<0)
  542. return pool[i];
  543. }
  544. return pool[pool.size()-1];
  545. }
  546. }
  547. //void CGameState::apply(CPack * pack)
  548. //{
  549. // while(!mx->try_lock())
  550. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  551. // //applyNL(pack);
  552. // mx->unlock();
  553. //}
  554. int CGameState::pickHero(int owner)
  555. {
  556. int h=-1;
  557. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  558. return h;
  559. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  560. int i=0;
  561. do //try to find free hero of our faction
  562. {
  563. i++;
  564. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  565. } while( map->getHero(h) && i<175);
  566. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  567. {
  568. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  569. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  570. if(!map->getHero(j))
  571. h=j;
  572. }
  573. return h;
  574. }
  575. CGHeroInstance *CGameState::getHero(int objid)
  576. {
  577. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=34)
  578. return NULL;
  579. return static_cast<CGHeroInstance *>(map->objects[objid]);
  580. }
  581. CGTownInstance *CGameState::getTown(int objid)
  582. {
  583. if(objid<0 || objid>=map->objects.size())
  584. return NULL;
  585. return static_cast<CGTownInstance *>(map->objects[objid]);
  586. }
  587. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  588. {
  589. switch(obj->ID)
  590. {
  591. case 65: //random artifact
  592. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  593. case 66: //random treasure artifact
  594. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  595. case 67: //random minor artifact
  596. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  597. case 68: //random major artifact
  598. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  599. case 69: //random relic artifact
  600. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  601. case 70: //random hero
  602. {
  603. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  604. }
  605. case 71: //random monster
  606. {
  607. int r;
  608. do
  609. {
  610. r = ran()%197;
  611. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  612. return std::pair<int,int>(54,r);
  613. }
  614. case 72: //random monster lvl1
  615. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  616. case 73: //random monster lvl2
  617. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  618. case 74: //random monster lvl3
  619. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  620. case 75: //random monster lvl4
  621. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  622. case 76: //random resource
  623. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  624. case 77: //random town
  625. {
  626. int align = ((CGTownInstance*)obj)->alignment,
  627. f;
  628. if(align>PLAYER_LIMIT-1)//same as owner / random
  629. {
  630. if(obj->tempOwner > PLAYER_LIMIT-1)
  631. f = -1; //random
  632. else
  633. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  634. }
  635. else
  636. {
  637. f = scenarioOps->getIthPlayersSettings(align).castle;
  638. }
  639. if(f<0) f = ran()%VLC->townh->towns.size();
  640. return std::pair<int,int>(TOWNI_TYPE,f);
  641. }
  642. case 162: //random monster lvl5
  643. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  644. case 163: //random monster lvl6
  645. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  646. case 164: //random monster lvl7
  647. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  648. case 216: //random dwelling
  649. {
  650. int faction = ran()%F_NUMBER;
  651. CCreGen2ObjInfo* info =(CCreGen2ObjInfo*)obj->info;
  652. if (info->asCastle)
  653. {
  654. for(int i=0;i<map->objects.size();i++)
  655. {
  656. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  657. {
  658. randomizeObject(map->objects[i]); //we have to randomize the castle first
  659. faction = map->objects[i]->subID;
  660. break;
  661. }
  662. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  663. {
  664. faction = map->objects[i]->subID;
  665. break;
  666. }
  667. }
  668. }
  669. else
  670. {
  671. while((!(info->castles[0]&(1<<faction))))
  672. {
  673. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  674. break;
  675. faction = ran()%F_NUMBER;
  676. }
  677. }
  678. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  679. int cid = VLC->townh->towns[faction].basicCreatures[level];
  680. for(int i=0;i<VLC->objh->cregens.size();i++)
  681. if(VLC->objh->cregens[i]==cid)
  682. return std::pair<int,int>(17,i);
  683. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  684. return std::pair<int,int>(17,0);
  685. }
  686. case 217:
  687. {
  688. int faction = ran()%F_NUMBER;
  689. CCreGenObjInfo* info =(CCreGenObjInfo*)obj->info;
  690. if (info->asCastle)
  691. {
  692. for(int i=0;i<map->objects.size();i++)
  693. {
  694. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  695. {
  696. randomizeObject(map->objects[i]); //we have to randomize the castle first
  697. faction = map->objects[i]->subID;
  698. break;
  699. }
  700. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  701. {
  702. faction = map->objects[i]->subID;
  703. break;
  704. }
  705. }
  706. }
  707. else
  708. {
  709. while((!(info->castles[0]&(1<<faction))))
  710. {
  711. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  712. break;
  713. faction = ran()%F_NUMBER;
  714. }
  715. }
  716. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  717. for(int i=0;i<VLC->objh->cregens.size();i++)
  718. if(VLC->objh->cregens[i]==cid)
  719. return std::pair<int,int>(17,i);
  720. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  721. return std::pair<int,int>(17,0);
  722. }
  723. case 218:
  724. {
  725. CCreGen3ObjInfo* info =(CCreGen3ObjInfo*)obj->info;
  726. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  727. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  728. for(int i=0;i<VLC->objh->cregens.size();i++)
  729. if(VLC->objh->cregens[i]==cid)
  730. return std::pair<int,int>(17,i);
  731. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  732. return std::pair<int,int>(17,0);
  733. }
  734. }
  735. return std::pair<int,int>(-1,-1);
  736. }
  737. void CGameState::randomizeObject(CGObjectInstance *cur)
  738. {
  739. std::pair<int,int> ran = pickObject(cur);
  740. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  741. {
  742. if(cur->ID==TOWNI_TYPE) //town - set def
  743. {
  744. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  745. if(t->hasCapitol())
  746. t->defInfo = capitols[t->subID];
  747. else if(t->hasFort())
  748. t->defInfo = forts[t->subID];
  749. else
  750. t->defInfo = villages[t->subID];
  751. }
  752. return;
  753. }
  754. else if(ran.first==HEROI_TYPE)//special code for hero
  755. {
  756. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  757. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  758. cur->ID = ran.first;
  759. h->portrait = cur->subID = ran.second;
  760. h->type = VLC->heroh->heroes[ran.second];
  761. map->heroes.push_back(h);
  762. return; //TODO: maybe we should do something with definfo?
  763. }
  764. else if(ran.first==TOWNI_TYPE)//special code for town
  765. {
  766. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  767. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  768. cur->ID = ran.first;
  769. cur->subID = ran.second;
  770. t->town = &VLC->townh->towns[ran.second];
  771. if(t->hasCapitol())
  772. t->defInfo = capitols[t->subID];
  773. else if(t->hasFort())
  774. t->defInfo = forts[t->subID];
  775. else
  776. t->defInfo = villages[t->subID];
  777. map->towns.push_back(t);
  778. return;
  779. }
  780. //we have to replace normal random object
  781. cur->ID = ran.first;
  782. cur->subID = ran.second;
  783. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  784. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  785. if(!cur->defInfo)
  786. {
  787. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  788. return;
  789. }
  790. map->addBlockVisTiles(cur);
  791. }
  792. int CGameState::getDate(int mode) const
  793. {
  794. int temp;
  795. switch (mode)
  796. {
  797. case 0:
  798. return day;
  799. break;
  800. case 1:
  801. temp = (day)%7;
  802. if (temp)
  803. return temp;
  804. else return 7;
  805. break;
  806. case 2:
  807. temp = ((day-1)/7)+1;
  808. if (!(temp%4))
  809. return 4;
  810. else
  811. return (temp%4);
  812. break;
  813. case 3:
  814. return ((day-1)/28)+1;
  815. break;
  816. }
  817. return 0;
  818. }
  819. CGameState::CGameState()
  820. {
  821. mx = new boost::shared_mutex();
  822. map = NULL;
  823. curB = NULL;
  824. scenarioOps = NULL;
  825. applierGs = new CGSApplier;
  826. }
  827. CGameState::~CGameState()
  828. {
  829. delete mx;
  830. delete map;
  831. delete curB;
  832. delete scenarioOps;
  833. delete applierGs;
  834. }
  835. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  836. {
  837. day = 0;
  838. seed = Seed;
  839. ran.seed((boost::int32_t)seed);
  840. scenarioOps = si;
  841. this->map = map;
  842. loadTownDInfos();
  843. //picking random factions for players
  844. for(int i=0;i<scenarioOps->playerInfos.size();i++)
  845. {
  846. if(scenarioOps->playerInfos[i].castle==-1)
  847. {
  848. int f;
  849. do
  850. {
  851. f = ran()%F_NUMBER;
  852. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  853. scenarioOps->playerInfos[i].castle = f;
  854. }
  855. }
  856. //randomizing objects
  857. for(int no=0; no<map->objects.size(); ++no)
  858. {
  859. randomizeObject(map->objects[no]);
  860. if(map->objects[no]->ID==26)
  861. {
  862. map->objects[no]->defInfo->handler=NULL;
  863. }
  864. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  865. }
  866. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  867. /*********give starting hero****************************************/
  868. for(int i=0;i<PLAYER_LIMIT;i++)
  869. {
  870. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==RoE))
  871. {
  872. int3 hpos = map->players[i].posOfMainTown;
  873. hpos.x+=1;// hpos.y+=1;
  874. int j;
  875. for(j=0; j<scenarioOps->playerInfos.size(); j++)
  876. if(scenarioOps->playerInfos[j].color == i)
  877. break;
  878. if(j == scenarioOps->playerInfos.size())
  879. continue;
  880. int h=pickHero(i);
  881. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  882. nnn->id = map->objects.size();
  883. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  884. for(int o=0;o<map->towns.size();o++) //find main town
  885. {
  886. if(map->towns[o]->pos == hpos)
  887. {
  888. map->towns[o]->visitingHero = nnn;
  889. nnn->visitedTown = map->towns[o];
  890. nnn->inTownGarrison = false;
  891. break;
  892. }
  893. }
  894. nnn->initHero();
  895. map->heroes.push_back(nnn);
  896. map->objects.push_back(nnn);
  897. map->addBlockVisTiles(nnn);
  898. }
  899. }
  900. /*********creating players entries in gs****************************************/
  901. for (int i=0; i<scenarioOps->playerInfos.size();i++)
  902. {
  903. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  904. ins.second.color=ins.first;
  905. ins.second.serial=i;
  906. ins.second.human = scenarioOps->playerInfos[i].human;
  907. players.insert(ins);
  908. }
  909. /******************RESOURCES****************************************************/
  910. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  911. std::vector<int> startres;
  912. std::ifstream tis("config/startres.txt");
  913. int k;
  914. for (int j=0;j<scenarioOps->difficulty;j++)
  915. {
  916. tis >> k;
  917. for (int z=0;z<RESOURCE_QUANTITY;z++)
  918. tis>>k;
  919. }
  920. tis >> k;
  921. for (int i=0;i<RESOURCE_QUANTITY;i++)
  922. {
  923. tis >> k;
  924. startres.push_back(k);
  925. }
  926. tis.close();
  927. tis.clear();
  928. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  929. {
  930. (*i).second.resources.resize(RESOURCE_QUANTITY);
  931. for (int x=0;x<RESOURCE_QUANTITY;x++)
  932. (*i).second.resources[x] = startres[x];
  933. }
  934. tis.open("config/resources.txt");
  935. tis >> k;
  936. int pom;
  937. for(int i=0;i<k;i++)
  938. {
  939. tis >> pom;
  940. resVals.push_back(pom);
  941. }
  942. /*************************HEROES************************************************/
  943. std::set<int> hids;
  944. for(int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  945. if(map->allowedHeroes[i])
  946. hids.insert(i);
  947. for (int i=0; i<map->heroes.size();i++) //heroes instances initialization
  948. {
  949. if (map->heroes[i]->getOwner()<0)
  950. {
  951. tlog2 << "Warning - hero with uninitialized owner!\n";
  952. continue;
  953. }
  954. CGHeroInstance * vhi = (map->heroes[i]);
  955. vhi->initHero();
  956. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  957. hids.erase(vhi->subID);
  958. }
  959. for(int i=0; i<map->predefinedHeroes.size(); i++)
  960. {
  961. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  962. continue;
  963. map->predefinedHeroes[i]->initHero();
  964. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  965. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  966. hids.erase(map->predefinedHeroes[i]->subID);
  967. }
  968. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  969. {
  970. CGHeroInstance * vhi = new CGHeroInstance();
  971. vhi->initHero(hid);
  972. hpool.heroesPool[hid] = vhi;
  973. hpool.pavailable[hid] = 0xff;
  974. }
  975. for(int i=0; i<map->disposedHeroes.size(); i++)
  976. {
  977. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  978. }
  979. /*************************FOG**OF**WAR******************************************/
  980. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  981. {
  982. k->second.fogOfWarMap.resize(map->width);
  983. for(int g=0; g<map->width; ++g)
  984. k->second.fogOfWarMap[g].resize(map->height);
  985. for(int g=-0; g<map->width; ++g)
  986. for(int h=0; h<map->height; ++h)
  987. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  988. for(int g=0; g<map->width; ++g)
  989. for(int h=0; h<map->height; ++h)
  990. for(int v=0; v<map->twoLevel+1; ++v)
  991. k->second.fogOfWarMap[g][h][v] = 0;
  992. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  993. {
  994. if(obj->tempOwner != k->first) continue; //not a flagged object
  995. int3 objCenter = obj->getSightCenter();
  996. int radious = obj->getSightRadious();
  997. for (int xd = std::max<int>(objCenter.x - radious , 0); xd <= std::min<int>(objCenter.x + radious, map->width - 1); xd++)
  998. {
  999. for (int yd = std::max<int>(objCenter.y - radious, 0); yd <= std::min<int>(objCenter.y + radious, map->height - 1); yd++)
  1000. {
  1001. double distance = objCenter.dist2d(int3(xd,yd,objCenter.z)) - 0.5;
  1002. if(distance <= radious)
  1003. k->second.fogOfWarMap[xd][yd][objCenter.z] = 1;
  1004. }
  1005. }
  1006. }
  1007. //for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1008. //{
  1009. // for(int yd=0; yd<map->height; ++yd)
  1010. // {
  1011. // for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1012. // {
  1013. // int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1014. // int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1015. // if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1016. // k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1017. // }
  1018. // }
  1019. //}
  1020. //starting bonus
  1021. if(si->playerInfos[k->second.serial].bonus==brandom)
  1022. si->playerInfos[k->second.serial].bonus = ran()%3;
  1023. switch(si->playerInfos[k->second.serial].bonus)
  1024. {
  1025. case bgold:
  1026. k->second.resources[6] += 500 + (ran()%6)*100;
  1027. break;
  1028. case bresource:
  1029. {
  1030. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1031. if(res == 127)
  1032. {
  1033. k->second.resources[0] += 5 + ran()%6;
  1034. k->second.resources[2] += 5 + ran()%6;
  1035. }
  1036. else
  1037. {
  1038. k->second.resources[res] += 3 + ran()%4;
  1039. }
  1040. break;
  1041. }
  1042. case bartifact:
  1043. {
  1044. if(!k->second.heroes.size())
  1045. {
  1046. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1047. break;
  1048. }
  1049. CArtifact *toGive;
  1050. do
  1051. {
  1052. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1053. } while (!map->allowedArtifact[toGive->id]);
  1054. CGHeroInstance *hero = k->second.heroes[0];
  1055. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1056. if(slot!=toGive->possibleSlots.end())
  1057. hero->artifWorn[*slot] = toGive->id;
  1058. else
  1059. hero->artifacts.push_back(toGive->id);
  1060. }
  1061. }
  1062. }
  1063. /****************************TOWNS************************************************/
  1064. for (int i=0;i<map->towns.size();i++)
  1065. {
  1066. CGTownInstance * vti =(map->towns[i]);
  1067. if(!vti->town)
  1068. vti->town = &VLC->townh->towns[vti->subID];
  1069. if (vti->name.length()==0) // if town hasn't name we draw it
  1070. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1071. //init buildings
  1072. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1073. {
  1074. vti->builtBuildings.erase(-50);
  1075. vti->builtBuildings.insert(10);
  1076. vti->builtBuildings.insert(5);
  1077. vti->builtBuildings.insert(30);
  1078. if(ran()%2)
  1079. vti->builtBuildings.insert(31);
  1080. }
  1081. //init spells
  1082. vti->spells.resize(SPELL_LEVELS);
  1083. CSpell *s;
  1084. for(int z=0; z<vti->obligatorySpells.size();z++)
  1085. {
  1086. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1087. vti->spells[s->level-1].push_back(s->id);
  1088. vti->possibleSpells -= s->id;
  1089. }
  1090. while(vti->possibleSpells.size())
  1091. {
  1092. ui32 total=0, sel=-1;
  1093. for(int ps=0;ps<vti->possibleSpells.size();ps++)
  1094. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1095. int r = (total)? ran()%total : -1;
  1096. for(int ps=0; ps<vti->possibleSpells.size();ps++)
  1097. {
  1098. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1099. if(r<0)
  1100. {
  1101. sel = ps;
  1102. break;
  1103. }
  1104. }
  1105. if(sel<0)
  1106. sel=0;
  1107. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1108. vti->spells[s->level-1].push_back(s->id);
  1109. vti->possibleSpells -= s->id;
  1110. }
  1111. //init garrisons
  1112. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1113. {
  1114. if(j->second.first > 196 && j->second.first < 211)
  1115. {
  1116. if(j->second.first%2)
  1117. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1118. else
  1119. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1120. }
  1121. }
  1122. if(vti->getOwner() != 255)
  1123. getPlayer(vti->getOwner())->towns.push_back(vti);
  1124. }
  1125. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1126. {
  1127. if(k->first==-1 || k->first==255)
  1128. continue;
  1129. // for(int xd=0; xd<map->width; ++xd) //revealing part of map around towns
  1130. // {
  1131. // for(int yd=0; yd<map->height; ++yd)
  1132. // {
  1133. // for(int ch=0; ch<k->second.towns.size(); ++ch)
  1134. // {
  1135. // int deltaX = (k->second.towns[ch]->pos.x-xd)*(k->second.towns[ch]->pos.x-xd);
  1136. // int deltaY = (k->second.towns[ch]->pos.y-yd)*(k->second.towns[ch]->pos.y-yd);
  1137. // if(deltaX+deltaY<k->second.towns[ch]->getSightDistance()*k->second.towns[ch]->getSightDistance())
  1138. // k->second.fogOfWarMap[xd][yd][k->second.towns[ch]->pos.z] = 1;
  1139. // }
  1140. // }
  1141. // }
  1142. //init visiting and garrisoned heroes
  1143. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1144. {
  1145. for(unsigned int m=0; m<k->second.towns.size();m++)
  1146. {
  1147. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1148. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1149. {
  1150. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1151. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1152. k->second.heroes[l]->inTownGarrison = false;
  1153. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1154. k->second.heroes[l]->pos.x -= 1;
  1155. break;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. for(int i=0; i<map->defy.size(); i++)
  1161. {
  1162. map->defy[i]->serial = i;
  1163. }
  1164. for(int i=0; i<map->objects.size(); i++)
  1165. {
  1166. map->objects[i]->initObj();
  1167. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1168. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1169. }
  1170. }
  1171. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1172. {
  1173. return true;
  1174. }
  1175. int CGameState::battleGetStack(int pos)
  1176. {
  1177. if(!curB)
  1178. return -1;
  1179. for(int g=0; g<curB->stacks.size(); ++g)
  1180. {
  1181. if((curB->stacks[g]->position == pos
  1182. || (curB->stacks[g]->creature->isDoubleWide()
  1183. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1184. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1185. ))
  1186. && curB->stacks[g]->alive()
  1187. )
  1188. return curB->stacks[g]->ID;
  1189. }
  1190. return -1;
  1191. }
  1192. int CGameState::battleGetBattlefieldType(int3 tile)
  1193. {
  1194. if(tile==int3() && curB)
  1195. tile = curB->tile;
  1196. else if(tile==int3() && !curB)
  1197. return -1;
  1198. //std::vector < std::pair<const CGObjectInstance*,SDL_Rect> > & objs = CGI->mh->ttiles[tile.x][tile.y][tile.z].objects;
  1199. //for(int g=0; g<objs.size(); ++g)
  1200. //{
  1201. // switch(objs[g].first->ID)
  1202. // {
  1203. // case 222: //clover field
  1204. // return 19;
  1205. // case 223: //cursed ground
  1206. // return 22;
  1207. // case 224: //evil fog
  1208. // return 20;
  1209. // case 225: //favourable winds
  1210. // return 21;
  1211. // case 226: //fiery fields
  1212. // return 14;
  1213. // case 227: //holy ground
  1214. // return 18;
  1215. // case 228: //lucid pools
  1216. // return 17;
  1217. // case 229: //magic clouds
  1218. // return 16;
  1219. // case 230: //magic plains
  1220. // return 9;
  1221. // case 231: //rocklands
  1222. // return 15;
  1223. // }
  1224. //}
  1225. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1226. {
  1227. case dirt:
  1228. return rand()%3+3;
  1229. case sand:
  1230. return 2; //TODO: coast support
  1231. case grass:
  1232. return rand()%2+6;
  1233. case snow:
  1234. return rand()%2+10;
  1235. case swamp:
  1236. return 13;
  1237. case rough:
  1238. return 23;
  1239. case subterranean:
  1240. return 12;
  1241. case lava:
  1242. return 8;
  1243. case water:
  1244. return 25;
  1245. case rock:
  1246. return 15;
  1247. default:
  1248. return -1;
  1249. }
  1250. }
  1251. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1252. {
  1253. UpgradeInfo ret;
  1254. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1255. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1256. {
  1257. CGTownInstance * t;
  1258. if(obj->ID == TOWNI_TYPE)
  1259. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1260. else
  1261. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1262. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1263. {
  1264. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1265. {
  1266. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1267. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1268. {
  1269. ret.newID.push_back(nid);
  1270. ret.cost.push_back(std::set<std::pair<int,int> >());
  1271. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1272. {
  1273. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1274. if(dif)
  1275. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1276. }
  1277. }
  1278. }
  1279. }//end for
  1280. }
  1281. //TODO: check if hero ability makes some upgrades possible
  1282. if(ret.newID.size())
  1283. ret.oldID = base->idNumber;
  1284. return ret;
  1285. }
  1286. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1287. {
  1288. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1289. if(mode) return -1; //todo - support other modes
  1290. int mcount = 0;
  1291. for(int i=0;i<getPlayer(player)->towns.size();i++)
  1292. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1293. mcount++;
  1294. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1295. return ret;
  1296. }
  1297. void CGameState::loadTownDInfos()
  1298. {
  1299. for(int i=0;i<F_NUMBER;i++)
  1300. {
  1301. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1302. forts[i] = VLC->dobjinfo->castles[i];
  1303. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1304. }
  1305. }
  1306. void CGameState::getNeighbours(int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand)
  1307. {
  1308. vec.clear();
  1309. int3 hlp;
  1310. bool weAreOnLand = (map->getTile(tile).tertype != 8);
  1311. if(tile.x > 0)
  1312. {
  1313. hlp = int3(tile.x-1,tile.y,tile.z);
  1314. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1315. vec.push_back(hlp);
  1316. }
  1317. if(tile.y > 0)
  1318. {
  1319. hlp = int3(tile.x,tile.y-1,tile.z);
  1320. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1321. vec.push_back(hlp);
  1322. }
  1323. if(tile.x > 0 && tile.y > 0)
  1324. {
  1325. hlp = int3(tile.x-1,tile.y-1,tile.z);
  1326. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1327. vec.push_back(hlp);
  1328. }
  1329. if(tile.x > 0 && tile.y < map->height-1)
  1330. {
  1331. hlp = int3(tile.x-1,tile.y+1,tile.z);
  1332. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1333. vec.push_back(hlp);
  1334. }
  1335. if(tile.y < map->height-1)
  1336. {
  1337. hlp = int3(tile.x,tile.y+1,tile.z);
  1338. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1339. vec.push_back(hlp);
  1340. }
  1341. if(tile.x < map->width-1)
  1342. {
  1343. hlp = int3(tile.x+1,tile.y,tile.z);
  1344. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1345. vec.push_back(hlp);
  1346. }
  1347. if(tile.x < map->width-1 && tile.y > 0)
  1348. {
  1349. hlp = int3(tile.x+1,tile.y-1,tile.z);
  1350. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1351. vec.push_back(hlp);
  1352. }
  1353. if(tile.x < map->width-1 && tile.y < map->height-1)
  1354. {
  1355. hlp = int3(tile.x+1,tile.y+1,tile.z);
  1356. if((weAreOnLand == (map->getTile(hlp).tertype!=8)) && map->getTile(hlp).tertype!=9)
  1357. vec.push_back(hlp);
  1358. }
  1359. }
  1360. int CGameState::getMovementCost(const CGHeroInstance *h, int3 src, int3 dest, int remainingMovePoints, bool checkLast)
  1361. {
  1362. if(src == dest) //same tile
  1363. return 0;
  1364. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1365. &d = map->terrain[dest.x][dest.y][dest.z];
  1366. //get basic cost
  1367. int ret = h->getTileCost(d,s);
  1368. if(src.x!=dest.x && src.y!=dest.y) //it's diagonal move
  1369. {
  1370. int old = ret;
  1371. ret *= 1.414;
  1372. //diagonal move costs too much but normal move is possible - allow diagonal move
  1373. if(ret > remainingMovePoints && remainingMovePoints > old)
  1374. {
  1375. return remainingMovePoints;
  1376. }
  1377. }
  1378. int left = remainingMovePoints-ret;
  1379. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1380. {
  1381. std::vector<int3> vec;
  1382. getNeighbours(dest,vec,true);
  1383. for(size_t i=0; i < vec.size(); i++)
  1384. {
  1385. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1386. if(fcost <= left)
  1387. {
  1388. return ret;
  1389. }
  1390. }
  1391. ret = remainingMovePoints;
  1392. }
  1393. return ret;
  1394. }
  1395. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1396. {
  1397. int ret = 7; //allowed by default
  1398. //checking resources
  1399. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1400. for(int res=0;res<7;res++) //TODO: support custom amount of resources
  1401. {
  1402. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1403. ret = 6; //lack of res
  1404. }
  1405. //checking for requirements
  1406. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][ID].begin();
  1407. ri != VLC->townh->requirements[t->subID][ID].end();
  1408. ri++ )
  1409. {
  1410. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1411. ret = 8; //lack of requirements - cannot build
  1412. }
  1413. //can we build it?
  1414. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1415. ret = 2; //forbidden
  1416. else if(t->builded >= MAX_BUILDING_PER_TURN)
  1417. ret = 5; //building limit
  1418. if(ID == 13) //capitol
  1419. {
  1420. for(int in = 0; in < map->towns.size(); in++)
  1421. {
  1422. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1423. {
  1424. ret = 0; //no more than one capitol
  1425. break;
  1426. }
  1427. }
  1428. }
  1429. else if(ID == 6) //shipyard
  1430. {
  1431. if(map->getTile(t->pos + int3(-1,3,0)).tertype != water && map->getTile(t->pos + int3(-3,3,0)).tertype != water)
  1432. ret = 1; //lack of water
  1433. }
  1434. return ret;
  1435. }
  1436. void CGameState::apply(CPack *pack)
  1437. {
  1438. applierGs->apps[typeList.getTypeID(pack)]->applyOnGS(this,pack);
  1439. }
  1440. PlayerState * CGameState::getPlayer( ui8 color )
  1441. {
  1442. if(vstd::contains(players,color))
  1443. {
  1444. return &players[color];
  1445. }
  1446. else
  1447. {
  1448. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1449. return NULL;
  1450. }
  1451. }
  1452. CPath * CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero)
  1453. {
  1454. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1455. return NULL;
  1456. int3 hpos = hero->getPosition(false);
  1457. tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1458. if (!hero->canWalkOnSea())
  1459. blockLandSea = (map->getTile(hpos).tertype != water); //block land if hero is on water and vice versa
  1460. else
  1461. blockLandSea = boost::logic::indeterminate;
  1462. //graph initialization
  1463. std::vector< std::vector<CPathNode> > graph;
  1464. graph.resize(map->width);
  1465. for(size_t i=0; i<graph.size(); ++i)
  1466. {
  1467. graph[i].resize(map->height);
  1468. for(size_t j=0; j<graph[i].size(); ++j)
  1469. {
  1470. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1471. CPathNode &node = graph[i][j];
  1472. node.accesible = !tinfo->blocked;
  1473. if(i==dest.x && j==dest.y && tinfo->visitable)
  1474. {
  1475. node.accesible = true; //for allowing visiting objects
  1476. }
  1477. node.dist = -1;
  1478. node.theNodeBefore = NULL;
  1479. node.visited = false;
  1480. node.coord.x = i;
  1481. node.coord.y = j;
  1482. node.coord.z = dest.z;
  1483. if ((tinfo->tertype == rock) //it's rock
  1484. || ((blockLandSea) && (tinfo->tertype == water)) //it's sea and we cannot walk on sea
  1485. || ((!blockLandSea) && (tinfo->tertype != water)) //it's land and we cannot walk on land
  1486. || !getPlayer(hero->tempOwner)->fogOfWarMap[i][j][src.z] //tile is covered by the FoW
  1487. )
  1488. {
  1489. node.accesible = false;
  1490. }
  1491. }
  1492. }
  1493. //graph initialized
  1494. //initial tile - set cost on 0 and add to the queue
  1495. graph[src.x][src.y].dist = 0;
  1496. std::queue<CPathNode> mq;
  1497. mq.push(graph[src.x][src.y]);
  1498. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1499. std::vector<int3> neighbours;
  1500. neighbours.reserve(8);
  1501. while(!mq.empty())
  1502. {
  1503. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1504. mq.pop();
  1505. if (cp.coord == dest) //it's destination tile
  1506. {
  1507. if (cp.dist < curDist) //that path is better than previous one
  1508. curDist = cp.dist;
  1509. continue;
  1510. }
  1511. else
  1512. {
  1513. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1514. continue;
  1515. }
  1516. //add accessible neighbouring nodes to the queue
  1517. getNeighbours(cp.coord,neighbours,blockLandSea);
  1518. for(int i=0; i < neighbours.size(); i++)
  1519. {
  1520. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1521. if(dp.accesible)
  1522. {
  1523. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1524. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accesible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1525. {
  1526. dp.dist = cp.dist + cost;
  1527. dp.theNodeBefore = &cp;
  1528. mq.push(dp);
  1529. }
  1530. }
  1531. }
  1532. }
  1533. CPathNode *curNode = &graph[dest.x][dest.y];
  1534. if(!curNode->theNodeBefore) //destination is not accessible
  1535. return NULL;
  1536. CPath * ret = new CPath;
  1537. while(curNode->coord != graph[src.x][src.y].coord)
  1538. {
  1539. ret->nodes.push_back(*curNode);
  1540. curNode = curNode->theNodeBefore;
  1541. }
  1542. ret->nodes.push_back(graph[src.x][src.y]);
  1543. return ret;
  1544. }
  1545. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1546. {
  1547. const TerrainTile * pom = &map->getTile(dst);
  1548. for(int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1549. {
  1550. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1551. continue;
  1552. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1553. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1554. {
  1555. return false;
  1556. }
  1557. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1558. {
  1559. return false;
  1560. }
  1561. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1562. {
  1563. return false;
  1564. }
  1565. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1566. {
  1567. return false;
  1568. }
  1569. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1570. {
  1571. return false;
  1572. }
  1573. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1574. {
  1575. return false;
  1576. }
  1577. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1578. {
  1579. return false;
  1580. }
  1581. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1582. {
  1583. return false;
  1584. }
  1585. }
  1586. return true;
  1587. }
  1588. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting)
  1589. {
  1590. int attackerAttackBonus = attacker->creature->attack + (attackerHero ? attackerHero->getPrimSkillLevel(0) : 0),
  1591. defenderDefenseBonus = defender->creature->defence + (defendingHero ? defendingHero->getPrimSkillLevel(1) : 0),
  1592. attackDefenseBonus = 0,
  1593. minDmg = attacker->creature->damageMin * attacker->amount,
  1594. maxDmg = attacker->creature->damageMax * attacker->amount;
  1595. //calculating total attack/defense skills modifier
  1596. if(attacker->getEffect(56)) //frenzy for attacker
  1597. {
  1598. attackerAttackBonus += (VLC->spellh->spells[attacker->getEffect(56)->id].powers[attacker->getEffect(56)->level]/100.0) *(attacker->creature->defence + (attackerHero ? attackerHero->getPrimSkillLevel(1) : 0));
  1599. }
  1600. if(defender->getEffect(56)) //frenzy for defender
  1601. {
  1602. defenderDefenseBonus = 0;
  1603. }
  1604. attackDefenseBonus = attackerAttackBonus - defenderDefenseBonus;
  1605. if(defender->getEffect(48)) //defender's prayer handling
  1606. {
  1607. attackDefenseBonus -= VLC->spellh->spells[defender->getEffect(48)->id].powers[defender->getEffect(48)->level];
  1608. }
  1609. if(attacker->getEffect(48)) //attacker's prayer handling
  1610. {
  1611. attackDefenseBonus += VLC->spellh->spells[attacker->getEffect(48)->id].powers[attacker->getEffect(48)->level];
  1612. }
  1613. if(defender->getEffect(46)) //stone skin handling
  1614. {
  1615. attackDefenseBonus -= VLC->spellh->spells[defender->getEffect(46)->id].powers[defender->getEffect(46)->level];
  1616. }
  1617. if(attacker->getEffect(45)) //weakness handling
  1618. {
  1619. attackDefenseBonus -= VLC->spellh->spells[attacker->getEffect(45)->id].powers[attacker->getEffect(45)->level];
  1620. }
  1621. if(!shooting && attacker->getEffect(43)) //bloodlust handling
  1622. {
  1623. attackDefenseBonus += VLC->spellh->spells[attacker->getEffect(43)->id].powers[attacker->getEffect(43)->level];
  1624. }
  1625. float dmgBonusMultiplier = 1.0f;
  1626. //bonus from attack/defense skills
  1627. if(attackDefenseBonus < 0) //decreasing dmg
  1628. {
  1629. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1630. {
  1631. dmgBonusMultiplier += -0.3f;
  1632. }
  1633. else
  1634. {
  1635. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1636. }
  1637. }
  1638. else //increasing dmg
  1639. {
  1640. if(0.05f * attackDefenseBonus > 4.0f)
  1641. {
  1642. dmgBonusMultiplier += 4.0f;
  1643. }
  1644. else
  1645. {
  1646. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1647. }
  1648. }
  1649. //handling secondary abilities
  1650. if(attackerHero)
  1651. {
  1652. if(shooting)
  1653. {
  1654. switch(attackerHero->getSecSkillLevel(1)) //archery
  1655. {
  1656. case 1: //basic
  1657. dmgBonusMultiplier *= 1.1f;
  1658. break;
  1659. case 2: //advanced
  1660. dmgBonusMultiplier *= 1.25f;
  1661. break;
  1662. case 3: //expert
  1663. dmgBonusMultiplier *= 1.5f;
  1664. break;
  1665. }
  1666. }
  1667. else
  1668. {
  1669. switch(attackerHero->getSecSkillLevel(22)) //offense
  1670. {
  1671. case 1: //basic
  1672. dmgBonusMultiplier *= 1.1f;
  1673. break;
  1674. case 2: //advanced
  1675. dmgBonusMultiplier *= 1.2f;
  1676. break;
  1677. case 3: //expert
  1678. dmgBonusMultiplier *= 1.3f;
  1679. break;
  1680. }
  1681. }
  1682. }
  1683. if(defendingHero)
  1684. {
  1685. switch(defendingHero->getSecSkillLevel(23)) //armorer
  1686. {
  1687. case 1: //basic
  1688. dmgBonusMultiplier *= 0.95f;
  1689. break;
  1690. case 2: //advanced
  1691. dmgBonusMultiplier *= 0.9f;
  1692. break;
  1693. case 3: //expert
  1694. dmgBonusMultiplier *= 0.85f;
  1695. break;
  1696. }
  1697. }
  1698. //handling spell effects
  1699. if(!shooting && defender->getEffect(27)) //shield
  1700. {
  1701. if(defender->getEffect(27)->level<=1) //none or basic
  1702. dmgBonusMultiplier *= 0.85f;
  1703. else //adv or expert
  1704. dmgBonusMultiplier *= 0.7f;
  1705. }
  1706. else if(shooting && defender->getEffect(28)) //air shield
  1707. {
  1708. if(defender->getEffect(28)->level<=1) //none or basic
  1709. dmgBonusMultiplier *= 0.75f;
  1710. else //adv or expert
  1711. dmgBonusMultiplier *= 0.5f;
  1712. }
  1713. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  1714. {
  1715. if(attacker->getEffect(42)->level>=2) //adv or expert
  1716. dmgBonusMultiplier *= 0.8f;
  1717. }
  1718. minDmg *= dmgBonusMultiplier;
  1719. maxDmg *= dmgBonusMultiplier;
  1720. if(attacker->getEffect(42)) //curse handling (rest)
  1721. {
  1722. minDmg -= VLC->spellh->spells[attacker->getEffect(42)->id].powers[attacker->getEffect(42)->level];
  1723. return minDmg;
  1724. }
  1725. else if(attacker->getEffect(41)) //bless handling
  1726. {
  1727. maxDmg += VLC->spellh->spells[attacker->getEffect(41)->id].powers[attacker->getEffect(41)->level];
  1728. return maxDmg;
  1729. }
  1730. else
  1731. {
  1732. if(minDmg != maxDmg)
  1733. return minDmg + rand() % (maxDmg - minDmg + 1);
  1734. else
  1735. return minDmg;
  1736. }
  1737. tlog1 << "We are too far in calculateDmg...\n";
  1738. return -1;
  1739. }
  1740. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties )
  1741. {
  1742. for(int i=0; i<stacks.size();i++)//setting casualties
  1743. {
  1744. if(!stacks[i]->alive())
  1745. {
  1746. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  1747. }
  1748. else if(stacks[i]->amount != stacks[i]->baseAmount)
  1749. {
  1750. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  1751. }
  1752. }
  1753. }
  1754. CStack * BattleInfo::getNextStack()
  1755. {
  1756. CStack *current = getStack(activeStack);
  1757. for (int i = 0; i < stacks.size(); i++) //find fastest not moved/waited stack (stacks vector is sorted by speed)
  1758. {
  1759. if(stacks[i]->willMove() && !vstd::contains(stacks[i]->state,WAITING))
  1760. return stacks[i];
  1761. }
  1762. for (int i = stacks.size() - 1; i >= 0 ; i--) //find slowest waiting stack
  1763. {
  1764. if(stacks[i]->willMove())
  1765. return stacks[i];
  1766. }
  1767. return NULL; //all stacks moved or defending!
  1768. }
  1769. std::vector<CStack> BattleInfo::getStackQueue()
  1770. {
  1771. std::vector<CStack> ret;
  1772. std::vector<int> taken; //if non-zero value, corresponding stack has been placed in ret
  1773. taken.resize(stacks.size());
  1774. for(int g=0; g<taken.size(); ++g)
  1775. {
  1776. taken[g] = 0;
  1777. }
  1778. 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
  1779. {
  1780. for(int gc=0; gc<stacks.size(); ++gc)
  1781. {
  1782. int id = -1, speed = -1;
  1783. for(int i=0; i<stacks.size(); ++i) //find not waited stacks only
  1784. {
  1785. if((moved == 1 ||!vstd::contains(stacks[i]->state,DEFENDING))
  1786. && stacks[i]->alive()
  1787. && (moved == 1 || !vstd::contains(stacks[i]->state,MOVED))
  1788. && !vstd::contains(stacks[i]->state,WAITING)
  1789. && taken[i]==0
  1790. && !vstd::contains(stacks[i]->abilities,NOT_ACTIVE)) //eg. Ammo Cart
  1791. {
  1792. if(speed == -1 || stacks[i]->Speed() > speed)
  1793. {
  1794. id = i;
  1795. speed = stacks[i]->Speed();
  1796. }
  1797. }
  1798. }
  1799. if(id != -1)
  1800. {
  1801. ret.push_back(*stacks[id]);
  1802. taken[id] = 1;
  1803. }
  1804. else //choose something from not moved stacks
  1805. {
  1806. int id = -1, speed = 10000; //infinite speed
  1807. for(int i=0; i<stacks.size(); ++i) //find waited stacks only
  1808. {
  1809. if((moved == 1 ||!vstd::contains(stacks[i]->state,DEFENDING))
  1810. && stacks[i]->alive()
  1811. && (moved == 1 || !vstd::contains(stacks[i]->state,MOVED))
  1812. && vstd::contains(stacks[i]->state,WAITING)
  1813. && taken[i]==0
  1814. && !vstd::contains(stacks[i]->abilities,NOT_ACTIVE)) //eg. Ammo Cart
  1815. {
  1816. if(stacks[i]->Speed() < speed) //slowest one
  1817. {
  1818. id = i;
  1819. speed = stacks[i]->Speed();
  1820. }
  1821. }
  1822. }
  1823. if(id != -1)
  1824. {
  1825. ret.push_back(*stacks[id]);
  1826. taken[id] = 1;
  1827. }
  1828. else
  1829. {
  1830. break; //no stacks have been found, so none of them will be found in next iterations
  1831. }
  1832. }
  1833. }
  1834. }
  1835. return ret;
  1836. }
  1837. int3 CPath::startPos() const
  1838. {
  1839. return nodes[nodes.size()-1].coord;
  1840. }
  1841. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  1842. {
  1843. if (mode==0)
  1844. {
  1845. for (int i=0;i<nodes.size();i++)
  1846. {
  1847. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  1848. }
  1849. }
  1850. }
  1851. int3 CPath::endPos() const
  1852. {
  1853. return nodes[0].coord;
  1854. }