CGameHandler.cpp 151 KB

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