CGameState.cpp 58 KB

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