CGameHandler.cpp 152 KB

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