CGameHandler.cpp 152 KB

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