CGameHandler.cpp 146 KB

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