CGameState.cpp 129 KB

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