CGameState.cpp 118 KB

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