CGameState.cpp 110 KB

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