CGameState.cpp 122 KB

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