CGameState.cpp 61 KB

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