CGameHandler.cpp 142 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898
  1. #include "../hch/CCampaignHandler.h"
  2. #include "../StartInfo.h"
  3. #include "../hch/CArtHandler.h"
  4. #include "../hch/CBuildingHandler.h"
  5. #include "../hch/CDefObjInfoHandler.h"
  6. #include "../hch/CHeroHandler.h"
  7. #include "../hch/CObjectHandler.h"
  8. #include "../hch/CSpellHandler.h"
  9. #include "../hch/CGeneralTextHandler.h"
  10. #include "../hch/CTownHandler.h"
  11. #include "../hch/CCreatureHandler.h"
  12. #include "../lib/CGameState.h"
  13. #include "../lib/CondSh.h"
  14. #include "../lib/NetPacks.h"
  15. #include "../lib/VCMI_Lib.h"
  16. #include "../lib/map.h"
  17. #include "../lib/VCMIDirs.h"
  18. #include "CGameHandler.h"
  19. #include <boost/bind.hpp>
  20. #include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
  21. #include <boost/foreach.hpp>
  22. #include <boost/thread.hpp>
  23. #include <boost/thread/shared_mutex.hpp>
  24. #include <boost/assign/list_of.hpp>
  25. #include <fstream>
  26. #include <boost/system/system_error.hpp>
  27. /*
  28. * CGameHandler.cpp, part of VCMI engine
  29. *
  30. * Authors: listed in file AUTHORS in main folder
  31. *
  32. * License: GNU General Public License v2.0 or later
  33. * Full text of license available in license.txt file, in main folder
  34. *
  35. */
  36. #undef DLL_EXPORT
  37. #define DLL_EXPORT
  38. #include "../lib/RegisterTypes.cpp"
  39. #ifndef _MSC_VER
  40. #include <boost/thread/xtime.hpp>
  41. #endif
  42. extern bool end2;
  43. #ifdef min
  44. #undef min
  45. #endif
  46. #ifdef max
  47. #undef max
  48. #endif
  49. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  50. #define NEW_ROUND BattleNextRound bnr;\
  51. bnr.round = gs->curB->round + 1;\
  52. sendAndApply(&bnr);
  53. CondSh<bool> battleMadeAction;
  54. CondSh<BattleResult *> battleResult(NULL);
  55. class CBaseForGHApply
  56. {
  57. public:
  58. virtual bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const =0;
  59. };
  60. template <typename T> class CApplyOnGH : public CBaseForGHApply
  61. {
  62. public:
  63. bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const
  64. {
  65. T *ptr = static_cast<T*>(pack);
  66. ptr->c = c;
  67. return ptr->applyGh(gh);
  68. }
  69. };
  70. class CGHApplier
  71. {
  72. public:
  73. std::map<ui16,CBaseForGHApply*> apps;
  74. CGHApplier()
  75. {
  76. registerTypes3(*this);
  77. }
  78. template<typename T> void registerType(const T * t=NULL)
  79. {
  80. ui16 ID = typeList.registerType(t);
  81. apps[ID] = new CApplyOnGH<T>;
  82. }
  83. } *applier = NULL;
  84. CMP_stack cmpst ;
  85. static inline double distance(int3 a, int3 b)
  86. {
  87. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  88. }
  89. static void giveExp(BattleResult &r)
  90. {
  91. r.exp[0] = 0;
  92. r.exp[1] = 0;
  93. for(std::map<ui32,si32>::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  94. {
  95. r.exp[r.winner] += VLC->creh->creatures[i->first]->valOfBonuses(Bonus::STACK_HEALTH) * i->second;
  96. }
  97. }
  98. PlayerStatus PlayerStatuses::operator[](ui8 player)
  99. {
  100. boost::unique_lock<boost::mutex> l(mx);
  101. if(players.find(player) != players.end())
  102. {
  103. return players[player];
  104. }
  105. else
  106. {
  107. throw std::string("No such player!");
  108. }
  109. }
  110. void PlayerStatuses::addPlayer(ui8 player)
  111. {
  112. boost::unique_lock<boost::mutex> l(mx);
  113. players[player];
  114. }
  115. bool PlayerStatuses::hasQueries(ui8 player)
  116. {
  117. boost::unique_lock<boost::mutex> l(mx);
  118. if(players.find(player) != players.end())
  119. {
  120. return players[player].queries.size();
  121. }
  122. else
  123. {
  124. throw std::string("No such player!");
  125. }
  126. }
  127. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  128. {
  129. boost::unique_lock<boost::mutex> l(mx);
  130. if(players.find(player) != players.end())
  131. {
  132. return players[player].*flag;
  133. }
  134. else
  135. {
  136. throw std::string("No such player!");
  137. }
  138. }
  139. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  140. {
  141. boost::unique_lock<boost::mutex> l(mx);
  142. if(players.find(player) != players.end())
  143. {
  144. players[player].*flag = val;
  145. }
  146. else
  147. {
  148. throw std::string("No such player!");
  149. }
  150. cv.notify_all();
  151. }
  152. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  153. {
  154. boost::unique_lock<boost::mutex> l(mx);
  155. if(players.find(player) != players.end())
  156. {
  157. players[player].queries.insert(id);
  158. }
  159. else
  160. {
  161. throw std::string("No such player!");
  162. }
  163. cv.notify_all();
  164. }
  165. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  166. {
  167. boost::unique_lock<boost::mutex> l(mx);
  168. if(players.find(player) != players.end())
  169. {
  170. players[player].queries.erase(id);
  171. }
  172. else
  173. {
  174. throw std::string("No such player!");
  175. }
  176. cv.notify_all();
  177. }
  178. template <typename T>
  179. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  180. {
  181. fun(args[which]);
  182. }
  183. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  184. {
  185. SetSecSkill sss;
  186. sss.id = ID;
  187. sss.which = which;
  188. sss.val = val;
  189. sss.abs = abs;
  190. sendAndApply(&sss);
  191. if(which == 7) //Wisdom
  192. {
  193. const CGHeroInstance *h = getHero(ID);
  194. if(h && h->visitedTown)
  195. giveSpells(h->visitedTown, h);
  196. }
  197. }
  198. void CGameHandler::changePrimSkill(int ID, int which, si64 val, bool abs)
  199. {
  200. SetPrimSkill sps;
  201. sps.id = ID;
  202. sps.which = which;
  203. sps.abs = abs;
  204. sps.val = val;
  205. sendAndApply(&sps);
  206. if(which==4) //only for exp - hero may level up
  207. {
  208. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  209. while (hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  210. {
  211. //give prim skill
  212. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  213. int r = rand()%100, pom=0, x=0;
  214. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  215. for(;x<PRIMARY_SKILLS;x++)
  216. {
  217. pom += hero->type->heroClass->primChance[x].*g;
  218. if(r<pom)
  219. break;
  220. }
  221. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  222. SetPrimSkill sps;
  223. sps.id = ID;
  224. sps.which = x;
  225. sps.abs = false;
  226. sps.val = 1;
  227. sendAndApply(&sps);
  228. HeroLevelUp hlu;
  229. hlu.heroid = ID;
  230. hlu.primskill = x;
  231. hlu.level = hero->level+1;
  232. //picking sec. skills for choice
  233. std::set<int> basicAndAdv, expert, none;
  234. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  235. for(unsigned i=0;i<hero->secSkills.size();i++)
  236. {
  237. if(hero->secSkills[i].second < 3)
  238. basicAndAdv.insert(hero->secSkills[i].first);
  239. else
  240. expert.insert(hero->secSkills[i].first);
  241. none.erase(hero->secSkills[i].first);
  242. }
  243. //first offered skill
  244. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  245. {
  246. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  247. none.erase(hlu.skills.back());
  248. }
  249. else if(basicAndAdv.size())
  250. {
  251. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  252. hlu.skills.push_back(s);
  253. basicAndAdv.erase(s);
  254. }
  255. //second offered skill
  256. if(basicAndAdv.size())
  257. {
  258. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  259. }
  260. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  261. {
  262. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  263. }
  264. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  265. {
  266. boost::function<void(ui32)> callback = boost::function<void(ui32)>(boost::bind(callWith<ui16>,hlu.skills,boost::function<void(ui16)>(boost::bind(&CGameHandler::changeSecSkill,this,ID,_1,1,0)),_1));
  267. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  268. }
  269. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  270. {
  271. sendAndApply(&hlu);
  272. changeSecSkill(ID,hlu.skills.back(),1,false);
  273. }
  274. else //apply and send info
  275. {
  276. sendAndApply(&hlu);
  277. }
  278. }
  279. }
  280. }
  281. static CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  282. {
  283. if(color == 254)
  284. color = 255;
  285. CCreatureSet ret(set);
  286. for(int i=0; i<bat->stacks.size();i++)
  287. {
  288. CStack *st = bat->stacks[i];
  289. if(vstd::contains(st->state, SUMMONED)) //don't take into account sumoned stacks
  290. continue;
  291. if(st->owner==color && !set.slotEmpty(st->slot) && st->count < set.getAmount(st->slot))
  292. {
  293. if(st->alive())
  294. ret.setStackCount(st->slot, st->count);
  295. else
  296. ret.eraseStack(st->slot);
  297. }
  298. }
  299. return ret;
  300. }
  301. void CGameHandler::startBattle(const CArmedInstance *army1, const CArmedInstance * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town)
  302. {
  303. battleEndCallback = new boost::function<void(BattleResult*)>(cb);
  304. bEndArmy1 = army1;
  305. bEndArmy2 = army2;
  306. {
  307. BattleInfo *curB = new BattleInfo;
  308. curB->side1 = army1->tempOwner;
  309. curB->side2 = army2->tempOwner;
  310. if(curB->side2 == 254)
  311. curB->side2 = 255;
  312. setupBattle(curB, tile, army1, army2, hero1, hero2, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  313. }
  314. NEW_ROUND;
  315. //TODO: pre-tactic stuff, call scripts etc.
  316. //tactic round
  317. {
  318. NEW_ROUND;
  319. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  320. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  321. {
  322. //TODO: tactic round (round -1)
  323. }
  324. }
  325. //spells opening battle
  326. if (hero1 && hero1->hasBonusOfType(Bonus::OPENING_BATTLE_SPELL))
  327. {
  328. BonusList bl;
  329. hero1->getBonuses(bl, Selector::type(Bonus::OPENING_BATTLE_SPELL));
  330. BOOST_FOREACH (Bonus b, bl)
  331. {
  332. handleSpellCasting(b.subtype, 3, -1, 0, hero1->tempOwner, NULL, hero2, b.val);
  333. }
  334. }
  335. if (hero2 && hero2->hasBonusOfType(Bonus::OPENING_BATTLE_SPELL))
  336. {
  337. BonusList bl;
  338. hero2->getBonuses(bl, Selector::type(Bonus::OPENING_BATTLE_SPELL));
  339. BOOST_FOREACH (Bonus b, bl)
  340. {
  341. handleSpellCasting(b.subtype, 3, -1, 1, hero2->tempOwner, NULL, hero1, b.val);
  342. }
  343. }
  344. //main loop
  345. while(!battleResult.get()) //till the end of the battle ;]
  346. {
  347. NEW_ROUND;
  348. std::vector<CStack*> & stacks = (gs->curB->stacks);
  349. const BattleInfo & curB = *gs->curB;
  350. //stack loop
  351. const CStack *next;
  352. while(!battleResult.get() && (next = curB.getNextStack()) && next->willMove())
  353. {
  354. //check for bad morale => freeze
  355. int nextStackMorale = next->MoraleVal();
  356. if( nextStackMorale < 0 &&
  357. !(NBonus::hasOfType(hero1, Bonus::BLOCK_MORALE) || NBonus::hasOfType(hero2, Bonus::BLOCK_MORALE)) //checking if heroes have (or don't have) morale blocking bonuses)
  358. )
  359. {
  360. if( rand()%24 < -2 * nextStackMorale)
  361. {
  362. //unit loses its turn - empty freeze action
  363. BattleAction ba;
  364. ba.actionType = 11;
  365. ba.additionalInfo = 1;
  366. ba.side = !next->attackerOwned;
  367. ba.stackNumber = next->ID;
  368. sendAndApply(&StartAction(ba));
  369. sendAndApply(&EndAction());
  370. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  371. continue;
  372. }
  373. }
  374. if(next->hasBonusOfType(Bonus::ATTACKS_NEAREST_CREATURE)) //while in berserk
  375. {
  376. std::pair<const CStack *, int> attackInfo = curB.getNearestStack(next, boost::logic::indeterminate);
  377. if(attackInfo.first != NULL)
  378. {
  379. BattleAction attack;
  380. attack.actionType = 6;
  381. attack.side = !next->attackerOwned;
  382. attack.stackNumber = next->ID;
  383. attack.additionalInfo = attackInfo.first->position;
  384. attack.destinationTile = attackInfo.second;
  385. makeBattleAction(attack);
  386. checkForBattleEnd(stacks);
  387. }
  388. continue;
  389. }
  390. const CGHeroInstance * curOwner = gs->battleGetOwner(next->ID);
  391. if( (next->position < 0 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //arrow turret, hero has no ballistics
  392. || (next->type->idNumber == 146 && (!curOwner || curOwner->getSecSkillLevel(20) == 0))) //ballista, hero has no artillery
  393. {
  394. BattleAction attack;
  395. attack.actionType = 7;
  396. attack.side = !next->attackerOwned;
  397. attack.stackNumber = next->ID;
  398. for(int g=0; g<gs->curB->stacks.size(); ++g)
  399. {
  400. if(gs->curB->stacks[g]->owner != next->owner && gs->curB->stacks[g]->alive())
  401. {
  402. attack.destinationTile = gs->curB->stacks[g]->position;
  403. break;
  404. }
  405. }
  406. makeBattleAction(attack);
  407. checkForBattleEnd(stacks);
  408. continue;
  409. }
  410. if(next->type->idNumber == 145 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //catapult, hero has no ballistics
  411. {
  412. BattleAction attack;
  413. static const int wallHexes[] = {50, 183, 182, 130, 62, 29, 12, 95};
  414. attack.destinationTile = wallHexes[ rand()%ARRAY_COUNT(wallHexes) ];
  415. attack.actionType = 9;
  416. attack.additionalInfo = 0;
  417. attack.side = !next->attackerOwned;
  418. attack.stackNumber = next->ID;
  419. makeBattleAction(attack);
  420. continue;
  421. }
  422. if(next->type->idNumber == 147 && (!curOwner || curOwner->getSecSkillLevel(27) == 0)) //first aid tent, hero has no first aid
  423. {
  424. BattleAction heal;
  425. std::vector< const CStack * > possibleStacks;
  426. for (int v=0; v<gs->curB->stacks.size(); ++v)
  427. {
  428. const CStack * cstack = gs->curB->stacks[v];
  429. if (cstack->owner == next->owner && cstack->firstHPleft < cstack->MaxHealth() && cstack->alive()) //it's friendly and not fully healthy
  430. {
  431. possibleStacks.push_back(cstack);
  432. }
  433. }
  434. if(possibleStacks.size() == 0)
  435. {
  436. //nothing to heal
  437. BattleAction doNothing;
  438. doNothing.actionType = 0;
  439. doNothing.additionalInfo = 0;
  440. doNothing.destinationTile = -1;
  441. doNothing.side = !next->attackerOwned;
  442. doNothing.stackNumber = next->ID;
  443. sendAndApply(&StartAction(doNothing));
  444. sendAndApply(&EndAction());
  445. continue;
  446. }
  447. else
  448. {
  449. //heal random creature
  450. const CStack * toBeHealed = possibleStacks[ rand()%possibleStacks.size() ];
  451. heal.actionType = 12;
  452. heal.additionalInfo = 0;
  453. heal.destinationTile = toBeHealed->position;
  454. heal.side = !next->attackerOwned;
  455. heal.stackNumber = next->ID;
  456. makeBattleAction(heal);
  457. }
  458. continue;
  459. }
  460. askInterfaceForMove:
  461. //ask interface and wait for answer
  462. if(!battleResult.get())
  463. {
  464. BattleSetActiveStack sas;
  465. sas.stack = next->ID;
  466. sendAndApply(&sas);
  467. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  468. while(next->alive() && (!battleMadeAction.data && !battleResult.get())) //active stack hasn't made its action and battle is still going
  469. battleMadeAction.cond.wait(lock);
  470. battleMadeAction.data = false;
  471. }
  472. else
  473. {
  474. break;
  475. }
  476. //we're after action, all results applied
  477. checkForBattleEnd(stacks); //check if this action ended the battle
  478. //check for good morale
  479. nextStackMorale = next->MoraleVal();
  480. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  481. && !vstd::contains(next->state,DEFENDING)
  482. && !vstd::contains(next->state,WAITING)
  483. && next->alive()
  484. && nextStackMorale > 0
  485. && !(NBonus::hasOfType(hero1, Bonus::BLOCK_MORALE) || NBonus::hasOfType(hero2, Bonus::BLOCK_MORALE)) //checking if heroes have (or don't have) morale blocking bonuses
  486. )
  487. if(rand()%24 < nextStackMorale) //this stack hasn't got morale this turn
  488. goto askInterfaceForMove; //move this stack once more
  489. }
  490. }
  491. endBattle(tile, hero1, hero2);
  492. }
  493. void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  494. {
  495. BattleResultsApplied resultsApplied;
  496. resultsApplied.player1 = bEndArmy1->tempOwner;
  497. resultsApplied.player2 = bEndArmy2->tempOwner;
  498. //unblock engaged players
  499. if(bEndArmy1->tempOwner<PLAYER_LIMIT)
  500. states.setFlag(bEndArmy1->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  501. if(bEndArmy2 && bEndArmy2->tempOwner<PLAYER_LIMIT)
  502. states.setFlag(bEndArmy2->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  503. //casualties among heroes armies
  504. SetGarrisons sg;
  505. sg.garrs[bEndArmy1->id] = takeCasualties(bEndArmy1->tempOwner, *bEndArmy1, gs->curB);
  506. sg.garrs[bEndArmy2->id] = takeCasualties(bEndArmy2->tempOwner, *bEndArmy2, gs->curB);
  507. sendAndApply(&sg);
  508. ui8 sides[2];
  509. sides[0] = gs->curB->side1;
  510. sides[1] = gs->curB->side2;
  511. ui8 loser = sides[!battleResult.data->winner];
  512. //end battle, remove all info, free memory
  513. giveExp(*battleResult.data);
  514. sendAndApply(battleResult.data);
  515. //if one hero has lost we will erase him
  516. if(battleResult.data->winner!=0 && hero1)
  517. {
  518. RemoveObject ro(hero1->id);
  519. sendAndApply(&ro);
  520. }
  521. if(battleResult.data->winner!=1 && hero2)
  522. {
  523. RemoveObject ro(hero2->id);
  524. sendAndApply(&ro);
  525. }
  526. //give exp
  527. if(battleResult.data->exp[0] && hero1)
  528. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  529. if(battleResult.data->exp[1] && hero2)
  530. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  531. if(battleEndCallback && *battleEndCallback)
  532. {
  533. (*battleEndCallback)(battleResult.data);
  534. delete battleEndCallback;
  535. battleEndCallback = 0;
  536. }
  537. sendAndApply(&resultsApplied);
  538. // Necromancy if applicable.
  539. const CGHeroInstance *winnerHero = battleResult.data->winner != 0 ? hero2 : hero1;
  540. const CGHeroInstance *loserHero = battleResult.data->winner != 0 ? hero1 : hero2;
  541. if (winnerHero)
  542. {
  543. CStackInstance raisedStack = winnerHero->calculateNecromancy(*battleResult.data);
  544. // Give raised units to winner and show dialog, if any were raised.
  545. if (raisedStack.type)
  546. {
  547. int slot = winnerHero->getSlotFor(raisedStack.type->idNumber);
  548. if (slot != -1)
  549. {
  550. SetGarrisons sg;
  551. sg.garrs[winnerHero->id] = winnerHero->getArmy();
  552. sg.garrs[winnerHero->id].addToSlot(slot, raisedStack);
  553. // if (vstd::contains(winnerHero->slots, slot)) // Add to existing stack.
  554. // sg.garrs[winnerHero->id].slots[slot].count += raisedStack.count;
  555. // else // Create a new stack.
  556. // sg.garrs[winnerHero->id].slots[slot] = raisedStack;
  557. winnerHero->showNecromancyDialog(raisedStack);
  558. sendAndApply(&sg);
  559. }
  560. }
  561. }
  562. if(visitObjectAfterVictory && winnerHero == hero1)
  563. {
  564. visitObjectOnTile(*getTile(winnerHero->getPosition()), winnerHero);
  565. }
  566. visitObjectAfterVictory = false;
  567. winLoseHandle(1<<sides[0] | 1<<sides[1]); //handle victory/loss of engaged players
  568. int result = battleResult.get()->result;
  569. if(result == 1 || result == 2) //loser has escaped or surrendered
  570. {
  571. SetAvailableHeroes sah;
  572. sah.player = loser;
  573. sah.hid[0] = loserHero->subID;
  574. if(result == 1) //retreat
  575. {
  576. sah.army[0] = new CCreatureSet();
  577. sah.army[0]->addToSlot(0, VLC->creh->nameToID[loserHero->type->refTypeStack[0]],1);
  578. }
  579. if(const CGHeroInstance *another = getPlayerState(loser)->availableHeroes[1])
  580. sah.hid[1] = another->subID;
  581. else
  582. sah.hid[1] = -1;
  583. sendAndApply(&sah);
  584. }
  585. delete battleResult.data;
  586. }
  587. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, const CStack *def)
  588. {
  589. bsa.killedAmount = bsa.damageAmount / def->MaxHealth();
  590. unsigned damageFirst = bsa.damageAmount % def->MaxHealth();
  591. if( def->firstHPleft <= damageFirst )
  592. {
  593. bsa.killedAmount++;
  594. bsa.newHP = def->firstHPleft + def->MaxHealth() - damageFirst;
  595. }
  596. else
  597. {
  598. bsa.newHP = def->firstHPleft - damageFirst;
  599. }
  600. if(def->count <= bsa.killedAmount) //stack killed
  601. {
  602. bsa.newAmount = 0;
  603. bsa.flags |= 1;
  604. bsa.killedAmount = def->count; //we cannot kill more creatures than we have
  605. }
  606. else
  607. {
  608. bsa.newAmount = def->count - bsa.killedAmount;
  609. }
  610. }
  611. void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance)
  612. {
  613. bat.bsa.clear();
  614. bat.stackAttacking = att->ID;
  615. bat.bsa.push_back(BattleStackAttacked());
  616. BattleStackAttacked *bsa = &bat.bsa.back();
  617. bsa->stackAttacked = def->ID;
  618. bsa->attackerID = att->ID;
  619. int attackerLuck = att->LuckVal();
  620. const CGHeroInstance * h0 = gs->curB->heroes[0],
  621. * h1 = gs->curB->heroes[1];
  622. bool noLuck = false;
  623. if(h0 && NBonus::hasOfType(h0, Bonus::BLOCK_LUCK) ||
  624. h1 && NBonus::hasOfType(h1, Bonus::BLOCK_LUCK))
  625. {
  626. noLuck = true;
  627. }
  628. if(!noLuck && attackerLuck > 0 && rand()%24 < attackerLuck) //TODO?: negative luck option?
  629. {
  630. bsa->damageAmount *= 2;
  631. bat.flags |= 4;
  632. }
  633. bsa->damageAmount = gs->curB->calculateDmg(att, def, gs->battleGetOwner(att->ID), gs->battleGetOwner(def->ID), bat.shot(), distance, bat.lucky());//counting dealt damage
  634. int dmg = bsa->damageAmount;
  635. prepareAttacked(*bsa, def);
  636. //life drain handling
  637. if (att->hasBonusOfType(Bonus::LIFE_DRAIN))
  638. {
  639. StacksHealedOrResurrected shi;
  640. shi.lifeDrain = true;
  641. shi.drainedFrom = def->ID;
  642. StacksHealedOrResurrected::HealInfo hi;
  643. hi.stackID = att->ID;
  644. hi.healedHP = std::min<int>(dmg, att->MaxHealth() - att->firstHPleft + att->MaxHealth() * (att->baseAmount - att->count) );
  645. hi.lowLevelResurrection = false;
  646. shi.healedStacks.push_back(hi);
  647. if (hi.healedHP > 0)
  648. {
  649. bsa->healedStacks.push_back(shi);
  650. }
  651. }
  652. else
  653. {
  654. }
  655. //fire shield handling
  656. if ( !bat.shot() && def->hasBonusOfType(Bonus::FIRE_SHIELD) && !bsa->killed() )
  657. {
  658. bat.bsa.push_back(BattleStackAttacked());
  659. BattleStackAttacked *bsa = &bat.bsa.back();
  660. bsa->stackAttacked = att->ID;
  661. bsa->attackerID = def->ID;
  662. bsa->flags |= 2;
  663. bsa->effect = 11;
  664. bsa->damageAmount = (dmg * def->valOfBonuses(Bonus::FIRE_SHIELD)) / 100;
  665. prepareAttacked(*bsa, att);
  666. }
  667. }
  668. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  669. {
  670. srand(time(NULL));
  671. CPack *pack = NULL;
  672. try
  673. {
  674. while(1)//server should never shut connection first //was: while(!end2)
  675. {
  676. {
  677. boost::unique_lock<boost::mutex> lock(*c.rmx);
  678. c >> pack; //get the package
  679. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  680. }
  681. int packType = typeList.getTypeID(pack); //get the id of type
  682. CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
  683. if(apply)
  684. {
  685. bool result = apply->applyOnGH(this,&c,pack);
  686. tlog5 << "Message successfully applied (result=" << result << ")!\n";
  687. //send confirmation that we've applied the package
  688. if(pack->type != 6000) //WORKAROUND - not confirm query replies TODO: reconsider
  689. {
  690. PackageApplied applied;
  691. applied.result = result;
  692. applied.packType = packType;
  693. {
  694. boost::unique_lock<boost::mutex> lock(*c.wmx);
  695. c << &applied;
  696. }
  697. }
  698. }
  699. else
  700. {
  701. tlog1 << "Message cannot be applied, cannot find applier (unregistered type)!\n";
  702. }
  703. delete pack;
  704. pack = NULL;
  705. }
  706. }
  707. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  708. {
  709. assert(!c.connected); //make sure that connection has been marked as broken
  710. tlog1 << e.what() << std::endl;
  711. end2 = true;
  712. }
  713. HANDLE_EXCEPTION(end2 = true);
  714. tlog1 << "Ended handling connection\n";
  715. }
  716. int CGameHandler::moveStack(int stack, int dest)
  717. {
  718. int ret = 0;
  719. CStack *curStack = gs->curB->getStack(stack),
  720. *stackAtEnd = gs->curB->getStackT(dest);
  721. assert(curStack);
  722. assert(dest < BFIELD_SIZE);
  723. //initing necessary tables
  724. bool accessibility[BFIELD_SIZE];
  725. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  726. for(int b=0; b<BFIELD_SIZE; ++b)
  727. {
  728. accessibility[b] = false;
  729. }
  730. for(int g=0; g<accessible.size(); ++g)
  731. {
  732. accessibility[accessible[g]] = true;
  733. }
  734. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  735. if(!stackAtEnd && curStack->doubleWide() && !accessibility[dest])
  736. {
  737. if(curStack->attackerOwned)
  738. {
  739. if(accessibility[dest+1])
  740. dest+=1;
  741. }
  742. else
  743. {
  744. if(accessibility[dest-1])
  745. dest-=1;
  746. }
  747. }
  748. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  749. return 0;
  750. bool accessibilityWithOccupyable[BFIELD_SIZE];
  751. std::vector<int> accOc = gs->curB->getAccessibility(curStack->ID, true);
  752. for(int b=0; b<BFIELD_SIZE; ++b)
  753. {
  754. accessibilityWithOccupyable[b] = false;
  755. }
  756. for(int g=0; g<accOc.size(); ++g)
  757. {
  758. accessibilityWithOccupyable[accOc[g]] = true;
  759. }
  760. //if(dists[dest] > curStack->creature->speed && !(stackAtEnd && dists[dest] == curStack->creature->speed+1)) //we can attack a stack if we can go to adjacent hex
  761. // return false;
  762. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibilityWithOccupyable, curStack->hasBonusOfType(Bonus::FLYING), curStack->doubleWide(), curStack->attackerOwned);
  763. ret = path.second;
  764. if(curStack->hasBonusOfType(Bonus::FLYING))
  765. {
  766. if(path.second <= curStack->Speed() && path.first.size() > 0)
  767. {
  768. //inform clients about move
  769. BattleStackMoved sm;
  770. sm.stack = curStack->ID;
  771. sm.tile = path.first[0];
  772. sm.distance = path.second;
  773. sm.ending = true;
  774. sm.teleporting = false;
  775. sendAndApply(&sm);
  776. }
  777. }
  778. else //for non-flying creatures
  779. {
  780. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  781. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  782. {
  783. //inform clients about move
  784. BattleStackMoved sm;
  785. sm.stack = curStack->ID;
  786. sm.tile = path.first[v];
  787. sm.distance = path.second;
  788. sm.ending = v==tilesToMove;
  789. sm.teleporting = false;
  790. sendAndApply(&sm);
  791. }
  792. }
  793. return ret;
  794. }
  795. CGameHandler::CGameHandler(void)
  796. {
  797. QID = 1;
  798. gs = NULL;
  799. IObjectInterface::cb = this;
  800. applier = new CGHApplier;
  801. visitObjectAfterVictory = false;
  802. }
  803. CGameHandler::~CGameHandler(void)
  804. {
  805. delete applier;
  806. applier = NULL;
  807. delete gs;
  808. }
  809. void CGameHandler::init(StartInfo *si, int Seed)
  810. {
  811. gs = new CGameState();
  812. tlog0 << "Gamestate created!" << std::endl;
  813. gs->init(si, 0, Seed);
  814. tlog0 << "Gamestate initialized!" << std::endl;
  815. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  816. states.addPlayer(i->first);
  817. }
  818. static bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  819. {
  820. return *a < *b;
  821. }
  822. void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false)
  823. {// bool forced = true - if creature should be replaced, if false - only if no creature was set
  824. if (forced || town->creatures[CREATURES_PER_TOWN].second.empty())//we need to change creature
  825. {
  826. SetAvailableCreatures ssi;
  827. ssi.tid = town->id;
  828. ssi.creatures = town->creatures;
  829. ssi.creatures[CREATURES_PER_TOWN].second.clear();//remove old one
  830. const std::vector<CGDwelling *> &dwellings = gs->getPlayer(town->tempOwner)->dwellings;
  831. if (dwellings.empty())//no dwellings - just remove
  832. {
  833. sendAndApply(&ssi);
  834. return;
  835. }
  836. ui32 dwellpos = rand()%dwellings.size();//take random dwelling
  837. ui32 creapos = rand()%dwellings[dwellpos]->creatures.size();//for multi-creature dwellings like Golem Factory
  838. ui32 creature = dwellings[dwellpos]->creatures[creapos].second[0];
  839. ssi.creatures[CREATURES_PER_TOWN].first = VLC->creh->creatures[creature]->growth;
  840. ssi.creatures[CREATURES_PER_TOWN].second.push_back(creature);
  841. sendAndApply(&ssi);
  842. }
  843. }
  844. void CGameHandler::newTurn()
  845. {
  846. tlog5 << "Turn " << gs->day+1 << std::endl;
  847. NewTurn n;
  848. n.day = gs->day + 1;
  849. n.resetBuilded = true;
  850. std::map<ui8, si32> hadGold;//starting gold - for buildings like dwarven treasury
  851. srand(time(NULL));
  852. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  853. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  854. {
  855. if(i->first == 255)
  856. continue;
  857. else if(i->first >= PLAYER_LIMIT)
  858. assert(0); //illegal player number!
  859. std::pair<ui8,si32> playerGold(i->first,i->second.resources[6]);
  860. hadGold.insert(playerGold);
  861. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  862. {
  863. SetAvailableHeroes sah;
  864. sah.player = i->first;
  865. //pick heroes and their armies
  866. CHeroClass *banned = NULL;
  867. for (int j = 0; j < AVAILABLE_HEROES_PER_PLAYER; j++)
  868. {
  869. if(CGHeroInstance *h = gs->hpool.pickHeroFor(j == 0, i->first, getNativeTown(i->first), pool, banned)) //first hero - native if possible, second hero -> any other class
  870. {
  871. sah.hid[j] = h->subID;
  872. h->initArmy(sah.army[j] = new CCreatureSet());
  873. banned = h->type->heroClass;
  874. }
  875. else
  876. sah.hid[j] = -1;
  877. }
  878. sendAndApply(&sah);
  879. }
  880. n.res[i->first] = i->second.resources;
  881. // SetResources r;
  882. // r.player = i->first;
  883. // for(int j=0;j<RESOURCE_QUANTITY;j++)
  884. // r.res[j] = i->second.resources[j];
  885. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  886. {
  887. if(h->visitedTown)
  888. giveSpells(h->visitedTown, h);
  889. NewTurn::Hero hth;
  890. hth.id = h->id;
  891. hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).tertype != TerrainTile::water);
  892. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  893. hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana
  894. else
  895. hth.mana = std::max(si32(0), std::max(h->mana, std::min(h->mana + h->manaRegain(), h->manaLimit())) );
  896. n.heroes.insert(hth);
  897. if(gs->day) //not first day
  898. {
  899. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  900. {
  901. case 1: //basic
  902. n.res[i->first][6] += 125;
  903. break;
  904. case 2: //advanced
  905. n.res[i->first][6] += 250;
  906. break;
  907. case 3: //expert
  908. n.res[i->first][6] += 500;
  909. break;
  910. }
  911. for (int k = 0; k < RESOURCE_QUANTITY; k++)
  912. {
  913. n.res[i->first][k] += h->valOfBonuses(Bonus::GENERATE_RESOURCE, k);
  914. }
  915. //TODO player bonuses
  916. }
  917. }
  918. //n.res.push_back(r);
  919. }
  920. for(std::vector<CGTownInstance *>::iterator j = gs->map->towns.begin(); j!=gs->map->towns.end(); j++)//handle towns
  921. {
  922. ui8 player = (*j)->tempOwner;
  923. if(gs->getDate(1)==7) //first day of week
  924. {
  925. if ((*j)->subID == 5 && vstd::contains((*j)->builtBuildings, 22))
  926. setPortalDwelling(*j, true);//set creatures for Portal of Summoning
  927. if ((**j).subID == 1 && gs->getDate(0) && player < PLAYER_LIMIT && vstd::contains((**j).builtBuildings, 22))//dwarven treasury
  928. n.res[player][6] += hadGold[player]/10; //give 10% of starting gold
  929. SetAvailableCreatures sac;
  930. sac.tid = (**j).id;
  931. sac.creatures = (**j).creatures;
  932. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  933. {
  934. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  935. {
  936. sac.creatures[k].first += (**j).creatureGrowth(k);
  937. if(!gs->getDate(0)) //first day of game: use only basic growths
  938. amin(sac.creatures[k].first, VLC->creh->creatures[(*j)->town->basicCreatures[k]]->growth);
  939. }
  940. }
  941. n.cres.push_back(sac);
  942. }
  943. if(gs->day && player < PLAYER_LIMIT)//not the first day and town not neutral
  944. {
  945. ////SetResources r;
  946. //r.player = (**j).tempOwner;
  947. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  948. {
  949. if((**j).town->primaryRes == 127) //we'll give wood and ore
  950. {
  951. n.res[player][0] += 1;
  952. n.res[player][2] += 1;
  953. }
  954. else
  955. {
  956. n.res[player][(**j).town->primaryRes] += 1;
  957. }
  958. }
  959. n.res[player][6] += (**j).dailyIncome();
  960. }
  961. if ((**j).subID == 2 && vstd::contains((**j).builtBuildings, 26)) // Skyship, probably easier to handle same as Veil of darkness
  962. { //do it every new day after veils apply
  963. FoWChange fw;
  964. fw.mode = 1;
  965. fw.player = player;
  966. getAllTiles(fw.tiles, player, -1, 0);
  967. sendAndApply (&fw);
  968. }
  969. if ((**j).hasBonusOfType (Bonus::DARKNESS))
  970. {
  971. (**j).hideTiles((**j).getOwner(), (**j).getBonus(Selector::type(Bonus::DARKNESS))->val);
  972. }
  973. //unhiding what shouldn't be hidden? //that's handled in netpacks client
  974. }
  975. if(getDate(2) == 1)
  976. {
  977. SetAvailableArtifacts saa;
  978. saa.id = -1;
  979. pickAllowedArtsSet(saa.arts);
  980. sendAndApply(&saa);
  981. }
  982. sendAndApply(&n);
  983. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  984. handleTimeEvents();
  985. //call objects
  986. for(size_t i = 0; i<gs->map->objects.size(); i++)
  987. if(gs->map->objects[i])
  988. gs->map->objects[i]->newTurn();
  989. winLoseHandle(0xff);
  990. //warn players without town
  991. if(gs->day)
  992. {
  993. for (std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  994. {
  995. if(i->second.status || i->second.towns.size() || i->second.color >= PLAYER_LIMIT)
  996. continue;
  997. InfoWindow iw;
  998. iw.player = i->first;
  999. iw.components.push_back(Component(Component::FLAG,i->first,0,0));
  1000. if(!i->second.daysWithoutCastle)
  1001. {
  1002. iw.text.addTxt(MetaString::GENERAL_TXT,6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  1003. iw.text.addReplacement(MetaString::COLOR, i->first);
  1004. }
  1005. else if(i->second.daysWithoutCastle == 6)
  1006. {
  1007. iw.text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  1008. iw.text.addReplacement(MetaString::COLOR, i->first);
  1009. }
  1010. else
  1011. {
  1012. iw.text.addTxt(MetaString::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.
  1013. iw.text.addReplacement(MetaString::COLOR, i->first);
  1014. iw.text.addReplacement(7 - i->second.daysWithoutCastle);
  1015. }
  1016. sendAndApply(&iw);
  1017. }
  1018. }
  1019. }
  1020. void CGameHandler::run(bool resume, const StartInfo *si /*= NULL*/)
  1021. {
  1022. using namespace boost::posix_time;
  1023. BOOST_FOREACH(CConnection *cc, conns)
  1024. {//init conn.
  1025. ui8 quantity, pom;
  1026. //ui32 seed;
  1027. if(!resume)
  1028. (*cc) << si << gs->map->checksum << gs->seed; // gs->scenarioOps
  1029. (*cc) >> quantity; //how many players will be handled at that client
  1030. for(int i=0;i<quantity;i++)
  1031. {
  1032. (*cc) >> pom; //read player color
  1033. {
  1034. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1035. connections[pom] = cc;
  1036. }
  1037. }
  1038. }
  1039. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  1040. {
  1041. std::set<int> pom;
  1042. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  1043. if(j->second == *i)
  1044. pom.insert(j->first);
  1045. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  1046. }
  1047. while (!end2)
  1048. {
  1049. if(!resume)
  1050. newTurn();
  1051. std::map<ui8,PlayerState>::iterator i;
  1052. if(!resume)
  1053. i = gs->players.begin();
  1054. else
  1055. i = gs->players.find(gs->currentPlayer);
  1056. resume = false;
  1057. for(; i != gs->players.end(); i++)
  1058. {
  1059. if(i->second.towns.size()==0 && i->second.heroes.size()==0
  1060. || i->second.color<0
  1061. || i->first>=PLAYER_LIMIT
  1062. || i->second.status)
  1063. {
  1064. continue;
  1065. }
  1066. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1067. {
  1068. YourTurn yt;
  1069. yt.player = i->first;
  1070. sendAndApply(&yt);
  1071. }
  1072. //wait till turn is done
  1073. boost::unique_lock<boost::mutex> lock(states.mx);
  1074. while(states.players[i->first].makingTurn && !end2)
  1075. {
  1076. static time_duration p = milliseconds(200);
  1077. states.cv.timed_wait(lock,p);
  1078. }
  1079. }
  1080. }
  1081. while(conns.size() && (*conns.begin())->isOpen())
  1082. boost::this_thread::sleep(boost::posix_time::milliseconds(5)); //give time client to close socket
  1083. }
  1084. namespace CGH
  1085. {
  1086. using namespace std;
  1087. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  1088. {
  1089. for(int j=0; j<7; ++j)
  1090. {
  1091. std::vector<int> pom;
  1092. for(int g=0; g<j+1; ++g)
  1093. {
  1094. int hlp; input>>hlp;
  1095. pom.push_back(hlp);
  1096. }
  1097. dest.push_back(pom);
  1098. }
  1099. }
  1100. }
  1101. void CGameHandler::setupBattle(BattleInfo * curB, int3 tile, const CArmedInstance *army1, const CArmedInstance *army2, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool creatureBank, const CGTownInstance *town)
  1102. {
  1103. battleResult.set(NULL);
  1104. std::vector<CStack*> & stacks = (curB->stacks);
  1105. curB->tile = tile;
  1106. curB->belligerents[0] = const_cast<CArmedInstance*>(army1);
  1107. curB->belligerents[1] = const_cast<CArmedInstance*>(army2);
  1108. curB->heroes[0] = const_cast<CGHeroInstance*>(hero1);
  1109. curB->heroes[1] = const_cast<CGHeroInstance*>(hero2);
  1110. curB->round = -2;
  1111. curB->activeStack = -1;
  1112. if(town)
  1113. {
  1114. curB->tid = town->id;
  1115. curB->siege = town->fortLevel();
  1116. }
  1117. else
  1118. {
  1119. curB->tid = -1;
  1120. curB->siege = 0;
  1121. }
  1122. //reading battleStartpos
  1123. std::ifstream positions;
  1124. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1125. if(!positions.is_open())
  1126. {
  1127. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1128. }
  1129. std::string dump;
  1130. positions>>dump; positions>>dump;
  1131. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1132. CGH::readItTo(positions, attackerLoose);
  1133. positions>>dump;
  1134. CGH::readItTo(positions, defenderLoose);
  1135. positions>>dump;
  1136. positions>>dump;
  1137. CGH::readItTo(positions, attackerTight);
  1138. positions>>dump;
  1139. CGH::readItTo(positions, defenderTight);
  1140. positions>>dump;
  1141. positions>>dump;
  1142. CGH::readItTo(positions, attackerCreBank);
  1143. positions>>dump;
  1144. CGH::readItTo(positions, defenderCreBank);
  1145. positions.close();
  1146. //battleStartpos read
  1147. int k = 0; //stack serial
  1148. for(TSlots::const_iterator i = army1->Slots().begin(); i!=army1->Slots().end(); i++, k++)
  1149. {
  1150. int pos;
  1151. if(creatureBank)
  1152. pos = attackerCreBank[army1->stacksCount()-1][k];
  1153. else if(army1->formation)
  1154. pos = attackerTight[army1->stacksCount()-1][k];
  1155. else
  1156. pos = attackerLoose[army1->stacksCount()-1][k];
  1157. CStack * stack = curB->generateNewStack(i->second, stacks.size(), true, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  1158. stacks.push_back(stack);
  1159. }
  1160. k = 0;
  1161. for(TSlots::const_iterator i = army2->Slots().begin(); i!=army2->Slots().end(); i++, k++)
  1162. {
  1163. int pos;
  1164. if(creatureBank)
  1165. pos = defenderCreBank[army2->stacksCount()-1][k];
  1166. else if(army2->formation)
  1167. pos = defenderTight[army2->stacksCount()-1][k];
  1168. else
  1169. pos = defenderLoose[army2->stacksCount()-1][k];
  1170. CStack * stack = curB->generateNewStack(i->second, stacks.size(), false, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  1171. stacks.push_back(stack);
  1172. }
  1173. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1174. {
  1175. if((stacks[g]->position%17)==1 && stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1176. {
  1177. stacks[g]->position += 1;
  1178. }
  1179. else if((stacks[g]->position%17)==15 && stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1180. {
  1181. stacks[g]->position -= 1;
  1182. }
  1183. }
  1184. //adding war machines
  1185. if(hero1)
  1186. {
  1187. if(hero1->getArt(13)) //ballista
  1188. {
  1189. CStack * stack = curB->generateNewStack(CStackInstance(146, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 52);
  1190. stacks.push_back(stack);
  1191. }
  1192. if(hero1->getArt(14)) //ammo cart
  1193. {
  1194. CStack * stack = curB->generateNewStack(CStackInstance(148, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 18);
  1195. stacks.push_back(stack);
  1196. }
  1197. if(hero1->getArt(15)) //first aid tent
  1198. {
  1199. CStack * stack = curB->generateNewStack(CStackInstance(147, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 154);
  1200. stacks.push_back(stack);
  1201. }
  1202. }
  1203. if(hero2)
  1204. {
  1205. if(hero2->getArt(13)) //ballista
  1206. {
  1207. CStack * stack = curB->generateNewStack(CStackInstance(146, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 66);
  1208. stacks.push_back(stack);
  1209. }
  1210. if(hero2->getArt(14)) //ammo cart
  1211. {
  1212. CStack * stack = curB->generateNewStack(CStackInstance(148, 1, hero1), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 32);
  1213. stacks.push_back(stack);
  1214. }
  1215. if(hero2->getArt(15)) //first aid tent
  1216. {
  1217. CStack * stack = curB->generateNewStack(CStackInstance(147, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 168);
  1218. stacks.push_back(stack);
  1219. }
  1220. }
  1221. if(town && hero1 && town->hasFort()) //catapult
  1222. {
  1223. CStack * stack = curB->generateNewStack(CStackInstance(145, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 120);
  1224. stacks.push_back(stack);
  1225. }
  1226. //war machines added
  1227. switch(curB->siege) //adding towers
  1228. {
  1229. case 3: //castle
  1230. {//lower tower / upper tower
  1231. CStack * stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -4);
  1232. stacks.push_back(stack);
  1233. stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -3);
  1234. stacks.push_back(stack);
  1235. }
  1236. case 2: //citadel
  1237. {//main tower
  1238. CStack * stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -2);
  1239. stacks.push_back(stack);
  1240. }
  1241. }
  1242. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1243. //seting up siege
  1244. if(town && town->hasFort())
  1245. {
  1246. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1247. {
  1248. curB->si.wallState[b] = 1;
  1249. }
  1250. }
  1251. int terType = gs->battleGetBattlefieldType(tile);
  1252. //randomize obstacles
  1253. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1254. {
  1255. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1256. std::vector<int> possibleObstacles;
  1257. for(int i=0; i<BFIELD_SIZE; ++i)
  1258. {
  1259. if(i%17 < 4 || i%17 > 12)
  1260. {
  1261. obAv[i] = false;
  1262. }
  1263. else
  1264. {
  1265. obAv[i] = true;
  1266. }
  1267. }
  1268. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1269. {
  1270. if(g->second.allowedTerrains[terType-1] == '1') //we need to take terType with -1 because terrain ids start from 1 and allowedTerrains array is indexed from 0
  1271. {
  1272. possibleObstacles.push_back(g->first);
  1273. }
  1274. }
  1275. srand(time(NULL));
  1276. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1277. {
  1278. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1279. while(toBlock>0)
  1280. {
  1281. CObstacleInstance coi;
  1282. coi.uniqueID = curB->obstacles.size();
  1283. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1284. coi.pos = rand()%BFIELD_SIZE;
  1285. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1286. bool badObstacle = false;
  1287. for(int b=0; b<block.size(); ++b)
  1288. {
  1289. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1290. {
  1291. badObstacle = true;
  1292. break;
  1293. }
  1294. }
  1295. if(badObstacle) continue;
  1296. //obstacle can be placed
  1297. curB->obstacles.push_back(coi);
  1298. for(int b=0; b<block.size(); ++b)
  1299. {
  1300. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1301. obAv[block[b]] = false;
  1302. }
  1303. toBlock -= block.size();
  1304. }
  1305. }
  1306. }
  1307. //giving building bonuses, if siege and we have harrisoned hero
  1308. if (town)
  1309. {
  1310. if (hero2)
  1311. {
  1312. for (int i=0; i<4; i++)
  1313. {
  1314. int val = town->defenceBonus(i);
  1315. if (val)
  1316. {
  1317. GiveBonus gs;
  1318. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::OBJECT, val, -1, "", i);
  1319. gs.id = hero2->id;
  1320. sendAndApply(&gs);
  1321. }
  1322. }
  1323. }
  1324. else//if we don't have hero - apply separately, if hero present - will be taken from hero bonuses
  1325. {
  1326. if(town->subID == 0 && vstd::contains(town->builtBuildings,22)) //castle, brotherhood of sword built
  1327. for(int g=0; g<stacks.size(); ++g)
  1328. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1329. else if(vstd::contains(town->builtBuildings,5)) //tavern is built
  1330. for(int g=0; g<stacks.size(); ++g)
  1331. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TOWN_STRUCTURE));
  1332. if(town->subID == 1 && vstd::contains(town->builtBuildings,21)) //rampart, fountain of fortune is present
  1333. for(int g=0; g<stacks.size(); ++g)
  1334. stacks[g]->bonuses.push_back(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1335. }
  1336. }
  1337. //giving terrain premies for heroes & stacks
  1338. int bonusSubtype = -1;
  1339. switch(terType)
  1340. {
  1341. case 9: //magic plains
  1342. {
  1343. bonusSubtype = 0;
  1344. }
  1345. case 14: //fiery fields
  1346. {
  1347. if(bonusSubtype == -1) bonusSubtype = 1;
  1348. }
  1349. case 15: //rock lands
  1350. {
  1351. if(bonusSubtype == -1) bonusSubtype = 8;
  1352. }
  1353. case 16: //magic clouds
  1354. {
  1355. if(bonusSubtype == -1) bonusSubtype = 2;
  1356. }
  1357. case 17: //lucid pools
  1358. {
  1359. if(bonusSubtype == -1) bonusSubtype = 4;
  1360. }
  1361. { //common part for cases 9, 14, 15, 16, 17
  1362. const CGHeroInstance * cHero = NULL;
  1363. for(int i=0; i<2; ++i)
  1364. {
  1365. if(i == 0) cHero = hero1;
  1366. else cHero = hero2;
  1367. if(cHero == NULL) continue;
  1368. GiveBonus gs;
  1369. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::OBJECT, 3, -1, "", bonusSubtype);
  1370. gs.id = cHero->id;
  1371. sendAndApply(&gs);
  1372. }
  1373. break;
  1374. }
  1375. case 18: //holy ground
  1376. {
  1377. for(int g=0; g<stacks.size(); ++g) //+1 morale bonus for good creatures, -1 morale bonus for evil creatures
  1378. {
  1379. if (stacks[g]->type->isGood())
  1380. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1381. else if (stacks[g]->type->isEvil())
  1382. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY));
  1383. }
  1384. break;
  1385. }
  1386. case 19: //clover field
  1387. {
  1388. for(int g=0; g<stacks.size(); ++g)
  1389. {
  1390. if(stacks[g]->type->faction == -1) //+2 luck bonus for neutral creatures
  1391. {
  1392. stacks[g]->bonuses.push_back(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TERRAIN_OVERLAY));
  1393. }
  1394. }
  1395. break;
  1396. }
  1397. case 20: //evil fog
  1398. {
  1399. for(int g=0; g<stacks.size(); ++g) //-1 morale bonus for good creatures, +1 morale bonus for evil creatures
  1400. {
  1401. if (stacks[g]->type->isGood())
  1402. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY));
  1403. else if (stacks[g]->type->isEvil())
  1404. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1405. }
  1406. break;
  1407. }
  1408. case 22: //cursed ground
  1409. {
  1410. for(int g=0; g<stacks.size(); ++g) //no luck nor morale
  1411. {
  1412. stacks[g]->bonuses.push_back(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1413. stacks[g]->bonuses.push_back(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1414. }
  1415. const CGHeroInstance * cHero = NULL;
  1416. for(int i=0; i<2; ++i) //blocking spells above level 1
  1417. {
  1418. if(i == 0) cHero = hero1;
  1419. else cHero = hero2;
  1420. if(cHero == NULL) continue;
  1421. GiveBonus gs;
  1422. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::BLOCK_SPELLS_ABOVE_LEVEL, Bonus::OBJECT, 1, -1, "", bonusSubtype);
  1423. gs.id = cHero->id;
  1424. sendAndApply(&gs);
  1425. }
  1426. break;
  1427. }
  1428. }
  1429. //premies given
  1430. //send info about battles
  1431. BattleStart bs;
  1432. bs.info = curB;
  1433. sendAndApply(&bs);
  1434. }
  1435. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1436. {
  1437. //checking winning condition
  1438. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1439. hasStack[0] = hasStack[1] = false;
  1440. for(int b = 0; b<stacks.size(); ++b)
  1441. {
  1442. if(stacks[b]->alive() && !stacks[b]->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1443. {
  1444. hasStack[1-stacks[b]->attackerOwned] = true;
  1445. }
  1446. }
  1447. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1448. {
  1449. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1450. br->result = 0;
  1451. br->winner = hasStack[1]; //fleeing side loses
  1452. gs->curB->calculateCasualties(br->casualties);
  1453. battleResult.set(br);
  1454. }
  1455. }
  1456. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1457. {
  1458. if(!vstd::contains(h->artifWorn,17))
  1459. return; //hero hasn't spellbok
  1460. ChangeSpells cs;
  1461. cs.hid = h->id;
  1462. cs.learn = true;
  1463. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  1464. {
  1465. if (t->subID == 8 && vstd::contains(t->builtBuildings, 26)) //Aurora Borealis
  1466. {
  1467. std::vector<ui16> spells;
  1468. getAllowedSpells(spells, i);
  1469. for (int j = 0; j < spells.size(); ++j)
  1470. cs.spells.insert(spells[j]);
  1471. }
  1472. else
  1473. {
  1474. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1475. {
  1476. if(!vstd::contains(h->spells,t->spells[i][j]))
  1477. cs.spells.insert(t->spells[i][j]);
  1478. }
  1479. }
  1480. }
  1481. if(cs.spells.size())
  1482. sendAndApply(&cs);
  1483. }
  1484. void CGameHandler::setBlockVis(int objid, bool bv)
  1485. {
  1486. SetObjectProperty sop(objid,2,bv);
  1487. sendAndApply(&sop);
  1488. }
  1489. bool CGameHandler::removeObject( int objid )
  1490. {
  1491. if(!getObj(objid))
  1492. {
  1493. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1494. return false;
  1495. }
  1496. RemoveObject ro;
  1497. ro.id = objid;
  1498. sendAndApply(&ro);
  1499. winLoseHandle(255); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1500. return true;
  1501. }
  1502. void CGameHandler::setAmount(int objid, ui32 val)
  1503. {
  1504. SetObjectProperty sop(objid,3,val);
  1505. sendAndApply(&sop);
  1506. }
  1507. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1508. {
  1509. bool blockvis = false;
  1510. const CGHeroInstance *h = getHero(hid);
  1511. if(!h || asker != 255 && (instant || h->getOwner() != gs->currentPlayer) //not turn of that hero or player can't simply teleport hero (at least not with this function)
  1512. )
  1513. {
  1514. tlog1 << "Illegal call to move hero!\n";
  1515. return false;
  1516. }
  1517. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1518. int3 hmpos = dst + int3(-1,0,0);
  1519. if(!gs->map->isInTheMap(hmpos))
  1520. {
  1521. tlog1 << "Destination tile is outside the map!\n";
  1522. return false;
  1523. }
  1524. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1525. int cost = gs->getMovementCost(h, h->getPosition(false), CGHeroInstance::convertPosition(dst,false),h->movement);
  1526. int3 guardPos = gs->guardingCreaturePosition(hmpos);
  1527. //result structure for start - movement failed, no move points used
  1528. TryMoveHero tmh;
  1529. tmh.id = hid;
  1530. tmh.start = h->pos;
  1531. tmh.end = dst;
  1532. tmh.result = TryMoveHero::FAILED;
  1533. tmh.movePoints = h->movement;
  1534. //check if destination tile is available
  1535. //it's a rock or blocked and not visitable tile
  1536. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1537. if((t.tertype == TerrainTile::rock || (t.blocked && !t.visitable && !h->hasBonusOfType(Bonus::FLYING_MOVEMENT) ))
  1538. && complain("Cannot move hero, destination tile is blocked!")
  1539. || (!h->boat && !h->canWalkOnSea() && t.tertype == TerrainTile::water && (t.visitableObjects.size() != 1 || (t.visitableObjects.front()->ID != 8 && t.visitableObjects.front()->ID != HEROI_TYPE))) //hero is not on boat/water walking and dst water tile doesn't contain boat/hero (objs visitable from land)
  1540. && complain("Cannot move hero, destination tile is on water!")
  1541. || (h->boat && t.tertype != TerrainTile::water && t.blocked)
  1542. && complain("Cannot disembark hero, tile is blocked!")
  1543. || (h->movement < cost && dst != h->pos && !instant)
  1544. && complain("Hero doesn't have any movement points left!")
  1545. || states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1546. && complain("Cannot move hero during the battle"))
  1547. {
  1548. //send info about movement failure
  1549. sendAndApply(&tmh);
  1550. return false;
  1551. }
  1552. //hero enters the boat
  1553. if(!h->boat && t.visitableObjects.size() && t.visitableObjects.front()->ID == 8)
  1554. {
  1555. tmh.result = TryMoveHero::EMBARK;
  1556. tmh.movePoints = 0; //embarking takes all move points
  1557. //TODO: check for bonus that removes that penalty
  1558. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1559. sendAndApply(&tmh);
  1560. return true;
  1561. }
  1562. //hero leaves the boat
  1563. else if(h->boat && t.tertype != TerrainTile::water && !t.blocked)
  1564. {
  1565. tmh.result = TryMoveHero::DISEMBARK;
  1566. tmh.movePoints = 0; //disembarking takes all move points
  1567. //TODO: check for bonus that removes that penalty
  1568. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1569. sendAndApply(&tmh);
  1570. tryAttackingGuard(guardPos, h);
  1571. return true;
  1572. }
  1573. //checks for standard movement
  1574. if(!instant)
  1575. {
  1576. if( distance(h->pos,dst) >= 1.5 && complain("Tiles are not neighboring!")
  1577. || h->movement < cost && h->movement < 100 && complain("Not enough move points!"))
  1578. {
  1579. sendAndApply(&tmh);
  1580. return false;
  1581. }
  1582. //check if there is blocking visitable object
  1583. blockvis = false;
  1584. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1585. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1586. {
  1587. if(obj != h && obj->blockVisit && !(obj->getPassableness() & 1<<h->tempOwner))
  1588. {
  1589. blockvis = true;
  1590. break;
  1591. }
  1592. }
  1593. //we start moving
  1594. if(blockvis)//interaction with blocking object (like resources)
  1595. {
  1596. tmh.result = TryMoveHero::BLOCKING_VISIT;
  1597. sendAndApply(&tmh);
  1598. //failed to move to that tile but we visit object
  1599. if(t.visitableObjects.size())
  1600. objectVisited(t.visitableObjects.back(), h);
  1601. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1602. // {
  1603. // if (obj->blockVisit)
  1604. // {
  1605. // objectVisited(obj, h);
  1606. // }
  1607. // }
  1608. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1609. return true;
  1610. }
  1611. else //normal move
  1612. {
  1613. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1614. {
  1615. obj->onHeroLeave(h);
  1616. }
  1617. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1618. tmh.result = TryMoveHero::SUCCESS;
  1619. tmh.attackedFrom = guardPos;
  1620. sendAndApply(&tmh);
  1621. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1622. // If a creature guards the tile, block visit.
  1623. const bool fightingGuard = tryAttackingGuard(guardPos, h);
  1624. if(!fightingGuard && t.visitableObjects.size()) //call objects if they are visited
  1625. {
  1626. visitObjectOnTile(t, h);
  1627. }
  1628. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1629. // {
  1630. // objectVisited(obj, h);
  1631. // }
  1632. tlog5 << "Movement end!\n";
  1633. return true;
  1634. }
  1635. }
  1636. else //instant move - teleportation
  1637. {
  1638. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1639. {
  1640. if(obj->ID==HEROI_TYPE)
  1641. {
  1642. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1643. if(obj->tempOwner==h->tempOwner)
  1644. {
  1645. heroExchange(dh->id, h->id);
  1646. return true;
  1647. }
  1648. //TODO: check for ally
  1649. startBattleI(h, dh);
  1650. return true;
  1651. }
  1652. }
  1653. tmh.result = TryMoveHero::TELEPORTATION;
  1654. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1655. sendAndApply(&tmh);
  1656. return true;
  1657. }
  1658. }
  1659. bool CGameHandler::teleportHero(si32 hid, si32 dstid, ui8 source, ui8 asker/* = 255*/)
  1660. {
  1661. const CGHeroInstance *h = getHero(hid);
  1662. const CGTownInstance *t = getTown(dstid);
  1663. if ( !h || !t || h->getOwner() != gs->currentPlayer )
  1664. tlog1<<"Invalid call to teleportHero!";
  1665. const CGTownInstance *from = h->visitedTown;
  1666. if((h->getOwner() != t->getOwner())
  1667. && complain("Cannot teleport hero to another player")
  1668. || (!from || from->subID!=3 || !vstd::contains(from->builtBuildings, 22))
  1669. && complain("Hero must be in town with Castle gate for teleporting")
  1670. || (t->subID!=3 || !vstd::contains(t->builtBuildings, 22))
  1671. && complain("Cannot teleport hero to town without Castle gate in it"))
  1672. return false;
  1673. int3 pos = t->visitablePos();
  1674. pos += h->getVisitableOffset();
  1675. stopHeroVisitCastle(from->id, hid);
  1676. moveHero(hid,pos,1);
  1677. heroVisitCastle(dstid, hid);
  1678. return true;
  1679. }
  1680. void CGameHandler::setOwner(int objid, ui8 owner)
  1681. {
  1682. ui8 oldOwner = getOwner(objid);
  1683. SetObjectProperty sop(objid,1,owner);
  1684. sendAndApply(&sop);
  1685. winLoseHandle(1<<owner | 1<<oldOwner);
  1686. if(owner < PLAYER_LIMIT && getTown(objid)) //town captured
  1687. {
  1688. const CGTownInstance * town = getTown(objid);
  1689. if (town->subID == 5 && vstd::contains(town->builtBuildings, 22))
  1690. setPortalDwelling(town);
  1691. if (!gs->getPlayer(owner)->towns.size())//player lost last town
  1692. {
  1693. InfoWindow iw;
  1694. iw.player = oldOwner;
  1695. iw.text.addTxt(MetaString::GENERAL_TXT, 6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  1696. sendAndApply(&iw);
  1697. }
  1698. }
  1699. const CGObjectInstance * obj = getObj(objid);
  1700. if ((obj->ID == 17 || obj->ID == 20 ) && gs->getPlayer(owner)->dwellings.size()==1 )//first dwelling captured
  1701. BOOST_FOREACH(const CGTownInstance *t, gs->getPlayer(owner)->towns)
  1702. if (t->subID == 5 && vstd::contains(t->builtBuildings, 22))
  1703. setPortalDwelling(t);//set initial creatures for all portals of summoning
  1704. }
  1705. void CGameHandler::setHoverName(int objid, MetaString* name)
  1706. {
  1707. SetHoverName shn(objid, *name);
  1708. sendAndApply(&shn);
  1709. }
  1710. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1711. {
  1712. sendToAllClients(iw);
  1713. }
  1714. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1715. {
  1716. ask(iw,iw->player,callback);
  1717. }
  1718. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1719. {
  1720. //TODO
  1721. //gsm.lock();
  1722. //int query = QID++;
  1723. //states.addQuery(player,query);
  1724. //sendToAllClients(iw);
  1725. //gsm.unlock();
  1726. //ui32 ret = getQueryResult(iw->player, query);
  1727. //gsm.lock();
  1728. //states.removeQuery(player, query);
  1729. //gsm.unlock();
  1730. return 0;
  1731. }
  1732. int CGameHandler::getCurrentPlayer()
  1733. {
  1734. return gs->currentPlayer;
  1735. }
  1736. void CGameHandler::giveResource(int player, int which, int val)
  1737. {
  1738. if(!val) return; //don't waste time on empty call
  1739. SetResource sr;
  1740. sr.player = player;
  1741. sr.resid = which;
  1742. sr.val = gs->players.find(player)->second.resources[which]+val;
  1743. sendAndApply(&sr);
  1744. }
  1745. void CGameHandler::giveCreatures (int objid, const CGHeroInstance * h, CCreatureSet creatures)
  1746. {
  1747. if (creatures.stacksCount() <= 0)
  1748. return;
  1749. CCreatureSet heroArmy = h->getArmy();
  1750. while (creatures.stacksCount())
  1751. {
  1752. int slot = heroArmy.getSlotFor(creatures.Slots().begin()->second.type->idNumber);
  1753. if (slot < 0)
  1754. break;
  1755. heroArmy.addToSlot(slot, creatures.slots.begin()->second);
  1756. creatures.slots.erase (creatures.slots.begin());
  1757. }
  1758. if (creatures.stacksCount() == 0) //all creatures can be moved to hero army - do that
  1759. {
  1760. SetGarrisons sg;
  1761. sg.garrs[h->id] = heroArmy;
  1762. sendAndApply(&sg);
  1763. }
  1764. else //show garrison window and let player pick creatures
  1765. {
  1766. SetGarrisons sg;
  1767. sg.garrs[objid] = creatures;
  1768. sendAndApply (&sg);
  1769. showGarrisonDialog (objid, h->id, true, 0);
  1770. return;
  1771. }
  1772. }
  1773. void CGameHandler::takeCreatures (int objid, TSlots creatures) //probably we could use ArmedInstance as well
  1774. {
  1775. if (creatures.size() <= 0)
  1776. return;
  1777. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  1778. CCreatureSet newArmy = obj->getArmy();
  1779. while (creatures.size())
  1780. {
  1781. int slot = newArmy.getSlotFor(creatures.begin()->second.type->idNumber);
  1782. if (slot < 0)
  1783. break;
  1784. newArmy.slots[slot].count -= creatures.begin()->second.count;
  1785. if (newArmy.getStack(slot).count < 1)
  1786. newArmy.eraseStack(slot);
  1787. creatures.erase (creatures.begin());
  1788. }
  1789. SetGarrisons sg;
  1790. sg.garrs[objid] = newArmy;
  1791. sendAndApply(&sg);
  1792. }
  1793. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1794. {
  1795. sendToAllClients(comp);
  1796. }
  1797. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1798. {
  1799. HeroVisitCastle vc;
  1800. vc.hid = heroID;
  1801. vc.tid = obj;
  1802. vc.flags |= 1;
  1803. sendAndApply(&vc);
  1804. const CGHeroInstance *h = getHero(heroID);
  1805. vistiCastleObjects (getTown(obj), h);
  1806. giveSpells (getTown(obj), getHero(heroID));
  1807. if(gs->map->victoryCondition.condition == transportItem)
  1808. checkLossVictory(h->tempOwner); //transported artifact?
  1809. }
  1810. void CGameHandler::vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h)
  1811. {
  1812. std::vector<CGTownBuilding*>::const_iterator i;
  1813. for (i = t->bonusingBuildings.begin(); i != t->bonusingBuildings.end(); i++)
  1814. (*i)->onHeroVisit (h);
  1815. }
  1816. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1817. {
  1818. HeroVisitCastle vc;
  1819. vc.hid = heroID;
  1820. vc.tid = obj;
  1821. sendAndApply(&vc);
  1822. }
  1823. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1824. {
  1825. const CGHeroInstance* h = getHero(hid);
  1826. const CArtifact &art = *VLC->arth->artifacts[artid];
  1827. SetHeroArtifacts sha;
  1828. sha.hid = hid;
  1829. sha.artifacts = h->artifacts;
  1830. sha.artifWorn = h->artifWorn;
  1831. if(position<0)
  1832. {
  1833. if(position == -2)
  1834. {
  1835. int i;
  1836. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1837. {
  1838. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1839. {
  1840. //we've found a free suitable slot
  1841. VLC->arth->equipArtifact(sha.artifWorn, art.possibleSlots[i], artid);
  1842. break;
  1843. }
  1844. }
  1845. if(i == art.possibleSlots.size() && !art.isBig()) //if haven't find proper slot, use backpack or discard big artifact
  1846. sha.artifacts.push_back(artid);
  1847. }
  1848. else if (!art.isBig()) //should be -1 => put artifact into backpack
  1849. {
  1850. sha.artifacts.push_back(artid);
  1851. }
  1852. }
  1853. else
  1854. {
  1855. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1856. {
  1857. VLC->arth->equipArtifact(sha.artifWorn, position, artid);
  1858. }
  1859. else if (!art.isBig())
  1860. {
  1861. sha.artifacts.push_back(artid);
  1862. }
  1863. }
  1864. sendAndApply(&sha);
  1865. }
  1866. void CGameHandler::removeArtifact(int artid, int hid)
  1867. {
  1868. const CGHeroInstance* h = getHero(hid);
  1869. SetHeroArtifacts sha;
  1870. sha.hid = hid;
  1871. sha.artifacts = h->artifacts;
  1872. sha.artifWorn = h->artifWorn;
  1873. std::vector<ui32>::iterator it;
  1874. if ((it = std::find(sha.artifacts.begin(), sha.artifacts.end(), artid)) != sha.artifacts.end()) //it is in backpack
  1875. sha.artifacts.erase(it);
  1876. else //worn
  1877. {
  1878. for (std::map<ui16,ui32>::iterator itr = sha.artifWorn.begin(); itr != sha.artifWorn.end(); ++itr)
  1879. {
  1880. if (itr->second == artid)
  1881. {
  1882. VLC->arth->unequipArtifact(sha.artifWorn, itr->first);
  1883. break;
  1884. }
  1885. }
  1886. }
  1887. sendAndApply(&sha);
  1888. }
  1889. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town) //use hero=NULL for no hero
  1890. {
  1891. engageIntoBattle(army1->tempOwner);
  1892. engageIntoBattle(army2->tempOwner);
  1893. //block engaged players
  1894. if(army2->tempOwner < PLAYER_LIMIT)
  1895. states.setFlag(army2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1896. boost::thread(boost::bind(&CGameHandler::startBattle, this, army1, army2, tile, hero1, hero2, creatureBank, cb, town));
  1897. }
  1898. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb, bool creatureBank )
  1899. {
  1900. startBattleI(army1, army2, tile,
  1901. army1->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army1) : NULL,
  1902. army2->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army2) : NULL,
  1903. creatureBank, cb);
  1904. }
  1905. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb, bool creatureBank)
  1906. {
  1907. startBattleI(army1, army2, army2->visitablePos(), cb, creatureBank);
  1908. }
  1909. //void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1910. //{
  1911. // CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1912. // startBattleI(&h->army,&army,tile,h,NULL,cb);
  1913. // //battle(&h->army,army,tile,h,NULL);
  1914. //}
  1915. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1916. {
  1917. ChangeSpells cs;
  1918. cs.hid = hid;
  1919. cs.spells = spells;
  1920. cs.learn = give;
  1921. sendAndApply(&cs);
  1922. }
  1923. int CGameHandler::getSelectedHero()
  1924. {
  1925. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1926. }
  1927. void CGameHandler::setObjProperty( int objid, int prop, si64 val )
  1928. {
  1929. SetObjectProperty sob;
  1930. sob.id = objid;
  1931. sob.what = prop;
  1932. sob.val = val;
  1933. sendAndApply(&sob);
  1934. }
  1935. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1936. {
  1937. SystemMessage sm;
  1938. sm.text = message;
  1939. c << &sm;
  1940. }
  1941. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1942. {
  1943. sendAndApply(bonus);
  1944. }
  1945. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1946. {
  1947. sendAndApply(smp);
  1948. }
  1949. void CGameHandler::setManaPoints( int hid, int val )
  1950. {
  1951. SetMana sm;
  1952. sm.hid = hid;
  1953. sm.val = val;
  1954. sendAndApply(&sm);
  1955. }
  1956. void CGameHandler::giveHero( int id, int player )
  1957. {
  1958. GiveHero gh;
  1959. gh.id = id;
  1960. gh.player = player;
  1961. sendAndApply(&gh);
  1962. }
  1963. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1964. {
  1965. ChangeObjPos cop;
  1966. cop.objid = objid;
  1967. cop.nPos = newPos;
  1968. cop.flags = flags;
  1969. sendAndApply(&cop);
  1970. }
  1971. void CGameHandler::useScholarSkill(si32 fromHero, si32 toHero)
  1972. {
  1973. const CGHeroInstance * h1 = getHero(fromHero);
  1974. const CGHeroInstance * h2 = getHero(toHero);
  1975. if ( h1->getSecSkillLevel(18) < h2->getSecSkillLevel(18) )
  1976. {
  1977. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  1978. std::swap(fromHero, toHero);
  1979. }
  1980. int ScholarLevel = h1->getSecSkillLevel(18);//heroes can trade up to this level
  1981. if (!ScholarLevel || !vstd::contains(h1->artifWorn,17) || !vstd::contains(h2->artifWorn,17) )
  1982. return;//no scholar skill or no spellbook
  1983. int h1Lvl = std::min(ScholarLevel+1, h1->getSecSkillLevel(7)+2),
  1984. h2Lvl = std::min(ScholarLevel+1, h2->getSecSkillLevel(7)+2);//heroes can receive this levels
  1985. ChangeSpells cs1;
  1986. cs1.learn = true;
  1987. cs1.hid = toHero;//giving spells to first hero
  1988. for(std::set<ui32>::const_iterator it=h1->spells.begin(); it!=h1->spells.end();it++)
  1989. if ( h2Lvl >= VLC->spellh->spells[*it].level && !vstd::contains(h2->spells, *it))//hero can learn it and don't have it yet
  1990. cs1.spells.insert(*it);//spell to learn
  1991. ChangeSpells cs2;
  1992. cs2.learn = true;
  1993. cs2.hid = fromHero;
  1994. for(std::set<ui32>::const_iterator it=h2->spells.begin(); it!=h2->spells.end();it++)
  1995. if ( h1Lvl >= VLC->spellh->spells[*it].level && !vstd::contains(h1->spells, *it))
  1996. cs2.spells.insert(*it);
  1997. if (cs1.spells.size() || cs2.spells.size())//create a message
  1998. {
  1999. InfoWindow iw;
  2000. iw.player = h1->tempOwner;
  2001. iw.components.push_back(Component(Component::SEC_SKILL, 18, ScholarLevel, 0));
  2002. iw.text.addTxt(MetaString::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  2003. iw.text.addReplacement(h1->name);
  2004. if (cs2.spells.size())//if found new spell - apply
  2005. {
  2006. iw.text.addTxt(MetaString::GENERAL_TXT, 140);//learns
  2007. int size = cs2.spells.size();
  2008. for(std::set<ui32>::const_iterator it=cs2.spells.begin(); it!=cs2.spells.end();it++)
  2009. {
  2010. iw.components.push_back(Component(Component::SPELL, (*it), 1, 0));
  2011. iw.text.addTxt(MetaString::SPELL_NAME, (*it));
  2012. switch (size--)
  2013. {
  2014. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  2015. case 1: break;
  2016. default: iw.text << ", ";
  2017. }
  2018. }
  2019. iw.text.addTxt(MetaString::GENERAL_TXT, 142);//from %s
  2020. iw.text.addReplacement(h2->name);
  2021. sendAndApply(&cs2);
  2022. }
  2023. if (cs1.spells.size() && cs2.spells.size() )
  2024. {
  2025. iw.text.addTxt(MetaString::GENERAL_TXT, 141);//and
  2026. }
  2027. if (cs1.spells.size())
  2028. {
  2029. iw.text.addTxt(MetaString::GENERAL_TXT, 147);//teaches
  2030. int size = cs1.spells.size();
  2031. for(std::set<ui32>::const_iterator it=cs1.spells.begin(); it!=cs1.spells.end();it++)
  2032. {
  2033. iw.components.push_back(Component(Component::SPELL, (*it), 1, 0));
  2034. iw.text.addTxt(MetaString::SPELL_NAME, (*it));
  2035. switch (size--)
  2036. {
  2037. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  2038. case 1: break;
  2039. default: iw.text << ", ";
  2040. } }
  2041. iw.text.addTxt(MetaString::GENERAL_TXT, 148);//from %s
  2042. iw.text.addReplacement(h2->name);
  2043. sendAndApply(&cs1);
  2044. }
  2045. sendAndApply(&iw);
  2046. }
  2047. }
  2048. void CGameHandler::heroExchange(si32 hero1, si32 hero2)
  2049. {
  2050. ui8 player1 = getHero(hero1)->tempOwner;
  2051. ui8 player2 = getHero(hero2)->tempOwner;
  2052. if(player1 == player2)//TODO: allies
  2053. {
  2054. OpenWindow hex;
  2055. hex.window = OpenWindow::EXCHANGE_WINDOW;
  2056. hex.id1 = hero1;
  2057. hex.id2 = hero2;
  2058. sendAndApply(&hex);
  2059. useScholarSkill(hero1,hero2);
  2060. }
  2061. }
  2062. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  2063. {
  2064. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2065. sel->id = QID;
  2066. callbacks[QID] = callback;
  2067. states.addQuery(player,QID);
  2068. QID++;
  2069. sendAndApply(sel);
  2070. }
  2071. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  2072. {
  2073. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2074. sel->id = QID;
  2075. callbacks[QID] = callback;
  2076. states.addQuery(player,QID);
  2077. sendToAllClients(sel);
  2078. QID++;
  2079. }
  2080. void CGameHandler::sendToAllClients( CPackForClient * info )
  2081. {
  2082. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  2083. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  2084. {
  2085. (*i)->wmx->lock();
  2086. **i << info;
  2087. (*i)->wmx->unlock();
  2088. }
  2089. }
  2090. void CGameHandler::sendAndApply( CPackForClient * info )
  2091. {
  2092. gs->apply(info);
  2093. sendToAllClients(info);
  2094. }
  2095. void CGameHandler::sendAndApply( SetGarrisons * info )
  2096. {
  2097. sendAndApply((CPackForClient*)info);
  2098. if(gs->map->victoryCondition.condition == gatherTroop)
  2099. for(std::map<ui32,CCreatureSet>::const_iterator i = info->garrs.begin(); i != info->garrs.end(); i++)
  2100. checkLossVictory(getObj(i->first)->tempOwner);
  2101. }
  2102. void CGameHandler::sendAndApply( SetResource * info )
  2103. {
  2104. sendAndApply((CPackForClient*)info);
  2105. if(gs->map->victoryCondition.condition == gatherResource)
  2106. checkLossVictory(info->player);
  2107. }
  2108. void CGameHandler::sendAndApply( SetResources * info )
  2109. {
  2110. sendAndApply((CPackForClient*)info);
  2111. if(gs->map->victoryCondition.condition == gatherResource)
  2112. checkLossVictory(info->player);
  2113. }
  2114. void CGameHandler::sendAndApply( NewStructures * info )
  2115. {
  2116. sendAndApply((CPackForClient*)info);
  2117. if(gs->map->victoryCondition.condition == buildCity)
  2118. checkLossVictory(getTown(info->tid)->tempOwner);
  2119. }
  2120. void CGameHandler::save( const std::string &fname )
  2121. {
  2122. {
  2123. tlog0 << "Ordering clients to serialize...\n";
  2124. SaveGame sg(fname);
  2125. sendToAllClients(&sg);
  2126. }
  2127. {
  2128. tlog0 << "Serializing game info...\n";
  2129. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vlgm1");
  2130. char hlp[8] = "VCMISVG";
  2131. save << hlp << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps << *VLC << gs;
  2132. }
  2133. {
  2134. tlog0 << "Serializing server info...\n";
  2135. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vsgm1");
  2136. save << *this;
  2137. }
  2138. tlog0 << "Game has been successfully saved!\n";
  2139. }
  2140. void CGameHandler::close()
  2141. {
  2142. tlog0 << "We have been requested to close.\n";
  2143. //BOOST_FOREACH(CConnection *cc, conns)
  2144. // if(cc && cc->socket && cc->socket->is_open())
  2145. // cc->socket->close();
  2146. //exit(0);
  2147. }
  2148. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val )
  2149. {
  2150. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  2151. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  2152. CCreatureSet temp1 = s1->getArmy(), temp2 = s2->getArmy(),
  2153. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  2154. if(!isAllowedExchange(id1,id2))
  2155. {
  2156. complain("Cannot exchange stacks between these two objects!\n");
  2157. return false;
  2158. }
  2159. if(what==1) //swap
  2160. {
  2161. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  2162. //if one of them is empty, remove entry
  2163. if(!S1.slots[p1].count)
  2164. S1.slots.erase(p1);
  2165. if(!S2.slots[p2].count)
  2166. S2.slots.erase(p2);
  2167. }
  2168. else if(what==2)//merge
  2169. {
  2170. if(S1.slots[p1].type != S2.slots[p2].type) //not same creature
  2171. {
  2172. complain("Cannot merge different creatures stacks!");
  2173. return false;
  2174. }
  2175. S2.slots[p2].count += S1.slots[p1].count;
  2176. S1.slots.erase(p1);
  2177. }
  2178. else if(what==3) //split
  2179. {
  2180. //general conditions checking
  2181. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  2182. || (val<1 && complain("no creatures to split")) )
  2183. {
  2184. return false;
  2185. }
  2186. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  2187. {
  2188. int total = S1.slots[p1].count + S2.slots[p2].count;
  2189. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  2190. || (S2.slots[p2].type != S1.slots[p1].type && complain("Cannot rebalance different creatures stacks!"))
  2191. )
  2192. {
  2193. return false;
  2194. }
  2195. S2.slots[p2].count = val;
  2196. S1.slots[p1].count = total - val;
  2197. }
  2198. else //split one stack to the two
  2199. {
  2200. if(S1.slots[p1].count < val)//not enough creatures
  2201. {
  2202. complain("Cannot split that stack, not enough creatures!");
  2203. return false;
  2204. }
  2205. S2.slots[p2].type = S1.slots[p1].type;
  2206. S2.slots[p2].count = val;
  2207. S1.slots[p1].count -= val;
  2208. }
  2209. if(!S1.slots[p1].count) //if we've moved all creatures
  2210. S1.slots.erase(p1);
  2211. }
  2212. if((s1->needsLastStack() && !S1.stacksCount()) //it's not allowed to take last stack from hero army!
  2213. || (s2->needsLastStack() && !S2.stacksCount())
  2214. )
  2215. {
  2216. complain("Cannot take the last stack!");
  2217. return false; //leave without applying changes to garrison
  2218. }
  2219. //apply changes
  2220. SetGarrisons sg;
  2221. sg.garrs[id1] = S1;
  2222. if(s1 != s2)
  2223. sg.garrs[id2] = S2;
  2224. sendAndApply(&sg);
  2225. return true;
  2226. }
  2227. int CGameHandler::getPlayerAt( CConnection *c ) const
  2228. {
  2229. std::set<int> all;
  2230. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  2231. if(i->second == c)
  2232. all.insert(i->first);
  2233. switch(all.size())
  2234. {
  2235. case 0:
  2236. return 255;
  2237. case 1:
  2238. return *all.begin();
  2239. default:
  2240. {
  2241. //if we have more than one player at this connection, try to pick active one
  2242. if(vstd::contains(all,int(gs->currentPlayer)))
  2243. return gs->currentPlayer;
  2244. else
  2245. return 253; //cannot say which player is it
  2246. }
  2247. }
  2248. }
  2249. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  2250. {
  2251. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  2252. if(!vstd::contains(s1->slots,pos))
  2253. {
  2254. complain("Illegal call to disbandCreature - no such stack in army!");
  2255. return false;
  2256. }
  2257. s1->slots.erase(pos);
  2258. SetGarrisons sg;
  2259. sg.garrs[id] = s1->getArmy();
  2260. sendAndApply(&sg);
  2261. return true;
  2262. }
  2263. bool CGameHandler::buildStructure( si32 tid, si32 bid )
  2264. {
  2265. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  2266. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  2267. if(gs->canBuildStructure(t,bid) != 7)
  2268. {
  2269. complain("Cannot build that building!");
  2270. return false;
  2271. }
  2272. if(bid == 26) //grail
  2273. {
  2274. if(!t->visitingHero || !t->visitingHero->hasArt(2))
  2275. {
  2276. complain("Cannot build grail - hero doesn't have it");
  2277. return false;
  2278. }
  2279. removeArtifact(2, t->visitingHero->id);
  2280. }
  2281. NewStructures ns;
  2282. ns.tid = tid;
  2283. if ( (bid == 18) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[0]+37))) )
  2284. ns.bid.insert(19);//we have upgr. dwelling, upgr. horde will be builded as well
  2285. else if ( (bid == 24) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[1]+37))) )
  2286. ns.bid.insert(25);
  2287. else if(bid>36) //upg dwelling
  2288. {
  2289. if ( (bid-37 == t->town->hordeLvl[0]) && (vstd::contains(t->builtBuildings,18)) )
  2290. ns.bid.insert(19);//we have horde, will be upgraded as well as dwelling
  2291. if ( (bid-37 == t->town->hordeLvl[1]) && (vstd::contains(t->builtBuildings,24)) )
  2292. ns.bid.insert(25);
  2293. SetAvailableCreatures ssi;
  2294. ssi.tid = tid;
  2295. ssi.creatures = t->creatures;
  2296. ssi.creatures[bid-37].second.push_back(t->town->upgradedCreatures[bid-37]);
  2297. sendAndApply(&ssi);
  2298. }
  2299. else if(bid >= 30) //bas. dwelling
  2300. {
  2301. int crid = t->town->basicCreatures[bid-30];
  2302. SetAvailableCreatures ssi;
  2303. ssi.tid = tid;
  2304. ssi.creatures = t->creatures;
  2305. ssi.creatures[bid-30].first = VLC->creh->creatures[crid]->growth;
  2306. ssi.creatures[bid-30].second.push_back(crid);
  2307. sendAndApply(&ssi);
  2308. }
  2309. else if(bid == 11)
  2310. ns.bid.insert(27);
  2311. else if(bid == 12)
  2312. ns.bid.insert(28);
  2313. else if(bid == 13)
  2314. ns.bid.insert(29);
  2315. else if (t->subID == 4 && bid == 17) //veil of darkness
  2316. {
  2317. GiveBonus gb(GiveBonus::TOWN);
  2318. gb.bonus.type = Bonus::DARKNESS;
  2319. gb.bonus.val = 20;
  2320. gb.id = t->id;
  2321. gb.bonus.duration = Bonus::PERMANENT;
  2322. gb.bonus.source = Bonus::TOWN_STRUCTURE;
  2323. gb.bonus.id = 17;
  2324. sendAndApply(&gb);
  2325. }
  2326. else if ( t->subID == 5 && bid == 22 )
  2327. {
  2328. setPortalDwelling(t);
  2329. }
  2330. ns.bid.insert(bid);
  2331. ns.builded = t->builded + 1;
  2332. sendAndApply(&ns);
  2333. //reveal ground for lookout tower
  2334. FoWChange fw;
  2335. fw.player = t->tempOwner;
  2336. fw.mode = 1;
  2337. getTilesInRange(fw.tiles,t->pos,t->getSightRadious(),t->tempOwner,1);
  2338. sendAndApply(&fw);
  2339. SetResources sr;
  2340. sr.player = t->tempOwner;
  2341. sr.res = gs->getPlayer(t->tempOwner)->resources;
  2342. for(int i=0;i<b->resources.size();i++)
  2343. sr.res[i]-=b->resources[i];
  2344. sendAndApply(&sr);
  2345. if(bid<5) //it's mage guild
  2346. {
  2347. if(t->visitingHero)
  2348. giveSpells(t,t->visitingHero);
  2349. if(t->garrisonHero)
  2350. giveSpells(t,t->garrisonHero);
  2351. }
  2352. if(t->visitingHero)
  2353. vistiCastleObjects (t, t->visitingHero);
  2354. if(t->garrisonHero)
  2355. vistiCastleObjects (t, t->garrisonHero);
  2356. checkLossVictory(t->tempOwner);
  2357. return true;
  2358. }
  2359. bool CGameHandler::razeStructure (si32 tid, si32 bid)
  2360. {
  2361. ///incomplete, simply erases target building
  2362. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  2363. if (t->builtBuildings.find(bid) == t->builtBuildings.end())
  2364. return false;
  2365. RazeStructures rs;
  2366. rs.tid = tid;
  2367. rs.bid.insert(bid);
  2368. rs.destroyed = t->destroyed + 1;
  2369. sendAndApply(&rs);
  2370. //TODO: Remove dwellers
  2371. if (t->subID == 4 && bid == 17) //Veil of Darkness
  2372. {
  2373. RemoveBonus rb(RemoveBonus::TOWN);
  2374. rb.whoID = t->id;
  2375. rb.source = Bonus::TOWN_STRUCTURE;
  2376. rb.id = 17;
  2377. sendAndApply(&rb);
  2378. }
  2379. return true;
  2380. }
  2381. void CGameHandler::sendMessageToAll( const std::string &message )
  2382. {
  2383. SystemMessage sm;
  2384. sm.text = message;
  2385. sendToAllClients(&sm);
  2386. }
  2387. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram, si32 fromLvl )
  2388. {
  2389. const CGDwelling *dw = static_cast<CGDwelling*>(gs->map->objects[objid]);
  2390. const CArmedInstance *dst = NULL;
  2391. const CCreature *c = VLC->creh->creatures[crid];
  2392. bool warMachine = c->hasBonusOfType(Bonus::SIEGE_WEAPON);
  2393. //TODO: test for owning
  2394. if(dw->ID == TOWNI_TYPE)
  2395. dst = dw;
  2396. else if(dw->ID == 17 || dw->ID == 20) //advmap dwelling
  2397. dst = getHero(gs->getPlayer(dw->tempOwner)->currentSelection); //TODO: check if current hero is really visiting dwelling
  2398. else if(dw->ID == 106)
  2399. dst = dynamic_cast<const CGHeroInstance *>(getTile(dw->visitablePos())->visitableObjects.back());
  2400. assert(dw && dst);
  2401. //verify
  2402. bool found = false;
  2403. int level = 0;
  2404. typedef std::pair<const int,int> Parka;
  2405. for(; level < dw->creatures.size(); level++) //iterate through all levels
  2406. {
  2407. if ( (fromLvl != -1) && ( level !=fromLvl ) )
  2408. continue;
  2409. const std::pair<ui32, std::vector<ui32> > &cur = dw->creatures[level]; //current level info <amount, list of cr. ids>
  2410. int i = 0;
  2411. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  2412. if(cur.second[i] == crid)
  2413. break;
  2414. if(i < cur.second.size())
  2415. {
  2416. found = true;
  2417. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  2418. break;
  2419. }
  2420. }
  2421. int slot = dst->getSlotFor(crid);
  2422. if(!found && complain("Cannot recruit: no such creatures!")
  2423. || cram > VLC->creh->creatures[crid]->maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  2424. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  2425. || slot<0 && !warMachine && complain("Cannot recruit: no available slot!"))
  2426. {
  2427. return false;
  2428. }
  2429. //recruit
  2430. SetResources sr;
  2431. sr.player = dst->tempOwner;
  2432. for(int i=0;i<RESOURCE_QUANTITY;i++)
  2433. sr.res[i] = gs->getPlayer(dst->tempOwner)->resources[i] - (c->cost[i] * cram);
  2434. SetAvailableCreatures sac;
  2435. sac.tid = objid;
  2436. sac.creatures = dw->creatures;
  2437. sac.creatures[level].first -= cram;
  2438. sendAndApply(&sr);
  2439. sendAndApply(&sac);
  2440. if(warMachine)
  2441. {
  2442. switch(crid)
  2443. {
  2444. case 146:
  2445. giveHeroArtifact(4, dst->id, 13);
  2446. break;
  2447. case 147:
  2448. giveHeroArtifact(6, dst->id, 15);
  2449. break;
  2450. case 148:
  2451. giveHeroArtifact(5, dst->id, 14);
  2452. break;
  2453. default:
  2454. complain("This war machine cannot be recruited!");
  2455. return false;
  2456. }
  2457. }
  2458. else
  2459. {
  2460. SetGarrisons sg;
  2461. sg.garrs[dst->id] = dst->getArmy();
  2462. sg.garrs[dst->id] .addToSlot(slot, crid, cram);
  2463. sendAndApply(&sg);
  2464. }
  2465. return true;
  2466. }
  2467. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  2468. {
  2469. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  2470. UpgradeInfo ui = gs->getUpgradeInfo(obj->getStack(pos));
  2471. int player = obj->tempOwner;
  2472. int crQuantity = obj->slots[pos].count;
  2473. //check if upgrade is possible
  2474. if((ui.oldID<0 || !vstd::contains(ui.newID,upgID)) && complain("That upgrade is not possible!"))
  2475. {
  2476. return false;
  2477. }
  2478. //check if player has enough resources
  2479. for(int i=0;i<ui.cost.size();i++)
  2480. {
  2481. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  2482. {
  2483. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  2484. {
  2485. complain("Cannot upgrade, not enough resources!");
  2486. return false;
  2487. }
  2488. }
  2489. }
  2490. //take resources
  2491. for(int i=0;i<ui.cost.size();i++)
  2492. {
  2493. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  2494. {
  2495. SetResource sr;
  2496. sr.player = player;
  2497. sr.resid = j->first;
  2498. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  2499. sendAndApply(&sr);
  2500. }
  2501. }
  2502. //upgrade creature
  2503. SetGarrisons sg;
  2504. sg.garrs[objid] = obj->getArmy();
  2505. sg.garrs[objid].slots[pos].setType(upgID);
  2506. sendAndApply(&sg);
  2507. return true;
  2508. }
  2509. bool CGameHandler::garrisonSwap( si32 tid )
  2510. {
  2511. CGTownInstance *town = gs->getTown(tid);
  2512. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2513. {
  2514. CCreatureSet csn = town->visitingHero->getArmy(), cso = town->getArmy();
  2515. while(!cso.slots.empty())//while there are unmoved creatures
  2516. {
  2517. int pos = csn.getSlotFor(cso.slots.begin()->second.type->idNumber);
  2518. if(pos<0)
  2519. {
  2520. //try to merge two other stacks to make place
  2521. std::pair<TSlot, TSlot> toMerge;
  2522. if(csn.mergableStacks(toMerge, cso.slots.begin()->first))
  2523. {
  2524. //merge
  2525. csn.slots[toMerge.second].count += csn.slots[toMerge.first].count;
  2526. csn.slots[toMerge.first] = cso.slots.begin()->second;
  2527. }
  2528. else
  2529. {
  2530. complain("Cannot make garrison swap, not enough free slots!");
  2531. return false;
  2532. }
  2533. }
  2534. else if(csn.slots.find(pos) != csn.slots.end()) //add creatures to the existing stack
  2535. {
  2536. csn.slots[pos].count += cso.slots.begin()->second.count;
  2537. }
  2538. else //move stack on the free pos
  2539. {
  2540. csn.slots[pos].type = cso.slots.begin()->second.type;
  2541. csn.slots[pos].count = cso.slots.begin()->second.count;
  2542. }
  2543. cso.slots.erase(cso.slots.begin());
  2544. }
  2545. SetGarrisons sg;
  2546. sg.garrs[town->visitingHero->id] = csn;
  2547. sg.garrs[town->id] = csn;
  2548. sendAndApply(&sg);
  2549. SetHeroesInTown intown;
  2550. intown.tid = tid;
  2551. intown.visiting = -1;
  2552. intown.garrison = town->visitingHero->id;
  2553. sendAndApply(&intown);
  2554. return true;
  2555. }
  2556. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2557. {
  2558. //check if moving hero out of town will break 8 wandering heroes limit
  2559. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2560. {
  2561. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2562. return false;
  2563. }
  2564. SetHeroesInTown intown;
  2565. intown.tid = tid;
  2566. intown.garrison = -1;
  2567. intown.visiting = town->garrisonHero->id;
  2568. sendAndApply(&intown);
  2569. //town will be empty
  2570. SetGarrisons sg;
  2571. sg.garrs[tid] = CCreatureSet();
  2572. sendAndApply(&sg);
  2573. return true;
  2574. }
  2575. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2576. {
  2577. SetGarrisons sg;
  2578. sg.garrs[town->id] = town->visitingHero->getArmy();;
  2579. sg.garrs[town->garrisonHero->id] = town->garrisonHero->getArmy();
  2580. SetHeroesInTown intown;
  2581. intown.tid = tid;
  2582. intown.garrison = town->visitingHero->id;
  2583. intown.visiting = town->garrisonHero->id;
  2584. sendAndApply(&intown);
  2585. sendAndApply(&sg);
  2586. return true;
  2587. }
  2588. else
  2589. {
  2590. complain("Cannot swap garrison hero!");
  2591. return false;
  2592. }
  2593. }
  2594. // With the amount of changes done to the function, it's more like transferArtifacts.
  2595. bool CGameHandler::swapArtifacts(si32 srcHeroID, si32 destHeroID, ui16 srcSlot, ui16 destSlot)
  2596. {
  2597. CGHeroInstance *srcHero = gs->getHero(srcHeroID);
  2598. CGHeroInstance *destHero = gs->getHero(destHeroID);
  2599. // Make sure exchange is even possible between the two heroes.
  2600. if ((distance(srcHero->pos,destHero->pos) > 1.5 )|| (srcHero->tempOwner != destHero->tempOwner))
  2601. return false;
  2602. const CArtifact *srcArtifact = srcHero->getArt(srcSlot);
  2603. const CArtifact *destArtifact = destHero->getArt(destSlot);
  2604. if (srcArtifact == NULL) {
  2605. complain("No artifact to swap!");
  2606. return false;
  2607. }
  2608. SetHeroArtifacts sha;
  2609. sha.hid = srcHeroID;
  2610. sha.artifacts = srcHero->artifacts;
  2611. sha.artifWorn = srcHero->artifWorn;
  2612. // Combinational artifacts needs to be removed first so they don't get denied movement because of their own locks.
  2613. if (srcHeroID == destHeroID && srcSlot < 19 && destSlot < 19) {
  2614. sha.setArtAtPos(srcSlot, -1);
  2615. if (!vstd::contains(sha.artifWorn, destSlot))
  2616. destArtifact = NULL;
  2617. }
  2618. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2619. // Moving to the backpack is always allowed.
  2620. if ((!srcArtifact || destSlot < 19)
  2621. && (srcArtifact && !srcArtifact->fitsAt(srcHeroID == destHeroID ? sha.artifWorn : destHero->artifWorn, destSlot)))
  2622. {
  2623. complain("Cannot swap artifacts!");
  2624. return false;
  2625. }
  2626. if ((srcArtifact && srcArtifact->id == 145) || (destArtifact && destArtifact->id == 145)) {
  2627. complain("Cannot move artifact locks.");
  2628. return false;
  2629. }
  2630. if (destSlot >= 19 && srcArtifact->isBig()) {
  2631. complain("Cannot put big artifacts in backpack!");
  2632. return false;
  2633. }
  2634. if (srcSlot == 16 || destSlot == 16) {
  2635. complain("Cannot move catapult!");
  2636. return false;
  2637. }
  2638. // If dest does not fit in src, put it in dest's backpack instead.
  2639. if (srcHeroID == destHeroID) // To avoid stumbling on own locks, remove artifact first.
  2640. sha.setArtAtPos(destSlot, -1);
  2641. const bool destFits = !destArtifact || srcSlot >= 19 || destSlot >= 19 || destArtifact->fitsAt(sha.artifWorn, srcSlot);
  2642. if (srcHeroID == destHeroID && destArtifact)
  2643. sha.setArtAtPos(destSlot, destArtifact->id);
  2644. sha.setArtAtPos(srcSlot, -1);
  2645. if (destSlot < 19 && (destArtifact || srcSlot < 19) && destFits)
  2646. sha.setArtAtPos(srcSlot, destArtifact ? destArtifact->id : -1);
  2647. // Internal hero artifact arrangement.
  2648. if(srcHero == destHero) {
  2649. // Correction for destination from removing source artifact in backpack.
  2650. if (srcSlot >= 19 && destSlot >= 19 && srcSlot < destSlot)
  2651. destSlot--;
  2652. sha.setArtAtPos(destSlot, srcHero->getArtAtPos(srcSlot));
  2653. }
  2654. sendAndApply(&sha);
  2655. if (srcHeroID != destHeroID) {
  2656. // Exchange between two different heroes.
  2657. sha.hid = destHeroID;
  2658. sha.artifacts = destHero->artifacts;
  2659. sha.artifWorn = destHero->artifWorn;
  2660. sha.setArtAtPos(destSlot, srcArtifact ? srcArtifact->id : -1);
  2661. if (!destFits)
  2662. sha.setArtAtPos(sha.artifacts.size() + 19, destHero->getArtAtPos(destSlot));
  2663. sendAndApply(&sha);
  2664. }
  2665. return true;
  2666. }
  2667. /**
  2668. * Assembles or disassembles a combination artifact.
  2669. * @param heroID ID of hero holding the artifact(s).
  2670. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  2671. * @param assemble True for assembly operation, false for disassembly.
  2672. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  2673. * artifact to assemble to. Otherwise it's not used.
  2674. */
  2675. bool CGameHandler::assembleArtifacts (si32 heroID, ui16 artifactSlot, bool assemble, ui32 assembleTo)
  2676. {
  2677. if (artifactSlot < 0 || artifactSlot > 18) {
  2678. complain("Illegal artifact slot.");
  2679. return false;
  2680. }
  2681. CGHeroInstance *hero = gs->getHero(heroID);
  2682. const CArtifact *destArtifact = hero->getArt(artifactSlot);
  2683. SetHeroArtifacts sha;
  2684. sha.hid = heroID;
  2685. sha.artifacts = hero->artifacts;
  2686. sha.artifWorn = hero->artifWorn;
  2687. if (assemble) {
  2688. if (VLC->arth->artifacts.size() < assembleTo) {
  2689. complain("Illegal artifact to assemble to.");
  2690. return false;
  2691. }
  2692. if (!destArtifact->canBeAssembledTo(hero->artifWorn, assembleTo)) {
  2693. complain("Artifact cannot be assembled.");
  2694. return false;
  2695. }
  2696. const CArtifact &artifact = *VLC->arth->artifacts[assembleTo];
  2697. if (artifact.constituents == NULL) {
  2698. complain("Not a combinational artifact.");
  2699. return false;
  2700. }
  2701. // Perform assembly.
  2702. bool destConsumed = false; // Determines which constituent that will be counted for together with the artifact.
  2703. const bool destSpecific = vstd::contains(artifact.possibleSlots, artifactSlot); // Prefer the chosen slot as the location for the assembled artifact.
  2704. BOOST_FOREACH(ui32 constituentID, *artifact.constituents) {
  2705. if (destSpecific && constituentID == destArtifact->id) {
  2706. sha.artifWorn[artifactSlot] = assembleTo;
  2707. destConsumed = true;
  2708. continue;
  2709. }
  2710. bool found = false;
  2711. for (std::map<ui16, ui32>::iterator it = sha.artifWorn.begin(); it != sha.artifWorn.end(); ++it) {
  2712. if (it->second == constituentID) { // Found possible constituent to substitute.
  2713. if (destSpecific && !destConsumed && it->second == destArtifact->id) {
  2714. // Find the specified destination for assembled artifact.
  2715. if (it->first == artifactSlot) {
  2716. it->second = assembleTo;
  2717. destConsumed = true;
  2718. found = true;
  2719. break;
  2720. }
  2721. } else {
  2722. // Either put the assembled artifact in a fitting spot, or put a lock.
  2723. if (!destSpecific && !destConsumed && vstd::contains(artifact.possibleSlots, it->first)) {
  2724. it->second = assembleTo;
  2725. destConsumed = true;
  2726. } else {
  2727. it->second = 145;
  2728. }
  2729. found = true;
  2730. break;
  2731. }
  2732. }
  2733. }
  2734. if (!found) {
  2735. complain("Constituent missing.");
  2736. return false;
  2737. }
  2738. }
  2739. } else {
  2740. // Perform disassembly.
  2741. bool destConsumed = false; // Determines which constituent that will be counted for together with the artifact.
  2742. BOOST_FOREACH(ui32 constituentID, *destArtifact->constituents) {
  2743. const CArtifact &constituent = *VLC->arth->artifacts[constituentID];
  2744. if (!destConsumed && vstd::contains(constituent.possibleSlots, artifactSlot)) {
  2745. sha.artifWorn[artifactSlot] = constituentID;
  2746. destConsumed = true;
  2747. } else {
  2748. BOOST_REVERSE_FOREACH(ui16 slotID, constituent.possibleSlots) {
  2749. if (vstd::contains(sha.artifWorn, slotID) && sha.artifWorn[slotID] == 145) {
  2750. sha.artifWorn[slotID] = constituentID;
  2751. break;
  2752. }
  2753. }
  2754. }
  2755. }
  2756. }
  2757. sendAndApply(&sha);
  2758. return true;
  2759. }
  2760. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  2761. {
  2762. CGHeroInstance *hero = gs->getHero(hid);
  2763. CGTownInstance *town = hero->visitedTown;
  2764. if(aid==0) //spellbook
  2765. {
  2766. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  2767. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  2768. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  2769. )
  2770. return false;
  2771. giveResource(hero->getOwner(),6,-500);
  2772. giveHeroArtifact(0,hid,17);
  2773. giveSpells(town,hero);
  2774. return true;
  2775. }
  2776. else if(aid < 7 && aid > 3) //war machine
  2777. {
  2778. int price = VLC->arth->artifacts[aid]->price;
  2779. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  2780. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  2781. || gs->getPlayer(hero->getOwner())->resources[6] < price && complain("Not enough gold!") //no gold
  2782. || (!(town->subID == 6 && vstd::contains(town->builtBuildings,si32(22) ) )
  2783. && town->town->warMachine!= aid ) && complain("This machine is unavailable here!") )
  2784. {
  2785. return false;
  2786. }
  2787. giveResource(hero->getOwner(),6,-price);
  2788. giveHeroArtifact(aid,hid,9+aid);
  2789. return true;
  2790. }
  2791. return false;
  2792. }
  2793. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, int rid, int aid)
  2794. {
  2795. if(!vstd::contains(m->availableItemsIds(RESOURCE_ARTIFACT), aid))
  2796. COMPLAIN_RET("That artifact is unavailable!");
  2797. int b1, b2;
  2798. m->getOffer(rid, aid, b1, b2, RESOURCE_ARTIFACT);
  2799. if(getResource(h->tempOwner, rid) < b1)
  2800. COMPLAIN_RET("You can't afford to buy this artifact!");
  2801. SetResource sr;
  2802. sr.player = h->tempOwner;
  2803. sr.resid = rid;
  2804. sr.val = getResource(h->tempOwner, rid) - b1;
  2805. sendAndApply(&sr);
  2806. SetAvailableArtifacts saa;
  2807. if(m->o->ID == TOWNI_TYPE)
  2808. {
  2809. saa.id = -1;
  2810. saa.arts = CGTownInstance::merchantArtifacts;
  2811. }
  2812. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m->o)) //black market
  2813. {
  2814. saa.id = bm->id;
  2815. saa.arts = bm->artifacts;
  2816. }
  2817. else
  2818. COMPLAIN_RET("Wrong marktet...");
  2819. bool found = false;
  2820. BOOST_FOREACH(const CArtifact *&art, saa.arts)
  2821. {
  2822. if(art && art->id == aid)
  2823. {
  2824. art = NULL;
  2825. found = true;
  2826. break;
  2827. }
  2828. }
  2829. if(!found)
  2830. COMPLAIN_RET("Cannot find selected artifact on the list");
  2831. sendAndApply(&saa);
  2832. giveHeroArtifact(aid, h->id, -2);
  2833. }
  2834. bool CGameHandler::tradeResources(const IMarket *market, ui32 val, ui8 player, ui32 id1, ui32 id2)
  2835. {
  2836. int r1 = gs->getPlayer(player)->resources[id1],
  2837. r2 = gs->getPlayer(player)->resources[id2];
  2838. amin(val, r1); //can't trade more resources than have
  2839. int b1, b2; //base quantities for trade
  2840. market->getOffer(id1, id2, b1, b2, RESOURCE_RESOURCE);
  2841. int units = val / b1; //how many base quantities we trade
  2842. if(val%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2843. {
  2844. //TODO: complain?
  2845. assert(0);
  2846. }
  2847. SetResource sr;
  2848. sr.player = player;
  2849. sr.resid = id1;
  2850. sr.val = r1 - b1 * units;
  2851. sendAndApply(&sr);
  2852. sr.resid = id2;
  2853. sr.val = r2 + b2 * units;
  2854. sendAndApply(&sr);
  2855. return true;
  2856. }
  2857. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, ui32 slot, ui32 resourceID)
  2858. {
  2859. if(!vstd::contains(hero->Slots(), slot))
  2860. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  2861. const CStackInstance &s = hero->getStack(slot);
  2862. if(s.count < count //can't sell more creatures than have
  2863. || hero->Slots().size() == 1 && hero->needsLastStack() && s.count == count) //can't sell last stack
  2864. {
  2865. COMPLAIN_RET("Not enough creatures in army!");
  2866. }
  2867. int b1, b2; //base quantities for trade
  2868. market->getOffer(s.type->idNumber, resourceID, b1, b2, CREATURE_RESOURCE);
  2869. int units = count / b1; //how many base quantities we trade
  2870. if(count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2871. {
  2872. //TODO: complain?
  2873. assert(0);
  2874. }
  2875. SetGarrisons sg;
  2876. sg.garrs[hero->id] = hero->getArmy();
  2877. if(s.count > count)
  2878. sg.garrs[hero->id].setStackCount(slot, s.count - count);
  2879. else
  2880. sg.garrs[hero->id].eraseStack(slot);
  2881. sendAndApply(&sg);
  2882. SetResource sr;
  2883. sr.player = hero->tempOwner;
  2884. sr.resid = resourceID;
  2885. sr.val = getResource(hero->tempOwner, resourceID) + b2 * units;
  2886. sendAndApply(&sr);
  2887. return true;
  2888. }
  2889. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, ui32 slot)
  2890. {
  2891. const CArmedInstance *army = NULL;
  2892. if (hero)
  2893. army = hero;
  2894. else
  2895. {
  2896. army = dynamic_cast<const CGTownInstance *>(market->o);
  2897. }
  2898. if (!army)
  2899. COMPLAIN_RET("Incorrect call to transform in undead!");
  2900. tlog1<<"test2\n";
  2901. if(!vstd::contains(army->Slots(), slot))
  2902. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  2903. tlog1<<"test3\n";
  2904. const CStackInstance &s = army->getStack(slot);
  2905. int resCreature;//resulting creature - bone dragons or skeletons
  2906. if (s.hasBonusOfType(Bonus::KING1))
  2907. resCreature = 68;
  2908. else
  2909. resCreature = 56;
  2910. tlog1<<"test4\n";
  2911. SetGarrisons sg;
  2912. sg.garrs[army->id] = army->getArmy();
  2913. sg.garrs[army->id].setCreature(slot, resCreature, s.count);
  2914. sendAndApply(&sg);
  2915. return true;
  2916. }
  2917. bool CGameHandler::sendResources(ui32 val, ui8 player, ui32 r1, ui32 r2)
  2918. {
  2919. const PlayerState *p2 = gs->getPlayer(r2, false);
  2920. if(!p2 || p2->status != PlayerState::INGAME)
  2921. {
  2922. complain("Dest player must be in game!");
  2923. return false;
  2924. }
  2925. si32 curRes1 = gs->getPlayer(player)->resources[r1], curRes2 = gs->getPlayer(r2)->resources[r1];
  2926. val = std::min(si32(val),curRes1);
  2927. SetResource sr;
  2928. sr.player = player;
  2929. sr.resid = r1;
  2930. sr.val = curRes1 - val;
  2931. sendAndApply(&sr);
  2932. sr.player = r2;
  2933. sr.val = curRes2 + val;
  2934. sendAndApply(&sr);
  2935. return true;
  2936. }
  2937. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  2938. {
  2939. gs->getHero(hid)-> formation = formation;
  2940. return true;
  2941. }
  2942. bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, ui8 player)
  2943. {
  2944. const PlayerState *p = gs->getPlayer(player);
  2945. const CGTownInstance *t = gs->getTown(obj->id);
  2946. //common prconditions
  2947. if( p->resources[6]<2500 && complain("Not enough gold for buying hero!")
  2948. || getHeroCount(player, false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!"))
  2949. return false;
  2950. if(t) //tavern in town
  2951. {
  2952. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  2953. || t->visitingHero && complain("There is visiting hero - no place!"))
  2954. return false;
  2955. }
  2956. else if(obj->ID == 95) //Tavern on adv map
  2957. {
  2958. if(getTile(obj->visitablePos())->visitableObjects.back() != obj && complain("Tavern entry must be unoccupied!"))
  2959. return false;
  2960. }
  2961. CGHeroInstance *nh = p->availableHeroes[hid];
  2962. assert(nh);
  2963. HeroRecruited hr;
  2964. hr.tid = obj->id;
  2965. hr.hid = nh->subID;
  2966. hr.player = player;
  2967. hr.tile = obj->visitablePos() + nh->getVisitableOffset();
  2968. sendAndApply(&hr);
  2969. std::map<ui32,CGHeroInstance *> pool = gs->unusedHeroesFromPool();
  2970. const CGHeroInstance *theOtherHero = p->availableHeroes[!hid];
  2971. const CGHeroInstance *newHero = gs->hpool.pickHeroFor(false, player, getNativeTown(player), pool, theOtherHero->type->heroClass);
  2972. SetAvailableHeroes sah;
  2973. sah.player = player;
  2974. if(newHero)
  2975. {
  2976. sah.hid[hid] = newHero->subID;
  2977. sah.army[hid] = new CCreatureSet();
  2978. sah.army[hid]->addToSlot(0, VLC->creh->nameToID[newHero->type->refTypeStack[0]],1);
  2979. }
  2980. else
  2981. sah.hid[hid] = -1;
  2982. sah.hid[!hid] = theOtherHero ? theOtherHero->subID : -1;
  2983. sendAndApply(&sah);
  2984. SetResource sr;
  2985. sr.player = player;
  2986. sr.resid = 6;
  2987. sr.val = p->resources[6] - 2500;
  2988. sendAndApply(&sr);
  2989. if(t)
  2990. {
  2991. vistiCastleObjects (t, nh);
  2992. giveSpells (t,nh);
  2993. }
  2994. return true;
  2995. }
  2996. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  2997. {
  2998. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2999. if(vstd::contains(callbacks,qid))
  3000. {
  3001. CFunctionList<void(ui32)> callb = callbacks[qid];
  3002. callbacks.erase(qid);
  3003. if(callb)
  3004. callb(answer);
  3005. }
  3006. else if(vstd::contains(garrisonCallbacks,qid))
  3007. {
  3008. if(garrisonCallbacks[qid])
  3009. garrisonCallbacks[qid]();
  3010. garrisonCallbacks.erase(qid);
  3011. allowedExchanges.erase(qid);
  3012. }
  3013. else
  3014. {
  3015. tlog1 << "Unknown query reply...\n";
  3016. return false;
  3017. }
  3018. return true;
  3019. }
  3020. bool CGameHandler::makeBattleAction( BattleAction &ba )
  3021. {
  3022. tlog1 << "\tMaking action of type " << ba.actionType << std::endl;
  3023. bool ok = true;
  3024. switch(ba.actionType)
  3025. {
  3026. case 2: //walk
  3027. {
  3028. sendAndApply(&StartAction(ba)); //start movement
  3029. moveStack(ba.stackNumber,ba.destinationTile); //move
  3030. sendAndApply(&EndAction());
  3031. break;
  3032. }
  3033. case 3: //defend
  3034. case 8: //wait
  3035. {
  3036. sendAndApply(&StartAction(ba));
  3037. sendAndApply(&EndAction());
  3038. break;
  3039. }
  3040. case 4: //retreat/flee
  3041. {
  3042. if( !gs->battleCanFlee(ba.side ? gs->curB->side2 : gs->curB->side1) )
  3043. break;
  3044. //TODO: remove retreating hero from map and place it in recruitment list
  3045. BattleResult *br = new BattleResult;
  3046. br->result = 1;
  3047. br->winner = !ba.side; //fleeing side loses
  3048. gs->curB->calculateCasualties(br->casualties);
  3049. giveExp(*br);
  3050. battleResult.set(br);
  3051. break;
  3052. }
  3053. case 6: //walk or attack
  3054. {
  3055. sendAndApply(&StartAction(ba)); //start movement and attack
  3056. int startingPos = gs->curB->getStack(ba.stackNumber)->position;
  3057. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  3058. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  3059. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  3060. if(curStack->position != ba.destinationTile //we wasn't able to reach destination tile
  3061. && !(curStack->doubleWide()
  3062. && ( curStack->position == ba.destinationTile + (curStack->attackerOwned ? +1 : -1 ) )
  3063. ) //nor occupy specified hex
  3064. )
  3065. {
  3066. std::string problem = "We cannot move this stack to its destination " + curStack->type->namePl;
  3067. tlog3 << problem << std::endl;
  3068. complain(problem);
  3069. ok = false;
  3070. sendAndApply(&EndAction());
  3071. break;
  3072. }
  3073. if(curStack->ID == stackAtEnd->ID) //we should just move, it will be handled by following check
  3074. {
  3075. stackAtEnd = NULL;
  3076. }
  3077. if(!stackAtEnd)
  3078. {
  3079. std::ostringstream problem;
  3080. problem << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  3081. std::string probl = problem.str();
  3082. tlog3 << probl << std::endl;
  3083. complain(probl);
  3084. ok = false;
  3085. sendAndApply(&EndAction());
  3086. break;
  3087. }
  3088. ui16 curpos = curStack->position,
  3089. enemypos = stackAtEnd->position;
  3090. if( !(
  3091. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  3092. || (curStack->doubleWide() //back <=> front
  3093. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  3094. || (stackAtEnd->doubleWide() //front <=> back
  3095. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  3096. || (stackAtEnd->doubleWide() && curStack->doubleWide()//back <=> back
  3097. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  3098. )
  3099. )
  3100. {
  3101. tlog3 << "Attack cannot be performed!";
  3102. sendAndApply(&EndAction());
  3103. ok = false;
  3104. }
  3105. //attack
  3106. BattleAttack bat;
  3107. prepareAttack(bat, curStack, stackAtEnd, distance);
  3108. sendAndApply(&bat);
  3109. handleAfterAttackCasting(bat);
  3110. //counterattack
  3111. if(!curStack->hasBonusOfType(Bonus::BLOCKS_RETALIATION)
  3112. && stackAtEnd->alive()
  3113. && ( stackAtEnd->counterAttacks > 0 || stackAtEnd->hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS) )
  3114. && !stackAtEnd->hasBonusOfType(Bonus::SIEGE_WEAPON)
  3115. && !stackAtEnd->hasBonusOfType(Bonus::HYPNOTIZED))
  3116. {
  3117. prepareAttack(bat, stackAtEnd, curStack, 0);
  3118. bat.flags |= 2;
  3119. sendAndApply(&bat);
  3120. handleAfterAttackCasting(bat);
  3121. }
  3122. //second attack
  3123. if(curStack->valOfBonuses(Bonus::ADDITIONAL_ATTACK) > 0
  3124. && !curStack->hasBonusOfType(Bonus::SHOOTER)
  3125. && curStack->alive()
  3126. && stackAtEnd->alive() )
  3127. {
  3128. bat.flags = 0;
  3129. prepareAttack(bat, curStack, stackAtEnd, 0);
  3130. sendAndApply(&bat);
  3131. handleAfterAttackCasting(bat);
  3132. }
  3133. //return
  3134. if(curStack->hasBonusOfType(Bonus::RETURN_AFTER_STRIKE) && startingPos != curStack->position && curStack->alive())
  3135. {
  3136. moveStack(ba.stackNumber, startingPos);
  3137. //NOTE: curStack->ID == ba.stackNumber (rev 1431)
  3138. }
  3139. sendAndApply(&EndAction());
  3140. break;
  3141. }
  3142. case 7: //shoot
  3143. {
  3144. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  3145. *destStack= gs->curB->getStackT(ba.destinationTile);
  3146. if( !gs->battleCanShoot(ba.stackNumber, ba.destinationTile) )
  3147. break;
  3148. sendAndApply(&StartAction(ba)); //start shooting
  3149. BattleAttack bat;
  3150. bat.flags |= 1;
  3151. prepareAttack(bat, curStack, destStack, 0);
  3152. sendAndApply(&bat);
  3153. if(curStack->valOfBonuses(Bonus::ADDITIONAL_ATTACK) > 0 //if unit shots twice let's make another shot
  3154. && curStack->alive()
  3155. && destStack->alive()
  3156. && curStack->shots
  3157. )
  3158. {
  3159. prepareAttack(bat, curStack, destStack, 0);
  3160. sendAndApply(&bat);
  3161. handleAfterAttackCasting(bat);
  3162. }
  3163. sendAndApply(&EndAction());
  3164. break;
  3165. }
  3166. case 9: //catapult
  3167. {
  3168. sendAndApply(&StartAction(ba));
  3169. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  3170. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics[attackingHero->getSecSkillLevel(10)]; //ballistics
  3171. int attackedPart = gs->curB->hexToWallPart(ba.destinationTile);
  3172. if(attackedPart == -1)
  3173. {
  3174. complain("catapult tried to attack non-catapultable hex!");
  3175. break;
  3176. }
  3177. int wallInitHP = gs->curB->si.wallState[attackedPart];
  3178. int dmgAlreadyDealt = 0; //in successive iterations damage is dealt but not yet substracted from wall's HPs
  3179. for(int g=0; g<sbi.shots; ++g)
  3180. {
  3181. if(wallInitHP + dmgAlreadyDealt == 3) //it's not destroyed
  3182. continue;
  3183. CatapultAttack ca; //package for clients
  3184. std::pair< std::pair< ui8, si16 >, ui8> attack; //<< attackedPart , destination tile >, damageDealt >
  3185. attack.first.first = attackedPart;
  3186. attack.first.second = ba.destinationTile;
  3187. attack.second = 0;
  3188. int chanceForHit = 0;
  3189. int dmgChance[3] = {sbi.noDmg, sbi.oneDmg, sbi.twoDmg}; //dmgChance[i] - chance for doing i dmg when hit is successful
  3190. switch(attackedPart)
  3191. {
  3192. case 0: //keep
  3193. chanceForHit = sbi.keep;
  3194. break;
  3195. case 1: //bottom tower
  3196. case 6: //upper tower
  3197. chanceForHit = sbi.tower;
  3198. break;
  3199. case 2: //bottom wall
  3200. case 3: //below gate
  3201. case 4: //over gate
  3202. case 5: //upper wall
  3203. chanceForHit = sbi.wall;
  3204. break;
  3205. case 7: //gate
  3206. chanceForHit = sbi.gate;
  3207. break;
  3208. }
  3209. if(rand()%100 <= chanceForHit) //hit is successful
  3210. {
  3211. int dmgRand = rand()%100;
  3212. //accumulating dmgChance
  3213. dmgChance[1] += dmgChance[0];
  3214. dmgChance[2] += dmgChance[1];
  3215. //calculating dealt damage
  3216. for(int v = 0; v < ARRAY_COUNT(dmgChance); ++v)
  3217. {
  3218. if(dmgRand <= dmgChance[v])
  3219. {
  3220. attack.second = std::min(3 - dmgAlreadyDealt - wallInitHP, v);
  3221. dmgAlreadyDealt += attack.second;
  3222. break;
  3223. }
  3224. }
  3225. //removing creatures in turrets / keep if one is destroyed
  3226. if(attack.second > 0 && (attackedPart == 0 || attackedPart == 1 || attackedPart == 6))
  3227. {
  3228. int posRemove = -1;
  3229. switch(attackedPart)
  3230. {
  3231. case 0: //keep
  3232. posRemove = -2;
  3233. break;
  3234. case 1: //bottom tower
  3235. posRemove = -3;
  3236. break;
  3237. case 6: //upper tower
  3238. posRemove = -4;
  3239. break;
  3240. }
  3241. BattleStacksRemoved bsr;
  3242. for(int g=0; g<gs->curB->stacks.size(); ++g)
  3243. {
  3244. if(gs->curB->stacks[g]->position == posRemove)
  3245. {
  3246. bsr.stackIDs.insert( gs->curB->stacks[g]->ID );
  3247. break;
  3248. }
  3249. }
  3250. sendAndApply(&bsr);
  3251. }
  3252. }
  3253. ca.attacker = ba.stackNumber;
  3254. ca.attackedParts.insert(attack);
  3255. sendAndApply(&ca);
  3256. }
  3257. sendAndApply(&EndAction());
  3258. break;
  3259. }
  3260. case 12: //healing
  3261. {
  3262. sendAndApply(&StartAction(ba));
  3263. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  3264. CStack *healer = gs->curB->getStack(ba.stackNumber),
  3265. *destStack = gs->curB->getStackT(ba.destinationTile);
  3266. if(healer == NULL || destStack == NULL || !healer->hasBonusOfType(Bonus::HEALER))
  3267. {
  3268. complain("There is either no healer, no destination, or healer cannot heal :P");
  3269. }
  3270. int maxHealable = destStack->MaxHealth() - destStack->firstHPleft;
  3271. int maxiumHeal = std::max(10, attackingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 27));
  3272. int healed = std::min(maxHealable, maxiumHeal);
  3273. if(healed == 0)
  3274. {
  3275. //nothing to heal.. should we complain?
  3276. }
  3277. else
  3278. {
  3279. StacksHealedOrResurrected shr;
  3280. shr.lifeDrain = false;
  3281. StacksHealedOrResurrected::HealInfo hi;
  3282. hi.healedHP = healed;
  3283. hi.lowLevelResurrection = 0;
  3284. hi.stackID = destStack->ID;
  3285. shr.healedStacks.push_back(hi);
  3286. sendAndApply(&shr);
  3287. }
  3288. sendAndApply(&EndAction());
  3289. break;
  3290. }
  3291. }
  3292. if(ba.stackNumber == gs->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  3293. battleMadeAction.setn(true);
  3294. return ok;
  3295. }
  3296. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  3297. {
  3298. bool cheated=true;
  3299. sendAndApply(&PlayerMessage(player,message));
  3300. if(message == "vcmiistari") //give all spells and 999 mana
  3301. {
  3302. SetMana sm;
  3303. ChangeSpells cs;
  3304. SetHeroArtifacts sha;
  3305. CGHeroInstance *h = gs->getHero(gs->getPlayer(player)->currentSelection);
  3306. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  3307. sm.hid = cs.hid = h->id;
  3308. //give all spells
  3309. cs.learn = 1;
  3310. for(int i=0;i<VLC->spellh->spells.size();i++)
  3311. {
  3312. if(!VLC->spellh->spells[i].creatureAbility)
  3313. cs.spells.insert(i);
  3314. }
  3315. //give mana
  3316. sm.val = 999;
  3317. if(!h->getArt(17)) //hero doesn't have spellbook
  3318. {
  3319. //give spellbook
  3320. sha.hid = h->id;
  3321. sha.artifacts = h->artifacts;
  3322. sha.artifWorn = h->artifWorn;
  3323. VLC->arth->equipArtifact(sha.artifWorn, 17, 0);
  3324. sendAndApply(&sha);
  3325. }
  3326. sendAndApply(&cs);
  3327. sendAndApply(&sm);
  3328. }
  3329. else if(message == "vcmiainur") //gives 5 archangels into each slot
  3330. {
  3331. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3332. if(!hero) return;
  3333. SetGarrisons sg;
  3334. CCreatureSet &newArmy = sg.garrs[hero->id];
  3335. newArmy = hero->getArmy();
  3336. for(int i=0; i<ARMY_SIZE; i++)
  3337. if(newArmy.slotEmpty(i))
  3338. newArmy.addToSlot(i, CStackInstance(13,5));
  3339. sendAndApply(&sg);
  3340. }
  3341. else if(message == "vcmiangband") //gives 10 black knight into each slot
  3342. {
  3343. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3344. if(!hero) return;
  3345. SetGarrisons sg;
  3346. CCreatureSet &newArmy = sg.garrs[hero->id];
  3347. newArmy = hero->getArmy();
  3348. for(int i=0; i<ARMY_SIZE; i++)
  3349. if(newArmy.slotEmpty(i))
  3350. newArmy.addToSlot(i, CStackInstance(66,10));
  3351. sendAndApply(&sg);
  3352. }
  3353. else if(message == "vcminoldor") //all war machines
  3354. {
  3355. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3356. if(!hero) return;
  3357. SetHeroArtifacts sha;
  3358. sha.hid = hero->id;
  3359. sha.artifacts = hero->artifacts;
  3360. sha.artifWorn = hero->artifWorn;
  3361. VLC->arth->equipArtifact(sha.artifWorn, 13, 4);
  3362. VLC->arth->equipArtifact(sha.artifWorn, 14, 5);
  3363. VLC->arth->equipArtifact(sha.artifWorn, 15, 6);
  3364. sendAndApply(&sha);
  3365. }
  3366. else if(message == "vcminahar") //1000000 movement points
  3367. {
  3368. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3369. if(!hero) return;
  3370. SetMovePoints smp;
  3371. smp.hid = hero->id;
  3372. smp.val = 1000000;
  3373. sendAndApply(&smp);
  3374. }
  3375. else if(message == "vcmiformenos") //give resources
  3376. {
  3377. SetResources sr;
  3378. sr.player = player;
  3379. sr.res = gs->getPlayer(player)->resources;
  3380. for(int i=0;i<7;i++)
  3381. sr.res[i] += 100;
  3382. sr.res[6] += 19900;
  3383. sendAndApply(&sr);
  3384. }
  3385. else if(message == "vcmieagles") //reveal FoW
  3386. {
  3387. FoWChange fc;
  3388. fc.mode = 1;
  3389. fc.player = player;
  3390. for(int i=0;i<gs->map->width;i++)
  3391. for(int j=0;j<gs->map->height;j++)
  3392. for(int k=0;k<gs->map->twoLevel+1;k++)
  3393. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  3394. fc.tiles.insert(int3(i,j,k));
  3395. sendAndApply(&fc);
  3396. }
  3397. else if(message == "vcmiglorfindel")
  3398. {
  3399. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3400. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  3401. }
  3402. else
  3403. cheated = false;
  3404. if(cheated)
  3405. {
  3406. sendAndApply(&SystemMessage(VLC->generaltexth->allTexts[260]));
  3407. }
  3408. }
  3409. static ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack)
  3410. {
  3411. switch(spell->id)
  3412. {
  3413. case 37: //cure
  3414. {
  3415. int healedHealth = caster->getPrimSkillLevel(2) * 5 + spell->powers[caster->getSpellSchoolLevel(spell)];
  3416. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft);
  3417. break;
  3418. }
  3419. case 38: //resurrection
  3420. {
  3421. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  3422. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  3423. break;
  3424. }
  3425. case 39: //animate dead
  3426. {
  3427. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  3428. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  3429. break;
  3430. }
  3431. }
  3432. //we shouldn't be here
  3433. tlog1 << "calculateHealedHP called for non-healing spell: " << spell->name << std::endl;
  3434. return 0;
  3435. }
  3436. static std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures)
  3437. {
  3438. std::vector<ui32> ret;
  3439. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  3440. {
  3441. if (NBonus::hasOfType(caster, Bonus::NEGATE_ALL_NATURAL_IMMUNITIES) ||
  3442. NBonus::hasOfType(hero2, Bonus::NEGATE_ALL_NATURAL_IMMUNITIES))
  3443. {
  3444. //don't use natural immunities when one of heroes has this bonus
  3445. BonusList bl = (*it)->getBonuses(Selector::type(Bonus::SPELL_IMMUNITY)),
  3446. b2 = (*it)->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  3447. bl.insert(bl.end(), b2.begin(), b2.end());
  3448. BOOST_FOREACH(Bonus bb, bl)
  3449. {
  3450. if( (bb.type == Bonus::SPELL_IMMUNITY && bb.subtype == sp->id || //100% sure spell immunity
  3451. bb.type == Bonus::LEVEL_SPELL_IMMUNITY && bb.val >= sp->level) //some creature abilities have level 0
  3452. && bb.source != Bonus::CREATURE_ABILITY)
  3453. {
  3454. ret.push_back((*it)->ID);
  3455. continue;
  3456. }
  3457. }
  3458. }
  3459. else
  3460. {
  3461. if ((*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  3462. || ( (*it)->hasBonusOfType(Bonus::LEVEL_SPELL_IMMUNITY) &&
  3463. (*it)->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY) >= sp->level) ) //some creature abilities have level 0
  3464. {
  3465. ret.push_back((*it)->ID);
  3466. continue;
  3467. }
  3468. }
  3469. //non-negative spells on friendly stacks should always succeed, unless immune
  3470. if(sp->positiveness >= 0 && (*it)->owner == caster->tempOwner)
  3471. continue;
  3472. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  3473. if(caster && (*it)->owner == caster->tempOwner)
  3474. bonusHero = caster;
  3475. else
  3476. bonusHero = hero2;
  3477. int prob = (*it)->valOfBonuses(Bonus::MAGIC_RESISTANCE); //probability of resistance in %
  3478. if(bonusHero)
  3479. {
  3480. //bonusHero's resistance support (secondary skils and artifacts)
  3481. prob += bonusHero->valOfBonuses(Bonus::MAGIC_RESISTANCE);
  3482. //resistance skill
  3483. prob += bonusHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 26) / 100.0f;
  3484. }
  3485. if(prob > 100) prob = 100;
  3486. if(rand()%100 < prob) //immunity from resistance
  3487. ret.push_back((*it)->ID);
  3488. }
  3489. if(sp->id == 60) //hypnotize
  3490. {
  3491. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  3492. {
  3493. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  3494. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  3495. >
  3496. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  3497. )
  3498. {
  3499. ret.push_back((*it)->ID);
  3500. }
  3501. }
  3502. }
  3503. return ret;
  3504. }
  3505. void CGameHandler::handleSpellCasting( int spellID, int spellLvl, int destination, ui8 casterSide, ui8 casterColor,
  3506. const CGHeroInstance * caster, const CGHeroInstance * secHero, int usedSpellPower )
  3507. {
  3508. CSpell *spell = &VLC->spellh->spells[spellID];
  3509. BattleSpellCast sc;
  3510. sc.side = casterSide;
  3511. sc.id = spellID;
  3512. sc.skill = spellLvl;
  3513. sc.tile = destination;
  3514. sc.dmgToDisplay = 0;
  3515. sc.castedByHero = (bool)caster;
  3516. //calculating affected creatures for all spells
  3517. std::set<CStack*> attackedCres = gs->curB->getAttackedCreatures(spell, spellLvl, casterColor, destination);
  3518. for(std::set<CStack*>::const_iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3519. {
  3520. sc.affectedCres.insert((*it)->ID);
  3521. }
  3522. //checking if creatures resist
  3523. sc.resisted = calculateResistedStacks(spell, caster, secHero, attackedCres);
  3524. //calculating dmg to display
  3525. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3526. {
  3527. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3528. continue;
  3529. sc.dmgToDisplay += gs->curB->calculateSpellDmg(spell, caster, *it, spellLvl, usedSpellPower);
  3530. }
  3531. sendAndApply(&sc);
  3532. //applying effects
  3533. switch(spellID)
  3534. {
  3535. case 15: //magic arrow
  3536. case 16: //ice bolt
  3537. case 17: //lightning bolt
  3538. case 18: //implosion
  3539. case 20: //frost ring
  3540. case 21: //fireball
  3541. case 22: //inferno
  3542. case 23: //meteor shower
  3543. case 24: //death ripple
  3544. case 25: //destroy undead
  3545. case 26: //armageddon
  3546. case 77: //Thunderbolt (thunderbirds)
  3547. {
  3548. StacksInjured si;
  3549. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3550. {
  3551. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3552. continue;
  3553. BattleStackAttacked bsa;
  3554. bsa.flags |= 2;
  3555. bsa.effect = spell->mainEffectAnim;
  3556. bsa.damageAmount = gs->curB->calculateSpellDmg(spell, caster, *it, spellLvl, usedSpellPower);
  3557. bsa.stackAttacked = (*it)->ID;
  3558. bsa.attackerID = -1;
  3559. prepareAttacked(bsa,*it);
  3560. si.stacks.push_back(bsa);
  3561. }
  3562. if(!si.stacks.empty())
  3563. sendAndApply(&si);
  3564. break;
  3565. }
  3566. case 27: //shield
  3567. case 28: //air shield
  3568. case 29: //fire shield
  3569. case 30: //protection from air
  3570. case 31: //protection from fire
  3571. case 32: //protection from water
  3572. case 33: //protection from earth
  3573. case 34: //anti-magic
  3574. case 41: //bless
  3575. case 42: //curse
  3576. case 43: //bloodlust
  3577. case 44: //precision
  3578. case 45: //weakness
  3579. case 46: //stone skin
  3580. case 47: //disrupting ray
  3581. case 48: //prayer
  3582. case 49: //mirth
  3583. case 50: //sorrow
  3584. case 51: //fortune
  3585. case 52: //misfortune
  3586. case 53: //haste
  3587. case 54: //slow
  3588. case 55: //slayer
  3589. case 56: //frenzy
  3590. case 58: //counterstrike
  3591. case 59: //berserk
  3592. case 60: //hypnotize
  3593. case 61: //forgetfulness
  3594. case 62: //blind
  3595. {
  3596. SetStackEffect sse;
  3597. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3598. {
  3599. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3600. continue;
  3601. sse.stacks.push_back((*it)->ID);
  3602. }
  3603. sse.effect.id = spellID;
  3604. sse.effect.level = spellLvl;
  3605. sse.effect.turnsRemain = BattleInfo::calculateSpellDuration(spell, caster, usedSpellPower);
  3606. if(!sse.stacks.empty())
  3607. sendAndApply(&sse);
  3608. break;
  3609. }
  3610. case 63: //teleport
  3611. {
  3612. BattleStackMoved bsm;
  3613. bsm.distance = -1;
  3614. bsm.stack = gs->curB->activeStack;
  3615. bsm.ending = true;
  3616. bsm.tile = destination;
  3617. bsm.teleporting = true;
  3618. sendAndApply(&bsm);
  3619. break;
  3620. }
  3621. case 37: //cure
  3622. case 38: //resurrection
  3623. case 39: //animate dead
  3624. {
  3625. StacksHealedOrResurrected shr;
  3626. shr.lifeDrain = false;
  3627. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3628. {
  3629. if(vstd::contains(sc.resisted, (*it)->ID) //this creature resisted the spell
  3630. || (spellID == 39 && !(*it)->hasBonusOfType(Bonus::UNDEAD)) //we try to cast animate dead on living stack
  3631. )
  3632. continue;
  3633. StacksHealedOrResurrected::HealInfo hi;
  3634. hi.stackID = (*it)->ID;
  3635. hi.healedHP = calculateHealedHP(caster, spell, *it);
  3636. hi.lowLevelResurrection = spellLvl <= 1;
  3637. shr.healedStacks.push_back(hi);
  3638. }
  3639. if(!shr.healedStacks.empty())
  3640. sendAndApply(&shr);
  3641. break;
  3642. }
  3643. case 64: //remove obstacle
  3644. {
  3645. ObstaclesRemoved obr;
  3646. for(int g=0; g<gs->curB->obstacles.size(); ++g)
  3647. {
  3648. std::vector<int> blockedHexes = VLC->heroh->obstacles[gs->curB->obstacles[g].ID].getBlocked(gs->curB->obstacles[g].pos);
  3649. if(vstd::contains(blockedHexes, destination)) //this obstacle covers given hex
  3650. {
  3651. obr.obstacles.insert(gs->curB->obstacles[g].uniqueID);
  3652. }
  3653. }
  3654. if(!obr.obstacles.empty())
  3655. sendAndApply(&obr);
  3656. break;
  3657. }
  3658. }
  3659. }
  3660. bool CGameHandler::makeCustomAction( BattleAction &ba )
  3661. {
  3662. switch(ba.actionType)
  3663. {
  3664. case 1: //hero casts spell
  3665. {
  3666. const CGHeroInstance *h = gs->curB->heroes[ba.side];
  3667. const CGHeroInstance *secondHero = gs->curB->heroes[!ba.side];
  3668. if(!h)
  3669. {
  3670. tlog2 << "Wrong caster!\n";
  3671. return false;
  3672. }
  3673. if(ba.additionalInfo >= VLC->spellh->spells.size())
  3674. {
  3675. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  3676. return false;
  3677. }
  3678. const CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  3679. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  3680. if( !(h->canCastThisSpell(s)) //hero cannot cast this spell at all
  3681. || (h->mana < gs->curB->getSpellCost(s, h)) //not enough mana
  3682. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  3683. || (gs->curB->castSpells[ba.side]) //spell has been cast
  3684. || (NBonus::hasOfType(secondHero, Bonus::SPELL_IMMUNITY, s->id)) //non - casting hero provides immunity for this spell
  3685. || (gs->battleMaxSpellLevel() < s->level) //non - casting hero stops caster from casting this spell
  3686. )
  3687. {
  3688. tlog2 << "Spell cannot be cast!\n";
  3689. return false;
  3690. }
  3691. sendAndApply(&StartAction(ba)); //start spell casting
  3692. handleSpellCasting(ba.additionalInfo, skill, ba.destinationTile, ba.side, h->tempOwner, h, secondHero, h->getPrimSkillLevel(2));
  3693. sendAndApply(&EndAction());
  3694. if( !gs->curB->getStack(gs->curB->activeStack, false)->alive() )
  3695. {
  3696. battleMadeAction.setn(true);
  3697. }
  3698. checkForBattleEnd(gs->curB->stacks);
  3699. if(battleResult.get())
  3700. {
  3701. endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  3702. }
  3703. return true;
  3704. }
  3705. }
  3706. return false;
  3707. }
  3708. void CGameHandler::handleTimeEvents()
  3709. {
  3710. gs->map->events.sort(evntCmp);
  3711. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  3712. {
  3713. CMapEvent *ev = gs->map->events.front();
  3714. for(int player = 0; player < PLAYER_LIMIT; player++)
  3715. {
  3716. PlayerState *pinfo = gs->getPlayer(player);
  3717. if( pinfo //player exists
  3718. && (ev->players & 1<<player) //event is enabled to this player
  3719. && ((ev->computerAffected && !pinfo->human)
  3720. || (ev->humanAffected && pinfo->human)
  3721. )
  3722. )
  3723. {
  3724. //give resources
  3725. SetResources sr;
  3726. sr.player = player;
  3727. sr.res = pinfo->resources;
  3728. //prepare dialog
  3729. InfoWindow iw;
  3730. iw.player = player;
  3731. iw.text << ev->message;
  3732. for (int i=0; i<ev->resources.size(); i++)
  3733. {
  3734. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  3735. {
  3736. // If removing too much resources, adjust the
  3737. // amount so the total doesn't become negative.
  3738. if (sr.res[i] + ev->resources[i] < 0)
  3739. ev->resources[i] = -sr.res[i];
  3740. if(ev->resources[i]) //if non-zero res change
  3741. {
  3742. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  3743. sr.res[i] += ev->resources[i];
  3744. }
  3745. }
  3746. }
  3747. if (iw.components.size())
  3748. {
  3749. sendAndApply(&sr); //update player resources if changed
  3750. }
  3751. sendAndApply(&iw); //show dialog
  3752. }
  3753. } //PLAYERS LOOP
  3754. if(ev->nextOccurence)
  3755. {
  3756. ev->firstOccurence += ev->nextOccurence;
  3757. gs->map->events.sort(evntCmp);
  3758. }
  3759. else
  3760. {
  3761. delete ev;
  3762. gs->map->events.pop_front();
  3763. }
  3764. }
  3765. }
  3766. bool CGameHandler::complain( const std::string &problem )
  3767. {
  3768. sendMessageToAll("Server encountered a problem: " + problem);
  3769. tlog1 << problem << std::endl;
  3770. return true;
  3771. }
  3772. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  3773. {
  3774. //TODO: write
  3775. return 0;
  3776. }
  3777. void CGameHandler::showGarrisonDialog( int upobj, int hid, bool removableUnits, const boost::function<void()> &cb )
  3778. {
  3779. ui8 player = getOwner(hid);
  3780. GarrisonDialog gd;
  3781. gd.hid = hid;
  3782. gd.objid = upobj;
  3783. {
  3784. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3785. gd.id = QID;
  3786. garrisonCallbacks[QID] = cb;
  3787. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  3788. states.addQuery(player,QID);
  3789. QID++;
  3790. gd.removableUnits = removableUnits;
  3791. sendAndApply(&gd);
  3792. }
  3793. }
  3794. void CGameHandler::showThievesGuildWindow(int requestingObjId)
  3795. {
  3796. OpenWindow ow;
  3797. ow.window = OpenWindow::THIEVES_GUILD;
  3798. ow.id1 = requestingObjId;
  3799. sendAndApply(&ow);
  3800. }
  3801. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  3802. {
  3803. if(id1 == id2)
  3804. return true;
  3805. {
  3806. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3807. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  3808. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  3809. return true;
  3810. }
  3811. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  3812. if(o1->ID == TOWNI_TYPE)
  3813. {
  3814. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  3815. if(t->visitingHero == o2 || t->garrisonHero == o2)
  3816. return true;
  3817. }
  3818. if(o2->ID == TOWNI_TYPE)
  3819. {
  3820. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  3821. if(t->visitingHero == o1 || t->garrisonHero == o1)
  3822. return true;
  3823. }
  3824. if(o1->ID == HEROI_TYPE && o2->ID == HEROI_TYPE
  3825. && distance(o1->pos, o2->pos) < 2) //hero stands on the same tile or on the neighbouring tiles
  3826. {
  3827. //TODO: it's workaround, we should check if first hero visited second and player hasn't closed exchange window
  3828. //(to block moving stacks for free [without visiting] beteen heroes)
  3829. return true;
  3830. }
  3831. return false;
  3832. }
  3833. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  3834. {
  3835. obj->onHeroVisit(h);
  3836. }
  3837. bool CGameHandler::buildBoat( ui32 objid )
  3838. {
  3839. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  3840. int boatType = 1;
  3841. if(obj->state())
  3842. {
  3843. complain("Cannot build boat in this shipyard!");
  3844. return false;
  3845. }
  3846. else if(obj->o->ID == TOWNI_TYPE
  3847. && !vstd::contains((static_cast<const CGTownInstance*>(obj))->builtBuildings,6))
  3848. {
  3849. complain("Cannot build boat in the town - no shipyard!");
  3850. return false;
  3851. }
  3852. //TODO use "real" cost via obj->getBoatCost
  3853. if(getResource(obj->o->tempOwner, 6) < 1000 || getResource(obj->o->tempOwner, 0) < 10)
  3854. {
  3855. complain("Not enough resources to build a boat!");
  3856. return false;
  3857. }
  3858. int3 tile = obj->bestLocation();
  3859. if(!gs->map->isInTheMap(tile))
  3860. {
  3861. complain("Cannot find appropriate tile for a boat!");
  3862. return false;
  3863. }
  3864. //take boat cost
  3865. SetResources sr;
  3866. sr.player = obj->o->tempOwner;
  3867. sr.res = gs->getPlayer(obj->o->tempOwner)->resources;
  3868. sr.res[0] -= 10;
  3869. sr.res[6] -= 1000;
  3870. sendAndApply(&sr);
  3871. //create boat
  3872. NewObject no;
  3873. no.ID = 8;
  3874. no.subID = obj->getBoatType();
  3875. no.pos = tile + int3(1,0,0);
  3876. sendAndApply(&no);
  3877. return true;
  3878. }
  3879. void CGameHandler::engageIntoBattle( ui8 player )
  3880. {
  3881. if(vstd::contains(states.players, player))
  3882. states.setFlag(player,&PlayerStatus::engagedIntoBattle,true);
  3883. //notify interfaces
  3884. PlayerBlocked pb;
  3885. pb.player = player;
  3886. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  3887. sendAndApply(&pb);
  3888. }
  3889. void CGameHandler::winLoseHandle(ui8 players )
  3890. {
  3891. for(size_t i = 0; i < PLAYER_LIMIT; i++)
  3892. {
  3893. if(players & 1<<i && gs->getPlayer(i))
  3894. {
  3895. checkLossVictory(i);
  3896. }
  3897. }
  3898. }
  3899. void CGameHandler::checkLossVictory( ui8 player )
  3900. {
  3901. const PlayerState *p = gs->getPlayer(player);
  3902. if(p->status) //player already won / lost
  3903. return;
  3904. int loss = gs->lossCheck(player);
  3905. int vic = gs->victoryCheck(player);
  3906. if(!loss && !vic)
  3907. return;
  3908. InfoWindow iw;
  3909. getLossVicMessage(player, vic ? vic : loss , vic, iw);
  3910. sendAndApply(&iw);
  3911. PlayerEndsGame peg;
  3912. peg.player = player;
  3913. peg.victory = vic;
  3914. sendAndApply(&peg);
  3915. if(vic > 0) //one player won -> all enemies lost //TODO: allies
  3916. {
  3917. iw.text.localStrings.front().second++; //message about losing because enemy won first is just after victory message
  3918. for (std::map<ui8,PlayerState>::const_iterator i = gs->players.begin(); i!=gs->players.end(); i++)
  3919. {
  3920. if(i->first < PLAYER_LIMIT && i->first != player)
  3921. {
  3922. iw.player = i->first;
  3923. sendAndApply(&iw);
  3924. peg.player = i->first;
  3925. peg.victory = false;
  3926. sendAndApply(&peg);
  3927. }
  3928. }
  3929. }
  3930. else //player lost -> all his objects become unflagged (neutral)
  3931. {
  3932. std::vector<CGHeroInstance*> hlp = p->heroes;
  3933. for (std::vector<CGHeroInstance*>::const_iterator i = hlp.begin(); i != hlp.end(); i++) //eliminate heroes
  3934. removeObject((*i)->id);
  3935. for (std::vector<CGObjectInstance*>::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  3936. {
  3937. if(*i && (*i)->tempOwner == player)
  3938. setOwner((**i).id,NEUTRAL_PLAYER);
  3939. }
  3940. //eliminating one player may cause victory of another:
  3941. winLoseHandle(ALL_PLAYERS & ~(1<<player));
  3942. }
  3943. if(vic)
  3944. end2 = true;
  3945. }
  3946. void CGameHandler::getLossVicMessage( ui8 player, ui8 standard, bool victory, InfoWindow &out ) const
  3947. {
  3948. const PlayerState *p = gs->getPlayer(player);
  3949. // if(!p->human)
  3950. // return; //AI doesn't need text info of loss
  3951. out.player = player;
  3952. if(victory)
  3953. {
  3954. if(standard < 0) //not std loss
  3955. {
  3956. switch(gs->map->victoryCondition.condition)
  3957. {
  3958. case artifact:
  3959. out.text.addTxt(MetaString::GENERAL_TXT, 280); //Congratulations! You have found the %s, and can claim victory!
  3960. out.text.addReplacement(MetaString::ART_NAMES,gs->map->victoryCondition.ID); //artifact name
  3961. break;
  3962. case gatherTroop:
  3963. out.text.addTxt(MetaString::GENERAL_TXT, 276); //Congratulations! You have over %d %s in your armies. Your enemies have no choice but to bow down before your power!
  3964. out.text.addReplacement(gs->map->victoryCondition.count);
  3965. out.text.addReplacement(MetaString::CRE_PL_NAMES, gs->map->victoryCondition.ID);
  3966. break;
  3967. case gatherResource:
  3968. out.text.addTxt(MetaString::GENERAL_TXT, 278); //Congratulations! You have collected over %d %s in your treasury. Victory is yours!
  3969. out.text.addReplacement(gs->map->victoryCondition.count);
  3970. out.text.addReplacement(MetaString::RES_NAMES, gs->map->victoryCondition.ID);
  3971. break;
  3972. case buildCity:
  3973. out.text.addTxt(MetaString::GENERAL_TXT, 282); //Congratulations! You have successfully upgraded your town, and can claim victory!
  3974. break;
  3975. case buildGrail:
  3976. out.text.addTxt(MetaString::GENERAL_TXT, 284); //Congratulations! You have constructed a permanent home for the Grail, and can claim victory!
  3977. break;
  3978. case beatHero:
  3979. {
  3980. out.text.addTxt(MetaString::GENERAL_TXT, 252); //Congratulations! You have completed your quest to defeat the enemy hero %s. Victory is yours!
  3981. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->victoryCondition.obj);
  3982. assert(h);
  3983. out.text.addReplacement(h->name);
  3984. }
  3985. break;
  3986. case captureCity:
  3987. {
  3988. out.text.addTxt(MetaString::GENERAL_TXT, 249); //Congratulations! You captured %s, and are victorious!
  3989. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->victoryCondition.obj);
  3990. assert(t);
  3991. out.text.addReplacement(t->name);
  3992. }
  3993. break;
  3994. case beatMonster:
  3995. out.text.addTxt(MetaString::GENERAL_TXT, 286); //Congratulations! You have completed your quest to kill the fearsome beast, and can claim victory!
  3996. break;
  3997. case takeDwellings:
  3998. out.text.addTxt(MetaString::GENERAL_TXT, 288); //Congratulations! Your flag flies on the dwelling of every creature. Victory is yours!
  3999. break;
  4000. case takeMines:
  4001. out.text.addTxt(MetaString::GENERAL_TXT, 290); //Congratulations! Your flag flies on every mine. Victory is yours!
  4002. break;
  4003. case transportItem:
  4004. out.text.addTxt(MetaString::GENERAL_TXT, 292); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  4005. break;
  4006. }
  4007. }
  4008. else
  4009. {
  4010. out.text.addTxt(MetaString::GENERAL_TXT, 659); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  4011. }
  4012. }
  4013. else
  4014. {
  4015. if(standard < 0) //not std loss
  4016. {
  4017. switch(gs->map->lossCondition.typeOfLossCon)
  4018. {
  4019. case lossCastle:
  4020. {
  4021. out.text.addTxt(MetaString::GENERAL_TXT, 251); //The town of %s has fallen - all is lost!
  4022. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->lossCondition.obj);
  4023. assert(t);
  4024. out.text.addReplacement(t->name);
  4025. }
  4026. break;
  4027. case lossHero:
  4028. {
  4029. out.text.addTxt(MetaString::GENERAL_TXT, 253); //The hero, %s, has suffered defeat - your quest is over!
  4030. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->lossCondition.obj);
  4031. assert(h);
  4032. out.text.addReplacement(h->name);
  4033. }
  4034. break;
  4035. case timeExpires:
  4036. out.text.addTxt(MetaString::GENERAL_TXT, 254); //Alas, time has run out on your quest. All is lost.
  4037. break;
  4038. }
  4039. }
  4040. else if(standard == 2)
  4041. {
  4042. out.text.addTxt(MetaString::GENERAL_TXT, 7);//%s, your heroes abandon you, and you are banished from this land.
  4043. out.text.addReplacement(MetaString::COLOR, player);
  4044. out.components.push_back(Component(Component::FLAG,player,0,0));
  4045. }
  4046. else //lost all towns and heroes
  4047. {
  4048. out.text.addTxt(MetaString::GENERAL_TXT, 660); //All your forces have been defeated, and you are banished from this land!
  4049. }
  4050. }
  4051. }
  4052. bool CGameHandler::dig( const CGHeroInstance *h )
  4053. {
  4054. for (std::vector<CGObjectInstance*>::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  4055. {
  4056. if(*i && (*i)->ID == 124 && (*i)->pos == h->getPosition())
  4057. {
  4058. complain("Cannot dig - there is already a hole under the hero!");
  4059. return false;
  4060. }
  4061. }
  4062. NewObject no;
  4063. no.ID = 124;
  4064. no.pos = h->getPosition();
  4065. no.subID = getTile(no.pos)->tertype;
  4066. if(no.subID >= 8) //no digging on water / rock
  4067. {
  4068. complain("Cannot dig - wrong terrain type!");
  4069. return false;
  4070. }
  4071. sendAndApply(&no);
  4072. SetMovePoints smp;
  4073. smp.hid = h->id;
  4074. smp.val = 0;
  4075. sendAndApply(&smp);
  4076. InfoWindow iw;
  4077. iw.player = h->tempOwner;
  4078. if(gs->map->grailPos == h->getPosition())
  4079. {
  4080. iw.text.addTxt(MetaString::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  4081. iw.text.addTxt(MetaString::ART_NAMES, 2);
  4082. iw.soundID = soundBase::ULTIMATEARTIFACT;
  4083. giveHeroArtifact(2, h->id, -1); //give grail
  4084. sendAndApply(&iw);
  4085. iw.text.clear();
  4086. iw.text.addTxt(MetaString::ART_DESCR, 2);
  4087. sendAndApply(&iw);
  4088. }
  4089. else
  4090. {
  4091. iw.text.addTxt(MetaString::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  4092. iw.soundID = soundBase::Dig;
  4093. sendAndApply(&iw);
  4094. }
  4095. return true;
  4096. }
  4097. void CGameHandler::handleAfterAttackCasting( const BattleAttack & bat )
  4098. {
  4099. const CStack * attacker = gs->curB->getStack(bat.stackAttacking);
  4100. if( attacker->hasBonusOfType(Bonus::SPELL_AFTER_ATTACK) )
  4101. {
  4102. BOOST_FOREACH(const Bonus & sf, attacker->getBonuses(Selector::type(Bonus::SPELL_AFTER_ATTACK)))
  4103. {
  4104. if (sf.type == Bonus::SPELL_AFTER_ATTACK)
  4105. {
  4106. const CStack * oneOfAttacked = NULL;
  4107. for(int g=0; g<bat.bsa.size(); ++g)
  4108. {
  4109. if (bat.bsa[g].newAmount > 0)
  4110. {
  4111. oneOfAttacked = gs->curB->getStack(bat.bsa[g].stackAttacked);
  4112. break;
  4113. }
  4114. }
  4115. if(oneOfAttacked == NULL) //all attacked creatures have been killed
  4116. return;
  4117. int spellID = sf.subtype;
  4118. int spellLevel = sf.val;
  4119. int chance = sf.additionalInfo % 1000;
  4120. int meleeRanged = sf.additionalInfo / 1000;
  4121. int destination = oneOfAttacked->position;
  4122. //check if spell should be casted (probability handling)
  4123. if( rand()%100 >= chance )
  4124. continue;
  4125. //casting
  4126. handleSpellCasting(spellID, spellLevel, destination, !attacker->attackerOwned, attacker->owner, NULL, NULL, attacker->count);
  4127. }
  4128. }
  4129. }
  4130. }
  4131. bool CGameHandler::castSpell(const CGHeroInstance *h, int spellID, const int3 &pos)
  4132. {
  4133. const CSpell *s = &VLC->spellh->spells[spellID];
  4134. int cost = h->getSpellCost(s);
  4135. int schoolLevel = h->getSpellSchoolLevel(s);
  4136. if(!h->canCastThisSpell(s))
  4137. COMPLAIN_RET("Hero cannot cast this spell!");
  4138. if(h->mana < cost)
  4139. COMPLAIN_RET("Hero doesn't have enough spell points to cast this spell!");
  4140. if(s->combatSpell)
  4141. COMPLAIN_RET("This function can be used only for adventure map spells!");
  4142. AdvmapSpellCast asc;
  4143. asc.caster = h;
  4144. asc.spellID = spellID;
  4145. sendAndApply(&asc);
  4146. using namespace Spells;
  4147. switch(spellID)
  4148. {
  4149. case SUMMON_BOAT: //Summon Boat
  4150. {
  4151. //check if spell works at all
  4152. if(rand() % 100 >= s->powers[schoolLevel]) //power is % chance of success
  4153. {
  4154. InfoWindow iw;
  4155. iw.player = h->tempOwner;
  4156. iw.text.addTxt(MetaString::GENERAL_TXT, 336); //%s tried to summon a boat, but failed.
  4157. iw.text.addReplacement(h->name);
  4158. sendAndApply(&iw);
  4159. return true; //TODO? or should it be false? request was correct and realized, but spell failed...
  4160. }
  4161. //try to find unoccupied boat to summon
  4162. const CGBoat *nearest = NULL;
  4163. double dist = 0;
  4164. int3 summonPos = h->bestLocation();
  4165. if(summonPos.x < 0)
  4166. COMPLAIN_RET("There is no water tile available!");
  4167. BOOST_FOREACH(const CGObjectInstance *obj, gs->map->objects)
  4168. {
  4169. if(obj && obj->ID == 8)
  4170. {
  4171. const CGBoat *b = static_cast<const CGBoat*>(obj);
  4172. if(b->hero) continue; //we're looking for unoccupied boat
  4173. double nDist = distance(b->pos, h->getPosition());
  4174. if(!nearest || nDist < dist) //it's first boat or closer than previous
  4175. {
  4176. nearest = b;
  4177. dist = nDist;
  4178. }
  4179. }
  4180. }
  4181. if(nearest) //we found boat to summon
  4182. {
  4183. ChangeObjPos cop;
  4184. cop.objid = nearest->id;
  4185. cop.nPos = summonPos + int3(1,0,0);;
  4186. cop.flags = 1;
  4187. sendAndApply(&cop);
  4188. }
  4189. else if(schoolLevel < 2) //none or basic level -> cannot create boat :(
  4190. {
  4191. InfoWindow iw;
  4192. iw.player = h->tempOwner;
  4193. iw.text.addTxt(MetaString::GENERAL_TXT, 335); //There are no boats to summon.
  4194. sendAndApply(&iw);
  4195. }
  4196. else //create boat
  4197. {
  4198. NewObject no;
  4199. no.ID = 8;
  4200. no.subID = h->getBoatType();
  4201. no.pos = summonPos + int3(1,0,0);;
  4202. sendAndApply(&no);
  4203. }
  4204. break;
  4205. }
  4206. case SCUTTLE_BOAT: //Scuttle Boat
  4207. {
  4208. //check if spell works at all
  4209. if(rand() % 100 >= s->powers[schoolLevel]) //power is % chance of success
  4210. {
  4211. InfoWindow iw;
  4212. iw.player = h->tempOwner;
  4213. iw.text.addTxt(MetaString::GENERAL_TXT, 337); //%s tried to scuttle the boat, but failed
  4214. iw.text.addReplacement(h->name);
  4215. sendAndApply(&iw);
  4216. return true; //TODO? or should it be false? request was correct and realized, but spell failed...
  4217. }
  4218. if(!gs->map->isInTheMap(pos))
  4219. COMPLAIN_RET("Invalid dst tile for scuttle!");
  4220. //TODO: test range, visibility
  4221. const TerrainTile *t = &gs->map->getTile(pos);
  4222. if(!t->visitableObjects.size() || t->visitableObjects.back()->ID != 8)
  4223. COMPLAIN_RET("There is no boat to scuttle!");
  4224. RemoveObject ro;
  4225. ro.id = t->visitableObjects.back()->id;
  4226. sendAndApply(&ro);
  4227. break;
  4228. }
  4229. case DIMENSION_DOOR: //Dimension Door
  4230. {
  4231. const TerrainTile *dest = getTile(pos);
  4232. const TerrainTile *curr = getTile(h->getSightCenter());
  4233. if(!dest)
  4234. COMPLAIN_RET("Destination tile doesn't exist!");
  4235. if(!h->movement)
  4236. COMPLAIN_RET("Hero needs movement points to cast Dimension Door!");
  4237. if(h->getBonusesCount(Bonus::CASTED_SPELL, Spells::DIMENSION_DOOR) >= s->powers[schoolLevel]) //limit casts per turn
  4238. {
  4239. InfoWindow iw;
  4240. iw.player = h->tempOwner;
  4241. iw.text.addTxt(MetaString::GENERAL_TXT, 338); //%s is not skilled enough to cast this spell again today.
  4242. iw.text.addReplacement(h->name);
  4243. sendAndApply(&iw);
  4244. break;
  4245. }
  4246. GiveBonus gb;
  4247. gb.id = h->id;
  4248. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::NONE, Bonus::CASTED_SPELL, 0, Spells::DIMENSION_DOOR);
  4249. sendAndApply(&gb);
  4250. if(!dest->isClear(curr)) //wrong dest tile
  4251. {
  4252. InfoWindow iw;
  4253. iw.player = h->tempOwner;
  4254. iw.text.addTxt(MetaString::GENERAL_TXT, 70); //Dimension Door failed!
  4255. sendAndApply(&iw);
  4256. break;
  4257. }
  4258. //we need obtain guard pos before moving hero, otherwise we get nothing, because tile will be "unguarded" by hero
  4259. int3 guardPos = gs->guardingCreaturePosition(pos);
  4260. TryMoveHero tmh;
  4261. tmh.id = h->id;
  4262. tmh.movePoints = std::max<int>(0, h->movement - 300);
  4263. tmh.result = TryMoveHero::TELEPORTATION;
  4264. tmh.start = h->pos;
  4265. tmh.end = pos + h->getVisitableOffset();
  4266. getTilesInRange(tmh.fowRevealed, pos, h->getSightRadious(), h->tempOwner,1);
  4267. sendAndApply(&tmh);
  4268. tryAttackingGuard(guardPos, h);
  4269. }
  4270. break;
  4271. case FLY: //Fly
  4272. {
  4273. int subtype = schoolLevel >= 2 ? 1 : 2; //adv or expert
  4274. GiveBonus gb;
  4275. gb.id = h->id;
  4276. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::FLYING_MOVEMENT, Bonus::CASTED_SPELL, 0, Spells::FLY, subtype);
  4277. sendAndApply(&gb);
  4278. }
  4279. break;
  4280. case WATER_WALK: //Water Walk
  4281. {
  4282. int subtype = schoolLevel >= 2 ? 1 : 2; //adv or expert
  4283. GiveBonus gb;
  4284. gb.id = h->id;
  4285. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::WATER_WALKING, Bonus::CASTED_SPELL, 0, Spells::FLY, subtype);
  4286. sendAndApply(&gb);
  4287. }
  4288. break;
  4289. case VISIONS: //Visions
  4290. case VIEW_EARTH: //View Earth
  4291. case DISGUISE: //Disguise
  4292. case VIEW_AIR: //View Air
  4293. case TOWN_PORTAL: //Town Portal
  4294. default:
  4295. COMPLAIN_RET("This spell is not implemented yet!");
  4296. }
  4297. SetMana sm;
  4298. sm.hid = h->id;
  4299. sm.val = h->mana - cost;
  4300. sendAndApply(&sm);
  4301. return true;
  4302. }
  4303. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  4304. {
  4305. //to prevent self-visiting heroes on space press
  4306. if(t.visitableObjects.back() != h)
  4307. objectVisited(t.visitableObjects.back(), h);
  4308. else if(t.visitableObjects.size() > 1)
  4309. objectVisited(*(t.visitableObjects.end()-2),h);
  4310. }
  4311. bool CGameHandler::tryAttackingGuard(const int3 &guardPos, const CGHeroInstance * h)
  4312. {
  4313. if(!gs->map->isInTheMap(guardPos))
  4314. return false;
  4315. const TerrainTile &guardTile = gs->map->terrain[guardPos.x][guardPos.y][guardPos.z];
  4316. objectVisited(guardTile.visitableObjects.back(), h);
  4317. visitObjectAfterVictory = true;
  4318. return true;
  4319. }
  4320. bool CGameHandler::sacrificeCreatures(const IMarket *market, const CGHeroInstance *hero, TSlot slot, ui32 count)
  4321. {
  4322. int oldCount = hero->getAmount(slot);
  4323. int newCount = oldCount - count;
  4324. if(oldCount < count)
  4325. COMPLAIN_RET("Not enough creatures to sacrifice!")
  4326. else if(oldCount == count && hero->Slots().size() == 1 && hero->needsLastStack())
  4327. COMPLAIN_RET("Cannot sacrifice last creature!");
  4328. int crid = hero->getStack(slot).type->idNumber;
  4329. SetGarrisons sg;
  4330. sg.garrs[hero->id] = hero->getArmy();
  4331. if(newCount)
  4332. sg.garrs[hero->id].setStackCount(slot, newCount);
  4333. else
  4334. sg.garrs[hero->id].eraseStack(slot);
  4335. sendAndApply(&sg);
  4336. int dump, exp;
  4337. market->getOffer(crid, 0, dump, exp, CREATURE_EXP);
  4338. exp *= count;
  4339. changePrimSkill (hero->id, 4, exp);
  4340. return true;
  4341. }