CObjectHandler.cpp 200 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446
  1. /*
  2. * CObjectHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CObjectHandler.h"
  12. #include "CDefObjInfoHandler.h"
  13. #include "CGeneralTextHandler.h"
  14. #include "CDefObjInfoHandler.h"
  15. #include "CHeroHandler.h"
  16. #include "CSpellHandler.h"
  17. #include "CModHandler.h"
  18. #include "../client/CSoundBase.h"
  19. #include <boost/random/linear_congruential.hpp>
  20. #include "CTownHandler.h"
  21. #include "CCreatureHandler.h"
  22. #include "VCMI_Lib.h"
  23. #include "IGameCallback.h"
  24. #include "CGameState.h"
  25. #include "NetPacks.h"
  26. #include "StartInfo.h"
  27. #include "mapping/CMap.h"
  28. #include <SDL_stdinc.h>
  29. #include "CBuildingHandler.h"
  30. #include "JsonNode.h"
  31. #include "filesystem/CResourceLoader.h"
  32. using namespace boost::assign;
  33. // It looks that we can't rely on shadowCoverage correctness (Mantis #866). This may result
  34. // in notable performance decrease (SDL blit with custom alpha blit) not notable on my system (Ivan)
  35. #define USE_COVERAGE_MAP 0
  36. std::map<Obj, std::map<int, std::vector<ObjectInstanceID> > > CGTeleport::objs;
  37. std::vector<std::pair<ObjectInstanceID, ObjectInstanceID> > CGTeleport::gates;
  38. IGameCallback * IObjectInterface::cb = NULL;
  39. extern boost::rand48 ran;
  40. std::map <PlayerColor, std::set <ui8> > CGKeys::playerKeyMap;
  41. std::map <si32, std::vector<ObjectInstanceID> > CGMagi::eyelist;
  42. ui8 CGObelisk::obeliskCount; //how many obelisks are on map
  43. std::map<TeamID, ui8> CGObelisk::visited; //map: team_id => how many obelisks has been visited
  44. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  45. std::vector<int> CGTownInstance::universitySkills;
  46. ///helpers
  47. static void openWindow(const OpenWindow::EWindow type, const int id1, const int id2 = -1)
  48. {
  49. OpenWindow ow;
  50. ow.window = type;
  51. ow.id1 = id1;
  52. ow.id2 = id2;
  53. IObjectInterface::cb->sendAndApply(&ow);
  54. }
  55. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID)
  56. {
  57. InfoWindow iw;
  58. iw.soundID = soundID;
  59. iw.player = playerID;
  60. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  61. IObjectInterface::cb->sendAndApply(&iw);
  62. }
  63. /*static void showInfoDialog(const ObjectInstanceID heroID, const ui32 txtID, const ui16 soundID)
  64. {
  65. const PlayerColor playerID = IObjectInterface::cb->getOwner(heroID);
  66. showInfoDialog(playerID,txtID,soundID);
  67. }*/
  68. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID)
  69. {
  70. const PlayerColor playerID = h->getOwner();
  71. showInfoDialog(playerID,txtID,soundID);
  72. }
  73. static std::string & visitedTxt(const bool visited)
  74. {
  75. int id = visited ? 352 : 353;
  76. return VLC->generaltexth->allTexts[id];
  77. }
  78. ///IObjectInterface
  79. void IObjectInterface::onHeroVisit(const CGHeroInstance * h) const
  80. {}
  81. void IObjectInterface::onHeroLeave(const CGHeroInstance * h) const
  82. {}
  83. void IObjectInterface::newTurn () const
  84. {}
  85. IObjectInterface::~IObjectInterface()
  86. {}
  87. IObjectInterface::IObjectInterface()
  88. {}
  89. void IObjectInterface::initObj()
  90. {}
  91. void IObjectInterface::setProperty( ui8 what, ui32 val )
  92. {}
  93. bool IObjectInterface::wasVisited (PlayerColor player) const
  94. {
  95. return false;
  96. }
  97. bool IObjectInterface::wasVisited (const CGHeroInstance * h) const
  98. {
  99. return false;
  100. }
  101. void IObjectInterface::postInit()
  102. {}
  103. void IObjectInterface::preInit()
  104. {}
  105. void IObjectInterface::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  106. {
  107. }
  108. void IObjectInterface::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  109. {
  110. }
  111. void IObjectInterface::garrisonDialogClosed(const CGHeroInstance *hero) const
  112. {
  113. }
  114. void CPlayersVisited::setPropertyDer( ui8 what, ui32 val )
  115. {
  116. if(what == 10)
  117. players.insert(PlayerColor(val));
  118. }
  119. bool CPlayersVisited::wasVisited( PlayerColor player ) const
  120. {
  121. return vstd::contains(players,player);
  122. }
  123. bool CPlayersVisited::wasVisited( TeamID team ) const
  124. {
  125. BOOST_FOREACH(auto i, players)
  126. {
  127. if(cb->getPlayer(i)->team == team)
  128. return true;
  129. }
  130. return false;
  131. }
  132. // Bank helper. Find the creature ID and their number, and store the
  133. // result in storage (either guards or reward creatures).
  134. static void readCreatures(const JsonNode &creature, std::vector< std::pair <CreatureID, ui32> > &storage)
  135. {
  136. std::pair<CreatureID, si32> creInfo = std::make_pair(CreatureID::NONE, 0);
  137. creInfo.second = creature["number"].Float();
  138. creInfo.first = CreatureID((si32)creature["id"].Float());
  139. storage.push_back(creInfo);
  140. }
  141. // Bank helper. Process a bank level.
  142. static void readBankLevel(const JsonNode &level, BankConfig &bc)
  143. {
  144. int idx;
  145. bc.chance = level["chance"].Float();
  146. BOOST_FOREACH(const JsonNode &creature, level["guards"].Vector())
  147. {
  148. readCreatures(creature, bc.guards);
  149. }
  150. bc.upgradeChance = level["upgrade_chance"].Float();
  151. bc.combatValue = level["combat_value"].Float();
  152. bc.resources.resize(GameConstants::RESOURCE_QUANTITY);
  153. idx = 0;
  154. BOOST_FOREACH(const JsonNode &resource, level["reward_resources"].Vector())
  155. {
  156. bc.resources[idx] = resource.Float();
  157. idx ++;
  158. }
  159. BOOST_FOREACH(const JsonNode &creature, level["reward_creatures"].Vector())
  160. {
  161. readCreatures(creature, bc.creatures);
  162. }
  163. bc.artifacts.resize(4);
  164. idx = 0;
  165. BOOST_FOREACH(const JsonNode &artifact, level["reward_artifacts"].Vector())
  166. {
  167. bc.artifacts[idx] = artifact.Float();
  168. idx ++;
  169. }
  170. bc.value = level["value"].Float();
  171. bc.rewardDifficulty = level["profitability"].Float();
  172. bc.easiest = level["easiest"].Float();
  173. }
  174. CObjectHandler::CObjectHandler()
  175. {
  176. logGlobal->traceStream() << "\t\tReading cregens ";
  177. const JsonNode config(ResourceID("config/dwellings.json"));
  178. BOOST_FOREACH(const JsonNode &dwelling, config["dwellings"].Vector())
  179. {
  180. cregens[dwelling["dwelling"].Float()] = CreatureID((si32)dwelling["creature"].Float());
  181. }
  182. logGlobal->traceStream() << "\t\tDone loading cregens!";
  183. logGlobal->traceStream() << "\t\tReading resources prices ";
  184. const JsonNode config2(ResourceID("config/resources.json"));
  185. BOOST_FOREACH(const JsonNode &price, config2["resources_prices"].Vector())
  186. {
  187. resVals.push_back(price.Float());
  188. }
  189. logGlobal->traceStream() << "\t\tDone loading resource prices!";
  190. logGlobal->traceStream() << "\t\tReading banks configs";
  191. const JsonNode config3(ResourceID("config/bankconfig.json"));
  192. int bank_num = 0;
  193. BOOST_FOREACH(const JsonNode &bank, config3["banks"].Vector())
  194. {
  195. creBanksNames[bank_num] = bank["name"].String();
  196. int level_num = 0;
  197. BOOST_FOREACH(const JsonNode &level, bank["levels"].Vector())
  198. {
  199. banksInfo[bank_num].push_back(new BankConfig);
  200. BankConfig &bc = *banksInfo[bank_num].back();
  201. bc.level = level_num;
  202. readBankLevel(level, bc);
  203. level_num ++;
  204. }
  205. bank_num ++;
  206. }
  207. logGlobal->traceStream() << "\t\tDone loading banks configs";
  208. }
  209. CObjectHandler::~CObjectHandler()
  210. {
  211. BOOST_FOREACH(auto & mapEntry, banksInfo)
  212. {
  213. BOOST_FOREACH(auto & vecEntry, mapEntry.second)
  214. {
  215. vecEntry.dellNull();
  216. }
  217. }
  218. }
  219. int CObjectHandler::bankObjToIndex (const CGObjectInstance * obj)
  220. {
  221. switch (obj->ID) //find appriopriate key
  222. {
  223. case Obj::CREATURE_BANK:
  224. return obj->subID;
  225. case Obj::DERELICT_SHIP:
  226. return 8;
  227. case Obj::DRAGON_UTOPIA:
  228. return 10;
  229. case Obj::CRYPT:
  230. return 9;
  231. case Obj::SHIPWRECK:
  232. return 7;
  233. default:
  234. logGlobal->warnStream() << "Unrecognized Bank indetifier!";
  235. return 0;
  236. }
  237. }
  238. PlayerColor CGObjectInstance::getOwner() const
  239. {
  240. //if (state)
  241. // return state->owner;
  242. //else
  243. return tempOwner; //won't have owner
  244. }
  245. CGObjectInstance::CGObjectInstance()
  246. {
  247. pos = int3(-1,-1,-1);
  248. //state = new CLuaObjectScript();
  249. ID = Obj::NO_OBJ;
  250. subID = -1;
  251. defInfo = NULL;
  252. tempOwner = PlayerColor::UNFLAGGABLE;
  253. blockVisit = false;
  254. }
  255. CGObjectInstance::~CGObjectInstance()
  256. {
  257. //if (state)
  258. // delete state;
  259. //state=NULL;
  260. }
  261. const std::string & CGObjectInstance::getHoverText() const
  262. {
  263. return hoverName;
  264. }
  265. void CGObjectInstance::setOwner(PlayerColor ow)
  266. {
  267. //if (state)
  268. // state->owner = ow;
  269. //else
  270. tempOwner = ow;
  271. }
  272. int CGObjectInstance::getWidth() const//returns width of object graphic in tiles
  273. {
  274. return defInfo->width;
  275. }
  276. int CGObjectInstance::getHeight() const //returns height of object graphic in tiles
  277. {
  278. return defInfo->height;
  279. }
  280. bool CGObjectInstance::visitableAt(int x, int y) const //returns true if object is visitable at location (x, y) form left top tile of image (x, y in tiles)
  281. {
  282. if(defInfo==NULL)
  283. {
  284. logGlobal->warnStream() << "Warning: VisitableAt for obj "<< id.getNum() <<": NULL defInfo!";
  285. return false;
  286. }
  287. if((defInfo->visitMap[y] >> (7-x) ) & 1)
  288. {
  289. return true;
  290. }
  291. return false;
  292. }
  293. bool CGObjectInstance::blockingAt(int x, int y) const
  294. {
  295. if(x<0 || y<0 || x>=getWidth() || y>=getHeight() || defInfo==NULL)
  296. return false;
  297. if((defInfo->blockMap[y+6-getHeight()] >> (7-(8-getWidth()+x) )) & 1)
  298. return false;
  299. return true;
  300. }
  301. bool CGObjectInstance::coveringAt(int x, int y) const
  302. {
  303. //input coordinates are always negative
  304. x = -x;
  305. y = -y;
  306. #if USE_COVERAGE_MAP
  307. //NOTE: this code may be broken
  308. if((defInfo->coverageMap[y] >> (7-(x) )) & 1
  309. || (defInfo->shadowCoverage[y] >> (7-(x) )) & 1)
  310. return true;
  311. return false;
  312. #else
  313. return x >= 0 && y >= 0 && x < getWidth() && y < getHeight();
  314. #endif
  315. }
  316. bool CGObjectInstance::hasShadowAt( int x, int y ) const
  317. {
  318. #if USE_COVERAGE_MAP
  319. //NOTE: this code may be broken
  320. if( (defInfo->shadowCoverage[y] >> (7-(x) )) & 1 )
  321. return true;
  322. return false;
  323. #else
  324. return coveringAt(x,y);// ignore unreliable shadowCoverage map
  325. #endif
  326. }
  327. std::set<int3> CGObjectInstance::getBlockedPos() const
  328. {
  329. std::set<int3> ret;
  330. for(int w=0; w<getWidth(); ++w)
  331. {
  332. for(int h=0; h<getHeight(); ++h)
  333. {
  334. if(blockingAt(w, h))
  335. ret.insert(int3(pos.x - getWidth() + w + 1, pos.y - getHeight() + h + 1, pos.z));
  336. }
  337. }
  338. return ret;
  339. }
  340. bool CGObjectInstance::operator<(const CGObjectInstance & cmp) const //screen printing priority comparing
  341. {
  342. if(defInfo->printPriority==1 && cmp.defInfo->printPriority==0)
  343. return true;
  344. if(cmp.defInfo->printPriority==1 && defInfo->printPriority==0)
  345. return false;
  346. if(this->pos.y<cmp.pos.y)
  347. return true;
  348. if(this->pos.y>cmp.pos.y)
  349. return false;
  350. if(cmp.ID==Obj::HERO && ID!=Obj::HERO)
  351. return true;
  352. if(cmp.ID!=Obj::HERO && ID==Obj::HERO)
  353. return false;
  354. if(!defInfo->isVisitable() && cmp.defInfo->isVisitable())
  355. return true;
  356. if(!cmp.defInfo->isVisitable() && defInfo->isVisitable())
  357. return false;
  358. if(this->pos.x<cmp.pos.x)
  359. return true;
  360. return false;
  361. }
  362. void CGObjectInstance::initObj()
  363. {
  364. switch(ID)
  365. {
  366. case Obj::TAVERN:
  367. blockVisit = true;
  368. break;
  369. }
  370. }
  371. void CGObjectInstance::setProperty( ui8 what, ui32 val )
  372. {
  373. switch(what)
  374. {
  375. case ObjProperty::OWNER:
  376. tempOwner = PlayerColor(val);
  377. break;
  378. case ObjProperty::BLOCKVIS:
  379. blockVisit = val;
  380. break;
  381. case ObjProperty::ID:
  382. ID = Obj(val);
  383. break;
  384. case ObjProperty::SUBID:
  385. subID = val;
  386. break;
  387. }
  388. setPropertyDer(what, val);
  389. }
  390. void CGObjectInstance::setPropertyDer( ui8 what, ui32 val )
  391. {}
  392. int3 CGObjectInstance::getSightCenter() const
  393. {
  394. //return vistiable tile if possible
  395. for(int i=0; i < 8; i++)
  396. for(int j=0; j < 6; j++)
  397. if(visitableAt(i,j))
  398. return(pos + int3(i-7, j-5, 0));
  399. return pos;
  400. }
  401. int CGObjectInstance::getSightRadious() const
  402. {
  403. return 3;
  404. }
  405. void CGObjectInstance::getSightTiles(boost::unordered_set<int3, ShashInt3> &tiles) const //returns reference to the set
  406. {
  407. cb->getTilesInRange(tiles, getSightCenter(), getSightRadious(), tempOwner, 1);
  408. }
  409. void CGObjectInstance::hideTiles(PlayerColor ourplayer, int radius) const
  410. {
  411. for (auto i = cb->gameState()->teams.begin(); i != cb->gameState()->teams.end(); i++)
  412. {
  413. if ( !vstd::contains(i->second.players, ourplayer ))//another team
  414. {
  415. for (auto j = i->second.players.begin(); j != i->second.players.end(); j++)
  416. if ( cb->getPlayer(*j)->status == EPlayerStatus::INGAME )//seek for living player (if any)
  417. {
  418. FoWChange fw;
  419. fw.mode = 0;
  420. fw.player = *j;
  421. cb->getTilesInRange (fw.tiles, pos, radius, (*j), -1);
  422. cb->sendAndApply (&fw);
  423. break;
  424. }
  425. }
  426. }
  427. }
  428. int3 CGObjectInstance::getVisitableOffset() const
  429. {
  430. for(int y = 0; y < 6; y++)
  431. for (int x = 0; x < 8; x++)
  432. if((defInfo->visitMap[5-y] >> x) & 1)
  433. return int3(x,y,0);
  434. logGlobal->warnStream() << "Warning: getVisitableOffset called on non-visitable obj!";
  435. return int3(-1,-1,-1);
  436. }
  437. void CGObjectInstance::getNameVis( std::string &hname ) const
  438. {
  439. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  440. hname = VLC->generaltexth->names[ID];
  441. if(h)
  442. {
  443. const bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  444. hname + " " + visitedTxt(visited);
  445. }
  446. }
  447. void CGObjectInstance::giveDummyBonus(ObjectInstanceID heroID, ui8 duration) const
  448. {
  449. GiveBonus gbonus;
  450. gbonus.bonus.type = Bonus::NONE;
  451. gbonus.id = heroID.getNum();
  452. gbonus.bonus.duration = duration;
  453. gbonus.bonus.source = Bonus::OBJECT;
  454. gbonus.bonus.sid = ID;
  455. cb->giveHeroBonus(&gbonus);
  456. }
  457. void CGObjectInstance::onHeroVisit( const CGHeroInstance * h ) const
  458. {
  459. switch(ID)
  460. {
  461. case Obj::HILL_FORT:
  462. {
  463. openWindow(OpenWindow::HILL_FORT_WINDOW,id.getNum(),h->id.getNum());
  464. }
  465. break;
  466. case Obj::SANCTUARY:
  467. {
  468. //You enter the sanctuary and immediately feel as if a great weight has been lifted off your shoulders. You feel safe here.
  469. showInfoDialog(h,114,soundBase::GETPROTECTION);
  470. }
  471. break;
  472. case Obj::TAVERN:
  473. {
  474. openWindow(OpenWindow::TAVERN_WINDOW,h->id.getNum(),id.getNum());
  475. }
  476. break;
  477. }
  478. }
  479. ui8 CGObjectInstance::getPassableness() const
  480. {
  481. return 0;
  482. }
  483. int3 CGObjectInstance::visitablePos() const
  484. {
  485. return pos - getVisitableOffset();
  486. }
  487. bool CGObjectInstance::isVisitable() const
  488. {
  489. for(int g=0; g<ARRAY_COUNT(defInfo->visitMap); ++g)
  490. {
  491. if(defInfo->visitMap[g] != 0)
  492. {
  493. return true;
  494. }
  495. }
  496. return false;
  497. }
  498. bool CGObjectInstance::passableFor(PlayerColor color) const
  499. {
  500. return getPassableness() & 1<<color.getNum();
  501. }
  502. static int lowestSpeed(const CGHeroInstance * chi)
  503. {
  504. if(!chi->Slots().size())
  505. {
  506. logGlobal->errorStream() << "Error! Hero " << chi->id.getNum() << " ("<<chi->name<<") has no army!";
  507. return 20;
  508. }
  509. TSlots::const_iterator i = chi->Slots().begin();
  510. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  511. int ret = (i++)->second->valOfBonuses(Bonus::STACKS_SPEED);
  512. for (;i!=chi->Slots().end();i++)
  513. {
  514. ret = std::min(ret, i->second->valOfBonuses(Bonus::STACKS_SPEED));
  515. }
  516. return ret;
  517. }
  518. ui32 CGHeroInstance::getTileCost(const TerrainTile &dest, const TerrainTile &from) const
  519. {
  520. //base move cost
  521. unsigned ret = 100;
  522. //if there is road both on dest and src tiles - use road movement cost
  523. if(dest.roadType != ERoadType::NO_ROAD && from.roadType != ERoadType::NO_ROAD)
  524. {
  525. int road = std::min(dest.roadType,from.roadType); //used road ID
  526. switch(road)
  527. {
  528. case ERoadType::DIRT_ROAD:
  529. ret = 75;
  530. break;
  531. case ERoadType::GRAVEL_ROAD:
  532. ret = 65;
  533. break;
  534. case ERoadType::COBBLESTONE_ROAD:
  535. ret = 50;
  536. break;
  537. default:
  538. logGlobal->errorStream() << "Unknown road type: " << road << "... Something wrong!";
  539. break;
  540. }
  541. }
  542. else
  543. {
  544. //FIXME: in H3 presence of Nomad in army will remove terrain penalty for sand. Bonus not implemented in VCMI
  545. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  546. // This is clearly bug in H3 however intended behaviour is not clear.
  547. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  548. // will always have best penalty without any influence from player-defined stacks order
  549. bool nativeArmy = true;
  550. BOOST_FOREACH(auto stack, stacks)
  551. {
  552. int nativeTerrain = VLC->townh->factions[stack.second->type->faction]->nativeTerrain;
  553. if (nativeTerrain != -1 && nativeTerrain != from.terType)
  554. {
  555. nativeArmy = false;
  556. break;
  557. }
  558. }
  559. if (!nativeArmy)
  560. ret = VLC->heroh->terrCosts[from.terType];
  561. }
  562. return ret;
  563. }
  564. int3 CGHeroInstance::convertPosition(int3 src, bool toh3m) //toh3m=true: manifest->h3m; toh3m=false: h3m->manifest
  565. {
  566. if (toh3m)
  567. {
  568. src.x+=1;
  569. return src;
  570. }
  571. else
  572. {
  573. src.x-=1;
  574. return src;
  575. }
  576. }
  577. int3 CGHeroInstance::getPosition(bool h3m) const //h3m=true - returns position of hero object; h3m=false - returns position of hero 'manifestation'
  578. {
  579. if (h3m)
  580. {
  581. return pos;
  582. }
  583. else
  584. {
  585. return convertPosition(pos,false);
  586. }
  587. }
  588. bool CGHeroInstance::canWalkOnSea() const
  589. {
  590. return hasBonusOfType(Bonus::FLYING_MOVEMENT) || hasBonusOfType(Bonus::WATER_WALKING);
  591. }
  592. ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
  593. {
  594. for(size_t i=0; i < secSkills.size(); ++i)
  595. if(secSkills[i].first == skill)
  596. return secSkills[i].second;
  597. return 0;
  598. }
  599. void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
  600. {
  601. if(getSecSkillLevel(which) == 0)
  602. {
  603. secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
  604. updateSkill(which, val);
  605. }
  606. else
  607. {
  608. for (unsigned i=0; i<secSkills.size(); i++)
  609. {
  610. if(secSkills[i].first == which)
  611. {
  612. if(abs)
  613. secSkills[i].second = val;
  614. else
  615. secSkills[i].second += val;
  616. if(secSkills[i].second > 3) //workaround to avoid crashes when same sec skill is given more than once
  617. {
  618. logGlobal->warnStream() << "Warning: Skill " << which << " increased over limit! Decreasing to Expert.";
  619. secSkills[i].second = 3;
  620. }
  621. updateSkill(which, secSkills[i].second); //when we know final value
  622. }
  623. }
  624. }
  625. }
  626. bool CGHeroInstance::canLearnSkill() const
  627. {
  628. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  629. }
  630. int CGHeroInstance::maxMovePoints(bool onLand) const
  631. {
  632. int base;
  633. if(onLand)
  634. {
  635. // used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
  636. static const int baseSpeed = 1300; // base speed from creature with 0 speed
  637. int armySpeed = lowestSpeed(this) * 20 / 3;
  638. base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
  639. vstd::abetween(base, 1500, 2000); // base speed is limited by these values
  640. }
  641. else
  642. {
  643. base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
  644. }
  645. const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
  646. const int bonus = valOfBonuses(Bonus::MOVEMENT) + valOfBonuses(bt);
  647. const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
  648. const double modifier = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;
  649. return int(base* (1+modifier)) + bonus;
  650. }
  651. CGHeroInstance::CGHeroInstance()
  652. : IBoatGenerator(this)
  653. {
  654. setNodeType(HERO);
  655. ID = Obj::HERO;
  656. tacticFormationEnabled = inTownGarrison = false;
  657. mana = movement = portrait = level = -1;
  658. isStanding = true;
  659. moveDir = 4;
  660. exp = 0xffffffff;
  661. visitedTown = NULL;
  662. type = NULL;
  663. boat = NULL;
  664. commander = NULL;
  665. sex = 0xff;
  666. secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
  667. }
  668. void CGHeroInstance::initHero(HeroTypeID SUBID)
  669. {
  670. subID = SUBID.getNum();
  671. initHero();
  672. }
  673. void CGHeroInstance::initHero()
  674. {
  675. assert(validTypes(true));
  676. if(ID == Obj::HERO)
  677. initHeroDefInfo();
  678. if(!type)
  679. type = VLC->heroh->heroes[subID];
  680. if(!vstd::contains(spells, SpellID::PRESET)) //hero starts with a spell
  681. {
  682. BOOST_FOREACH(auto spellID, type->spells)
  683. spells.insert(spellID);
  684. }
  685. else //remove placeholder
  686. spells -= SpellID::PRESET;
  687. if(!getArt(ArtifactPosition::MACH4) && !getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook) //no catapult means we haven't read pre-existent set -> use default rules for spellbook
  688. putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  689. if(!getArt(ArtifactPosition::MACH4))
  690. putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createNewArtifactInstance(3)); //everyone has a catapult
  691. if(portrait < 0 || portrait == 255)
  692. portrait = type->imageIndex;
  693. if(!hasBonus(Selector::sourceType(Bonus::HERO_BASE_SKILL)))
  694. {
  695. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  696. {
  697. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(g), type->heroClass->primarySkillInitial[g]);
  698. }
  699. }
  700. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1)) //set secondary skills to default
  701. secSkills = type->secSkillsInit;
  702. if (!name.length())
  703. name = type->name;
  704. if (sex == 0xFF)//sex is default
  705. sex = type->sex;
  706. setFormation(false);
  707. if (!stacksCount()) //standard army//initial army
  708. {
  709. initArmy();
  710. }
  711. assert(validTypes());
  712. if (exp == 0xffffffff)
  713. {
  714. initExp();
  715. }
  716. else if (ID != Obj::PRISON)
  717. {
  718. level = VLC->heroh->level(exp);
  719. }
  720. else //warp hero at the beginning of next turn
  721. {
  722. level = 1;
  723. }
  724. if (VLC->modh->modules.COMMANDERS && !commander)
  725. {
  726. commander = new CCommanderInstance (VLC->townh->factions[type->heroClass->faction]->commander);
  727. commander->setArmyObj (castToArmyObj()); //TODO: separate function for setting commanders
  728. commander->giveStackExp (exp); //after our exp is set
  729. }
  730. hoverName = VLC->generaltexth->allTexts[15];
  731. boost::algorithm::replace_first(hoverName,"%s",name);
  732. boost::algorithm::replace_first(hoverName,"%s", type->heroClass->name);
  733. if (mana < 0)
  734. mana = manaLimit();
  735. }
  736. void CGHeroInstance::initArmy(IArmyDescriptor *dst /*= NULL*/)
  737. {
  738. if(!dst)
  739. dst = this;
  740. int howManyStacks = 0; //how many stacks will hero receives <1 - 3>
  741. int pom = ran()%100;
  742. int warMachinesGiven = 0;
  743. if(pom < 9)
  744. howManyStacks = 1;
  745. else if(pom < 79)
  746. howManyStacks = 2;
  747. else
  748. howManyStacks = 3;
  749. vstd::amin(howManyStacks, type->initialArmy.size());
  750. for(int stackNo=0; stackNo < howManyStacks; stackNo++)
  751. {
  752. auto & stack = type->initialArmy[stackNo];
  753. int range = stack.maxAmount - stack.minAmount;
  754. int count = ran()%(range+1) + stack.minAmount;
  755. if(stack.creature >= CreatureID::CATAPULT &&
  756. stack.creature <= CreatureID::ARROW_TOWERS) //war machine
  757. {
  758. warMachinesGiven++;
  759. if(dst != this)
  760. continue;
  761. int slot = -1;
  762. ArtifactID aid = ArtifactID::NONE;
  763. switch (stack.creature)
  764. {
  765. case CreatureID::CATAPULT:
  766. slot = ArtifactPosition::MACH4;
  767. aid = ArtifactID::CATAPULT;
  768. break;
  769. default:
  770. aid = CArtHandler::creatureToMachineID(stack.creature);
  771. slot = 9 + aid;
  772. break;
  773. }
  774. auto convSlot = ArtifactPosition(slot);
  775. if(!getArt(convSlot))
  776. putArtifact(convSlot, CArtifactInstance::createNewArtifactInstance(aid));
  777. else
  778. logGlobal->warnStream() << "Hero " << name << " already has artifact at " << slot << ", omitting giving " << aid;
  779. }
  780. else
  781. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  782. }
  783. }
  784. void CGHeroInstance::initHeroDefInfo()
  785. {
  786. if(!defInfo || defInfo->id != Obj::HERO)
  787. {
  788. defInfo = new CGDefInfo();
  789. defInfo->id = Obj::HERO;
  790. defInfo->subid = subID;
  791. defInfo->printPriority = 0;
  792. defInfo->visitDir = 0xff;
  793. }
  794. for(int i=0;i<6;i++)
  795. {
  796. defInfo->blockMap[i] = 255;
  797. defInfo->visitMap[i] = 0;
  798. defInfo->coverageMap[i] = 0;
  799. defInfo->shadowCoverage[i] = 0;
  800. }
  801. defInfo->blockMap[5] = 253;
  802. defInfo->visitMap[5] = 2;
  803. defInfo->coverageMap[4] = defInfo->coverageMap[5] = 224;
  804. }
  805. CGHeroInstance::~CGHeroInstance()
  806. {
  807. commander.dellNull();
  808. }
  809. bool CGHeroInstance::needsLastStack() const
  810. {
  811. return true;
  812. }
  813. void CGHeroInstance::onHeroVisit(const CGHeroInstance * h) const
  814. {
  815. if(h == this) return; //exclude potential self-visiting
  816. if (ID == Obj::HERO)
  817. {
  818. if( cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner)) //our or ally hero
  819. {
  820. //exchange
  821. cb->heroExchange(h->id, id);
  822. }
  823. else //battle
  824. {
  825. if(visitedTown) //we're in town
  826. visitedTown->onHeroVisit(h); //town will handle attacking
  827. else
  828. cb->startBattleI(h, this);
  829. }
  830. }
  831. else if(ID == Obj::PRISON)
  832. {
  833. int txt_id;
  834. if(cb->getHeroCount(h->tempOwner,false) < GameConstants::MAX_HEROES_PER_PLAYER) //free hero slot
  835. {
  836. cb->changeObjPos(id,pos+int3(1,0,0),0);
  837. //update hero parameters
  838. SetMovePoints smp;
  839. smp.hid = id;
  840. smp.val = maxMovePoints (true); //TODO: hota prison on water?
  841. cb->setMovePoints (&smp);
  842. cb->setManaPoints (id, manaLimit());
  843. cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
  844. cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player
  845. txt_id = 102;
  846. }
  847. else //already 8 wandering heroes
  848. {
  849. txt_id = 103;
  850. }
  851. showInfoDialog(h,txt_id,soundBase::ROGUE);
  852. }
  853. }
  854. const std::string & CGHeroInstance::getBiography() const
  855. {
  856. if (biography.length())
  857. return biography;
  858. return type->biography;
  859. }
  860. void CGHeroInstance::initObj() //TODO: use bonus system
  861. {
  862. blockVisit = true;
  863. HeroSpecial * hs = new HeroSpecial();
  864. hs->setNodeType(CBonusSystemNode::specialty);
  865. attachTo(hs); //do we ever need to detach it?
  866. if(!type)
  867. initHero(); //TODO: set up everything for prison before specialties are configured
  868. BOOST_FOREACH(const auto &spec, type->spec) //TODO: unfity with bonus system
  869. {
  870. Bonus *bonus = new Bonus();
  871. bonus->val = spec.val;
  872. bonus->sid = id.getNum(); //from the hero, specialty has no unique id
  873. bonus->duration = Bonus::PERMANENT;
  874. bonus->source = Bonus::HERO_SPECIAL;
  875. switch (spec.type)
  876. {
  877. case 1:// creature specialty
  878. {
  879. hs->growsWithLevel = true;
  880. const CCreature &specCreature = *VLC->creh->creatures[spec.additionalinfo]; //creature in which we have specialty
  881. int creLevel = specCreature.level;
  882. if(!creLevel)
  883. {
  884. if(spec.additionalinfo == 146)
  885. creLevel = 5; //treat ballista as 5-level
  886. else
  887. {
  888. logGlobal->warnStream() << "Warning: unknown level of " << specCreature.namePl;
  889. continue;
  890. }
  891. }
  892. //bonus->additionalInfo = spec.additionalinfo; //creature id, should not be used again - this works only with limiter
  893. bonus->limiter.reset(new CCreatureTypeLimiter (specCreature, true)); //with upgrades
  894. bonus->type = Bonus::PRIMARY_SKILL;
  895. bonus->valType = Bonus::ADDITIVE_VALUE;
  896. bonus->subtype = PrimarySkill::ATTACK;
  897. hs->addNewBonus(bonus);
  898. bonus = new Bonus(*bonus);
  899. bonus->subtype = PrimarySkill::DEFENSE;
  900. hs->addNewBonus(bonus);
  901. //values will be calculated later
  902. bonus = new Bonus(*bonus);
  903. bonus->type = Bonus::STACKS_SPEED;
  904. bonus->val = 1; //+1 speed
  905. hs->addNewBonus(bonus);
  906. }
  907. break;
  908. case 2://secondary skill
  909. hs->growsWithLevel = true;
  910. bonus->type = Bonus::SPECIAL_SECONDARY_SKILL; //needs to be recalculated with level, based on this value
  911. bonus->valType = Bonus::BASE_NUMBER; // to receive nonzero value
  912. bonus->subtype = spec.subtype; //skill id
  913. bonus->val = spec.val; //value per level, in percent
  914. hs->addNewBonus(bonus);
  915. bonus = new Bonus(*bonus);
  916. switch (spec.additionalinfo)
  917. {
  918. case 0: //normal
  919. bonus->valType = Bonus::PERCENT_TO_BASE;
  920. break;
  921. case 1: //when it's navigation or there's no 'base' at all
  922. bonus->valType = Bonus::PERCENT_TO_ALL;
  923. break;
  924. }
  925. bonus->type = Bonus::SECONDARY_SKILL_PREMY; //value will be calculated later
  926. hs->addNewBonus(bonus);
  927. break;
  928. case 3://spell damage bonus, level dependent but calculated elsewhere
  929. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  930. bonus->subtype = spec.subtype;
  931. hs->addNewBonus(bonus);
  932. break;
  933. case 4://creature stat boost
  934. switch (spec.subtype)
  935. {
  936. case 1://attack
  937. bonus->type = Bonus::PRIMARY_SKILL;
  938. bonus->subtype = PrimarySkill::ATTACK;
  939. break;
  940. case 2://defense
  941. bonus->type = Bonus::PRIMARY_SKILL;
  942. bonus->subtype = PrimarySkill::DEFENSE;
  943. break;
  944. case 3:
  945. bonus->type = Bonus::CREATURE_DAMAGE;
  946. bonus->subtype = 0; //both min and max
  947. break;
  948. case 4://hp
  949. bonus->type = Bonus::STACK_HEALTH;
  950. break;
  951. case 5:
  952. bonus->type = Bonus::STACKS_SPEED;
  953. break;
  954. default:
  955. continue;
  956. }
  957. bonus->additionalInfo = spec.additionalinfo; //creature id
  958. bonus->valType = Bonus::ADDITIVE_VALUE;
  959. bonus->limiter.reset(new CCreatureTypeLimiter (*VLC->creh->creatures[spec.additionalinfo], true));
  960. hs->addNewBonus(bonus);
  961. break;
  962. case 5://spell damage bonus in percent
  963. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  964. bonus->valType = Bonus::BASE_NUMBER; // current spell system is screwed
  965. bonus->subtype = spec.subtype; //spell id
  966. hs->addNewBonus(bonus);
  967. break;
  968. case 6://damage bonus for bless (Adela)
  969. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  970. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  971. bonus->additionalInfo = spec.additionalinfo; //damage factor
  972. hs->addNewBonus(bonus);
  973. break;
  974. case 7://maxed mastery for spell
  975. bonus->type = Bonus::MAXED_SPELL;
  976. bonus->subtype = spec.subtype; //spell i
  977. hs->addNewBonus(bonus);
  978. break;
  979. case 8://peculiar spells - enchantments
  980. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  981. bonus->subtype = spec.subtype; //spell id
  982. bonus->additionalInfo = spec.additionalinfo;//0, 1 for Coronius
  983. hs->addNewBonus(bonus);
  984. break;
  985. case 9://upgrade creatures
  986. {
  987. const auto &creatures = VLC->creh->creatures;
  988. bonus->type = Bonus::SPECIAL_UPGRADE;
  989. bonus->subtype = spec.subtype; //base id
  990. bonus->additionalInfo = spec.additionalinfo; //target id
  991. hs->addNewBonus(bonus);
  992. bonus = new Bonus(*bonus);
  993. BOOST_FOREACH(auto cre_id, creatures[spec.subtype]->upgrades)
  994. {
  995. bonus->subtype = cre_id; //propagate for regular upgrades of base creature
  996. hs->addNewBonus(bonus);
  997. bonus = new Bonus(*bonus);
  998. }
  999. vstd::clear_pointer(bonus);
  1000. break;
  1001. }
  1002. case 10://resource generation
  1003. bonus->type = Bonus::GENERATE_RESOURCE;
  1004. bonus->subtype = spec.subtype;
  1005. hs->addNewBonus(bonus);
  1006. break;
  1007. case 11://starting skill with mastery (Adrienne)
  1008. cb->changeSecSkill(this, SecondarySkill(spec.val), spec.additionalinfo); //simply give it and forget
  1009. break;
  1010. case 12://army speed
  1011. bonus->type = Bonus::STACKS_SPEED;
  1012. hs->addNewBonus(bonus);
  1013. break;
  1014. case 13://Dragon bonuses (Mutare)
  1015. bonus->type = Bonus::PRIMARY_SKILL;
  1016. bonus->valType = Bonus::ADDITIVE_VALUE;
  1017. switch (spec.subtype)
  1018. {
  1019. case 1:
  1020. bonus->subtype = PrimarySkill::ATTACK;
  1021. break;
  1022. case 2:
  1023. bonus->subtype = PrimarySkill::DEFENSE;
  1024. break;
  1025. }
  1026. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  1027. hs->addNewBonus(bonus);
  1028. break;
  1029. default:
  1030. logGlobal->warnStream() << "Unexpected hero specialty " << type;
  1031. }
  1032. }
  1033. specialty.push_back(hs); //will it work?
  1034. BOOST_FOREACH (auto hs2, type->specialty) //copy active (probably growing) bonuses from hero prootype to hero object
  1035. {
  1036. HeroSpecial * hs = new HeroSpecial();
  1037. attachTo(hs); //do we ever need to detach it?
  1038. hs->setNodeType(CBonusSystemNode::specialty);
  1039. BOOST_FOREACH (auto bonus, hs2.bonuses)
  1040. {
  1041. hs->addNewBonus (bonus);
  1042. }
  1043. hs->growsWithLevel = hs2.growsWithLevel;
  1044. specialty.push_back(hs); //will it work?
  1045. }
  1046. //initialize bonuses
  1047. BOOST_FOREACH(auto skill_info, secSkills)
  1048. updateSkill(SecondarySkill(skill_info.first), skill_info.second);
  1049. Updatespecialty();
  1050. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  1051. type->name = name;
  1052. }
  1053. void CGHeroInstance::Updatespecialty() //TODO: calculate special value of bonuses on-the-fly?
  1054. {
  1055. BOOST_FOREACH (auto hs, specialty)
  1056. {
  1057. if (hs->growsWithLevel)
  1058. {
  1059. //const auto &creatures = VLC->creh->creatures;
  1060. BOOST_FOREACH(Bonus * b, hs->getBonusList())
  1061. {
  1062. switch (b->type)
  1063. {
  1064. case Bonus::SECONDARY_SKILL_PREMY:
  1065. b->val = (hs->valOfBonuses(Bonus::SPECIAL_SECONDARY_SKILL, b->subtype) * level);
  1066. break; //use only hero skills as bonuses to avoid feedback loop
  1067. case Bonus::PRIMARY_SKILL: //for creatures, that is
  1068. {
  1069. const CCreature * cre = NULL;
  1070. int creLevel = 0;
  1071. if (auto creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(b->limiter)) //TODO: more general eveluation of bonuses?
  1072. {
  1073. cre = creatureLimiter->creature;
  1074. creLevel = cre->level;
  1075. if (!creLevel)
  1076. {
  1077. creLevel = 5; //treat ballista as tier 5
  1078. }
  1079. }
  1080. else //no creature found, can't calculate value
  1081. {
  1082. logGlobal->warnStream() << "Primary skill specialty growth supported only with creature type limiters";
  1083. break;
  1084. }
  1085. double primSkillModifier = (int)(level / creLevel) / 20.0;
  1086. int param;
  1087. switch (b->subtype)
  1088. {
  1089. case PrimarySkill::ATTACK:
  1090. param = cre->Attack();
  1091. break;
  1092. case PrimarySkill::DEFENSE:
  1093. param = cre->Defense();
  1094. break;
  1095. default:
  1096. continue;
  1097. }
  1098. b->val = ceil(param * (1 + primSkillModifier)) - param; //yep, overcomplicated but matches original
  1099. break;
  1100. }
  1101. }
  1102. }
  1103. }
  1104. }
  1105. }
  1106. void CGHeroInstance::updateSkill(SecondarySkill which, int val)
  1107. {
  1108. if(which == SecondarySkill::LEADERSHIP || which == SecondarySkill::LUCK)
  1109. { //luck-> VLC->generaltexth->arraytxt[73+luckSkill]; VLC->generaltexth->arraytxt[104+moraleSkill]
  1110. bool luck = which == SecondarySkill::LUCK;
  1111. Bonus::BonusType type[] = {Bonus::MORALE, Bonus::LUCK};
  1112. Bonus *b = getBonusLocalFirst(Selector::type(type[luck]) && Selector::sourceType(Bonus::SECONDARY_SKILL));
  1113. if(!b)
  1114. {
  1115. b = new Bonus(Bonus::PERMANENT, type[luck], Bonus::SECONDARY_SKILL, +val, which, which, Bonus::BASE_NUMBER);
  1116. addNewBonus(b);
  1117. }
  1118. else
  1119. b->val = +val;
  1120. }
  1121. else if(which == SecondarySkill::DIPLOMACY) //surrender discount: 20% per level
  1122. {
  1123. if(Bonus *b = getBonusLocalFirst(Selector::type(Bonus::SURRENDER_DISCOUNT) && Selector::sourceType(Bonus::SECONDARY_SKILL)))
  1124. b->val = +val;
  1125. else
  1126. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::SURRENDER_DISCOUNT, Bonus::SECONDARY_SKILL, val * 20, which));
  1127. }
  1128. int skillVal = 0;
  1129. switch (which)
  1130. {
  1131. case SecondarySkill::ARCHERY:
  1132. switch (val)
  1133. {
  1134. case 1:
  1135. skillVal = 10; break;
  1136. case 2:
  1137. skillVal = 25; break;
  1138. case 3:
  1139. skillVal = 50; break;
  1140. }
  1141. break;
  1142. case SecondarySkill::LOGISTICS:
  1143. skillVal = 10 * val; break;
  1144. case SecondarySkill::NAVIGATION:
  1145. skillVal = 50 * val; break;
  1146. case SecondarySkill::MYSTICISM:
  1147. skillVal = val; break;
  1148. case SecondarySkill::EAGLE_EYE:
  1149. skillVal = 30 + 10 * val; break;
  1150. case SecondarySkill::NECROMANCY:
  1151. skillVal = 10 * val; break;
  1152. case SecondarySkill::LEARNING:
  1153. skillVal = 5 * val; break;
  1154. case SecondarySkill::OFFENCE:
  1155. skillVal = 10 * val; break;
  1156. case SecondarySkill::ARMORER:
  1157. skillVal = 5 * val; break;
  1158. case SecondarySkill::INTELLIGENCE:
  1159. skillVal = 25 << (val-1); break;
  1160. case SecondarySkill::SORCERY:
  1161. skillVal = 5 * val; break;
  1162. case SecondarySkill::RESISTANCE:
  1163. skillVal = 5 << (val-1); break;
  1164. case SecondarySkill::FIRST_AID:
  1165. skillVal = 25 + 25*val; break;
  1166. case SecondarySkill::ESTATES:
  1167. skillVal = 125 << (val-1); break;
  1168. }
  1169. Bonus::ValueType skillValType = skillVal ? Bonus::BASE_NUMBER : Bonus::INDEPENDENT_MIN;
  1170. if(Bonus * b = getBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which) && Selector::sourceType(Bonus::SECONDARY_SKILL))) //only local hero bonus
  1171. {
  1172. b->val = skillVal;
  1173. b->valType = skillValType;
  1174. }
  1175. else
  1176. {
  1177. Bonus *bonus = new Bonus(Bonus::PERMANENT, Bonus::SECONDARY_SKILL_PREMY, Bonus::SECONDARY_SKILL, skillVal, id.getNum(), which, skillValType);
  1178. bonus->source = Bonus::SECONDARY_SKILL;
  1179. addNewBonus(bonus);
  1180. }
  1181. }
  1182. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  1183. {
  1184. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  1185. setStackCount(SlotID(0), val);
  1186. }
  1187. double CGHeroInstance::getHeroStrength() const
  1188. {
  1189. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  1190. }
  1191. ui64 CGHeroInstance::getTotalStrength() const
  1192. {
  1193. double ret = getHeroStrength() * getArmyStrength();
  1194. return (ui64) ret;
  1195. }
  1196. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  1197. {
  1198. return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
  1199. }
  1200. ui8 CGHeroInstance::getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool) const
  1201. {
  1202. si16 skill = -1; //skill level
  1203. #define TRY_SCHOOL(schoolName, schoolMechanicsId, schoolOutId) \
  1204. if(spell-> schoolName) \
  1205. { \
  1206. int thisSchool = std::max<int>(getSecSkillLevel( \
  1207. SecondarySkill(14 + (schoolMechanicsId))), \
  1208. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << (schoolMechanicsId))); \
  1209. if(thisSchool > skill) \
  1210. { \
  1211. skill = thisSchool; \
  1212. if(outSelectedSchool) \
  1213. *outSelectedSchool = schoolOutId; \
  1214. } \
  1215. }
  1216. TRY_SCHOOL(fire, 0, 1)
  1217. TRY_SCHOOL(air, 1, 0)
  1218. TRY_SCHOOL(water, 2, 2)
  1219. TRY_SCHOOL(earth, 3, 3)
  1220. #undef TRY_SCHOOL
  1221. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  1222. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect
  1223. if (hasBonusOfType(Bonus::MAXED_SPELL, spell->id))//hero specialty (Daremyth, Melodia)
  1224. skill = 3;
  1225. assert(skill >= 0 && skill <= 3);
  1226. return skill;
  1227. }
  1228. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  1229. {
  1230. if(!getArt(ArtifactPosition::SPELLBOOK)) //if hero has no spellbook
  1231. return false;
  1232. if(vstd::contains(spells, spell->id) //hero has this spell in spellbook
  1233. || (spell->air && hasBonusOfType(Bonus::AIR_SPELLS)) // this is air spell and hero can cast all air spells
  1234. || (spell->fire && hasBonusOfType(Bonus::FIRE_SPELLS)) // this is fire spell and hero can cast all fire spells
  1235. || (spell->water && hasBonusOfType(Bonus::WATER_SPELLS)) // this is water spell and hero can cast all water spells
  1236. || (spell->earth && hasBonusOfType(Bonus::EARTH_SPELLS)) // this is earth spell and hero can cast all earth spells
  1237. || hasBonusOfType(Bonus::SPELL, spell->id)
  1238. || hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level)
  1239. )
  1240. return true;
  1241. return false;
  1242. }
  1243. /**
  1244. * Calculates what creatures and how many to be raised from a battle.
  1245. * @param battleResult The results of the battle.
  1246. * @return Returns a pair with the first value indicating the ID of the creature
  1247. * type and second value the amount. Both values are returned as -1 if necromancy
  1248. * could not be applied.
  1249. */
  1250. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  1251. {
  1252. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  1253. // Hero knows necromancy.
  1254. if (necromancyLevel > 0)
  1255. {
  1256. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  1257. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  1258. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  1259. ui32 raisedUnits = 0;
  1260. // Figure out what to raise and how many.
  1261. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  1262. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  1263. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  1264. const ui32 raisedUnitHP = raisedUnitType->valOfBonuses(Bonus::STACK_HEALTH);
  1265. //calculate creatures raised from each defeated stack
  1266. for (std::map<ui32,si32>::const_iterator it = casualties.begin(); it != casualties.end(); it++)
  1267. {
  1268. // Get lost enemy hit points convertible to units.
  1269. CCreature * c = VLC->creh->creatures[it->first];
  1270. if (c->isLiving())
  1271. {
  1272. const ui32 raisedHP = c->valOfBonuses(Bonus::STACK_HEALTH) * it->second * necromancySkill;
  1273. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, it->second * necromancySkill); //limit to % of HP and % of original stack count
  1274. }
  1275. }
  1276. // Make room for new units.
  1277. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  1278. if (slot == SlotID())
  1279. {
  1280. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  1281. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  1282. raisedUnits = (raisedUnits*2)/3;
  1283. slot = getSlotFor(raisedUnitType->idNumber);
  1284. }
  1285. if (raisedUnits <= 0)
  1286. raisedUnits = 1;
  1287. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  1288. }
  1289. return CStackBasicDescriptor();
  1290. }
  1291. /**
  1292. * Show the necromancy dialog with information about units raised.
  1293. * @param raisedStack Pair where the first element represents ID of the raised creature
  1294. * and the second element the amount.
  1295. */
  1296. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack) const
  1297. {
  1298. InfoWindow iw;
  1299. iw.soundID = soundBase::pickup01 + ran() % 7;
  1300. iw.player = tempOwner;
  1301. iw.components.push_back(Component(raisedStack));
  1302. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  1303. {
  1304. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  1305. iw.text.addReplacement(raisedStack.count);
  1306. }
  1307. else // Practicing the dark arts of necromancy, ... (singular)
  1308. {
  1309. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  1310. }
  1311. iw.text.addReplacement(raisedStack);
  1312. cb->showInfoDialog(&iw);
  1313. }
  1314. int3 CGHeroInstance::getSightCenter() const
  1315. {
  1316. return getPosition(false);
  1317. }
  1318. int CGHeroInstance::getSightRadious() const
  1319. {
  1320. return 5 + getSecSkillLevel(SecondarySkill::SCOUTING) + valOfBonuses(Bonus::SIGHT_RADIOUS); //default + scouting
  1321. }
  1322. si32 CGHeroInstance::manaRegain() const
  1323. {
  1324. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  1325. return manaLimit();
  1326. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 8) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  1327. }
  1328. // /**
  1329. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  1330. // * or discards it if it cannot be equipped.
  1331. // */
  1332. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  1333. // {
  1334. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  1335. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  1336. // ai->putAt(this, ai->firstAvailableSlot(this));
  1337. // }
  1338. int CGHeroInstance::getBoatType() const
  1339. {
  1340. switch(type->heroClass->getAlignment())
  1341. {
  1342. case EAlignment::GOOD:
  1343. return 1;
  1344. case EAlignment::EVIL:
  1345. return 0;
  1346. case EAlignment::NEUTRAL:
  1347. return 2;
  1348. default:
  1349. throw std::runtime_error("Wrong alignment!");
  1350. }
  1351. }
  1352. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  1353. {
  1354. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0), int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1355. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1356. offsets += dirs[i];
  1357. }
  1358. int CGHeroInstance::getSpellCost(const CSpell *sp) const
  1359. {
  1360. return sp->costs[getSpellSchoolLevel(sp)];
  1361. }
  1362. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  1363. {
  1364. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  1365. }
  1366. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  1367. {
  1368. return type->heroClass->getAlignment();
  1369. }
  1370. void CGHeroInstance::initExp()
  1371. {
  1372. exp=40+ (ran()) % 50;
  1373. level = 1;
  1374. }
  1375. std::string CGHeroInstance::nodeName() const
  1376. {
  1377. return "Hero " + name;
  1378. }
  1379. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  1380. {
  1381. assert(!getArt(pos));
  1382. art->putAt(ArtifactLocation(this, pos));
  1383. }
  1384. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  1385. {
  1386. putArtifact(art->firstBackpackSlot(this), art);
  1387. }
  1388. bool CGHeroInstance::hasSpellbook() const
  1389. {
  1390. return getArt(ArtifactPosition::SPELLBOOK);
  1391. }
  1392. void CGHeroInstance::deserializationFix()
  1393. {
  1394. artDeserializationFix(this);
  1395. //BOOST_FOREACH (auto hs, specialty)
  1396. //{
  1397. // attachTo (hs);
  1398. //}
  1399. }
  1400. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  1401. {
  1402. if(visitedTown)
  1403. {
  1404. if(inTownGarrison)
  1405. return visitedTown;
  1406. else
  1407. return &visitedTown->townAndVis;
  1408. }
  1409. else
  1410. return CArmedInstance::whereShouldBeAttached(gs);
  1411. }
  1412. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark /*= false*/) const
  1413. {
  1414. if(hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  1415. return (MPsBefore - basicCost) * static_cast<double>(maxMovePoints(disembark)) / maxMovePoints(!disembark);
  1416. return 0; //take all MPs otherwise
  1417. }
  1418. CGHeroInstance::ECanDig CGHeroInstance::diggingStatus() const
  1419. {
  1420. if(movement < maxMovePoints(true))
  1421. return LACK_OF_MOVEMENT;
  1422. else if(cb->getTile(getPosition(false))->terType == ETerrainType::WATER)
  1423. return WRONG_TERRAIN;
  1424. else
  1425. {
  1426. const TerrainTile *t = cb->getTile(getPosition());
  1427. //TODO look for hole
  1428. //CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  1429. if(/*hlp.length() || */t->blockingObjects.size() > 1)
  1430. return TILE_OCCUPIED;
  1431. else
  1432. return CAN_DIG;
  1433. }
  1434. }
  1435. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1436. {
  1437. return ArtBearer::HERO;
  1438. }
  1439. std::vector<SecondarySkill> CGHeroInstance::levelUpProposedSkills() const
  1440. {
  1441. std::vector<SecondarySkill> skills;
  1442. //picking sec. skills for choice
  1443. std::set<SecondarySkill> basicAndAdv, expert, none;
  1444. for(int i=0;i<GameConstants::SKILL_QUANTITY;i++)
  1445. if (cb->isAllowed(2,i))
  1446. none.insert(SecondarySkill(i));
  1447. for(unsigned i=0; i<secSkills.size(); i++)
  1448. {
  1449. if(secSkills[i].second < 3)
  1450. basicAndAdv.insert(secSkills[i].first);
  1451. else
  1452. expert.insert(secSkills[i].first);
  1453. none.erase(secSkills[i].first);
  1454. }
  1455. //first offered skill
  1456. if(basicAndAdv.size())
  1457. {
  1458. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv);//upgrade existing
  1459. skills.push_back(s);
  1460. basicAndAdv.erase(s);
  1461. }
  1462. else if(none.size() && canLearnSkill())
  1463. {
  1464. skills.push_back(type->heroClass->chooseSecSkill(none)); //give new skill
  1465. none.erase(skills.back());
  1466. }
  1467. //second offered skill
  1468. if(none.size() && canLearnSkill()) //hero have free skill slot
  1469. {
  1470. skills.push_back(type->heroClass->chooseSecSkill(none)); //new skill
  1471. }
  1472. else if(basicAndAdv.size())
  1473. {
  1474. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv)); //upgrade existing
  1475. }
  1476. return skills;
  1477. }
  1478. bool CGHeroInstance::gainsLevel() const
  1479. {
  1480. return exp >= VLC->heroh->reqExp(level+1);
  1481. }
  1482. void CGDwelling::initObj()
  1483. {
  1484. switch(ID)
  1485. {
  1486. case Obj::CREATURE_GENERATOR1:
  1487. {
  1488. CreatureID crid = VLC->objh->cregens[subID];
  1489. const CCreature *crs = VLC->creh->creatures[crid];
  1490. creatures.resize(1);
  1491. creatures[0].second.push_back(crid);
  1492. if (subID >= VLC->generaltexth->creGens.size()) //very messy workaround
  1493. {
  1494. auto & dwellingNames = VLC->townh->factions[crs->faction]->town->dwellingNames;
  1495. assert (!dwellingNames.empty());
  1496. hoverName = dwellingNames[VLC->creh->creatures[subID]->level - 1];
  1497. }
  1498. else
  1499. hoverName = VLC->generaltexth->creGens[subID];
  1500. if(crs->level > 4)
  1501. putStack(SlotID(0), new CStackInstance(crs, (crs->growth) * 3));
  1502. if (getOwner() != PlayerColor::NEUTRAL)
  1503. cb->gameState()->players[getOwner()].dwellings.push_back (this);
  1504. }
  1505. break;
  1506. case Obj::CREATURE_GENERATOR4:
  1507. creatures.resize(4);
  1508. if(subID == 1) //Golem Factory
  1509. {
  1510. creatures[0].second.push_back(CreatureID::STONE_GOLEM);
  1511. creatures[1].second.push_back(CreatureID::IRON_GOLEM);
  1512. creatures[2].second.push_back(CreatureID::GOLD_GOLEM);
  1513. creatures[3].second.push_back(CreatureID::DIAMOND_GOLEM);
  1514. //guards
  1515. putStack(SlotID(0), new CStackInstance(CreatureID::GOLD_GOLEM, 9));
  1516. putStack(SlotID(1), new CStackInstance(CreatureID::DIAMOND_GOLEM, 6));
  1517. }
  1518. else if(subID == 0) // Elemental Conflux
  1519. {
  1520. creatures[0].second.push_back(CreatureID::AIR_ELEMENTAL);
  1521. creatures[1].second.push_back(CreatureID::FIRE_ELEMENTAL);
  1522. creatures[2].second.push_back(CreatureID::EARTH_ELEMENTAL);
  1523. creatures[3].second.push_back(CreatureID::WATER_ELEMENTAL);
  1524. //guards
  1525. putStack(SlotID(0), new CStackInstance(CreatureID::EARTH_ELEMENTAL, 12));
  1526. }
  1527. else
  1528. {
  1529. assert(0);
  1530. }
  1531. hoverName = VLC->generaltexth->creGens4[subID];
  1532. break;
  1533. case Obj::REFUGEE_CAMP:
  1534. //is handled within newturn func
  1535. break;
  1536. case Obj::WAR_MACHINE_FACTORY:
  1537. creatures.resize(3);
  1538. creatures[0].second.push_back(CreatureID::BALLISTA);
  1539. creatures[1].second.push_back(CreatureID::FIRST_AID_TENT);
  1540. creatures[2].second.push_back(CreatureID::AMMO_CART);
  1541. break;
  1542. default:
  1543. assert(0);
  1544. break;
  1545. }
  1546. }
  1547. void CGDwelling::setProperty(ui8 what, ui32 val)
  1548. {
  1549. switch (what)
  1550. {
  1551. case ObjProperty::OWNER: //change owner
  1552. if (ID == Obj::CREATURE_GENERATOR1) //single generators
  1553. {
  1554. if (tempOwner != PlayerColor::NEUTRAL)
  1555. {
  1556. std::vector<ConstTransitivePtr<CGDwelling> >* dwellings = &cb->gameState()->players[tempOwner].dwellings;
  1557. dwellings->erase (std::find(dwellings->begin(), dwellings->end(), this));
  1558. }
  1559. if (PlayerColor(val) != PlayerColor::NEUTRAL) //can new owner be neutral?
  1560. cb->gameState()->players[PlayerColor(val)].dwellings.push_back (this);
  1561. }
  1562. break;
  1563. case ObjProperty::AVAILABLE_CREATURE:
  1564. creatures.resize(1);
  1565. creatures[0].second.resize(1);
  1566. creatures[0].second[0] = CreatureID(val);
  1567. break;
  1568. }
  1569. CGObjectInstance::setProperty(what,val);
  1570. }
  1571. void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
  1572. {
  1573. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  1574. {
  1575. InfoWindow iw;
  1576. iw.player = h->tempOwner;
  1577. iw.text.addTxt(MetaString::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  1578. iw.text.addReplacement(MetaString::OBJ_NAMES, ID);
  1579. cb->sendAndApply(&iw);
  1580. return;
  1581. }
  1582. PlayerRelations::PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
  1583. if ( relations == PlayerRelations::ALLIES )
  1584. return;//do not allow recruiting or capturing
  1585. if( !relations && stacksCount() > 0) //object is guarded, owned by enemy
  1586. {
  1587. BlockingDialog bd(true,false);
  1588. bd.player = h->tempOwner;
  1589. bd.text.addTxt(MetaString::GENERAL_TXT, 421); //Much to your dismay, the %s is guarded by %s %s. Do you wish to fight the guards?
  1590. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  1591. bd.text.addReplacement(MetaString::ARRAY_TXT, 176 + Slots().begin()->second->getQuantityID()*3);
  1592. bd.text.addReplacement(*Slots().begin()->second);
  1593. cb->showBlockingDialog(&bd);
  1594. return;
  1595. }
  1596. if(!relations && ID != Obj::WAR_MACHINE_FACTORY)
  1597. {
  1598. cb->setOwner(this, h->tempOwner);
  1599. }
  1600. BlockingDialog bd (true,false);
  1601. bd.player = h->tempOwner;
  1602. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  1603. {
  1604. bd.text.addTxt(MetaString::ADVOB_TXT, ID == Obj::CREATURE_GENERATOR1 ? 35 : 36); //{%s} Would you like to recruit %s? / {%s} Would you like to recruit %s, %s, %s, or %s?
  1605. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  1606. for(size_t i = 0; i < creatures.size(); i++)
  1607. bd.text.addReplacement(MetaString::CRE_PL_NAMES, creatures[i].second[0]);
  1608. }
  1609. else if(ID == Obj::REFUGEE_CAMP)
  1610. {
  1611. bd.text.addTxt(MetaString::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  1612. bd.text.addReplacement(MetaString::OBJ_NAMES, ID);
  1613. for(size_t i = 0; i < creatures.size(); i++)
  1614. bd.text.addReplacement(MetaString::CRE_PL_NAMES, creatures[i].second[0]);
  1615. }
  1616. else if(ID == Obj::WAR_MACHINE_FACTORY)
  1617. bd.text.addTxt(MetaString::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  1618. else
  1619. throw std::runtime_error("Illegal dwelling!");
  1620. cb->showBlockingDialog(&bd);
  1621. }
  1622. void CGDwelling::newTurn() const
  1623. {
  1624. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  1625. return;
  1626. //town growths and War Machines Factories are handled separately
  1627. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  1628. return;
  1629. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  1630. {
  1631. cb->setObjProperty(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster());
  1632. }
  1633. bool change = false;
  1634. SetAvailableCreatures sac;
  1635. sac.creatures = creatures;
  1636. sac.tid = id;
  1637. for (size_t i = 0; i < creatures.size(); i++)
  1638. {
  1639. if(creatures[i].second.size())
  1640. {
  1641. CCreature *cre = VLC->creh->creatures[creatures[i].second[0]];
  1642. TQuantity amount = cre->growth * (1 + cre->valOfBonuses(Bonus::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(Bonus::CREATURE_GROWTH);
  1643. if (VLC->modh->settings.DWELLINGS_ACCUMULATE_CREATURES && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  1644. sac.creatures[i].first += amount;
  1645. else
  1646. sac.creatures[i].first = amount;
  1647. change = true;
  1648. }
  1649. }
  1650. if(change)
  1651. cb->sendAndApply(&sac);
  1652. }
  1653. void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h) const
  1654. {
  1655. CreatureID crid = creatures[0].second[0];
  1656. CCreature *crs = VLC->creh->creatures[crid];
  1657. TQuantity count = creatures[0].first;
  1658. if(crs->level == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  1659. {
  1660. if(count) //there are available creatures
  1661. {
  1662. SlotID slot = h->getSlotFor(crid);
  1663. if(!slot.validSlot()) //no available slot
  1664. {
  1665. InfoWindow iw;
  1666. iw.player = h->tempOwner;
  1667. iw.text.addTxt(MetaString::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  1668. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1669. cb->showInfoDialog(&iw);
  1670. }
  1671. else //give creatures
  1672. {
  1673. SetAvailableCreatures sac;
  1674. sac.tid = id;
  1675. sac.creatures = creatures;
  1676. sac.creatures[0].first = 0;
  1677. InfoWindow iw;
  1678. iw.player = h->tempOwner;
  1679. iw.text.addTxt(MetaString::GENERAL_TXT, 423); //%d %s join your army.
  1680. iw.text.addReplacement(count);
  1681. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1682. cb->showInfoDialog(&iw);
  1683. cb->sendAndApply(&sac);
  1684. cb->addToSlot(StackLocation(h, slot), crs, count);
  1685. }
  1686. }
  1687. else //there no creatures
  1688. {
  1689. InfoWindow iw;
  1690. iw.text.addTxt(MetaString::GENERAL_TXT, 422); //There are no %s here to recruit.
  1691. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1692. iw.player = h->tempOwner;
  1693. cb->sendAndApply(&iw);
  1694. }
  1695. }
  1696. else
  1697. {
  1698. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  1699. {
  1700. //there is 1 war machine available to recruit if hero doesn't have one
  1701. SetAvailableCreatures sac;
  1702. sac.tid = id;
  1703. sac.creatures = creatures;
  1704. sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
  1705. sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
  1706. sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
  1707. cb->sendAndApply(&sac);
  1708. }
  1709. OpenWindow ow;
  1710. ow.id1 = id.getNum();
  1711. ow.id2 = h->id.getNum();
  1712. ow.window = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP)
  1713. ? OpenWindow::RECRUITMENT_FIRST
  1714. : OpenWindow::RECRUITMENT_ALL;
  1715. cb->sendAndApply(&ow);
  1716. }
  1717. }
  1718. void CGDwelling::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1719. {
  1720. if (result.winner == 0)
  1721. {
  1722. onHeroVisit(hero);
  1723. }
  1724. }
  1725. void CGDwelling::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1726. {
  1727. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  1728. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  1729. {
  1730. if(answer)
  1731. cb->startBattleI(hero, this);
  1732. }
  1733. else if(relations == PlayerRelations::SAME_PLAYER && answer)
  1734. {
  1735. heroAcceptsCreatures(hero);
  1736. }
  1737. }
  1738. int CGTownInstance::getSightRadious() const //returns sight distance
  1739. {
  1740. if (subID == ETownType::TOWER)
  1741. {
  1742. if (hasBuilt(BuildingID::GRAIL)) //skyship
  1743. return -1; //entire map
  1744. else if (hasBuilt(BuildingID::LOOKOUT_TOWER)) //lookout tower
  1745. return 20;
  1746. }
  1747. return 5;
  1748. }
  1749. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  1750. {
  1751. ///this is freakin' overcomplicated solution
  1752. switch (what)
  1753. {
  1754. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  1755. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, visitingHero->id.getNum());
  1756. break;
  1757. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1758. bonusingBuildings[val]->setProperty (ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  1759. break;
  1760. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  1761. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, garrisonHero->id.getNum());
  1762. break;
  1763. case ObjProperty::BONUS_VALUE_FIRST:
  1764. bonusValue.first = val;
  1765. break;
  1766. case ObjProperty::BONUS_VALUE_SECOND:
  1767. bonusValue.second = val;
  1768. break;
  1769. }
  1770. }
  1771. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  1772. {
  1773. if (hasBuilt(BuildingID::CASTLE))
  1774. return CASTLE;
  1775. if (hasBuilt(BuildingID::CITADEL))
  1776. return CITADEL;
  1777. if (hasBuilt(BuildingID::FORT))
  1778. return FORT;
  1779. return NONE;
  1780. }
  1781. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  1782. {
  1783. if (hasBuilt(BuildingID::CAPITOL))
  1784. return 3;
  1785. if (hasBuilt(BuildingID::CITY_HALL))
  1786. return 2;
  1787. if (hasBuilt(BuildingID::TOWN_HALL))
  1788. return 1;
  1789. if (hasBuilt(BuildingID::VILLAGE_HALL))
  1790. return 0;
  1791. return -1;
  1792. }
  1793. int CGTownInstance::mageGuildLevel() const
  1794. {
  1795. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  1796. return 5;
  1797. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  1798. return 4;
  1799. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  1800. return 3;
  1801. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  1802. return 2;
  1803. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  1804. return 1;
  1805. return 0;
  1806. }
  1807. int CGTownInstance::creatureDwellingLevel(int dwelling) const
  1808. {
  1809. if ( dwelling<0 || dwelling >= GameConstants::CREATURES_PER_TOWN )
  1810. return -1;
  1811. for (int i=0; ; i++)
  1812. {
  1813. if (!hasBuilt(BuildingID(BuildingID::DWELL_FIRST+dwelling+i*GameConstants::CREATURES_PER_TOWN)))
  1814. return i-1;
  1815. }
  1816. }
  1817. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  1818. {
  1819. return town->hordeLvl[HID];
  1820. }
  1821. int CGTownInstance::creatureGrowth(const int & level) const
  1822. {
  1823. return getGrowthInfo(level).totalGrowth();
  1824. }
  1825. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  1826. {
  1827. GrowthInfo ret;
  1828. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  1829. return ret;
  1830. if (!hasBuilt(BuildingID(BuildingID::DWELL_FIRST+level)))
  1831. return ret; //no dwelling
  1832. const CCreature *creature = VLC->creh->creatures[creatures[level].second.back()];
  1833. const int base = creature->growth;
  1834. int castleBonus = 0;
  1835. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[590], base));// \n\nBasic growth %d"
  1836. if (hasBuilt(BuildingID::CASTLE))
  1837. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CASTLE, castleBonus = base));
  1838. else if (hasBuilt(BuildingID::CITADEL))
  1839. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CITADEL, castleBonus = base / 2));
  1840. if(town->hordeLvl[0] == level)//horde 1
  1841. if(hasBuilt(BuildingID::HORDE_1))
  1842. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_1, creature->hordeGrowth));
  1843. if(town->hordeLvl[1] == level)//horde 2
  1844. if(hasBuilt(BuildingID::HORDE_2))
  1845. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_2, creature->hordeGrowth));
  1846. int dwellingBonus = 0;
  1847. if(const PlayerState *p = cb->getPlayer(tempOwner, false))
  1848. {
  1849. BOOST_FOREACH(const CGDwelling *dwelling, p->dwellings)
  1850. if(vstd::contains(creatures[level].second, dwelling->creatures[0].second[0]))
  1851. dwellingBonus++;
  1852. }
  1853. if(dwellingBonus)
  1854. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[591], dwellingBonus));// \nExternal dwellings %+d
  1855. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  1856. TBonusListPtr bonuses = getBonuses(Selector::type(Bonus::CREATURE_GROWTH) && Selector::subtype(level));
  1857. BOOST_FOREACH(const Bonus *b, *bonuses)
  1858. ret.entries.push_back(GrowthInfo::Entry(b->Description() + " %+d", b->val));
  1859. //statue-of-legion-like bonus: % to base+castle
  1860. TBonusListPtr bonuses2 = getBonuses(Selector::type(Bonus::CREATURE_GROWTH_PERCENT));
  1861. BOOST_FOREACH(const Bonus *b, *bonuses2)
  1862. ret.entries.push_back(GrowthInfo::Entry(b->Description() + " %+d", b->val * (base + castleBonus) / 100));
  1863. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  1864. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::GRAIL, ret.totalGrowth() / 2));
  1865. return ret;
  1866. }
  1867. int CGTownInstance::dailyIncome() const
  1868. {
  1869. int ret = 0;
  1870. if (hasBuilt(BuildingID::GRAIL))
  1871. ret+=5000;
  1872. if (hasBuilt(BuildingID::CAPITOL))
  1873. ret+=4000;
  1874. else if (hasBuilt(BuildingID::CITY_HALL))
  1875. ret+=2000;
  1876. else if (hasBuilt(BuildingID::TOWN_HALL))
  1877. ret+=1000;
  1878. else if (hasBuilt(BuildingID::VILLAGE_HALL))
  1879. ret+=500;
  1880. return ret;
  1881. }
  1882. bool CGTownInstance::hasFort() const
  1883. {
  1884. return hasBuilt(BuildingID::FORT);
  1885. }
  1886. bool CGTownInstance::hasCapitol() const
  1887. {
  1888. return hasBuilt(BuildingID::CAPITOL);
  1889. }
  1890. CGTownInstance::CGTownInstance()
  1891. :IShipyard(this), IMarket(this), town(nullptr), builded(0), destroyed(0), identifier(0), alignment(0xff)
  1892. {
  1893. }
  1894. CGTownInstance::~CGTownInstance()
  1895. {
  1896. for (std::vector<CGTownBuilding*>::const_iterator i = bonusingBuildings.begin(); i != bonusingBuildings.end(); i++)
  1897. delete *i;
  1898. }
  1899. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  1900. {
  1901. if(checkGuild && mageGuildLevel() < level)
  1902. return 0;
  1903. int ret = 6 - level; //how many spells are available at this level
  1904. if (hasBuilt(BuildingID::LIBRARY, ETownType::TOWER))
  1905. ret++;
  1906. return ret;
  1907. }
  1908. bool CGTownInstance::needsLastStack() const
  1909. {
  1910. if(garrisonHero)
  1911. return true;
  1912. else return false;
  1913. }
  1914. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  1915. {
  1916. if( !cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  1917. {
  1918. if(armedGarrison() || visitingHero)
  1919. {
  1920. const CGHeroInstance *defendingHero = NULL;
  1921. const CArmedInstance *defendingArmy = this;
  1922. if(visitingHero)
  1923. defendingHero = visitingHero;
  1924. else if(garrisonHero)
  1925. defendingHero = garrisonHero;
  1926. if(defendingHero)
  1927. defendingArmy = defendingHero;
  1928. bool outsideTown = (defendingHero == visitingHero && garrisonHero);
  1929. //TODO
  1930. //"borrowing" army from garrison to visiting hero
  1931. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (outsideTown ? NULL : this));
  1932. }
  1933. else
  1934. {
  1935. cb->setOwner(this, h->tempOwner);
  1936. removeCapitols(h->getOwner());
  1937. cb->heroVisitCastle(this, h);
  1938. }
  1939. }
  1940. else if(h->visitablePos() == visitablePos())
  1941. {
  1942. if (h->commander && !h->commander->alive) //rise commander. TODO: interactive script
  1943. {
  1944. SetCommanderProperty scp;
  1945. scp.heroid = h->id;
  1946. scp.which = SetCommanderProperty::ALIVE;
  1947. scp.amount = 1;
  1948. cb->sendAndApply (&scp);
  1949. }
  1950. cb->heroVisitCastle(this, h);
  1951. }
  1952. else
  1953. {
  1954. logGlobal->errorStream() << h->name << " visits allied town of " << name << " from different pos?";
  1955. }
  1956. }
  1957. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  1958. {
  1959. cb->stopHeroVisitCastle(this, h);
  1960. }
  1961. void CGTownInstance::initObj()
  1962. ///initialize town structures
  1963. {
  1964. blockVisit = true;
  1965. hoverName = name + ", " + town->faction->name;
  1966. if (subID == ETownType::DUNGEON)
  1967. creatures.resize(GameConstants::CREATURES_PER_TOWN+1);//extra dwelling for Dungeon
  1968. else
  1969. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  1970. for (int i = 0; i < GameConstants::CREATURES_PER_TOWN; i++)
  1971. {
  1972. int dwellingLevel = creatureDwellingLevel(i);
  1973. int creaturesTotal = town->creatures[i].size();
  1974. for (int j=0; j< std::min(dwellingLevel + 1, creaturesTotal); j++)
  1975. creatures[i].second.push_back(town->creatures[i][j]);
  1976. }
  1977. switch (subID)
  1978. { //add new visitable objects
  1979. case 0:
  1980. bonusingBuildings.push_back (new COPWBonus(BuildingID::STABLES, this));
  1981. break;
  1982. case 5:
  1983. bonusingBuildings.push_back (new COPWBonus(BuildingID::MANA_VORTEX, this));
  1984. case 2: case 3: case 6:
  1985. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_4, this));
  1986. break;
  1987. case 7:
  1988. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_1, this));
  1989. break;
  1990. }
  1991. //add special bonuses from buildings
  1992. recreateBuildingsBonuses();
  1993. }
  1994. void CGTownInstance::newTurn() const
  1995. {
  1996. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  1997. {
  1998. //give resources for Rampart, Mystic Pond
  1999. if (hasBuilt(BuildingID::MYSTIC_POND, ETownType::RAMPART)
  2000. && cb->getDate(Date::DAY) != 1 && (tempOwner < PlayerColor::PLAYER_LIMIT))
  2001. {
  2002. int resID = rand()%4+2;//bonus to random rare resource
  2003. resID = (resID==2)?1:resID;
  2004. int resVal = rand()%4+1;//with size 1..4
  2005. cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
  2006. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  2007. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  2008. }
  2009. if ( subID == ETownType::DUNGEON )
  2010. for (std::vector<CGTownBuilding*>::const_iterator i = bonusingBuildings.begin(); i!=bonusingBuildings.end(); i++)
  2011. {
  2012. if ((*i)->ID == BuildingID::MANA_VORTEX)
  2013. cb->setObjProperty (id, ObjProperty::STRUCTURE_CLEAR_VISITORS, (*i)->id); //reset visitors for Mana Vortex
  2014. }
  2015. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  2016. {
  2017. std::vector<SlotID> nativeCrits; //slots
  2018. for (TSlots::const_iterator it = Slots().begin(); it != Slots().end(); it++)
  2019. {
  2020. if (it->second->type->faction == subID) //native
  2021. {
  2022. nativeCrits.push_back(it->first); //collect matching slots
  2023. }
  2024. }
  2025. if (nativeCrits.size())
  2026. {
  2027. SlotID pos = nativeCrits[rand() % nativeCrits.size()];
  2028. StackLocation sl(this, pos);
  2029. const CCreature *c = getCreature(pos);
  2030. if (rand()%100 < 90 || c->upgrades.empty()) //increase number if no upgrade available
  2031. {
  2032. cb->changeStackCount(sl, c->growth);
  2033. }
  2034. else //upgrade
  2035. {
  2036. cb->changeStackType(sl, VLC->creh->creatures[*c->upgrades.begin()]);
  2037. }
  2038. }
  2039. if ((stacksCount() < GameConstants::ARMY_SIZE && rand()%100 < 25) || Slots().empty()) //add new stack
  2040. {
  2041. int i = rand() % std::min (GameConstants::ARMY_SIZE, cb->getDate(Date::MONTH)<<1);
  2042. CreatureID c = town->creatures[i][0];
  2043. SlotID n;
  2044. TQuantity count = creatureGrowth(i);
  2045. if (!count) // no dwelling
  2046. count = VLC->creh->creatures[c]->growth;
  2047. {//no lower tiers or above current month
  2048. if ((n = getSlotFor(c)).validSlot())
  2049. {
  2050. StackLocation sl(this, n);
  2051. if (slotEmpty(n))
  2052. cb->insertNewStack(sl, VLC->creh->creatures[c], count);
  2053. else //add to existing
  2054. cb->changeStackCount(sl, count);
  2055. }
  2056. }
  2057. }
  2058. }
  2059. }
  2060. }
  2061. int3 CGTownInstance::getSightCenter() const
  2062. {
  2063. return pos - int3(2,0,0);
  2064. }
  2065. ui8 CGTownInstance::getPassableness() const
  2066. {
  2067. if (!armedGarrison())//empty castle - anyone can visit
  2068. return GameConstants::ALL_PLAYERS;
  2069. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  2070. return 0;
  2071. ui8 mask = 0;
  2072. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  2073. BOOST_FOREACH(PlayerColor it, ts->players)
  2074. mask |= 1<<it.getNum();//allies - add to possible visitors
  2075. return mask;
  2076. }
  2077. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  2078. {
  2079. offsets += int3(-1,2,0), int3(-3,2,0);
  2080. }
  2081. void CGTownInstance::removeCapitols (PlayerColor owner) const
  2082. {
  2083. if (hasCapitol()) // search if there's an older capitol
  2084. {
  2085. PlayerState* state = cb->gameState()->getPlayer (owner); //get all towns owned by player
  2086. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  2087. {
  2088. if (*i != this && (*i)->hasCapitol())
  2089. {
  2090. RazeStructures rs;
  2091. rs.tid = id;
  2092. rs.bid.insert(BuildingID::CAPITOL);
  2093. rs.destroyed = destroyed;
  2094. cb->sendAndApply(&rs);
  2095. return;
  2096. }
  2097. }
  2098. }
  2099. }
  2100. int CGTownInstance::getBoatType() const
  2101. {
  2102. switch (town->faction->alignment)
  2103. {
  2104. case EAlignment::EVIL : return 0;
  2105. case EAlignment::GOOD : return 1;
  2106. case EAlignment::NEUTRAL : return 2;
  2107. }
  2108. assert(0);
  2109. return -1;
  2110. }
  2111. int CGTownInstance::getMarketEfficiency() const
  2112. {
  2113. if (!hasBuilt(BuildingID::MARKETPLACE))
  2114. return 0;
  2115. const PlayerState *p = cb->getPlayer(tempOwner);
  2116. assert(p);
  2117. int marketCount = 0;
  2118. BOOST_FOREACH(const CGTownInstance *t, p->towns)
  2119. if(t->hasBuilt(BuildingID::MARKETPLACE))
  2120. marketCount++;
  2121. return marketCount;
  2122. }
  2123. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  2124. {
  2125. switch(mode)
  2126. {
  2127. case EMarketMode::RESOURCE_RESOURCE:
  2128. case EMarketMode::RESOURCE_PLAYER:
  2129. return hasBuilt(BuildingID::MARKETPLACE);
  2130. case EMarketMode::ARTIFACT_RESOURCE:
  2131. case EMarketMode::RESOURCE_ARTIFACT:
  2132. return hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::TOWER)
  2133. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::DUNGEON)
  2134. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::CONFLUX);
  2135. case EMarketMode::CREATURE_RESOURCE:
  2136. return hasBuilt(BuildingID::FREELANCERS_GUILD, ETownType::STRONGHOLD);
  2137. case EMarketMode::CREATURE_UNDEAD:
  2138. return hasBuilt(BuildingID::SKELETON_TRANSFORMER, ETownType::NECROPOLIS);
  2139. case EMarketMode::RESOURCE_SKILL:
  2140. return hasBuilt(BuildingID::MAGIC_UNIVERSITY, ETownType::CONFLUX);
  2141. default:
  2142. assert(0);
  2143. return false;
  2144. }
  2145. }
  2146. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  2147. {
  2148. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  2149. {
  2150. std::vector<int> ret;
  2151. BOOST_FOREACH(const CArtifact *a, merchantArtifacts)
  2152. if(a)
  2153. ret.push_back(a->id);
  2154. else
  2155. ret.push_back(-1);
  2156. return ret;
  2157. }
  2158. else if ( mode == EMarketMode::RESOURCE_SKILL )
  2159. {
  2160. return universitySkills;
  2161. }
  2162. else
  2163. return IMarket::availableItemsIds(mode);
  2164. }
  2165. std::string CGTownInstance::nodeName() const
  2166. {
  2167. return "Town (" + (town ? town->faction->name : "unknown") + ") of " + name;
  2168. }
  2169. void CGTownInstance::deserializationFix()
  2170. {
  2171. attachTo(&townAndVis);
  2172. //Hero is already handled by CGameState::attachArmedObjects
  2173. // if(visitingHero)
  2174. // visitingHero->attachTo(&townAndVis);
  2175. // if(garrisonHero)
  2176. // garrisonHero->attachTo(this);
  2177. }
  2178. void CGTownInstance::updateMoraleBonusFromArmy()
  2179. {
  2180. Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY) && Selector::type(Bonus::MORALE));
  2181. if(!b)
  2182. {
  2183. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  2184. addNewBonus(b);
  2185. }
  2186. if (garrisonHero)
  2187. b->val = 0;
  2188. else
  2189. CArmedInstance::updateMoraleBonusFromArmy();
  2190. }
  2191. void CGTownInstance::recreateBuildingsBonuses()
  2192. {
  2193. static TPropagatorPtr playerProp(new CPropagatorNodeType(PLAYER));
  2194. BonusList bl;
  2195. getExportedBonusList().getBonuses(bl, Selector::sourceType(Bonus::TOWN_STRUCTURE));
  2196. BOOST_FOREACH(Bonus *b, bl)
  2197. removeBonus(b);
  2198. //tricky! -> checks tavern only if no bratherhood of sword or not a castle
  2199. if(subID != ETownType::CASTLE || !addBonusIfBuilt(BuildingID::BROTHERHOOD, Bonus::MORALE, +2))
  2200. addBonusIfBuilt(BuildingID::TAVERN, Bonus::MORALE, +1);
  2201. if(subID == ETownType::CASTLE) //castle
  2202. {
  2203. addBonusIfBuilt(BuildingID::LIGHTHOUSE, Bonus::SEA_MOVEMENT, +500, playerProp);
  2204. addBonusIfBuilt(BuildingID::GRAIL, Bonus::MORALE, +2, playerProp); //colossus
  2205. }
  2206. else if(subID == ETownType::RAMPART) //rampart
  2207. {
  2208. addBonusIfBuilt(BuildingID::FOUNTAIN_OF_FORTUNE, Bonus::LUCK, +2); //fountain of fortune
  2209. addBonusIfBuilt(BuildingID::GRAIL, Bonus::LUCK, +2, playerProp); //guardian spirit
  2210. }
  2211. else if(subID == ETownType::TOWER) //tower
  2212. {
  2213. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +15, PrimarySkill::KNOWLEDGE); //grail
  2214. }
  2215. else if(subID == ETownType::INFERNO) //Inferno
  2216. {
  2217. addBonusIfBuilt(BuildingID::STORMCLOUDS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER); //Brimstone Clouds
  2218. }
  2219. else if(subID == ETownType::NECROPOLIS) //necropolis
  2220. {
  2221. addBonusIfBuilt(BuildingID::COVER_OF_DARKNESS, Bonus::DARKNESS, +20);
  2222. addBonusIfBuilt(BuildingID::NECROMANCY_AMPLIFIER, Bonus::SECONDARY_SKILL_PREMY, +10, playerProp, SecondarySkill::NECROMANCY); //necromancy amplifier
  2223. addBonusIfBuilt(BuildingID::GRAIL, Bonus::SECONDARY_SKILL_PREMY, +20, playerProp, SecondarySkill::NECROMANCY); //Soul prison
  2224. }
  2225. else if(subID == ETownType::DUNGEON) //Dungeon
  2226. {
  2227. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +12, PrimarySkill::SPELL_POWER); //grail
  2228. }
  2229. else if(subID == ETownType::STRONGHOLD) //Stronghold
  2230. {
  2231. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +20, PrimarySkill::ATTACK); //grail
  2232. }
  2233. else if(subID == ETownType::FORTRESS) //Fortress
  2234. {
  2235. addBonusIfBuilt(BuildingID::GLYPHS_OF_FEAR, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE); //Glyphs of Fear
  2236. addBonusIfBuilt(BuildingID::BLOOD_OBELISK, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK); //Blood Obelisk
  2237. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::ATTACK); //grail
  2238. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::DEFENSE); //grail
  2239. }
  2240. else if(subID == ETownType::CONFLUX)
  2241. {
  2242. }
  2243. }
  2244. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, int subtype /*= -1*/)
  2245. {
  2246. static auto emptyPropagator = TPropagatorPtr();
  2247. return addBonusIfBuilt(building, type, val, emptyPropagator, subtype);
  2248. }
  2249. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype /*= -1*/)
  2250. {
  2251. if(hasBuilt(building))
  2252. {
  2253. std::ostringstream descr;
  2254. descr << town->buildings[building]->Name() << " ";
  2255. if(val > 0)
  2256. descr << "+";
  2257. else if(val < 0)
  2258. descr << "-";
  2259. descr << val;
  2260. Bonus *b = new Bonus(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, descr.str(), subtype);
  2261. if(prop)
  2262. b->addPropagator(prop);
  2263. addNewBonus(b);
  2264. return true;
  2265. }
  2266. return false;
  2267. }
  2268. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  2269. {
  2270. assert(!!visitingHero == !h);
  2271. if(h)
  2272. {
  2273. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  2274. assert(p);
  2275. h->detachFrom(p);
  2276. h->attachTo(&townAndVis);
  2277. visitingHero = h;
  2278. h->visitedTown = this;
  2279. h->inTownGarrison = false;
  2280. }
  2281. else
  2282. {
  2283. PlayerState *p = cb->gameState()->getPlayer(visitingHero->tempOwner);
  2284. visitingHero->visitedTown = NULL;
  2285. visitingHero->detachFrom(&townAndVis);
  2286. visitingHero->attachTo(p);
  2287. visitingHero = NULL;
  2288. }
  2289. }
  2290. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  2291. {
  2292. assert(!!garrisonHero == !h);
  2293. if(h)
  2294. {
  2295. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  2296. assert(p);
  2297. h->detachFrom(p);
  2298. h->attachTo(this);
  2299. garrisonHero = h;
  2300. h->visitedTown = this;
  2301. h->inTownGarrison = true;
  2302. }
  2303. else
  2304. {
  2305. PlayerState *p = cb->gameState()->getPlayer(garrisonHero->tempOwner);
  2306. garrisonHero->visitedTown = NULL;
  2307. garrisonHero->inTownGarrison = false;
  2308. garrisonHero->detachFrom(this);
  2309. garrisonHero->attachTo(p);
  2310. garrisonHero = NULL;
  2311. }
  2312. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  2313. }
  2314. bool CGTownInstance::armedGarrison() const
  2315. {
  2316. return stacksCount() || garrisonHero;
  2317. }
  2318. CBonusSystemNode * CGTownInstance::whatShouldBeAttached()
  2319. {
  2320. return &townAndVis;
  2321. }
  2322. const CArmedInstance * CGTownInstance::getUpperArmy() const
  2323. {
  2324. if(garrisonHero)
  2325. return garrisonHero;
  2326. return this;
  2327. }
  2328. bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
  2329. {
  2330. if (townID == town->faction->index || townID == ETownType::ANY)
  2331. return hasBuilt(buildingID);
  2332. return false;
  2333. }
  2334. bool CGTownInstance::hasBuilt(BuildingID buildingID) const
  2335. {
  2336. return vstd::contains(builtBuildings, buildingID);
  2337. }
  2338. void CGTownInstance::addHeroToStructureVisitors( const CGHeroInstance *h, si32 structureInstanceID ) const
  2339. {
  2340. if(visitingHero == h)
  2341. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  2342. else if(garrisonHero == h)
  2343. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  2344. else
  2345. {
  2346. //should never ever happen
  2347. logGlobal->errorStream() << "Cannot add hero " << h->name << " to visitors of structure #" << structureInstanceID;
  2348. assert(0);
  2349. }
  2350. }
  2351. void CGTownInstance::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  2352. {
  2353. if(result.winner == 0)
  2354. {
  2355. removeCapitols(hero->getOwner());
  2356. cb->setOwner (this, hero->tempOwner); //give control after checkout is done
  2357. FoWChange fw;
  2358. fw.player = hero->tempOwner;
  2359. fw.mode = 1;
  2360. getSightTiles (fw.tiles); //update visibility for castle structures
  2361. cb->sendAndApply (&fw);
  2362. }
  2363. }
  2364. bool CGVisitableOPH::wasVisited (const CGHeroInstance * h) const
  2365. {
  2366. return vstd::contains(visitors, h->id);
  2367. }
  2368. void CGVisitableOPH::onHeroVisit( const CGHeroInstance * h ) const
  2369. {
  2370. if(!vstd::contains(visitors, h->id))
  2371. {
  2372. onNAHeroVisit (h, false);
  2373. switch(ID)
  2374. {
  2375. case Obj::TREE_OF_KNOWLEDGE:
  2376. case Obj::ARENA:
  2377. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2378. case Obj::SCHOOL_OF_MAGIC:
  2379. case Obj::SCHOOL_OF_WAR:
  2380. break;
  2381. default:
  2382. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2383. break;
  2384. }
  2385. }
  2386. else
  2387. {
  2388. onNAHeroVisit(h, true);
  2389. }
  2390. }
  2391. void CGVisitableOPH::initObj()
  2392. {
  2393. if(ID==Obj::TREE_OF_KNOWLEDGE)
  2394. {
  2395. switch (ran() % 3)
  2396. {
  2397. case 1:
  2398. treePrice[Res::GOLD] = 2000;
  2399. break;
  2400. case 2:
  2401. treePrice[Res::GEMS] = 10;
  2402. break;
  2403. default:
  2404. break;
  2405. }
  2406. }
  2407. }
  2408. void CGVisitableOPH::treeSelected (const CGHeroInstance * h, ui32 result) const
  2409. {
  2410. if(result) //player agreed to give res for exp
  2411. {
  2412. si64 expToGive = VLC->heroh->reqExp(h->level+1) - VLC->heroh->reqExp(h->level);;
  2413. cb->giveResources (h->getOwner(), -treePrice);
  2414. cb->changePrimSkill (h, PrimarySkill::EXPERIENCE, expToGive);
  2415. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2416. }
  2417. }
  2418. void CGVisitableOPH::onNAHeroVisit (const CGHeroInstance * h, bool alreadyVisited) const
  2419. {
  2420. Component::EComponentType c_id = Component::PRIM_SKILL; //most used here
  2421. int subid=0, ot=0, sound = 0;
  2422. TExpType val=1;
  2423. switch(ID)
  2424. {
  2425. case Obj::ARENA:
  2426. sound = soundBase::NOMAD;
  2427. ot = 0;
  2428. break;
  2429. case Obj::MERCENARY_CAMP:
  2430. sound = soundBase::NOMAD;
  2431. subid=PrimarySkill::ATTACK;
  2432. ot=80;
  2433. break;
  2434. case Obj::MARLETTO_TOWER:
  2435. sound = soundBase::NOMAD;
  2436. subid=PrimarySkill::DEFENSE;
  2437. ot=39;
  2438. break;
  2439. case Obj::STAR_AXIS:
  2440. sound = soundBase::gazebo;
  2441. subid=PrimarySkill::SPELL_POWER;
  2442. ot=100;
  2443. break;
  2444. case Obj::GARDEN_OF_REVELATION:
  2445. sound = soundBase::GETPROTECTION;
  2446. subid=PrimarySkill::KNOWLEDGE;
  2447. ot=59;
  2448. break;
  2449. case Obj::LEARNING_STONE:
  2450. sound = soundBase::gazebo;
  2451. c_id=Component::EXPERIENCE;
  2452. ot=143;
  2453. val=1000;
  2454. break;
  2455. case Obj::TREE_OF_KNOWLEDGE:
  2456. sound = soundBase::gazebo;
  2457. c_id = Component::EXPERIENCE;
  2458. subid = 1;
  2459. ot = 147;
  2460. val = 1;
  2461. break;
  2462. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2463. sound = soundBase::gazebo;
  2464. ot = 66;
  2465. break;
  2466. case Obj::SCHOOL_OF_MAGIC:
  2467. sound = soundBase::faerie;
  2468. ot = 71;
  2469. break;
  2470. case Obj::SCHOOL_OF_WAR:
  2471. c_id=Component::PRIM_SKILL;
  2472. sound = soundBase::MILITARY;
  2473. ot = 158;
  2474. break;
  2475. }
  2476. if (!alreadyVisited)
  2477. {
  2478. switch (ID)
  2479. {
  2480. case Obj::ARENA:
  2481. {
  2482. BlockingDialog sd(false,true);
  2483. sd.soundID = sound;
  2484. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2485. sd.components.push_back(Component(c_id, PrimarySkill::ATTACK, 2, 0));
  2486. sd.components.push_back(Component(c_id, PrimarySkill::DEFENSE, 2, 0));
  2487. sd.player = h->getOwner();
  2488. cb->showBlockingDialog(&sd);
  2489. return;
  2490. }
  2491. case Obj::MERCENARY_CAMP:
  2492. case Obj::MARLETTO_TOWER:
  2493. case Obj::STAR_AXIS:
  2494. case Obj::GARDEN_OF_REVELATION:
  2495. {
  2496. cb->changePrimSkill (h, static_cast<PrimarySkill::PrimarySkill>(subid), val);
  2497. InfoWindow iw;
  2498. iw.soundID = sound;
  2499. iw.components.push_back(Component(c_id, subid, val, 0));
  2500. iw.text.addTxt(MetaString::ADVOB_TXT,ot);
  2501. iw.player = h->getOwner();
  2502. cb->showInfoDialog(&iw);
  2503. break;
  2504. }
  2505. case Obj::LEARNING_STONE: //give exp
  2506. {
  2507. val = h->calculateXp(val);
  2508. InfoWindow iw;
  2509. iw.soundID = sound;
  2510. iw.components.push_back (Component(c_id,subid,val,0));
  2511. iw.player = h->getOwner();
  2512. iw.text.addTxt(MetaString::ADVOB_TXT,ot);
  2513. cb->showInfoDialog(&iw);
  2514. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, val);
  2515. break;
  2516. }
  2517. case Obj::TREE_OF_KNOWLEDGE:
  2518. {
  2519. val = VLC->heroh->reqExp (h->level + val) - VLC->heroh->reqExp(h->level);
  2520. if(!treePrice.nonZero())
  2521. {
  2522. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2523. InfoWindow iw;
  2524. iw.soundID = sound;
  2525. iw.components.push_back (Component(c_id,subid,1,0));
  2526. iw.player = h->getOwner();
  2527. iw.text.addTxt (MetaString::ADVOB_TXT,148);
  2528. cb->showInfoDialog (&iw);
  2529. cb->changePrimSkill (h, PrimarySkill::EXPERIENCE, val);
  2530. break;
  2531. }
  2532. else
  2533. {
  2534. if(treePrice[Res::GOLD] > 0)
  2535. ot = 149;
  2536. else
  2537. ot = 151;
  2538. if(!cb->getPlayer(h->tempOwner)->resources.canAfford(treePrice)) //not enough resources
  2539. {
  2540. ot++;
  2541. showInfoDialog(h,ot,sound);
  2542. return;
  2543. }
  2544. BlockingDialog sd (true, false);
  2545. sd.soundID = sound;
  2546. sd.player = h->getOwner();
  2547. sd.text.addTxt (MetaString::ADVOB_TXT,ot);
  2548. sd.addResourceComponents (treePrice);
  2549. cb->showBlockingDialog (&sd);
  2550. }
  2551. break;
  2552. }
  2553. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2554. {
  2555. int txt_id = 66;
  2556. if(h->level < 10 - 2*h->getSecSkillLevel(SecondarySkill::DIPLOMACY)) //not enough level
  2557. {
  2558. txt_id += 2;
  2559. }
  2560. else
  2561. {
  2562. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2563. cb->changePrimSkill (h, PrimarySkill::ATTACK, 2);
  2564. cb->changePrimSkill (h, PrimarySkill::DEFENSE, 2);
  2565. cb->changePrimSkill (h, PrimarySkill::KNOWLEDGE, 2);
  2566. cb->changePrimSkill (h, PrimarySkill::SPELL_POWER, 2);
  2567. }
  2568. showInfoDialog(h,txt_id,sound);
  2569. break;
  2570. }
  2571. case Obj::SCHOOL_OF_MAGIC:
  2572. case Obj::SCHOOL_OF_WAR:
  2573. {
  2574. int skill = (ID==Obj::SCHOOL_OF_MAGIC ? 2 : 0);
  2575. if (cb->getResource (h->getOwner(), Res::GOLD) < 1000) //not enough resources
  2576. {
  2577. showInfoDialog (h->getOwner(), ot+2, sound);
  2578. }
  2579. else
  2580. {
  2581. BlockingDialog sd(true,true);
  2582. sd.soundID = sound;
  2583. sd.player = h->getOwner();
  2584. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2585. sd.components.push_back(Component(c_id, skill, +1, 0));
  2586. sd.components.push_back(Component(c_id, skill+1, +1, 0));
  2587. cb->showBlockingDialog(&sd);
  2588. }
  2589. }
  2590. break;
  2591. }
  2592. }
  2593. else
  2594. {
  2595. ot++;
  2596. showInfoDialog (h->getOwner(),ot,sound);
  2597. }
  2598. }
  2599. const std::string & CGVisitableOPH::getHoverText() const
  2600. {
  2601. int pom = -1;
  2602. switch(ID)
  2603. {
  2604. case Obj::ARENA:
  2605. pom = -1;
  2606. break;
  2607. case Obj::MERCENARY_CAMP:
  2608. pom = 8;
  2609. break;
  2610. case Obj::MARLETTO_TOWER:
  2611. pom = 7;
  2612. break;
  2613. case Obj::STAR_AXIS:
  2614. pom = 11;
  2615. break;
  2616. case Obj::GARDEN_OF_REVELATION:
  2617. pom = 4;
  2618. break;
  2619. case Obj::LEARNING_STONE:
  2620. pom = 5;
  2621. break;
  2622. case Obj::TREE_OF_KNOWLEDGE:
  2623. pom = 18;
  2624. break;
  2625. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2626. break;
  2627. case Obj::SCHOOL_OF_MAGIC:
  2628. pom = 9;
  2629. break;
  2630. case Obj::SCHOOL_OF_WAR:
  2631. pom = 10;
  2632. break;
  2633. default:
  2634. throw std::runtime_error("Wrong CGVisitableOPH object ID!\n");
  2635. }
  2636. hoverName = VLC->generaltexth->names[ID];
  2637. if(pom >= 0)
  2638. hoverName += ("\n" + VLC->generaltexth->xtrainfo[pom]);
  2639. const CGHeroInstance *h = cb->getSelectedHero (cb->getCurrentPlayer());
  2640. if(h)
  2641. {
  2642. hoverName += "\n\n";
  2643. bool visited = vstd::contains (visitors, h->id);
  2644. hoverName += visitedTxt (visited);
  2645. }
  2646. return hoverName;
  2647. }
  2648. void CGVisitableOPH::arenaSelected(const CGHeroInstance * h, int primSkill ) const
  2649. {
  2650. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2651. cb->changePrimSkill(h, static_cast<PrimarySkill::PrimarySkill>(primSkill-1), 2);
  2652. }
  2653. void CGVisitableOPH::setPropertyDer( ui8 what, ui32 val )
  2654. {
  2655. if(what == ObjProperty::VISITORS)
  2656. visitors.insert(ObjectInstanceID(val));
  2657. }
  2658. void CGVisitableOPH::schoolSelected(const CGHeroInstance * h, ui32 which) const
  2659. {
  2660. if(!which) //player refused to pay
  2661. return;
  2662. int base = (ID == Obj::SCHOOL_OF_MAGIC ? 2 : 0);
  2663. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2664. cb->giveResource (h->getOwner(),Res::GOLD,-1000); //take 1000 gold
  2665. cb->changePrimSkill (h, static_cast<PrimarySkill::PrimarySkill>(base + which-1), +1); //give appropriate skill
  2666. }
  2667. void CGVisitableOPH::blockingDialogAnswered(const CGHeroInstance *h, ui32 answer) const
  2668. {
  2669. switch (ID)
  2670. {
  2671. case Obj::ARENA:
  2672. arenaSelected(h, answer);
  2673. break;
  2674. case Obj::TREE_OF_KNOWLEDGE:
  2675. treeSelected(h, answer);
  2676. break;
  2677. case Obj::SCHOOL_OF_MAGIC:
  2678. case Obj::SCHOOL_OF_WAR:
  2679. schoolSelected(h, answer);
  2680. break;
  2681. default:
  2682. assert(0);
  2683. break;
  2684. }
  2685. }
  2686. COPWBonus::COPWBonus (BuildingID index, CGTownInstance *TOWN)
  2687. {
  2688. ID = index;
  2689. town = TOWN;
  2690. id = town->bonusingBuildings.size();
  2691. }
  2692. void COPWBonus::setProperty(ui8 what, ui32 val)
  2693. {
  2694. switch (what)
  2695. {
  2696. case ObjProperty::VISITORS:
  2697. visitors.insert(val);
  2698. break;
  2699. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  2700. visitors.clear();
  2701. break;
  2702. }
  2703. }
  2704. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  2705. {
  2706. ObjectInstanceID heroID = h->id;
  2707. if (town->hasBuilt(ID))
  2708. {
  2709. InfoWindow iw;
  2710. iw.player = h->tempOwner;
  2711. switch (town->subID)
  2712. {
  2713. case ETownType::CASTLE: //Stables
  2714. if (!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  2715. {
  2716. GiveBonus gb;
  2717. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  2718. gb.id = heroID.getNum();
  2719. cb->giveHeroBonus(&gb);
  2720. iw.text << VLC->generaltexth->allTexts[580];
  2721. cb->showInfoDialog(&iw);
  2722. }
  2723. break;
  2724. case ETownType::DUNGEON: //Mana Vortex
  2725. if (visitors.empty() && h->mana <= h->manaLimit() * 2)
  2726. {
  2727. cb->setManaPoints (heroID, 2 * h->manaLimit());
  2728. //TODO: investigate line below
  2729. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  2730. iw.text << VLC->generaltexth->allTexts[579];
  2731. cb->showInfoDialog(&iw);
  2732. town->addHeroToStructureVisitors(h, id);
  2733. }
  2734. break;
  2735. }
  2736. }
  2737. }
  2738. CTownBonus::CTownBonus (BuildingID index, CGTownInstance *TOWN)
  2739. {
  2740. ID = index;
  2741. town = TOWN;
  2742. id = town->bonusingBuildings.size();
  2743. }
  2744. void CTownBonus::setProperty (ui8 what, ui32 val)
  2745. {
  2746. if(what == ObjProperty::VISITORS)
  2747. visitors.insert(ObjectInstanceID(val));
  2748. }
  2749. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  2750. {
  2751. ObjectInstanceID heroID = h->id;
  2752. if (town->hasBuilt(ID) && visitors.find(heroID) == visitors.end())
  2753. {
  2754. InfoWindow iw;
  2755. PrimarySkill::PrimarySkill what = PrimarySkill::ATTACK;
  2756. int val=0, mid=0;
  2757. switch (ID)
  2758. {
  2759. case BuildingID::SPECIAL_4:
  2760. switch(town->subID)
  2761. {
  2762. case ETownType::TOWER: //wall
  2763. what = PrimarySkill::KNOWLEDGE;
  2764. val = 1;
  2765. mid = 581;
  2766. iw.components.push_back (Component(Component::PRIM_SKILL, 3, 1, 0));
  2767. break;
  2768. case ETownType::INFERNO: //order of fire
  2769. what = PrimarySkill::SPELL_POWER;
  2770. val = 1;
  2771. mid = 582;
  2772. iw.components.push_back (Component(Component::PRIM_SKILL, 2, 1, 0));
  2773. break;
  2774. case ETownType::STRONGHOLD://hall of Valhalla
  2775. what = PrimarySkill::ATTACK;
  2776. val = 1;
  2777. mid = 584;
  2778. iw.components.push_back (Component(Component::PRIM_SKILL, 0, 1, 0));
  2779. break;
  2780. case ETownType::DUNGEON://academy of battle scholars
  2781. what = PrimarySkill::EXPERIENCE;
  2782. val = h->calculateXp(1000);
  2783. mid = 583;
  2784. iw.components.push_back (Component(Component::EXPERIENCE, 0, val, 0));
  2785. break;
  2786. }
  2787. break;
  2788. case BuildingID::SPECIAL_1:
  2789. switch(town->subID)
  2790. {
  2791. case ETownType::FORTRESS: //cage of warlords
  2792. what = PrimarySkill::DEFENSE;
  2793. val = 1;
  2794. mid = 585;
  2795. iw.components.push_back (Component(Component::PRIM_SKILL, 1, 1, 0));
  2796. break;
  2797. }
  2798. break;
  2799. }
  2800. assert(mid);
  2801. iw.player = cb->getOwner(heroID);
  2802. iw.text << VLC->generaltexth->allTexts[mid];
  2803. cb->showInfoDialog(&iw);
  2804. cb->changePrimSkill (cb->getHero(heroID), what, val);
  2805. town->addHeroToStructureVisitors(h, id);
  2806. }
  2807. }
  2808. const std::string & CGCreature::getHoverText() const
  2809. {
  2810. if(stacks.empty())
  2811. {
  2812. static const std::string errorValue("!!!INVALID_STACK!!!");
  2813. //should not happen...
  2814. logGlobal->errorStream() << "Invalid stack at tile " << pos << ": subID=" << subID << "; id=" << id;
  2815. return errorValue; // references to temporary are illegal - use pre-constructed string
  2816. }
  2817. MetaString ms;
  2818. int pom = stacks.begin()->second->getQuantityID();
  2819. pom = 172 + 3*pom;
  2820. ms.addTxt(MetaString::ARRAY_TXT,pom);
  2821. ms << " " ;
  2822. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  2823. ms.toString(hoverName);
  2824. if(const CGHeroInstance *selHero = cb->getSelectedHero(cb->getCurrentPlayer()))
  2825. {
  2826. std::vector<std::string> * texts = &VLC->generaltexth->threat;
  2827. hoverName += "\n\n ";
  2828. hoverName += (*texts)[0];
  2829. int choice;
  2830. double ratio = ((double)getArmyStrength() / selHero->getTotalStrength());
  2831. if (ratio < 0.1) choice = 1;
  2832. else if (ratio < 0.25) choice = 2;
  2833. else if (ratio < 0.6) choice = 3;
  2834. else if (ratio < 0.9) choice = 4;
  2835. else if (ratio < 1.1) choice = 5;
  2836. else if (ratio < 1.3) choice = 6;
  2837. else if (ratio < 1.8) choice = 7;
  2838. else if (ratio < 2.5) choice = 8;
  2839. else if (ratio < 4) choice = 9;
  2840. else if (ratio < 8) choice = 10;
  2841. else if (ratio < 20) choice = 11;
  2842. else choice = 12;
  2843. hoverName += (*texts)[choice];
  2844. }
  2845. return hoverName;
  2846. }
  2847. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  2848. {
  2849. int action = takenAction(h);
  2850. switch( action ) //decide what we do...
  2851. {
  2852. case FIGHT:
  2853. fight(h);
  2854. break;
  2855. case FLEE: //flee
  2856. {
  2857. flee(h);
  2858. break;
  2859. }
  2860. case JOIN_FOR_FREE: //join for free
  2861. {
  2862. BlockingDialog ynd(true,false);
  2863. ynd.player = h->tempOwner;
  2864. ynd.text.addTxt(MetaString::ADVOB_TXT, 86);
  2865. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  2866. cb->showBlockingDialog(&ynd);
  2867. break;
  2868. }
  2869. default: //join for gold
  2870. {
  2871. assert(action > 0);
  2872. //ask if player agrees to pay gold
  2873. BlockingDialog ynd(true,false);
  2874. ynd.player = h->tempOwner;
  2875. std::string tmp = VLC->generaltexth->advobtxt[90];
  2876. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(getStackCount(SlotID(0))));
  2877. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(action));
  2878. boost::algorithm::replace_first(tmp,"%s",VLC->creh->creatures[subID]->namePl);
  2879. ynd.text << tmp;
  2880. cb->showBlockingDialog(&ynd);
  2881. break;
  2882. }
  2883. }
  2884. }
  2885. void CGCreature::initObj()
  2886. {
  2887. blockVisit = true;
  2888. switch(character)
  2889. {
  2890. case 0:
  2891. character = -4;
  2892. break;
  2893. case 1:
  2894. character = 1 + ran()%7;
  2895. break;
  2896. case 2:
  2897. character = 1 + ran()%10;
  2898. break;
  2899. case 3:
  2900. character = 4 + ran()%7;
  2901. break;
  2902. case 4:
  2903. character = 10;
  2904. break;
  2905. }
  2906. stacks[SlotID(0)]->setType(CreatureID(subID));
  2907. TQuantity &amount = stacks[SlotID(0)]->count;
  2908. CCreature &c = *VLC->creh->creatures[subID];
  2909. if(!amount)
  2910. {
  2911. if(c.ammMax == c.ammMin)
  2912. amount = c.ammMax;
  2913. else
  2914. amount = c.ammMin + (ran() % (c.ammMax - c.ammMin));
  2915. if(!amount) //armies with 0 creatures are illegal
  2916. {
  2917. logGlobal->warnStream() << "Problem: stack " << nodeName() << " cannot have 0 creatures. Check properties of " << c.nodeName();
  2918. amount = 1;
  2919. }
  2920. }
  2921. temppower = stacks[SlotID(0)]->count * 1000;
  2922. refusedJoining = false;
  2923. }
  2924. void CGCreature::newTurn() const
  2925. {//Works only for stacks of single type of size up to 2 millions
  2926. if (stacks.begin()->second->count < VLC->modh->settings.CREEP_SIZE && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  2927. {
  2928. ui32 power = temppower * (100 + VLC->modh->settings.WEEKLY_GROWTH)/100;
  2929. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min (power/1000 , (ui32)VLC->modh->settings.CREEP_SIZE)); //set new amount
  2930. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  2931. }
  2932. if (VLC->modh->modules.STACK_EXP)
  2933. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->modh->settings.NEUTRAL_STACK_EXP); //for testing purpose
  2934. }
  2935. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  2936. {
  2937. switch (what)
  2938. {
  2939. case ObjProperty::MONSTER_COUNT:
  2940. stacks[SlotID(0)]->count = val;
  2941. break;
  2942. case ObjProperty::MONSTER_POWER:
  2943. temppower = val;
  2944. break;
  2945. case ObjProperty::MONSTER_EXP:
  2946. giveStackExp(val);
  2947. break;
  2948. case ObjProperty::MONSTER_RESTORE_TYPE:
  2949. restore.basicType = val;
  2950. break;
  2951. case ObjProperty::MONSTER_REFUSED_JOIN:
  2952. refusedJoining = val;
  2953. break;
  2954. }
  2955. }
  2956. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  2957. {
  2958. //calculate relative strength of hero and creatures armies
  2959. double relStrength = double(h->getTotalStrength()) / getArmyStrength();
  2960. int powerFactor;
  2961. if(relStrength >= 7)
  2962. powerFactor = 11;
  2963. else if(relStrength >= 1)
  2964. powerFactor = (int)(2*(relStrength-1));
  2965. else if(relStrength >= 0.5)
  2966. powerFactor = -1;
  2967. else if(relStrength >= 0.333)
  2968. powerFactor = -2;
  2969. else
  2970. powerFactor = -3;
  2971. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  2972. const CCreature * myCreature = VLC->creh->creatures[subID];
  2973. myKindCres.insert(myCreature->idNumber); //we
  2974. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  2975. BOOST_FOREACH(ConstTransitivePtr<CCreature> &crea, VLC->creh->creatures)
  2976. {
  2977. if(vstd::contains(crea->upgrades, myCreature->idNumber)) //it's our base creatures
  2978. myKindCres.insert(crea->idNumber);
  2979. }
  2980. int count = 0, //how many creatures of similar kind has hero
  2981. totalCount = 0;
  2982. for (TSlots::const_iterator i = h->Slots().begin(); i != h->Slots().end(); i++)
  2983. {
  2984. if(vstd::contains(myKindCres,i->second->type->idNumber))
  2985. count += i->second->count;
  2986. totalCount += i->second->count;
  2987. }
  2988. int sympathy = 0; // 0 if hero have no similar creatures
  2989. if(count)
  2990. sympathy++; // 1 - if hero have at least 1 similar creature
  2991. if(count*2 > totalCount)
  2992. sympathy++; // 2 - hero have similar creatures more that 50%
  2993. int charisma = powerFactor + h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy;
  2994. if(charisma < character) //creatures will fight
  2995. return -2;
  2996. if (allowJoin)
  2997. {
  2998. if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy + 1 >= character)
  2999. return 0; //join for free
  3000. else if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) * 2 + sympathy + 1 >= character)
  3001. return VLC->creh->creatures[subID]->cost[6] * getStackCount(SlotID(0)); //join for gold
  3002. }
  3003. //we are still here - creatures have not joined hero, flee or fight
  3004. if (charisma > character)
  3005. return -1; //flee
  3006. else
  3007. return -2; //fight
  3008. }
  3009. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  3010. {
  3011. if(refusedJoining)
  3012. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  3013. if(pursue)
  3014. {
  3015. fight(h);
  3016. }
  3017. else
  3018. {
  3019. cb->removeObject(this);
  3020. }
  3021. }
  3022. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  3023. {
  3024. if(!accept)
  3025. {
  3026. if(takenAction(h,false) == -1) //they flee
  3027. {
  3028. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  3029. flee(h);
  3030. }
  3031. else //they fight
  3032. {
  3033. showInfoDialog(h,87,0);//Insulted by your refusal of their offer, the monsters attack!
  3034. fight(h);
  3035. }
  3036. }
  3037. else //accepted
  3038. {
  3039. if (cb->getResource(h->tempOwner, Res::GOLD) < cost) //player don't have enough gold!
  3040. {
  3041. InfoWindow iw;
  3042. iw.player = h->tempOwner;
  3043. iw.text << std::pair<ui8,ui32>(1,29); //You don't have enough gold
  3044. cb->showInfoDialog(&iw);
  3045. //act as if player refused
  3046. joinDecision(h,cost,false);
  3047. return;
  3048. }
  3049. //take gold
  3050. if(cost)
  3051. cb->giveResource(h->tempOwner,Res::GOLD,-cost);
  3052. cb->tryJoiningArmy(this, h, true, true);
  3053. }
  3054. }
  3055. void CGCreature::fight( const CGHeroInstance *h ) const
  3056. {
  3057. //split stacks
  3058. //TODO: multiple creature types in a stack?
  3059. int basicType = stacks.begin()->second->type->idNumber;
  3060. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  3061. double relativePower = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  3062. int stacksCount;
  3063. //TODO: number depends on tile type
  3064. if (relativePower < 0.5)
  3065. {
  3066. stacksCount = 7;
  3067. }
  3068. else if (relativePower < 0.67)
  3069. {
  3070. stacksCount = 7;
  3071. }
  3072. else if (relativePower < 1)
  3073. {
  3074. stacksCount = 6;
  3075. }
  3076. else if (relativePower < 1.5)
  3077. {
  3078. stacksCount = 5;
  3079. }
  3080. else if (relativePower < 2)
  3081. {
  3082. stacksCount = 4;
  3083. }
  3084. else
  3085. {
  3086. stacksCount = 3;
  3087. }
  3088. int stackSize;
  3089. SlotID sourceSlot = stacks.begin()->first;
  3090. SlotID destSlot;
  3091. for (int stacksLeft = stacksCount; stacksLeft > 1; --stacksLeft)
  3092. {
  3093. stackSize = stacks.begin()->second->count / stacksLeft;
  3094. if (stackSize)
  3095. {
  3096. if ((destSlot = getFreeSlot()).validSlot())
  3097. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, destSlot), stackSize);
  3098. else
  3099. {
  3100. logGlobal->warnStream() <<"Warning! Not enough empty slots to split stack!";
  3101. break;
  3102. }
  3103. }
  3104. else break;
  3105. }
  3106. if (stacksCount > 1)
  3107. {
  3108. if (rand()%100 < 50) //upgrade
  3109. {
  3110. SlotID slotId = SlotID(stacks.size() / 2);
  3111. if(ui32 upgradesSize = getStack(slotId).type->upgrades.size())
  3112. {
  3113. auto it = getStack(slotId).type->upgrades.cbegin(); //pick random in case there are more
  3114. std::advance (it, rand() % upgradesSize);
  3115. cb->changeStackType(StackLocation(this, slotId), VLC->creh->creatures[*it]);
  3116. }
  3117. }
  3118. }
  3119. cb->startBattleI(h, this);
  3120. }
  3121. void CGCreature::flee( const CGHeroInstance * h ) const
  3122. {
  3123. BlockingDialog ynd(true,false);
  3124. ynd.player = h->tempOwner;
  3125. ynd.text.addTxt(MetaString::ADVOB_TXT,91);
  3126. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  3127. cb->showBlockingDialog(&ynd);
  3128. }
  3129. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3130. {
  3131. if(result.winner==0)
  3132. {
  3133. cb->removeObject(this);
  3134. }
  3135. else
  3136. {
  3137. //int killedAmount=0;
  3138. //for(std::set<std::pair<ui32,si32> >::iterator i=result->casualties[1].begin(); i!=result->casualties[1].end(); i++)
  3139. // if(i->first == subID)
  3140. // killedAmount += i->second;
  3141. //cb->setAmount(id, slots.find(0)->second.second - killedAmount);
  3142. /*
  3143. MetaString ms;
  3144. int pom = slots.find(0)->second.getQuantityID();
  3145. pom = 174 + 3*pom + 1;
  3146. ms << std::pair<ui8,ui32>(6,pom) << " " << std::pair<ui8,ui32>(7,subID);
  3147. cb->setHoverName(id,&ms);
  3148. cb->setObjProperty(id, 11, slots.begin()->second.count * 1000);
  3149. */
  3150. //merge stacks into one
  3151. TSlots::const_iterator i;
  3152. CCreature * cre = VLC->creh->creatures[restore.basicType];
  3153. for (i = stacks.begin(); i != stacks.end(); i++)
  3154. {
  3155. if (cre->isMyUpgrade(i->second->type))
  3156. {
  3157. cb->changeStackType (StackLocation(this, i->first), cre); //un-upgrade creatures
  3158. }
  3159. }
  3160. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  3161. if(!hasStackAtSlot(SlotID(0)))
  3162. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  3163. while (stacks.size() > 1) //hopefully that's enough
  3164. {
  3165. // TODO it's either overcomplicated (if we assume there'll be only one stack) or buggy (if we allow multiple stacks... but that'll also cause troubles elsewhere)
  3166. i = stacks.end();
  3167. i--;
  3168. SlotID slot = getSlotFor(i->second->type);
  3169. if (slot == i->first) //no reason to move stack to its own slot
  3170. break;
  3171. else
  3172. cb->moveStack (StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  3173. }
  3174. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  3175. }
  3176. }
  3177. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3178. {
  3179. auto action = takenAction(hero);
  3180. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  3181. joinDecision(hero, action, answer);
  3182. else if(action != FIGHT)
  3183. fleeDecision(hero, answer);
  3184. else
  3185. assert(0);
  3186. }
  3187. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  3188. {
  3189. int relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  3190. if(relations == 2) //we're visiting our mine
  3191. {
  3192. cb->showGarrisonDialog(id,h->id,true);
  3193. return;
  3194. }
  3195. else if (relations == 1)//ally
  3196. return;
  3197. if(stacksCount()) //Mine is guarded
  3198. {
  3199. BlockingDialog ynd(true,false);
  3200. ynd.player = h->tempOwner;
  3201. ynd.text.addTxt(MetaString::ADVOB_TXT, subID == 7 ? 84 : 187);
  3202. cb->showBlockingDialog(&ynd);
  3203. return;
  3204. }
  3205. flagMine(h->tempOwner);
  3206. }
  3207. void CGMine::newTurn() const
  3208. {
  3209. if(cb->getDate() == 1)
  3210. return;
  3211. if (tempOwner == PlayerColor::NEUTRAL)
  3212. return;
  3213. cb->giveResource(tempOwner, producedResource, producedQuantity);
  3214. }
  3215. void CGMine::initObj()
  3216. {
  3217. if(subID >= 7) //Abandoned Mine
  3218. {
  3219. //set guardians
  3220. int howManyTroglodytes = 100 + ran()%100;
  3221. CStackInstance *troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  3222. putStack(SlotID(0), troglodytes);
  3223. //after map reading tempOwner placeholds bitmask for allowed resources
  3224. std::vector<Res::ERes> possibleResources;
  3225. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  3226. if(tempOwner.getNum() & 1<<i) //NOTE: reuse of tempOwner
  3227. possibleResources.push_back(static_cast<Res::ERes>(i));
  3228. assert(possibleResources.size());
  3229. producedResource = possibleResources[ran()%possibleResources.size()];
  3230. tempOwner = PlayerColor::NEUTRAL;
  3231. hoverName = VLC->generaltexth->mines[7].first + "\n" + VLC->generaltexth->allTexts[202] + " " + troglodytes->getQuantityTXT(false) + " " + troglodytes->type->namePl;
  3232. }
  3233. else
  3234. {
  3235. producedResource = static_cast<Res::ERes>(subID);
  3236. MetaString ms;
  3237. ms << std::pair<ui8,ui32>(9,producedResource);
  3238. if(tempOwner >= PlayerColor::PLAYER_LIMIT)
  3239. tempOwner = PlayerColor::NEUTRAL;
  3240. else
  3241. ms << " (" << std::pair<ui8,ui32>(6,23+tempOwner.getNum()) << ")";
  3242. ms.toString(hoverName);
  3243. }
  3244. producedQuantity = defaultResProduction();
  3245. }
  3246. void CGMine::flagMine(PlayerColor player) const
  3247. {
  3248. assert(tempOwner != player);
  3249. cb->setOwner(this, player); //not ours? flag it!
  3250. MetaString ms;
  3251. ms << std::pair<ui8,ui32>(9,subID) << "\n(" << std::pair<ui8,ui32>(6,23+player.getNum()) << ")";
  3252. if(subID == 7)
  3253. {
  3254. ms << "(%s)";
  3255. ms.addReplacement(MetaString::RES_NAMES, producedResource);
  3256. }
  3257. cb->setHoverName(this,&ms);
  3258. InfoWindow iw;
  3259. iw.soundID = soundBase::FLAGMINE;
  3260. iw.text.addTxt(MetaString::MINE_EVNTS,producedResource); //not use subID, abandoned mines uses default mine texts
  3261. iw.player = player;
  3262. iw.components.push_back(Component(Component::RESOURCE,producedResource,producedQuantity,-1));
  3263. cb->showInfoDialog(&iw);
  3264. }
  3265. ui32 CGMine::defaultResProduction()
  3266. {
  3267. switch(producedResource)
  3268. {
  3269. case Res::WOOD:
  3270. case Res::ORE:
  3271. return 2;
  3272. case Res::GOLD:
  3273. return 1000;
  3274. default:
  3275. return 1;
  3276. }
  3277. }
  3278. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3279. {
  3280. if(result.winner == 0) //attacker won
  3281. {
  3282. if(subID == 7)
  3283. {
  3284. showInfoDialog(hero->tempOwner, 85, 0);
  3285. }
  3286. flagMine(hero->tempOwner);
  3287. }
  3288. }
  3289. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3290. {
  3291. if(answer)
  3292. cb->startBattleI(hero, this);
  3293. }
  3294. void CGResource::initObj()
  3295. {
  3296. blockVisit = true;
  3297. hoverName = VLC->generaltexth->restypes[subID];
  3298. if(!amount)
  3299. {
  3300. switch(subID)
  3301. {
  3302. case 6:
  3303. amount = 500 + (ran()%6)*100;
  3304. break;
  3305. case 0: case 2:
  3306. amount = 6 + (ran()%5);
  3307. break;
  3308. default:
  3309. amount = 3 + (ran()%3);
  3310. break;
  3311. }
  3312. }
  3313. }
  3314. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  3315. {
  3316. if(stacksCount())
  3317. {
  3318. if(message.size())
  3319. {
  3320. BlockingDialog ynd(true,false);
  3321. ynd.player = h->getOwner();
  3322. ynd.text << message;
  3323. cb->showBlockingDialog(&ynd);
  3324. }
  3325. else
  3326. {
  3327. blockingDialogAnswered(h, true); //behave as if player accepted battle
  3328. }
  3329. }
  3330. else
  3331. {
  3332. if(message.length())
  3333. {
  3334. InfoWindow iw;
  3335. iw.player = h->tempOwner;
  3336. iw.text << message;
  3337. cb->showInfoDialog(&iw);
  3338. }
  3339. collectRes(h->getOwner());
  3340. }
  3341. }
  3342. void CGResource::collectRes( PlayerColor player ) const
  3343. {
  3344. cb->giveResource(player, static_cast<Res::ERes>(subID), amount);
  3345. ShowInInfobox sii;
  3346. sii.player = player;
  3347. sii.c = Component(Component::RESOURCE,subID,amount,0);
  3348. sii.text.addTxt(MetaString::ADVOB_TXT,113);
  3349. sii.text.addReplacement(MetaString::RES_NAMES, subID);
  3350. cb->showCompInfo(&sii);
  3351. cb->removeObject(this);
  3352. }
  3353. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3354. {
  3355. if(result.winner == 0) //attacker won
  3356. collectRes(hero->getOwner());
  3357. }
  3358. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3359. {
  3360. if(answer)
  3361. cb->startBattleI(hero, this);
  3362. }
  3363. void CGVisitableOPW::newTurn() const
  3364. {
  3365. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //first day of week = 1
  3366. {
  3367. cb->setObjProperty(id, ObjProperty::VISITED, false);
  3368. MetaString ms; //set text to "not visited"
  3369. ms << std::pair<ui8,ui32>(3,ID) << " " << std::pair<ui8,ui32>(1,353);
  3370. cb->setHoverName(this,&ms);
  3371. }
  3372. }
  3373. bool CGVisitableOPW::wasVisited(PlayerColor player) const
  3374. {
  3375. return visited; //TODO: other players should see object as unvisited
  3376. }
  3377. void CGVisitableOPW::onHeroVisit( const CGHeroInstance * h ) const
  3378. {
  3379. int mid=0, sound = 0;
  3380. switch (ID)
  3381. {
  3382. case Obj::MYSTICAL_GARDEN:
  3383. sound = soundBase::experience;
  3384. mid = 92;
  3385. break;
  3386. case Obj::WINDMILL:
  3387. sound = soundBase::GENIE;
  3388. mid = 170;
  3389. break;
  3390. case Obj::WATER_WHEEL:
  3391. sound = soundBase::GENIE;
  3392. mid = 164;
  3393. break;
  3394. default:
  3395. assert(0);
  3396. }
  3397. if (visited)
  3398. {
  3399. if (ID!=Obj::WINDMILL)
  3400. mid++;
  3401. else
  3402. mid--;
  3403. showInfoDialog(h,mid,sound);
  3404. }
  3405. else
  3406. {
  3407. Component::EComponentType type = Component::RESOURCE;
  3408. Res::ERes sub=Res::WOOD;
  3409. int val=0;
  3410. switch (ID)
  3411. {
  3412. case Obj::MYSTICAL_GARDEN:
  3413. if (rand()%2)
  3414. {
  3415. sub = Res::GEMS;
  3416. val = 5;
  3417. }
  3418. else
  3419. {
  3420. sub = Res::GOLD;
  3421. val = 500;
  3422. }
  3423. break;
  3424. case Obj::WINDMILL:
  3425. mid = 170;
  3426. sub = static_cast<Res::ERes>((rand() % 5) + 1);
  3427. val = (rand() % 4) + 3;
  3428. break;
  3429. case Obj::WATER_WHEEL:
  3430. mid = 164;
  3431. sub = Res::GOLD;
  3432. if(cb->getDate(Date::DAY)<8)
  3433. val = 500;
  3434. else
  3435. val = 1000;
  3436. }
  3437. cb->giveResource(h->tempOwner, sub, val);
  3438. InfoWindow iw;
  3439. iw.soundID = sound;
  3440. iw.player = h->tempOwner;
  3441. iw.components.push_back(Component(type,sub,val,0));
  3442. iw.text.addTxt(MetaString::ADVOB_TXT,mid);
  3443. cb->showInfoDialog(&iw);
  3444. cb->setObjProperty(id, ObjProperty::VISITED, true);
  3445. MetaString ms; //set text to "visited"
  3446. ms.addTxt(MetaString::OBJ_NAMES,ID); ms << " "; ms.addTxt(MetaString::GENERAL_TXT,352);
  3447. cb->setHoverName(this,&ms);
  3448. }
  3449. }
  3450. void CGVisitableOPW::setPropertyDer( ui8 what, ui32 val )
  3451. {
  3452. if(what == ObjProperty::VISITED)
  3453. visited = val;
  3454. }
  3455. void CGTeleport::onHeroVisit( const CGHeroInstance * h ) const
  3456. {
  3457. ObjectInstanceID destinationid;
  3458. switch(ID)
  3459. {
  3460. case Obj::MONOLITH1: //one way - find corresponding exit monolith
  3461. if(vstd::contains(objs,Obj::MONOLITH2) && vstd::contains(objs[Obj::MONOLITH2],subID) && objs[Obj::MONOLITH2][subID].size())
  3462. destinationid = objs[Obj::MONOLITH2][subID][rand()%objs[Obj::MONOLITH2][subID].size()];
  3463. else
  3464. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  3465. break;
  3466. case Obj::MONOLITH3://two way monolith - pick any other one
  3467. case Obj::WHIRLPOOL: //Whirlpool
  3468. if(vstd::contains(objs,ID) && vstd::contains(objs[ID],subID) && objs[ID][subID].size()>1)
  3469. {
  3470. while ((destinationid = objs[ID][subID][rand()%objs[ID][subID].size()]) == id); //choose another exit
  3471. if (ID == Obj::WHIRLPOOL)
  3472. {
  3473. if (!h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION))
  3474. {
  3475. if (h->Slots().size() > 1 || h->Slots().begin()->second->count > 1)
  3476. { //we can't remove last unit
  3477. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  3478. for(TSlots::const_reverse_iterator i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  3479. {
  3480. if (h->getPower(targetstack) > h->getPower(i->first))
  3481. {
  3482. targetstack = (i->first);
  3483. }
  3484. }
  3485. TQuantity countToTake = h->getStackCount(targetstack) * 0.5;
  3486. vstd::amax(countToTake, 1);
  3487. InfoWindow iw;
  3488. iw.player = h->tempOwner;
  3489. iw.text.addTxt (MetaString::ADVOB_TXT, 168);
  3490. iw.components.push_back (Component(CStackBasicDescriptor(h->getCreature(targetstack), countToTake)));
  3491. cb->showInfoDialog(&iw);
  3492. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  3493. }
  3494. }
  3495. }
  3496. }
  3497. else
  3498. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  3499. break;
  3500. case Obj::SUBTERRANEAN_GATE: //find nearest subterranean gate on the other level
  3501. {
  3502. destinationid = getMatchingGate(id);
  3503. if(destinationid == ObjectInstanceID()) //no exit
  3504. {
  3505. showInfoDialog(h,153,0);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  3506. }
  3507. break;
  3508. }
  3509. }
  3510. if(destinationid == ObjectInstanceID())
  3511. {
  3512. logGlobal->warnStream() << "Cannot find exit... (obj at " << pos << ") :( ";
  3513. return;
  3514. }
  3515. if (ID == Obj::WHIRLPOOL)
  3516. {
  3517. std::set<int3> tiles = cb->getObj(destinationid)->getBlockedPos();
  3518. std::set<int3>::iterator it = tiles.begin();
  3519. std::advance (it, rand() % tiles.size()); //picking random element of set is tiring
  3520. cb->moveHero (h->id, *it + int3(1,0,0), true);
  3521. }
  3522. else
  3523. cb->moveHero (h->id,CGHeroInstance::convertPosition(cb->getObj(destinationid)->pos,true) - getVisitableOffset(), true);
  3524. }
  3525. void CGTeleport::initObj()
  3526. {
  3527. int si = subID;
  3528. switch (ID)
  3529. {
  3530. case Obj::SUBTERRANEAN_GATE://ignore subterranean gates subid
  3531. case Obj::WHIRLPOOL:
  3532. {
  3533. si = 0;
  3534. break;
  3535. }
  3536. default:
  3537. break;
  3538. }
  3539. objs[ID][si].push_back(id);
  3540. }
  3541. void CGTeleport::postInit() //matches subterranean gates into pairs
  3542. {
  3543. //split on underground and surface gates
  3544. std::vector<const CGObjectInstance *> gatesSplit[2]; //surface and underground gates
  3545. for(size_t i = 0; i < objs[Obj::SUBTERRANEAN_GATE][0].size(); i++)
  3546. {
  3547. const CGObjectInstance *hlp = cb->getObj(objs[Obj::SUBTERRANEAN_GATE][0][i]);
  3548. gatesSplit[hlp->pos.z].push_back(hlp);
  3549. }
  3550. //sort by position
  3551. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), boost::bind(&CGObjectInstance::pos, _1) < boost::bind(&CGObjectInstance::pos, _2));
  3552. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  3553. {
  3554. const CGObjectInstance *cur = gatesSplit[0][i];
  3555. //find nearest underground exit
  3556. std::pair<int,double> best(-1,150000); //pair<pos_in_vector, distance>
  3557. for(int j = 0; j < gatesSplit[1].size(); j++)
  3558. {
  3559. const CGObjectInstance *checked = gatesSplit[1][j];
  3560. if(!checked)
  3561. continue;
  3562. double hlp = checked->pos.dist2d(cur->pos);
  3563. if(hlp < best.second)
  3564. {
  3565. best.first = j;
  3566. best.second = hlp;
  3567. }
  3568. }
  3569. if(best.first >= 0) //found pair
  3570. {
  3571. gates.push_back(std::make_pair(cur->id, gatesSplit[1][best.first]->id));
  3572. gatesSplit[1][best.first] = NULL;
  3573. }
  3574. else
  3575. {
  3576. gates.push_back(std::make_pair(cur->id, ObjectInstanceID()));
  3577. }
  3578. }
  3579. objs.erase(Obj::SUBTERRANEAN_GATE);
  3580. }
  3581. ObjectInstanceID CGTeleport::getMatchingGate(ObjectInstanceID id)
  3582. {
  3583. for(int i=0; i < gates.size(); i++)
  3584. {
  3585. if(gates[i].first == id)
  3586. return gates[i].second;
  3587. if(gates[i].second == id)
  3588. return gates[i].first;
  3589. }
  3590. return ObjectInstanceID();
  3591. }
  3592. void CGArtifact::initObj()
  3593. {
  3594. blockVisit = true;
  3595. if(ID == Obj::ARTIFACT)
  3596. {
  3597. hoverName = VLC->arth->artifacts[subID]->Name();
  3598. if(!storedArtifact->artType)
  3599. storedArtifact->setType(VLC->arth->artifacts[subID]);
  3600. }
  3601. if(ID == Obj::SPELL_SCROLL)
  3602. subID = 1;
  3603. assert(storedArtifact->artType);
  3604. assert(storedArtifact->getParentNodes().size());
  3605. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  3606. }
  3607. void CGArtifact::onHeroVisit( const CGHeroInstance * h ) const
  3608. {
  3609. if(!stacksCount())
  3610. {
  3611. InfoWindow iw;
  3612. iw.player = h->tempOwner;
  3613. switch(ID)
  3614. {
  3615. case Obj::ARTIFACT:
  3616. {
  3617. iw.soundID = soundBase::treasure; //play sound only for non-scroll arts
  3618. iw.components.push_back(Component(Component::ARTIFACT,subID,0,0));
  3619. if(message.length())
  3620. iw.text << message;
  3621. else
  3622. {
  3623. if (VLC->arth->artifacts[subID]->EventText().size())
  3624. iw.text << std::pair<ui8, ui32> (MetaString::ART_EVNTS, subID);
  3625. else //fix for mod artifacts with no event text
  3626. {
  3627. iw.text.addTxt (MetaString::ADVOB_TXT, 183); //% has found treasure
  3628. iw.text.addReplacement (h->name);
  3629. }
  3630. }
  3631. }
  3632. break;
  3633. case Obj::SPELL_SCROLL:
  3634. {
  3635. int spellID = storedArtifact->getGivenSpellID();
  3636. iw.components.push_back (Component(Component::SPELL, spellID,0,0));
  3637. iw.text.addTxt (MetaString::ADVOB_TXT,135);
  3638. iw.text.addReplacement(MetaString::SPELL_NAME, spellID);
  3639. }
  3640. break;
  3641. }
  3642. cb->showInfoDialog(&iw);
  3643. pick(h);
  3644. }
  3645. else
  3646. {
  3647. if(message.size())
  3648. {
  3649. BlockingDialog ynd(true,false);
  3650. ynd.player = h->getOwner();
  3651. ynd.text << message;
  3652. cb->showBlockingDialog(&ynd);
  3653. }
  3654. else
  3655. {
  3656. blockingDialogAnswered(h, true);
  3657. }
  3658. }
  3659. }
  3660. void CGArtifact::pick(const CGHeroInstance * h) const
  3661. {
  3662. cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  3663. cb->removeObject(this);
  3664. }
  3665. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3666. {
  3667. if(result.winner == 0) //attacker won
  3668. pick(hero);
  3669. }
  3670. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3671. {
  3672. if(answer)
  3673. cb->startBattleI(hero, this);
  3674. }
  3675. void CGPickable::initObj()
  3676. {
  3677. blockVisit = true;
  3678. switch(ID)
  3679. {
  3680. case Obj::CAMPFIRE:
  3681. val2 = (ran()%3) + 4; //4 - 6
  3682. val1 = val2 * 100;
  3683. type = ran()%6; //given resource
  3684. break;
  3685. case Obj::FLOTSAM:
  3686. switch(type = ran()%4)
  3687. {
  3688. case 0:
  3689. val1 = val2 = 0;
  3690. break;
  3691. case 1:
  3692. val1 = 5;
  3693. val2 = 0;
  3694. break;
  3695. case 2:
  3696. val1 = 5;
  3697. val2 = 200;
  3698. break;
  3699. case 3:
  3700. val1 = 10;
  3701. val2 = 500;
  3702. break;
  3703. }
  3704. break;
  3705. case Obj::SEA_CHEST:
  3706. {
  3707. int hlp = ran()%100;
  3708. if(hlp < 20)
  3709. {
  3710. val1 = 0;
  3711. type = 0;
  3712. }
  3713. else if(hlp < 90)
  3714. {
  3715. val1 = 1500;
  3716. type = 2;
  3717. }
  3718. else
  3719. {
  3720. val1 = 1000;
  3721. val2 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3722. type = 1;
  3723. }
  3724. }
  3725. break;
  3726. case Obj::SHIPWRECK_SURVIVOR:
  3727. {
  3728. int hlp = ran()%100;
  3729. if(hlp < 55)
  3730. val1 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3731. else if(hlp < 75)
  3732. val1 = cb->getRandomArt (CArtifact::ART_MINOR);
  3733. else if(hlp < 95)
  3734. val1 = cb->getRandomArt (CArtifact::ART_MAJOR);
  3735. else
  3736. val1 = cb->getRandomArt (CArtifact::ART_RELIC);
  3737. }
  3738. break;
  3739. case Obj::TREASURE_CHEST:
  3740. {
  3741. int hlp = ran()%100;
  3742. if(hlp >= 95)
  3743. {
  3744. type = 1;
  3745. val1 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3746. return;
  3747. }
  3748. else if (hlp >= 65)
  3749. {
  3750. val1 = 2000;
  3751. }
  3752. else if(hlp >= 33)
  3753. {
  3754. val1 = 1500;
  3755. }
  3756. else
  3757. {
  3758. val1 = 1000;
  3759. }
  3760. val2 = val1 - 500;
  3761. type = 0;
  3762. break;
  3763. }
  3764. }
  3765. }
  3766. void CGPickable::onHeroVisit( const CGHeroInstance * h ) const
  3767. {
  3768. switch(ID)
  3769. {
  3770. case Obj::CAMPFIRE:
  3771. {
  3772. cb->giveResource(h->tempOwner,static_cast<Res::ERes>(type),val2); //non-gold resource
  3773. cb->giveResource(h->tempOwner,Res::GOLD,val1);//gold
  3774. InfoWindow iw;
  3775. iw.soundID = soundBase::experience;
  3776. iw.player = h->tempOwner;
  3777. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3778. iw.components.push_back(Component(Component::RESOURCE,type,val2,0));
  3779. iw.text.addTxt(MetaString::ADVOB_TXT,23);
  3780. cb->showInfoDialog(&iw);
  3781. break;
  3782. }
  3783. case Obj::FLOTSAM:
  3784. {
  3785. cb->giveResource(h->tempOwner,Res::WOOD,val1); //wood
  3786. cb->giveResource(h->tempOwner,Res::GOLD,val2);//gold
  3787. InfoWindow iw;
  3788. iw.soundID = soundBase::GENIE;
  3789. iw.player = h->tempOwner;
  3790. if(val1)
  3791. iw.components.push_back(Component(Component::RESOURCE,Res::WOOD,val1,0));
  3792. if(val2)
  3793. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val2,0));
  3794. iw.text.addTxt(MetaString::ADVOB_TXT, 51+type);
  3795. cb->showInfoDialog(&iw);
  3796. break;
  3797. }
  3798. case Obj::SEA_CHEST:
  3799. {
  3800. InfoWindow iw;
  3801. iw.soundID = soundBase::chest;
  3802. iw.player = h->tempOwner;
  3803. iw.text.addTxt(MetaString::ADVOB_TXT, 116 + type);
  3804. if(val1) //there is gold
  3805. {
  3806. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3807. cb->giveResource(h->tempOwner,Res::GOLD,val1);
  3808. }
  3809. if(type == 1) //art
  3810. {
  3811. //TODO: what if no space in backpack?
  3812. iw.components.push_back(Component(Component::ARTIFACT, val2, 1, 0));
  3813. iw.text.addReplacement(MetaString::ART_NAMES, val2);
  3814. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val2],ArtifactPosition::FIRST_AVAILABLE);
  3815. }
  3816. cb->showInfoDialog(&iw);
  3817. break;
  3818. }
  3819. case Obj::SHIPWRECK_SURVIVOR:
  3820. {
  3821. InfoWindow iw;
  3822. iw.soundID = soundBase::experience;
  3823. iw.player = h->tempOwner;
  3824. iw.components.push_back(Component(Component::ARTIFACT,val1,1,0));
  3825. iw.text.addTxt(MetaString::ADVOB_TXT, 125);
  3826. iw.text.addReplacement(MetaString::ART_NAMES, val1);
  3827. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val1],ArtifactPosition::FIRST_AVAILABLE);
  3828. cb->showInfoDialog(&iw);
  3829. break;
  3830. }
  3831. case Obj::TREASURE_CHEST:
  3832. {
  3833. if (subID) //not OH3 treasure chest
  3834. {
  3835. logGlobal->warnStream() << "Not supported WoG treasure chest!";
  3836. return;
  3837. }
  3838. if(type) //there is an artifact
  3839. {
  3840. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val1],ArtifactPosition::FIRST_AVAILABLE);
  3841. InfoWindow iw;
  3842. iw.soundID = soundBase::treasure;
  3843. iw.player = h->tempOwner;
  3844. iw.components.push_back(Component(Component::ARTIFACT,val1,1,0));
  3845. iw.text.addTxt(MetaString::ADVOB_TXT,145);
  3846. iw.text.addReplacement(MetaString::ART_NAMES, val1);
  3847. cb->showInfoDialog(&iw);
  3848. break;
  3849. }
  3850. else
  3851. {
  3852. BlockingDialog sd(false,true);
  3853. sd.player = h->tempOwner;
  3854. sd.text.addTxt(MetaString::ADVOB_TXT,146);
  3855. sd.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3856. TExpType expVal = h->calculateXp(val2);
  3857. sd.components.push_back(Component(Component::EXPERIENCE,0,expVal, 0));
  3858. sd.soundID = soundBase::chest;
  3859. cb->showBlockingDialog(&sd);
  3860. return;
  3861. }
  3862. }
  3863. }
  3864. cb->removeObject(this);
  3865. }
  3866. void CGPickable::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3867. {
  3868. switch(answer)
  3869. {
  3870. case 1: //player pick gold
  3871. cb->giveResource(hero->tempOwner, Res::GOLD, val1);
  3872. break;
  3873. case 2: //player pick exp
  3874. cb->changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(val2));
  3875. break;
  3876. default:
  3877. throw std::runtime_error("Unhandled treasure choice");
  3878. }
  3879. cb->removeObject(this);
  3880. }
  3881. bool CQuest::checkQuest (const CGHeroInstance * h) const
  3882. {
  3883. switch (missionType)
  3884. {
  3885. case MISSION_NONE:
  3886. return true;
  3887. case MISSION_LEVEL:
  3888. if (m13489val <= h->level)
  3889. return true;
  3890. return false;
  3891. case MISSION_PRIMARY_STAT:
  3892. for (int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  3893. {
  3894. if (h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i)) < m2stats[i])
  3895. return false;
  3896. }
  3897. return true;
  3898. case MISSION_KILL_HERO:
  3899. case MISSION_KILL_CREATURE:
  3900. if (!h->cb->getObjByQuestIdentifier(m13489val))
  3901. return true;
  3902. return false;
  3903. case MISSION_ART:
  3904. for (int i = 0; i < m5arts.size(); ++i)
  3905. {
  3906. if (h->hasArt(m5arts[i]))
  3907. continue;
  3908. return false; //if the artifact was not found
  3909. }
  3910. return true;
  3911. case MISSION_ARMY:
  3912. {
  3913. std::vector<CStackBasicDescriptor>::const_iterator cre;
  3914. TSlots::const_iterator it;
  3915. ui32 count;
  3916. for (cre = m6creatures.begin(); cre != m6creatures.end(); ++cre)
  3917. {
  3918. for (count = 0, it = h->Slots().begin(); it != h->Slots().end(); ++it)
  3919. {
  3920. if (it->second->type == cre->type)
  3921. count += it->second->count;
  3922. }
  3923. if (count < cre->count) //not enough creatures of this kind
  3924. return false;
  3925. }
  3926. }
  3927. return true;
  3928. case MISSION_RESOURCES:
  3929. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, +1)) //including Mithril ?
  3930. { //Quest has no direct access to callback
  3931. if (h->cb->getResource (h->tempOwner, i) < m7resources[i])
  3932. return false;
  3933. }
  3934. return true;
  3935. case MISSION_HERO:
  3936. if (m13489val == h->type->ID.getNum())
  3937. return true;
  3938. return false;
  3939. case MISSION_PLAYER:
  3940. if (m13489val == h->getOwner().getNum())
  3941. return true;
  3942. return false;
  3943. default:
  3944. return false;
  3945. }
  3946. }
  3947. void CQuest::getVisitText (MetaString &iwText, std::vector<Component> &components, bool isCustom, bool firstVisit, const CGHeroInstance * h) const
  3948. {
  3949. std::string text;
  3950. bool failRequirements = (h ? !checkQuest(h) : true);
  3951. if (firstVisit)
  3952. {
  3953. isCustom = isCustomFirst;
  3954. iwText << firstVisitText;
  3955. }
  3956. else if (failRequirements)
  3957. {
  3958. isCustom = isCustomNext;
  3959. iwText << nextVisitText;
  3960. }
  3961. switch (missionType)
  3962. {
  3963. case MISSION_LEVEL:
  3964. components.push_back(Component (Component::EXPERIENCE, 1, m13489val, 0));
  3965. if (!isCustom)
  3966. iwText.addReplacement(m13489val);
  3967. break;
  3968. case MISSION_PRIMARY_STAT:
  3969. {
  3970. MetaString loot;
  3971. for (int i = 0; i < 4; ++i)
  3972. {
  3973. if (m2stats[i])
  3974. {
  3975. components.push_back(Component (Component::PRIM_SKILL, i, m2stats[i], 0));
  3976. loot << "%d %s";
  3977. loot.addReplacement(m2stats[i]);
  3978. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  3979. }
  3980. }
  3981. if (!isCustom)
  3982. iwText.addReplacement(loot.buildList());
  3983. }
  3984. break;
  3985. case MISSION_KILL_HERO:
  3986. components.push_back(Component(Component::HERO, heroPortrait, 0, 0));
  3987. if (!isCustom)
  3988. addReplacements(iwText, text);
  3989. break;
  3990. case MISSION_HERO:
  3991. components.push_back(Component (Component::HERO, m13489val, 0, 0));
  3992. if (!isCustom)
  3993. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  3994. break;
  3995. case MISSION_KILL_CREATURE:
  3996. {
  3997. components.push_back(Component(stackToKill));
  3998. if (!isCustom)
  3999. addReplacements(iwText, text);
  4000. }
  4001. break;
  4002. case MISSION_ART:
  4003. {
  4004. MetaString loot;
  4005. for (std::vector<ui16>::const_iterator it = m5arts.begin(); it != m5arts.end(); ++it)
  4006. {
  4007. components.push_back(Component (Component::ARTIFACT, *it, 0, 0));
  4008. loot << "%s";
  4009. loot.addReplacement(MetaString::ART_NAMES, *it);
  4010. }
  4011. if (!isCustom)
  4012. iwText.addReplacement(loot.buildList());
  4013. }
  4014. break;
  4015. case MISSION_ARMY:
  4016. {
  4017. MetaString loot;
  4018. for (std::vector<CStackBasicDescriptor>::const_iterator it = m6creatures.begin(); it != m6creatures.end(); ++it)
  4019. {
  4020. components.push_back(Component(*it));
  4021. loot << "%s";
  4022. loot.addReplacement(*it);
  4023. }
  4024. if (!isCustom)
  4025. iwText.addReplacement(loot.buildList());
  4026. }
  4027. break;
  4028. case MISSION_RESOURCES:
  4029. {
  4030. MetaString loot;
  4031. for (int i = 0; i < 7; ++i)
  4032. {
  4033. if (m7resources[i])
  4034. {
  4035. components.push_back(Component (Component::RESOURCE, i, m7resources[i], 0));
  4036. loot << "%d %s";
  4037. loot.addReplacement(m7resources[i]);
  4038. loot.addReplacement(MetaString::RES_NAMES, i);
  4039. }
  4040. }
  4041. if (!isCustom)
  4042. iwText.addReplacement(loot.buildList());
  4043. }
  4044. break;
  4045. case MISSION_PLAYER:
  4046. components.push_back(Component (Component::FLAG, m13489val, 0, 0));
  4047. if (!isCustom)
  4048. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  4049. break;
  4050. }
  4051. }
  4052. void CQuest::getRolloverText (MetaString &ms, bool onHover) const
  4053. {
  4054. if (onHover)
  4055. ms << "\n\n";
  4056. ms << VLC->generaltexth->quests[missionType-1][onHover ? 3 : 4][textOption];
  4057. switch (missionType)
  4058. {
  4059. case MISSION_LEVEL:
  4060. ms.addReplacement(m13489val);
  4061. break;
  4062. case MISSION_PRIMARY_STAT:
  4063. {
  4064. MetaString loot;
  4065. for (int i = 0; i < 4; ++i)
  4066. {
  4067. if (m2stats[i])
  4068. {
  4069. loot << "%d %s";
  4070. loot.addReplacement(m2stats[i]);
  4071. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4072. }
  4073. }
  4074. ms.addReplacement(loot.buildList());
  4075. }
  4076. break;
  4077. case MISSION_KILL_HERO:
  4078. ms.addReplacement(heroName);
  4079. break;
  4080. case MISSION_KILL_CREATURE:
  4081. ms.addReplacement(stackToKill);
  4082. break;
  4083. case MISSION_ART:
  4084. {
  4085. MetaString loot;
  4086. for (std::vector<ui16>::const_iterator it = m5arts.begin(); it != m5arts.end(); ++it)
  4087. {
  4088. loot << "%s";
  4089. loot.addReplacement(MetaString::ART_NAMES, *it);
  4090. }
  4091. ms.addReplacement(loot.buildList());
  4092. }
  4093. break;
  4094. case MISSION_ARMY:
  4095. {
  4096. MetaString loot;
  4097. for (std::vector<CStackBasicDescriptor>::const_iterator it = m6creatures.begin(); it != m6creatures.end(); ++it)
  4098. {
  4099. loot << "%s";
  4100. loot.addReplacement(*it);
  4101. }
  4102. ms.addReplacement(loot.buildList());
  4103. }
  4104. break;
  4105. case MISSION_RESOURCES:
  4106. {
  4107. MetaString loot;
  4108. for (int i = 0; i < 7; ++i)
  4109. {
  4110. if (m7resources[i])
  4111. {
  4112. loot << "%d %s";
  4113. loot.addReplacement(m7resources[i]);
  4114. loot.addReplacement(MetaString::RES_NAMES, i);
  4115. }
  4116. }
  4117. ms.addReplacement(loot.buildList());
  4118. }
  4119. break;
  4120. case MISSION_HERO:
  4121. ms.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4122. break;
  4123. case MISSION_PLAYER:
  4124. ms.addReplacement(VLC->generaltexth->colors[m13489val]);
  4125. break;
  4126. default:
  4127. break;
  4128. }
  4129. }
  4130. void CQuest::getCompletionText (MetaString &iwText, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  4131. {
  4132. iwText << completedText;
  4133. switch (missionType)
  4134. {
  4135. case CQuest::MISSION_LEVEL:
  4136. if (!isCustomComplete)
  4137. iwText.addReplacement(m13489val);
  4138. break;
  4139. case CQuest::MISSION_PRIMARY_STAT:
  4140. if (vstd::contains (completedText,'%')) //there's one case when there's nothing to replace
  4141. {
  4142. MetaString loot;
  4143. for (int i = 0; i < 4; ++i)
  4144. {
  4145. if (m2stats[i])
  4146. {
  4147. loot << "%d %s";
  4148. loot.addReplacement(m2stats[i]);
  4149. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4150. }
  4151. }
  4152. if (!isCustomComplete)
  4153. iwText.addReplacement(loot.buildList());
  4154. }
  4155. break;
  4156. case CQuest::MISSION_ART:
  4157. {
  4158. MetaString loot;
  4159. for (std::vector<ui16>::const_iterator it = m5arts.begin(); it != m5arts.end(); ++it)
  4160. {
  4161. loot << "%s";
  4162. loot.addReplacement(MetaString::ART_NAMES, *it);
  4163. }
  4164. if (!isCustomComplete)
  4165. iwText.addReplacement(loot.buildList());
  4166. }
  4167. break;
  4168. case CQuest::MISSION_ARMY:
  4169. {
  4170. MetaString loot;
  4171. for (std::vector<CStackBasicDescriptor>::const_iterator it = m6creatures.begin(); it != m6creatures.end(); ++it)
  4172. {
  4173. loot << "%s";
  4174. loot.addReplacement(*it);
  4175. }
  4176. if (!isCustomComplete)
  4177. iwText.addReplacement(loot.buildList());
  4178. }
  4179. break;
  4180. case CQuest::MISSION_RESOURCES:
  4181. {
  4182. MetaString loot;
  4183. for (int i = 0; i < 7; ++i)
  4184. {
  4185. if (m7resources[i])
  4186. {
  4187. loot << "%d %s";
  4188. loot.addReplacement(m7resources[i]);
  4189. loot.addReplacement(MetaString::RES_NAMES, i);
  4190. }
  4191. }
  4192. if (!isCustomComplete)
  4193. iwText.addReplacement(loot.buildList());
  4194. }
  4195. break;
  4196. case MISSION_KILL_HERO:
  4197. case MISSION_KILL_CREATURE:
  4198. if (!isCustomComplete)
  4199. addReplacements(iwText, completedText);
  4200. break;
  4201. case MISSION_HERO:
  4202. if (!isCustomComplete)
  4203. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4204. break;
  4205. case MISSION_PLAYER:
  4206. if (!isCustomComplete)
  4207. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  4208. break;
  4209. }
  4210. }
  4211. void CGSeerHut::setObjToKill()
  4212. {
  4213. if (quest->missionType == CQuest::MISSION_KILL_CREATURE)
  4214. {
  4215. quest->stackToKill = getCreatureToKill(false)->getStack(SlotID(0)); //FIXME: stacks tend to dissapear (desync?) on server :?
  4216. assert(quest->stackToKill.type);
  4217. quest->stackToKill.count = 0; //no count in info window
  4218. quest->stackDirection = checkDirection();
  4219. }
  4220. else if (quest->missionType == CQuest::MISSION_KILL_HERO)
  4221. {
  4222. quest->heroName = getHeroToKill(false)->name;
  4223. quest->heroPortrait = getHeroToKill(false)->portrait;
  4224. }
  4225. }
  4226. void CGSeerHut::initObj()
  4227. {
  4228. seerName = VLC->generaltexth->seerNames[ran()%VLC->generaltexth->seerNames.size()];
  4229. quest->textOption = ran()%3;
  4230. quest->progress = CQuest::NOT_ACTIVE;
  4231. if (quest->missionType)
  4232. {
  4233. if (!quest->isCustomFirst)
  4234. quest->firstVisitText = VLC->generaltexth->quests[quest->missionType-1][0][quest->textOption];
  4235. if (!quest->isCustomNext)
  4236. quest->nextVisitText = VLC->generaltexth->quests[quest->missionType-1][1][quest->textOption];
  4237. if (!quest->isCustomComplete)
  4238. quest->completedText = VLC->generaltexth->quests[quest->missionType-1][2][quest->textOption];
  4239. }
  4240. else
  4241. quest->firstVisitText = VLC->generaltexth->seerEmpty[quest->textOption];
  4242. }
  4243. void CGSeerHut::getRolloverText (MetaString &text, bool onHover) const
  4244. {
  4245. quest->getRolloverText (text, onHover);//TODO: simplify?
  4246. if (!onHover)
  4247. text.addReplacement(seerName);
  4248. }
  4249. const std::string & CGSeerHut::getHoverText() const
  4250. {
  4251. switch (ID)
  4252. {
  4253. case Obj::SEER_HUT:
  4254. if (quest->progress != CQuest::NOT_ACTIVE)
  4255. {
  4256. hoverName = VLC->generaltexth->allTexts[347];
  4257. boost::algorithm::replace_first(hoverName,"%s", seerName);
  4258. }
  4259. else //just seer hut
  4260. hoverName = VLC->generaltexth->names[ID];
  4261. break;
  4262. case Obj::QUEST_GUARD:
  4263. hoverName = VLC->generaltexth->names[ID];
  4264. break;
  4265. default:
  4266. logGlobal->debugStream() << "unrecognized quest object";
  4267. }
  4268. if (quest->progress & quest->missionType) //rollover when the quest is active
  4269. {
  4270. MetaString ms;
  4271. getRolloverText (ms, true);
  4272. hoverName += ms.toString();
  4273. }
  4274. return hoverName;
  4275. }
  4276. void CQuest::addReplacements(MetaString &out, const std::string &base) const
  4277. {
  4278. switch(missionType)
  4279. {
  4280. case MISSION_KILL_CREATURE:
  4281. out.addReplacement(stackToKill);
  4282. if (std::count(base.begin(), base.end(), '%') == 2) //say where is placed monster
  4283. {
  4284. out.addReplacement(VLC->generaltexth->arraytxt[147+stackDirection]);
  4285. }
  4286. break;
  4287. case MISSION_KILL_HERO:
  4288. out.addReplacement(heroName);
  4289. break;
  4290. }
  4291. }
  4292. bool IQuestObject::checkQuest(const CGHeroInstance* h) const
  4293. {
  4294. return quest->checkQuest(h);
  4295. }
  4296. void IQuestObject::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  4297. {
  4298. quest->getVisitText (text,components, isCustom, FirstVisit, h);
  4299. }
  4300. void CGSeerHut::getCompletionText(MetaString &text, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  4301. {
  4302. quest->getCompletionText (text, components, isCustom, h);
  4303. switch (rewardType)
  4304. {
  4305. case EXPERIENCE: components.push_back(Component (Component::EXPERIENCE, 0, h->calculateXp(rVal), 0));
  4306. break;
  4307. case MANA_POINTS: components.push_back(Component (Component::PRIM_SKILL, 5, rVal, 0));
  4308. break;
  4309. case MORALE_BONUS: components.push_back(Component (Component::MORALE, 0, rVal, 0));
  4310. break;
  4311. case LUCK_BONUS: components.push_back(Component (Component::LUCK, 0, rVal, 0));
  4312. break;
  4313. case RESOURCES: components.push_back(Component (Component::RESOURCE, rID, rVal, 0));
  4314. break;
  4315. case PRIMARY_SKILL: components.push_back(Component (Component::PRIM_SKILL, rID, rVal, 0));
  4316. break;
  4317. case SECONDARY_SKILL: components.push_back(Component (Component::SEC_SKILL, rID, rVal, 0));
  4318. break;
  4319. case ARTIFACT: components.push_back(Component (Component::ARTIFACT, rID, 0, 0));
  4320. break;
  4321. case SPELL: components.push_back(Component (Component::SPELL, rID, 0, 0));
  4322. break;
  4323. case CREATURE: components.push_back(Component (Component::CREATURE, rID, rVal, 0));
  4324. break;
  4325. }
  4326. }
  4327. void CGSeerHut::setPropertyDer (ui8 what, ui32 val)
  4328. {
  4329. switch (what)
  4330. {
  4331. case 10:
  4332. quest->progress = static_cast<CQuest::Eprogress>(val);
  4333. break;
  4334. case 11:
  4335. quest->missionType = CQuest::MISSION_NONE;
  4336. break;
  4337. }
  4338. }
  4339. void CGSeerHut::newTurn() const
  4340. {
  4341. if (quest->lastDay >= 0 && quest->lastDay < cb->getDate()) //time is up
  4342. {
  4343. cb->setObjProperty (id, 11, 0);
  4344. cb->setObjProperty (id, 10, 0);
  4345. }
  4346. }
  4347. void CGSeerHut::onHeroVisit( const CGHeroInstance * h ) const
  4348. {
  4349. InfoWindow iw;
  4350. iw.player = h->getOwner();
  4351. if (quest->missionType)
  4352. {
  4353. bool firstVisit = !quest->progress;
  4354. bool failRequirements = !checkQuest(h);
  4355. bool isCustom=false;
  4356. if (firstVisit)
  4357. {
  4358. isCustom = quest->isCustomFirst;
  4359. cb->setObjProperty (id, 10, CQuest::IN_PROGRESS);
  4360. AddQuest aq;
  4361. aq.quest = QuestInfo (quest, this, visitablePos());
  4362. aq.player = h->tempOwner;
  4363. cb->sendAndApply (&aq); //TODO: merge with setObjProperty?
  4364. }
  4365. else if (failRequirements)
  4366. {
  4367. isCustom = quest->isCustomNext;
  4368. }
  4369. if (firstVisit || failRequirements)
  4370. {
  4371. getVisitText (iw.text, iw.components, isCustom, firstVisit, h);
  4372. cb->showInfoDialog(&iw);
  4373. }
  4374. if (!failRequirements) // propose completion, also on first visit
  4375. {
  4376. BlockingDialog bd (true, false);
  4377. bd.player = h->getOwner();
  4378. bd.soundID = soundBase::QUEST;
  4379. getCompletionText (bd.text, bd.components, isCustom, h);
  4380. cb->showBlockingDialog (&bd);
  4381. return;
  4382. }
  4383. }
  4384. else
  4385. {
  4386. iw.text << VLC->generaltexth->seerEmpty[quest->textOption];
  4387. if (ID == Obj::SEER_HUT)
  4388. iw.text.addReplacement(seerName);
  4389. cb->showInfoDialog(&iw);
  4390. }
  4391. }
  4392. int CGSeerHut::checkDirection() const
  4393. {
  4394. int3 cord = getCreatureToKill()->pos;
  4395. if ((double)cord.x/(double)cb->getMapSize().x < 0.34) //north
  4396. {
  4397. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //northwest
  4398. return 8;
  4399. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //north
  4400. return 1;
  4401. else //northeast
  4402. return 2;
  4403. }
  4404. else if ((double)cord.x/(double)cb->getMapSize().x < 0.67) //horizontal
  4405. {
  4406. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //west
  4407. return 7;
  4408. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //central
  4409. return 9;
  4410. else //east
  4411. return 3;
  4412. }
  4413. else //south
  4414. {
  4415. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //southwest
  4416. return 6;
  4417. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //south
  4418. return 5;
  4419. else //southeast
  4420. return 4;
  4421. }
  4422. }
  4423. void CGSeerHut::finishQuest(const CGHeroInstance * h, ui32 accept) const
  4424. {
  4425. if (accept)
  4426. {
  4427. switch (quest->missionType)
  4428. {
  4429. case CQuest::MISSION_ART:
  4430. for (std::vector<ui16>::const_iterator it = quest->m5arts.begin(); it != quest->m5arts.end(); ++it)
  4431. {
  4432. cb->removeArtifact(ArtifactLocation(h, h->getArtPos(*it, false)));
  4433. }
  4434. break;
  4435. case CQuest::MISSION_ARMY:
  4436. cb->takeCreatures(h->id, quest->m6creatures);
  4437. break;
  4438. case CQuest::MISSION_RESOURCES:
  4439. for (int i = 0; i < 7; ++i)
  4440. {
  4441. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(i), -quest->m7resources[i]);
  4442. }
  4443. break;
  4444. default:
  4445. break;
  4446. }
  4447. cb->setObjProperty (id, 10, CQuest::COMPLETE); //mission complete - for AI
  4448. cb->setObjProperty (id, 11, 0); //no more mission available - redundant?
  4449. completeQuest(h); //make sure to remove QuestQuard at the very end
  4450. }
  4451. }
  4452. void CGSeerHut::completeQuest (const CGHeroInstance * h) const //reward
  4453. {
  4454. switch (rewardType)
  4455. {
  4456. case EXPERIENCE:
  4457. {
  4458. TExpType expVal = h->calculateXp(rVal);
  4459. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  4460. break;
  4461. }
  4462. case MANA_POINTS:
  4463. {
  4464. cb->setManaPoints(h->id, h->mana+rVal);
  4465. break;
  4466. }
  4467. case MORALE_BONUS: case LUCK_BONUS:
  4468. {
  4469. Bonus hb(Bonus::ONE_WEEK, (rewardType == 3 ? Bonus::MORALE : Bonus::LUCK),
  4470. Bonus::OBJECT, rVal, h->id.getNum(), "", -1);
  4471. GiveBonus gb;
  4472. gb.id = h->id.getNum();
  4473. gb.bonus = hb;
  4474. cb->giveHeroBonus(&gb);
  4475. }
  4476. break;
  4477. case RESOURCES:
  4478. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(rID), rVal);
  4479. break;
  4480. case PRIMARY_SKILL:
  4481. cb->changePrimSkill(h, static_cast<PrimarySkill::PrimarySkill>(rID), rVal, false);
  4482. break;
  4483. case SECONDARY_SKILL:
  4484. cb->changeSecSkill(h, SecondarySkill(rID), rVal, false);
  4485. break;
  4486. case ARTIFACT:
  4487. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[rID],ArtifactPosition::FIRST_AVAILABLE);
  4488. break;
  4489. case SPELL:
  4490. {
  4491. std::set<SpellID> spell;
  4492. spell.insert (SpellID(rID));
  4493. cb->changeSpells(h, true, spell);
  4494. }
  4495. break;
  4496. case CREATURE:
  4497. {
  4498. CCreatureSet creatures;
  4499. creatures.setCreature(SlotID(0), CreatureID(rID), rVal);
  4500. cb->giveCreatures(this, h, creatures, false);
  4501. }
  4502. break;
  4503. default:
  4504. break;
  4505. }
  4506. }
  4507. const CGHeroInstance * CGSeerHut::getHeroToKill(bool allowNull) const
  4508. {
  4509. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  4510. if(allowNull && !o)
  4511. return NULL;
  4512. assert(o && o->ID == Obj::HERO);
  4513. return static_cast<const CGHeroInstance*>(o);
  4514. }
  4515. const CGCreature * CGSeerHut::getCreatureToKill(bool allowNull) const
  4516. {
  4517. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  4518. if(allowNull && !o)
  4519. return NULL;
  4520. assert(o && o->ID == Obj::MONSTER);
  4521. return static_cast<const CGCreature*>(o);
  4522. }
  4523. void CGSeerHut::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  4524. {
  4525. finishQuest(hero, answer);
  4526. }
  4527. void CGQuestGuard::initObj()
  4528. {
  4529. blockVisit = true;
  4530. quest->progress = CQuest::NOT_ACTIVE;
  4531. quest->textOption = ran()%3 + 3; //3-5
  4532. if (quest->missionType)
  4533. {
  4534. if (!quest->isCustomFirst)
  4535. quest->firstVisitText = VLC->generaltexth->quests[quest->missionType-1][0][quest->textOption];
  4536. if (!quest->isCustomNext)
  4537. quest->nextVisitText = VLC->generaltexth->quests[quest->missionType-1][1][quest->textOption];
  4538. if (!quest->isCustomComplete)
  4539. quest->completedText = VLC->generaltexth->quests[quest->missionType-1][2][quest->textOption];
  4540. }
  4541. else
  4542. quest->firstVisitText = VLC->generaltexth->seerEmpty[quest->textOption];
  4543. }
  4544. void CGQuestGuard::completeQuest(const CGHeroInstance *h) const
  4545. {
  4546. cb->removeObject(this);
  4547. }
  4548. void CGWitchHut::initObj()
  4549. {
  4550. ability = allowedAbilities[ran()%allowedAbilities.size()];
  4551. }
  4552. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  4553. {
  4554. InfoWindow iw;
  4555. iw.soundID = soundBase::gazebo;
  4556. iw.player = h->getOwner();
  4557. if(!wasVisited(h->tempOwner))
  4558. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  4559. ui32 txt_id;
  4560. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  4561. {
  4562. txt_id =172;
  4563. }
  4564. else if(!h->canLearnSkill()) //already all skills slots used
  4565. {
  4566. txt_id = 173;
  4567. }
  4568. else //give sec skill
  4569. {
  4570. iw.components.push_back(Component(Component::SEC_SKILL, ability, 1, 0));
  4571. txt_id = 171;
  4572. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  4573. }
  4574. iw.text.addTxt(MetaString::ADVOB_TXT,txt_id);
  4575. iw.text.addReplacement(MetaString::SEC_SKILL_NAME, ability);
  4576. cb->showInfoDialog(&iw);
  4577. }
  4578. const std::string & CGWitchHut::getHoverText() const
  4579. {
  4580. hoverName = VLC->generaltexth->names[ID];
  4581. if(wasVisited(cb->getLocalPlayer()))
  4582. {
  4583. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  4584. boost::algorithm::replace_first(hoverName,"%s",VLC->generaltexth->skillName[ability]);
  4585. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4586. if(h && h->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  4587. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  4588. }
  4589. return hoverName;
  4590. }
  4591. bool CGBonusingObject::wasVisited (const CGHeroInstance * h) const
  4592. {
  4593. return h->hasBonusFrom(Bonus::OBJECT, ID);
  4594. }
  4595. void CGBonusingObject::onHeroVisit( const CGHeroInstance * h ) const
  4596. {
  4597. bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  4598. int messageID=0;
  4599. int bonusMove = 0;
  4600. ui32 descr_id = 0;
  4601. InfoWindow iw;
  4602. iw.player = h->tempOwner;
  4603. GiveBonus gbonus;
  4604. gbonus.id = h->id.getNum();
  4605. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  4606. gbonus.bonus.source = Bonus::OBJECT;
  4607. gbonus.bonus.sid = ID;
  4608. bool second = false;
  4609. Bonus secondBonus;
  4610. switch(ID)
  4611. {
  4612. case Obj::BUOY:
  4613. messageID = 21;
  4614. iw.soundID = soundBase::MORALE;
  4615. gbonus.bonus.type = Bonus::MORALE;
  4616. gbonus.bonus.val = +1;
  4617. descr_id = 94;
  4618. break;
  4619. case Obj::SWAN_POND:
  4620. messageID = 29;
  4621. iw.soundID = soundBase::LUCK;
  4622. gbonus.bonus.type = Bonus::LUCK;
  4623. gbonus.bonus.val = 2;
  4624. descr_id = 67;
  4625. bonusMove = -h->movement;
  4626. break;
  4627. case Obj::FAERIE_RING:
  4628. messageID = 49;
  4629. iw.soundID = soundBase::LUCK;
  4630. gbonus.bonus.type = Bonus::LUCK;
  4631. gbonus.bonus.val = 1;
  4632. descr_id = 71;
  4633. break;
  4634. case Obj::FOUNTAIN_OF_FORTUNE:
  4635. messageID = 55;
  4636. iw.soundID = soundBase::LUCK;
  4637. gbonus.bonus.type = Bonus::LUCK;
  4638. gbonus.bonus.val = rand()%5 - 1;
  4639. descr_id = 69;
  4640. gbonus.bdescr.addReplacement((gbonus.bonus.val<0 ? "-" : "+") + boost::lexical_cast<std::string>(gbonus.bonus.val));
  4641. break;
  4642. case Obj::IDOL_OF_FORTUNE:
  4643. messageID = 62;
  4644. iw.soundID = soundBase::experience;
  4645. gbonus.bonus.val = 1;
  4646. descr_id = 68;
  4647. if(cb->getDate(Date::DAY_OF_WEEK) == 7) //7th day of week
  4648. {
  4649. gbonus.bonus.type = Bonus::MORALE;
  4650. second = true;
  4651. secondBonus = gbonus.bonus;
  4652. secondBonus.type = Bonus::LUCK;
  4653. }
  4654. else
  4655. {
  4656. gbonus.bonus.type = (cb->getDate(Date::DAY_OF_WEEK)%2) ? Bonus::LUCK : Bonus::MORALE;
  4657. }
  4658. break;
  4659. case Obj::MERMAID:
  4660. messageID = 83;
  4661. iw.soundID = soundBase::LUCK;
  4662. gbonus.bonus.type = Bonus::LUCK;
  4663. gbonus.bonus.val = 1;
  4664. descr_id = 72;
  4665. break;
  4666. case Obj::RALLY_FLAG:
  4667. iw.soundID = soundBase::MORALE;
  4668. messageID = 111;
  4669. gbonus.bonus.type = Bonus::MORALE;
  4670. gbonus.bonus.val = 1;
  4671. descr_id = 102;
  4672. second = true;
  4673. secondBonus = gbonus.bonus;
  4674. secondBonus.type = Bonus::LUCK;
  4675. bonusMove = 400;
  4676. break;
  4677. case Obj::OASIS:
  4678. iw.soundID = soundBase::MORALE;
  4679. messageID = 95;
  4680. gbonus.bonus.type = Bonus::MORALE;
  4681. gbonus.bonus.val = 1;
  4682. descr_id = 95;
  4683. bonusMove = 800;
  4684. break;
  4685. case Obj::TEMPLE:
  4686. messageID = 140;
  4687. iw.soundID = soundBase::temple;
  4688. gbonus.bonus.type = Bonus::MORALE;
  4689. if(cb->getDate(Date::DAY_OF_WEEK)==7) //sunday
  4690. {
  4691. gbonus.bonus.val = 2;
  4692. descr_id = 97;
  4693. }
  4694. else
  4695. {
  4696. gbonus.bonus.val = 1;
  4697. descr_id = 96;
  4698. }
  4699. break;
  4700. case Obj::WATERING_HOLE:
  4701. iw.soundID = soundBase::MORALE;
  4702. messageID = 166;
  4703. gbonus.bonus.type = Bonus::MORALE;
  4704. gbonus.bonus.val = 1;
  4705. descr_id = 100;
  4706. bonusMove = 400;
  4707. break;
  4708. case Obj::FOUNTAIN_OF_YOUTH:
  4709. iw.soundID = soundBase::MORALE;
  4710. messageID = 57;
  4711. gbonus.bonus.type = Bonus::MORALE;
  4712. gbonus.bonus.val = 1;
  4713. descr_id = 103;
  4714. bonusMove = 400;
  4715. break;
  4716. case Obj::STABLES:
  4717. iw.soundID = soundBase::STORE;
  4718. bool someUpgradeDone = false;
  4719. for (TSlots::const_iterator i = h->Slots().begin(); i != h->Slots().end(); ++i)
  4720. {
  4721. if(i->second->type->idNumber == CreatureID::CAVALIER)
  4722. {
  4723. cb->changeStackType(StackLocation(h, i->first), VLC->creh->creatures[CreatureID::CHAMPION]);
  4724. someUpgradeDone = true;
  4725. }
  4726. }
  4727. if (someUpgradeDone)
  4728. {
  4729. messageID = 138;
  4730. iw.components.push_back(Component(Component::CREATURE,11,0,1));
  4731. }
  4732. else
  4733. messageID = 137;
  4734. gbonus.bonus.type = Bonus::LAND_MOVEMENT;
  4735. gbonus.bonus.val = 600;
  4736. bonusMove = 600;
  4737. gbonus.bonus.duration = Bonus::ONE_WEEK;
  4738. //gbonus.bdescr << std::pair<ui8,ui32>(6, 100);
  4739. break;
  4740. }
  4741. if (descr_id != 0)
  4742. gbonus.bdescr.addTxt(MetaString::ARRAY_TXT,descr_id);
  4743. assert(messageID);
  4744. if(visited)
  4745. {
  4746. if(ID==Obj::RALLY_FLAG || ID==Obj::OASIS || ID==Obj::MERMAID || ID==Obj::STABLES)
  4747. messageID--;
  4748. else
  4749. messageID++;
  4750. }
  4751. else
  4752. {
  4753. //TODO: fix if second bonus val != main bonus val
  4754. if(gbonus.bonus.type == Bonus::MORALE || secondBonus.type == Bonus::MORALE)
  4755. iw.components.push_back(Component(Component::MORALE,0,gbonus.bonus.val,0));
  4756. if(gbonus.bonus.type == Bonus::LUCK || secondBonus.type == Bonus::LUCK)
  4757. iw.components.push_back(Component(Component::LUCK,0,gbonus.bonus.val,0));
  4758. cb->giveHeroBonus(&gbonus);
  4759. if(second)
  4760. {
  4761. gbonus.bonus = secondBonus;
  4762. cb->giveHeroBonus(&gbonus);
  4763. }
  4764. if(bonusMove) //swan pond - take all move points, stables - give move point this day
  4765. {
  4766. SetMovePoints smp;
  4767. smp.hid = h->id;
  4768. smp.val = h->movement + bonusMove;
  4769. cb->setMovePoints(&smp);
  4770. }
  4771. }
  4772. iw.text.addTxt(MetaString::ADVOB_TXT,messageID);
  4773. cb->showInfoDialog(&iw);
  4774. }
  4775. const std::string & CGBonusingObject::getHoverText() const
  4776. {
  4777. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4778. hoverName = VLC->generaltexth->names[ID];
  4779. if(h)
  4780. {
  4781. bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  4782. hoverName += " " + visitedTxt(visited);
  4783. }
  4784. return hoverName;
  4785. }
  4786. void CGBonusingObject::initObj()
  4787. {
  4788. if(ID == Obj::BUOY || ID == Obj::MERMAID)
  4789. {
  4790. blockVisit = true;
  4791. }
  4792. }
  4793. void CGMagicSpring::onHeroVisit(const CGHeroInstance * h) const
  4794. {
  4795. int messageID;
  4796. if (!visited)
  4797. {
  4798. if (h->mana > h->manaLimit())
  4799. messageID = 76;
  4800. else
  4801. {
  4802. messageID = 74;
  4803. cb->setManaPoints (h->id, 2 * h->manaLimit());
  4804. cb->setObjProperty (id, ObjProperty::VISITED, true);
  4805. }
  4806. }
  4807. else
  4808. messageID = 75;
  4809. showInfoDialog(h,messageID,soundBase::GENIE);
  4810. }
  4811. const std::string & CGMagicSpring::getHoverText() const
  4812. {
  4813. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  4814. return hoverName;
  4815. }
  4816. void CGMagicWell::onHeroVisit( const CGHeroInstance * h ) const
  4817. {
  4818. int message;
  4819. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Well today
  4820. {
  4821. message = 78;//"A second drink at the well in one day will not help you."
  4822. }
  4823. else if(h->mana < h->manaLimit())
  4824. {
  4825. giveDummyBonus(h->id);
  4826. cb->setManaPoints(h->id,h->manaLimit());
  4827. message = 77;
  4828. }
  4829. else
  4830. {
  4831. message = 79;
  4832. }
  4833. showInfoDialog(h,message,soundBase::faerie);
  4834. }
  4835. const std::string & CGMagicWell::getHoverText() const
  4836. {
  4837. getNameVis(hoverName);
  4838. return hoverName;
  4839. }
  4840. void CGPandoraBox::initObj()
  4841. {
  4842. blockVisit = (ID==Obj::PANDORAS_BOX); //block only if it's really pandora's box (events also derive from that class)
  4843. }
  4844. void CGPandoraBox::onHeroVisit(const CGHeroInstance * h) const
  4845. {
  4846. BlockingDialog bd (true, false);
  4847. bd.player = h->getOwner();
  4848. bd.soundID = soundBase::QUEST;
  4849. bd.text.addTxt (MetaString::ADVOB_TXT, 14);
  4850. cb->showBlockingDialog (&bd);
  4851. }
  4852. void CGPandoraBox::giveContents( const CGHeroInstance *h, bool afterBattle ) const
  4853. {
  4854. InfoWindow iw;
  4855. iw.player = h->getOwner();
  4856. std::string msg = message; //in case box is removed in the meantime
  4857. bool changesPrimSkill = false;
  4858. for (int i = 0; i < primskills.size(); i++)
  4859. {
  4860. if(primskills[i])
  4861. {
  4862. changesPrimSkill = true;
  4863. break;
  4864. }
  4865. }
  4866. if(gainedExp || changesPrimSkill || abilities.size())
  4867. {
  4868. TExpType expVal = h->calculateXp(gainedExp);
  4869. //getText(iw,afterBattle,175,h); //wtf?
  4870. iw.text.addTxt(MetaString::ADVOB_TXT, 175); //%s learns something
  4871. iw.text.addReplacement(h->name);
  4872. if(expVal)
  4873. iw.components.push_back(Component(Component::EXPERIENCE,0,expVal,0));
  4874. for(int i=0; i<primskills.size(); i++)
  4875. if(primskills[i])
  4876. iw.components.push_back(Component(Component::PRIM_SKILL,i,primskills[i],0));
  4877. for(int i=0; i<abilities.size(); i++)
  4878. iw.components.push_back(Component(Component::SEC_SKILL,abilities[i],abilityLevels[i],0));
  4879. cb->showInfoDialog(&iw);
  4880. //give exp
  4881. if(expVal)
  4882. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  4883. //give prim skills
  4884. for(int i=0; i<primskills.size(); i++)
  4885. if(primskills[i])
  4886. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(i),primskills[i],false);
  4887. //give sec skills
  4888. for(int i=0; i<abilities.size(); i++)
  4889. {
  4890. int curLev = h->getSecSkillLevel(abilities[i]);
  4891. if( (curLev && curLev < abilityLevels[i]) || (h->canLearnSkill() ))
  4892. {
  4893. cb->changeSecSkill(h,abilities[i],abilityLevels[i],true);
  4894. }
  4895. }
  4896. }
  4897. if(spells.size())
  4898. {
  4899. std::set<SpellID> spellsToGive;
  4900. iw.components.clear();
  4901. if (spells.size() > 1)
  4902. {
  4903. iw.text.addTxt(MetaString::ADVOB_TXT, 188); //%s learns spells
  4904. }
  4905. else
  4906. {
  4907. iw.text.addTxt(MetaString::ADVOB_TXT, 184); //%s learns a spell
  4908. }
  4909. iw.text.addReplacement(h->name);
  4910. std::vector<ConstTransitivePtr<CSpell> > * sp = &VLC->spellh->spells;
  4911. for(auto i=spells.cbegin(); i != spells.cend(); i++)
  4912. {
  4913. if ((*sp)[*i]->level <= h->getSecSkillLevel(SecondarySkill::WISDOM) + 2) //enough wisdom
  4914. {
  4915. iw.components.push_back(Component(Component::SPELL,*i,0,0));
  4916. spellsToGive.insert(*i);
  4917. }
  4918. }
  4919. if(spellsToGive.size())
  4920. {
  4921. cb->changeSpells(h,true,spellsToGive);
  4922. cb->showInfoDialog(&iw);
  4923. }
  4924. }
  4925. if(manaDiff)
  4926. {
  4927. getText(iw,afterBattle,manaDiff,176,177,h);
  4928. iw.components.push_back(Component(Component::PRIM_SKILL,5,manaDiff,0));
  4929. cb->showInfoDialog(&iw);
  4930. cb->setManaPoints(h->id, h->mana + manaDiff);
  4931. }
  4932. if(moraleDiff)
  4933. {
  4934. getText(iw,afterBattle,moraleDiff,178,179,h);
  4935. iw.components.push_back(Component(Component::MORALE,0,moraleDiff,0));
  4936. cb->showInfoDialog(&iw);
  4937. GiveBonus gb;
  4938. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,moraleDiff,id.getNum(),"");
  4939. gb.id = h->id.getNum();
  4940. cb->giveHeroBonus(&gb);
  4941. }
  4942. if(luckDiff)
  4943. {
  4944. getText(iw,afterBattle,luckDiff,180,181,h);
  4945. iw.components.push_back(Component(Component::LUCK,0,luckDiff,0));
  4946. cb->showInfoDialog(&iw);
  4947. GiveBonus gb;
  4948. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,luckDiff,id.getNum(),"");
  4949. gb.id = h->id.getNum();
  4950. cb->giveHeroBonus(&gb);
  4951. }
  4952. iw.components.clear();
  4953. iw.text.clear();
  4954. for(int i=0; i<resources.size(); i++)
  4955. {
  4956. if(resources[i] < 0)
  4957. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  4958. }
  4959. if(iw.components.size())
  4960. {
  4961. getText(iw,afterBattle,182,h);
  4962. cb->showInfoDialog(&iw);
  4963. }
  4964. iw.components.clear();
  4965. iw.text.clear();
  4966. for(int i=0; i<resources.size(); i++)
  4967. {
  4968. if(resources[i] > 0)
  4969. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  4970. }
  4971. if(iw.components.size())
  4972. {
  4973. getText(iw,afterBattle,183,h);
  4974. cb->showInfoDialog(&iw);
  4975. }
  4976. iw.components.clear();
  4977. // getText(iw,afterBattle,183,h);
  4978. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure
  4979. iw.text.addReplacement(h->name);
  4980. for(int i=0; i<artifacts.size(); i++)
  4981. {
  4982. iw.components.push_back(Component(Component::ARTIFACT,artifacts[i],0,0));
  4983. if(iw.components.size() >= 14)
  4984. {
  4985. cb->showInfoDialog(&iw);
  4986. iw.components.clear();
  4987. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure - once more?
  4988. iw.text.addReplacement(h->name);
  4989. }
  4990. }
  4991. if(iw.components.size())
  4992. {
  4993. cb->showInfoDialog(&iw);
  4994. }
  4995. for(int i=0; i<resources.size(); i++)
  4996. if(resources[i])
  4997. cb->giveResource(h->getOwner(),static_cast<Res::ERes>(i),resources[i]);
  4998. for(int i=0; i<artifacts.size(); i++)
  4999. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[artifacts[i]],ArtifactPosition::FIRST_AVAILABLE);
  5000. iw.components.clear();
  5001. iw.text.clear();
  5002. if (creatures.Slots().size())
  5003. { //this part is taken straight from creature bank
  5004. MetaString loot;
  5005. for(TSlots::const_iterator i = creatures.Slots().begin(); i != creatures.Slots().end(); i++)
  5006. { //build list of joined creatures
  5007. iw.components.push_back(Component(*i->second));
  5008. loot << "%s";
  5009. loot.addReplacement(*i->second);
  5010. }
  5011. if (creatures.Slots().size() == 1 && creatures.Slots().begin()->second->count == 1)
  5012. iw.text.addTxt(MetaString::ADVOB_TXT, 185);
  5013. else
  5014. iw.text.addTxt(MetaString::ADVOB_TXT, 186);
  5015. iw.text.addReplacement(loot.buildList());
  5016. iw.text.addReplacement(h->name);
  5017. cb->showInfoDialog(&iw);
  5018. cb->giveCreatures(this, h, creatures, true);
  5019. }
  5020. if(!afterBattle && msg.size())
  5021. {
  5022. iw.text << msg;
  5023. cb->showInfoDialog(&iw);
  5024. }
  5025. if (!creatures.Slots().size())
  5026. cb->removeObject(this); //only when we don't need to display garrison window
  5027. }
  5028. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int text, const CGHeroInstance * h ) const
  5029. {
  5030. if(afterBattle || !message.size())
  5031. {
  5032. iw.text.addTxt(MetaString::ADVOB_TXT,text);//%s has lost treasure.
  5033. iw.text.addReplacement(h->name);
  5034. }
  5035. else
  5036. {
  5037. iw.text << message;
  5038. afterBattle = true;
  5039. }
  5040. }
  5041. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int val, int negative, int positive, const CGHeroInstance * h ) const
  5042. {
  5043. iw.components.clear();
  5044. iw.text.clear();
  5045. if(afterBattle || !message.size())
  5046. {
  5047. iw.text.addTxt(MetaString::ADVOB_TXT,val < 0 ? negative : positive); //%s's luck takes a turn for the worse / %s's luck increases
  5048. iw.text.addReplacement(h->name);
  5049. }
  5050. else
  5051. {
  5052. iw.text << message;
  5053. afterBattle = true;
  5054. }
  5055. }
  5056. void CGPandoraBox::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5057. {
  5058. if(result.winner)
  5059. return;
  5060. giveContents(hero, true);
  5061. }
  5062. void CGPandoraBox::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5063. {
  5064. if (answer)
  5065. {
  5066. if (stacksCount() > 0) //if pandora's box is protected by army
  5067. {
  5068. showInfoDialog(hero,16,0);
  5069. cb->startBattleI(hero, this); //grants things after battle
  5070. }
  5071. else if (message.size() == 0 && resources.size() == 0
  5072. && primskills.size() == 0 && abilities.size() == 0
  5073. && abilityLevels.size() == 0 && artifacts.size() == 0
  5074. && spells.size() == 0 && creatures.Slots().size() > 0
  5075. && gainedExp == 0 && manaDiff == 0 && moraleDiff == 0 && luckDiff == 0) //if it gives nothing without battle
  5076. {
  5077. showInfoDialog(hero,15,0);
  5078. cb->removeObject(this);
  5079. }
  5080. else //if it gives something without battle
  5081. {
  5082. giveContents(hero, false);
  5083. }
  5084. }
  5085. }
  5086. void CGEvent::onHeroVisit( const CGHeroInstance * h ) const
  5087. {
  5088. if(!(availableFor & (1 << h->tempOwner.getNum())))
  5089. return;
  5090. if(cb->getPlayerSettings(h->tempOwner)->playerID)
  5091. {
  5092. if(humanActivate)
  5093. activated(h);
  5094. }
  5095. else if(computerActivate)
  5096. activated(h);
  5097. }
  5098. void CGEvent::activated( const CGHeroInstance * h ) const
  5099. {
  5100. if(stacksCount() > 0)
  5101. {
  5102. InfoWindow iw;
  5103. iw.player = h->tempOwner;
  5104. if(message.size())
  5105. iw.text << message;
  5106. else
  5107. iw.text.addTxt(MetaString::ADVOB_TXT, 16);
  5108. cb->showInfoDialog(&iw);
  5109. cb->startBattleI(h, this);
  5110. }
  5111. else
  5112. {
  5113. giveContents(h,false);
  5114. }
  5115. }
  5116. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  5117. {
  5118. InfoWindow iw;
  5119. iw.player = h->tempOwner;
  5120. switch (ID)
  5121. {
  5122. case Obj::REDWOOD_OBSERVATORY:
  5123. case Obj::PILLAR_OF_FIRE:
  5124. {
  5125. iw.soundID = soundBase::LIGHTHOUSE;
  5126. iw.text.addTxt(MetaString::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  5127. FoWChange fw;
  5128. fw.player = h->tempOwner;
  5129. fw.mode = 1;
  5130. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  5131. cb->sendAndApply (&fw);
  5132. break;
  5133. }
  5134. case Obj::COVER_OF_DARKNESS:
  5135. {
  5136. iw.text.addTxt (MetaString::ADVOB_TXT, 31);
  5137. hideTiles(h->tempOwner, 20);
  5138. break;
  5139. }
  5140. }
  5141. cb->showInfoDialog(&iw);
  5142. }
  5143. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  5144. {
  5145. if(spell == SpellID::NONE)
  5146. {
  5147. logGlobal->errorStream() << "Not initialized shrine visited!";
  5148. return;
  5149. }
  5150. if(!wasVisited(h->tempOwner))
  5151. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  5152. InfoWindow iw;
  5153. iw.soundID = soundBase::temple;
  5154. iw.player = h->getOwner();
  5155. iw.text.addTxt(MetaString::ADVOB_TXT,127 + ID - 88);
  5156. iw.text.addTxt(MetaString::SPELL_NAME,spell);
  5157. iw.text << ".";
  5158. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  5159. {
  5160. iw.text.addTxt(MetaString::ADVOB_TXT,131);
  5161. }
  5162. else if(ID == Obj::SHRINE_OF_MAGIC_THOUGHT && !h->getSecSkillLevel(SecondarySkill::WISDOM)) //it's third level spell and hero doesn't have wisdom
  5163. {
  5164. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  5165. }
  5166. else if(vstd::contains(h->spells,spell))//hero already knows the spell
  5167. {
  5168. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  5169. }
  5170. else //give spell
  5171. {
  5172. std::set<SpellID> spells;
  5173. spells.insert(spell);
  5174. cb->changeSpells(h, true, spells);
  5175. iw.components.push_back(Component(Component::SPELL,spell,0,0));
  5176. }
  5177. cb->showInfoDialog(&iw);
  5178. }
  5179. void CGShrine::initObj()
  5180. {
  5181. if(spell == SpellID::NONE) //spell not set
  5182. {
  5183. int level = ID-87;
  5184. std::vector<SpellID> possibilities;
  5185. cb->getAllowedSpells (possibilities, level);
  5186. if(!possibilities.size())
  5187. {
  5188. logGlobal->errorStream() << "Error: cannot init shrine, no allowed spells!";
  5189. return;
  5190. }
  5191. spell = possibilities[ran() % possibilities.size()];
  5192. }
  5193. }
  5194. const std::string & CGShrine::getHoverText() const
  5195. {
  5196. hoverName = VLC->generaltexth->names[ID];
  5197. if(wasVisited(cb->getCurrentPlayer())) //TODO: use local player, not current
  5198. {
  5199. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  5200. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->name);
  5201. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  5202. if(h && vstd::contains(h->spells,spell)) //hero knows that ability
  5203. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  5204. }
  5205. return hoverName;
  5206. }
  5207. void CGSignBottle::initObj()
  5208. {
  5209. //if no text is set than we pick random from the predefined ones
  5210. if(!message.size())
  5211. message = VLC->generaltexth->randsign[ran()%VLC->generaltexth->randsign.size()];
  5212. if(ID == Obj::OCEAN_BOTTLE)
  5213. {
  5214. blockVisit = true;
  5215. }
  5216. }
  5217. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  5218. {
  5219. InfoWindow iw;
  5220. iw.soundID = soundBase::STORE;
  5221. iw.player = h->getOwner();
  5222. iw.text << message;
  5223. cb->showInfoDialog(&iw);
  5224. if(ID == Obj::OCEAN_BOTTLE)
  5225. cb->removeObject(this);
  5226. }
  5227. //TODO: remove
  5228. //void CGScholar::giveAnyBonus( const CGHeroInstance * h ) const
  5229. //{
  5230. //
  5231. //}
  5232. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  5233. {
  5234. EBonusType type = bonusType;
  5235. int bid = bonusID;
  5236. //check if the bonus if applicable, if not - give primary skill (always possible)
  5237. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  5238. if((type == SECONDARY_SKILL
  5239. && ((ssl == 3) || (!ssl && !h->canLearnSkill()))) ////hero already has expert level in the skill or (don't know skill and doesn't have free slot)
  5240. || (type == SPELL && (!h->getArt(ArtifactPosition::SPELLBOOK) || vstd::contains(h->spells, (ui32) bid)
  5241. || ( SpellID(bid).toSpell()->level > h->getSecSkillLevel(SecondarySkill::WISDOM) + 2)
  5242. ))) //hero doesn't have a spellbook or already knows the spell or doesn't have Wisdom
  5243. {
  5244. type = PRIM_SKILL;
  5245. bid = ran() % GameConstants::PRIMARY_SKILLS;
  5246. }
  5247. InfoWindow iw;
  5248. iw.soundID = soundBase::gazebo;
  5249. iw.player = h->getOwner();
  5250. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  5251. switch (type)
  5252. {
  5253. case PRIM_SKILL:
  5254. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  5255. iw.components.push_back(Component(Component::PRIM_SKILL,bid,+1,0));
  5256. break;
  5257. case SECONDARY_SKILL:
  5258. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  5259. iw.components.push_back(Component(Component::SEC_SKILL,bid,ssl+1,0));
  5260. break;
  5261. case SPELL:
  5262. {
  5263. std::set<SpellID> hlp;
  5264. hlp.insert(SpellID(bid));
  5265. cb->changeSpells(h,true,hlp);
  5266. iw.components.push_back(Component(Component::SPELL,bid,0,0));
  5267. }
  5268. break;
  5269. default:
  5270. logGlobal->errorStream() << "Error: wrong bonus type (" << (int)type << ") for Scholar!\n";
  5271. return;
  5272. }
  5273. cb->showInfoDialog(&iw);
  5274. cb->removeObject(this);
  5275. }
  5276. void CGScholar::initObj()
  5277. {
  5278. blockVisit = true;
  5279. if(bonusType == RANDOM)
  5280. {
  5281. bonusType = static_cast<EBonusType>(ran()%3);
  5282. switch(bonusType)
  5283. {
  5284. case PRIM_SKILL:
  5285. bonusID = ran() % GameConstants::PRIMARY_SKILLS;
  5286. break;
  5287. case SECONDARY_SKILL:
  5288. bonusID = ran() % GameConstants::SKILL_QUANTITY;
  5289. break;
  5290. case SPELL:
  5291. std::vector<SpellID> possibilities;
  5292. for (int i = 1; i < 6; ++i)
  5293. cb->getAllowedSpells (possibilities, i);
  5294. bonusID = possibilities[ran() % possibilities.size()];
  5295. break;
  5296. }
  5297. }
  5298. }
  5299. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  5300. {
  5301. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  5302. if (!ally && stacksCount() > 0) {
  5303. //TODO: Find a way to apply magic garrison effects in battle.
  5304. cb->startBattleI(h, this);
  5305. return;
  5306. }
  5307. //New owner.
  5308. if (!ally)
  5309. cb->setOwner(this, h->tempOwner);
  5310. cb->showGarrisonDialog(id, h->id, removableUnits);
  5311. }
  5312. ui8 CGGarrison::getPassableness() const
  5313. {
  5314. if ( !stacksCount() )//empty - anyone can visit
  5315. return GameConstants::ALL_PLAYERS;
  5316. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  5317. return 0;
  5318. ui8 mask = 0;
  5319. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  5320. BOOST_FOREACH(PlayerColor it, ts->players)
  5321. mask |= 1<<it.getNum(); //allies - add to possible visitors
  5322. return mask;
  5323. }
  5324. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5325. {
  5326. if (result.winner == 0)
  5327. onHeroVisit(hero);
  5328. }
  5329. void CGOnceVisitable::onHeroVisit( const CGHeroInstance * h ) const
  5330. {
  5331. int sound = soundBase::sound_todo;
  5332. int txtid;
  5333. switch(ID)
  5334. {
  5335. case Obj::CORPSE:
  5336. txtid = 37;
  5337. sound = soundBase::MYSTERY;
  5338. break;
  5339. case Obj::LEAN_TO:
  5340. sound = soundBase::GENIE;
  5341. txtid = 64;
  5342. break;
  5343. case Obj::WAGON:
  5344. sound = soundBase::GENIE;
  5345. txtid = 154;
  5346. break;
  5347. case Obj::WARRIORS_TOMB:
  5348. {
  5349. //ask if player wants to search the Tomb
  5350. BlockingDialog bd(true, false);
  5351. bd.soundID = soundBase::GRAVEYARD;
  5352. bd.player = h->getOwner();
  5353. bd.text.addTxt(MetaString::ADVOB_TXT,161);
  5354. cb->showBlockingDialog(&bd);
  5355. return;
  5356. }
  5357. break;
  5358. default:
  5359. logGlobal->errorStream() << "Error: Unknown object (" << ID <<") treated as CGOnceVisitable!";
  5360. return;
  5361. }
  5362. InfoWindow iw;
  5363. iw.soundID = sound;
  5364. iw.player = h->getOwner();
  5365. if(players.size()) //we have been already visited...
  5366. {
  5367. txtid++;
  5368. if(ID == Obj::WAGON) //wagon has extra text (for finding art) we need to omit
  5369. txtid++;
  5370. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5371. }
  5372. else //first visit - give bonus!
  5373. {
  5374. switch(artOrRes)
  5375. {
  5376. case 0: // first visit but empty
  5377. if (ID == Obj::CORPSE)
  5378. ++txtid;
  5379. else
  5380. txtid+=2;
  5381. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5382. break;
  5383. case 1: //art
  5384. iw.components.push_back(Component(Component::ARTIFACT,bonusType,0,0));
  5385. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[bonusType],ArtifactPosition::FIRST_AVAILABLE);
  5386. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5387. if (ID == Obj::CORPSE)
  5388. {
  5389. iw.text << "%s";
  5390. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5391. }
  5392. break;
  5393. case 2: //res
  5394. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5395. iw.components.push_back (Component(Component::RESOURCE, bonusType, bonusVal, 0));
  5396. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(bonusType), bonusVal);
  5397. break;
  5398. }
  5399. if(ID == Obj::WAGON && artOrRes == 1)
  5400. {
  5401. iw.text.localStrings.back().second++;
  5402. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5403. }
  5404. }
  5405. cb->showInfoDialog(&iw);
  5406. cb->setObjProperty(id, 10, h->getOwner().getNum());
  5407. }
  5408. const std::string & CGOnceVisitable::getHoverText() const
  5409. {
  5410. const bool visited = wasVisited(cb->getCurrentPlayer());
  5411. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  5412. return hoverName;
  5413. }
  5414. void CGOnceVisitable::initObj()
  5415. {
  5416. switch(ID)
  5417. {
  5418. case Obj::CORPSE:
  5419. {
  5420. blockVisit = true;
  5421. int hlp = ran()%100;
  5422. if(hlp < 20)
  5423. {
  5424. artOrRes = 1;
  5425. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR);
  5426. }
  5427. else
  5428. {
  5429. artOrRes = 0;
  5430. }
  5431. }
  5432. break;
  5433. case Obj::LEAN_TO:
  5434. {
  5435. artOrRes = 2;
  5436. bonusType = ran()%6; //any basic resource without gold
  5437. bonusVal = ran()%4 + 1;
  5438. }
  5439. break;
  5440. case Obj::WARRIORS_TOMB:
  5441. {
  5442. artOrRes = 1;
  5443. int hlp = ran()%100;
  5444. if(hlp < 30)
  5445. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE);
  5446. else if(hlp < 80)
  5447. bonusType = cb->getRandomArt (CArtifact::ART_MINOR);
  5448. else if(hlp < 95)
  5449. bonusType = cb->getRandomArt (CArtifact::ART_MAJOR);
  5450. else
  5451. bonusType = cb->getRandomArt (CArtifact::ART_RELIC);
  5452. }
  5453. break;
  5454. case Obj::WAGON:
  5455. {
  5456. int hlp = ran()%100;
  5457. if(hlp < 10)
  5458. {
  5459. artOrRes = 0; // nothing... :(
  5460. }
  5461. else if(hlp < 50) //minor or treasure art
  5462. {
  5463. artOrRes = 1;
  5464. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR);
  5465. }
  5466. else //2 - 5 of non-gold resource
  5467. {
  5468. artOrRes = 2;
  5469. bonusType = ran()%6;
  5470. bonusVal = ran()%4 + 2;
  5471. }
  5472. }
  5473. break;
  5474. }
  5475. }
  5476. void CGOnceVisitable::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5477. {
  5478. //must have been Tomb
  5479. if(answer)
  5480. {
  5481. InfoWindow iw;
  5482. iw.player = hero->getOwner();
  5483. iw.components.push_back(Component(Component::MORALE,0,-3,0));
  5484. if(players.size()) //we've been already visited, player found nothing
  5485. {
  5486. iw.text.addTxt(MetaString::ADVOB_TXT,163);
  5487. }
  5488. else //first visit - give artifact
  5489. {
  5490. iw.text.addTxt(MetaString::ADVOB_TXT,162);
  5491. iw.components.push_back(Component(Component::ARTIFACT,bonusType,0,0));
  5492. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5493. cb->giveHeroNewArtifact(hero, VLC->arth->artifacts[bonusType],ArtifactPosition::FIRST_AVAILABLE);
  5494. }
  5495. if(!hero->hasBonusFrom(Bonus::OBJECT,ID)) //we don't have modifier from this object yet
  5496. {
  5497. //ruin morale
  5498. GiveBonus gb;
  5499. gb.id = hero->id.getNum();
  5500. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,-3,id.getNum(),"");
  5501. gb.bdescr.addTxt(MetaString::ARRAY_TXT,104); //Warrior Tomb Visited -3
  5502. cb->giveHeroBonus(&gb);
  5503. }
  5504. cb->showInfoDialog(&iw);
  5505. cb->setObjProperty(id, 10, hero->getOwner().getNum());
  5506. }
  5507. }
  5508. void CBank::initObj()
  5509. {
  5510. index = VLC->objh->bankObjToIndex(this);
  5511. bc = NULL;
  5512. daycounter = 0;
  5513. multiplier = 1;
  5514. }
  5515. const std::string & CBank::getHoverText() const
  5516. {
  5517. bool visited = (bc == nullptr);
  5518. hoverName = VLC->objh->creBanksNames[index] + " " + visitedTxt(visited);
  5519. return hoverName;
  5520. }
  5521. void CBank::reset(ui16 var1) //prevents desync
  5522. {
  5523. ui8 chance = 0;
  5524. for (ui8 i = 0; i < VLC->objh->banksInfo[index].size(); i++)
  5525. {
  5526. if (var1 < (chance += VLC->objh->banksInfo[index][i]->chance))
  5527. {
  5528. bc = VLC->objh->banksInfo[index][i];
  5529. break;
  5530. }
  5531. }
  5532. artifacts.clear();
  5533. }
  5534. void CBank::initialize() const
  5535. {
  5536. cb->setObjProperty (id, ObjProperty::BANK_RESET, ran()); //synchronous reset
  5537. for (ui8 i = 0; i <= 3; i++)
  5538. {
  5539. for (ui8 n = 0; n < bc->artifacts[i]; n++)
  5540. {
  5541. CArtifact::EartClass artClass;
  5542. switch(i)
  5543. {
  5544. case 0: artClass = CArtifact::ART_TREASURE; break;
  5545. case 1: artClass = CArtifact::ART_MINOR; break;
  5546. case 2: artClass = CArtifact::ART_MAJOR; break;
  5547. case 3: artClass = CArtifact::ART_RELIC; break;
  5548. default: assert(0); continue;
  5549. }
  5550. int artID = cb->getArtSync(ran(), artClass, true);
  5551. cb->setObjProperty(id, ObjProperty::BANK_ADD_ARTIFACT, artID);
  5552. }
  5553. }
  5554. cb->setObjProperty (id, ObjProperty::BANK_INIT_ARMY, ran()); //get army
  5555. }
  5556. void CBank::setPropertyDer (ui8 what, ui32 val)
  5557. /// random values are passed as arguments and processed identically on all clients
  5558. {
  5559. switch (what)
  5560. {
  5561. case ObjProperty::BANK_DAYCOUNTER: //daycounter
  5562. if (val == 0)
  5563. daycounter = 1; //yes, 1
  5564. else
  5565. daycounter++;
  5566. break;
  5567. case ObjProperty::BANK_MULTIPLIER: //multiplier, in percent
  5568. multiplier = val / 100.0;
  5569. break;
  5570. case 13: //bank preset
  5571. bc = VLC->objh->banksInfo[index][val];
  5572. break;
  5573. case ObjProperty::BANK_RESET:
  5574. reset (val%100);
  5575. break;
  5576. case ObjProperty::BANK_CLEAR_CONFIG:
  5577. bc = NULL;
  5578. break;
  5579. case ObjProperty::BANK_CLEAR_ARTIFACTS: //remove rewards from Derelict Ship
  5580. artifacts.clear();
  5581. break;
  5582. case ObjProperty::BANK_INIT_ARMY: //set ArmedInstance army
  5583. {
  5584. int upgraded = 0;
  5585. if (val%100 < bc->upgradeChance) //once again anti-desync
  5586. upgraded = 1;
  5587. switch (bc->guards.size())
  5588. {
  5589. case 1:
  5590. for (int i = 0; i < 4; ++i)
  5591. setCreature (SlotID(i), bc->guards[0].first, bc->guards[0].second / 5 );
  5592. setCreature (SlotID(4), CreatureID(bc->guards[0].first + upgraded), bc->guards[0].second / 5 );
  5593. break;
  5594. case 4:
  5595. {
  5596. if (bc->guards.back().second) //all stacks are present
  5597. {
  5598. for (auto it = bc->guards.begin(); it != bc->guards.end(); it++)
  5599. {
  5600. setCreature (SlotID(stacksCount()), it->first, it->second);
  5601. }
  5602. }
  5603. else if (bc->guards[2].second)//Wraiths are present, split two stacks in Crypt
  5604. {
  5605. setCreature (SlotID(0), bc->guards[0].first, bc->guards[0].second / 2 );
  5606. setCreature (SlotID(1), bc->guards[1].first, bc->guards[1].second / 2);
  5607. setCreature (SlotID(2), CreatureID(bc->guards[2].first + upgraded), bc->guards[2].second);
  5608. setCreature (SlotID(3), bc->guards[1].first, bc->guards[1].second / 2 );
  5609. setCreature (SlotID(4), bc->guards[0].first, bc->guards[0].second - (bc->guards[0].second / 2) );
  5610. }
  5611. else //split both stacks
  5612. {
  5613. for (int i = 0; i < 3; ++i) //skellies
  5614. setCreature (SlotID(2*i), bc->guards[0].first, bc->guards[0].second / 3);
  5615. for (int i = 0; i < 2; ++i) //zombies
  5616. setCreature (SlotID(2*i+1), bc->guards[1].first, bc->guards[1].second / 2);
  5617. }
  5618. }
  5619. break;
  5620. default:
  5621. logGlobal->warnStream() << "Error: Unexpected army data: " << bc->guards.size() <<" items found";
  5622. return;
  5623. }
  5624. }
  5625. break;
  5626. case ObjProperty::BANK_ADD_ARTIFACT: //add Artifact
  5627. {
  5628. artifacts.push_back (val);
  5629. break;
  5630. }
  5631. }
  5632. }
  5633. void CBank::newTurn() const
  5634. {
  5635. if (bc == NULL)
  5636. {
  5637. if (cb->getDate() == 1)
  5638. initialize(); //initialize on first day
  5639. else if (daycounter >= 28 && (subID < 13 || subID > 16)) //no reset for Emissaries
  5640. {
  5641. initialize();
  5642. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 0); //daycounter 0
  5643. if (ID == Obj::DERELICT_SHIP && cb->getDate() > 1)
  5644. {
  5645. cb->setObjProperty (id, ObjProperty::BANK_MULTIPLIER, 0);//ugly hack to make derelict ships usable only once
  5646. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_ARTIFACTS, 0);
  5647. }
  5648. }
  5649. else
  5650. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 1); //daycounter++
  5651. }
  5652. }
  5653. bool CBank::wasVisited (PlayerColor player) const
  5654. {
  5655. return !bc;
  5656. }
  5657. void CBank::onHeroVisit (const CGHeroInstance * h) const
  5658. {
  5659. if (bc)
  5660. {
  5661. int banktext = 0;
  5662. switch (ID)
  5663. {
  5664. case Obj::CREATURE_BANK:
  5665. banktext = 32;
  5666. break;
  5667. case Obj::DERELICT_SHIP:
  5668. banktext = 41;
  5669. break;
  5670. case Obj::DRAGON_UTOPIA:
  5671. banktext = 47;
  5672. break;
  5673. case Obj::CRYPT:
  5674. banktext = 119;
  5675. break;
  5676. case Obj::SHIPWRECK:
  5677. banktext = 122;
  5678. break;
  5679. }
  5680. BlockingDialog bd (true, false);
  5681. bd.player = h->getOwner();
  5682. bd.soundID = soundBase::ROGUE;
  5683. bd.text.addTxt(MetaString::ADVOB_TXT,banktext);
  5684. if (ID == Obj::CREATURE_BANK)
  5685. bd.text.addReplacement(VLC->objh->creBanksNames[index]);
  5686. cb->showBlockingDialog (&bd);
  5687. }
  5688. else
  5689. {
  5690. InfoWindow iw;
  5691. iw.soundID = soundBase::GRAVEYARD;
  5692. iw.player = h->getOwner();
  5693. if (ID == Obj::CRYPT) //morale penalty for empty Crypt
  5694. {
  5695. GiveBonus gbonus;
  5696. gbonus.id = h->id.getNum();
  5697. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5698. gbonus.bonus.source = Bonus::OBJECT;
  5699. gbonus.bonus.sid = ID;
  5700. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[98];
  5701. gbonus.bonus.type = Bonus::MORALE;
  5702. gbonus.bonus.val = -1;
  5703. cb->giveHeroBonus(&gbonus);
  5704. iw.text << VLC->generaltexth->advobtxt[120];
  5705. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5706. }
  5707. else
  5708. {
  5709. iw.text << VLC->generaltexth->advobtxt[33];
  5710. iw.text.addReplacement(VLC->objh->creBanksNames[index]);
  5711. }
  5712. cb->showInfoDialog(&iw);
  5713. }
  5714. }
  5715. void CBank::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5716. {
  5717. if (result.winner == 0)
  5718. {
  5719. int textID = -1;
  5720. InfoWindow iw;
  5721. iw.player = hero->getOwner();
  5722. MetaString loot;
  5723. switch (ID)
  5724. {
  5725. case Obj::CREATURE_BANK: case Obj::DRAGON_UTOPIA:
  5726. textID = 34;
  5727. break;
  5728. case Obj::DERELICT_SHIP:
  5729. if (multiplier)
  5730. textID = 43;
  5731. else
  5732. {
  5733. GiveBonus gbonus;
  5734. gbonus.id = hero->id.getNum();
  5735. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5736. gbonus.bonus.source = Bonus::OBJECT;
  5737. gbonus.bonus.sid = ID;
  5738. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[101];
  5739. gbonus.bonus.type = Bonus::MORALE;
  5740. gbonus.bonus.val = -1;
  5741. cb->giveHeroBonus(&gbonus);
  5742. textID = 42;
  5743. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5744. }
  5745. break;
  5746. case Obj::CRYPT:
  5747. if (bc->resources.size() != 0)
  5748. textID = 121;
  5749. else
  5750. {
  5751. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5752. GiveBonus gbonus;
  5753. gbonus.id = hero->id.getNum();
  5754. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5755. gbonus.bonus.source = Bonus::OBJECT;
  5756. gbonus.bonus.sid = ID;
  5757. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[ID];
  5758. gbonus.bonus.type = Bonus::MORALE;
  5759. gbonus.bonus.val = -1;
  5760. cb->giveHeroBonus(&gbonus);
  5761. textID = 120;
  5762. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5763. }
  5764. break;
  5765. case Obj::SHIPWRECK:
  5766. if (bc->resources.size())
  5767. textID = 124;
  5768. else
  5769. textID = 123;
  5770. break;
  5771. }
  5772. //grant resources
  5773. if (textID != 42) //empty derelict ship gives no cash
  5774. {
  5775. for (int it = 0; it < bc->resources.size(); it++)
  5776. {
  5777. if (bc->resources[it] != 0)
  5778. {
  5779. iw.components.push_back (Component (Component::RESOURCE, it, bc->resources[it], 0));
  5780. loot << "%d %s";
  5781. loot.addReplacement(iw.components.back().val);
  5782. loot.addReplacement(MetaString::RES_NAMES, iw.components.back().subtype);
  5783. cb->giveResource (hero->getOwner(), static_cast<Res::ERes>(it), bc->resources[it]);
  5784. }
  5785. }
  5786. }
  5787. //grant artifacts
  5788. for (std::vector<ui32>::const_iterator it = artifacts.begin(); it != artifacts.end(); it++)
  5789. {
  5790. iw.components.push_back (Component (Component::ARTIFACT, *it, 0, 0));
  5791. loot << "%s";
  5792. loot.addReplacement(MetaString::ART_NAMES, *it);
  5793. cb->giveHeroNewArtifact (hero, VLC->arth->artifacts[*it], ArtifactPosition::FIRST_AVAILABLE);
  5794. }
  5795. //display loot
  5796. if (!iw.components.empty())
  5797. {
  5798. iw.text.addTxt (MetaString::ADVOB_TXT, textID);
  5799. if (textID == 34)
  5800. {
  5801. iw.text.addReplacement(MetaString::CRE_PL_NAMES, result.casualties[1].begin()->first);
  5802. iw.text.addReplacement(loot.buildList());
  5803. }
  5804. cb->showInfoDialog(&iw);
  5805. }
  5806. loot.clear();
  5807. iw.components.clear();
  5808. iw.text.clear();
  5809. //grant creatures
  5810. CCreatureSet ourArmy;
  5811. for (auto it = bc->creatures.cbegin(); it != bc->creatures.cend(); it++)
  5812. {
  5813. SlotID slot = ourArmy.getSlotFor(it->first);
  5814. ourArmy.addToSlot(slot, it->first, it->second);
  5815. }
  5816. for (TSlots::const_iterator i = ourArmy.Slots().begin(); i != ourArmy.Slots().end(); i++)
  5817. {
  5818. iw.components.push_back(Component(*i->second));
  5819. loot << "%s";
  5820. loot.addReplacement(*i->second);
  5821. }
  5822. if (ourArmy.Slots().size())
  5823. {
  5824. if (ourArmy.Slots().size() == 1 && ourArmy.Slots().begin()->second->count == 1)
  5825. iw.text.addTxt (MetaString::ADVOB_TXT, 185);
  5826. else
  5827. iw.text.addTxt (MetaString::ADVOB_TXT, 186);
  5828. iw.text.addReplacement(loot.buildList());
  5829. iw.text.addReplacement(hero->name);
  5830. cb->showInfoDialog(&iw);
  5831. cb->giveCreatures(this, hero, ourArmy, false);
  5832. }
  5833. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0); //bc = NULL
  5834. }
  5835. }
  5836. void CBank::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5837. {
  5838. if (answer)
  5839. {
  5840. cb->startBattleI(hero, this, true);
  5841. }
  5842. }
  5843. void CGPyramid::initObj()
  5844. {
  5845. std::vector<SpellID> available;
  5846. cb->getAllowedSpells (available, 5);
  5847. if (available.size())
  5848. {
  5849. bc = VLC->objh->banksInfo[21].front(); //TODO: remove hardcoded value?
  5850. spell = (available[ran()%available.size()]);
  5851. }
  5852. else
  5853. {
  5854. logGlobal->errorStream() <<"No spells available for Pyramid! Object set to empty.";
  5855. }
  5856. setPropertyDer (ObjProperty::BANK_INIT_ARMY,ran()); //set guards at game start
  5857. }
  5858. const std::string & CGPyramid::getHoverText() const
  5859. {
  5860. hoverName = VLC->objh->creBanksNames[21]+ " " + visitedTxt((bc==nullptr));
  5861. return hoverName;
  5862. }
  5863. void CGPyramid::onHeroVisit (const CGHeroInstance * h) const
  5864. {
  5865. if (bc)
  5866. {
  5867. BlockingDialog bd (true, false);
  5868. bd.player = h->getOwner();
  5869. bd.soundID = soundBase::MYSTERY;
  5870. bd.text << VLC->generaltexth->advobtxt[105];
  5871. cb->showBlockingDialog(&bd);
  5872. }
  5873. else
  5874. {
  5875. InfoWindow iw;
  5876. iw.player = h->getOwner();
  5877. iw.text << VLC->generaltexth->advobtxt[107];
  5878. iw.components.push_back (Component (Component::LUCK, 0 , -2, 0));
  5879. GiveBonus gb;
  5880. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,-2,id.getNum(),VLC->generaltexth->arraytxt[70]);
  5881. gb.id = h->id.getNum();
  5882. cb->giveHeroBonus(&gb);
  5883. cb->showInfoDialog(&iw);
  5884. }
  5885. }
  5886. void CGPyramid::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5887. {
  5888. if (result.winner == 0)
  5889. {
  5890. InfoWindow iw;
  5891. iw.player = hero->getOwner();
  5892. iw.text.addTxt (MetaString::ADVOB_TXT, 106);
  5893. iw.text.addTxt (MetaString::SPELL_NAME, spell);
  5894. if (!hero->getArt(ArtifactPosition::SPELLBOOK))
  5895. iw.text.addTxt (MetaString::ADVOB_TXT, 109); //no spellbook
  5896. else if (hero->getSecSkillLevel(SecondarySkill::WISDOM) < 3)
  5897. iw.text.addTxt (MetaString::ADVOB_TXT, 108); //no expert Wisdom
  5898. else
  5899. {
  5900. std::set<SpellID> spells;
  5901. spells.insert (SpellID(spell));
  5902. cb->changeSpells (hero, true, spells);
  5903. iw.components.push_back(Component (Component::SPELL, spell, 0, 0));
  5904. }
  5905. cb->showInfoDialog(&iw);
  5906. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0);
  5907. }
  5908. }
  5909. void CGKeys::setPropertyDer (ui8 what, ui32 val) //101-108 - enable key for player 1-8
  5910. {
  5911. if (what >= 101 && what <= (100 + PlayerColor::PLAYER_LIMIT_I))
  5912. playerKeyMap.find(PlayerColor(what-101))->second.insert((ui8)val);
  5913. }
  5914. bool CGKeys::wasMyColorVisited (PlayerColor player) const
  5915. {
  5916. if (vstd::contains(playerKeyMap[player], subID)) //creates set if it's not there
  5917. return true;
  5918. else
  5919. return false;
  5920. }
  5921. const std::string& CGKeys::getHoverText() const
  5922. {
  5923. bool visited = wasMyColorVisited (cb->getLocalPlayer());
  5924. hoverName = getName() + "\n" + visitedTxt(visited);
  5925. return hoverName;
  5926. }
  5927. const std::string CGKeys::getName() const
  5928. {
  5929. std::string name;
  5930. name = VLC->generaltexth->tentColors[subID] + " " + VLC->generaltexth->names[ID];
  5931. return name;
  5932. }
  5933. bool CGKeymasterTent::wasVisited (PlayerColor player) const
  5934. {
  5935. return wasMyColorVisited (player);
  5936. }
  5937. void CGKeymasterTent::onHeroVisit( const CGHeroInstance * h ) const
  5938. {
  5939. int txt_id;
  5940. if (!wasMyColorVisited (h->getOwner()) )
  5941. {
  5942. cb->setObjProperty(id, h->tempOwner.getNum()+101, subID);
  5943. txt_id=19;
  5944. }
  5945. else
  5946. txt_id=20;
  5947. showInfoDialog(h,txt_id,soundBase::CAVEHEAD);
  5948. }
  5949. void CGBorderGuard::initObj()
  5950. {
  5951. //ui32 m13489val = subID; //store color as quest info
  5952. blockVisit = true;
  5953. }
  5954. void CGBorderGuard::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  5955. {
  5956. text << std::pair<ui8,ui32>(11,18);
  5957. }
  5958. void CGBorderGuard::getRolloverText (MetaString &text, bool onHover) const
  5959. {
  5960. if (!onHover)
  5961. text << VLC->generaltexth->tentColors[subID] << " " << VLC->generaltexth->names[Obj::KEYMASTER];
  5962. }
  5963. bool CGBorderGuard::checkQuest (const CGHeroInstance * h) const
  5964. {
  5965. return wasMyColorVisited (h->tempOwner);
  5966. }
  5967. void CGBorderGuard::onHeroVisit( const CGHeroInstance * h ) const
  5968. {
  5969. if (wasMyColorVisited (h->getOwner()) )
  5970. {
  5971. BlockingDialog bd (true, false);
  5972. bd.player = h->getOwner();
  5973. bd.soundID = soundBase::QUEST;
  5974. bd.text.addTxt (MetaString::ADVOB_TXT, 17);
  5975. cb->showBlockingDialog (&bd);
  5976. }
  5977. else
  5978. {
  5979. showInfoDialog(h,18,soundBase::CAVEHEAD);
  5980. AddQuest aq;
  5981. aq.quest = QuestInfo (quest, this, visitablePos());
  5982. aq.player = h->tempOwner;
  5983. cb->sendAndApply (&aq);
  5984. //TODO: add this quest only once OR check for multiple instances later
  5985. }
  5986. }
  5987. void CGBorderGuard::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5988. {
  5989. if (answer)
  5990. cb->removeObject(this);
  5991. }
  5992. void CGBorderGate::onHeroVisit( const CGHeroInstance * h ) const //TODO: passability
  5993. {
  5994. if (!wasMyColorVisited (h->getOwner()) )
  5995. {
  5996. showInfoDialog(h,18,0);
  5997. AddQuest aq;
  5998. aq.quest = QuestInfo (quest, this, visitablePos());
  5999. aq.player = h->tempOwner;
  6000. cb->sendAndApply (&aq);
  6001. }
  6002. }
  6003. ui8 CGBorderGate::getPassableness() const
  6004. {
  6005. ui8 ret = 0;
  6006. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  6007. ret |= wasMyColorVisited(PlayerColor(i))<<i;
  6008. return ret;
  6009. }
  6010. void CGMagi::initObj()
  6011. {
  6012. if (ID == Obj::EYE_OF_MAGI)
  6013. {
  6014. blockVisit = true;
  6015. eyelist[subID].push_back(id);
  6016. }
  6017. }
  6018. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  6019. {
  6020. if (ID == Obj::HUT_OF_MAGI)
  6021. {
  6022. showInfoDialog(h, 61, soundBase::LIGHTHOUSE);
  6023. if (!eyelist[subID].empty())
  6024. {
  6025. CenterView cv;
  6026. cv.player = h->tempOwner;
  6027. cv.focusTime = 2000;
  6028. FoWChange fw;
  6029. fw.player = h->tempOwner;
  6030. fw.mode = 1;
  6031. BOOST_FOREACH(auto it, eyelist[subID])
  6032. {
  6033. const CGObjectInstance *eye = cb->getObj(it);
  6034. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  6035. cb->sendAndApply(&fw);
  6036. cv.pos = eye->pos;
  6037. cb->sendAndApply(&cv);
  6038. }
  6039. cv.pos = h->getPosition(false);
  6040. cb->sendAndApply(&cv);
  6041. }
  6042. }
  6043. else if (ID == Obj::EYE_OF_MAGI)
  6044. {
  6045. showInfoDialog(h,48,soundBase::invalid);
  6046. }
  6047. }
  6048. void CGBoat::initObj()
  6049. {
  6050. hero = NULL;
  6051. }
  6052. void CGSirens::initObj()
  6053. {
  6054. blockVisit = true;
  6055. }
  6056. const std::string & CGSirens::getHoverText() const
  6057. {
  6058. getNameVis(hoverName);
  6059. return hoverName;
  6060. }
  6061. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  6062. {
  6063. InfoWindow iw;
  6064. iw.soundID = soundBase::DANGER;
  6065. iw.player = h->tempOwner;
  6066. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  6067. {
  6068. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  6069. }
  6070. else
  6071. {
  6072. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  6073. TExpType xp = 0;
  6074. for (TSlots::const_iterator i = h->Slots().begin(); i != h->Slots().end(); i++)
  6075. {
  6076. TQuantity drown = i->second->count * 0.3;
  6077. if(drown)
  6078. {
  6079. cb->changeStackCount(StackLocation(h, i->first), -drown);
  6080. xp += drown * i->second->type->valOfBonuses(Bonus::STACK_HEALTH);
  6081. }
  6082. }
  6083. if(xp)
  6084. {
  6085. xp = h->calculateXp(xp);
  6086. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  6087. iw.text.addReplacement(xp);
  6088. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  6089. }
  6090. else
  6091. {
  6092. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  6093. }
  6094. }
  6095. cb->showInfoDialog(&iw);
  6096. }
  6097. //bool IShipyard::validLocation() const
  6098. //{
  6099. // std::vector<int3> offsets;
  6100. // getOutOffsets(offsets);
  6101. //
  6102. // TerrainTile *tile;
  6103. // for(int i = 0; i < offsets.size(); i++)
  6104. // if((tile = IObjectInterface::cb->getTile(o->pos + offsets[i])) && tile->terType == TerrainTile::water) //tile is in the map and is water
  6105. // return true;
  6106. // return false;
  6107. //}
  6108. int3 IBoatGenerator::bestLocation() const
  6109. {
  6110. std::vector<int3> offsets;
  6111. getOutOffsets(offsets);
  6112. for (int i = 0; i < offsets.size(); ++i)
  6113. {
  6114. if (const TerrainTile *tile = IObjectInterface::cb->getTile(o->pos + offsets[i], false)) //tile is in the map
  6115. {
  6116. if (tile->terType == ETerrainType::WATER && (!tile->blocked || tile->blockingObjects.front()->ID == 8)) //and is water and is not blocked or is blocked by boat
  6117. return o->pos + offsets[i];
  6118. }
  6119. }
  6120. return int3 (-1,-1,-1);
  6121. }
  6122. IBoatGenerator::EGeneratorState IBoatGenerator::state() const
  6123. {
  6124. int3 tile = bestLocation();
  6125. const TerrainTile *t = IObjectInterface::cb->getTile(tile);
  6126. if(!t)
  6127. return TILE_BLOCKED; //no available water
  6128. else if(!t->blockingObjects.size())
  6129. return GOOD; //OK
  6130. else if(t->blockingObjects.front()->ID == Obj::BOAT)
  6131. return BOAT_ALREADY_BUILT; //blocked with boat
  6132. else
  6133. return TILE_BLOCKED; //blocked
  6134. }
  6135. int IBoatGenerator::getBoatType() const
  6136. {
  6137. //We make good ships by default
  6138. return 1;
  6139. }
  6140. IBoatGenerator::IBoatGenerator(const CGObjectInstance *O)
  6141. : o(O)
  6142. {
  6143. }
  6144. void IBoatGenerator::getProblemText(MetaString &out, const CGHeroInstance *visitor) const
  6145. {
  6146. switch(state())
  6147. {
  6148. case BOAT_ALREADY_BUILT:
  6149. out.addTxt(MetaString::GENERAL_TXT, 51);
  6150. break;
  6151. case TILE_BLOCKED:
  6152. if(visitor)
  6153. {
  6154. out.addTxt(MetaString::GENERAL_TXT, 134);
  6155. out.addReplacement(visitor->name);
  6156. }
  6157. else
  6158. out.addTxt(MetaString::ADVOB_TXT, 189);
  6159. break;
  6160. case NO_WATER:
  6161. logGlobal->errorStream() << "Shipyard without water!!! " << o->pos << "\t" << o->id;
  6162. return;
  6163. }
  6164. }
  6165. void IShipyard::getBoatCost( std::vector<si32> &cost ) const
  6166. {
  6167. cost.resize(GameConstants::RESOURCE_QUANTITY);
  6168. cost[Res::WOOD] = 10;
  6169. cost[Res::GOLD] = 1000;
  6170. }
  6171. IShipyard::IShipyard(const CGObjectInstance *O)
  6172. : IBoatGenerator(O)
  6173. {
  6174. }
  6175. IShipyard * IShipyard::castFrom( CGObjectInstance *obj )
  6176. {
  6177. if(!obj)
  6178. return NULL;
  6179. if(obj->ID == Obj::TOWN)
  6180. {
  6181. return static_cast<CGTownInstance*>(obj);
  6182. }
  6183. else if(obj->ID == Obj::SHIPYARD)
  6184. {
  6185. return static_cast<CGShipyard*>(obj);
  6186. }
  6187. else
  6188. {
  6189. return NULL;
  6190. }
  6191. }
  6192. const IShipyard * IShipyard::castFrom( const CGObjectInstance *obj )
  6193. {
  6194. return castFrom(const_cast<CGObjectInstance*>(obj));
  6195. }
  6196. CGShipyard::CGShipyard()
  6197. :IShipyard(this)
  6198. {
  6199. }
  6200. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  6201. {
  6202. // H J L K I
  6203. // A x S x B
  6204. // C E G F D
  6205. offsets += int3(-3,0,0), int3(1,0,0), //AB
  6206. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  6207. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0); //HIJKL
  6208. }
  6209. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  6210. {
  6211. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  6212. cb->setOwner(this, h->tempOwner);
  6213. auto s = state();
  6214. if(s != IBoatGenerator::GOOD)
  6215. {
  6216. InfoWindow iw;
  6217. iw.player = tempOwner;
  6218. getProblemText(iw.text, h);
  6219. cb->showInfoDialog(&iw);
  6220. }
  6221. else
  6222. {
  6223. openWindow(OpenWindow::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  6224. }
  6225. }
  6226. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  6227. {
  6228. if (!wasVisited (h->getOwner()) ) //if hero has not visited yet this cartographer
  6229. {
  6230. if (cb->getResource(h->tempOwner, Res::GOLD) >= 1000) //if he can afford a map
  6231. {
  6232. //ask if he wants to buy one
  6233. int text=0;
  6234. switch (subID)
  6235. {
  6236. case 0:
  6237. text = 25;
  6238. break;
  6239. case 1:
  6240. text = 26;
  6241. break;
  6242. case 2:
  6243. text = 27;
  6244. break;
  6245. default:
  6246. logGlobal->warnStream() << "Unrecognized subtype of cartographer";
  6247. }
  6248. assert(text);
  6249. BlockingDialog bd (true, false);
  6250. bd.player = h->getOwner();
  6251. bd.soundID = soundBase::LIGHTHOUSE;
  6252. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  6253. cb->showBlockingDialog (&bd);
  6254. }
  6255. else //if he cannot afford
  6256. {
  6257. showInfoDialog(h,28,soundBase::CAVEHEAD);
  6258. }
  6259. }
  6260. else //if he already visited carographer
  6261. {
  6262. showInfoDialog(h,24,soundBase::CAVEHEAD);
  6263. }
  6264. }
  6265. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  6266. {
  6267. if (answer) //if hero wants to buy map
  6268. {
  6269. cb->giveResource (hero->tempOwner, Res::GOLD, -1000);
  6270. FoWChange fw;
  6271. fw.mode = 1;
  6272. fw.player = hero->tempOwner;
  6273. //subIDs of different types of cartographers:
  6274. //water = 0; land = 1; underground = 2;
  6275. cb->getAllTiles (fw.tiles, hero->tempOwner, subID - 1, !subID + 1); //reveal appropriate tiles
  6276. cb->sendAndApply (&fw);
  6277. cb->setObjProperty (id, 10, hero->tempOwner.getNum());
  6278. }
  6279. }
  6280. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  6281. {
  6282. cb->showThievesGuildWindow(h->tempOwner, id);
  6283. }
  6284. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  6285. {
  6286. InfoWindow iw;
  6287. iw.player = h->tempOwner;
  6288. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  6289. assert(ts);
  6290. TeamID team = ts->id;
  6291. if(!wasVisited(team))
  6292. {
  6293. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  6294. cb->sendAndApply(&iw);
  6295. cb->setObjProperty(id, 20, h->tempOwner.getNum()); //increment general visited obelisks counter
  6296. openWindow(OpenWindow::PUZZLE_MAP, h->tempOwner.getNum());
  6297. cb->setObjProperty(id, 10, h->tempOwner.getNum()); //mark that particular obelisk as visited
  6298. }
  6299. else
  6300. {
  6301. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  6302. cb->sendAndApply(&iw);
  6303. }
  6304. }
  6305. void CGObelisk::initObj()
  6306. {
  6307. obeliskCount++;
  6308. }
  6309. const std::string & CGObelisk::getHoverText() const
  6310. {
  6311. bool visited = wasVisited(cb->getLocalPlayer());
  6312. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  6313. return hoverName;
  6314. }
  6315. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  6316. {
  6317. CPlayersVisited::setPropertyDer(what, val);
  6318. switch(what)
  6319. {
  6320. case 20:
  6321. assert(val < PlayerColor::PLAYER_LIMIT_I);
  6322. visited[TeamID(val)]++;
  6323. if(visited[TeamID(val)] > obeliskCount)
  6324. {
  6325. logGlobal->errorStream() << "Error: Visited " << visited[TeamID(val)] << "\t\t" << obeliskCount;
  6326. assert(0);
  6327. }
  6328. break;
  6329. }
  6330. }
  6331. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  6332. {
  6333. if(h->tempOwner != tempOwner)
  6334. {
  6335. PlayerColor oldOwner = tempOwner;
  6336. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  6337. showInfoDialog(h,69,soundBase::LIGHTHOUSE);
  6338. giveBonusTo(h->tempOwner);
  6339. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  6340. {
  6341. RemoveBonus rb(RemoveBonus::PLAYER);
  6342. rb.whoID = oldOwner.getNum();
  6343. rb.source = Bonus::OBJECT;
  6344. rb.id = id.getNum();
  6345. cb->sendAndApply(&rb);
  6346. }
  6347. }
  6348. }
  6349. void CGLighthouse::initObj()
  6350. {
  6351. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  6352. {
  6353. giveBonusTo(tempOwner);
  6354. }
  6355. }
  6356. const std::string & CGLighthouse::getHoverText() const
  6357. {
  6358. hoverName = VLC->generaltexth->names[ID];
  6359. //TODO: owned by %s player
  6360. return hoverName;
  6361. }
  6362. void CGLighthouse::giveBonusTo( PlayerColor player ) const
  6363. {
  6364. GiveBonus gb(GiveBonus::PLAYER);
  6365. gb.bonus.type = Bonus::SEA_MOVEMENT;
  6366. gb.bonus.val = 500;
  6367. gb.id = player.getNum();
  6368. gb.bonus.duration = Bonus::PERMANENT;
  6369. gb.bonus.source = Bonus::OBJECT;
  6370. gb.bonus.sid = id.getNum();
  6371. cb->sendAndApply(&gb);
  6372. }
  6373. void CArmedInstance::randomizeArmy(int type)
  6374. {
  6375. int max = VLC->creh->creatures.size();
  6376. for (TSlots::iterator j = stacks.begin(); j != stacks.end();j++)
  6377. {
  6378. int randID = j->second->idRand;
  6379. if(randID > max)
  6380. {
  6381. int level = (randID-VLC->creh->creatures.size()) / 2 -1;
  6382. bool upgrade = !(randID % 2);
  6383. j->second->setType(VLC->townh->factions[type]->town->creatures[level][upgrade]);
  6384. randID = -1;
  6385. }
  6386. assert(j->second->armyObj == this);
  6387. }
  6388. return;
  6389. }
  6390. CArmedInstance::CArmedInstance()
  6391. {
  6392. battle = NULL;
  6393. }
  6394. //int CArmedInstance::valOfGlobalBonuses(CSelector selector) const
  6395. //{
  6396. //// if (tempOwner != NEUTRAL_PLAYER)
  6397. // return cb->gameState()->players[tempOwner].valOfBonuses(selector);
  6398. //}
  6399. void CArmedInstance::updateMoraleBonusFromArmy()
  6400. {
  6401. if(!validTypes(false)) //object not randomized, don't bother
  6402. return;
  6403. Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY) && Selector::type(Bonus::MORALE));
  6404. if(!b)
  6405. {
  6406. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  6407. addNewBonus(b);
  6408. }
  6409. //number of alignments and presence of undead
  6410. std::set<TFaction> factions;
  6411. bool hasUndead = false;
  6412. BOOST_FOREACH(auto slot, Slots())
  6413. {
  6414. const CStackInstance * inst = slot.second;
  6415. const CCreature * creature = VLC->creh->creatures[inst->getCreatureID()];
  6416. factions.insert(creature->faction);
  6417. // Check for undead flag instead of faction (undead mummies are neutral)
  6418. hasUndead |= inst->hasBonusOfType(Bonus::UNDEAD);
  6419. }
  6420. size_t factionsInArmy = factions.size(); //town garrison seems to take both sets into account
  6421. // Take Angelic Alliance troop-mixing freedom of non-evil units into account.
  6422. if (hasBonusOfType(Bonus::NONEVIL_ALIGNMENT_MIX))
  6423. {
  6424. size_t mixableFactions = 0;
  6425. BOOST_FOREACH(TFaction f, factions)
  6426. {
  6427. if (VLC->townh->factions[f]->alignment != EAlignment::EVIL)
  6428. mixableFactions++;
  6429. }
  6430. if (mixableFactions > 0)
  6431. factionsInArmy -= mixableFactions - 1;
  6432. }
  6433. if(factionsInArmy == 1)
  6434. {
  6435. b->val = +1;
  6436. b->description = VLC->generaltexth->arraytxt[115]; //All troops of one alignment +1
  6437. }
  6438. else if (factions.size()) // no bonus from empty garrison
  6439. {
  6440. b->val = 2 - factionsInArmy;
  6441. b->description = boost::str(boost::format(VLC->generaltexth->arraytxt[114]) % factionsInArmy % b->val); //Troops of %d alignments %d
  6442. }
  6443. boost::algorithm::trim(b->description);
  6444. //-1 modifier for any Undead unit in army
  6445. const ui8 UNDEAD_MODIFIER_ID = -2;
  6446. Bonus *undeadModifier = getBonusList().getFirst(Selector::source(Bonus::ARMY, UNDEAD_MODIFIER_ID));
  6447. if(hasUndead)
  6448. {
  6449. if(!undeadModifier)
  6450. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, -1, UNDEAD_MODIFIER_ID, VLC->generaltexth->arraytxt[116]));
  6451. }
  6452. else if(undeadModifier)
  6453. removeBonus(undeadModifier);
  6454. }
  6455. void CArmedInstance::armyChanged()
  6456. {
  6457. updateMoraleBonusFromArmy();
  6458. }
  6459. CBonusSystemNode * CArmedInstance::whereShouldBeAttached(CGameState *gs)
  6460. {
  6461. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  6462. return gs->getPlayer(tempOwner);
  6463. else
  6464. return &gs->globalEffects;
  6465. }
  6466. CBonusSystemNode * CArmedInstance::whatShouldBeAttached()
  6467. {
  6468. return this;
  6469. }
  6470. bool IMarket::getOffer(int id1, int id2, int &val1, int &val2, EMarketMode::EMarketMode mode) const
  6471. {
  6472. switch(mode)
  6473. {
  6474. case EMarketMode::RESOURCE_RESOURCE:
  6475. {
  6476. double effectiveness = std::min((getMarketEfficiency() + 1.0) / 20.0, 0.5);
  6477. double r = VLC->objh->resVals[id1], //value of given resource
  6478. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  6479. if(r>g) //if given resource is more expensive than wanted
  6480. {
  6481. val2 = ceil(r / g);
  6482. val1 = 1;
  6483. }
  6484. else //if wanted resource is more expensive
  6485. {
  6486. val1 = (g / r) + 0.5;
  6487. val2 = 1;
  6488. }
  6489. }
  6490. break;
  6491. case EMarketMode::CREATURE_RESOURCE:
  6492. {
  6493. const double effectivenessArray[] = {0.0, 0.3, 0.45, 0.50, 0.65, 0.7, 0.85, 0.9, 1.0};
  6494. double effectiveness = effectivenessArray[std::min(getMarketEfficiency(), 8)];
  6495. double r = VLC->creh->creatures[id1]->cost[6], //value of given creature in gold
  6496. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  6497. if(r>g) //if given resource is more expensive than wanted
  6498. {
  6499. val2 = ceil(r / g);
  6500. val1 = 1;
  6501. }
  6502. else //if wanted resource is more expensive
  6503. {
  6504. val1 = (g / r) + 0.5;
  6505. val2 = 1;
  6506. }
  6507. }
  6508. break;
  6509. case EMarketMode::RESOURCE_PLAYER:
  6510. val1 = 1;
  6511. val2 = 1;
  6512. break;
  6513. case EMarketMode::RESOURCE_ARTIFACT:
  6514. {
  6515. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  6516. double r = VLC->objh->resVals[id1], //value of offered resource
  6517. g = VLC->arth->artifacts[id2]->price / effectiveness; //value of bought artifact in gold
  6518. if(id1 != 6) //non-gold prices are doubled
  6519. r /= 2;
  6520. val1 = std::max(1, (int)((g / r) + 0.5)); //don't sell arts for less than 1 resource
  6521. val2 = 1;
  6522. }
  6523. break;
  6524. case EMarketMode::ARTIFACT_RESOURCE:
  6525. {
  6526. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  6527. double r = VLC->arth->artifacts[id1]->price * effectiveness,
  6528. g = VLC->objh->resVals[id2];
  6529. // if(id2 != 6) //non-gold prices are doubled
  6530. // r /= 2;
  6531. val1 = 1;
  6532. val2 = std::max(1, (int)((r / g) + 0.5)); //at least one resource is given in return
  6533. }
  6534. break;
  6535. case EMarketMode::CREATURE_EXP:
  6536. {
  6537. val1 = 1;
  6538. val2 = (VLC->creh->creatures[id1]->AIValue / 40) * 5;
  6539. }
  6540. break;
  6541. case EMarketMode::ARTIFACT_EXP:
  6542. {
  6543. val1 = 1;
  6544. int givenClass = VLC->arth->artifacts[id1]->getArtClassSerial();
  6545. if(givenClass < 0 || givenClass > 3)
  6546. {
  6547. val2 = 0;
  6548. return false;
  6549. }
  6550. static const int expPerClass[] = {1000, 1500, 3000, 6000};
  6551. val2 = expPerClass[givenClass];
  6552. }
  6553. break;
  6554. default:
  6555. assert(0);
  6556. return false;
  6557. }
  6558. return true;
  6559. }
  6560. bool IMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  6561. {
  6562. return false;
  6563. }
  6564. int IMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  6565. {
  6566. switch(mode)
  6567. {
  6568. case EMarketMode::RESOURCE_RESOURCE:
  6569. case EMarketMode::ARTIFACT_RESOURCE:
  6570. case EMarketMode::CREATURE_RESOURCE:
  6571. return -1;
  6572. default:
  6573. return 1;
  6574. }
  6575. }
  6576. std::vector<int> IMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6577. {
  6578. std::vector<int> ret;
  6579. switch(mode)
  6580. {
  6581. case EMarketMode::RESOURCE_RESOURCE:
  6582. case EMarketMode::ARTIFACT_RESOURCE:
  6583. case EMarketMode::CREATURE_RESOURCE:
  6584. for (int i = 0; i < 7; i++)
  6585. ret.push_back(i);
  6586. default:
  6587. break;
  6588. }
  6589. return ret;
  6590. }
  6591. const IMarket * IMarket::castFrom(const CGObjectInstance *obj, bool verbose /*= true*/)
  6592. {
  6593. switch(obj->ID)
  6594. {
  6595. case Obj::TOWN:
  6596. return static_cast<const CGTownInstance*>(obj);
  6597. case Obj::ALTAR_OF_SACRIFICE:
  6598. case Obj::BLACK_MARKET:
  6599. case Obj::TRADING_POST:
  6600. case Obj::TRADING_POST_SNOW:
  6601. case Obj::FREELANCERS_GUILD:
  6602. return static_cast<const CGMarket*>(obj);
  6603. case Obj::UNIVERSITY:
  6604. return static_cast<const CGUniversity*>(obj);
  6605. default:
  6606. if(verbose)
  6607. logGlobal->errorStream() << "Cannot cast to IMarket object with ID " << obj->ID;
  6608. return NULL;
  6609. }
  6610. }
  6611. IMarket::IMarket(const CGObjectInstance *O)
  6612. :o(O)
  6613. {
  6614. }
  6615. std::vector<EMarketMode::EMarketMode> IMarket::availableModes() const
  6616. {
  6617. std::vector<EMarketMode::EMarketMode> ret;
  6618. for (int i = 0; i < EMarketMode::MARTKET_AFTER_LAST_PLACEHOLDER; i++)
  6619. if(allowsTrade((EMarketMode::EMarketMode)i))
  6620. ret.push_back((EMarketMode::EMarketMode)i);
  6621. return ret;
  6622. }
  6623. void CGMarket::onHeroVisit(const CGHeroInstance * h) const
  6624. {
  6625. openWindow(OpenWindow::MARKET_WINDOW,id.getNum(),h->id.getNum());
  6626. }
  6627. int CGMarket::getMarketEfficiency() const
  6628. {
  6629. return 5;
  6630. }
  6631. bool CGMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  6632. {
  6633. switch(mode)
  6634. {
  6635. case EMarketMode::RESOURCE_RESOURCE:
  6636. case EMarketMode::RESOURCE_PLAYER:
  6637. switch(ID)
  6638. {
  6639. case Obj::TRADING_POST:
  6640. case Obj::TRADING_POST_SNOW:
  6641. return true;
  6642. default:
  6643. return false;
  6644. }
  6645. case EMarketMode::CREATURE_RESOURCE:
  6646. return ID == Obj::FREELANCERS_GUILD;
  6647. //case ARTIFACT_RESOURCE:
  6648. case EMarketMode::RESOURCE_ARTIFACT:
  6649. return ID == Obj::BLACK_MARKET;
  6650. case EMarketMode::ARTIFACT_EXP:
  6651. case EMarketMode::CREATURE_EXP:
  6652. return ID == Obj::ALTAR_OF_SACRIFICE; //TODO? check here for alignment of visiting hero? - would not be coherent with other checks here
  6653. case EMarketMode::RESOURCE_SKILL:
  6654. return ID == Obj::UNIVERSITY;
  6655. default:
  6656. return false;
  6657. }
  6658. }
  6659. int CGMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  6660. {
  6661. return -1;
  6662. }
  6663. std::vector<int> CGMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6664. {
  6665. switch(mode)
  6666. {
  6667. case EMarketMode::RESOURCE_RESOURCE:
  6668. case EMarketMode::RESOURCE_PLAYER:
  6669. return IMarket::availableItemsIds(mode);
  6670. default:
  6671. return std::vector<int>();
  6672. }
  6673. }
  6674. CGMarket::CGMarket()
  6675. :IMarket(this)
  6676. {
  6677. }
  6678. std::vector<int> CGBlackMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6679. {
  6680. switch(mode)
  6681. {
  6682. case EMarketMode::ARTIFACT_RESOURCE:
  6683. return IMarket::availableItemsIds(mode);
  6684. case EMarketMode::RESOURCE_ARTIFACT:
  6685. {
  6686. std::vector<int> ret;
  6687. BOOST_FOREACH(const CArtifact *a, artifacts)
  6688. if(a)
  6689. ret.push_back(a->id);
  6690. else
  6691. ret.push_back(-1);
  6692. return ret;
  6693. }
  6694. default:
  6695. return std::vector<int>();
  6696. }
  6697. }
  6698. void CGBlackMarket::newTurn() const
  6699. {
  6700. if(cb->getDate(Date::DAY_OF_MONTH) != 1) //new month
  6701. return;
  6702. SetAvailableArtifacts saa;
  6703. saa.id = id.getNum();
  6704. cb->pickAllowedArtsSet(saa.arts);
  6705. cb->sendAndApply(&saa);
  6706. }
  6707. void CGUniversity::initObj()
  6708. {
  6709. std::vector <int> toChoose;
  6710. for (int i=0; i<GameConstants::SKILL_QUANTITY; i++)
  6711. if (cb->isAllowed(2,i))
  6712. toChoose.push_back(i);
  6713. if (toChoose.size() < 4)
  6714. {
  6715. logGlobal->warnStream()<<"Warning: less then 4 available skills was found by University initializer!";
  6716. return;
  6717. }
  6718. for (int i=0; i<4; i++)//get 4 skills
  6719. {
  6720. int skillPos = ran()%toChoose.size();
  6721. skills.push_back(toChoose[skillPos]);//move it to selected
  6722. toChoose.erase(toChoose.begin()+skillPos);//remove from list
  6723. }
  6724. }
  6725. std::vector<int> CGUniversity::availableItemsIds(EMarketMode::EMarketMode mode) const
  6726. {
  6727. switch (mode)
  6728. {
  6729. case EMarketMode::RESOURCE_SKILL:
  6730. return skills;
  6731. default:
  6732. return std::vector <int> ();
  6733. }
  6734. }
  6735. void CGUniversity::onHeroVisit(const CGHeroInstance * h) const
  6736. {
  6737. openWindow(OpenWindow::UNIVERSITY_WINDOW,id.getNum(),h->id.getNum());
  6738. }
  6739. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  6740. : count(_count)
  6741. {
  6742. description = boost::str(boost::format(format) % count);
  6743. }
  6744. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  6745. : count(_count)
  6746. {
  6747. description = boost::str(boost::format("%s %+d") % VLC->townh->factions[subID]->town->buildings[building]->Name() % count);
  6748. }
  6749. CTownAndVisitingHero::CTownAndVisitingHero()
  6750. {
  6751. setNodeType(TOWN_AND_VISITOR);
  6752. }
  6753. int GrowthInfo::totalGrowth() const
  6754. {
  6755. int ret = 0;
  6756. BOOST_FOREACH(const Entry &entry, entries)
  6757. ret += entry.count;
  6758. return ret;
  6759. }