CGameHandler.cpp 129 KB

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