CGameHandler.cpp 152 KB

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