CGameState.cpp 119 KB

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