CGameHandler.cpp 156 KB

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