CGameHandler.cpp 154 KB

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