CObjectHandler.cpp 203 KB

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