CGameState.cpp 108 KB

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