CGameState.cpp 129 KB

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