CGameHandler.cpp 152 KB

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