CGameState.cpp 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839
  1. #define VCMI_DLL
  2. #include "../hch/CCampaignHandler.h"
  3. #include <algorithm>
  4. #include <queue>
  5. #include <fstream>
  6. #include "CGameState.h"
  7. #include <boost/random/linear_congruential.hpp>
  8. #include "../hch/CDefObjInfoHandler.h"
  9. #include "../hch/CArtHandler.h"
  10. #include "../hch/CBuildingHandler.h"
  11. #include "../hch/CGeneralTextHandler.h"
  12. #include "../hch/CTownHandler.h"
  13. #include "../hch/CSpellHandler.h"
  14. #include "../hch/CHeroHandler.h"
  15. #include "../hch/CObjectHandler.h"
  16. #include "../hch/CCreatureHandler.h"
  17. #include "VCMI_Lib.h"
  18. #include "Connection.h"
  19. #include "map.h"
  20. #include "../StartInfo.h"
  21. #include "NetPacks.h"
  22. #include <boost/foreach.hpp>
  23. #include <boost/lexical_cast.hpp>
  24. #include <boost/thread.hpp>
  25. #include <boost/thread/shared_mutex.hpp>
  26. #include <boost/assign/list_of.hpp>
  27. #include "RegisterTypes.cpp"
  28. #include <algorithm>
  29. #include <numeric>
  30. boost::rand48 ran;
  31. #ifdef min
  32. #undef min
  33. #endif
  34. #ifdef max
  35. #undef max
  36. #endif
  37. /*
  38. * CGameState.cpp, part of VCMI engine
  39. *
  40. * Authors: listed in file AUTHORS in main folder
  41. *
  42. * License: GNU General Public License v2.0 or later
  43. * Full text of license available in license.txt file, in main folder
  44. *
  45. */
  46. void foofoofoo()
  47. {
  48. //never called function to force instantation of templates
  49. int *ccc = NULL;
  50. registerTypes((CISer<CConnection>&)*ccc);
  51. registerTypes((COSer<CConnection>&)*ccc);
  52. registerTypes((CSaveFile&)*ccc);
  53. registerTypes((CLoadFile&)*ccc);
  54. registerTypes((CTypeList&)*ccc);
  55. }
  56. class CBaseForGSApply
  57. {
  58. public:
  59. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  60. virtual ~CBaseForGSApply(){};
  61. };
  62. template <typename T> class CApplyOnGS : public CBaseForGSApply
  63. {
  64. public:
  65. void applyOnGS(CGameState *gs, void *pack) const
  66. {
  67. T *ptr = static_cast<T*>(pack);
  68. while(!gs->mx->try_lock())
  69. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  70. ptr->applyGs(gs);
  71. gs->mx->unlock();
  72. }
  73. };
  74. class CGSApplier
  75. {
  76. public:
  77. std::map<ui16,CBaseForGSApply*> apps;
  78. CGSApplier()
  79. {
  80. registerTypes2(*this);
  81. }
  82. ~CGSApplier()
  83. {
  84. std::map<ui16,CBaseForGSApply*>::iterator iter;
  85. for(iter = apps.begin(); iter != apps.end(); iter++)
  86. delete iter->second;
  87. }
  88. template<typename T> void registerType(const T * t=NULL)
  89. {
  90. ui16 ID = typeList.registerType(t);
  91. apps[ID] = new CApplyOnGS<T>;
  92. }
  93. } *applierGs = NULL;
  94. class IObjectCaller
  95. {
  96. public:
  97. virtual void preInit()=0;
  98. virtual void postInit()=0;
  99. };
  100. template <typename T>
  101. class CObjectCaller : public IObjectCaller
  102. {
  103. public:
  104. void preInit()
  105. {
  106. T::preInit();
  107. }
  108. void postInit()
  109. {
  110. T::postInit();
  111. }
  112. };
  113. class CObjectCallersHandler
  114. {
  115. public:
  116. std::vector<IObjectCaller*> apps;
  117. template<typename T> void registerType(const T * t=NULL)
  118. {
  119. apps.push_back(new CObjectCaller<T>);
  120. }
  121. CObjectCallersHandler()
  122. {
  123. registerTypes1(*this);
  124. }
  125. ~CObjectCallersHandler()
  126. {
  127. for (size_t i = 0; i < apps.size(); i++)
  128. delete apps[i];
  129. }
  130. void preInit()
  131. {
  132. for (size_t i = 0; i < apps.size(); i++)
  133. apps[i]->preInit();
  134. }
  135. void postInit()
  136. {
  137. for (size_t i = 0; i < apps.size(); i++)
  138. apps[i]->postInit();
  139. }
  140. } *objCaller = NULL;
  141. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  142. {
  143. int type = txt.first, ser = txt.second;
  144. if(type == ART_NAMES)
  145. {
  146. dst = VLC->arth->artifacts[ser].Name();
  147. }
  148. else if(type == CRE_PL_NAMES)
  149. {
  150. dst = VLC->creh->creatures[ser]->namePl;
  151. }
  152. else if(type == MINE_NAMES)
  153. {
  154. dst = VLC->generaltexth->mines[ser].first;
  155. }
  156. else if(type == MINE_EVNTS)
  157. {
  158. dst = VLC->generaltexth->mines[ser].second;
  159. }
  160. else if(type == SPELL_NAME)
  161. {
  162. dst = VLC->spellh->spells[ser].name;
  163. }
  164. else if(type == CRE_SING_NAMES)
  165. {
  166. dst = VLC->creh->creatures[ser]->nameSing;
  167. }
  168. else if(type == ART_DESCR)
  169. {
  170. dst = VLC->arth->artifacts[ser].Description();
  171. }
  172. else
  173. {
  174. std::vector<std::string> *vec;
  175. switch(type)
  176. {
  177. case GENERAL_TXT:
  178. vec = &VLC->generaltexth->allTexts;
  179. break;
  180. case XTRAINFO_TXT:
  181. vec = &VLC->generaltexth->xtrainfo;
  182. break;
  183. case OBJ_NAMES:
  184. vec = &VLC->generaltexth->names;
  185. break;
  186. case RES_NAMES:
  187. vec = &VLC->generaltexth->restypes;
  188. break;
  189. case ARRAY_TXT:
  190. vec = &VLC->generaltexth->arraytxt;
  191. break;
  192. case CREGENS:
  193. vec = &VLC->generaltexth->creGens;
  194. break;
  195. case CREGENS4:
  196. vec = &VLC->generaltexth->creGens4;
  197. break;
  198. case ADVOB_TXT:
  199. vec = &VLC->generaltexth->advobtxt;
  200. break;
  201. case ART_EVNTS:
  202. vec = &VLC->generaltexth->artifEvents;
  203. break;
  204. case SEC_SKILL_NAME:
  205. vec = &VLC->generaltexth->skillName;
  206. break;
  207. case COLOR:
  208. vec = &VLC->generaltexth->capColors;
  209. break;
  210. }
  211. dst = (*vec)[ser];
  212. }
  213. }
  214. DLL_EXPORT void MetaString::toString(std::string &dst) const
  215. {
  216. size_t exSt = 0, loSt = 0, nums = 0;
  217. dst.clear();
  218. for(size_t i=0;i<message.size();++i)
  219. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  220. switch(message[i])
  221. {
  222. case TEXACT_STRING:
  223. dst += exactStrings[exSt++];
  224. break;
  225. case TLOCAL_STRING:
  226. {
  227. std::string hlp;
  228. getLocalString(localStrings[loSt++], hlp);
  229. dst += hlp;
  230. }
  231. break;
  232. case TNUMBER:
  233. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  234. break;
  235. case TREPLACE_ESTRING:
  236. dst.replace (dst.find("%s"), 2, exactStrings[exSt++]);
  237. break;
  238. case TREPLACE_LSTRING:
  239. {
  240. std::string hlp;
  241. getLocalString(localStrings[loSt++], hlp);
  242. dst.replace (dst.find("%s"), 2, hlp);
  243. }
  244. break;
  245. case TREPLACE_NUMBER:
  246. dst.replace (dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  247. break;
  248. default:
  249. tlog1 << "MetaString processing error!\n";
  250. break;
  251. }
  252. }
  253. }
  254. DLL_EXPORT std::string MetaString::buildList () const
  255. ///used to handle loot from creature bank
  256. {
  257. size_t exSt = 0, loSt = 0, nums = 0;
  258. std::string lista;
  259. for (int i = 0; i < message.size(); ++i)
  260. {
  261. if (i > 0 && message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING)
  262. {
  263. if (exSt == exactStrings.size() - 1)
  264. lista += VLC->generaltexth->allTexts[141]; //" and "
  265. else
  266. lista += ", ";
  267. }
  268. switch (message[i])
  269. {
  270. case TEXACT_STRING:
  271. lista += exactStrings[exSt++];
  272. break;
  273. case TLOCAL_STRING:
  274. {
  275. std::string hlp;
  276. getLocalString (localStrings[loSt++], hlp);
  277. lista += hlp;
  278. }
  279. break;
  280. case TNUMBER:
  281. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  282. break;
  283. case TREPLACE_ESTRING:
  284. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  285. break;
  286. case TREPLACE_LSTRING:
  287. {
  288. std::string hlp;
  289. getLocalString (localStrings[loSt++], hlp);
  290. lista.replace (lista.find("%s"), 2, hlp);
  291. }
  292. break;
  293. case TREPLACE_NUMBER:
  294. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  295. break;
  296. default:
  297. tlog1 << "MetaString processing error!\n";
  298. }
  299. }
  300. return lista;
  301. }
  302. void MetaString::addReplacement(const CStackInstance &stack)
  303. {
  304. assert(stack.count); //valid count
  305. assert(stack.type); //valid type
  306. if (stack.count == 1)
  307. addReplacement (CRE_SING_NAMES, stack.type->idNumber);
  308. else
  309. addReplacement (CRE_PL_NAMES, stack.type->idNumber);
  310. }
  311. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  312. {
  313. CGObjectInstance * nobj;
  314. switch(id)
  315. {
  316. case HEROI_TYPE: //hero
  317. {
  318. CGHeroInstance * nobj = new CGHeroInstance();
  319. nobj->pos = pos;
  320. nobj->tempOwner = owner;
  321. nobj->subID = subid;
  322. //nobj->initHero(ran);
  323. return nobj;
  324. }
  325. case TOWNI_TYPE: //town
  326. nobj = new CGTownInstance;
  327. break;
  328. default: //rest of objects
  329. nobj = new CGObjectInstance;
  330. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  331. break;
  332. }
  333. nobj->ID = id;
  334. nobj->subID = subid;
  335. if(!nobj->defInfo)
  336. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  337. nobj->pos = pos;
  338. //nobj->state = NULL;//new CLuaObjectScript();
  339. nobj->tempOwner = owner;
  340. nobj->defInfo->id = id;
  341. nobj->defInfo->subid = subid;
  342. //assigning defhandler
  343. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  344. return nobj;
  345. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  346. return nobj;
  347. }
  348. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  349. {
  350. for(unsigned int g=0; g<stacks.size(); ++g)
  351. {
  352. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  353. return stacks[g];
  354. }
  355. return NULL;
  356. }
  357. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  358. {
  359. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  360. }
  361. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  362. {
  363. for(unsigned int g=0; g<stacks.size(); ++g)
  364. {
  365. if(stacks[g]->position == tileID
  366. || (stacks[g]->doubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  367. || (stacks[g]->doubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  368. {
  369. if(!onlyAlive || stacks[g]->alive())
  370. {
  371. return stacks[g];
  372. }
  373. }
  374. }
  375. return NULL;
  376. }
  377. const CStack * BattleInfo::getStackT(int tileID, bool onlyAlive) const
  378. {
  379. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  380. }
  381. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit) const
  382. {
  383. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  384. //removing accessibility for side columns of hexes
  385. for(int v = 0; v < BFIELD_SIZE; ++v)
  386. {
  387. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  388. accessibility[v] = false;
  389. }
  390. for(unsigned int g=0; g<stacks.size(); ++g)
  391. {
  392. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  393. continue;
  394. accessibility[stacks[g]->position] = false;
  395. if(stacks[g]->doubleWide()) //if it's a double hex creature
  396. {
  397. if(stacks[g]->attackerOwned)
  398. accessibility[stacks[g]->position-1] = false;
  399. else
  400. accessibility[stacks[g]->position+1] = false;
  401. }
  402. }
  403. //obstacles
  404. for(unsigned int b=0; b<obstacles.size(); ++b)
  405. {
  406. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  407. for(unsigned int c=0; c<blocked.size(); ++c)
  408. {
  409. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  410. accessibility[blocked[c]] = false;
  411. }
  412. }
  413. //walls
  414. if(siege > 0)
  415. {
  416. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  417. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  418. {
  419. accessibility[permanentlyLocked[b]] = false;
  420. }
  421. static const std::pair<int, int> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  422. {std::make_pair(2, 182), std::make_pair(3, 130), std::make_pair(4, 62), std::make_pair(5, 29)};
  423. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  424. {
  425. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  426. {
  427. accessibility[lockedIfNotDestroyed[b].second] = false;
  428. }
  429. }
  430. //gate
  431. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  432. {
  433. accessibility[95] = accessibility[96] = false; //block gate's hexes
  434. }
  435. }
  436. //occupyability
  437. if(addOccupiable && twoHex)
  438. {
  439. std::set<int> rem; //tiles to unlock
  440. for(int h=0; h<BFIELD_HEIGHT; ++h)
  441. {
  442. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  443. {
  444. int hex = h * BFIELD_WIDTH + w;
  445. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  446. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  447. )
  448. rem.insert(hex);
  449. }
  450. }
  451. occupyable = rem;
  452. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  453. {
  454. accessibility[*it] = true;
  455. }*/
  456. }
  457. }
  458. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  459. {
  460. if(flying && !lastPos)
  461. return true;
  462. if(twoHex)
  463. {
  464. //if given hex is accessible and appropriate adjacent one is free too
  465. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  466. }
  467. else
  468. {
  469. return accessibility[hex];
  470. }
  471. }
  472. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  473. {
  474. //inits
  475. for(int b=0; b<BFIELD_SIZE; ++b)
  476. predecessor[b] = -1;
  477. for(int g=0; g<BFIELD_SIZE; ++g)
  478. dists[g] = 100000000;
  479. std::queue< std::pair<int, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  480. hexq.push(std::make_pair(start, true));
  481. dists[hexq.front().first] = 0;
  482. int curNext = -1; //for bfs loop only (helper var)
  483. while(!hexq.empty()) //bfs loop
  484. {
  485. std::pair<int, bool> curHex = hexq.front();
  486. std::vector<int> neighbours = neighbouringTiles(curHex.first);
  487. hexq.pop();
  488. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  489. {
  490. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  491. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  492. if( dists[curHex.first]+1 >= dists[curNext] )
  493. continue;
  494. if(accessible && curHex.second)
  495. {
  496. hexq.push(std::make_pair(curNext, true));
  497. dists[curNext] = dists[curHex.first] + 1;
  498. }
  499. else if(fillPredecessors && !(accessible && !curHex.second))
  500. {
  501. hexq.push(std::make_pair(curNext, false));
  502. dists[curNext] = dists[curHex.first] + 1;
  503. }
  504. predecessor[curNext] = curHex.first;
  505. }
  506. }
  507. };
  508. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable) const
  509. {
  510. std::vector<int> ret;
  511. bool ac[BFIELD_SIZE];
  512. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  513. if(s->position < 0) //turrets
  514. return std::vector<int>();
  515. std::set<int> occupyable;
  516. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, addOccupiable, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  517. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  518. makeBFS(s->position, ac, pr, dist, s->doubleWide(), s->attackerOwned, s->hasBonusOfType(Bonus::FLYING), false);
  519. if(s->doubleWide())
  520. {
  521. if(!addOccupiable)
  522. {
  523. std::vector<int> rem;
  524. for(int b=0; b<BFIELD_SIZE; ++b)
  525. {
  526. //don't take into account most left and most right columns of hexes
  527. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  528. continue;
  529. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  530. {
  531. rem.push_back(b);
  532. }
  533. }
  534. for(unsigned int g=0; g<rem.size(); ++g)
  535. {
  536. ac[rem[g]] = false;
  537. }
  538. //removing accessibility for side hexes
  539. for(int v=0; v<BFIELD_SIZE; ++v)
  540. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  541. ac[v] = false;
  542. }
  543. }
  544. for (int i=0; i < BFIELD_SIZE ; ++i) {
  545. if(
  546. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->doubleWide(), s->attackerOwned, s->hasBonusOfType(Bonus::FLYING), true) ) )//we can reach it
  547. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  548. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  549. )
  550. {
  551. ret.push_back(i);
  552. }
  553. }
  554. return ret;
  555. }
  556. bool BattleInfo::isStackBlocked(int ID)
  557. {
  558. CStack *our = getStack(ID);
  559. if(our->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  560. return false;
  561. for(unsigned int i=0; i<stacks.size();i++)
  562. {
  563. if( !stacks[i]->alive()
  564. || stacks[i]->owner==our->owner
  565. )
  566. continue; //we omit dead and allied stacks
  567. if(stacks[i]->doubleWide())
  568. {
  569. if( mutualPosition(stacks[i]->position, our->position) >= 0
  570. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  571. return true;
  572. }
  573. else
  574. {
  575. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  576. return true;
  577. }
  578. }
  579. return false;
  580. }
  581. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  582. {
  583. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  584. return 0;
  585. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  586. return 1;
  587. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  588. return 5;
  589. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  590. return 2;
  591. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  592. return 4;
  593. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  594. return 3;
  595. return -1;
  596. }
  597. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  598. {
  599. #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);}
  600. std::vector<int> ret;
  601. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  602. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  603. CHECK_AND_PUSH(hex - 1);
  604. CHECK_AND_PUSH(hex + 1);
  605. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  606. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  607. #undef CHECK_AND_PUSH
  608. return ret;
  609. }
  610. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  611. {
  612. int predecessor[BFIELD_SIZE]; //for getting the Path
  613. int dist[BFIELD_SIZE]; //calculated distances
  614. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  615. if(predecessor[dest] == -1) //cannot reach destination
  616. {
  617. return std::make_pair(std::vector<int>(), 0);
  618. }
  619. //making the Path
  620. std::vector<int> path;
  621. int curElem = dest;
  622. while(curElem != start)
  623. {
  624. path.push_back(curElem);
  625. curElem = predecessor[curElem];
  626. }
  627. return std::make_pair(path, dist[dest]);
  628. }
  629. CStack::CStack(const CStackInstance *base, int O, int I, bool AO, int S)
  630. : CStackInstance(*base), ID(I), owner(O), slot(S), attackerOwned(AO), position(-1),
  631. counterAttacks(1)
  632. {
  633. baseAmount = base->count;
  634. firstHPleft = valOfBonuses(Bonus::STACK_HEALTH);
  635. shots = type->shots;
  636. counterAttacks += valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  637. //alive state indication
  638. state.insert(ALIVE);
  639. }
  640. ui32 CStack::Speed( int turn /*= 0*/ ) const
  641. {
  642. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON) && Selector::turns(turn))) //war machines cannot move
  643. return 0;
  644. int speed = valOfBonuses(Selector::type(Bonus::STACKS_SPEED) && Selector::turns(turn));
  645. int percentBonus = 0;
  646. BOOST_FOREACH(const Bonus &b, bonuses)
  647. {
  648. if(b.type == Bonus::STACKS_SPEED)
  649. {
  650. percentBonus += b.additionalInfo;
  651. }
  652. }
  653. speed = ((100 + percentBonus) * speed)/100;
  654. //bind effect check
  655. if(getEffect(72))
  656. {
  657. return 0;
  658. }
  659. return speed;
  660. }
  661. const CStack::StackEffect * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  662. {
  663. for (unsigned int i=0; i< effects.size(); i++)
  664. if(effects[i].id == id)
  665. if(!turn || effects[i].turnsRemain > turn)
  666. return &effects[i];
  667. return NULL;
  668. }
  669. ui8 CStack::howManyEffectsSet(ui16 id) const
  670. {
  671. ui8 ret = 0;
  672. for (unsigned int i=0; i< effects.size(); i++)
  673. if(effects[i].id == id) //effect found
  674. {
  675. ++ret;
  676. }
  677. return ret;
  678. }
  679. bool CStack::willMove(int turn /*= 0*/) const
  680. {
  681. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  682. && !moved(turn)
  683. && canMove(turn);
  684. }
  685. bool CStack::canMove( int turn /*= 0*/ ) const
  686. {
  687. return alive()
  688. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE) && Selector::turns(turn)); //eg. Ammo Cart or blinded creature
  689. }
  690. bool CStack::moved( int turn /*= 0*/ ) const
  691. {
  692. if(!turn)
  693. return vstd::contains(state, MOVED);
  694. else
  695. return false;
  696. }
  697. bool CStack::doubleWide() const
  698. {
  699. return type->doubleWide;
  700. }
  701. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const
  702. {
  703. CGHeroInstance *ret = NULL;
  704. if(player<0 || player>=PLAYER_LIMIT)
  705. {
  706. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  707. return NULL;
  708. }
  709. std::vector<CGHeroInstance *> pool;
  710. if(native)
  711. {
  712. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  713. {
  714. if(pavailable.find(i->first)->second & 1<<player
  715. && i->second->type->heroType/2 == town->typeID)
  716. {
  717. pool.push_back(i->second); //get all avaliable heroes
  718. }
  719. }
  720. if(!pool.size())
  721. {
  722. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  723. return pickHeroFor(false, player, town, available);
  724. }
  725. else
  726. {
  727. ret = pool[rand()%pool.size()];
  728. }
  729. }
  730. else
  731. {
  732. int sum=0, r;
  733. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  734. {
  735. if(pavailable.find(i->first)->second & 1<<player)
  736. {
  737. pool.push_back(i->second);
  738. sum += i->second->type->heroClass->selectionProbability[town->typeID]; //total weight
  739. }
  740. }
  741. if(!pool.size())
  742. {
  743. tlog1 << "There are no heroes available for player " << player<<"!\n";
  744. return NULL;
  745. }
  746. r = rand()%sum;
  747. for (unsigned int i=0; i<pool.size(); i++)
  748. {
  749. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  750. if(r < 0)
  751. {
  752. ret = pool[i];
  753. break;
  754. }
  755. }
  756. if(!ret)
  757. ret = pool.back();
  758. }
  759. available.erase(ret->subID);
  760. return ret;
  761. }
  762. //void CGameState::apply(CPack * pack)
  763. //{
  764. // while(!mx->try_lock())
  765. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  766. // //applyNL(pack);
  767. // mx->unlock();
  768. //}
  769. int CGameState::pickHero(int owner)
  770. {
  771. int h=-1;
  772. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  773. return h;
  774. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  775. int i=0;
  776. do //try to find free hero of our faction
  777. {
  778. i++;
  779. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  780. } while( map->getHero(h) && i<175);
  781. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  782. {
  783. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  784. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  785. if(!map->getHero(j))
  786. h=j;
  787. }
  788. return h;
  789. }
  790. CGHeroInstance *CGameState::getHero(int objid)
  791. {
  792. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  793. return NULL;
  794. return static_cast<CGHeroInstance *>(map->objects[objid]);
  795. }
  796. const CGHeroInstance * CGameState::getHero( int objid ) const
  797. {
  798. return (const_cast<CGameState *>(this))->getHero(objid);
  799. }
  800. CGTownInstance *CGameState::getTown(int objid)
  801. {
  802. if(objid<0 || objid>=map->objects.size())
  803. return NULL;
  804. return static_cast<CGTownInstance *>(map->objects[objid]);
  805. }
  806. const CGTownInstance * CGameState::getTown( int objid ) const
  807. {
  808. return (const_cast<CGameState *>(this))->getTown(objid);
  809. }
  810. std::pair<int,int> CGameState::pickObject (CGObjectInstance *obj)
  811. {
  812. switch(obj->ID)
  813. {
  814. case 65: //random artifact
  815. return std::pair<int,int>(5,(ran()%136)+7); //the only reasonable range - there are siege weapons and blanks we must ommit
  816. case 66: //random treasure artifact
  817. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  818. case 67: //random minor artifact
  819. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  820. case 68: //random major artifact
  821. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  822. case 69: //random relic artifact
  823. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  824. /*case 65: //random artifact //TODO: apply new randndomization system
  825. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  826. case 66: //random treasure artifact
  827. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_TREASURE));
  828. case 67: //random minor artifact
  829. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_MINOR));
  830. case 68: //random major artifact
  831. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_MAJOR));
  832. case 69: //random relic artifact
  833. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_RELIC));*/
  834. case 70: //random hero
  835. {
  836. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  837. }
  838. case 71: //random monster
  839. {
  840. int r;
  841. do
  842. {
  843. r = ran()%197;
  844. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  845. return std::pair<int,int>(54,r);
  846. }
  847. case 72: //random monster lvl1
  848. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  849. case 73: //random monster lvl2
  850. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  851. case 74: //random monster lvl3
  852. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  853. case 75: //random monster lvl4
  854. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  855. case 76: //random resource
  856. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  857. case 77: //random town
  858. {
  859. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  860. f;
  861. if(align>PLAYER_LIMIT-1)//same as owner / random
  862. {
  863. if(obj->tempOwner > PLAYER_LIMIT-1)
  864. f = -1; //random
  865. else
  866. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  867. }
  868. else
  869. {
  870. f = scenarioOps->getIthPlayersSettings(align).castle;
  871. }
  872. if(f<0) f = ran()%VLC->townh->towns.size();
  873. return std::pair<int,int>(TOWNI_TYPE,f);
  874. }
  875. case 162: //random monster lvl5
  876. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  877. case 163: //random monster lvl6
  878. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  879. case 164: //random monster lvl7
  880. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  881. case 216: //random dwelling
  882. {
  883. int faction = ran()%F_NUMBER;
  884. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  885. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(dwl->info);
  886. if (info->asCastle)
  887. {
  888. for(unsigned int i=0;i<map->objects.size();i++)
  889. {
  890. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  891. {
  892. randomizeObject(map->objects[i]); //we have to randomize the castle first
  893. faction = map->objects[i]->subID;
  894. break;
  895. }
  896. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  897. {
  898. faction = map->objects[i]->subID;
  899. break;
  900. }
  901. }
  902. }
  903. else
  904. {
  905. while((!(info->castles[0]&(1<<faction))))
  906. {
  907. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  908. break;
  909. faction = ran()%F_NUMBER;
  910. }
  911. }
  912. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  913. int cid = VLC->townh->towns[faction].basicCreatures[level];
  914. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  915. if(VLC->objh->cregens[i]==cid)
  916. return std::pair<int,int>(17,i);
  917. tlog3 << "Cannot find a dwelling for creature "<< cid << std::endl;
  918. return std::pair<int,int>(17,0);
  919. delete dwl->info;
  920. dwl->info = NULL;
  921. }
  922. case 217:
  923. {
  924. int faction = ran()%F_NUMBER;
  925. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  926. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(dwl->info);
  927. if (info->asCastle)
  928. {
  929. for(unsigned int i=0;i<map->objects.size();i++)
  930. {
  931. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  932. {
  933. randomizeObject(map->objects[i]); //we have to randomize the castle first
  934. faction = map->objects[i]->subID;
  935. break;
  936. }
  937. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  938. {
  939. faction = map->objects[i]->subID;
  940. break;
  941. }
  942. }
  943. }
  944. else
  945. {
  946. while((!(info->castles[0]&(1<<faction))))
  947. {
  948. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  949. break;
  950. faction = ran()%F_NUMBER;
  951. }
  952. }
  953. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  954. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  955. if(VLC->objh->cregens[i]==cid)
  956. return std::pair<int,int>(17,i);
  957. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  958. return std::pair<int,int>(17,0);
  959. delete dwl->info;
  960. dwl->info = NULL;
  961. }
  962. case 218:
  963. {
  964. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  965. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(dwl->info);
  966. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  967. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  968. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  969. if(VLC->objh->cregens[i]==cid)
  970. return std::pair<int,int>(17,i);
  971. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  972. return std::pair<int,int>(17,0);
  973. delete dwl->info;
  974. dwl->info = NULL;
  975. }
  976. }
  977. return std::pair<int,int>(-1,-1);
  978. }
  979. void CGameState::randomizeObject(CGObjectInstance *cur)
  980. {
  981. std::pair<int,int> ran = pickObject(cur);
  982. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  983. {
  984. if(cur->ID==TOWNI_TYPE) //town - set def
  985. {
  986. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  987. t->town = &VLC->townh->towns[t->subID];
  988. if(t->hasCapitol())
  989. t->defInfo = capitols[t->subID];
  990. else if(t->hasFort())
  991. t->defInfo = forts[t->subID];
  992. else
  993. t->defInfo = villages[t->subID];
  994. }
  995. return;
  996. }
  997. else if(ran.first==HEROI_TYPE)//special code for hero
  998. {
  999. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  1000. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  1001. cur->ID = ran.first;
  1002. h->portrait = cur->subID = ran.second;
  1003. h->type = VLC->heroh->heroes[ran.second];
  1004. h->randomizeArmy(h->type->heroType/2);
  1005. map->heroes.push_back(h);
  1006. return; //TODO: maybe we should do something with definfo?
  1007. }
  1008. else if(ran.first==TOWNI_TYPE)//special code for town
  1009. {
  1010. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1011. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1012. cur->ID = ran.first;
  1013. cur->subID = ran.second;
  1014. t->town = &VLC->townh->towns[ran.second];
  1015. if(t->hasCapitol())
  1016. t->defInfo = capitols[t->subID];
  1017. else if(t->hasFort())
  1018. t->defInfo = forts[t->subID];
  1019. else
  1020. t->defInfo = villages[t->subID];
  1021. t->randomizeArmy(t->subID);
  1022. map->towns.push_back(t);
  1023. return;
  1024. }
  1025. //we have to replace normal random object
  1026. cur->ID = ran.first;
  1027. cur->subID = ran.second;
  1028. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  1029. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1030. if(!cur->defInfo)
  1031. {
  1032. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1033. return;
  1034. }
  1035. map->addBlockVisTiles(cur);
  1036. }
  1037. int CGameState::getDate(int mode) const
  1038. {
  1039. int temp;
  1040. switch (mode)
  1041. {
  1042. case 0:
  1043. return day;
  1044. break;
  1045. case 1:
  1046. temp = (day)%7;
  1047. if (temp)
  1048. return temp;
  1049. else return 7;
  1050. break;
  1051. case 2:
  1052. temp = ((day-1)/7)+1;
  1053. if (!(temp%4))
  1054. return 4;
  1055. else
  1056. return (temp%4);
  1057. break;
  1058. case 3:
  1059. return ((day-1)/28)+1;
  1060. break;
  1061. }
  1062. return 0;
  1063. }
  1064. CGameState::CGameState()
  1065. {
  1066. mx = new boost::shared_mutex();
  1067. map = NULL;
  1068. curB = NULL;
  1069. scenarioOps = NULL;
  1070. applierGs = new CGSApplier;
  1071. objCaller = new CObjectCallersHandler;
  1072. campaign = NULL;
  1073. }
  1074. CGameState::~CGameState()
  1075. {
  1076. delete mx;
  1077. delete map;
  1078. delete curB;
  1079. delete scenarioOps;
  1080. delete applierGs;
  1081. delete objCaller;
  1082. }
  1083. void CGameState::init( StartInfo * si, ui32 checksum, int Seed )
  1084. {
  1085. switch(si->mode)
  1086. {
  1087. case 0:
  1088. map = new Mapa(si->mapname);
  1089. break;
  1090. case 2:
  1091. campaign = new CCampaignState();
  1092. campaign->initNewCampaign(*si);
  1093. std::string &mapContent = campaign->camp->mapPieces[si->whichMapInCampaign];
  1094. map = new Mapa();
  1095. map->initFromBytes((const unsigned char*)mapContent.c_str());
  1096. break;
  1097. }
  1098. tlog0 << "Map loaded!" << std::endl;
  1099. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  1100. if(checksum)
  1101. {
  1102. tlog0 << "\tServer checksum for " << si->mapname <<": "<< checksum << std::endl;
  1103. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  1104. if(map->checksum != checksum)
  1105. {
  1106. tlog1 << "Wrong map checksum!!!" << std::endl;
  1107. throw std::string("Wrong checksum");
  1108. }
  1109. }
  1110. day = 0;
  1111. seed = Seed;
  1112. ran.seed((boost::int32_t)seed);
  1113. scenarioOps = si;
  1114. loadTownDInfos();
  1115. //pick grail location
  1116. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  1117. {
  1118. if(!map->grailRadious) //radius not given -> anywhere on map
  1119. map->grailRadious = map->width * 2;
  1120. std::vector<int3> allowedPos;
  1121. // add all not blocked tiles in range
  1122. for (int i = 0; i < map->width ; i++)
  1123. {
  1124. for (int j = 0; j < map->height ; j++)
  1125. {
  1126. for (int k = 0; k <= map->twoLevel ; k++)
  1127. {
  1128. const TerrainTile &t = map->terrain[i][j][k];
  1129. if(!t.blocked
  1130. && !t.visitable
  1131. && t.tertype != TerrainTile::water
  1132. && t.tertype != TerrainTile::rock
  1133. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  1134. allowedPos.push_back(int3(i,j,k));
  1135. }
  1136. }
  1137. }
  1138. //remove tiles with holes
  1139. for(unsigned int no=0; no<map->objects.size(); ++no)
  1140. if(map->objects[no]->ID == 124)
  1141. allowedPos -= map->objects[no]->pos;
  1142. if(allowedPos.size())
  1143. map->grailPos = allowedPos[ran() % allowedPos.size()];
  1144. else
  1145. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  1146. }
  1147. //picking random factions for players
  1148. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  1149. {
  1150. if(scenarioOps->playerInfos[i].castle==-1)
  1151. {
  1152. int f;
  1153. do
  1154. {
  1155. f = ran()%F_NUMBER;
  1156. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1157. scenarioOps->playerInfos[i].castle = f;
  1158. }
  1159. }
  1160. //randomizing objects
  1161. for(unsigned int no=0; no<map->objects.size(); ++no)
  1162. {
  1163. randomizeObject(map->objects[no]);
  1164. if(map->objects[no]->ID==EVENTI_TYPE)
  1165. {
  1166. map->objects[no]->defInfo->handler=NULL;
  1167. }
  1168. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1169. }
  1170. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1171. /*********give starting hero****************************************/
  1172. for(int i=0;i<PLAYER_LIMIT;i++)
  1173. {
  1174. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1175. {
  1176. int3 hpos = map->players[i].posOfMainTown;
  1177. hpos.x+=1;// hpos.y+=1;
  1178. int j;
  1179. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1180. if(scenarioOps->playerInfos[j].color == i)
  1181. break;
  1182. if(j == scenarioOps->playerInfos.size())
  1183. continue;
  1184. int h=pickHero(i);
  1185. if(scenarioOps->playerInfos[j].hero == -1)
  1186. scenarioOps->playerInfos[j].hero = h;
  1187. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1188. nnn->id = map->objects.size();
  1189. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1190. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1191. {
  1192. if(map->towns[o]->pos == hpos)
  1193. {
  1194. map->towns[o]->visitingHero = nnn;
  1195. nnn->visitedTown = map->towns[o];
  1196. nnn->inTownGarrison = false;
  1197. break;
  1198. }
  1199. }
  1200. nnn->initHero();
  1201. map->heroes.push_back(nnn);
  1202. map->objects.push_back(nnn);
  1203. map->addBlockVisTiles(nnn);
  1204. }
  1205. }
  1206. /*********creating players entries in gs****************************************/
  1207. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1208. {
  1209. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1210. ins.second.color=ins.first;
  1211. ins.second.serial=i;
  1212. ins.second.human = scenarioOps->playerInfos[i].human;
  1213. players.insert(ins);
  1214. }
  1215. /******************RESOURCES****************************************************/
  1216. //TODO: computer player should receive other amount of resource than player (depending on difficulty)
  1217. std::vector<int> startres;
  1218. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1219. int k;
  1220. for (int j=0;j<scenarioOps->difficulty;j++)
  1221. {
  1222. tis >> k;
  1223. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1224. tis>>k;
  1225. }
  1226. tis >> k;
  1227. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1228. {
  1229. tis >> k;
  1230. startres.push_back(k);
  1231. }
  1232. tis.close();
  1233. tis.clear();
  1234. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1235. {
  1236. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1237. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1238. (*i).second.resources[x] = startres[x];
  1239. }
  1240. tis.open(DATA_DIR "/config/resources.txt");
  1241. tis >> k;
  1242. int pom;
  1243. for(int i=0;i<k;i++)
  1244. {
  1245. tis >> pom;
  1246. resVals.push_back(pom);
  1247. }
  1248. /*************************HEROES************************************************/
  1249. std::set<int> hids;
  1250. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1251. if(map->allowedHeroes[i])
  1252. hids.insert(i);
  1253. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1254. {
  1255. if (map->heroes[i]->getOwner()<0)
  1256. {
  1257. tlog2 << "Warning - hero with uninitialized owner!\n";
  1258. continue;
  1259. }
  1260. CGHeroInstance * vhi = (map->heroes[i]);
  1261. vhi->initHero();
  1262. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1263. hids.erase(vhi->subID);
  1264. }
  1265. for (unsigned int i=0; i<map->objects.size();i++) //heroes instances initialization
  1266. {
  1267. if (map->objects[i]->ID == 62)
  1268. hids.erase(map->objects[i]->subID);
  1269. }
  1270. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1271. {
  1272. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1273. continue;
  1274. map->predefinedHeroes[i]->initHero();
  1275. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1276. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1277. hids.erase(map->predefinedHeroes[i]->subID);
  1278. }
  1279. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1280. {
  1281. CGHeroInstance * vhi = new CGHeroInstance();
  1282. vhi->initHero(hid);
  1283. hpool.heroesPool[hid] = vhi;
  1284. hpool.pavailable[hid] = 0xff;
  1285. }
  1286. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1287. {
  1288. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1289. }
  1290. /*************************FOG**OF**WAR******************************************/
  1291. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1292. {
  1293. k->second.fogOfWarMap.resize(map->width);
  1294. for(int g=0; g<map->width; ++g)
  1295. k->second.fogOfWarMap[g].resize(map->height);
  1296. for(int g=-0; g<map->width; ++g)
  1297. for(int h=0; h<map->height; ++h)
  1298. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1299. for(int g=0; g<map->width; ++g)
  1300. for(int h=0; h<map->height; ++h)
  1301. for(int v=0; v<map->twoLevel+1; ++v)
  1302. k->second.fogOfWarMap[g][h][v] = 0;
  1303. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1304. {
  1305. if(obj->tempOwner != k->first) continue; //not a flagged object
  1306. std::set<int3> tiles;
  1307. obj->getSightTiles(tiles);
  1308. BOOST_FOREACH(int3 tile, tiles)
  1309. {
  1310. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1311. }
  1312. }
  1313. //starting bonus
  1314. if(si->playerInfos[k->second.serial].bonus==brandom)
  1315. si->playerInfos[k->second.serial].bonus = ran()%3;
  1316. switch(si->playerInfos[k->second.serial].bonus)
  1317. {
  1318. case bgold:
  1319. k->second.resources[6] += 500 + (ran()%6)*100;
  1320. break;
  1321. case bresource:
  1322. {
  1323. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1324. if(res == 127)
  1325. {
  1326. k->second.resources[0] += 5 + ran()%6;
  1327. k->second.resources[2] += 5 + ran()%6;
  1328. }
  1329. else
  1330. {
  1331. k->second.resources[res] += 3 + ran()%4;
  1332. }
  1333. break;
  1334. }
  1335. case bartifact:
  1336. {
  1337. if(!k->second.heroes.size())
  1338. {
  1339. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1340. break;
  1341. }
  1342. CArtifact *toGive;
  1343. do
  1344. {
  1345. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1346. } while (!map->allowedArtifact[toGive->id]);
  1347. CGHeroInstance *hero = k->second.heroes[0];
  1348. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1349. if(slot!=toGive->possibleSlots.end())
  1350. {
  1351. VLC->arth->equipArtifact(hero->artifWorn, *slot, toGive->id, &hero->bonuses);
  1352. }
  1353. else
  1354. hero->giveArtifact(toGive->id);
  1355. }
  1356. }
  1357. }
  1358. /****************************TOWNS************************************************/
  1359. for (unsigned int i=0;i<map->towns.size();i++)
  1360. {
  1361. CGTownInstance * vti =(map->towns[i]);
  1362. if(!vti->town)
  1363. vti->town = &VLC->townh->towns[vti->subID];
  1364. if (vti->name.length()==0) // if town hasn't name we draw it
  1365. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1366. //init buildings
  1367. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1368. {
  1369. vti->builtBuildings.erase(-50);
  1370. vti->builtBuildings.insert(10);
  1371. vti->builtBuildings.insert(5);
  1372. vti->builtBuildings.insert(30);
  1373. if(ran()%2)
  1374. vti->builtBuildings.insert(31);
  1375. }//init hordes
  1376. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1377. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1378. {
  1379. vti->builtBuildings.erase(-31-i);//remove old ID
  1380. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1381. {
  1382. vti->builtBuildings.insert(18);//add it
  1383. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1384. vti->builtBuildings.insert(19);//add it as well
  1385. }
  1386. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1387. {
  1388. vti->builtBuildings.insert(24);
  1389. if (vstd::contains(vti->builtBuildings,(37+i)))
  1390. vti->builtBuildings.insert(25);
  1391. }
  1392. }
  1393. //init spells
  1394. vti->spells.resize(SPELL_LEVELS);
  1395. CSpell *s;
  1396. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1397. {
  1398. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1399. vti->spells[s->level-1].push_back(s->id);
  1400. vti->possibleSpells -= s->id;
  1401. }
  1402. while(vti->possibleSpells.size())
  1403. {
  1404. ui32 total=0, sel=-1;
  1405. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1406. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1407. int r = (total)? ran()%total : -1;
  1408. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1409. {
  1410. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1411. if(r<0)
  1412. {
  1413. sel = ps;
  1414. break;
  1415. }
  1416. }
  1417. if(sel<0)
  1418. sel=0;
  1419. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1420. vti->spells[s->level-1].push_back(s->id);
  1421. vti->possibleSpells -= s->id;
  1422. }
  1423. if(vti->getOwner() != 255)
  1424. getPlayer(vti->getOwner())->towns.push_back(vti);
  1425. }
  1426. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1427. {
  1428. if(k->first==-1 || k->first==255)
  1429. continue;
  1430. //init visiting and garrisoned heroes
  1431. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1432. {
  1433. CGHeroInstance *h = k->second.heroes[l];
  1434. for(unsigned int m=0; m<k->second.towns.size();m++)
  1435. {
  1436. CGTownInstance *t = k->second.towns[m];
  1437. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1438. if(vistile == h->pos || h->pos==t->pos)
  1439. {
  1440. t->visitingHero = h;
  1441. h->visitedTown = t;
  1442. h->inTownGarrison = false;
  1443. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1444. {
  1445. map->removeBlockVisTiles(h);
  1446. h->pos.x -= 1;
  1447. map->addBlockVisTiles(h);
  1448. }
  1449. break;
  1450. }
  1451. }
  1452. }
  1453. }
  1454. for(unsigned int i=0; i<map->defy.size(); i++)
  1455. {
  1456. map->defy[i]->serial = i;
  1457. }
  1458. objCaller->preInit();
  1459. for(unsigned int i=0; i<map->objects.size(); i++)
  1460. {
  1461. map->objects[i]->initObj();
  1462. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1463. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1464. }
  1465. objCaller->postInit();
  1466. }
  1467. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1468. {
  1469. return true;
  1470. }
  1471. bool CGameState::battleCanFlee(int player)
  1472. {
  1473. if(!curB) //there is no battle
  1474. return false;
  1475. if(curB->heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1476. || curB->heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE))
  1477. return false;
  1478. return true;
  1479. }
  1480. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1481. {
  1482. if(!curB)
  1483. return -1;
  1484. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1485. {
  1486. if((curB->stacks[g]->position == pos
  1487. || (curB->stacks[g]->doubleWide()
  1488. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1489. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1490. ))
  1491. && (!onlyAlive || curB->stacks[g]->alive())
  1492. )
  1493. return curB->stacks[g]->ID;
  1494. }
  1495. return -1;
  1496. }
  1497. int CGameState::battleGetBattlefieldType(int3 tile)
  1498. {
  1499. if(tile==int3() && curB)
  1500. tile = curB->tile;
  1501. else if(tile==int3() && !curB)
  1502. return -1;
  1503. const std::vector <CGObjectInstance*> & objs = map->objects;
  1504. for(int g=0; g<objs.size(); ++g)
  1505. {
  1506. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1507. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1508. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1509. ) //look only for objects covering given tile
  1510. continue;
  1511. switch(objs[g]->ID)
  1512. {
  1513. case 222: //clover field
  1514. return 19;
  1515. case 21: case 223: //cursed ground
  1516. return 22;
  1517. case 224: //evil fog
  1518. return 20;
  1519. case 225: //favourable winds
  1520. return 21;
  1521. case 226: //fiery fields
  1522. return 14;
  1523. case 227: //holy ground
  1524. return 18;
  1525. case 228: //lucid pools
  1526. return 17;
  1527. case 229: //magic clouds
  1528. return 16;
  1529. case 46: case 230: //magic plains
  1530. return 9;
  1531. case 231: //rocklands
  1532. return 15;
  1533. }
  1534. }
  1535. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1536. {
  1537. case TerrainTile::dirt:
  1538. return rand()%3+3;
  1539. case TerrainTile::sand:
  1540. return 2; //TODO: coast support
  1541. case TerrainTile::grass:
  1542. return rand()%2+6;
  1543. case TerrainTile::snow:
  1544. return rand()%2+10;
  1545. case TerrainTile::swamp:
  1546. return 13;
  1547. case TerrainTile::rough:
  1548. return 23;
  1549. case TerrainTile::subterranean:
  1550. return 12;
  1551. case TerrainTile::lava:
  1552. return 8;
  1553. case TerrainTile::water:
  1554. return 25;
  1555. case TerrainTile::rock:
  1556. return 15;
  1557. default:
  1558. return -1;
  1559. }
  1560. }
  1561. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  1562. {
  1563. if(!curB)
  1564. return NULL;
  1565. return curB->heroes[!curB->getStack(stackID)->attackerOwned];
  1566. }
  1567. UpgradeInfo CGameState::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
  1568. {
  1569. UpgradeInfo ret;
  1570. const CCreature *base = obj->getCreature(stackPos);
  1571. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1572. {
  1573. const CGTownInstance * t;
  1574. if(obj->ID == TOWNI_TYPE)
  1575. t = static_cast<const CGTownInstance *>(obj);
  1576. else
  1577. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1578. for(std::set<si32>::const_iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1579. {
  1580. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1581. {
  1582. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1583. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1584. {
  1585. ret.newID.push_back(nid);
  1586. ret.cost.push_back(std::set<std::pair<int,int> >());
  1587. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1588. {
  1589. int dif = VLC->creh->creatures[nid]->cost[j] - base->cost[j];
  1590. if(dif)
  1591. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1592. }
  1593. }
  1594. }
  1595. }//end for
  1596. }
  1597. //TODO: check if hero ability makes some upgrades possible
  1598. if(ret.newID.size())
  1599. ret.oldID = base->idNumber;
  1600. return ret;
  1601. }
  1602. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1603. {
  1604. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1605. if(mode) return -1; //todo - support other modes
  1606. int mcount = 0;
  1607. for(unsigned int i=0;i<getPlayer(player)->towns.size();i++)
  1608. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1609. mcount++;
  1610. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1611. return ret;
  1612. }
  1613. void CGameState::loadTownDInfos()
  1614. {
  1615. for(int i=0;i<F_NUMBER;i++)
  1616. {
  1617. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1618. forts[i] = VLC->dobjinfo->castles[i];
  1619. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1620. }
  1621. }
  1622. void CGameState::getNeighbours( const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand )
  1623. {
  1624. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1625. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1626. vec.clear();
  1627. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1628. {
  1629. const int3 hlp = tile + dirs[i];
  1630. if(!map->isInTheMap(hlp))
  1631. continue;
  1632. const TerrainTile &hlpt = map->getTile(hlp);
  1633. if((indeterminate(onLand) || onLand == (hlpt.tertype!=8) )
  1634. && hlpt.tertype!=9)
  1635. {
  1636. vec.push_back(hlp);
  1637. }
  1638. }
  1639. }
  1640. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1641. {
  1642. if(src == dest) //same tile
  1643. return 0;
  1644. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1645. &d = map->terrain[dest.x][dest.y][dest.z];
  1646. //get basic cost
  1647. int ret = h->getTileCost(d,s);
  1648. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1649. {
  1650. int old = ret;
  1651. ret *= 1.414213;
  1652. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1653. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1654. {
  1655. return remainingMovePoints;
  1656. }
  1657. }
  1658. int left = remainingMovePoints-ret;
  1659. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1660. {
  1661. std::vector<int3> vec;
  1662. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water);
  1663. for(size_t i=0; i < vec.size(); i++)
  1664. {
  1665. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1666. if(fcost <= left)
  1667. {
  1668. return ret;
  1669. }
  1670. }
  1671. ret = remainingMovePoints;
  1672. }
  1673. return ret;
  1674. }
  1675. std::set<int> CGameState::getBuildingRequiments(const CGTownInstance *t, int ID)
  1676. {
  1677. std::set<int> used;
  1678. used.insert(ID);
  1679. std::set<int> reqs = VLC->townh->requirements[t->subID][ID];
  1680. while(true)
  1681. {
  1682. size_t noloop=0;
  1683. for(std::set<int>::iterator i=reqs.begin();i!=reqs.end();i++)
  1684. {
  1685. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  1686. {
  1687. used.insert(*i);
  1688. for(
  1689. std::set<int>::iterator j=VLC->townh->requirements[t->subID][*i].begin();
  1690. j!=VLC->townh->requirements[t->subID][*i].end();
  1691. j++)
  1692. {
  1693. reqs.insert(*j);//creating full list of requirements
  1694. }
  1695. }
  1696. else
  1697. {
  1698. noloop++;
  1699. }
  1700. }
  1701. if(noloop==reqs.size())
  1702. break;
  1703. }
  1704. return reqs;
  1705. }
  1706. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1707. {
  1708. int ret = 7; //allowed by default
  1709. if(t->builded >= MAX_BUILDING_PER_TURN)
  1710. ret = 5; //building limit
  1711. //checking resources
  1712. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1713. if(!pom)
  1714. return 8;
  1715. // if(pom->Name().size()==0||pom->resources.size()==0)
  1716. // return 2;//TODO: why does this happen?
  1717. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1718. {
  1719. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1720. ret = 6; //lack of res
  1721. }
  1722. //checking for requirements
  1723. std::set<int> reqs = getBuildingRequiments(t, ID);//getting all requiments
  1724. for( std::set<int>::iterator ri = reqs.begin(); ri != reqs.end(); ri++ )
  1725. {
  1726. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1727. ret = 8; //lack of requirements - cannot build
  1728. }
  1729. //can we build it?
  1730. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1731. ret = 2; //forbidden
  1732. if(ID == 13) //capitol
  1733. {
  1734. for(unsigned int in = 0; in < map->towns.size(); in++)
  1735. {
  1736. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1737. {
  1738. ret = 0; //no more than one capitol
  1739. break;
  1740. }
  1741. }
  1742. }
  1743. else if(ID == 6) //shipyard
  1744. {
  1745. int3 t1(t->pos + int3(-1,3,0)),
  1746. t2(t->pos + int3(-3,3,0));
  1747. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1748. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1749. ret = 1; //lack of water
  1750. }
  1751. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1752. ret = 4;
  1753. return ret;
  1754. }
  1755. void CGameState::apply(CPack *pack)
  1756. {
  1757. ui16 typ = typeList.getTypeID(pack);
  1758. assert(typ >= 0);
  1759. applierGs->apps[typ]->applyOnGS(this,pack);
  1760. }
  1761. PlayerState * CGameState::getPlayer( ui8 color, bool verbose )
  1762. {
  1763. if(vstd::contains(players,color))
  1764. {
  1765. return &players[color];
  1766. }
  1767. else
  1768. {
  1769. if(verbose)
  1770. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1771. return NULL;
  1772. }
  1773. }
  1774. const PlayerState * CGameState::getPlayer( ui8 color, bool verbose ) const
  1775. {
  1776. return (const_cast<CGameState *>(this))->getPlayer(color, verbose);
  1777. }
  1778. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1779. {
  1780. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1781. return false;
  1782. int3 hpos = hero->getPosition(false);
  1783. bool flying = false; //hero is under flying effect TODO
  1784. bool waterWalking = false; //hero is on land and can walk on water TODO
  1785. bool onLand = map->getTile(hpos).tertype != TerrainTile::water;
  1786. // tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1787. //
  1788. // if (!hero->canWalkOnSea())
  1789. // blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1790. // else
  1791. // blockLandSea = boost::logic::indeterminate;
  1792. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1793. //graph initialization
  1794. std::vector< std::vector<CPathNode> > graph;
  1795. graph.resize(map->width);
  1796. for(size_t i=0; i<graph.size(); ++i)
  1797. {
  1798. graph[i].resize(map->height);
  1799. for(size_t j=0; j<graph[i].size(); ++j)
  1800. {
  1801. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1802. CPathNode &node = graph[i][j];
  1803. node.accessible = !tinfo->blocked;
  1804. node.dist = -1;
  1805. node.theNodeBefore = NULL;
  1806. node.visited = false;
  1807. node.coord.x = i;
  1808. node.coord.y = j;
  1809. node.coord.z = dest.z;
  1810. if(!tinfo->entrableTerrain(onLand, flying || waterWalking)
  1811. || !FoW[i][j][src.z] //tile is covered by the FoW
  1812. )
  1813. {
  1814. node.accessible = false;
  1815. }
  1816. }
  1817. }
  1818. //Special rules for the destination tile
  1819. {
  1820. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1821. CPathNode &d = graph[dest.x][dest.y];
  1822. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1823. if(t->visitable)
  1824. {
  1825. d.accessible = true; //for allowing visiting objects
  1826. }
  1827. if(onLand && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1828. {
  1829. size_t i = 0;
  1830. for(; i < t->visitableObjects.size(); i++)
  1831. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1832. break;
  1833. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1834. }
  1835. else if(!onLand && t->tertype != TerrainTile::water) //hero is moving by water
  1836. {
  1837. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1838. }
  1839. }
  1840. //graph initialized
  1841. //initial tile - set cost on 0 and add to the queue
  1842. graph[src.x][src.y].dist = 0;
  1843. std::queue<CPathNode> mq;
  1844. mq.push(graph[src.x][src.y]);
  1845. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1846. std::vector<int3> neighbours;
  1847. neighbours.reserve(8);
  1848. while(!mq.empty())
  1849. {
  1850. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1851. mq.pop();
  1852. if (cp.coord == dest) //it's destination tile
  1853. {
  1854. if (cp.dist < curDist) //that path is better than previous one
  1855. curDist = cp.dist;
  1856. continue;
  1857. }
  1858. else
  1859. {
  1860. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1861. continue;
  1862. }
  1863. //add accessible neighbouring nodes to the queue
  1864. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate);
  1865. for(unsigned int i=0; i < neighbours.size(); i++)
  1866. {
  1867. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1868. if(dp.accessible)
  1869. {
  1870. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1871. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1872. {
  1873. dp.dist = cp.dist + cost;
  1874. dp.theNodeBefore = &cp;
  1875. mq.push(dp);
  1876. }
  1877. }
  1878. }
  1879. }
  1880. CPathNode *curNode = &graph[dest.x][dest.y];
  1881. if(!curNode->theNodeBefore) //destination is not accessible
  1882. return false;
  1883. //fill ret with found path
  1884. ret.nodes.clear();
  1885. while(curNode->coord != graph[src.x][src.y].coord)
  1886. {
  1887. ret.nodes.push_back(*curNode);
  1888. curNode = curNode->theNodeBefore;
  1889. }
  1890. ret.nodes.push_back(graph[src.x][src.y]);
  1891. return true;
  1892. }
  1893. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1894. {
  1895. assert(hero);
  1896. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1897. if(src.x < 0)
  1898. src = hero->getPosition(false);
  1899. if(movement < 0)
  1900. movement = hero->movement;
  1901. out.hero = hero;
  1902. out.hpos = src;
  1903. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1904. {
  1905. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1906. return;
  1907. }
  1908. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1909. if (!hero->canWalkOnSea())
  1910. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1911. else
  1912. onLand = boost::logic::indeterminate;
  1913. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1914. //graph initialization
  1915. CGPathNode ***graph = out.nodes;
  1916. for(size_t i=0; i < out.sizes.x; ++i)
  1917. {
  1918. for(size_t j=0; j < out.sizes.y; ++j)
  1919. {
  1920. for(size_t k=0; k < out.sizes.z; ++k)
  1921. {
  1922. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1923. CGPathNode &node = graph[i][j][k];
  1924. node.accessible = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  1925. node.turns = 0xff;
  1926. node.moveRemains = 0;
  1927. node.coord.x = i;
  1928. node.coord.y = j;
  1929. node.coord.z = k;
  1930. node.land = tinfo->tertype != TerrainTile::water;
  1931. node.theNodeBefore = NULL;
  1932. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1933. || onLand && !node.land //it's sea and we cannot walk on sea
  1934. || !onLand && node.land //it's land and we cannot walk on land
  1935. || !FoW[i][j][k] //tile is covered by the FoW
  1936. )
  1937. {
  1938. node.accessible = CGPathNode::BLOCKED;
  1939. }
  1940. else if(tinfo->visitable)
  1941. {
  1942. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1943. {
  1944. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  1945. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  1946. {
  1947. node.accessible = CGPathNode::ACCESSIBLE;
  1948. }
  1949. else if(obj->blockVisit)
  1950. {
  1951. node.accessible = CGPathNode::BLOCKVIS;
  1952. break;
  1953. }
  1954. else if(obj->ID != EVENTI_TYPE) //pathfinder should ignore placed events
  1955. {
  1956. node.accessible = CGPathNode::VISITABLE;
  1957. }
  1958. }
  1959. }
  1960. else if (map->isInTheMap(guardingCreaturePosition(int3(i, j, k)))
  1961. && tinfo->blockingObjects.size() == 0)
  1962. {
  1963. // Monster close by; blocked visit for battle.
  1964. node.accessible = CGPathNode::BLOCKVIS;
  1965. }
  1966. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  1967. {
  1968. size_t i = 0;
  1969. for(; i < tinfo->visitableObjects.size(); i++)
  1970. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1971. break;
  1972. if(i < tinfo->visitableObjects.size())
  1973. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  1974. }
  1975. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  1976. {
  1977. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  1978. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  1979. }
  1980. }
  1981. }
  1982. }
  1983. //graph initialized
  1984. //initial tile - set cost on 0 and add to the queue
  1985. graph[src.x][src.y][src.z].turns = 0;
  1986. graph[src.x][src.y][src.z].moveRemains = movement;
  1987. std::queue<CGPathNode*> mq;
  1988. mq.push(&graph[src.x][src.y][src.z]);
  1989. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1990. std::vector<int3> neighbours;
  1991. neighbours.reserve(8);
  1992. while(!mq.empty())
  1993. {
  1994. CGPathNode *cp = mq.front();
  1995. mq.pop();
  1996. const TerrainTile &ct = map->getTile(cp->coord);
  1997. int movement = cp->moveRemains, turn = cp->turns;
  1998. if(!movement)
  1999. {
  2000. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2001. turn++;
  2002. }
  2003. //add accessible neighbouring nodes to the queue
  2004. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate);
  2005. for(unsigned int i=0; i < neighbours.size(); i++)
  2006. {
  2007. int moveAtNextTile = movement;
  2008. int turnAtNextTile = turn;
  2009. const int3 &n = neighbours[i]; //current neighbor
  2010. CGPathNode & dp = graph[n.x][n.y][n.z];
  2011. if( !checkForVisitableDir(cp->coord, dp.coord)
  2012. || !checkForVisitableDir(dp.coord, cp->coord)
  2013. || dp.accessible == CGPathNode::BLOCKED )
  2014. {
  2015. continue;
  2016. }
  2017. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  2018. int remains = movement - cost;
  2019. if(remains < 0)
  2020. {
  2021. //occurs rarely, when hero with low movepoints tries to go leave the road
  2022. turnAtNextTile++;
  2023. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2024. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2025. remains = moveAtNextTile - cost;
  2026. }
  2027. const bool guardedPosition = guardingCreaturePosition(cp->coord) != int3(-1, -1, -1);
  2028. const bool neighborIsGuard = guardingCreaturePosition(cp->coord) == dp.coord;
  2029. if((dp.turns==0xff //we haven't been here before
  2030. || dp.turns > turnAtNextTile
  2031. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  2032. && (!guardedPosition || neighborIsGuard)) // Can step into tile of guard
  2033. {
  2034. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  2035. dp.moveRemains = remains;
  2036. dp.turns = turnAtNextTile;
  2037. dp.theNodeBefore = cp;
  2038. const bool guardedNeighbor = guardingCreaturePosition(dp.coord) != int3(-1, -1, -1);
  2039. const bool positionIsGuard = guardingCreaturePosition(cp->coord) == cp->coord;
  2040. if (dp.accessible == CGPathNode::ACCESSIBLE
  2041. || (guardedNeighbor && !positionIsGuard)) // Can step into a hostile tile once.
  2042. {
  2043. mq.push(&dp);
  2044. }
  2045. }
  2046. } //neighbours loop
  2047. } //queue loop
  2048. }
  2049. /**
  2050. * Tells if the tile is guarded by a monster as well as the position
  2051. * of the monster that will attack on it.
  2052. *
  2053. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  2054. * the monster guarding the tile.
  2055. */
  2056. int3 CGameState::guardingCreaturePosition (int3 pos) const
  2057. {
  2058. // Give monster at position priority.
  2059. if (!map->isInTheMap(pos))
  2060. return int3(-1, -1, -1);
  2061. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  2062. if (posTile.visitable) {
  2063. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects) {
  2064. if (obj->ID == 54) { // Monster
  2065. return pos;
  2066. }
  2067. }
  2068. }
  2069. // See if there are any monsters adjacent.
  2070. pos -= int3(1, 1, 0); // Start with top left.
  2071. for (int dx = 0; dx < 3; dx++) {
  2072. for (int dy = 0; dy < 3; dy++) {
  2073. if (map->isInTheMap(pos)) {
  2074. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  2075. if (tile.visitable) {
  2076. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects) {
  2077. if (obj->ID == 54) { // Monster
  2078. return pos;
  2079. }
  2080. }
  2081. }
  2082. }
  2083. pos.y++;
  2084. }
  2085. pos.y -= 3;
  2086. pos.x++;
  2087. }
  2088. return int3(-1, -1, -1);
  2089. }
  2090. bool CGameState::isVisible(int3 pos, int player)
  2091. {
  2092. if(player == 255) //neutral player
  2093. return false;
  2094. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  2095. }
  2096. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  2097. {
  2098. if(player == 255) //neutral player
  2099. return false;
  2100. //object is visible when at least one blocked tile is visible
  2101. for(int fx=0; fx<8; ++fx)
  2102. {
  2103. for(int fy=0; fy<6; ++fy)
  2104. {
  2105. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  2106. if(map->isInTheMap(pos)
  2107. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  2108. && isVisible(pos, player) )
  2109. return true;
  2110. }
  2111. }
  2112. return false;
  2113. }
  2114. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2115. {
  2116. const TerrainTile * pom = &map->getTile(dst);
  2117. return checkForVisitableDir(src, pom, dst);
  2118. }
  2119. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2120. {
  2121. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2122. {
  2123. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2124. continue;
  2125. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2126. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2127. {
  2128. return false;
  2129. }
  2130. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2131. {
  2132. return false;
  2133. }
  2134. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2135. {
  2136. return false;
  2137. }
  2138. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2139. {
  2140. return false;
  2141. }
  2142. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2143. {
  2144. return false;
  2145. }
  2146. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2147. {
  2148. return false;
  2149. }
  2150. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2151. {
  2152. return false;
  2153. }
  2154. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2155. {
  2156. return false;
  2157. }
  2158. }
  2159. return true;
  2160. }
  2161. std::pair<ui32, ui32> BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  2162. {
  2163. float additiveBonus=1.0f, multBonus=1.0f,
  2164. minDmg = attacker->type->damageMin * attacker->count,
  2165. maxDmg = attacker->type->damageMax * attacker->count;
  2166. if(attacker->type->idNumber == 149) //arrow turret
  2167. {
  2168. switch(attacker->position)
  2169. {
  2170. case -2: //keep
  2171. minDmg = 15;
  2172. maxDmg = 15;
  2173. break;
  2174. case -3: case -4: //turrets
  2175. minDmg = 7.5f;
  2176. maxDmg = 7.5f;
  2177. break;
  2178. }
  2179. }
  2180. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->type->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  2181. { //minDmg and maxDmg are multiplied by hero attack + 1
  2182. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2183. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2184. }
  2185. int attackDefenceDifference = 0;
  2186. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  2187. {
  2188. float multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f;
  2189. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  2190. }
  2191. else
  2192. {
  2193. attackDefenceDifference = attacker->Attack();
  2194. }
  2195. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  2196. {
  2197. float multDefenceReduction = (100.0f - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0f;
  2198. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  2199. }
  2200. else
  2201. {
  2202. attackDefenceDifference -= defender->Defense();
  2203. }
  2204. //calculating total attack/defense skills modifier
  2205. if(shooting) //precision handling (etc.)
  2206. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)).totalValue();
  2207. else //bloodlust handling (etc.)
  2208. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT)).totalValue();
  2209. if(attacker->getEffect(55)) //slayer handling
  2210. {
  2211. std::vector<int> affectedIds;
  2212. int spLevel = attacker->getEffect(55)->level;
  2213. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  2214. {
  2215. BOOST_FOREACH(const Bonus &b, VLC->creh->creatures[g]->bonuses)
  2216. {
  2217. if ( (b.type == Bonus::KING3 && spLevel >= 3) || //expert
  2218. (b.type == Bonus::KING2 && spLevel >= 2) || //adv +
  2219. (b.type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  2220. {
  2221. affectedIds.push_back(g);
  2222. break;
  2223. }
  2224. }
  2225. }
  2226. for(unsigned int g=0; g<affectedIds.size(); ++g)
  2227. {
  2228. if(defender->type->idNumber == affectedIds[g])
  2229. {
  2230. attackDefenceDifference += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  2231. break;
  2232. }
  2233. }
  2234. }
  2235. //bonus from attack/defense skills
  2236. if(attackDefenceDifference < 0) //decreasing dmg
  2237. {
  2238. float dec = 0.025f * (-attackDefenceDifference);
  2239. if(dec > 0.7f)
  2240. {
  2241. multBonus *= 0.3f; //1.0 - 0.7
  2242. }
  2243. else
  2244. {
  2245. multBonus *= 1.0f - dec;
  2246. }
  2247. }
  2248. else //increasing dmg
  2249. {
  2250. float inc = 0.05f * attackDefenceDifference;
  2251. if(inc > 4.0f)
  2252. {
  2253. additiveBonus += 4.0f;
  2254. }
  2255. else
  2256. {
  2257. additiveBonus += inc;
  2258. }
  2259. }
  2260. //applying jousting bonus
  2261. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  2262. additiveBonus += charge * 0.05f;
  2263. //handling secondary abilities and artifacts giving premies to them
  2264. if(attackerHero)
  2265. {
  2266. if(shooting)
  2267. {
  2268. switch(attackerHero->getSecSkillLevel(1)) //archery
  2269. {
  2270. case 1: //basic
  2271. additiveBonus += 0.1f;
  2272. break;
  2273. case 2: //advanced
  2274. additiveBonus += 0.25f;
  2275. break;
  2276. case 3: //expert
  2277. additiveBonus += 0.5f;
  2278. break;
  2279. }
  2280. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  2281. {
  2282. //apply artifact premy to archery
  2283. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2284. }
  2285. }
  2286. else
  2287. {
  2288. switch(attackerHero->getSecSkillLevel(22)) //offense
  2289. {
  2290. case 1: //basic
  2291. additiveBonus += 0.1f;
  2292. break;
  2293. case 2: //advanced
  2294. additiveBonus += 0.2f;
  2295. break;
  2296. case 3: //expert
  2297. additiveBonus += 0.3f;
  2298. break;
  2299. }
  2300. }
  2301. }
  2302. if(defendingHero)
  2303. {
  2304. switch(defendingHero->getSecSkillLevel(23)) //armorer
  2305. {
  2306. case 1: //basic
  2307. multBonus *= 0.95f;
  2308. break;
  2309. case 2: //advanced
  2310. multBonus *= 0.9f;
  2311. break;
  2312. case 3: //expert
  2313. multBonus *= 0.85f;
  2314. break;
  2315. }
  2316. }
  2317. //handling hate effect
  2318. if( attacker->hasBonusOfType(Bonus::HATE, defender->type->idNumber) )
  2319. additiveBonus += 0.5f;
  2320. //luck bonus
  2321. if (lucky)
  2322. {
  2323. additiveBonus += 1.0f;
  2324. }
  2325. //handling spell effects
  2326. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2327. {
  2328. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2329. }
  2330. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2331. {
  2332. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2333. }
  2334. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2335. {
  2336. multBonus *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2337. }
  2338. class HLP
  2339. {
  2340. public:
  2341. static bool hasAdvancedAirShield(const CStack * stack)
  2342. {
  2343. for(int g=0; g<stack->effects.size(); ++g)
  2344. {
  2345. if (stack->effects[g].id == 28 && stack->effects[g].level >= 2)
  2346. {
  2347. return true;
  2348. }
  2349. }
  2350. return false;
  2351. }
  2352. };
  2353. //wall / distance penalty + advanced air shield
  2354. if (shooting && (
  2355. hasDistancePenalty(attacker->ID, defender->position) || hasWallPenalty(attacker->ID, defender->position) ||
  2356. HLP::hasAdvancedAirShield(defender) )
  2357. )
  2358. {
  2359. multBonus *= 0.5;
  2360. }
  2361. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  2362. {
  2363. multBonus *= 0.5;
  2364. }
  2365. minDmg *= additiveBonus * multBonus;
  2366. maxDmg *= additiveBonus * multBonus;
  2367. std::pair<ui32, ui32> returnedVal;
  2368. if(attacker->getEffect(42)) //curse handling (rest)
  2369. {
  2370. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2371. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  2372. }
  2373. else if(attacker->getEffect(41)) //bless handling
  2374. {
  2375. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2376. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  2377. }
  2378. else
  2379. {
  2380. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  2381. }
  2382. //damage cannot be less than 1
  2383. amax(returnedVal.first, 1);
  2384. amax(returnedVal.second, 1);
  2385. return returnedVal;
  2386. }
  2387. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  2388. {
  2389. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky);
  2390. if(range.first != range.second)
  2391. {
  2392. int valuesToAverage[10];
  2393. int howManyToAv = std::min<ui32>(10, attacker->count);
  2394. for (int g=0; g<howManyToAv; ++g)
  2395. {
  2396. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  2397. }
  2398. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  2399. }
  2400. else
  2401. return range.first;
  2402. }
  2403. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  2404. {
  2405. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2406. {
  2407. const CStack * const st = stacks[i];
  2408. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  2409. amax(killed, 0);
  2410. if(killed)
  2411. casualties[!st->attackerOwned][st->type->idNumber] += killed;
  2412. }
  2413. }
  2414. si8 CGameState::battleMaxSpellLevel()
  2415. {
  2416. if(!curB) //there is not battle
  2417. {
  2418. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2419. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2420. }
  2421. si8 levelLimit = SPELL_LEVELS;
  2422. const CGHeroInstance *h1 = curB->heroes[0];
  2423. if(h1)
  2424. {
  2425. for(std::list<Bonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2426. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2427. amin(levelLimit, i->val);
  2428. }
  2429. const CGHeroInstance *h2 = curB->heroes[1];
  2430. if(h2)
  2431. {
  2432. for(std::list<Bonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2433. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2434. amin(levelLimit, i->val);
  2435. }
  2436. return levelLimit;
  2437. }
  2438. std::set<CStack*> BattleInfo::getAttackedCreatures( const CSpell * s, int skillLevel, ui8 attackerOwner, int destinationTile )
  2439. {
  2440. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  2441. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  2442. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2443. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  2444. {
  2445. for(int it=0; it<stacks.size(); ++it)
  2446. {
  2447. if((s->id == 24 && !stacks[it]->type->isUndead()) //death ripple
  2448. || (s->id == 25 && stacks[it]->type->isUndead()) //destroy undead
  2449. || (s->id == 26) //Armageddon
  2450. )
  2451. {
  2452. if(stacks[it]->alive())
  2453. attackedCres.insert(stacks[it]);
  2454. }
  2455. }
  2456. }
  2457. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2458. || VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  2459. {
  2460. if(skillLevel < 3) /*not expert */
  2461. {
  2462. CStack * st = getStackT(destinationTile, onlyAlive);
  2463. if(st)
  2464. attackedCres.insert(st);
  2465. }
  2466. else
  2467. {
  2468. for(int it=0; it<stacks.size(); ++it)
  2469. {
  2470. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2471. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == attackerOwner)
  2472. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != attackerOwner )
  2473. )
  2474. {
  2475. if(!onlyAlive || stacks[it]->alive())
  2476. attackedCres.insert(stacks[it]);
  2477. }
  2478. }
  2479. } //if(caster->getSpellSchoolLevel(s) < 3)
  2480. }
  2481. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2482. {
  2483. CStack * st = getStackT(destinationTile, onlyAlive);
  2484. if(st)
  2485. attackedCres.insert(st);
  2486. }
  2487. else //custom range from attackedHexes
  2488. {
  2489. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2490. {
  2491. CStack * st = getStackT(*it, onlyAlive);
  2492. if(st)
  2493. attackedCres.insert(st);
  2494. }
  2495. }
  2496. return attackedCres;
  2497. }
  2498. int BattleInfo::calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster)
  2499. {
  2500. if(!caster) //TODO: something better
  2501. return 5;
  2502. switch(spell->id)
  2503. {
  2504. case 56: //frenzy
  2505. return 1;
  2506. default: //other spells
  2507. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  2508. }
  2509. }
  2510. CStack * BattleInfo::generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2511. {
  2512. CStack * ret = new CStack(&base, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2513. //native terrain bonuses
  2514. int faction = ret->type->faction;
  2515. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2516. {
  2517. ret->bonuses.push_back(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE));
  2518. ret->bonuses.push_back(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE));
  2519. ret->bonuses.push_back(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE));
  2520. }
  2521. ret->position = position;
  2522. return ret;
  2523. }
  2524. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2525. {
  2526. ui32 ret = caster->getSpellCost(sp);
  2527. //checking for friendly stacks reducing cost of the spell and
  2528. //enemy stacks increasing it
  2529. si32 manaReduction = 0;
  2530. si32 manaIncrease = 0;
  2531. for(int g=0; g<stacks.size(); ++g)
  2532. {
  2533. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  2534. {
  2535. amin(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  2536. }
  2537. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  2538. {
  2539. amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  2540. }
  2541. }
  2542. return ret + manaReduction + manaIncrease;
  2543. }
  2544. int BattleInfo::hexToWallPart(int hex) const
  2545. {
  2546. if(siege == 0) //there is no battle!
  2547. return -1;
  2548. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2549. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2550. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7)};
  2551. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2552. {
  2553. if(attackable[g].first == hex)
  2554. return attackable[g].second;
  2555. }
  2556. return -1; //not found!
  2557. }
  2558. int BattleInfo::lineToWallHex( int line ) const
  2559. {
  2560. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  2561. return lineToHex[line];
  2562. }
  2563. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2564. {
  2565. bool ac[BFIELD_SIZE];
  2566. std::set<int> occupyable;
  2567. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest->ID);
  2568. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2569. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  2570. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2571. for(int g=0; g<BFIELD_SIZE; ++g)
  2572. {
  2573. const CStack * atG = getStackT(g);
  2574. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2575. continue;
  2576. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2577. {
  2578. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2579. continue;
  2580. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2581. }
  2582. }
  2583. if(stackPairs.size() > 0)
  2584. {
  2585. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  2586. minimalPairs.push_back(stackPairs[0]);
  2587. for(int b=1; b<stackPairs.size(); ++b)
  2588. {
  2589. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  2590. {
  2591. minimalPairs.clear();
  2592. minimalPairs.push_back(stackPairs[b]);
  2593. }
  2594. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  2595. {
  2596. minimalPairs.push_back(stackPairs[b]);
  2597. }
  2598. }
  2599. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  2600. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  2601. }
  2602. return std::make_pair<const CStack * , int>(NULL, -1);
  2603. }
  2604. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  2605. {
  2606. ui32 ret = 0; //value to return
  2607. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  2608. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  2609. static std::map <int, int> dmgMultipliers = boost::assign::map_list_of(15, 10)(16, 20)(17, 25)(18, 75)(20, 10)(21, 10)(22, 10)(23, 10)(24, 5)(25, 10)(26, 50)(77, 10);
  2610. //check if spell really does damage - if not, return 0
  2611. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  2612. return 0;
  2613. ret = usedSpellPower * dmgMultipliers[sp->id];
  2614. ret += sp->powers[spellSchoolLevel];
  2615. //applying sorcerery secondary skill
  2616. if(caster)
  2617. {
  2618. switch(caster->getSecSkillLevel(25))
  2619. {
  2620. case 1: //basic
  2621. ret *= 1.05f;
  2622. break;
  2623. case 2: //advanced
  2624. ret *= 1.1f;
  2625. break;
  2626. case 3: //expert
  2627. ret *= 1.15f;
  2628. break;
  2629. }
  2630. }
  2631. //applying hero bonuses
  2632. if(sp->air && caster && caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY) != 0)
  2633. {
  2634. ret *= (100.0f + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0f;
  2635. }
  2636. else if(sp->fire && caster && caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY) != 0)
  2637. {
  2638. ret *= (100.0f + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0f;
  2639. }
  2640. else if(sp->water && caster && caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY) != 0)
  2641. {
  2642. ret *= (100.0f + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0f;
  2643. }
  2644. else if(sp->earth && caster && caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY) != 0)
  2645. {
  2646. ret *= (100.0f + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0f;
  2647. }
  2648. //affected creature-specific part
  2649. if(affectedCreature)
  2650. {
  2651. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  2652. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  2653. {
  2654. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  2655. ret /= 100;
  2656. }
  2657. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  2658. {
  2659. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  2660. ret /= 100;
  2661. }
  2662. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  2663. {
  2664. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  2665. ret /= 100;
  2666. }
  2667. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  2668. {
  2669. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  2670. ret /= 100;
  2671. }
  2672. //general spell dmg reduction
  2673. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  2674. {
  2675. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  2676. ret /= 100;
  2677. }
  2678. //dmg increasing
  2679. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  2680. {
  2681. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  2682. ret /= 100;
  2683. }
  2684. }
  2685. return ret;
  2686. }
  2687. bool CGameState::battleCanShoot(int ID, int dest)
  2688. {
  2689. if(!curB)
  2690. return false;
  2691. const CStack *our = curB->getStack(ID),
  2692. *dst = curB->getStackT(dest);
  2693. if(!our || !dst) return false;
  2694. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  2695. if(our->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  2696. return false;
  2697. if(our->type->idNumber == 145 && dst) //catapult cannot attack creatures
  2698. return false;
  2699. if(our->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  2700. && our->owner != dst->owner
  2701. && dst->alive()
  2702. && (!curB->isStackBlocked(ID) || NBonus::hasOfType(ourHero, Bonus::FREE_SHOOTING))
  2703. && our->shots
  2704. )
  2705. return true;
  2706. return false;
  2707. }
  2708. int CGameState::victoryCheck( ui8 player ) const
  2709. {
  2710. const PlayerState *p = getPlayer(player);
  2711. if(map->victoryCondition.condition == winStandard || map->victoryCondition.allowNormalVictory)
  2712. if(player == checkForStandardWin())
  2713. return -1;
  2714. if(p->human || map->victoryCondition.appliesToAI)
  2715. {
  2716. switch(map->victoryCondition.condition)
  2717. {
  2718. case artifact:
  2719. //check if any hero has winning artifact
  2720. for(size_t i = 0; i < p->heroes.size(); i++)
  2721. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  2722. return 1;
  2723. break;
  2724. case gatherTroop:
  2725. {
  2726. //check if in players armies there is enough creatures
  2727. int total = 0; //creature counter
  2728. for(size_t i = 0; i < map->objects.size(); i++)
  2729. {
  2730. const CArmedInstance *ai = NULL;
  2731. if(map->objects[i]
  2732. && map->objects[i]->tempOwner == player //object controlled by player
  2733. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i]))) //contains army
  2734. {
  2735. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  2736. if(i->second.type->idNumber == map->victoryCondition.ID) //it's searched creature
  2737. total += i->second.count;
  2738. }
  2739. }
  2740. if(total >= map->victoryCondition.count)
  2741. return 1;
  2742. }
  2743. break;
  2744. case gatherResource:
  2745. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  2746. return 1;
  2747. break;
  2748. case buildCity:
  2749. {
  2750. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2751. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  2752. return 1;
  2753. }
  2754. break;
  2755. case buildGrail:
  2756. for(size_t i = 0; i < map->towns.size(); i++)
  2757. if(map->towns[i]->pos == map->victoryCondition.pos
  2758. && map->towns[i]->tempOwner == player
  2759. && vstd::contains(map->towns[i]->builtBuildings, 26))
  2760. return 1;
  2761. break;
  2762. case beatHero:
  2763. if(map->victoryCondition.obj->tempOwner >= PLAYER_LIMIT) //target hero not present on map
  2764. return 1;
  2765. break;
  2766. case captureCity:
  2767. {
  2768. if(map->victoryCondition.obj->tempOwner == player)
  2769. return 1;
  2770. }
  2771. break;
  2772. case beatMonster:
  2773. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  2774. return 1;
  2775. break;
  2776. case takeDwellings:
  2777. for(size_t i = 0; i < map->objects.size(); i++)
  2778. {
  2779. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2780. {
  2781. switch(map->objects[i]->ID)
  2782. {
  2783. case 17: case 18: case 19: case 20: //dwellings
  2784. case 216: case 217: case 218:
  2785. return 0; //found not flagged dwelling - player not won
  2786. }
  2787. }
  2788. }
  2789. return 1;
  2790. break;
  2791. case takeMines:
  2792. for(size_t i = 0; i < map->objects.size(); i++)
  2793. {
  2794. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2795. {
  2796. switch(map->objects[i]->ID)
  2797. {
  2798. case 53: case 220:
  2799. return 0; //found not flagged mine - player not won
  2800. }
  2801. }
  2802. }
  2803. return 1;
  2804. break;
  2805. case transportItem:
  2806. {
  2807. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2808. if(t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID)
  2809. || t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID))
  2810. {
  2811. return 1;
  2812. }
  2813. }
  2814. break;
  2815. }
  2816. }
  2817. return 0;
  2818. }
  2819. ui8 CGameState::checkForStandardWin() const
  2820. {
  2821. //std victory condition is:
  2822. //all enemies lost
  2823. ui8 supposedWinner = 255, winnerTeam = 255;
  2824. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  2825. {
  2826. if(i->second.status == PlayerState::INGAME && i->first < PLAYER_LIMIT)
  2827. {
  2828. if(supposedWinner == 255)
  2829. {
  2830. //first player remaining ingame - candidate for victory
  2831. supposedWinner = i->second.color;
  2832. winnerTeam = map->players[supposedWinner].team;
  2833. }
  2834. else if(winnerTeam != map->players[i->second.color].team)
  2835. {
  2836. //current candidate has enemy remaining in game -> no vicotry
  2837. return 255;
  2838. }
  2839. }
  2840. }
  2841. return supposedWinner;
  2842. }
  2843. bool CGameState::checkForStandardLoss( ui8 player ) const
  2844. {
  2845. //std loss condition is: player lost all towns and heroes
  2846. const PlayerState &p = *getPlayer(player);
  2847. return !p.heroes.size() && !p.towns.size();
  2848. }
  2849. struct statsHLP
  2850. {
  2851. typedef std::pair< ui8, si64 > TStat;
  2852. //converts [<player's color, value>] to vec[place] -> platers
  2853. static std::vector< std::list< ui8 > > getRank( std::vector<TStat> stats )
  2854. {
  2855. std::sort(stats.begin(), stats.end(), statsHLP());
  2856. //put first element
  2857. std::vector< std::list<ui8> > ret;
  2858. std::list<ui8> tmp;
  2859. tmp.push_back( stats[0].first );
  2860. ret.push_back( tmp );
  2861. //the rest of elements
  2862. for(int g=1; g<stats.size(); ++g)
  2863. {
  2864. if(stats[g].second == stats[g-1].second)
  2865. {
  2866. (ret.end()-1)->push_back( stats[g].first );
  2867. }
  2868. else
  2869. {
  2870. //create next occupied rank
  2871. std::list<ui8> tmp;
  2872. tmp.push_back(stats[g].first);
  2873. ret.push_back(tmp);
  2874. }
  2875. }
  2876. return ret;
  2877. }
  2878. bool operator()(const TStat & a, const TStat & b) const
  2879. {
  2880. return a.second > b.second;
  2881. }
  2882. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2883. {
  2884. std::vector<CGHeroInstance *> &h = gs->players[color].heroes;
  2885. if(!h.size())
  2886. return NULL;
  2887. //best hero will be that with highest exp
  2888. int best = 0;
  2889. for(int b=1; b<h.size(); ++b)
  2890. {
  2891. if(h[b]->exp > h[best]->exp)
  2892. {
  2893. best = b;
  2894. }
  2895. }
  2896. return h[best];
  2897. }
  2898. //calculates total number of artifacts that belong to given player
  2899. static int getNumberOfArts(const PlayerState * ps)
  2900. {
  2901. int ret = 0;
  2902. for(int g=0; g<ps->heroes.size(); ++g)
  2903. {
  2904. ret += ps->heroes[g]->artifacts.size() + ps->heroes[g]->artifWorn.size();
  2905. }
  2906. return ret;
  2907. }
  2908. };
  2909. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2910. {
  2911. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2912. { \
  2913. std::vector< std::pair< ui8, si64 > > stats; \
  2914. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  2915. { \
  2916. if(g->second.color == 255) \
  2917. continue; \
  2918. std::pair< ui8, si64 > stat; \
  2919. stat.first = g->second.color; \
  2920. stat.second = VAL_GETTER; \
  2921. stats.push_back(stat); \
  2922. } \
  2923. tgi.FIELD = statsHLP::getRank(stats); \
  2924. }
  2925. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2926. {
  2927. if(g->second.color != 255)
  2928. tgi.playerColors.push_back(g->second.color);
  2929. }
  2930. if(level >= 1) //num of towns & num of heroes
  2931. {
  2932. //num of towns
  2933. FILL_FIELD(numOfTowns, g->second.towns.size())
  2934. //num of heroes
  2935. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2936. //best hero's portrait
  2937. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2938. {
  2939. if(g->second.color == 255)
  2940. continue;
  2941. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2942. InfoAboutHero iah;
  2943. iah.initFromHero(best, level >= 8);
  2944. iah.army.clear();
  2945. tgi.colorToBestHero[g->second.color] = iah;
  2946. }
  2947. }
  2948. if(level >= 2) //gold
  2949. {
  2950. FILL_FIELD(gold, g->second.resources[6])
  2951. }
  2952. if(level >= 2) //wood & ore
  2953. {
  2954. FILL_FIELD(woodOre, g->second.resources[0] + g->second.resources[1])
  2955. }
  2956. if(level >= 3) //mercury, sulfur, crystal, gems
  2957. {
  2958. FILL_FIELD(mercSulfCrystGems, g->second.resources[2] + g->second.resources[3] + g->second.resources[4] + g->second.resources[5])
  2959. }
  2960. if(level >= 4) //obelisks found
  2961. {
  2962. //TODO
  2963. }
  2964. if(level >= 5) //artifacts
  2965. {
  2966. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2967. }
  2968. if(level >= 6) //army strength
  2969. {
  2970. //TODO
  2971. }
  2972. if(level >= 7) //income
  2973. {
  2974. //TODO
  2975. }
  2976. if(level >= 8) //best hero's stats
  2977. {
  2978. //already set in lvl 1 handling
  2979. }
  2980. if(level >= 9) //personality
  2981. {
  2982. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2983. {
  2984. if(g->second.color == 255) //do nothing for neutral player
  2985. continue;
  2986. if(g->second.human)
  2987. {
  2988. tgi.personality[g->second.color] = -1;
  2989. }
  2990. else //AI
  2991. {
  2992. tgi.personality[g->second.color] = map->players[g->second.serial].AITactic;
  2993. }
  2994. }
  2995. }
  2996. if(level >= 10) //best creature
  2997. {
  2998. //best creatures belonging to player (highest AI value)
  2999. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3000. {
  3001. if(g->second.color == 255) //do nothing for neutral player
  3002. continue;
  3003. int bestCre = -1; //best creature's ID
  3004. for(int b=0; b<g->second.heroes.size(); ++b)
  3005. {
  3006. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  3007. {
  3008. int toCmp = it->second.type->idNumber; //ID of creature we should compare with the best one
  3009. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  3010. {
  3011. bestCre = toCmp;
  3012. }
  3013. }
  3014. }
  3015. tgi.bestCreature[g->second.color] = bestCre;
  3016. }
  3017. }
  3018. #undef FILL_FIELD
  3019. }
  3020. int CGameState::lossCheck( ui8 player ) const
  3021. {
  3022. const PlayerState *p = getPlayer(player);
  3023. //if(map->lossCondition.typeOfLossCon == lossStandard)
  3024. if(checkForStandardLoss(player))
  3025. return -1;
  3026. if(p->human) //special loss condition applies only to human player
  3027. {
  3028. switch(map->lossCondition.typeOfLossCon)
  3029. {
  3030. case lossCastle:
  3031. {
  3032. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  3033. assert(t);
  3034. if(t->tempOwner != player)
  3035. return 1;
  3036. }
  3037. break;
  3038. case lossHero:
  3039. {
  3040. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  3041. assert(h);
  3042. if(h->tempOwner != player)
  3043. return 1;
  3044. }
  3045. break;
  3046. case timeExpires:
  3047. if(map->lossCondition.timeLimit < day)
  3048. return 1;
  3049. break;
  3050. }
  3051. }
  3052. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  3053. return 2;
  3054. return false;
  3055. }
  3056. const CStack * BattleInfo::getNextStack() const
  3057. {
  3058. std::vector<const CStack *> hlp;
  3059. getStackQueue(hlp, 1, -1);
  3060. if(hlp.size())
  3061. return hlp[0];
  3062. else
  3063. return NULL;
  3064. }
  3065. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  3066. {
  3067. const CStack *ret = NULL;
  3068. unsigned i, //fastest stack
  3069. j; //fastest stack of the other side
  3070. for(i = 0; i < st.size(); i++)
  3071. if(st[i])
  3072. break;
  3073. //no stacks left
  3074. if(i == st.size())
  3075. return NULL;
  3076. const CStack *fastest = st[i], *other = NULL;
  3077. int bestSpeed = fastest->Speed(turn);
  3078. if(fastest->attackerOwned != curside)
  3079. {
  3080. ret = fastest;
  3081. }
  3082. else
  3083. {
  3084. for(j = i + 1; j < st.size(); j++)
  3085. {
  3086. if(!st[j]) continue;
  3087. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  3088. break;
  3089. }
  3090. if(j >= st.size())
  3091. {
  3092. ret = fastest;
  3093. }
  3094. else
  3095. {
  3096. other = st[j];
  3097. if(other->Speed(turn) != bestSpeed)
  3098. ret = fastest;
  3099. else
  3100. ret = other;
  3101. }
  3102. }
  3103. assert(ret);
  3104. if(ret == fastest)
  3105. st[i] = NULL;
  3106. else
  3107. st[j] = NULL;
  3108. curside = ret->attackerOwned;
  3109. return ret;
  3110. }
  3111. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  3112. {
  3113. //we'll split creatures with remaining movement to 4 parts
  3114. std::vector<const CStack *> phase[4]; //0 - turrets/catapult, 1 - normal (unmoved) creatures, other war machines, 2 - waited cres that had morale, 3 - rest of waited cres
  3115. int toMove = 0; //how many stacks still has move
  3116. const CStack *active = getStack(activeStack);
  3117. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  3118. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  3119. {
  3120. out.push_back(active);
  3121. if(out.size() == howMany)
  3122. return;
  3123. }
  3124. for(unsigned int i=0; i<stacks.size(); ++i)
  3125. {
  3126. const CStack * const s = stacks[i];
  3127. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  3128. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  3129. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  3130. {
  3131. continue;
  3132. }
  3133. int p = -1; //in which phase this tack will move?
  3134. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  3135. {
  3136. if(vstd::contains(s->state, HAD_MORALE))
  3137. p = 2;
  3138. else
  3139. p = 3;
  3140. }
  3141. else if(s->type->idNumber == 145 || s->type->idNumber == 149) //catapult and turrets are first
  3142. {
  3143. p = 0;
  3144. }
  3145. else
  3146. {
  3147. p = 1;
  3148. }
  3149. phase[p].push_back(s);
  3150. toMove++;
  3151. }
  3152. for(int i = 0; i < 4; i++)
  3153. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  3154. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  3155. out.push_back(phase[0][i]);
  3156. if(out.size() == howMany)
  3157. return;
  3158. if(lastMoved == -1)
  3159. {
  3160. if(active)
  3161. {
  3162. if(out.size() && out.front() == active)
  3163. lastMoved = active->attackerOwned;
  3164. else
  3165. lastMoved = active->attackerOwned;
  3166. }
  3167. else
  3168. {
  3169. lastMoved = 0;
  3170. }
  3171. }
  3172. int pi = 1;
  3173. while(out.size() < howMany)
  3174. {
  3175. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  3176. if(!hlp)
  3177. {
  3178. pi++;
  3179. if(pi > 3)
  3180. {
  3181. //if(turn != 2)
  3182. getStackQueue(out, howMany, turn + 1, lastMoved);
  3183. return;
  3184. }
  3185. }
  3186. else
  3187. {
  3188. out.push_back(hlp);
  3189. }
  3190. }
  3191. }
  3192. si8 BattleInfo::hasDistancePenalty( int stackID, int destHex )
  3193. {
  3194. const CStack * stack = getStack(stackID);
  3195. int distance = std::abs(destHex % BFIELD_WIDTH - stack->position % BFIELD_WIDTH);
  3196. //I hope it's approximately correct
  3197. return distance > 8 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  3198. }
  3199. si8 BattleInfo::sameSideOfWall(int pos1, int pos2)
  3200. {
  3201. int wallInStackLine = lineToWallHex(pos1/BFIELD_WIDTH);
  3202. int wallInDestLine = lineToWallHex(pos2/BFIELD_WIDTH);
  3203. bool stackLeft = pos1 < wallInStackLine;
  3204. bool destLeft = pos2 < wallInDestLine;
  3205. return stackLeft != destLeft;
  3206. }
  3207. si8 BattleInfo::hasWallPenalty( int stackID, int destHex )
  3208. {
  3209. if (siege == 0)
  3210. {
  3211. return false;
  3212. }
  3213. const CStack * stack = getStack(stackID);
  3214. if (stack->hasBonusOfType(Bonus::NO_WALL_PENALTY));
  3215. {
  3216. return false;
  3217. }
  3218. return !sameSideOfWall(stack->position, destHex);
  3219. }
  3220. si8 BattleInfo::canTeleportTo(int stackID, int destHex, int telportLevel)
  3221. {
  3222. bool ac[BFIELD_SIZE];
  3223. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  3224. std::set<int> occupyable;
  3225. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, false, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  3226. if (siege && telportLevel < 2) //check for wall
  3227. {
  3228. return ac[destHex] && sameSideOfWall(s->position, destHex);
  3229. }
  3230. else
  3231. {
  3232. return ac[destHex];
  3233. }
  3234. }
  3235. void BattleInfo::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  3236. {
  3237. CBonusSystemNode::getBonuses(out, selector, root);
  3238. const CStack *dest = dynamic_cast<const CStack*>(root);
  3239. if (!dest)
  3240. return;
  3241. //TODO: make it in clean way
  3242. if(Selector::matchesType(selector, Bonus::MORALE) || Selector::matchesType(selector, Bonus::LUCK))
  3243. {
  3244. BOOST_FOREACH(const CStack *s, stacks)
  3245. {
  3246. if(s->owner == dest->owner)
  3247. s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ALLIED_ARMY), this);
  3248. else
  3249. s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ENEMY_ARMY), this);
  3250. }
  3251. }
  3252. }
  3253. int3 CPath::startPos() const
  3254. {
  3255. return nodes[nodes.size()-1].coord;
  3256. }
  3257. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  3258. {
  3259. if (mode==0)
  3260. {
  3261. for (unsigned int i=0;i<nodes.size();i++)
  3262. {
  3263. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3264. }
  3265. }
  3266. }
  3267. int3 CPath::endPos() const
  3268. {
  3269. return nodes[0].coord;
  3270. }
  3271. CGPathNode::CGPathNode()
  3272. :coord(-1,-1,-1)
  3273. {
  3274. accessible = 0;
  3275. land = 0;
  3276. moveRemains = 0;
  3277. turns = 255;
  3278. theNodeBefore = NULL;
  3279. }
  3280. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  3281. {
  3282. out.nodes.clear();
  3283. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  3284. if(!curnode->theNodeBefore)
  3285. return false;
  3286. while(curnode)
  3287. {
  3288. out.nodes.push_back(*curnode);
  3289. curnode = curnode->theNodeBefore;
  3290. }
  3291. return true;
  3292. }
  3293. CPathsInfo::CPathsInfo( const int3 &Sizes )
  3294. :sizes(Sizes)
  3295. {
  3296. hero = NULL;
  3297. nodes = new CGPathNode**[sizes.x];
  3298. for(int i = 0; i < sizes.x; i++)
  3299. {
  3300. nodes[i] = new CGPathNode*[sizes.y];
  3301. for (int j = 0; j < sizes.y; j++)
  3302. {
  3303. nodes[i][j] = new CGPathNode[sizes.z];
  3304. }
  3305. }
  3306. }
  3307. CPathsInfo::~CPathsInfo()
  3308. {
  3309. for(int i = 0; i < sizes.x; i++)
  3310. {
  3311. for (int j = 0; j < sizes.y; j++)
  3312. {
  3313. delete [] nodes[i][j];
  3314. }
  3315. delete [] nodes[i];
  3316. }
  3317. delete [] nodes;
  3318. }
  3319. int3 CGPath::startPos() const
  3320. {
  3321. return nodes[nodes.size()-1].coord;
  3322. }
  3323. int3 CGPath::endPos() const
  3324. {
  3325. return nodes[0].coord;
  3326. }
  3327. void CGPath::convert( ui8 mode )
  3328. {
  3329. if(mode==0)
  3330. {
  3331. for(unsigned int i=0;i<nodes.size();i++)
  3332. {
  3333. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3334. }
  3335. }
  3336. }
  3337. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  3338. {
  3339. switch(phase)
  3340. {
  3341. case 0: //catapult moves after turrets
  3342. return a->type->idNumber < b->type->idNumber; //catapult is 145 and turrets are 149
  3343. //TODO? turrets order
  3344. case 1: //fastest first, upper slot first
  3345. {
  3346. int as = a->Speed(turn), bs = b->Speed(turn);
  3347. if(as != bs)
  3348. return as > bs;
  3349. else
  3350. return a->slot < b->slot;
  3351. }
  3352. case 2: //fastest last, upper slot first
  3353. //TODO: should be replaced with order of receiving morale!
  3354. case 3: //fastest last, upper slot first
  3355. {
  3356. int as = a->Speed(turn), bs = b->Speed(turn);
  3357. if(as != bs)
  3358. return as < bs;
  3359. else
  3360. return a->slot < b->slot;
  3361. }
  3362. default:
  3363. assert(0);
  3364. return false;
  3365. }
  3366. }
  3367. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  3368. {
  3369. phase = Phase;
  3370. turn = Turn;
  3371. }
  3372. PlayerState::PlayerState()
  3373. : color(-1), currentSelection(0xffffffff), status(INGAME), daysWithoutCastle(0)
  3374. {
  3375. }
  3376. void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  3377. {
  3378. //TODO: global effects
  3379. }
  3380. InfoAboutHero::InfoAboutHero()
  3381. {
  3382. details = NULL;
  3383. hclass = NULL;
  3384. portrait = -1;
  3385. }
  3386. InfoAboutHero::InfoAboutHero( const InfoAboutHero & iah )
  3387. {
  3388. assign(iah);
  3389. }
  3390. InfoAboutHero::~InfoAboutHero()
  3391. {
  3392. delete details;
  3393. }
  3394. void InfoAboutHero::initFromHero( const CGHeroInstance *h, bool detailed )
  3395. {
  3396. if(!h) return;
  3397. owner = h->tempOwner;
  3398. hclass = h->type->heroClass;
  3399. name = h->name;
  3400. portrait = h->portrait;
  3401. army = h->getArmy();
  3402. if(detailed)
  3403. {
  3404. //include details about hero
  3405. details = new Details;
  3406. details->luck = h->LuckVal();
  3407. details->morale = h->MoraleVal();
  3408. details->mana = h->mana;
  3409. details->primskills.resize(PRIMARY_SKILLS);
  3410. for (int i = 0; i < PRIMARY_SKILLS ; i++)
  3411. {
  3412. details->primskills[i] = h->getPrimSkillLevel(i);
  3413. }
  3414. }
  3415. else
  3416. {
  3417. //hide info about hero stacks counts using descriptives names ids
  3418. for(TSlots::const_iterator i = army.Slots().begin(); i != army.Slots().end(); ++i)
  3419. {
  3420. army.setStackCount(i->first, i->second.getQuantityID());
  3421. }
  3422. }
  3423. }
  3424. void InfoAboutHero::assign( const InfoAboutHero & iah )
  3425. {
  3426. army = iah.army;
  3427. details = (iah.details ? new Details(*iah.details) : NULL);
  3428. hclass = iah.hclass;
  3429. name = iah.name;
  3430. owner = iah.owner;
  3431. portrait = iah.portrait;
  3432. }
  3433. InfoAboutHero & InfoAboutHero::operator=( const InfoAboutHero & iah )
  3434. {
  3435. assign(iah);
  3436. return *this;
  3437. }
  3438. void CCampaignState::initNewCampaign( const StartInfo &si )
  3439. {
  3440. assert(si.mode == 2);
  3441. campaignName = si.mapname;
  3442. currentMap = si.whichMapInCampaign;
  3443. camp = CCampaignHandler::getCampaign(campaignName, true); //TODO lod???
  3444. for (ui8 i = 0; i < camp->mapPieces.size(); i++)
  3445. mapsRemaining.push_back(i);
  3446. }