CGameState.cpp 130 KB

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