CGameState.cpp 129 KB

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