CGameHandler.cpp 143 KB

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