CGameHandler.cpp 151 KB

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