CGameState.cpp 131 KB

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