CObjectHandler.cpp 209 KB

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