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