CObjectHandler.cpp 203 KB

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