2
0

CGameState.cpp 129 KB

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