CGameHandler.cpp 151 KB

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