CGameHandler.cpp 143 KB

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