CObjectHandler.cpp 209 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754
  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. int CGTownInstance::dailyIncome() const
  1998. {
  1999. int ret = 0;
  2000. if (hasBuilt(BuildingID::GRAIL))
  2001. ret+=5000;
  2002. if (hasBuilt(BuildingID::CAPITOL))
  2003. ret+=4000;
  2004. else if (hasBuilt(BuildingID::CITY_HALL))
  2005. ret+=2000;
  2006. else if (hasBuilt(BuildingID::TOWN_HALL))
  2007. ret+=1000;
  2008. else if (hasBuilt(BuildingID::VILLAGE_HALL))
  2009. ret+=500;
  2010. return ret;
  2011. }
  2012. bool CGTownInstance::hasFort() const
  2013. {
  2014. return hasBuilt(BuildingID::FORT);
  2015. }
  2016. bool CGTownInstance::hasCapitol() const
  2017. {
  2018. return hasBuilt(BuildingID::CAPITOL);
  2019. }
  2020. CGTownInstance::CGTownInstance()
  2021. :IShipyard(this), IMarket(this), town(nullptr), builded(0), destroyed(0), identifier(0), alignment(0xff)
  2022. {
  2023. }
  2024. CGTownInstance::~CGTownInstance()
  2025. {
  2026. for (auto & elem : bonusingBuildings)
  2027. delete elem;
  2028. }
  2029. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  2030. {
  2031. if(checkGuild && mageGuildLevel() < level)
  2032. return 0;
  2033. int ret = 6 - level; //how many spells are available at this level
  2034. if (hasBuilt(BuildingID::LIBRARY, ETownType::TOWER))
  2035. ret++;
  2036. return ret;
  2037. }
  2038. bool CGTownInstance::needsLastStack() const
  2039. {
  2040. if(garrisonHero)
  2041. return true;
  2042. else return false;
  2043. }
  2044. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  2045. {
  2046. if( !cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  2047. {
  2048. if(armedGarrison() || visitingHero)
  2049. {
  2050. const CGHeroInstance *defendingHero = nullptr;
  2051. const CArmedInstance *defendingArmy = this;
  2052. if(visitingHero)
  2053. defendingHero = visitingHero;
  2054. else if(garrisonHero)
  2055. defendingHero = garrisonHero;
  2056. if(defendingHero)
  2057. defendingArmy = defendingHero;
  2058. bool outsideTown = (defendingHero == visitingHero && garrisonHero);
  2059. //TODO
  2060. //"borrowing" army from garrison to visiting hero
  2061. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (outsideTown ? nullptr : this));
  2062. }
  2063. else
  2064. {
  2065. cb->setOwner(this, h->tempOwner);
  2066. removeCapitols(h->getOwner());
  2067. cb->heroVisitCastle(this, h);
  2068. }
  2069. }
  2070. else if(h->visitablePos() == visitablePos())
  2071. {
  2072. if (h->commander && !h->commander->alive) //rise commander. TODO: interactive script
  2073. {
  2074. SetCommanderProperty scp;
  2075. scp.heroid = h->id;
  2076. scp.which = SetCommanderProperty::ALIVE;
  2077. scp.amount = 1;
  2078. cb->sendAndApply (&scp);
  2079. }
  2080. cb->heroVisitCastle(this, h);
  2081. }
  2082. else
  2083. {
  2084. logGlobal->errorStream() << h->name << " visits allied town of " << name << " from different pos?";
  2085. }
  2086. }
  2087. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  2088. {
  2089. cb->stopHeroVisitCastle(this, h);
  2090. }
  2091. void CGTownInstance::initObj()
  2092. ///initialize town structures
  2093. {
  2094. blockVisit = true;
  2095. hoverName = name + ", " + town->faction->name;
  2096. if (subID == ETownType::DUNGEON)
  2097. creatures.resize(GameConstants::CREATURES_PER_TOWN+1);//extra dwelling for Dungeon
  2098. else
  2099. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  2100. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  2101. {
  2102. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  2103. int upgradeNum = 0;
  2104. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  2105. {
  2106. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  2107. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  2108. }
  2109. }
  2110. switch (subID)
  2111. { //add new visitable objects
  2112. case 0:
  2113. bonusingBuildings.push_back (new COPWBonus(BuildingID::STABLES, this));
  2114. break;
  2115. case 5:
  2116. bonusingBuildings.push_back (new COPWBonus(BuildingID::MANA_VORTEX, this));
  2117. //fallthrough
  2118. case 2: case 3: case 6:
  2119. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_4, this));
  2120. break;
  2121. case 7:
  2122. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_1, this));
  2123. break;
  2124. }
  2125. //add special bonuses from buildings
  2126. recreateBuildingsBonuses();
  2127. }
  2128. void CGTownInstance::newTurn() const
  2129. {
  2130. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  2131. {
  2132. auto & rand = cb->gameState()->getRandomGenerator();
  2133. //give resources for Rampart, Mystic Pond
  2134. if (hasBuilt(BuildingID::MYSTIC_POND, ETownType::RAMPART)
  2135. && cb->getDate(Date::DAY) != 1 && (tempOwner < PlayerColor::PLAYER_LIMIT))
  2136. {
  2137. int resID = rand.nextInt(2, 5); //bonus to random rare resource
  2138. resID = (resID==2)?1:resID;
  2139. int resVal = rand.nextInt(1, 4);//with size 1..4
  2140. cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
  2141. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  2142. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  2143. }
  2144. if ( subID == ETownType::DUNGEON )
  2145. for (auto & elem : bonusingBuildings)
  2146. {
  2147. if ((elem)->ID == BuildingID::MANA_VORTEX)
  2148. cb->setObjProperty (id, ObjProperty::STRUCTURE_CLEAR_VISITORS, (elem)->id); //reset visitors for Mana Vortex
  2149. }
  2150. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  2151. {
  2152. std::vector<SlotID> nativeCrits; //slots
  2153. for (auto & elem : Slots())
  2154. {
  2155. if (elem.second->type->faction == subID) //native
  2156. {
  2157. nativeCrits.push_back(elem.first); //collect matching slots
  2158. }
  2159. }
  2160. if (nativeCrits.size())
  2161. {
  2162. SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
  2163. StackLocation sl(this, pos);
  2164. const CCreature *c = getCreature(pos);
  2165. if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
  2166. {
  2167. cb->changeStackCount(sl, c->growth);
  2168. }
  2169. else //upgrade
  2170. {
  2171. cb->changeStackType(sl, VLC->creh->creatures[*c->upgrades.begin()]);
  2172. }
  2173. }
  2174. if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
  2175. {
  2176. int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
  2177. if (!town->creatures[i].empty())
  2178. {
  2179. CreatureID c = town->creatures[i][0];
  2180. SlotID n;
  2181. TQuantity count = creatureGrowth(i);
  2182. if (!count) // no dwelling
  2183. count = VLC->creh->creatures[c]->growth;
  2184. {//no lower tiers or above current month
  2185. if ((n = getSlotFor(c)).validSlot())
  2186. {
  2187. StackLocation sl(this, n);
  2188. if (slotEmpty(n))
  2189. cb->insertNewStack(sl, VLC->creh->creatures[c], count);
  2190. else //add to existing
  2191. cb->changeStackCount(sl, count);
  2192. }
  2193. }
  2194. }
  2195. }
  2196. }
  2197. }
  2198. }
  2199. int3 CGTownInstance::getSightCenter() const
  2200. {
  2201. return pos - int3(2,0,0);
  2202. }
  2203. ui8 CGTownInstance::getPassableness() const
  2204. {
  2205. if (!armedGarrison())//empty castle - anyone can visit
  2206. return GameConstants::ALL_PLAYERS;
  2207. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  2208. return 0;
  2209. ui8 mask = 0;
  2210. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  2211. for(PlayerColor it : ts->players)
  2212. mask |= 1<<it.getNum();//allies - add to possible visitors
  2213. return mask;
  2214. }
  2215. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  2216. {
  2217. offsets += int3(-1,2,0), int3(-3,2,0);
  2218. }
  2219. void CGTownInstance::removeCapitols (PlayerColor owner) const
  2220. {
  2221. if (hasCapitol()) // search if there's an older capitol
  2222. {
  2223. PlayerState* state = cb->gameState()->getPlayer (owner); //get all towns owned by player
  2224. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  2225. {
  2226. if (*i != this && (*i)->hasCapitol())
  2227. {
  2228. RazeStructures rs;
  2229. rs.tid = id;
  2230. rs.bid.insert(BuildingID::CAPITOL);
  2231. rs.destroyed = destroyed;
  2232. cb->sendAndApply(&rs);
  2233. return;
  2234. }
  2235. }
  2236. }
  2237. }
  2238. int CGTownInstance::getBoatType() const
  2239. {
  2240. switch (town->faction->alignment)
  2241. {
  2242. case EAlignment::EVIL : return 0;
  2243. case EAlignment::GOOD : return 1;
  2244. case EAlignment::NEUTRAL : return 2;
  2245. }
  2246. assert(0);
  2247. return -1;
  2248. }
  2249. int CGTownInstance::getMarketEfficiency() const
  2250. {
  2251. if (!hasBuilt(BuildingID::MARKETPLACE))
  2252. return 0;
  2253. const PlayerState *p = cb->getPlayer(tempOwner);
  2254. assert(p);
  2255. int marketCount = 0;
  2256. for(const CGTownInstance *t : p->towns)
  2257. if(t->hasBuilt(BuildingID::MARKETPLACE))
  2258. marketCount++;
  2259. return marketCount;
  2260. }
  2261. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  2262. {
  2263. switch(mode)
  2264. {
  2265. case EMarketMode::RESOURCE_RESOURCE:
  2266. case EMarketMode::RESOURCE_PLAYER:
  2267. return hasBuilt(BuildingID::MARKETPLACE);
  2268. case EMarketMode::ARTIFACT_RESOURCE:
  2269. case EMarketMode::RESOURCE_ARTIFACT:
  2270. return hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::TOWER)
  2271. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::DUNGEON)
  2272. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::CONFLUX);
  2273. case EMarketMode::CREATURE_RESOURCE:
  2274. return hasBuilt(BuildingID::FREELANCERS_GUILD, ETownType::STRONGHOLD);
  2275. case EMarketMode::CREATURE_UNDEAD:
  2276. return hasBuilt(BuildingID::SKELETON_TRANSFORMER, ETownType::NECROPOLIS);
  2277. case EMarketMode::RESOURCE_SKILL:
  2278. return hasBuilt(BuildingID::MAGIC_UNIVERSITY, ETownType::CONFLUX);
  2279. default:
  2280. assert(0);
  2281. return false;
  2282. }
  2283. }
  2284. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  2285. {
  2286. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  2287. {
  2288. std::vector<int> ret;
  2289. for(const CArtifact *a : merchantArtifacts)
  2290. if(a)
  2291. ret.push_back(a->id);
  2292. else
  2293. ret.push_back(-1);
  2294. return ret;
  2295. }
  2296. else if ( mode == EMarketMode::RESOURCE_SKILL )
  2297. {
  2298. return universitySkills;
  2299. }
  2300. else
  2301. return IMarket::availableItemsIds(mode);
  2302. }
  2303. void CGTownInstance::updateAppearance()
  2304. {
  2305. if (!hasFort())
  2306. appearance.animationFile = town->clientInfo.advMapVillage;
  2307. else if(hasCapitol())
  2308. appearance.animationFile = town->clientInfo.advMapCapitol;
  2309. else
  2310. appearance.animationFile = town->clientInfo.advMapCastle;
  2311. }
  2312. std::string CGTownInstance::nodeName() const
  2313. {
  2314. return "Town (" + (town ? town->faction->name : "unknown") + ") of " + name;
  2315. }
  2316. void CGTownInstance::deserializationFix()
  2317. {
  2318. attachTo(&townAndVis);
  2319. //Hero is already handled by CGameState::attachArmedObjects
  2320. // if(visitingHero)
  2321. // visitingHero->attachTo(&townAndVis);
  2322. // if(garrisonHero)
  2323. // garrisonHero->attachTo(this);
  2324. }
  2325. void CGTownInstance::updateMoraleBonusFromArmy()
  2326. {
  2327. Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE)));
  2328. if(!b)
  2329. {
  2330. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  2331. addNewBonus(b);
  2332. }
  2333. if (garrisonHero)
  2334. b->val = 0;
  2335. else
  2336. CArmedInstance::updateMoraleBonusFromArmy();
  2337. }
  2338. void CGTownInstance::recreateBuildingsBonuses()
  2339. {
  2340. static TPropagatorPtr playerProp(new CPropagatorNodeType(PLAYER));
  2341. BonusList bl;
  2342. getExportedBonusList().getBonuses(bl, Selector::sourceType(Bonus::TOWN_STRUCTURE));
  2343. for(Bonus *b : bl)
  2344. removeBonus(b);
  2345. //tricky! -> checks tavern only if no bratherhood of sword or not a castle
  2346. if(subID != ETownType::CASTLE || !addBonusIfBuilt(BuildingID::BROTHERHOOD, Bonus::MORALE, +2))
  2347. addBonusIfBuilt(BuildingID::TAVERN, Bonus::MORALE, +1);
  2348. if(subID == ETownType::CASTLE) //castle
  2349. {
  2350. addBonusIfBuilt(BuildingID::LIGHTHOUSE, Bonus::SEA_MOVEMENT, +500, playerProp);
  2351. addBonusIfBuilt(BuildingID::GRAIL, Bonus::MORALE, +2, playerProp); //colossus
  2352. }
  2353. else if(subID == ETownType::RAMPART) //rampart
  2354. {
  2355. addBonusIfBuilt(BuildingID::FOUNTAIN_OF_FORTUNE, Bonus::LUCK, +2); //fountain of fortune
  2356. addBonusIfBuilt(BuildingID::GRAIL, Bonus::LUCK, +2, playerProp); //guardian spirit
  2357. }
  2358. else if(subID == ETownType::TOWER) //tower
  2359. {
  2360. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +15, PrimarySkill::KNOWLEDGE); //grail
  2361. }
  2362. else if(subID == ETownType::INFERNO) //Inferno
  2363. {
  2364. addBonusIfBuilt(BuildingID::STORMCLOUDS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER); //Brimstone Clouds
  2365. }
  2366. else if(subID == ETownType::NECROPOLIS) //necropolis
  2367. {
  2368. addBonusIfBuilt(BuildingID::COVER_OF_DARKNESS, Bonus::DARKNESS, +20);
  2369. addBonusIfBuilt(BuildingID::NECROMANCY_AMPLIFIER, Bonus::SECONDARY_SKILL_PREMY, +10, playerProp, SecondarySkill::NECROMANCY); //necromancy amplifier
  2370. addBonusIfBuilt(BuildingID::GRAIL, Bonus::SECONDARY_SKILL_PREMY, +20, playerProp, SecondarySkill::NECROMANCY); //Soul prison
  2371. }
  2372. else if(subID == ETownType::DUNGEON) //Dungeon
  2373. {
  2374. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +12, PrimarySkill::SPELL_POWER); //grail
  2375. }
  2376. else if(subID == ETownType::STRONGHOLD) //Stronghold
  2377. {
  2378. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +20, PrimarySkill::ATTACK); //grail
  2379. }
  2380. else if(subID == ETownType::FORTRESS) //Fortress
  2381. {
  2382. addBonusIfBuilt(BuildingID::GLYPHS_OF_FEAR, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE); //Glyphs of Fear
  2383. addBonusIfBuilt(BuildingID::BLOOD_OBELISK, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK); //Blood Obelisk
  2384. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::ATTACK); //grail
  2385. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::DEFENSE); //grail
  2386. }
  2387. else if(subID == ETownType::CONFLUX)
  2388. {
  2389. }
  2390. }
  2391. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, int subtype /*= -1*/)
  2392. {
  2393. static auto emptyPropagator = TPropagatorPtr();
  2394. return addBonusIfBuilt(building, type, val, emptyPropagator, subtype);
  2395. }
  2396. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype /*= -1*/)
  2397. {
  2398. if(hasBuilt(building))
  2399. {
  2400. std::ostringstream descr;
  2401. descr << town->buildings.at(building)->Name() << " ";
  2402. if(val > 0)
  2403. descr << "+";
  2404. else if(val < 0)
  2405. descr << "-";
  2406. descr << val;
  2407. Bonus *b = new Bonus(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, descr.str(), subtype);
  2408. if(prop)
  2409. b->addPropagator(prop);
  2410. addNewBonus(b);
  2411. return true;
  2412. }
  2413. return false;
  2414. }
  2415. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  2416. {
  2417. assert(!!visitingHero == !h);
  2418. if(h)
  2419. {
  2420. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  2421. assert(p);
  2422. h->detachFrom(p);
  2423. h->attachTo(&townAndVis);
  2424. visitingHero = h;
  2425. h->visitedTown = this;
  2426. h->inTownGarrison = false;
  2427. }
  2428. else
  2429. {
  2430. PlayerState *p = cb->gameState()->getPlayer(visitingHero->tempOwner);
  2431. visitingHero->visitedTown = nullptr;
  2432. visitingHero->detachFrom(&townAndVis);
  2433. visitingHero->attachTo(p);
  2434. visitingHero = nullptr;
  2435. }
  2436. }
  2437. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  2438. {
  2439. assert(!!garrisonHero == !h);
  2440. if(h)
  2441. {
  2442. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  2443. assert(p);
  2444. h->detachFrom(p);
  2445. h->attachTo(this);
  2446. garrisonHero = h;
  2447. h->visitedTown = this;
  2448. h->inTownGarrison = true;
  2449. }
  2450. else
  2451. {
  2452. PlayerState *p = cb->gameState()->getPlayer(garrisonHero->tempOwner);
  2453. garrisonHero->visitedTown = nullptr;
  2454. garrisonHero->inTownGarrison = false;
  2455. garrisonHero->detachFrom(this);
  2456. garrisonHero->attachTo(p);
  2457. garrisonHero = nullptr;
  2458. }
  2459. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  2460. }
  2461. bool CGTownInstance::armedGarrison() const
  2462. {
  2463. return stacksCount() || garrisonHero;
  2464. }
  2465. int CGTownInstance::getTownLevel() const
  2466. {
  2467. // count all buildings that are not upgrades
  2468. return boost::range::count_if(builtBuildings, [&](const BuildingID & build)
  2469. {
  2470. return town->buildings.at(build) && town->buildings.at(build)->upgrade == -1;
  2471. });
  2472. }
  2473. CBonusSystemNode * CGTownInstance::whatShouldBeAttached()
  2474. {
  2475. return &townAndVis;
  2476. }
  2477. const CArmedInstance * CGTownInstance::getUpperArmy() const
  2478. {
  2479. if(garrisonHero)
  2480. return garrisonHero;
  2481. return this;
  2482. }
  2483. bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
  2484. {
  2485. if (townID == town->faction->index || townID == ETownType::ANY)
  2486. return hasBuilt(buildingID);
  2487. return false;
  2488. }
  2489. bool CGTownInstance::hasBuilt(BuildingID buildingID) const
  2490. {
  2491. return vstd::contains(builtBuildings, buildingID);
  2492. }
  2493. void CGTownInstance::addHeroToStructureVisitors( const CGHeroInstance *h, si32 structureInstanceID ) const
  2494. {
  2495. if(visitingHero == h)
  2496. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  2497. else if(garrisonHero == h)
  2498. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  2499. else
  2500. {
  2501. //should never ever happen
  2502. logGlobal->errorStream() << "Cannot add hero " << h->name << " to visitors of structure #" << structureInstanceID;
  2503. assert(0);
  2504. }
  2505. }
  2506. void CGTownInstance::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  2507. {
  2508. if(result.winner == 0)
  2509. {
  2510. removeCapitols(hero->getOwner());
  2511. cb->setOwner (this, hero->tempOwner); //give control after checkout is done
  2512. FoWChange fw;
  2513. fw.player = hero->tempOwner;
  2514. fw.mode = 1;
  2515. getSightTiles (fw.tiles); //update visibility for castle structures
  2516. cb->sendAndApply (&fw);
  2517. }
  2518. }
  2519. bool CGVisitableOPH::wasVisited (const CGHeroInstance * h) const
  2520. {
  2521. return vstd::contains(visitors, h->id);
  2522. }
  2523. void CGVisitableOPH::onHeroVisit( const CGHeroInstance * h ) const
  2524. {
  2525. if(!vstd::contains(visitors, h->id))
  2526. {
  2527. onNAHeroVisit (h, false);
  2528. switch(ID)
  2529. {
  2530. case Obj::TREE_OF_KNOWLEDGE:
  2531. case Obj::ARENA:
  2532. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2533. case Obj::SCHOOL_OF_MAGIC:
  2534. case Obj::SCHOOL_OF_WAR:
  2535. break;
  2536. default:
  2537. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2538. break;
  2539. }
  2540. }
  2541. else
  2542. {
  2543. onNAHeroVisit(h, true);
  2544. }
  2545. }
  2546. void CGVisitableOPH::initObj()
  2547. {
  2548. if(ID==Obj::TREE_OF_KNOWLEDGE)
  2549. {
  2550. switch (cb->gameState()->getRandomGenerator().nextInt(2))
  2551. {
  2552. case 1:
  2553. treePrice[Res::GOLD] = 2000;
  2554. break;
  2555. case 2:
  2556. treePrice[Res::GEMS] = 10;
  2557. break;
  2558. default:
  2559. break;
  2560. }
  2561. }
  2562. }
  2563. void CGVisitableOPH::treeSelected (const CGHeroInstance * h, ui32 result) const
  2564. {
  2565. if(result) //player agreed to give res for exp
  2566. {
  2567. si64 expToGive = VLC->heroh->reqExp(h->level+1) - VLC->heroh->reqExp(h->level);;
  2568. cb->giveResources (h->getOwner(), -treePrice);
  2569. cb->changePrimSkill (h, PrimarySkill::EXPERIENCE, expToGive);
  2570. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2571. }
  2572. }
  2573. void CGVisitableOPH::onNAHeroVisit (const CGHeroInstance * h, bool alreadyVisited) const
  2574. {
  2575. Component::EComponentType c_id = Component::PRIM_SKILL; //most used here
  2576. int subid=0, ot=0, sound = 0;
  2577. TExpType val=1;
  2578. switch(ID)
  2579. {
  2580. case Obj::ARENA:
  2581. sound = soundBase::NOMAD;
  2582. ot = 0;
  2583. break;
  2584. case Obj::MERCENARY_CAMP:
  2585. sound = soundBase::NOMAD;
  2586. subid=PrimarySkill::ATTACK;
  2587. ot=80;
  2588. break;
  2589. case Obj::MARLETTO_TOWER:
  2590. sound = soundBase::NOMAD;
  2591. subid=PrimarySkill::DEFENSE;
  2592. ot=39;
  2593. break;
  2594. case Obj::STAR_AXIS:
  2595. sound = soundBase::gazebo;
  2596. subid=PrimarySkill::SPELL_POWER;
  2597. ot=100;
  2598. break;
  2599. case Obj::GARDEN_OF_REVELATION:
  2600. sound = soundBase::GETPROTECTION;
  2601. subid=PrimarySkill::KNOWLEDGE;
  2602. ot=59;
  2603. break;
  2604. case Obj::LEARNING_STONE:
  2605. sound = soundBase::gazebo;
  2606. c_id=Component::EXPERIENCE;
  2607. ot=143;
  2608. val=1000;
  2609. break;
  2610. case Obj::TREE_OF_KNOWLEDGE:
  2611. sound = soundBase::gazebo;
  2612. c_id = Component::EXPERIENCE;
  2613. subid = 1;
  2614. ot = 147;
  2615. val = 1;
  2616. break;
  2617. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2618. sound = soundBase::gazebo;
  2619. ot = 66;
  2620. break;
  2621. case Obj::SCHOOL_OF_MAGIC:
  2622. sound = soundBase::faerie;
  2623. ot = 71;
  2624. break;
  2625. case Obj::SCHOOL_OF_WAR:
  2626. c_id=Component::PRIM_SKILL;
  2627. sound = soundBase::MILITARY;
  2628. ot = 158;
  2629. break;
  2630. }
  2631. if (!alreadyVisited)
  2632. {
  2633. switch (ID)
  2634. {
  2635. case Obj::ARENA:
  2636. {
  2637. BlockingDialog sd(false,true);
  2638. sd.soundID = sound;
  2639. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2640. sd.components.push_back(Component(c_id, PrimarySkill::ATTACK, 2, 0));
  2641. sd.components.push_back(Component(c_id, PrimarySkill::DEFENSE, 2, 0));
  2642. sd.player = h->getOwner();
  2643. cb->showBlockingDialog(&sd);
  2644. return;
  2645. }
  2646. case Obj::MERCENARY_CAMP:
  2647. case Obj::MARLETTO_TOWER:
  2648. case Obj::STAR_AXIS:
  2649. case Obj::GARDEN_OF_REVELATION:
  2650. {
  2651. cb->changePrimSkill (h, static_cast<PrimarySkill::PrimarySkill>(subid), val);
  2652. InfoWindow iw;
  2653. iw.soundID = sound;
  2654. iw.components.push_back(Component(c_id, subid, val, 0));
  2655. iw.text.addTxt(MetaString::ADVOB_TXT,ot);
  2656. iw.player = h->getOwner();
  2657. cb->showInfoDialog(&iw);
  2658. break;
  2659. }
  2660. case Obj::LEARNING_STONE: //give exp
  2661. {
  2662. val = h->calculateXp(val);
  2663. InfoWindow iw;
  2664. iw.soundID = sound;
  2665. iw.components.push_back (Component(c_id,subid,val,0));
  2666. iw.player = h->getOwner();
  2667. iw.text.addTxt(MetaString::ADVOB_TXT,ot);
  2668. cb->showInfoDialog(&iw);
  2669. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, val);
  2670. break;
  2671. }
  2672. case Obj::TREE_OF_KNOWLEDGE:
  2673. {
  2674. val = VLC->heroh->reqExp (h->level + val) - VLC->heroh->reqExp(h->level);
  2675. if(!treePrice.nonZero())
  2676. {
  2677. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2678. InfoWindow iw;
  2679. iw.soundID = sound;
  2680. iw.components.push_back (Component(c_id,subid,1,0));
  2681. iw.player = h->getOwner();
  2682. iw.text.addTxt (MetaString::ADVOB_TXT,148);
  2683. cb->showInfoDialog (&iw);
  2684. cb->changePrimSkill (h, PrimarySkill::EXPERIENCE, val);
  2685. break;
  2686. }
  2687. else
  2688. {
  2689. if(treePrice[Res::GOLD] > 0)
  2690. ot = 149;
  2691. else
  2692. ot = 151;
  2693. if(!cb->getPlayer(h->tempOwner)->resources.canAfford(treePrice)) //not enough resources
  2694. {
  2695. ot++;
  2696. showInfoDialog(h,ot,sound);
  2697. return;
  2698. }
  2699. BlockingDialog sd (true, false);
  2700. sd.soundID = sound;
  2701. sd.player = h->getOwner();
  2702. sd.text.addTxt (MetaString::ADVOB_TXT,ot);
  2703. sd.addResourceComponents (treePrice);
  2704. cb->showBlockingDialog (&sd);
  2705. }
  2706. break;
  2707. }
  2708. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2709. {
  2710. int txt_id = 66;
  2711. if(h->level < 10 - 2*h->getSecSkillLevel(SecondarySkill::DIPLOMACY)) //not enough level
  2712. {
  2713. txt_id += 2;
  2714. }
  2715. else
  2716. {
  2717. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2718. cb->changePrimSkill (h, PrimarySkill::ATTACK, 2);
  2719. cb->changePrimSkill (h, PrimarySkill::DEFENSE, 2);
  2720. cb->changePrimSkill (h, PrimarySkill::KNOWLEDGE, 2);
  2721. cb->changePrimSkill (h, PrimarySkill::SPELL_POWER, 2);
  2722. }
  2723. showInfoDialog(h,txt_id,sound);
  2724. break;
  2725. }
  2726. case Obj::SCHOOL_OF_MAGIC:
  2727. case Obj::SCHOOL_OF_WAR:
  2728. {
  2729. int skill = (ID==Obj::SCHOOL_OF_MAGIC ? 2 : 0);
  2730. if (cb->getResource (h->getOwner(), Res::GOLD) < 1000) //not enough resources
  2731. {
  2732. showInfoDialog (h->getOwner(), ot+2, sound);
  2733. }
  2734. else
  2735. {
  2736. BlockingDialog sd(true,true);
  2737. sd.soundID = sound;
  2738. sd.player = h->getOwner();
  2739. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2740. sd.components.push_back(Component(c_id, skill, +1, 0));
  2741. sd.components.push_back(Component(c_id, skill+1, +1, 0));
  2742. cb->showBlockingDialog(&sd);
  2743. }
  2744. }
  2745. break;
  2746. }
  2747. }
  2748. else
  2749. {
  2750. ot++;
  2751. showInfoDialog (h->getOwner(),ot,sound);
  2752. }
  2753. }
  2754. const std::string & CGVisitableOPH::getHoverText() const
  2755. {
  2756. int pom = -1;
  2757. switch(ID)
  2758. {
  2759. case Obj::ARENA:
  2760. pom = -1;
  2761. break;
  2762. case Obj::MERCENARY_CAMP:
  2763. pom = 8;
  2764. break;
  2765. case Obj::MARLETTO_TOWER:
  2766. pom = 7;
  2767. break;
  2768. case Obj::STAR_AXIS:
  2769. pom = 11;
  2770. break;
  2771. case Obj::GARDEN_OF_REVELATION:
  2772. pom = 4;
  2773. break;
  2774. case Obj::LEARNING_STONE:
  2775. pom = 5;
  2776. break;
  2777. case Obj::TREE_OF_KNOWLEDGE:
  2778. pom = 18;
  2779. break;
  2780. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2781. break;
  2782. case Obj::SCHOOL_OF_MAGIC:
  2783. pom = 9;
  2784. break;
  2785. case Obj::SCHOOL_OF_WAR:
  2786. pom = 10;
  2787. break;
  2788. default:
  2789. throw std::runtime_error("Wrong CGVisitableOPH object ID!\n");
  2790. }
  2791. hoverName = VLC->generaltexth->names[ID];
  2792. if(pom >= 0)
  2793. hoverName += ("\n" + VLC->generaltexth->xtrainfo[pom]);
  2794. const CGHeroInstance *h = cb->getSelectedHero (cb->getCurrentPlayer());
  2795. if(h)
  2796. {
  2797. hoverName += "\n\n";
  2798. bool visited = vstd::contains (visitors, h->id);
  2799. hoverName += visitedTxt (visited);
  2800. }
  2801. return hoverName;
  2802. }
  2803. void CGVisitableOPH::arenaSelected(const CGHeroInstance * h, int primSkill ) const
  2804. {
  2805. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2806. cb->changePrimSkill(h, static_cast<PrimarySkill::PrimarySkill>(primSkill-1), 2);
  2807. }
  2808. void CGVisitableOPH::setPropertyDer( ui8 what, ui32 val )
  2809. {
  2810. if(what == ObjProperty::VISITORS)
  2811. visitors.insert(ObjectInstanceID(val));
  2812. }
  2813. void CGVisitableOPH::schoolSelected(const CGHeroInstance * h, ui32 which) const
  2814. {
  2815. if(!which) //player refused to pay
  2816. return;
  2817. int base = (ID == Obj::SCHOOL_OF_MAGIC ? 2 : 0);
  2818. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2819. cb->giveResource (h->getOwner(),Res::GOLD,-1000); //take 1000 gold
  2820. cb->changePrimSkill (h, static_cast<PrimarySkill::PrimarySkill>(base + which-1), +1); //give appropriate skill
  2821. }
  2822. void CGVisitableOPH::blockingDialogAnswered(const CGHeroInstance *h, ui32 answer) const
  2823. {
  2824. switch (ID)
  2825. {
  2826. case Obj::ARENA:
  2827. arenaSelected(h, answer);
  2828. break;
  2829. case Obj::TREE_OF_KNOWLEDGE:
  2830. treeSelected(h, answer);
  2831. break;
  2832. case Obj::SCHOOL_OF_MAGIC:
  2833. case Obj::SCHOOL_OF_WAR:
  2834. schoolSelected(h, answer);
  2835. break;
  2836. default:
  2837. assert(0);
  2838. break;
  2839. }
  2840. }
  2841. COPWBonus::COPWBonus (BuildingID index, CGTownInstance *TOWN)
  2842. {
  2843. ID = index;
  2844. town = TOWN;
  2845. id = town->bonusingBuildings.size();
  2846. }
  2847. void COPWBonus::setProperty(ui8 what, ui32 val)
  2848. {
  2849. switch (what)
  2850. {
  2851. case ObjProperty::VISITORS:
  2852. visitors.insert(val);
  2853. break;
  2854. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  2855. visitors.clear();
  2856. break;
  2857. }
  2858. }
  2859. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  2860. {
  2861. ObjectInstanceID heroID = h->id;
  2862. if (town->hasBuilt(ID))
  2863. {
  2864. InfoWindow iw;
  2865. iw.player = h->tempOwner;
  2866. switch (town->subID)
  2867. {
  2868. case ETownType::CASTLE: //Stables
  2869. if (!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  2870. {
  2871. GiveBonus gb;
  2872. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  2873. gb.id = heroID.getNum();
  2874. cb->giveHeroBonus(&gb);
  2875. iw.text << VLC->generaltexth->allTexts[580];
  2876. cb->showInfoDialog(&iw);
  2877. }
  2878. break;
  2879. case ETownType::DUNGEON: //Mana Vortex
  2880. if (visitors.empty() && h->mana <= h->manaLimit() * 2)
  2881. {
  2882. cb->setManaPoints (heroID, 2 * h->manaLimit());
  2883. //TODO: investigate line below
  2884. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  2885. iw.text << VLC->generaltexth->allTexts[579];
  2886. cb->showInfoDialog(&iw);
  2887. town->addHeroToStructureVisitors(h, id);
  2888. }
  2889. break;
  2890. }
  2891. }
  2892. }
  2893. CTownBonus::CTownBonus (BuildingID index, CGTownInstance *TOWN)
  2894. {
  2895. ID = index;
  2896. town = TOWN;
  2897. id = town->bonusingBuildings.size();
  2898. }
  2899. void CTownBonus::setProperty (ui8 what, ui32 val)
  2900. {
  2901. if(what == ObjProperty::VISITORS)
  2902. visitors.insert(ObjectInstanceID(val));
  2903. }
  2904. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  2905. {
  2906. ObjectInstanceID heroID = h->id;
  2907. if (town->hasBuilt(ID) && visitors.find(heroID) == visitors.end())
  2908. {
  2909. InfoWindow iw;
  2910. PrimarySkill::PrimarySkill what = PrimarySkill::ATTACK;
  2911. int val=0, mid=0;
  2912. switch (ID)
  2913. {
  2914. case BuildingID::SPECIAL_4:
  2915. switch(town->subID)
  2916. {
  2917. case ETownType::TOWER: //wall
  2918. what = PrimarySkill::KNOWLEDGE;
  2919. val = 1;
  2920. mid = 581;
  2921. iw.components.push_back (Component(Component::PRIM_SKILL, 3, 1, 0));
  2922. break;
  2923. case ETownType::INFERNO: //order of fire
  2924. what = PrimarySkill::SPELL_POWER;
  2925. val = 1;
  2926. mid = 582;
  2927. iw.components.push_back (Component(Component::PRIM_SKILL, 2, 1, 0));
  2928. break;
  2929. case ETownType::STRONGHOLD://hall of Valhalla
  2930. what = PrimarySkill::ATTACK;
  2931. val = 1;
  2932. mid = 584;
  2933. iw.components.push_back (Component(Component::PRIM_SKILL, 0, 1, 0));
  2934. break;
  2935. case ETownType::DUNGEON://academy of battle scholars
  2936. what = PrimarySkill::EXPERIENCE;
  2937. val = h->calculateXp(1000);
  2938. mid = 583;
  2939. iw.components.push_back (Component(Component::EXPERIENCE, 0, val, 0));
  2940. break;
  2941. }
  2942. break;
  2943. case BuildingID::SPECIAL_1:
  2944. switch(town->subID)
  2945. {
  2946. case ETownType::FORTRESS: //cage of warlords
  2947. what = PrimarySkill::DEFENSE;
  2948. val = 1;
  2949. mid = 585;
  2950. iw.components.push_back (Component(Component::PRIM_SKILL, 1, 1, 0));
  2951. break;
  2952. }
  2953. break;
  2954. }
  2955. assert(mid);
  2956. iw.player = cb->getOwner(heroID);
  2957. iw.text << VLC->generaltexth->allTexts[mid];
  2958. cb->showInfoDialog(&iw);
  2959. cb->changePrimSkill (cb->getHero(heroID), what, val);
  2960. town->addHeroToStructureVisitors(h, id);
  2961. }
  2962. }
  2963. const std::string & CGCreature::getHoverText() const
  2964. {
  2965. if(stacks.empty())
  2966. {
  2967. static const std::string errorValue("!!!INVALID_STACK!!!");
  2968. //should not happen...
  2969. logGlobal->errorStream() << "Invalid stack at tile " << pos << ": subID=" << subID << "; id=" << id;
  2970. return errorValue; // references to temporary are illegal - use pre-constructed string
  2971. }
  2972. MetaString ms;
  2973. int pom = stacks.begin()->second->getQuantityID();
  2974. pom = 172 + 3*pom;
  2975. ms.addTxt(MetaString::ARRAY_TXT,pom);
  2976. ms << " " ;
  2977. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  2978. ms.toString(hoverName);
  2979. if(const CGHeroInstance *selHero = cb->getSelectedHero(cb->getCurrentPlayer()))
  2980. {
  2981. const JsonNode & texts = VLC->generaltexth->localizedTexts["adventureMap"]["monsterThreat"];
  2982. hoverName += texts["title"].String();
  2983. int choice;
  2984. double ratio = ((double)getArmyStrength() / selHero->getTotalStrength());
  2985. if (ratio < 0.1) choice = 0;
  2986. else if (ratio < 0.25) choice = 1;
  2987. else if (ratio < 0.6) choice = 2;
  2988. else if (ratio < 0.9) choice = 3;
  2989. else if (ratio < 1.1) choice = 4;
  2990. else if (ratio < 1.3) choice = 5;
  2991. else if (ratio < 1.8) choice = 6;
  2992. else if (ratio < 2.5) choice = 7;
  2993. else if (ratio < 4) choice = 8;
  2994. else if (ratio < 8) choice = 9;
  2995. else if (ratio < 20) choice = 10;
  2996. else choice = 11;
  2997. hoverName += texts["levels"].Vector()[choice].String();
  2998. }
  2999. return hoverName;
  3000. }
  3001. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  3002. {
  3003. int action = takenAction(h);
  3004. switch( action ) //decide what we do...
  3005. {
  3006. case FIGHT:
  3007. fight(h);
  3008. break;
  3009. case FLEE: //flee
  3010. {
  3011. flee(h);
  3012. break;
  3013. }
  3014. case JOIN_FOR_FREE: //join for free
  3015. {
  3016. BlockingDialog ynd(true,false);
  3017. ynd.player = h->tempOwner;
  3018. ynd.text.addTxt(MetaString::ADVOB_TXT, 86);
  3019. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  3020. cb->showBlockingDialog(&ynd);
  3021. break;
  3022. }
  3023. default: //join for gold
  3024. {
  3025. assert(action > 0);
  3026. //ask if player agrees to pay gold
  3027. BlockingDialog ynd(true,false);
  3028. ynd.player = h->tempOwner;
  3029. std::string tmp = VLC->generaltexth->advobtxt[90];
  3030. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(getStackCount(SlotID(0))));
  3031. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(action));
  3032. boost::algorithm::replace_first(tmp,"%s",VLC->creh->creatures[subID]->namePl);
  3033. ynd.text << tmp;
  3034. cb->showBlockingDialog(&ynd);
  3035. break;
  3036. }
  3037. }
  3038. }
  3039. void CGCreature::initObj()
  3040. {
  3041. blockVisit = true;
  3042. switch(character)
  3043. {
  3044. case 0:
  3045. character = -4;
  3046. break;
  3047. case 1:
  3048. character = cb->gameState()->getRandomGenerator().nextInt(1, 7);
  3049. break;
  3050. case 2:
  3051. character = cb->gameState()->getRandomGenerator().nextInt(1, 10);
  3052. break;
  3053. case 3:
  3054. character = cb->gameState()->getRandomGenerator().nextInt(4, 10);
  3055. break;
  3056. case 4:
  3057. character = 10;
  3058. break;
  3059. }
  3060. stacks[SlotID(0)]->setType(CreatureID(subID));
  3061. TQuantity &amount = stacks[SlotID(0)]->count;
  3062. CCreature &c = *VLC->creh->creatures[subID];
  3063. if(amount == 0)
  3064. {
  3065. amount = cb->gameState()->getRandomGenerator().nextInt(c.ammMin, c.ammMax);
  3066. if(amount == 0) //armies with 0 creatures are illegal
  3067. {
  3068. logGlobal->warnStream() << "Problem: stack " << nodeName() << " cannot have 0 creatures. Check properties of " << c.nodeName();
  3069. amount = 1;
  3070. }
  3071. }
  3072. formation.randomFormation = cb->gameState()->getRandomGenerator().nextInt();
  3073. temppower = stacks[SlotID(0)]->count * 1000;
  3074. refusedJoining = false;
  3075. }
  3076. void CGCreature::newTurn() const
  3077. {//Works only for stacks of single type of size up to 2 millions
  3078. if (stacks.begin()->second->count < VLC->modh->settings.CREEP_SIZE && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  3079. {
  3080. ui32 power = temppower * (100 + VLC->modh->settings.WEEKLY_GROWTH)/100;
  3081. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min (power/1000 , (ui32)VLC->modh->settings.CREEP_SIZE)); //set new amount
  3082. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  3083. }
  3084. if (VLC->modh->modules.STACK_EXP)
  3085. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->modh->settings.NEUTRAL_STACK_EXP); //for testing purpose
  3086. }
  3087. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  3088. {
  3089. switch (what)
  3090. {
  3091. case ObjProperty::MONSTER_COUNT:
  3092. stacks[SlotID(0)]->count = val;
  3093. break;
  3094. case ObjProperty::MONSTER_POWER:
  3095. temppower = val;
  3096. break;
  3097. case ObjProperty::MONSTER_EXP:
  3098. giveStackExp(val);
  3099. break;
  3100. case ObjProperty::MONSTER_RESTORE_TYPE:
  3101. formation.basicType = val;
  3102. break;
  3103. case ObjProperty::MONSTER_REFUSED_JOIN:
  3104. refusedJoining = val;
  3105. break;
  3106. }
  3107. }
  3108. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  3109. {
  3110. //calculate relative strength of hero and creatures armies
  3111. double relStrength = double(h->getTotalStrength()) / getArmyStrength();
  3112. int powerFactor;
  3113. if(relStrength >= 7)
  3114. powerFactor = 11;
  3115. else if(relStrength >= 1)
  3116. powerFactor = (int)(2*(relStrength-1));
  3117. else if(relStrength >= 0.5)
  3118. powerFactor = -1;
  3119. else if(relStrength >= 0.333)
  3120. powerFactor = -2;
  3121. else
  3122. powerFactor = -3;
  3123. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  3124. const CCreature * myCreature = VLC->creh->creatures[subID];
  3125. myKindCres.insert(myCreature->idNumber); //we
  3126. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  3127. for(ConstTransitivePtr<CCreature> &crea : VLC->creh->creatures)
  3128. {
  3129. if(vstd::contains(crea->upgrades, myCreature->idNumber)) //it's our base creatures
  3130. myKindCres.insert(crea->idNumber);
  3131. }
  3132. int count = 0, //how many creatures of similar kind has hero
  3133. totalCount = 0;
  3134. for (auto & elem : h->Slots())
  3135. {
  3136. if(vstd::contains(myKindCres,elem.second->type->idNumber))
  3137. count += elem.second->count;
  3138. totalCount += elem.second->count;
  3139. }
  3140. int sympathy = 0; // 0 if hero have no similar creatures
  3141. if(count)
  3142. sympathy++; // 1 - if hero have at least 1 similar creature
  3143. if(count*2 > totalCount)
  3144. sympathy++; // 2 - hero have similar creatures more that 50%
  3145. int charisma = powerFactor + h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy;
  3146. if(charisma < character) //creatures will fight
  3147. return -2;
  3148. if (allowJoin)
  3149. {
  3150. if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy + 1 >= character)
  3151. return 0; //join for free
  3152. else if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) * 2 + sympathy + 1 >= character)
  3153. return VLC->creh->creatures[subID]->cost[6] * getStackCount(SlotID(0)); //join for gold
  3154. }
  3155. //we are still here - creatures have not joined hero, flee or fight
  3156. if (charisma > character)
  3157. return -1; //flee
  3158. else
  3159. return -2; //fight
  3160. }
  3161. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  3162. {
  3163. if(refusedJoining)
  3164. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  3165. if(pursue)
  3166. {
  3167. fight(h);
  3168. }
  3169. else
  3170. {
  3171. cb->removeObject(this);
  3172. }
  3173. }
  3174. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  3175. {
  3176. if(!accept)
  3177. {
  3178. if(takenAction(h,false) == -1) //they flee
  3179. {
  3180. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  3181. flee(h);
  3182. }
  3183. else //they fight
  3184. {
  3185. showInfoDialog(h,87,0);//Insulted by your refusal of their offer, the monsters attack!
  3186. fight(h);
  3187. }
  3188. }
  3189. else //accepted
  3190. {
  3191. if (cb->getResource(h->tempOwner, Res::GOLD) < cost) //player don't have enough gold!
  3192. {
  3193. InfoWindow iw;
  3194. iw.player = h->tempOwner;
  3195. iw.text << std::pair<ui8,ui32>(1,29); //You don't have enough gold
  3196. cb->showInfoDialog(&iw);
  3197. //act as if player refused
  3198. joinDecision(h,cost,false);
  3199. return;
  3200. }
  3201. //take gold
  3202. if(cost)
  3203. cb->giveResource(h->tempOwner,Res::GOLD,-cost);
  3204. cb->tryJoiningArmy(this, h, true, true);
  3205. }
  3206. }
  3207. void CGCreature::fight( const CGHeroInstance *h ) const
  3208. {
  3209. //split stacks
  3210. //TODO: multiple creature types in a stack?
  3211. int basicType = stacks.begin()->second->type->idNumber;
  3212. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  3213. double relativePower = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  3214. int stacksCount;
  3215. //TODO: number depends on tile type
  3216. if (relativePower < 0.5)
  3217. {
  3218. stacksCount = 7;
  3219. }
  3220. else if (relativePower < 0.67)
  3221. {
  3222. stacksCount = 7;
  3223. }
  3224. else if (relativePower < 1)
  3225. {
  3226. stacksCount = 6;
  3227. }
  3228. else if (relativePower < 1.5)
  3229. {
  3230. stacksCount = 5;
  3231. }
  3232. else if (relativePower < 2)
  3233. {
  3234. stacksCount = 4;
  3235. }
  3236. else
  3237. {
  3238. stacksCount = 3;
  3239. }
  3240. SlotID sourceSlot = stacks.begin()->first;
  3241. SlotID destSlot;
  3242. for (int stacksLeft = stacksCount; stacksLeft > 1; --stacksLeft)
  3243. {
  3244. int stackSize = stacks.begin()->second->count / stacksLeft;
  3245. if (stackSize)
  3246. {
  3247. if ((destSlot = getFreeSlot()).validSlot())
  3248. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, destSlot), stackSize);
  3249. else
  3250. {
  3251. logGlobal->warnStream() <<"Warning! Not enough empty slots to split stack!";
  3252. break;
  3253. }
  3254. }
  3255. else break;
  3256. }
  3257. if (stacksCount > 1)
  3258. {
  3259. if (formation.randomFormation % 100 < 50) //upgrade
  3260. {
  3261. SlotID slotId = SlotID(stacks.size() / 2);
  3262. const auto & upgrades = getStack(slotId).type->upgrades;
  3263. if(!upgrades.empty())
  3264. {
  3265. auto it = RandomGeneratorUtil::nextItem(upgrades, cb->gameState()->getRandomGenerator());
  3266. cb->changeStackType(StackLocation(this, slotId), VLC->creh->creatures[*it]);
  3267. }
  3268. }
  3269. }
  3270. cb->startBattleI(h, this);
  3271. }
  3272. void CGCreature::flee( const CGHeroInstance * h ) const
  3273. {
  3274. BlockingDialog ynd(true,false);
  3275. ynd.player = h->tempOwner;
  3276. ynd.text.addTxt(MetaString::ADVOB_TXT,91);
  3277. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  3278. cb->showBlockingDialog(&ynd);
  3279. }
  3280. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3281. {
  3282. if(result.winner==0)
  3283. {
  3284. cb->removeObject(this);
  3285. }
  3286. else
  3287. {
  3288. //int killedAmount=0;
  3289. //for(std::set<std::pair<ui32,si32> >::iterator i=result->casualties[1].begin(); i!=result->casualties[1].end(); i++)
  3290. // if(i->first == subID)
  3291. // killedAmount += i->second;
  3292. //cb->setAmount(id, slots.find(0)->second.second - killedAmount);
  3293. /*
  3294. MetaString ms;
  3295. int pom = slots.find(0)->second.getQuantityID();
  3296. pom = 174 + 3*pom + 1;
  3297. ms << std::pair<ui8,ui32>(6,pom) << " " << std::pair<ui8,ui32>(7,subID);
  3298. cb->setHoverName(id,&ms);
  3299. cb->setObjProperty(id, 11, slots.begin()->second.count * 1000);
  3300. */
  3301. //merge stacks into one
  3302. TSlots::const_iterator i;
  3303. CCreature * cre = VLC->creh->creatures[formation.basicType];
  3304. for (i = stacks.begin(); i != stacks.end(); i++)
  3305. {
  3306. if (cre->isMyUpgrade(i->second->type))
  3307. {
  3308. cb->changeStackType (StackLocation(this, i->first), cre); //un-upgrade creatures
  3309. }
  3310. }
  3311. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  3312. if(!hasStackAtSlot(SlotID(0)))
  3313. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  3314. while (stacks.size() > 1) //hopefully that's enough
  3315. {
  3316. // 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)
  3317. i = stacks.end();
  3318. i--;
  3319. SlotID slot = getSlotFor(i->second->type);
  3320. if (slot == i->first) //no reason to move stack to its own slot
  3321. break;
  3322. else
  3323. cb->moveStack (StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  3324. }
  3325. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  3326. }
  3327. }
  3328. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3329. {
  3330. auto action = takenAction(hero);
  3331. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  3332. joinDecision(hero, action, answer);
  3333. else if(action != FIGHT)
  3334. fleeDecision(hero, answer);
  3335. else
  3336. assert(0);
  3337. }
  3338. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  3339. {
  3340. int relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  3341. if(relations == 2) //we're visiting our mine
  3342. {
  3343. cb->showGarrisonDialog(id,h->id,true);
  3344. return;
  3345. }
  3346. else if (relations == 1)//ally
  3347. return;
  3348. if(stacksCount()) //Mine is guarded
  3349. {
  3350. BlockingDialog ynd(true,false);
  3351. ynd.player = h->tempOwner;
  3352. ynd.text.addTxt(MetaString::ADVOB_TXT, subID == 7 ? 84 : 187);
  3353. cb->showBlockingDialog(&ynd);
  3354. return;
  3355. }
  3356. flagMine(h->tempOwner);
  3357. }
  3358. void CGMine::newTurn() const
  3359. {
  3360. if(cb->getDate() == 1)
  3361. return;
  3362. if (tempOwner == PlayerColor::NEUTRAL)
  3363. return;
  3364. cb->giveResource(tempOwner, producedResource, producedQuantity);
  3365. }
  3366. void CGMine::initObj()
  3367. {
  3368. if(subID >= 7) //Abandoned Mine
  3369. {
  3370. //set guardians
  3371. int howManyTroglodytes = cb->gameState()->getRandomGenerator().nextInt(100, 199);
  3372. auto troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  3373. putStack(SlotID(0), troglodytes);
  3374. //after map reading tempOwner placeholds bitmask for allowed resources
  3375. std::vector<Res::ERes> possibleResources;
  3376. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  3377. if(tempOwner.getNum() & 1<<i) //NOTE: reuse of tempOwner
  3378. possibleResources.push_back(static_cast<Res::ERes>(i));
  3379. assert(!possibleResources.empty());
  3380. producedResource = *RandomGeneratorUtil::nextItem(possibleResources, cb->gameState()->getRandomGenerator());
  3381. tempOwner = PlayerColor::NEUTRAL;
  3382. hoverName = VLC->generaltexth->mines[7].first + "\n" + VLC->generaltexth->allTexts[202] + " " + troglodytes->getQuantityTXT(false) + " " + troglodytes->type->namePl;
  3383. }
  3384. else
  3385. {
  3386. producedResource = static_cast<Res::ERes>(subID);
  3387. MetaString ms;
  3388. ms << std::pair<ui8,ui32>(9,producedResource);
  3389. if(tempOwner >= PlayerColor::PLAYER_LIMIT)
  3390. tempOwner = PlayerColor::NEUTRAL;
  3391. else
  3392. ms << " (" << std::pair<ui8,ui32>(6,23+tempOwner.getNum()) << ")";
  3393. ms.toString(hoverName);
  3394. }
  3395. producedQuantity = defaultResProduction();
  3396. }
  3397. void CGMine::flagMine(PlayerColor player) const
  3398. {
  3399. assert(tempOwner != player);
  3400. cb->setOwner(this, player); //not ours? flag it!
  3401. MetaString ms;
  3402. ms << std::pair<ui8,ui32>(9,subID) << "\n(" << std::pair<ui8,ui32>(6,23+player.getNum()) << ")";
  3403. if(subID == 7)
  3404. {
  3405. ms << "(%s)";
  3406. ms.addReplacement(MetaString::RES_NAMES, producedResource);
  3407. }
  3408. cb->setHoverName(this,&ms);
  3409. InfoWindow iw;
  3410. iw.soundID = soundBase::FLAGMINE;
  3411. iw.text.addTxt(MetaString::MINE_EVNTS,producedResource); //not use subID, abandoned mines uses default mine texts
  3412. iw.player = player;
  3413. iw.components.push_back(Component(Component::RESOURCE,producedResource,producedQuantity,-1));
  3414. cb->showInfoDialog(&iw);
  3415. }
  3416. ui32 CGMine::defaultResProduction()
  3417. {
  3418. switch(producedResource)
  3419. {
  3420. case Res::WOOD:
  3421. case Res::ORE:
  3422. return 2;
  3423. case Res::GOLD:
  3424. return 1000;
  3425. default:
  3426. return 1;
  3427. }
  3428. }
  3429. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3430. {
  3431. if(result.winner == 0) //attacker won
  3432. {
  3433. if(subID == 7)
  3434. {
  3435. showInfoDialog(hero->tempOwner, 85, 0);
  3436. }
  3437. flagMine(hero->tempOwner);
  3438. }
  3439. }
  3440. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3441. {
  3442. if(answer)
  3443. cb->startBattleI(hero, this);
  3444. }
  3445. void CGResource::initObj()
  3446. {
  3447. blockVisit = true;
  3448. hoverName = VLC->generaltexth->restypes[subID];
  3449. if(!amount)
  3450. {
  3451. switch(subID)
  3452. {
  3453. case 6:
  3454. amount = cb->gameState()->getRandomGenerator().nextInt(500, 1000);
  3455. break;
  3456. case 0: case 2:
  3457. amount = cb->gameState()->getRandomGenerator().nextInt(6, 10);
  3458. break;
  3459. default:
  3460. amount = cb->gameState()->getRandomGenerator().nextInt(3, 5);
  3461. break;
  3462. }
  3463. }
  3464. }
  3465. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  3466. {
  3467. if(stacksCount())
  3468. {
  3469. if(message.size())
  3470. {
  3471. BlockingDialog ynd(true,false);
  3472. ynd.player = h->getOwner();
  3473. ynd.text << message;
  3474. cb->showBlockingDialog(&ynd);
  3475. }
  3476. else
  3477. {
  3478. blockingDialogAnswered(h, true); //behave as if player accepted battle
  3479. }
  3480. }
  3481. else
  3482. {
  3483. if(message.length())
  3484. {
  3485. InfoWindow iw;
  3486. iw.player = h->tempOwner;
  3487. iw.text << message;
  3488. cb->showInfoDialog(&iw);
  3489. }
  3490. collectRes(h->getOwner());
  3491. }
  3492. }
  3493. void CGResource::collectRes( PlayerColor player ) const
  3494. {
  3495. cb->giveResource(player, static_cast<Res::ERes>(subID), amount);
  3496. ShowInInfobox sii;
  3497. sii.player = player;
  3498. sii.c = Component(Component::RESOURCE,subID,amount,0);
  3499. sii.text.addTxt(MetaString::ADVOB_TXT,113);
  3500. sii.text.addReplacement(MetaString::RES_NAMES, subID);
  3501. cb->showCompInfo(&sii);
  3502. cb->removeObject(this);
  3503. }
  3504. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3505. {
  3506. if(result.winner == 0) //attacker won
  3507. collectRes(hero->getOwner());
  3508. }
  3509. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3510. {
  3511. if(answer)
  3512. cb->startBattleI(hero, this);
  3513. }
  3514. void CGVisitableOPW::newTurn() const
  3515. {
  3516. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //first day of week = 1
  3517. {
  3518. cb->setObjProperty(id, ObjProperty::VISITED, false);
  3519. MetaString ms; //set text to "not visited"
  3520. ms << std::pair<ui8,ui32>(3,ID) << " " << std::pair<ui8,ui32>(1,353);
  3521. cb->setHoverName(this,&ms);
  3522. }
  3523. }
  3524. bool CGVisitableOPW::wasVisited(PlayerColor player) const
  3525. {
  3526. return visited; //TODO: other players should see object as unvisited
  3527. }
  3528. void CGVisitableOPW::onHeroVisit( const CGHeroInstance * h ) const
  3529. {
  3530. int mid=0, sound = 0;
  3531. switch (ID)
  3532. {
  3533. case Obj::MYSTICAL_GARDEN:
  3534. sound = soundBase::experience;
  3535. mid = 92;
  3536. break;
  3537. case Obj::WINDMILL:
  3538. sound = soundBase::GENIE;
  3539. mid = 170;
  3540. break;
  3541. case Obj::WATER_WHEEL:
  3542. sound = soundBase::GENIE;
  3543. mid = 164;
  3544. break;
  3545. default:
  3546. assert(0);
  3547. }
  3548. if (visited)
  3549. {
  3550. if (ID!=Obj::WINDMILL)
  3551. mid++;
  3552. else
  3553. mid--;
  3554. showInfoDialog(h,mid,sound);
  3555. }
  3556. else
  3557. {
  3558. Component::EComponentType type = Component::RESOURCE;
  3559. Res::ERes sub=Res::WOOD;
  3560. int val=0;
  3561. auto & rand = cb->gameState()->getRandomGenerator();
  3562. switch (ID)
  3563. {
  3564. case Obj::MYSTICAL_GARDEN:
  3565. if(rand.nextInt(1) == 1)
  3566. {
  3567. sub = Res::GEMS;
  3568. val = 5;
  3569. }
  3570. else
  3571. {
  3572. sub = Res::GOLD;
  3573. val = 500;
  3574. }
  3575. break;
  3576. case Obj::WINDMILL:
  3577. mid = 170;
  3578. sub = static_cast<Res::ERes>(rand.nextInt(1, 5));
  3579. val = rand.nextInt(3, 6);
  3580. break;
  3581. case Obj::WATER_WHEEL:
  3582. mid = 164;
  3583. sub = Res::GOLD;
  3584. if(cb->getDate(Date::DAY)<8)
  3585. val = 500;
  3586. else
  3587. val = 1000;
  3588. }
  3589. cb->giveResource(h->tempOwner, sub, val);
  3590. InfoWindow iw;
  3591. iw.soundID = sound;
  3592. iw.player = h->tempOwner;
  3593. iw.components.push_back(Component(type,sub,val,0));
  3594. iw.text.addTxt(MetaString::ADVOB_TXT,mid);
  3595. cb->showInfoDialog(&iw);
  3596. cb->setObjProperty(id, ObjProperty::VISITED, true);
  3597. MetaString ms; //set text to "visited"
  3598. ms.addTxt(MetaString::OBJ_NAMES,ID); ms << " "; ms.addTxt(MetaString::GENERAL_TXT,352);
  3599. cb->setHoverName(this,&ms);
  3600. }
  3601. }
  3602. void CGVisitableOPW::setPropertyDer( ui8 what, ui32 val )
  3603. {
  3604. if(what == ObjProperty::VISITED)
  3605. visited = val;
  3606. }
  3607. void CGTeleport::onHeroVisit( const CGHeroInstance * h ) const
  3608. {
  3609. ObjectInstanceID destinationid;
  3610. switch(ID)
  3611. {
  3612. case Obj::MONOLITH1: //one way - find corresponding exit monolith
  3613. {
  3614. if(vstd::contains(objs,Obj::MONOLITH2) && vstd::contains(objs[Obj::MONOLITH2],subID) && objs[Obj::MONOLITH2][subID].size())
  3615. {
  3616. destinationid = *RandomGeneratorUtil::nextItem(objs[Obj::MONOLITH2][subID], cb->gameState()->getRandomGenerator());
  3617. }
  3618. else
  3619. {
  3620. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  3621. }
  3622. break;
  3623. }
  3624. case Obj::MONOLITH3://two way monolith - pick any other one
  3625. case Obj::WHIRLPOOL: //Whirlpool
  3626. if(vstd::contains(objs,ID) && vstd::contains(objs[ID],subID) && objs[ID][subID].size()>1)
  3627. {
  3628. //choose another exit
  3629. do
  3630. {
  3631. destinationid = *RandomGeneratorUtil::nextItem(objs[ID][subID], cb->gameState()->getRandomGenerator());
  3632. } while(destinationid == id);
  3633. if (ID == Obj::WHIRLPOOL)
  3634. {
  3635. if (!h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION))
  3636. {
  3637. if (h->Slots().size() > 1 || h->Slots().begin()->second->count > 1)
  3638. { //we can't remove last unit
  3639. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  3640. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  3641. {
  3642. if (h->getPower(targetstack) > h->getPower(i->first))
  3643. {
  3644. targetstack = (i->first);
  3645. }
  3646. }
  3647. TQuantity countToTake = h->getStackCount(targetstack) * 0.5;
  3648. vstd::amax(countToTake, 1);
  3649. InfoWindow iw;
  3650. iw.player = h->tempOwner;
  3651. iw.text.addTxt (MetaString::ADVOB_TXT, 168);
  3652. iw.components.push_back (Component(CStackBasicDescriptor(h->getCreature(targetstack), countToTake)));
  3653. cb->showInfoDialog(&iw);
  3654. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  3655. }
  3656. }
  3657. }
  3658. }
  3659. else
  3660. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  3661. break;
  3662. case Obj::SUBTERRANEAN_GATE: //find nearest subterranean gate on the other level
  3663. {
  3664. destinationid = getMatchingGate(id);
  3665. if(destinationid == ObjectInstanceID()) //no exit
  3666. {
  3667. showInfoDialog(h,153,0);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  3668. }
  3669. break;
  3670. }
  3671. }
  3672. if(destinationid == ObjectInstanceID())
  3673. {
  3674. logGlobal->warnStream() << "Cannot find exit... (obj at " << pos << ") :( ";
  3675. return;
  3676. }
  3677. if (ID == Obj::WHIRLPOOL)
  3678. {
  3679. std::set<int3> tiles = cb->getObj(destinationid)->getBlockedPos();
  3680. auto & tile = *RandomGeneratorUtil::nextItem(tiles, cb->gameState()->getRandomGenerator());
  3681. cb->moveHero(h->id, tile + int3(1,0,0), true);
  3682. }
  3683. else
  3684. cb->moveHero (h->id,CGHeroInstance::convertPosition(cb->getObj(destinationid)->pos,true) - getVisitableOffset(), true);
  3685. }
  3686. void CGTeleport::initObj()
  3687. {
  3688. int si = subID;
  3689. switch (ID)
  3690. {
  3691. case Obj::SUBTERRANEAN_GATE://ignore subterranean gates subid
  3692. case Obj::WHIRLPOOL:
  3693. {
  3694. si = 0;
  3695. break;
  3696. }
  3697. default:
  3698. break;
  3699. }
  3700. objs[ID][si].push_back(id);
  3701. }
  3702. void CGTeleport::postInit() //matches subterranean gates into pairs
  3703. {
  3704. //split on underground and surface gates
  3705. std::vector<const CGObjectInstance *> gatesSplit[2]; //surface and underground gates
  3706. for(auto & elem : objs[Obj::SUBTERRANEAN_GATE][0])
  3707. {
  3708. const CGObjectInstance *hlp = cb->getObj(elem);
  3709. gatesSplit[hlp->pos.z].push_back(hlp);
  3710. }
  3711. //sort by position
  3712. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  3713. {
  3714. return a->pos < b->pos;
  3715. });
  3716. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  3717. {
  3718. const CGObjectInstance *cur = gatesSplit[0][i];
  3719. //find nearest underground exit
  3720. std::pair<int,double> best(-1,150000); //pair<pos_in_vector, distance>
  3721. for(int j = 0; j < gatesSplit[1].size(); j++)
  3722. {
  3723. const CGObjectInstance *checked = gatesSplit[1][j];
  3724. if(!checked)
  3725. continue;
  3726. double hlp = checked->pos.dist2d(cur->pos);
  3727. if(hlp < best.second)
  3728. {
  3729. best.first = j;
  3730. best.second = hlp;
  3731. }
  3732. }
  3733. if(best.first >= 0) //found pair
  3734. {
  3735. gates.push_back(std::make_pair(cur->id, gatesSplit[1][best.first]->id));
  3736. gatesSplit[1][best.first] = nullptr;
  3737. }
  3738. else
  3739. {
  3740. gates.push_back(std::make_pair(cur->id, ObjectInstanceID()));
  3741. }
  3742. }
  3743. objs.erase(Obj::SUBTERRANEAN_GATE);
  3744. }
  3745. ObjectInstanceID CGTeleport::getMatchingGate(ObjectInstanceID id)
  3746. {
  3747. for(auto & gate : gates)
  3748. {
  3749. if(gate.first == id)
  3750. return gate.second;
  3751. if(gate.second == id)
  3752. return gate.first;
  3753. }
  3754. return ObjectInstanceID();
  3755. }
  3756. void CGArtifact::initObj()
  3757. {
  3758. blockVisit = true;
  3759. if(ID == Obj::ARTIFACT)
  3760. {
  3761. hoverName = VLC->arth->artifacts[subID]->Name();
  3762. if(!storedArtifact->artType)
  3763. storedArtifact->setType(VLC->arth->artifacts[subID]);
  3764. }
  3765. if(ID == Obj::SPELL_SCROLL)
  3766. subID = 1;
  3767. assert(storedArtifact->artType);
  3768. assert(storedArtifact->getParentNodes().size());
  3769. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  3770. }
  3771. void CGArtifact::onHeroVisit( const CGHeroInstance * h ) const
  3772. {
  3773. if(!stacksCount())
  3774. {
  3775. InfoWindow iw;
  3776. iw.player = h->tempOwner;
  3777. switch(ID)
  3778. {
  3779. case Obj::ARTIFACT:
  3780. {
  3781. iw.soundID = soundBase::treasure; //play sound only for non-scroll arts
  3782. iw.components.push_back(Component(Component::ARTIFACT,subID,0,0));
  3783. if(message.length())
  3784. iw.text << message;
  3785. else
  3786. {
  3787. if (VLC->arth->artifacts[subID]->EventText().size())
  3788. iw.text << std::pair<ui8, ui32> (MetaString::ART_EVNTS, subID);
  3789. else //fix for mod artifacts with no event text
  3790. {
  3791. iw.text.addTxt (MetaString::ADVOB_TXT, 183); //% has found treasure
  3792. iw.text.addReplacement (h->name);
  3793. }
  3794. }
  3795. }
  3796. break;
  3797. case Obj::SPELL_SCROLL:
  3798. {
  3799. int spellID = storedArtifact->getGivenSpellID();
  3800. iw.components.push_back (Component(Component::SPELL, spellID,0,0));
  3801. iw.text.addTxt (MetaString::ADVOB_TXT,135);
  3802. iw.text.addReplacement(MetaString::SPELL_NAME, spellID);
  3803. }
  3804. break;
  3805. }
  3806. cb->showInfoDialog(&iw);
  3807. pick(h);
  3808. }
  3809. else
  3810. {
  3811. if(message.size())
  3812. {
  3813. BlockingDialog ynd(true,false);
  3814. ynd.player = h->getOwner();
  3815. ynd.text << message;
  3816. cb->showBlockingDialog(&ynd);
  3817. }
  3818. else
  3819. {
  3820. blockingDialogAnswered(h, true);
  3821. }
  3822. }
  3823. }
  3824. void CGArtifact::pick(const CGHeroInstance * h) const
  3825. {
  3826. cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  3827. cb->removeObject(this);
  3828. }
  3829. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3830. {
  3831. if(result.winner == 0) //attacker won
  3832. pick(hero);
  3833. }
  3834. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3835. {
  3836. if(answer)
  3837. cb->startBattleI(hero, this);
  3838. }
  3839. void CGPickable::initObj()
  3840. {
  3841. blockVisit = true;
  3842. switch(ID)
  3843. {
  3844. case Obj::CAMPFIRE:
  3845. val2 = cb->gameState()->getRandomGenerator().nextInt(4, 6);
  3846. val1 = val2 * 100;
  3847. type = cb->gameState()->getRandomGenerator().nextInt(5); // given resource
  3848. break;
  3849. case Obj::FLOTSAM:
  3850. switch(type = cb->gameState()->getRandomGenerator().nextInt(3))
  3851. {
  3852. case 0:
  3853. val1 = val2 = 0;
  3854. break;
  3855. case 1:
  3856. val1 = 5;
  3857. val2 = 0;
  3858. break;
  3859. case 2:
  3860. val1 = 5;
  3861. val2 = 200;
  3862. break;
  3863. case 3:
  3864. val1 = 10;
  3865. val2 = 500;
  3866. break;
  3867. }
  3868. break;
  3869. case Obj::SEA_CHEST:
  3870. {
  3871. int hlp = cb->gameState()->getRandomGenerator().nextInt(99);
  3872. if(hlp < 20)
  3873. {
  3874. val1 = 0;
  3875. type = 0;
  3876. }
  3877. else if(hlp < 90)
  3878. {
  3879. val1 = 1500;
  3880. type = 2;
  3881. }
  3882. else
  3883. {
  3884. val1 = 1000;
  3885. val2 = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_TREASURE);
  3886. type = 1;
  3887. }
  3888. }
  3889. break;
  3890. case Obj::SHIPWRECK_SURVIVOR:
  3891. {
  3892. int hlp = cb->gameState()->getRandomGenerator().nextInt(99);
  3893. if(hlp < 55)
  3894. val1 = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_TREASURE);
  3895. else if(hlp < 75)
  3896. val1 = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_MINOR);
  3897. else if(hlp < 95)
  3898. val1 = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_MAJOR);
  3899. else
  3900. val1 = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_RELIC);
  3901. }
  3902. break;
  3903. case Obj::TREASURE_CHEST:
  3904. {
  3905. int hlp = cb->gameState()->getRandomGenerator().nextInt(99);
  3906. if(hlp >= 95)
  3907. {
  3908. type = 1;
  3909. val1 = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_TREASURE);
  3910. return;
  3911. }
  3912. else if (hlp >= 65)
  3913. {
  3914. val1 = 2000;
  3915. }
  3916. else if(hlp >= 33)
  3917. {
  3918. val1 = 1500;
  3919. }
  3920. else
  3921. {
  3922. val1 = 1000;
  3923. }
  3924. val2 = val1 - 500;
  3925. type = 0;
  3926. break;
  3927. }
  3928. }
  3929. }
  3930. void CGPickable::onHeroVisit( const CGHeroInstance * h ) const
  3931. {
  3932. switch(ID)
  3933. {
  3934. case Obj::CAMPFIRE:
  3935. {
  3936. cb->giveResource(h->tempOwner,static_cast<Res::ERes>(type),val2); //non-gold resource
  3937. cb->giveResource(h->tempOwner,Res::GOLD,val1);//gold
  3938. InfoWindow iw;
  3939. iw.soundID = soundBase::experience;
  3940. iw.player = h->tempOwner;
  3941. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3942. iw.components.push_back(Component(Component::RESOURCE,type,val2,0));
  3943. iw.text.addTxt(MetaString::ADVOB_TXT,23);
  3944. cb->showInfoDialog(&iw);
  3945. break;
  3946. }
  3947. case Obj::FLOTSAM:
  3948. {
  3949. cb->giveResource(h->tempOwner,Res::WOOD,val1); //wood
  3950. cb->giveResource(h->tempOwner,Res::GOLD,val2);//gold
  3951. InfoWindow iw;
  3952. iw.soundID = soundBase::GENIE;
  3953. iw.player = h->tempOwner;
  3954. if(val1)
  3955. iw.components.push_back(Component(Component::RESOURCE,Res::WOOD,val1,0));
  3956. if(val2)
  3957. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val2,0));
  3958. iw.text.addTxt(MetaString::ADVOB_TXT, 51+type);
  3959. cb->showInfoDialog(&iw);
  3960. break;
  3961. }
  3962. case Obj::SEA_CHEST:
  3963. {
  3964. InfoWindow iw;
  3965. iw.soundID = soundBase::chest;
  3966. iw.player = h->tempOwner;
  3967. iw.text.addTxt(MetaString::ADVOB_TXT, 116 + type);
  3968. if(val1) //there is gold
  3969. {
  3970. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3971. cb->giveResource(h->tempOwner,Res::GOLD,val1);
  3972. }
  3973. if(type == 1) //art
  3974. {
  3975. //TODO: what if no space in backpack?
  3976. iw.components.push_back(Component(Component::ARTIFACT, val2, 1, 0));
  3977. iw.text.addReplacement(MetaString::ART_NAMES, val2);
  3978. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val2],ArtifactPosition::FIRST_AVAILABLE);
  3979. }
  3980. cb->showInfoDialog(&iw);
  3981. break;
  3982. }
  3983. case Obj::SHIPWRECK_SURVIVOR:
  3984. {
  3985. InfoWindow iw;
  3986. iw.soundID = soundBase::experience;
  3987. iw.player = h->tempOwner;
  3988. iw.components.push_back(Component(Component::ARTIFACT,val1,1,0));
  3989. iw.text.addTxt(MetaString::ADVOB_TXT, 125);
  3990. iw.text.addReplacement(MetaString::ART_NAMES, val1);
  3991. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val1],ArtifactPosition::FIRST_AVAILABLE);
  3992. cb->showInfoDialog(&iw);
  3993. break;
  3994. }
  3995. case Obj::TREASURE_CHEST:
  3996. {
  3997. if (subID) //not OH3 treasure chest
  3998. {
  3999. logGlobal->warnStream() << "Not supported WoG treasure chest!";
  4000. return;
  4001. }
  4002. if(type) //there is an artifact
  4003. {
  4004. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val1],ArtifactPosition::FIRST_AVAILABLE);
  4005. InfoWindow iw;
  4006. iw.soundID = soundBase::treasure;
  4007. iw.player = h->tempOwner;
  4008. iw.components.push_back(Component(Component::ARTIFACT,val1,1,0));
  4009. iw.text.addTxt(MetaString::ADVOB_TXT,145);
  4010. iw.text.addReplacement(MetaString::ART_NAMES, val1);
  4011. cb->showInfoDialog(&iw);
  4012. break;
  4013. }
  4014. else
  4015. {
  4016. BlockingDialog sd(false,true);
  4017. sd.player = h->tempOwner;
  4018. sd.text.addTxt(MetaString::ADVOB_TXT,146);
  4019. sd.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  4020. TExpType expVal = h->calculateXp(val2);
  4021. sd.components.push_back(Component(Component::EXPERIENCE,0,expVal, 0));
  4022. sd.soundID = soundBase::chest;
  4023. cb->showBlockingDialog(&sd);
  4024. return;
  4025. }
  4026. }
  4027. }
  4028. cb->removeObject(this);
  4029. }
  4030. void CGPickable::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  4031. {
  4032. switch(answer)
  4033. {
  4034. case 1: //player pick gold
  4035. cb->giveResource(hero->tempOwner, Res::GOLD, val1);
  4036. break;
  4037. case 2: //player pick exp
  4038. cb->changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(val2));
  4039. break;
  4040. default:
  4041. throw std::runtime_error("Unhandled treasure choice");
  4042. }
  4043. cb->removeObject(this);
  4044. }
  4045. bool CQuest::checkQuest (const CGHeroInstance * h) const
  4046. {
  4047. switch (missionType)
  4048. {
  4049. case MISSION_NONE:
  4050. return true;
  4051. case MISSION_LEVEL:
  4052. if (m13489val <= h->level)
  4053. return true;
  4054. return false;
  4055. case MISSION_PRIMARY_STAT:
  4056. for (int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  4057. {
  4058. if (h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i)) < m2stats[i])
  4059. return false;
  4060. }
  4061. return true;
  4062. case MISSION_KILL_HERO:
  4063. case MISSION_KILL_CREATURE:
  4064. if (!h->cb->getObjByQuestIdentifier(m13489val))
  4065. return true;
  4066. return false;
  4067. case MISSION_ART:
  4068. for (auto & elem : m5arts)
  4069. {
  4070. if (h->hasArt(elem))
  4071. continue;
  4072. return false; //if the artifact was not found
  4073. }
  4074. return true;
  4075. case MISSION_ARMY:
  4076. {
  4077. std::vector<CStackBasicDescriptor>::const_iterator cre;
  4078. TSlots::const_iterator it;
  4079. ui32 count;
  4080. for (cre = m6creatures.begin(); cre != m6creatures.end(); ++cre)
  4081. {
  4082. for (count = 0, it = h->Slots().begin(); it != h->Slots().end(); ++it)
  4083. {
  4084. if (it->second->type == cre->type)
  4085. count += it->second->count;
  4086. }
  4087. if (count < cre->count) //not enough creatures of this kind
  4088. return false;
  4089. }
  4090. }
  4091. return true;
  4092. case MISSION_RESOURCES:
  4093. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, +1)) //including Mithril ?
  4094. { //Quest has no direct access to callback
  4095. if (h->cb->getResource (h->tempOwner, i) < m7resources[i])
  4096. return false;
  4097. }
  4098. return true;
  4099. case MISSION_HERO:
  4100. if (m13489val == h->type->ID.getNum())
  4101. return true;
  4102. return false;
  4103. case MISSION_PLAYER:
  4104. if (m13489val == h->getOwner().getNum())
  4105. return true;
  4106. return false;
  4107. default:
  4108. return false;
  4109. }
  4110. }
  4111. void CQuest::getVisitText (MetaString &iwText, std::vector<Component> &components, bool isCustom, bool firstVisit, const CGHeroInstance * h) const
  4112. {
  4113. std::string text;
  4114. bool failRequirements = (h ? !checkQuest(h) : true);
  4115. if (firstVisit)
  4116. {
  4117. isCustom = isCustomFirst;
  4118. iwText << (text = firstVisitText);
  4119. }
  4120. else if (failRequirements)
  4121. {
  4122. isCustom = isCustomNext;
  4123. iwText << (text = nextVisitText);
  4124. }
  4125. switch (missionType)
  4126. {
  4127. case MISSION_LEVEL:
  4128. components.push_back(Component (Component::EXPERIENCE, 0, m13489val, 0));
  4129. if (!isCustom)
  4130. iwText.addReplacement(m13489val);
  4131. break;
  4132. case MISSION_PRIMARY_STAT:
  4133. {
  4134. MetaString loot;
  4135. for (int i = 0; i < 4; ++i)
  4136. {
  4137. if (m2stats[i])
  4138. {
  4139. components.push_back(Component (Component::PRIM_SKILL, i, m2stats[i], 0));
  4140. loot << "%d %s";
  4141. loot.addReplacement(m2stats[i]);
  4142. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4143. }
  4144. }
  4145. if (!isCustom)
  4146. iwText.addReplacement(loot.buildList());
  4147. }
  4148. break;
  4149. case MISSION_KILL_HERO:
  4150. components.push_back(Component(Component::HERO_PORTRAIT, heroPortrait, 0, 0));
  4151. if (!isCustom)
  4152. addReplacements(iwText, text);
  4153. break;
  4154. case MISSION_HERO:
  4155. //FIXME: portrait may not match hero, if custom portrait was set in map editor
  4156. components.push_back(Component (Component::HERO_PORTRAIT, VLC->heroh->heroes[m13489val]->imageIndex, 0, 0));
  4157. if (!isCustom)
  4158. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4159. break;
  4160. case MISSION_KILL_CREATURE:
  4161. {
  4162. components.push_back(Component(stackToKill));
  4163. if (!isCustom)
  4164. {
  4165. addReplacements(iwText, text);
  4166. }
  4167. }
  4168. break;
  4169. case MISSION_ART:
  4170. {
  4171. MetaString loot;
  4172. for (auto & elem : m5arts)
  4173. {
  4174. components.push_back(Component (Component::ARTIFACT, elem, 0, 0));
  4175. loot << "%s";
  4176. loot.addReplacement(MetaString::ART_NAMES, elem);
  4177. }
  4178. if (!isCustom)
  4179. iwText.addReplacement(loot.buildList());
  4180. }
  4181. break;
  4182. case MISSION_ARMY:
  4183. {
  4184. MetaString loot;
  4185. for (auto & elem : m6creatures)
  4186. {
  4187. components.push_back(Component(elem));
  4188. loot << "%s";
  4189. loot.addReplacement(elem);
  4190. }
  4191. if (!isCustom)
  4192. iwText.addReplacement(loot.buildList());
  4193. }
  4194. break;
  4195. case MISSION_RESOURCES:
  4196. {
  4197. MetaString loot;
  4198. for (int i = 0; i < 7; ++i)
  4199. {
  4200. if (m7resources[i])
  4201. {
  4202. components.push_back(Component (Component::RESOURCE, i, m7resources[i], 0));
  4203. loot << "%d %s";
  4204. loot.addReplacement(m7resources[i]);
  4205. loot.addReplacement(MetaString::RES_NAMES, i);
  4206. }
  4207. }
  4208. if (!isCustom)
  4209. iwText.addReplacement(loot.buildList());
  4210. }
  4211. break;
  4212. case MISSION_PLAYER:
  4213. components.push_back(Component (Component::FLAG, m13489val, 0, 0));
  4214. if (!isCustom)
  4215. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  4216. break;
  4217. }
  4218. }
  4219. void CQuest::getRolloverText (MetaString &ms, bool onHover) const
  4220. {
  4221. if (onHover)
  4222. ms << "\n\n";
  4223. ms << VLC->generaltexth->quests[missionType-1][onHover ? 3 : 4][textOption];
  4224. switch (missionType)
  4225. {
  4226. case MISSION_LEVEL:
  4227. ms.addReplacement(m13489val);
  4228. break;
  4229. case MISSION_PRIMARY_STAT:
  4230. {
  4231. MetaString loot;
  4232. for (int i = 0; i < 4; ++i)
  4233. {
  4234. if (m2stats[i])
  4235. {
  4236. loot << "%d %s";
  4237. loot.addReplacement(m2stats[i]);
  4238. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4239. }
  4240. }
  4241. ms.addReplacement(loot.buildList());
  4242. }
  4243. break;
  4244. case MISSION_KILL_HERO:
  4245. ms.addReplacement(heroName);
  4246. break;
  4247. case MISSION_KILL_CREATURE:
  4248. ms.addReplacement(stackToKill);
  4249. break;
  4250. case MISSION_ART:
  4251. {
  4252. MetaString loot;
  4253. for (auto & elem : m5arts)
  4254. {
  4255. loot << "%s";
  4256. loot.addReplacement(MetaString::ART_NAMES, elem);
  4257. }
  4258. ms.addReplacement(loot.buildList());
  4259. }
  4260. break;
  4261. case MISSION_ARMY:
  4262. {
  4263. MetaString loot;
  4264. for (auto & elem : m6creatures)
  4265. {
  4266. loot << "%s";
  4267. loot.addReplacement(elem);
  4268. }
  4269. ms.addReplacement(loot.buildList());
  4270. }
  4271. break;
  4272. case MISSION_RESOURCES:
  4273. {
  4274. MetaString loot;
  4275. for (int i = 0; i < 7; ++i)
  4276. {
  4277. if (m7resources[i])
  4278. {
  4279. loot << "%d %s";
  4280. loot.addReplacement(m7resources[i]);
  4281. loot.addReplacement(MetaString::RES_NAMES, i);
  4282. }
  4283. }
  4284. ms.addReplacement(loot.buildList());
  4285. }
  4286. break;
  4287. case MISSION_HERO:
  4288. ms.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4289. break;
  4290. case MISSION_PLAYER:
  4291. ms.addReplacement(VLC->generaltexth->colors[m13489val]);
  4292. break;
  4293. default:
  4294. break;
  4295. }
  4296. }
  4297. void CQuest::getCompletionText (MetaString &iwText, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  4298. {
  4299. iwText << completedText;
  4300. switch (missionType)
  4301. {
  4302. case CQuest::MISSION_LEVEL:
  4303. if (!isCustomComplete)
  4304. iwText.addReplacement(m13489val);
  4305. break;
  4306. case CQuest::MISSION_PRIMARY_STAT:
  4307. if (vstd::contains (completedText,'%')) //there's one case when there's nothing to replace
  4308. {
  4309. MetaString loot;
  4310. for (int i = 0; i < 4; ++i)
  4311. {
  4312. if (m2stats[i])
  4313. {
  4314. loot << "%d %s";
  4315. loot.addReplacement(m2stats[i]);
  4316. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4317. }
  4318. }
  4319. if (!isCustomComplete)
  4320. iwText.addReplacement(loot.buildList());
  4321. }
  4322. break;
  4323. case CQuest::MISSION_ART:
  4324. {
  4325. MetaString loot;
  4326. for (auto & elem : m5arts)
  4327. {
  4328. loot << "%s";
  4329. loot.addReplacement(MetaString::ART_NAMES, elem);
  4330. }
  4331. if (!isCustomComplete)
  4332. iwText.addReplacement(loot.buildList());
  4333. }
  4334. break;
  4335. case CQuest::MISSION_ARMY:
  4336. {
  4337. MetaString loot;
  4338. for (auto & elem : m6creatures)
  4339. {
  4340. loot << "%s";
  4341. loot.addReplacement(elem);
  4342. }
  4343. if (!isCustomComplete)
  4344. iwText.addReplacement(loot.buildList());
  4345. }
  4346. break;
  4347. case CQuest::MISSION_RESOURCES:
  4348. {
  4349. MetaString loot;
  4350. for (int i = 0; i < 7; ++i)
  4351. {
  4352. if (m7resources[i])
  4353. {
  4354. loot << "%d %s";
  4355. loot.addReplacement(m7resources[i]);
  4356. loot.addReplacement(MetaString::RES_NAMES, i);
  4357. }
  4358. }
  4359. if (!isCustomComplete)
  4360. iwText.addReplacement(loot.buildList());
  4361. }
  4362. break;
  4363. case MISSION_KILL_HERO:
  4364. case MISSION_KILL_CREATURE:
  4365. if (!isCustomComplete)
  4366. addReplacements(iwText, completedText);
  4367. break;
  4368. case MISSION_HERO:
  4369. if (!isCustomComplete)
  4370. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4371. break;
  4372. case MISSION_PLAYER:
  4373. if (!isCustomComplete)
  4374. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  4375. break;
  4376. }
  4377. }
  4378. void CGSeerHut::setObjToKill()
  4379. {
  4380. if (quest->missionType == CQuest::MISSION_KILL_CREATURE)
  4381. {
  4382. quest->stackToKill = getCreatureToKill(false)->getStack(SlotID(0)); //FIXME: stacks tend to disappear (desync?) on server :?
  4383. assert(quest->stackToKill.type);
  4384. quest->stackToKill.count = 0; //no count in info window
  4385. quest->stackDirection = checkDirection();
  4386. }
  4387. else if (quest->missionType == CQuest::MISSION_KILL_HERO)
  4388. {
  4389. quest->heroName = getHeroToKill(false)->name;
  4390. quest->heroPortrait = getHeroToKill(false)->portrait;
  4391. }
  4392. }
  4393. void CGSeerHut::init()
  4394. {
  4395. seerName = *RandomGeneratorUtil::nextItem(VLC->generaltexth->seerNames, cb->gameState()->getRandomGenerator());
  4396. quest->textOption = cb->gameState()->getRandomGenerator().nextInt(2);
  4397. }
  4398. void CGSeerHut::initObj()
  4399. {
  4400. init();
  4401. quest->progress = CQuest::NOT_ACTIVE;
  4402. if (quest->missionType)
  4403. {
  4404. if (!quest->isCustomFirst)
  4405. quest->firstVisitText = VLC->generaltexth->quests[quest->missionType-1][0][quest->textOption];
  4406. if (!quest->isCustomNext)
  4407. quest->nextVisitText = VLC->generaltexth->quests[quest->missionType-1][1][quest->textOption];
  4408. if (!quest->isCustomComplete)
  4409. quest->completedText = VLC->generaltexth->quests[quest->missionType-1][2][quest->textOption];
  4410. }
  4411. else
  4412. {
  4413. quest->progress = CQuest::COMPLETE;
  4414. quest->firstVisitText = VLC->generaltexth->seerEmpty[quest->textOption];
  4415. }
  4416. }
  4417. void CGSeerHut::getRolloverText (MetaString &text, bool onHover) const
  4418. {
  4419. quest->getRolloverText (text, onHover);//TODO: simplify?
  4420. if (!onHover)
  4421. text.addReplacement(seerName);
  4422. }
  4423. const std::string & CGSeerHut::getHoverText() const
  4424. {
  4425. switch (ID)
  4426. {
  4427. case Obj::SEER_HUT:
  4428. if (quest->progress != CQuest::NOT_ACTIVE)
  4429. {
  4430. hoverName = VLC->generaltexth->allTexts[347];
  4431. boost::algorithm::replace_first(hoverName,"%s", seerName);
  4432. }
  4433. else //just seer hut
  4434. hoverName = VLC->generaltexth->names[ID];
  4435. break;
  4436. case Obj::QUEST_GUARD:
  4437. hoverName = VLC->generaltexth->names[ID];
  4438. break;
  4439. default:
  4440. logGlobal->debugStream() << "unrecognized quest object";
  4441. }
  4442. if (quest->progress & quest->missionType) //rollover when the quest is active
  4443. {
  4444. MetaString ms;
  4445. getRolloverText (ms, true);
  4446. hoverName += ms.toString();
  4447. }
  4448. return hoverName;
  4449. }
  4450. void CQuest::addReplacements(MetaString &out, const std::string &base) const
  4451. {
  4452. switch(missionType)
  4453. {
  4454. case MISSION_KILL_CREATURE:
  4455. out.addReplacement(stackToKill);
  4456. if (std::count(base.begin(), base.end(), '%') == 2) //say where is placed monster
  4457. {
  4458. out.addReplacement(VLC->generaltexth->arraytxt[147+stackDirection]);
  4459. }
  4460. break;
  4461. case MISSION_KILL_HERO:
  4462. out.addReplacement(heroName);
  4463. break;
  4464. }
  4465. }
  4466. bool IQuestObject::checkQuest(const CGHeroInstance* h) const
  4467. {
  4468. return quest->checkQuest(h);
  4469. }
  4470. void IQuestObject::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  4471. {
  4472. quest->getVisitText (text,components, isCustom, FirstVisit, h);
  4473. }
  4474. void CGSeerHut::getCompletionText(MetaString &text, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  4475. {
  4476. quest->getCompletionText (text, components, isCustom, h);
  4477. switch (rewardType)
  4478. {
  4479. case EXPERIENCE: components.push_back(Component (Component::EXPERIENCE, 0, h->calculateXp(rVal), 0));
  4480. break;
  4481. case MANA_POINTS: components.push_back(Component (Component::PRIM_SKILL, 5, rVal, 0));
  4482. break;
  4483. case MORALE_BONUS: components.push_back(Component (Component::MORALE, 0, rVal, 0));
  4484. break;
  4485. case LUCK_BONUS: components.push_back(Component (Component::LUCK, 0, rVal, 0));
  4486. break;
  4487. case RESOURCES: components.push_back(Component (Component::RESOURCE, rID, rVal, 0));
  4488. break;
  4489. case PRIMARY_SKILL: components.push_back(Component (Component::PRIM_SKILL, rID, rVal, 0));
  4490. break;
  4491. case SECONDARY_SKILL: components.push_back(Component (Component::SEC_SKILL, rID, rVal, 0));
  4492. break;
  4493. case ARTIFACT: components.push_back(Component (Component::ARTIFACT, rID, 0, 0));
  4494. break;
  4495. case SPELL: components.push_back(Component (Component::SPELL, rID, 0, 0));
  4496. break;
  4497. case CREATURE: components.push_back(Component (Component::CREATURE, rID, rVal, 0));
  4498. break;
  4499. }
  4500. }
  4501. void CGSeerHut::setPropertyDer (ui8 what, ui32 val)
  4502. {
  4503. switch (what)
  4504. {
  4505. case 10:
  4506. quest->progress = static_cast<CQuest::Eprogress>(val);
  4507. break;
  4508. }
  4509. }
  4510. void CGSeerHut::newTurn() const
  4511. {
  4512. if (quest->lastDay >= 0 && quest->lastDay < cb->getDate()-1) //time is up
  4513. {
  4514. cb->setObjProperty (id, 10, CQuest::COMPLETE);
  4515. }
  4516. }
  4517. void CGSeerHut::onHeroVisit( const CGHeroInstance * h ) const
  4518. {
  4519. InfoWindow iw;
  4520. iw.player = h->getOwner();
  4521. if (quest->progress < CQuest::COMPLETE)
  4522. {
  4523. bool firstVisit = !quest->progress;
  4524. bool failRequirements = !checkQuest(h);
  4525. bool isCustom=false;
  4526. if (firstVisit)
  4527. {
  4528. isCustom = quest->isCustomFirst;
  4529. cb->setObjProperty (id, 10, CQuest::IN_PROGRESS);
  4530. AddQuest aq;
  4531. aq.quest = QuestInfo (quest, this, visitablePos());
  4532. aq.player = h->tempOwner;
  4533. cb->sendAndApply (&aq); //TODO: merge with setObjProperty?
  4534. }
  4535. else if (failRequirements)
  4536. {
  4537. isCustom = quest->isCustomNext;
  4538. }
  4539. if (firstVisit || failRequirements)
  4540. {
  4541. getVisitText (iw.text, iw.components, isCustom, firstVisit, h);
  4542. cb->showInfoDialog(&iw);
  4543. }
  4544. if (!failRequirements) // propose completion, also on first visit
  4545. {
  4546. BlockingDialog bd (true, false);
  4547. bd.player = h->getOwner();
  4548. bd.soundID = soundBase::QUEST;
  4549. getCompletionText (bd.text, bd.components, isCustom, h);
  4550. cb->showBlockingDialog (&bd);
  4551. return;
  4552. }
  4553. }
  4554. else
  4555. {
  4556. iw.text << VLC->generaltexth->seerEmpty[quest->textOption];
  4557. if (ID == Obj::SEER_HUT)
  4558. iw.text.addReplacement(seerName);
  4559. cb->showInfoDialog(&iw);
  4560. }
  4561. }
  4562. int CGSeerHut::checkDirection() const
  4563. {
  4564. int3 cord = getCreatureToKill()->pos;
  4565. if ((double)cord.x/(double)cb->getMapSize().x < 0.34) //north
  4566. {
  4567. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //northwest
  4568. return 8;
  4569. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //north
  4570. return 1;
  4571. else //northeast
  4572. return 2;
  4573. }
  4574. else if ((double)cord.x/(double)cb->getMapSize().x < 0.67) //horizontal
  4575. {
  4576. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //west
  4577. return 7;
  4578. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //central
  4579. return 9;
  4580. else //east
  4581. return 3;
  4582. }
  4583. else //south
  4584. {
  4585. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //southwest
  4586. return 6;
  4587. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //south
  4588. return 5;
  4589. else //southeast
  4590. return 4;
  4591. }
  4592. }
  4593. void CGSeerHut::finishQuest(const CGHeroInstance * h, ui32 accept) const
  4594. {
  4595. if (accept)
  4596. {
  4597. switch (quest->missionType)
  4598. {
  4599. case CQuest::MISSION_ART:
  4600. for (auto & elem : quest->m5arts)
  4601. {
  4602. cb->removeArtifact(ArtifactLocation(h, h->getArtPos(elem, false)));
  4603. }
  4604. break;
  4605. case CQuest::MISSION_ARMY:
  4606. cb->takeCreatures(h->id, quest->m6creatures);
  4607. break;
  4608. case CQuest::MISSION_RESOURCES:
  4609. for (int i = 0; i < 7; ++i)
  4610. {
  4611. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(i), -quest->m7resources[i]);
  4612. }
  4613. break;
  4614. default:
  4615. break;
  4616. }
  4617. cb->setObjProperty (id, 10, CQuest::COMPLETE); //mission complete
  4618. completeQuest(h); //make sure to remove QuestGuard at the very end
  4619. }
  4620. }
  4621. void CGSeerHut::completeQuest (const CGHeroInstance * h) const //reward
  4622. {
  4623. switch (rewardType)
  4624. {
  4625. case EXPERIENCE:
  4626. {
  4627. TExpType expVal = h->calculateXp(rVal);
  4628. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  4629. break;
  4630. }
  4631. case MANA_POINTS:
  4632. {
  4633. cb->setManaPoints(h->id, h->mana+rVal);
  4634. break;
  4635. }
  4636. case MORALE_BONUS: case LUCK_BONUS:
  4637. {
  4638. Bonus hb(Bonus::ONE_WEEK, (rewardType == 3 ? Bonus::MORALE : Bonus::LUCK),
  4639. Bonus::OBJECT, rVal, h->id.getNum(), "", -1);
  4640. GiveBonus gb;
  4641. gb.id = h->id.getNum();
  4642. gb.bonus = hb;
  4643. cb->giveHeroBonus(&gb);
  4644. }
  4645. break;
  4646. case RESOURCES:
  4647. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(rID), rVal);
  4648. break;
  4649. case PRIMARY_SKILL:
  4650. cb->changePrimSkill(h, static_cast<PrimarySkill::PrimarySkill>(rID), rVal, false);
  4651. break;
  4652. case SECONDARY_SKILL:
  4653. cb->changeSecSkill(h, SecondarySkill(rID), rVal, false);
  4654. break;
  4655. case ARTIFACT:
  4656. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[rID],ArtifactPosition::FIRST_AVAILABLE);
  4657. break;
  4658. case SPELL:
  4659. {
  4660. std::set<SpellID> spell;
  4661. spell.insert (SpellID(rID));
  4662. cb->changeSpells(h, true, spell);
  4663. }
  4664. break;
  4665. case CREATURE:
  4666. {
  4667. CCreatureSet creatures;
  4668. creatures.setCreature(SlotID(0), CreatureID(rID), rVal);
  4669. cb->giveCreatures(this, h, creatures, false);
  4670. }
  4671. break;
  4672. default:
  4673. break;
  4674. }
  4675. }
  4676. const CGHeroInstance * CGSeerHut::getHeroToKill(bool allowNull) const
  4677. {
  4678. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  4679. if(allowNull && !o)
  4680. return nullptr;
  4681. assert(o && (o->ID == Obj::HERO || o->ID == Obj::PRISON));
  4682. return static_cast<const CGHeroInstance*>(o);
  4683. }
  4684. const CGCreature * CGSeerHut::getCreatureToKill(bool allowNull) const
  4685. {
  4686. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  4687. if(allowNull && !o)
  4688. return nullptr;
  4689. assert(o && o->ID == Obj::MONSTER);
  4690. return static_cast<const CGCreature*>(o);
  4691. }
  4692. void CGSeerHut::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  4693. {
  4694. finishQuest(hero, answer);
  4695. }
  4696. void CGQuestGuard::init()
  4697. {
  4698. blockVisit = true;
  4699. quest->textOption = cb->gameState()->getRandomGenerator().nextInt(3, 5);
  4700. }
  4701. void CGQuestGuard::completeQuest(const CGHeroInstance *h) const
  4702. {
  4703. cb->removeObject(this);
  4704. }
  4705. void CGWitchHut::initObj()
  4706. {
  4707. ability = *RandomGeneratorUtil::nextItem(allowedAbilities, cb->gameState()->getRandomGenerator());
  4708. }
  4709. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  4710. {
  4711. InfoWindow iw;
  4712. iw.soundID = soundBase::gazebo;
  4713. iw.player = h->getOwner();
  4714. if(!wasVisited(h->tempOwner))
  4715. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  4716. ui32 txt_id;
  4717. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  4718. {
  4719. txt_id =172;
  4720. }
  4721. else if(!h->canLearnSkill()) //already all skills slots used
  4722. {
  4723. txt_id = 173;
  4724. }
  4725. else //give sec skill
  4726. {
  4727. iw.components.push_back(Component(Component::SEC_SKILL, ability, 1, 0));
  4728. txt_id = 171;
  4729. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  4730. }
  4731. iw.text.addTxt(MetaString::ADVOB_TXT,txt_id);
  4732. iw.text.addReplacement(MetaString::SEC_SKILL_NAME, ability);
  4733. cb->showInfoDialog(&iw);
  4734. }
  4735. const std::string & CGWitchHut::getHoverText() const
  4736. {
  4737. hoverName = VLC->generaltexth->names[ID];
  4738. if(wasVisited(cb->getLocalPlayer()))
  4739. {
  4740. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  4741. boost::algorithm::replace_first(hoverName,"%s",VLC->generaltexth->skillName[ability]);
  4742. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4743. if(h && h->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  4744. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  4745. }
  4746. return hoverName;
  4747. }
  4748. bool CGBonusingObject::wasVisited (const CGHeroInstance * h) const
  4749. {
  4750. return h->hasBonusFrom(Bonus::OBJECT, ID);
  4751. }
  4752. void CGBonusingObject::onHeroVisit( const CGHeroInstance * h ) const
  4753. {
  4754. bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  4755. int messageID=0;
  4756. int bonusMove = 0;
  4757. ui32 descr_id = 0;
  4758. InfoWindow iw;
  4759. iw.player = h->tempOwner;
  4760. GiveBonus gbonus;
  4761. gbonus.id = h->id.getNum();
  4762. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  4763. gbonus.bonus.source = Bonus::OBJECT;
  4764. gbonus.bonus.sid = ID;
  4765. bool second = false;
  4766. Bonus secondBonus;
  4767. switch(ID)
  4768. {
  4769. case Obj::BUOY:
  4770. messageID = 21;
  4771. iw.soundID = soundBase::MORALE;
  4772. gbonus.bonus.type = Bonus::MORALE;
  4773. gbonus.bonus.val = +1;
  4774. descr_id = 94;
  4775. break;
  4776. case Obj::SWAN_POND:
  4777. messageID = 29;
  4778. iw.soundID = soundBase::LUCK;
  4779. gbonus.bonus.type = Bonus::LUCK;
  4780. gbonus.bonus.val = 2;
  4781. descr_id = 67;
  4782. bonusMove = -h->movement;
  4783. break;
  4784. case Obj::FAERIE_RING:
  4785. messageID = 49;
  4786. iw.soundID = soundBase::LUCK;
  4787. gbonus.bonus.type = Bonus::LUCK;
  4788. gbonus.bonus.val = 1;
  4789. descr_id = 71;
  4790. break;
  4791. case Obj::FOUNTAIN_OF_FORTUNE:
  4792. messageID = 55;
  4793. iw.soundID = soundBase::LUCK;
  4794. gbonus.bonus.type = Bonus::LUCK;
  4795. gbonus.bonus.val = cb->gameState()->getRandomGenerator().nextInt(-1, 3);
  4796. descr_id = 69;
  4797. gbonus.bdescr.addReplacement((gbonus.bonus.val<0 ? "-" : "+") + boost::lexical_cast<std::string>(gbonus.bonus.val));
  4798. break;
  4799. case Obj::IDOL_OF_FORTUNE:
  4800. messageID = 62;
  4801. iw.soundID = soundBase::experience;
  4802. gbonus.bonus.val = 1;
  4803. descr_id = 68;
  4804. if(cb->getDate(Date::DAY_OF_WEEK) == 7) //7th day of week
  4805. {
  4806. gbonus.bonus.type = Bonus::MORALE;
  4807. second = true;
  4808. secondBonus = gbonus.bonus;
  4809. secondBonus.type = Bonus::LUCK;
  4810. }
  4811. else
  4812. {
  4813. gbonus.bonus.type = (cb->getDate(Date::DAY_OF_WEEK)%2) ? Bonus::LUCK : Bonus::MORALE;
  4814. }
  4815. break;
  4816. case Obj::MERMAID:
  4817. messageID = 83;
  4818. iw.soundID = soundBase::LUCK;
  4819. gbonus.bonus.type = Bonus::LUCK;
  4820. gbonus.bonus.val = 1;
  4821. descr_id = 72;
  4822. break;
  4823. case Obj::RALLY_FLAG:
  4824. iw.soundID = soundBase::MORALE;
  4825. messageID = 111;
  4826. gbonus.bonus.type = Bonus::MORALE;
  4827. gbonus.bonus.val = 1;
  4828. descr_id = 102;
  4829. second = true;
  4830. secondBonus = gbonus.bonus;
  4831. secondBonus.type = Bonus::LUCK;
  4832. bonusMove = 400;
  4833. break;
  4834. case Obj::OASIS:
  4835. iw.soundID = soundBase::MORALE;
  4836. messageID = 95;
  4837. gbonus.bonus.type = Bonus::MORALE;
  4838. gbonus.bonus.val = 1;
  4839. descr_id = 95;
  4840. bonusMove = 800;
  4841. break;
  4842. case Obj::TEMPLE:
  4843. messageID = 140;
  4844. iw.soundID = soundBase::temple;
  4845. gbonus.bonus.type = Bonus::MORALE;
  4846. if(cb->getDate(Date::DAY_OF_WEEK)==7) //sunday
  4847. {
  4848. gbonus.bonus.val = 2;
  4849. descr_id = 97;
  4850. }
  4851. else
  4852. {
  4853. gbonus.bonus.val = 1;
  4854. descr_id = 96;
  4855. }
  4856. break;
  4857. case Obj::WATERING_HOLE:
  4858. iw.soundID = soundBase::MORALE;
  4859. messageID = 166;
  4860. gbonus.bonus.type = Bonus::MORALE;
  4861. gbonus.bonus.val = 1;
  4862. descr_id = 100;
  4863. bonusMove = 400;
  4864. break;
  4865. case Obj::FOUNTAIN_OF_YOUTH:
  4866. iw.soundID = soundBase::MORALE;
  4867. messageID = 57;
  4868. gbonus.bonus.type = Bonus::MORALE;
  4869. gbonus.bonus.val = 1;
  4870. descr_id = 103;
  4871. bonusMove = 400;
  4872. break;
  4873. case Obj::STABLES:
  4874. iw.soundID = soundBase::STORE;
  4875. bool someUpgradeDone = false;
  4876. for (auto i = h->Slots().begin(); i != h->Slots().end(); ++i)
  4877. {
  4878. if(i->second->type->idNumber == CreatureID::CAVALIER)
  4879. {
  4880. cb->changeStackType(StackLocation(h, i->first), VLC->creh->creatures[CreatureID::CHAMPION]);
  4881. someUpgradeDone = true;
  4882. }
  4883. }
  4884. if (someUpgradeDone)
  4885. {
  4886. messageID = 138;
  4887. iw.components.push_back(Component(Component::CREATURE,11,0,1));
  4888. }
  4889. else
  4890. messageID = 137;
  4891. gbonus.bonus.type = Bonus::LAND_MOVEMENT;
  4892. gbonus.bonus.val = 600;
  4893. bonusMove = 600;
  4894. gbonus.bonus.duration = Bonus::ONE_WEEK;
  4895. //gbonus.bdescr << std::pair<ui8,ui32>(6, 100);
  4896. break;
  4897. }
  4898. if (descr_id != 0)
  4899. gbonus.bdescr.addTxt(MetaString::ARRAY_TXT,descr_id);
  4900. assert(messageID);
  4901. if(visited)
  4902. {
  4903. if(ID==Obj::RALLY_FLAG || ID==Obj::OASIS || ID==Obj::MERMAID || ID==Obj::STABLES)
  4904. messageID--;
  4905. else
  4906. messageID++;
  4907. }
  4908. else
  4909. {
  4910. //TODO: fix if second bonus val != main bonus val
  4911. if(gbonus.bonus.type == Bonus::MORALE || secondBonus.type == Bonus::MORALE)
  4912. iw.components.push_back(Component(Component::MORALE,0,gbonus.bonus.val,0));
  4913. if(gbonus.bonus.type == Bonus::LUCK || secondBonus.type == Bonus::LUCK)
  4914. iw.components.push_back(Component(Component::LUCK,0,gbonus.bonus.val,0));
  4915. cb->giveHeroBonus(&gbonus);
  4916. if(second)
  4917. {
  4918. gbonus.bonus = secondBonus;
  4919. cb->giveHeroBonus(&gbonus);
  4920. }
  4921. if(bonusMove) //swan pond - take all move points, stables - give move point this day
  4922. {
  4923. SetMovePoints smp;
  4924. smp.hid = h->id;
  4925. smp.val = h->movement + bonusMove;
  4926. cb->setMovePoints(&smp);
  4927. }
  4928. }
  4929. iw.text.addTxt(MetaString::ADVOB_TXT,messageID);
  4930. cb->showInfoDialog(&iw);
  4931. }
  4932. const std::string & CGBonusingObject::getHoverText() const
  4933. {
  4934. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4935. hoverName = VLC->generaltexth->names[ID];
  4936. if(h)
  4937. {
  4938. bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  4939. hoverName += " " + visitedTxt(visited);
  4940. }
  4941. return hoverName;
  4942. }
  4943. void CGBonusingObject::initObj()
  4944. {
  4945. if(ID == Obj::BUOY || ID == Obj::MERMAID)
  4946. {
  4947. blockVisit = true;
  4948. }
  4949. }
  4950. void CGMagicSpring::setPropertyDer(ui8 what, ui32 val)
  4951. {
  4952. CGVisitableOPW::setPropertyDer (what, val); //set visitable if applicable
  4953. if (what == ObjProperty::LEFT_VISITED)
  4954. {
  4955. if (visitedTile == RIGHT)
  4956. visited = true; //both field were used, object is not available this week
  4957. else
  4958. visitedTile = LEFT;
  4959. }
  4960. else if (what == ObjProperty::RIGHT_VISITED)
  4961. {
  4962. if (visitedTile == LEFT)
  4963. visited = true;
  4964. else
  4965. visitedTile = RIGHT;
  4966. }
  4967. else if (what == ObjProperty::LEFTRIGHT_CLEAR)
  4968. visitedTile = CLEAR;
  4969. }
  4970. std::vector<int3> CGMagicSpring::getVisitableOffsets() const
  4971. {
  4972. std::vector <int3> visitableTiles;
  4973. for(int y = 0; y < 6; y++)
  4974. for (int x = 0; x < 8; x++) //starting from left
  4975. if (appearance.isVisitableAt(x, y))
  4976. visitableTiles.push_back (int3(x, y , 0));
  4977. return visitableTiles;
  4978. }
  4979. int3 CGMagicSpring::getVisitableOffset() const
  4980. {
  4981. //FIXME: this also should stop AI from passing through already visited spring, is that ok?
  4982. auto visitableTiles = getVisitableOffsets();
  4983. if (visitableTiles.size() < 2)
  4984. {
  4985. logGlobal->warnStream() << "Warning: Magic Spring should have at least two visitable offsets!";
  4986. return int3(-1,-1,-1);
  4987. }
  4988. if (visited)
  4989. return int3(-1,-1,-1);
  4990. else
  4991. {
  4992. if (visitedTile == RIGHT)
  4993. return visitableTiles[0]; //visit the other one now
  4994. else if (visitedTile == LEFT)
  4995. return visitableTiles[1];
  4996. else
  4997. return visitableTiles[0]; //only left one?
  4998. }
  4999. }
  5000. void CGMagicSpring::onHeroVisit(const CGHeroInstance * h) const
  5001. {
  5002. int messageID;
  5003. if (!visited)
  5004. {
  5005. if (h->mana > h->manaLimit())
  5006. messageID = 76;
  5007. else
  5008. {
  5009. messageID = 74;
  5010. cb->setManaPoints (h->id, 2 * h->manaLimit());//TODO: mark left or right tile visited
  5011. if (visitedTile) //visitng the second tile
  5012. cb->setObjProperty (id, ObjProperty::VISITED, true);
  5013. else
  5014. {
  5015. auto visitableTiles = getVisitableOffsets();
  5016. assert (visitableTiles.size() >= 2);
  5017. if (h->getPosition() == pos - visitableTiles[0])
  5018. cb->setObjProperty (id, ObjProperty::LEFT_VISITED, true);
  5019. else if (h->getPosition() == pos - visitableTiles[1])
  5020. cb->setObjProperty (id, ObjProperty::RIGHT_VISITED, true);
  5021. else
  5022. logGlobal->warnStream() << "Warning: hero is not on any Magic Spring visitable offsets!";
  5023. }
  5024. }
  5025. }
  5026. else
  5027. messageID = 75;
  5028. showInfoDialog(h,messageID,soundBase::GENIE);
  5029. }
  5030. void CGMagicSpring::newTurn() const
  5031. {
  5032. CGVisitableOPW::newTurn();
  5033. if (cb->getDate(Date::DAY_OF_WEEK) == 1)
  5034. {
  5035. cb->setObjProperty(id, ObjProperty::LEFTRIGHT_CLEAR, false);
  5036. }
  5037. }
  5038. const std::string & CGMagicSpring::getHoverText() const
  5039. {
  5040. //TODO: change hover text depending on hovered tile
  5041. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  5042. return hoverName;
  5043. }
  5044. void CGMagicWell::onHeroVisit( const CGHeroInstance * h ) const
  5045. {
  5046. int message;
  5047. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Well today
  5048. {
  5049. message = 78;//"A second drink at the well in one day will not help you."
  5050. }
  5051. else if(h->mana < h->manaLimit())
  5052. {
  5053. giveDummyBonus(h->id);
  5054. cb->setManaPoints(h->id,h->manaLimit());
  5055. message = 77;
  5056. }
  5057. else
  5058. {
  5059. message = 79;
  5060. }
  5061. showInfoDialog(h,message,soundBase::faerie);
  5062. }
  5063. const std::string & CGMagicWell::getHoverText() const
  5064. {
  5065. getNameVis(hoverName);
  5066. return hoverName;
  5067. }
  5068. void CGPandoraBox::initObj()
  5069. {
  5070. blockVisit = (ID==Obj::PANDORAS_BOX); //block only if it's really pandora's box (events also derive from that class)
  5071. hasGuardians = stacks.size();
  5072. }
  5073. void CGPandoraBox::onHeroVisit(const CGHeroInstance * h) const
  5074. {
  5075. BlockingDialog bd (true, false);
  5076. bd.player = h->getOwner();
  5077. bd.soundID = soundBase::QUEST;
  5078. bd.text.addTxt (MetaString::ADVOB_TXT, 14);
  5079. cb->showBlockingDialog (&bd);
  5080. }
  5081. void CGPandoraBox::giveContentsUpToExp(const CGHeroInstance *h) const
  5082. {
  5083. cb->removeAfterVisit(this);
  5084. InfoWindow iw;
  5085. iw.player = h->getOwner();
  5086. bool changesPrimSkill = false;
  5087. for (auto & elem : primskills)
  5088. {
  5089. if(elem)
  5090. {
  5091. changesPrimSkill = true;
  5092. break;
  5093. }
  5094. }
  5095. if(gainedExp || changesPrimSkill || abilities.size())
  5096. {
  5097. TExpType expVal = h->calculateXp(gainedExp);
  5098. //getText(iw,afterBattle,175,h); //wtf?
  5099. iw.text.addTxt(MetaString::ADVOB_TXT, 175); //%s learns something
  5100. iw.text.addReplacement(h->name);
  5101. if(expVal)
  5102. iw.components.push_back(Component(Component::EXPERIENCE,0,expVal,0));
  5103. for(int i=0; i<primskills.size(); i++)
  5104. if(primskills[i])
  5105. iw.components.push_back(Component(Component::PRIM_SKILL,i,primskills[i],0));
  5106. for(int i=0; i<abilities.size(); i++)
  5107. iw.components.push_back(Component(Component::SEC_SKILL,abilities[i],abilityLevels[i],0));
  5108. cb->showInfoDialog(&iw);
  5109. //give sec skills
  5110. for(int i=0; i<abilities.size(); i++)
  5111. {
  5112. int curLev = h->getSecSkillLevel(abilities[i]);
  5113. if( (curLev && curLev < abilityLevels[i]) || (h->canLearnSkill() ))
  5114. {
  5115. cb->changeSecSkill(h,abilities[i],abilityLevels[i],true);
  5116. }
  5117. }
  5118. //give prim skills
  5119. for(int i=0; i<primskills.size(); i++)
  5120. if(primskills[i])
  5121. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(i),primskills[i],false);
  5122. assert(!cb->isVisitCoveredByAnotherQuery(this, h));
  5123. //give exp
  5124. if(expVal)
  5125. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  5126. }
  5127. if(!cb->isVisitCoveredByAnotherQuery(this, h))
  5128. giveContentsAfterExp(h);
  5129. //Otherwise continuation occurs via post-level-up callback.
  5130. }
  5131. void CGPandoraBox::giveContentsAfterExp(const CGHeroInstance *h) const
  5132. {
  5133. bool hadGuardians = hasGuardians; //copy, because flag will be emptied after issuing first post-battle message
  5134. std::string msg = message; //in case box is removed in the meantime
  5135. InfoWindow iw;
  5136. iw.player = h->getOwner();
  5137. if(spells.size())
  5138. {
  5139. std::set<SpellID> spellsToGive;
  5140. iw.components.clear();
  5141. if (spells.size() > 1)
  5142. {
  5143. iw.text.addTxt(MetaString::ADVOB_TXT, 188); //%s learns spells
  5144. }
  5145. else
  5146. {
  5147. iw.text.addTxt(MetaString::ADVOB_TXT, 184); //%s learns a spell
  5148. }
  5149. iw.text.addReplacement(h->name);
  5150. std::vector<ConstTransitivePtr<CSpell> > * sp = &VLC->spellh->objects;
  5151. for(auto i=spells.cbegin(); i != spells.cend(); i++)
  5152. {
  5153. if ((*sp)[*i]->level <= h->getSecSkillLevel(SecondarySkill::WISDOM) + 2) //enough wisdom
  5154. {
  5155. iw.components.push_back(Component(Component::SPELL,*i,0,0));
  5156. spellsToGive.insert(*i);
  5157. }
  5158. }
  5159. if(!spellsToGive.empty())
  5160. {
  5161. cb->changeSpells(h,true,spellsToGive);
  5162. cb->showInfoDialog(&iw);
  5163. }
  5164. }
  5165. if(manaDiff)
  5166. {
  5167. getText(iw,hadGuardians,manaDiff,176,177,h);
  5168. iw.components.push_back(Component(Component::PRIM_SKILL,5,manaDiff,0));
  5169. cb->showInfoDialog(&iw);
  5170. cb->setManaPoints(h->id, h->mana + manaDiff);
  5171. }
  5172. if(moraleDiff)
  5173. {
  5174. getText(iw,hadGuardians,moraleDiff,178,179,h);
  5175. iw.components.push_back(Component(Component::MORALE,0,moraleDiff,0));
  5176. cb->showInfoDialog(&iw);
  5177. GiveBonus gb;
  5178. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,moraleDiff,id.getNum(),"");
  5179. gb.id = h->id.getNum();
  5180. cb->giveHeroBonus(&gb);
  5181. }
  5182. if(luckDiff)
  5183. {
  5184. getText(iw,hadGuardians,luckDiff,180,181,h);
  5185. iw.components.push_back(Component(Component::LUCK,0,luckDiff,0));
  5186. cb->showInfoDialog(&iw);
  5187. GiveBonus gb;
  5188. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,luckDiff,id.getNum(),"");
  5189. gb.id = h->id.getNum();
  5190. cb->giveHeroBonus(&gb);
  5191. }
  5192. iw.components.clear();
  5193. iw.text.clear();
  5194. for(int i=0; i<resources.size(); i++)
  5195. {
  5196. if(resources[i] < 0)
  5197. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  5198. }
  5199. if(iw.components.size())
  5200. {
  5201. getText(iw,hadGuardians,182,h);
  5202. cb->showInfoDialog(&iw);
  5203. }
  5204. iw.components.clear();
  5205. iw.text.clear();
  5206. for(int i=0; i<resources.size(); i++)
  5207. {
  5208. if(resources[i] > 0)
  5209. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  5210. }
  5211. if(iw.components.size())
  5212. {
  5213. getText(iw,hadGuardians,183,h);
  5214. cb->showInfoDialog(&iw);
  5215. }
  5216. iw.components.clear();
  5217. // getText(iw,afterBattle,183,h);
  5218. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure
  5219. iw.text.addReplacement(h->name);
  5220. for(auto & elem : artifacts)
  5221. {
  5222. iw.components.push_back(Component(Component::ARTIFACT,elem,0,0));
  5223. if(iw.components.size() >= 14)
  5224. {
  5225. cb->showInfoDialog(&iw);
  5226. iw.components.clear();
  5227. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure - once more?
  5228. iw.text.addReplacement(h->name);
  5229. }
  5230. }
  5231. if(iw.components.size())
  5232. {
  5233. cb->showInfoDialog(&iw);
  5234. }
  5235. for(int i=0; i<resources.size(); i++)
  5236. if(resources[i])
  5237. cb->giveResource(h->getOwner(),static_cast<Res::ERes>(i),resources[i]);
  5238. for(auto & elem : artifacts)
  5239. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[elem],ArtifactPosition::FIRST_AVAILABLE);
  5240. iw.components.clear();
  5241. iw.text.clear();
  5242. if (creatures.Slots().size())
  5243. { //this part is taken straight from creature bank
  5244. MetaString loot;
  5245. for(auto & elem : creatures.Slots())
  5246. { //build list of joined creatures
  5247. iw.components.push_back(Component(*elem.second));
  5248. loot << "%s";
  5249. loot.addReplacement(*elem.second);
  5250. }
  5251. if (creatures.Slots().size() == 1 && creatures.Slots().begin()->second->count == 1)
  5252. iw.text.addTxt(MetaString::ADVOB_TXT, 185);
  5253. else
  5254. iw.text.addTxt(MetaString::ADVOB_TXT, 186);
  5255. iw.text.addReplacement(loot.buildList());
  5256. iw.text.addReplacement(h->name);
  5257. cb->showInfoDialog(&iw);
  5258. cb->giveCreatures(this, h, creatures, true);
  5259. }
  5260. if(!hasGuardians && msg.size())
  5261. {
  5262. iw.text << msg;
  5263. cb->showInfoDialog(&iw);
  5264. }
  5265. }
  5266. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int text, const CGHeroInstance * h ) const
  5267. {
  5268. if(afterBattle || !message.size())
  5269. {
  5270. iw.text.addTxt(MetaString::ADVOB_TXT,text);//%s has lost treasure.
  5271. iw.text.addReplacement(h->name);
  5272. }
  5273. else
  5274. {
  5275. iw.text << message;
  5276. afterBattle = true;
  5277. }
  5278. }
  5279. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int val, int negative, int positive, const CGHeroInstance * h ) const
  5280. {
  5281. iw.components.clear();
  5282. iw.text.clear();
  5283. if(afterBattle || !message.size())
  5284. {
  5285. iw.text.addTxt(MetaString::ADVOB_TXT,val < 0 ? negative : positive); //%s's luck takes a turn for the worse / %s's luck increases
  5286. iw.text.addReplacement(h->name);
  5287. }
  5288. else
  5289. {
  5290. iw.text << message;
  5291. afterBattle = true;
  5292. }
  5293. }
  5294. void CGPandoraBox::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5295. {
  5296. if(result.winner)
  5297. return;
  5298. giveContentsUpToExp(hero);
  5299. }
  5300. void CGPandoraBox::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5301. {
  5302. if (answer)
  5303. {
  5304. if (stacksCount() > 0) //if pandora's box is protected by army
  5305. {
  5306. showInfoDialog(hero,16,0);
  5307. cb->startBattleI(hero, this); //grants things after battle
  5308. }
  5309. else if (message.size() == 0 && resources.size() == 0
  5310. && primskills.size() == 0 && abilities.size() == 0
  5311. && abilityLevels.size() == 0 && artifacts.size() == 0
  5312. && spells.size() == 0 && creatures.Slots().size() > 0
  5313. && gainedExp == 0 && manaDiff == 0 && moraleDiff == 0 && luckDiff == 0) //if it gives nothing without battle
  5314. {
  5315. showInfoDialog(hero,15,0);
  5316. cb->removeObject(this);
  5317. }
  5318. else //if it gives something without battle
  5319. {
  5320. giveContentsUpToExp(hero);
  5321. }
  5322. }
  5323. }
  5324. void CGPandoraBox::heroLevelUpDone(const CGHeroInstance *hero) const
  5325. {
  5326. giveContentsAfterExp(hero);
  5327. }
  5328. void CGEvent::onHeroVisit( const CGHeroInstance * h ) const
  5329. {
  5330. if(!(availableFor & (1 << h->tempOwner.getNum())))
  5331. return;
  5332. if(cb->getPlayerSettings(h->tempOwner)->playerID)
  5333. {
  5334. if(humanActivate)
  5335. activated(h);
  5336. }
  5337. else if(computerActivate)
  5338. activated(h);
  5339. }
  5340. void CGEvent::activated( const CGHeroInstance * h ) const
  5341. {
  5342. if(stacksCount() > 0)
  5343. {
  5344. InfoWindow iw;
  5345. iw.player = h->tempOwner;
  5346. if(message.size())
  5347. iw.text << message;
  5348. else
  5349. iw.text.addTxt(MetaString::ADVOB_TXT, 16);
  5350. cb->showInfoDialog(&iw);
  5351. cb->startBattleI(h, this);
  5352. }
  5353. else
  5354. {
  5355. giveContentsUpToExp(h);
  5356. }
  5357. }
  5358. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  5359. {
  5360. InfoWindow iw;
  5361. iw.player = h->tempOwner;
  5362. switch (ID)
  5363. {
  5364. case Obj::REDWOOD_OBSERVATORY:
  5365. case Obj::PILLAR_OF_FIRE:
  5366. {
  5367. iw.soundID = soundBase::LIGHTHOUSE;
  5368. iw.text.addTxt(MetaString::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  5369. FoWChange fw;
  5370. fw.player = h->tempOwner;
  5371. fw.mode = 1;
  5372. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  5373. cb->sendAndApply (&fw);
  5374. break;
  5375. }
  5376. case Obj::COVER_OF_DARKNESS:
  5377. {
  5378. iw.text.addTxt (MetaString::ADVOB_TXT, 31);
  5379. hideTiles(h->tempOwner, 20);
  5380. break;
  5381. }
  5382. }
  5383. cb->showInfoDialog(&iw);
  5384. }
  5385. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  5386. {
  5387. if(spell == SpellID::NONE)
  5388. {
  5389. logGlobal->errorStream() << "Not initialized shrine visited!";
  5390. return;
  5391. }
  5392. if(!wasVisited(h->tempOwner))
  5393. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  5394. InfoWindow iw;
  5395. iw.soundID = soundBase::temple;
  5396. iw.player = h->getOwner();
  5397. iw.text.addTxt(MetaString::ADVOB_TXT,127 + ID - 88);
  5398. iw.text.addTxt(MetaString::SPELL_NAME,spell);
  5399. iw.text << ".";
  5400. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  5401. {
  5402. iw.text.addTxt(MetaString::ADVOB_TXT,131);
  5403. }
  5404. else if(ID == Obj::SHRINE_OF_MAGIC_THOUGHT && !h->getSecSkillLevel(SecondarySkill::WISDOM)) //it's third level spell and hero doesn't have wisdom
  5405. {
  5406. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  5407. }
  5408. else if(vstd::contains(h->spells,spell))//hero already knows the spell
  5409. {
  5410. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  5411. }
  5412. else //give spell
  5413. {
  5414. std::set<SpellID> spells;
  5415. spells.insert(spell);
  5416. cb->changeSpells(h, true, spells);
  5417. iw.components.push_back(Component(Component::SPELL,spell,0,0));
  5418. }
  5419. cb->showInfoDialog(&iw);
  5420. }
  5421. void CGShrine::initObj()
  5422. {
  5423. if(spell == SpellID::NONE) //spell not set
  5424. {
  5425. int level = ID-87;
  5426. std::vector<SpellID> possibilities;
  5427. cb->getAllowedSpells (possibilities, level);
  5428. if(possibilities.empty())
  5429. {
  5430. logGlobal->errorStream() << "Error: cannot init shrine, no allowed spells!";
  5431. return;
  5432. }
  5433. spell = *RandomGeneratorUtil::nextItem(possibilities, cb->gameState()->getRandomGenerator());
  5434. }
  5435. }
  5436. const std::string & CGShrine::getHoverText() const
  5437. {
  5438. hoverName = VLC->generaltexth->names[ID];
  5439. if(wasVisited(cb->getCurrentPlayer())) //TODO: use local player, not current
  5440. {
  5441. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  5442. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->name);
  5443. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  5444. if(h && vstd::contains(h->spells,spell)) //hero knows that ability
  5445. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  5446. }
  5447. return hoverName;
  5448. }
  5449. void CGSignBottle::initObj()
  5450. {
  5451. //if no text is set than we pick random from the predefined ones
  5452. if(message.empty())
  5453. {
  5454. message = *RandomGeneratorUtil::nextItem(VLC->generaltexth->randsign, cb->gameState()->getRandomGenerator());
  5455. }
  5456. if(ID == Obj::OCEAN_BOTTLE)
  5457. {
  5458. blockVisit = true;
  5459. }
  5460. }
  5461. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  5462. {
  5463. InfoWindow iw;
  5464. iw.soundID = soundBase::STORE;
  5465. iw.player = h->getOwner();
  5466. iw.text << message;
  5467. cb->showInfoDialog(&iw);
  5468. if(ID == Obj::OCEAN_BOTTLE)
  5469. cb->removeObject(this);
  5470. }
  5471. //TODO: remove
  5472. //void CGScholar::giveAnyBonus( const CGHeroInstance * h ) const
  5473. //{
  5474. //
  5475. //}
  5476. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  5477. {
  5478. EBonusType type = bonusType;
  5479. int bid = bonusID;
  5480. //check if the bonus if applicable, if not - give primary skill (always possible)
  5481. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  5482. if((type == SECONDARY_SKILL
  5483. && ((ssl == 3) || (!ssl && !h->canLearnSkill()))) ////hero already has expert level in the skill or (don't know skill and doesn't have free slot)
  5484. || (type == SPELL && (!h->getArt(ArtifactPosition::SPELLBOOK) || vstd::contains(h->spells, (ui32) bid)
  5485. || ( SpellID(bid).toSpell()->level > h->getSecSkillLevel(SecondarySkill::WISDOM) + 2)
  5486. ))) //hero doesn't have a spellbook or already knows the spell or doesn't have Wisdom
  5487. {
  5488. type = PRIM_SKILL;
  5489. bid = cb->gameState()->getRandomGenerator().nextInt(GameConstants::PRIMARY_SKILLS - 1);
  5490. }
  5491. InfoWindow iw;
  5492. iw.soundID = soundBase::gazebo;
  5493. iw.player = h->getOwner();
  5494. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  5495. switch (type)
  5496. {
  5497. case PRIM_SKILL:
  5498. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  5499. iw.components.push_back(Component(Component::PRIM_SKILL,bid,+1,0));
  5500. break;
  5501. case SECONDARY_SKILL:
  5502. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  5503. iw.components.push_back(Component(Component::SEC_SKILL,bid,ssl+1,0));
  5504. break;
  5505. case SPELL:
  5506. {
  5507. std::set<SpellID> hlp;
  5508. hlp.insert(SpellID(bid));
  5509. cb->changeSpells(h,true,hlp);
  5510. iw.components.push_back(Component(Component::SPELL,bid,0,0));
  5511. }
  5512. break;
  5513. default:
  5514. logGlobal->errorStream() << "Error: wrong bonus type (" << (int)type << ") for Scholar!\n";
  5515. return;
  5516. }
  5517. cb->showInfoDialog(&iw);
  5518. cb->removeObject(this);
  5519. }
  5520. void CGScholar::initObj()
  5521. {
  5522. blockVisit = true;
  5523. if(bonusType == RANDOM)
  5524. {
  5525. bonusType = static_cast<EBonusType>(cb->gameState()->getRandomGenerator().nextInt(2));
  5526. switch(bonusType)
  5527. {
  5528. case PRIM_SKILL:
  5529. bonusID = cb->gameState()->getRandomGenerator().nextInt(GameConstants::PRIMARY_SKILLS -1);
  5530. break;
  5531. case SECONDARY_SKILL:
  5532. bonusID = cb->gameState()->getRandomGenerator().nextInt(GameConstants::SKILL_QUANTITY -1);
  5533. break;
  5534. case SPELL:
  5535. std::vector<SpellID> possibilities;
  5536. for (int i = 1; i < 6; ++i)
  5537. cb->getAllowedSpells (possibilities, i);
  5538. bonusID = *RandomGeneratorUtil::nextItem(possibilities, cb->gameState()->getRandomGenerator());
  5539. break;
  5540. }
  5541. }
  5542. }
  5543. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  5544. {
  5545. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  5546. if (!ally && stacksCount() > 0) {
  5547. //TODO: Find a way to apply magic garrison effects in battle.
  5548. cb->startBattleI(h, this);
  5549. return;
  5550. }
  5551. //New owner.
  5552. if (!ally)
  5553. cb->setOwner(this, h->tempOwner);
  5554. cb->showGarrisonDialog(id, h->id, removableUnits);
  5555. }
  5556. ui8 CGGarrison::getPassableness() const
  5557. {
  5558. if ( !stacksCount() )//empty - anyone can visit
  5559. return GameConstants::ALL_PLAYERS;
  5560. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  5561. return 0;
  5562. ui8 mask = 0;
  5563. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  5564. for(PlayerColor it : ts->players)
  5565. mask |= 1<<it.getNum(); //allies - add to possible visitors
  5566. return mask;
  5567. }
  5568. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5569. {
  5570. if (result.winner == 0)
  5571. onHeroVisit(hero);
  5572. }
  5573. void CGOnceVisitable::onHeroVisit( const CGHeroInstance * h ) const
  5574. {
  5575. int sound = soundBase::sound_todo;
  5576. int txtid;
  5577. switch(ID)
  5578. {
  5579. case Obj::CORPSE:
  5580. txtid = 37;
  5581. sound = soundBase::MYSTERY;
  5582. break;
  5583. case Obj::LEAN_TO:
  5584. sound = soundBase::GENIE;
  5585. txtid = 64;
  5586. break;
  5587. case Obj::WAGON:
  5588. sound = soundBase::GENIE;
  5589. txtid = 154;
  5590. break;
  5591. case Obj::WARRIORS_TOMB:
  5592. {
  5593. //ask if player wants to search the Tomb
  5594. BlockingDialog bd(true, false);
  5595. bd.soundID = soundBase::GRAVEYARD;
  5596. bd.player = h->getOwner();
  5597. bd.text.addTxt(MetaString::ADVOB_TXT,161);
  5598. cb->showBlockingDialog(&bd);
  5599. return;
  5600. }
  5601. default:
  5602. logGlobal->errorStream() << "Error: Unknown object (" << ID <<") treated as CGOnceVisitable!";
  5603. return;
  5604. }
  5605. InfoWindow iw;
  5606. iw.soundID = sound;
  5607. iw.player = h->getOwner();
  5608. if(players.size()) //we have been already visited...
  5609. {
  5610. txtid++;
  5611. if(ID == Obj::WAGON) //wagon has extra text (for finding art) we need to omit
  5612. txtid++;
  5613. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5614. }
  5615. else //first visit - give bonus!
  5616. {
  5617. switch(artOrRes)
  5618. {
  5619. case 0: // first visit but empty
  5620. if (ID == Obj::CORPSE)
  5621. ++txtid;
  5622. else
  5623. txtid+=2;
  5624. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5625. break;
  5626. case 1: //art
  5627. iw.components.push_back(Component(Component::ARTIFACT,bonusType,0,0));
  5628. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[bonusType],ArtifactPosition::FIRST_AVAILABLE);
  5629. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5630. if (ID == Obj::CORPSE)
  5631. {
  5632. iw.text << "%s";
  5633. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5634. }
  5635. break;
  5636. case 2: //res
  5637. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5638. iw.components.push_back (Component(Component::RESOURCE, bonusType, bonusVal, 0));
  5639. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(bonusType), bonusVal);
  5640. break;
  5641. }
  5642. if(ID == Obj::WAGON && artOrRes == 1)
  5643. {
  5644. iw.text.localStrings.back().second++;
  5645. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5646. }
  5647. }
  5648. cb->showInfoDialog(&iw);
  5649. cb->setObjProperty(id, 10, h->getOwner().getNum());
  5650. }
  5651. const std::string & CGOnceVisitable::getHoverText() const
  5652. {
  5653. const bool visited = wasVisited(cb->getCurrentPlayer());
  5654. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  5655. return hoverName;
  5656. }
  5657. void CGOnceVisitable::initObj()
  5658. {
  5659. switch(ID)
  5660. {
  5661. case Obj::CORPSE:
  5662. {
  5663. blockVisit = true;
  5664. int hlp = cb->gameState()->getRandomGenerator().nextInt(99);
  5665. if(hlp < 20)
  5666. {
  5667. artOrRes = 1;
  5668. bonusType = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR);
  5669. }
  5670. else
  5671. {
  5672. artOrRes = 0;
  5673. }
  5674. }
  5675. break;
  5676. case Obj::LEAN_TO:
  5677. {
  5678. artOrRes = 2;
  5679. bonusType = cb->gameState()->getRandomGenerator().nextInt(5); //any basic resource without gold
  5680. bonusVal = cb->gameState()->getRandomGenerator().nextInt(1, 4);
  5681. }
  5682. break;
  5683. case Obj::WARRIORS_TOMB:
  5684. {
  5685. artOrRes = 1;
  5686. int hlp = cb->gameState()->getRandomGenerator().nextInt(99);
  5687. if(hlp < 30)
  5688. bonusType = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_TREASURE);
  5689. else if(hlp < 80)
  5690. bonusType = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_MINOR);
  5691. else if(hlp < 95)
  5692. bonusType = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_MAJOR);
  5693. else
  5694. bonusType = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_RELIC);
  5695. }
  5696. break;
  5697. case Obj::WAGON:
  5698. {
  5699. int hlp = cb->gameState()->getRandomGenerator().nextInt(99);
  5700. if(hlp < 10)
  5701. {
  5702. artOrRes = 0; // nothing... :(
  5703. }
  5704. else if(hlp < 50) //minor or treasure art
  5705. {
  5706. artOrRes = 1;
  5707. bonusType = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), CArtifact::ART_TREASURE | CArtifact::ART_MINOR);
  5708. }
  5709. else //2 - 5 of non-gold resource
  5710. {
  5711. artOrRes = 2;
  5712. bonusType = cb->gameState()->getRandomGenerator().nextInt(5);
  5713. bonusVal = cb->gameState()->getRandomGenerator().nextInt(2, 5);
  5714. }
  5715. }
  5716. break;
  5717. }
  5718. }
  5719. void CGOnceVisitable::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5720. {
  5721. //must have been Tomb
  5722. if(answer)
  5723. {
  5724. InfoWindow iw;
  5725. iw.player = hero->getOwner();
  5726. iw.components.push_back(Component(Component::MORALE,0,-3,0));
  5727. if(players.size()) //we've been already visited, player found nothing
  5728. {
  5729. iw.text.addTxt(MetaString::ADVOB_TXT,163);
  5730. }
  5731. else //first visit - give artifact
  5732. {
  5733. iw.text.addTxt(MetaString::ADVOB_TXT,162);
  5734. iw.components.push_back(Component(Component::ARTIFACT,bonusType,0,0));
  5735. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5736. cb->giveHeroNewArtifact(hero, VLC->arth->artifacts[bonusType],ArtifactPosition::FIRST_AVAILABLE);
  5737. }
  5738. if(!hero->hasBonusFrom(Bonus::OBJECT,ID)) //we don't have modifier from this object yet
  5739. {
  5740. //ruin morale
  5741. GiveBonus gb;
  5742. gb.id = hero->id.getNum();
  5743. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,-3,id.getNum(),"");
  5744. gb.bdescr.addTxt(MetaString::ARRAY_TXT,104); //Warrior Tomb Visited -3
  5745. cb->giveHeroBonus(&gb);
  5746. }
  5747. cb->showInfoDialog(&iw);
  5748. cb->setObjProperty(id, 10, hero->getOwner().getNum());
  5749. }
  5750. }
  5751. void CBank::initObj()
  5752. {
  5753. index = VLC->objh->bankObjToIndex(this);
  5754. bc = nullptr;
  5755. daycounter = 0;
  5756. multiplier = 1;
  5757. }
  5758. const std::string & CBank::getHoverText() const
  5759. {
  5760. bool visited = (bc == nullptr);
  5761. hoverName = VLC->objh->creBanksNames[index] + " " + visitedTxt(visited);
  5762. return hoverName;
  5763. }
  5764. void CBank::reset(ui16 var1) //prevents desync
  5765. {
  5766. ui8 chance = 0;
  5767. for (auto & elem : VLC->objh->banksInfo[index])
  5768. {
  5769. if (var1 < (chance += elem->chance))
  5770. {
  5771. bc = elem;
  5772. break;
  5773. }
  5774. }
  5775. artifacts.clear();
  5776. }
  5777. void CBank::initialize() const
  5778. {
  5779. cb->setObjProperty(id, ObjProperty::BANK_RESET, cb->gameState()->getRandomGenerator().nextInt()); //synchronous reset
  5780. for (ui8 i = 0; i <= 3; i++)
  5781. {
  5782. for (ui8 n = 0; n < bc->artifacts[i]; n++)
  5783. {
  5784. CArtifact::EartClass artClass;
  5785. switch(i)
  5786. {
  5787. case 0: artClass = CArtifact::ART_TREASURE; break;
  5788. case 1: artClass = CArtifact::ART_MINOR; break;
  5789. case 2: artClass = CArtifact::ART_MAJOR; break;
  5790. case 3: artClass = CArtifact::ART_RELIC; break;
  5791. default: assert(0); continue;
  5792. }
  5793. int artID = VLC->arth->pickRandomArtifact(cb->gameState()->getRandomGenerator(), artClass);
  5794. cb->setObjProperty(id, ObjProperty::BANK_ADD_ARTIFACT, artID);
  5795. }
  5796. }
  5797. cb->setObjProperty(id, ObjProperty::BANK_INIT_ARMY, cb->gameState()->getRandomGenerator().nextInt()); //get army
  5798. }
  5799. void CBank::setPropertyDer (ui8 what, ui32 val)
  5800. /// random values are passed as arguments and processed identically on all clients
  5801. {
  5802. switch (what)
  5803. {
  5804. case ObjProperty::BANK_DAYCOUNTER: //daycounter
  5805. if (val == 0)
  5806. daycounter = 1; //yes, 1
  5807. else
  5808. daycounter++;
  5809. break;
  5810. case ObjProperty::BANK_MULTIPLIER: //multiplier, in percent
  5811. multiplier = val / 100.0;
  5812. break;
  5813. case 13: //bank preset
  5814. bc = VLC->objh->banksInfo[index][val];
  5815. break;
  5816. case ObjProperty::BANK_RESET:
  5817. reset (val%100);
  5818. break;
  5819. case ObjProperty::BANK_CLEAR_CONFIG:
  5820. bc = nullptr;
  5821. break;
  5822. case ObjProperty::BANK_CLEAR_ARTIFACTS: //remove rewards from Derelict Ship
  5823. artifacts.clear();
  5824. break;
  5825. case ObjProperty::BANK_INIT_ARMY: //set ArmedInstance army
  5826. {
  5827. int upgraded = 0;
  5828. if (val%100 < bc->upgradeChance) //once again anti-desync
  5829. upgraded = 1;
  5830. switch (bc->guards.size())
  5831. {
  5832. case 1:
  5833. for (int i = 0; i < 4; ++i)
  5834. setCreature (SlotID(i), bc->guards[0].first, bc->guards[0].second / 5 );
  5835. setCreature (SlotID(4), CreatureID(bc->guards[0].first + upgraded), bc->guards[0].second / 5 );
  5836. break;
  5837. case 4:
  5838. {
  5839. if (bc->guards.back().second) //all stacks are present
  5840. {
  5841. for (auto & elem : bc->guards)
  5842. {
  5843. setCreature (SlotID(stacksCount()), elem.first, elem.second);
  5844. }
  5845. }
  5846. else if (bc->guards[2].second)//Wraiths are present, split two stacks in Crypt
  5847. {
  5848. setCreature (SlotID(0), bc->guards[0].first, bc->guards[0].second / 2 );
  5849. setCreature (SlotID(1), bc->guards[1].first, bc->guards[1].second / 2);
  5850. setCreature (SlotID(2), CreatureID(bc->guards[2].first + upgraded), bc->guards[2].second);
  5851. setCreature (SlotID(3), bc->guards[1].first, bc->guards[1].second / 2 );
  5852. setCreature (SlotID(4), bc->guards[0].first, bc->guards[0].second - (bc->guards[0].second / 2) );
  5853. }
  5854. else //split both stacks
  5855. {
  5856. for (int i = 0; i < 3; ++i) //skellies
  5857. setCreature (SlotID(2*i), bc->guards[0].first, bc->guards[0].second / 3);
  5858. for (int i = 0; i < 2; ++i) //zombies
  5859. setCreature (SlotID(2*i+1), bc->guards[1].first, bc->guards[1].second / 2);
  5860. }
  5861. }
  5862. break;
  5863. default:
  5864. logGlobal->warnStream() << "Error: Unexpected army data: " << bc->guards.size() <<" items found";
  5865. return;
  5866. }
  5867. }
  5868. break;
  5869. case ObjProperty::BANK_ADD_ARTIFACT: //add Artifact
  5870. {
  5871. artifacts.push_back (val);
  5872. break;
  5873. }
  5874. }
  5875. }
  5876. void CBank::newTurn() const
  5877. {
  5878. if (bc == nullptr)
  5879. {
  5880. if (cb->getDate() == 1)
  5881. initialize(); //initialize on first day
  5882. else if (daycounter >= 28 && (subID < 13 || subID > 16)) //no reset for Emissaries
  5883. {
  5884. initialize();
  5885. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 0); //daycounter 0
  5886. if (ID == Obj::DERELICT_SHIP && cb->getDate() > 1)
  5887. {
  5888. cb->setObjProperty (id, ObjProperty::BANK_MULTIPLIER, 0);//ugly hack to make derelict ships usable only once
  5889. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_ARTIFACTS, 0);
  5890. }
  5891. }
  5892. else
  5893. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 1); //daycounter++
  5894. }
  5895. }
  5896. bool CBank::wasVisited (PlayerColor player) const
  5897. {
  5898. return !bc;
  5899. }
  5900. void CBank::onHeroVisit (const CGHeroInstance * h) const
  5901. {
  5902. if (bc)
  5903. {
  5904. int banktext = 0;
  5905. switch (ID)
  5906. {
  5907. case Obj::CREATURE_BANK:
  5908. banktext = 32;
  5909. break;
  5910. case Obj::DERELICT_SHIP:
  5911. banktext = 41;
  5912. break;
  5913. case Obj::DRAGON_UTOPIA:
  5914. banktext = 47;
  5915. break;
  5916. case Obj::CRYPT:
  5917. banktext = 119;
  5918. break;
  5919. case Obj::SHIPWRECK:
  5920. banktext = 122;
  5921. break;
  5922. }
  5923. BlockingDialog bd (true, false);
  5924. bd.player = h->getOwner();
  5925. bd.soundID = soundBase::ROGUE;
  5926. bd.text.addTxt(MetaString::ADVOB_TXT,banktext);
  5927. if (ID == Obj::CREATURE_BANK)
  5928. bd.text.addReplacement(VLC->objh->creBanksNames[index]);
  5929. cb->showBlockingDialog (&bd);
  5930. }
  5931. else
  5932. {
  5933. InfoWindow iw;
  5934. iw.soundID = soundBase::GRAVEYARD;
  5935. iw.player = h->getOwner();
  5936. if (ID == Obj::CRYPT) //morale penalty for empty Crypt
  5937. {
  5938. GiveBonus gbonus;
  5939. gbonus.id = h->id.getNum();
  5940. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5941. gbonus.bonus.source = Bonus::OBJECT;
  5942. gbonus.bonus.sid = ID;
  5943. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[98];
  5944. gbonus.bonus.type = Bonus::MORALE;
  5945. gbonus.bonus.val = -1;
  5946. cb->giveHeroBonus(&gbonus);
  5947. iw.text << VLC->generaltexth->advobtxt[120];
  5948. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5949. }
  5950. else
  5951. {
  5952. iw.text << VLC->generaltexth->advobtxt[33];
  5953. iw.text.addReplacement(VLC->objh->creBanksNames[index]);
  5954. }
  5955. cb->showInfoDialog(&iw);
  5956. }
  5957. }
  5958. void CBank::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5959. {
  5960. if (result.winner == 0)
  5961. {
  5962. int textID = -1;
  5963. InfoWindow iw;
  5964. iw.player = hero->getOwner();
  5965. MetaString loot;
  5966. switch (ID)
  5967. {
  5968. case Obj::CREATURE_BANK: case Obj::DRAGON_UTOPIA:
  5969. textID = 34;
  5970. break;
  5971. case Obj::DERELICT_SHIP:
  5972. if (multiplier)
  5973. textID = 43;
  5974. else
  5975. {
  5976. GiveBonus gbonus;
  5977. gbonus.id = hero->id.getNum();
  5978. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5979. gbonus.bonus.source = Bonus::OBJECT;
  5980. gbonus.bonus.sid = ID;
  5981. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[101];
  5982. gbonus.bonus.type = Bonus::MORALE;
  5983. gbonus.bonus.val = -1;
  5984. cb->giveHeroBonus(&gbonus);
  5985. textID = 42;
  5986. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5987. }
  5988. break;
  5989. case Obj::CRYPT:
  5990. if (bc->resources.size() != 0)
  5991. textID = 121;
  5992. else
  5993. {
  5994. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5995. GiveBonus gbonus;
  5996. gbonus.id = hero->id.getNum();
  5997. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5998. gbonus.bonus.source = Bonus::OBJECT;
  5999. gbonus.bonus.sid = ID;
  6000. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[ID];
  6001. gbonus.bonus.type = Bonus::MORALE;
  6002. gbonus.bonus.val = -1;
  6003. cb->giveHeroBonus(&gbonus);
  6004. textID = 120;
  6005. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  6006. }
  6007. break;
  6008. case Obj::SHIPWRECK:
  6009. if (bc->resources.size())
  6010. textID = 124;
  6011. else
  6012. textID = 123;
  6013. break;
  6014. }
  6015. //grant resources
  6016. if (textID != 42) //empty derelict ship gives no cash
  6017. {
  6018. for (int it = 0; it < bc->resources.size(); it++)
  6019. {
  6020. if (bc->resources[it] != 0)
  6021. {
  6022. iw.components.push_back (Component (Component::RESOURCE, it, bc->resources[it], 0));
  6023. loot << "%d %s";
  6024. loot.addReplacement(iw.components.back().val);
  6025. loot.addReplacement(MetaString::RES_NAMES, iw.components.back().subtype);
  6026. cb->giveResource (hero->getOwner(), static_cast<Res::ERes>(it), bc->resources[it]);
  6027. }
  6028. }
  6029. }
  6030. //grant artifacts
  6031. for (auto & elem : artifacts)
  6032. {
  6033. iw.components.push_back (Component (Component::ARTIFACT, elem, 0, 0));
  6034. loot << "%s";
  6035. loot.addReplacement(MetaString::ART_NAMES, elem);
  6036. cb->giveHeroNewArtifact (hero, VLC->arth->artifacts[elem], ArtifactPosition::FIRST_AVAILABLE);
  6037. }
  6038. //display loot
  6039. if (!iw.components.empty())
  6040. {
  6041. iw.text.addTxt (MetaString::ADVOB_TXT, textID);
  6042. if (textID == 34)
  6043. {
  6044. iw.text.addReplacement(MetaString::CRE_PL_NAMES, result.casualties[1].begin()->first);
  6045. iw.text.addReplacement(loot.buildList());
  6046. }
  6047. cb->showInfoDialog(&iw);
  6048. }
  6049. loot.clear();
  6050. iw.components.clear();
  6051. iw.text.clear();
  6052. //grant creatures
  6053. CCreatureSet ourArmy;
  6054. for (auto it = bc->creatures.cbegin(); it != bc->creatures.cend(); it++)
  6055. {
  6056. SlotID slot = ourArmy.getSlotFor(it->first);
  6057. ourArmy.addToSlot(slot, it->first, it->second);
  6058. }
  6059. for (auto & elem : ourArmy.Slots())
  6060. {
  6061. iw.components.push_back(Component(*elem.second));
  6062. loot << "%s";
  6063. loot.addReplacement(*elem.second);
  6064. }
  6065. if (ourArmy.Slots().size())
  6066. {
  6067. if (ourArmy.Slots().size() == 1 && ourArmy.Slots().begin()->second->count == 1)
  6068. iw.text.addTxt (MetaString::ADVOB_TXT, 185);
  6069. else
  6070. iw.text.addTxt (MetaString::ADVOB_TXT, 186);
  6071. iw.text.addReplacement(loot.buildList());
  6072. iw.text.addReplacement(hero->name);
  6073. cb->showInfoDialog(&iw);
  6074. cb->giveCreatures(this, hero, ourArmy, false);
  6075. }
  6076. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0); //bc = nullptr
  6077. }
  6078. }
  6079. void CBank::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  6080. {
  6081. if (answer)
  6082. {
  6083. cb->startBattleI(hero, this, true);
  6084. }
  6085. }
  6086. void CGPyramid::initObj()
  6087. {
  6088. std::vector<SpellID> available;
  6089. cb->getAllowedSpells (available, 5);
  6090. if (available.size())
  6091. {
  6092. bc = VLC->objh->banksInfo[21].front(); //TODO: remove hardcoded value?
  6093. spell = *RandomGeneratorUtil::nextItem(available, cb->gameState()->getRandomGenerator());
  6094. }
  6095. else
  6096. {
  6097. logGlobal->errorStream() <<"No spells available for Pyramid! Object set to empty.";
  6098. }
  6099. setPropertyDer(ObjProperty::BANK_INIT_ARMY, cb->gameState()->getRandomGenerator().nextInt()); //set guards at game start
  6100. }
  6101. const std::string & CGPyramid::getHoverText() const
  6102. {
  6103. hoverName = VLC->objh->creBanksNames[21]+ " " + visitedTxt((bc==nullptr));
  6104. return hoverName;
  6105. }
  6106. void CGPyramid::onHeroVisit (const CGHeroInstance * h) const
  6107. {
  6108. if (bc)
  6109. {
  6110. BlockingDialog bd (true, false);
  6111. bd.player = h->getOwner();
  6112. bd.soundID = soundBase::MYSTERY;
  6113. bd.text << VLC->generaltexth->advobtxt[105];
  6114. cb->showBlockingDialog(&bd);
  6115. }
  6116. else
  6117. {
  6118. InfoWindow iw;
  6119. iw.player = h->getOwner();
  6120. iw.text << VLC->generaltexth->advobtxt[107];
  6121. iw.components.push_back (Component (Component::LUCK, 0 , -2, 0));
  6122. GiveBonus gb;
  6123. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,-2,id.getNum(),VLC->generaltexth->arraytxt[70]);
  6124. gb.id = h->id.getNum();
  6125. cb->giveHeroBonus(&gb);
  6126. cb->showInfoDialog(&iw);
  6127. }
  6128. }
  6129. void CGPyramid::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  6130. {
  6131. if (result.winner == 0)
  6132. {
  6133. InfoWindow iw;
  6134. iw.player = hero->getOwner();
  6135. iw.text.addTxt (MetaString::ADVOB_TXT, 106);
  6136. iw.text.addTxt (MetaString::SPELL_NAME, spell);
  6137. if (!hero->getArt(ArtifactPosition::SPELLBOOK))
  6138. iw.text.addTxt (MetaString::ADVOB_TXT, 109); //no spellbook
  6139. else if (hero->getSecSkillLevel(SecondarySkill::WISDOM) < 3)
  6140. iw.text.addTxt (MetaString::ADVOB_TXT, 108); //no expert Wisdom
  6141. else
  6142. {
  6143. std::set<SpellID> spells;
  6144. spells.insert (SpellID(spell));
  6145. cb->changeSpells (hero, true, spells);
  6146. iw.components.push_back(Component (Component::SPELL, spell, 0, 0));
  6147. }
  6148. cb->showInfoDialog(&iw);
  6149. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0);
  6150. }
  6151. }
  6152. void CGKeys::setPropertyDer (ui8 what, ui32 val) //101-108 - enable key for player 1-8
  6153. {
  6154. if (what >= 101 && what <= (100 + PlayerColor::PLAYER_LIMIT_I))
  6155. {
  6156. PlayerColor player(what-101);
  6157. playerKeyMap[player].insert((ui8)val);
  6158. }
  6159. else
  6160. logGlobal->errorStream() << boost::format("Unexpected properties requested to set: what=%d, val=%d") % (int)what % val;
  6161. }
  6162. bool CGKeys::wasMyColorVisited (PlayerColor player) const
  6163. {
  6164. if (vstd::contains(playerKeyMap[player], subID)) //creates set if it's not there
  6165. return true;
  6166. else
  6167. return false;
  6168. }
  6169. const std::string& CGKeys::getHoverText() const
  6170. {
  6171. bool visited = wasMyColorVisited (cb->getLocalPlayer());
  6172. hoverName = getName() + "\n" + visitedTxt(visited);
  6173. return hoverName;
  6174. }
  6175. const std::string CGKeys::getName() const
  6176. {
  6177. std::string name;
  6178. name = VLC->generaltexth->tentColors[subID] + " " + VLC->generaltexth->names[ID];
  6179. return name;
  6180. }
  6181. bool CGKeymasterTent::wasVisited (PlayerColor player) const
  6182. {
  6183. return wasMyColorVisited (player);
  6184. }
  6185. void CGKeymasterTent::onHeroVisit( const CGHeroInstance * h ) const
  6186. {
  6187. int txt_id;
  6188. if (!wasMyColorVisited (h->getOwner()) )
  6189. {
  6190. cb->setObjProperty(id, h->tempOwner.getNum()+101, subID);
  6191. txt_id=19;
  6192. }
  6193. else
  6194. txt_id=20;
  6195. showInfoDialog(h,txt_id,soundBase::CAVEHEAD);
  6196. }
  6197. void CGBorderGuard::initObj()
  6198. {
  6199. //ui32 m13489val = subID; //store color as quest info
  6200. blockVisit = true;
  6201. }
  6202. void CGBorderGuard::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  6203. {
  6204. text << std::pair<ui8,ui32>(11,18);
  6205. }
  6206. void CGBorderGuard::getRolloverText (MetaString &text, bool onHover) const
  6207. {
  6208. if (!onHover)
  6209. text << VLC->generaltexth->tentColors[subID] << " " << VLC->generaltexth->names[Obj::KEYMASTER];
  6210. }
  6211. bool CGBorderGuard::checkQuest (const CGHeroInstance * h) const
  6212. {
  6213. return wasMyColorVisited (h->tempOwner);
  6214. }
  6215. void CGBorderGuard::onHeroVisit( const CGHeroInstance * h ) const
  6216. {
  6217. if (wasMyColorVisited (h->getOwner()) )
  6218. {
  6219. BlockingDialog bd (true, false);
  6220. bd.player = h->getOwner();
  6221. bd.soundID = soundBase::QUEST;
  6222. bd.text.addTxt (MetaString::ADVOB_TXT, 17);
  6223. cb->showBlockingDialog (&bd);
  6224. }
  6225. else
  6226. {
  6227. showInfoDialog(h,18,soundBase::CAVEHEAD);
  6228. AddQuest aq;
  6229. aq.quest = QuestInfo (quest, this, visitablePos());
  6230. aq.player = h->tempOwner;
  6231. cb->sendAndApply (&aq);
  6232. //TODO: add this quest only once OR check for multiple instances later
  6233. }
  6234. }
  6235. void CGBorderGuard::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  6236. {
  6237. if (answer)
  6238. cb->removeObject(this);
  6239. }
  6240. void CGBorderGate::onHeroVisit( const CGHeroInstance * h ) const //TODO: passability
  6241. {
  6242. if (!wasMyColorVisited (h->getOwner()) )
  6243. {
  6244. showInfoDialog(h,18,0);
  6245. AddQuest aq;
  6246. aq.quest = QuestInfo (quest, this, visitablePos());
  6247. aq.player = h->tempOwner;
  6248. cb->sendAndApply (&aq);
  6249. }
  6250. }
  6251. ui8 CGBorderGate::getPassableness() const
  6252. {
  6253. ui8 ret = 0;
  6254. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  6255. ret |= wasMyColorVisited(PlayerColor(i))<<i;
  6256. return ret;
  6257. }
  6258. void CGMagi::initObj()
  6259. {
  6260. if (ID == Obj::EYE_OF_MAGI)
  6261. {
  6262. blockVisit = true;
  6263. eyelist[subID].push_back(id);
  6264. }
  6265. }
  6266. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  6267. {
  6268. if (ID == Obj::HUT_OF_MAGI)
  6269. {
  6270. showInfoDialog(h, 61, soundBase::LIGHTHOUSE);
  6271. if (!eyelist[subID].empty())
  6272. {
  6273. CenterView cv;
  6274. cv.player = h->tempOwner;
  6275. cv.focusTime = 2000;
  6276. FoWChange fw;
  6277. fw.player = h->tempOwner;
  6278. fw.mode = 1;
  6279. for(auto it : eyelist[subID])
  6280. {
  6281. const CGObjectInstance *eye = cb->getObj(it);
  6282. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  6283. cb->sendAndApply(&fw);
  6284. cv.pos = eye->pos;
  6285. cb->sendAndApply(&cv);
  6286. }
  6287. cv.pos = h->getPosition(false);
  6288. cb->sendAndApply(&cv);
  6289. }
  6290. }
  6291. else if (ID == Obj::EYE_OF_MAGI)
  6292. {
  6293. showInfoDialog(h,48,soundBase::invalid);
  6294. }
  6295. }
  6296. void CGBoat::initObj()
  6297. {
  6298. hero = nullptr;
  6299. }
  6300. void CGSirens::initObj()
  6301. {
  6302. blockVisit = true;
  6303. }
  6304. const std::string & CGSirens::getHoverText() const
  6305. {
  6306. getNameVis(hoverName);
  6307. return hoverName;
  6308. }
  6309. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  6310. {
  6311. InfoWindow iw;
  6312. iw.soundID = soundBase::DANGER;
  6313. iw.player = h->tempOwner;
  6314. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  6315. {
  6316. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  6317. }
  6318. else
  6319. {
  6320. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  6321. TExpType xp = 0;
  6322. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  6323. {
  6324. TQuantity drown = i->second->count * 0.3;
  6325. if(drown)
  6326. {
  6327. cb->changeStackCount(StackLocation(h, i->first), -drown);
  6328. xp += drown * i->second->type->valOfBonuses(Bonus::STACK_HEALTH);
  6329. }
  6330. }
  6331. if(xp)
  6332. {
  6333. xp = h->calculateXp(xp);
  6334. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  6335. iw.text.addReplacement(xp);
  6336. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  6337. }
  6338. else
  6339. {
  6340. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  6341. }
  6342. }
  6343. cb->showInfoDialog(&iw);
  6344. }
  6345. //bool IShipyard::validLocation() const
  6346. //{
  6347. // std::vector<int3> offsets;
  6348. // getOutOffsets(offsets);
  6349. //
  6350. // TerrainTile *tile;
  6351. // for(int i = 0; i < offsets.size(); i++)
  6352. // if((tile = IObjectInterface::cb->getTile(o->pos + offsets[i])) && tile->terType == TerrainTile::water) //tile is in the map and is water
  6353. // return true;
  6354. // return false;
  6355. //}
  6356. int3 IBoatGenerator::bestLocation() const
  6357. {
  6358. std::vector<int3> offsets;
  6359. getOutOffsets(offsets);
  6360. for (auto & offset : offsets)
  6361. {
  6362. if (const TerrainTile *tile = IObjectInterface::cb->getTile(o->pos + offset, false)) //tile is in the map
  6363. {
  6364. if (tile->terType == ETerrainType::WATER && (!tile->blocked || tile->blockingObjects.front()->ID == 8)) //and is water and is not blocked or is blocked by boat
  6365. return o->pos + offset;
  6366. }
  6367. }
  6368. return int3 (-1,-1,-1);
  6369. }
  6370. IBoatGenerator::EGeneratorState IBoatGenerator::shipyardStatus() const
  6371. {
  6372. int3 tile = bestLocation();
  6373. const TerrainTile *t = IObjectInterface::cb->getTile(tile);
  6374. if(!t)
  6375. return TILE_BLOCKED; //no available water
  6376. else if(!t->blockingObjects.size())
  6377. return GOOD; //OK
  6378. else if(t->blockingObjects.front()->ID == Obj::BOAT)
  6379. return BOAT_ALREADY_BUILT; //blocked with boat
  6380. else
  6381. return TILE_BLOCKED; //blocked
  6382. }
  6383. int IBoatGenerator::getBoatType() const
  6384. {
  6385. //We make good ships by default
  6386. return 1;
  6387. }
  6388. IBoatGenerator::IBoatGenerator(const CGObjectInstance *O)
  6389. : o(O)
  6390. {
  6391. }
  6392. void IBoatGenerator::getProblemText(MetaString &out, const CGHeroInstance *visitor) const
  6393. {
  6394. switch(shipyardStatus())
  6395. {
  6396. case BOAT_ALREADY_BUILT:
  6397. out.addTxt(MetaString::GENERAL_TXT, 51);
  6398. break;
  6399. case TILE_BLOCKED:
  6400. if(visitor)
  6401. {
  6402. out.addTxt(MetaString::GENERAL_TXT, 134);
  6403. out.addReplacement(visitor->name);
  6404. }
  6405. else
  6406. out.addTxt(MetaString::ADVOB_TXT, 189);
  6407. break;
  6408. case NO_WATER:
  6409. logGlobal->errorStream() << "Shipyard without water!!! " << o->pos << "\t" << o->id;
  6410. return;
  6411. }
  6412. }
  6413. void IShipyard::getBoatCost( std::vector<si32> &cost ) const
  6414. {
  6415. cost.resize(GameConstants::RESOURCE_QUANTITY);
  6416. cost[Res::WOOD] = 10;
  6417. cost[Res::GOLD] = 1000;
  6418. }
  6419. IShipyard::IShipyard(const CGObjectInstance *O)
  6420. : IBoatGenerator(O)
  6421. {
  6422. }
  6423. IShipyard * IShipyard::castFrom( CGObjectInstance *obj )
  6424. {
  6425. if(!obj)
  6426. return nullptr;
  6427. if(obj->ID == Obj::TOWN)
  6428. {
  6429. return static_cast<CGTownInstance*>(obj);
  6430. }
  6431. else if(obj->ID == Obj::SHIPYARD)
  6432. {
  6433. return static_cast<CGShipyard*>(obj);
  6434. }
  6435. else
  6436. {
  6437. return nullptr;
  6438. }
  6439. }
  6440. const IShipyard * IShipyard::castFrom( const CGObjectInstance *obj )
  6441. {
  6442. return castFrom(const_cast<CGObjectInstance*>(obj));
  6443. }
  6444. CGShipyard::CGShipyard()
  6445. :IShipyard(this)
  6446. {
  6447. }
  6448. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  6449. {
  6450. // H J L K I
  6451. // A x S x B
  6452. // C E G F D
  6453. offsets += int3(-3,0,0), int3(1,0,0), //AB
  6454. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  6455. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0); //HIJKL
  6456. }
  6457. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  6458. {
  6459. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  6460. cb->setOwner(this, h->tempOwner);
  6461. auto s = shipyardStatus();
  6462. if(s != IBoatGenerator::GOOD)
  6463. {
  6464. InfoWindow iw;
  6465. iw.player = tempOwner;
  6466. getProblemText(iw.text, h);
  6467. cb->showInfoDialog(&iw);
  6468. }
  6469. else
  6470. {
  6471. openWindow(OpenWindow::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  6472. }
  6473. }
  6474. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  6475. {
  6476. if (!wasVisited (h->getOwner()) ) //if hero has not visited yet this cartographer
  6477. {
  6478. if (cb->getResource(h->tempOwner, Res::GOLD) >= 1000) //if he can afford a map
  6479. {
  6480. //ask if he wants to buy one
  6481. int text=0;
  6482. switch (subID)
  6483. {
  6484. case 0:
  6485. text = 25;
  6486. break;
  6487. case 1:
  6488. text = 26;
  6489. break;
  6490. case 2:
  6491. text = 27;
  6492. break;
  6493. default:
  6494. logGlobal->warnStream() << "Unrecognized subtype of cartographer";
  6495. }
  6496. assert(text);
  6497. BlockingDialog bd (true, false);
  6498. bd.player = h->getOwner();
  6499. bd.soundID = soundBase::LIGHTHOUSE;
  6500. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  6501. cb->showBlockingDialog (&bd);
  6502. }
  6503. else //if he cannot afford
  6504. {
  6505. showInfoDialog(h,28,soundBase::CAVEHEAD);
  6506. }
  6507. }
  6508. else //if he already visited carographer
  6509. {
  6510. showInfoDialog(h,24,soundBase::CAVEHEAD);
  6511. }
  6512. }
  6513. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  6514. {
  6515. if (answer) //if hero wants to buy map
  6516. {
  6517. cb->giveResource (hero->tempOwner, Res::GOLD, -1000);
  6518. FoWChange fw;
  6519. fw.mode = 1;
  6520. fw.player = hero->tempOwner;
  6521. //subIDs of different types of cartographers:
  6522. //water = 0; land = 1; underground = 2;
  6523. cb->getAllTiles (fw.tiles, hero->tempOwner, subID - 1, !subID + 1); //reveal appropriate tiles
  6524. cb->sendAndApply (&fw);
  6525. cb->setObjProperty (id, 10, hero->tempOwner.getNum());
  6526. }
  6527. }
  6528. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  6529. {
  6530. cb->showThievesGuildWindow(h->tempOwner, id);
  6531. }
  6532. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  6533. {
  6534. InfoWindow iw;
  6535. iw.player = h->tempOwner;
  6536. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  6537. assert(ts);
  6538. TeamID team = ts->id;
  6539. if(!wasVisited(team))
  6540. {
  6541. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  6542. cb->sendAndApply(&iw);
  6543. cb->setObjProperty(id, 20, h->tempOwner.getNum()); //increment general visited obelisks counter
  6544. openWindow(OpenWindow::PUZZLE_MAP, h->tempOwner.getNum());
  6545. cb->setObjProperty(id, 10, h->tempOwner.getNum()); //mark that particular obelisk as visited
  6546. }
  6547. else
  6548. {
  6549. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  6550. cb->sendAndApply(&iw);
  6551. }
  6552. }
  6553. void CGObelisk::initObj()
  6554. {
  6555. obeliskCount++;
  6556. }
  6557. const std::string & CGObelisk::getHoverText() const
  6558. {
  6559. bool visited = wasVisited(cb->getLocalPlayer());
  6560. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  6561. return hoverName;
  6562. }
  6563. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  6564. {
  6565. CPlayersVisited::setPropertyDer(what, val);
  6566. switch(what)
  6567. {
  6568. case 20:
  6569. assert(val < PlayerColor::PLAYER_LIMIT_I);
  6570. visited[TeamID(val)]++;
  6571. if(visited[TeamID(val)] > obeliskCount)
  6572. {
  6573. logGlobal->errorStream() << "Error: Visited " << visited[TeamID(val)] << "\t\t" << obeliskCount;
  6574. assert(0);
  6575. }
  6576. break;
  6577. }
  6578. }
  6579. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  6580. {
  6581. if(h->tempOwner != tempOwner)
  6582. {
  6583. PlayerColor oldOwner = tempOwner;
  6584. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  6585. showInfoDialog(h,69,soundBase::LIGHTHOUSE);
  6586. giveBonusTo(h->tempOwner);
  6587. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  6588. {
  6589. RemoveBonus rb(RemoveBonus::PLAYER);
  6590. rb.whoID = oldOwner.getNum();
  6591. rb.source = Bonus::OBJECT;
  6592. rb.id = id.getNum();
  6593. cb->sendAndApply(&rb);
  6594. }
  6595. }
  6596. }
  6597. void CGLighthouse::initObj()
  6598. {
  6599. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  6600. {
  6601. giveBonusTo(tempOwner);
  6602. }
  6603. }
  6604. const std::string & CGLighthouse::getHoverText() const
  6605. {
  6606. hoverName = VLC->generaltexth->names[ID];
  6607. //TODO: owned by %s player
  6608. return hoverName;
  6609. }
  6610. void CGLighthouse::giveBonusTo( PlayerColor player ) const
  6611. {
  6612. GiveBonus gb(GiveBonus::PLAYER);
  6613. gb.bonus.type = Bonus::SEA_MOVEMENT;
  6614. gb.bonus.val = 500;
  6615. gb.id = player.getNum();
  6616. gb.bonus.duration = Bonus::PERMANENT;
  6617. gb.bonus.source = Bonus::OBJECT;
  6618. gb.bonus.sid = id.getNum();
  6619. cb->sendAndApply(&gb);
  6620. }
  6621. void CArmedInstance::randomizeArmy(int type)
  6622. {
  6623. for (auto & elem : stacks)
  6624. {
  6625. int & randID = elem.second->idRand;
  6626. if(randID >= 0)
  6627. {
  6628. int level = randID / 2;
  6629. bool upgrade = randID % 2;
  6630. elem.second->setType(VLC->townh->factions[type]->town->creatures[level][upgrade]);
  6631. randID = -1;
  6632. }
  6633. assert(elem.second->valid(false));
  6634. assert(elem.second->armyObj == this);
  6635. }
  6636. return;
  6637. }
  6638. CArmedInstance::CArmedInstance()
  6639. {
  6640. battle = nullptr;
  6641. }
  6642. //int CArmedInstance::valOfGlobalBonuses(CSelector selector) const
  6643. //{
  6644. //// if (tempOwner != NEUTRAL_PLAYER)
  6645. // return cb->gameState()->players[tempOwner].valOfBonuses(selector);
  6646. //}
  6647. void CArmedInstance::updateMoraleBonusFromArmy()
  6648. {
  6649. if(!validTypes(false)) //object not randomized, don't bother
  6650. return;
  6651. Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE)));
  6652. if(!b)
  6653. {
  6654. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  6655. addNewBonus(b);
  6656. }
  6657. //number of alignments and presence of undead
  6658. std::set<TFaction> factions;
  6659. bool hasUndead = false;
  6660. for(auto slot : Slots())
  6661. {
  6662. const CStackInstance * inst = slot.second;
  6663. const CCreature * creature = VLC->creh->creatures[inst->getCreatureID()];
  6664. factions.insert(creature->faction);
  6665. // Check for undead flag instead of faction (undead mummies are neutral)
  6666. hasUndead |= inst->hasBonusOfType(Bonus::UNDEAD);
  6667. }
  6668. size_t factionsInArmy = factions.size(); //town garrison seems to take both sets into account
  6669. // Take Angelic Alliance troop-mixing freedom of non-evil units into account.
  6670. if (hasBonusOfType(Bonus::NONEVIL_ALIGNMENT_MIX))
  6671. {
  6672. size_t mixableFactions = 0;
  6673. for(TFaction f : factions)
  6674. {
  6675. if (VLC->townh->factions[f]->alignment != EAlignment::EVIL)
  6676. mixableFactions++;
  6677. }
  6678. if (mixableFactions > 0)
  6679. factionsInArmy -= mixableFactions - 1;
  6680. }
  6681. if(factionsInArmy == 1)
  6682. {
  6683. b->val = +1;
  6684. b->description = VLC->generaltexth->arraytxt[115]; //All troops of one alignment +1
  6685. }
  6686. else if (!factions.empty()) // no bonus from empty garrison
  6687. {
  6688. b->val = 2 - factionsInArmy;
  6689. b->description = boost::str(boost::format(VLC->generaltexth->arraytxt[114]) % factionsInArmy % b->val); //Troops of %d alignments %d
  6690. }
  6691. boost::algorithm::trim(b->description);
  6692. //-1 modifier for any Undead unit in army
  6693. const ui8 UNDEAD_MODIFIER_ID = -2;
  6694. Bonus *undeadModifier = getBonusList().getFirst(Selector::source(Bonus::ARMY, UNDEAD_MODIFIER_ID));
  6695. if(hasUndead)
  6696. {
  6697. if(!undeadModifier)
  6698. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, -1, UNDEAD_MODIFIER_ID, VLC->generaltexth->arraytxt[116]));
  6699. }
  6700. else if(undeadModifier)
  6701. removeBonus(undeadModifier);
  6702. }
  6703. void CArmedInstance::armyChanged()
  6704. {
  6705. updateMoraleBonusFromArmy();
  6706. }
  6707. CBonusSystemNode * CArmedInstance::whereShouldBeAttached(CGameState *gs)
  6708. {
  6709. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  6710. return gs->getPlayer(tempOwner);
  6711. else
  6712. return &gs->globalEffects;
  6713. }
  6714. CBonusSystemNode * CArmedInstance::whatShouldBeAttached()
  6715. {
  6716. return this;
  6717. }
  6718. bool IMarket::getOffer(int id1, int id2, int &val1, int &val2, EMarketMode::EMarketMode mode) const
  6719. {
  6720. switch(mode)
  6721. {
  6722. case EMarketMode::RESOURCE_RESOURCE:
  6723. {
  6724. double effectiveness = std::min((getMarketEfficiency() + 1.0) / 20.0, 0.5);
  6725. double r = VLC->objh->resVals[id1], //value of given resource
  6726. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  6727. if(r>g) //if given resource is more expensive than wanted
  6728. {
  6729. val2 = ceil(r / g);
  6730. val1 = 1;
  6731. }
  6732. else //if wanted resource is more expensive
  6733. {
  6734. val1 = (g / r) + 0.5;
  6735. val2 = 1;
  6736. }
  6737. }
  6738. break;
  6739. case EMarketMode::CREATURE_RESOURCE:
  6740. {
  6741. const double effectivenessArray[] = {0.0, 0.3, 0.45, 0.50, 0.65, 0.7, 0.85, 0.9, 1.0};
  6742. double effectiveness = effectivenessArray[std::min(getMarketEfficiency(), 8)];
  6743. double r = VLC->creh->creatures[id1]->cost[6], //value of given creature in gold
  6744. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  6745. if(r>g) //if given resource is more expensive than wanted
  6746. {
  6747. val2 = ceil(r / g);
  6748. val1 = 1;
  6749. }
  6750. else //if wanted resource is more expensive
  6751. {
  6752. val1 = (g / r) + 0.5;
  6753. val2 = 1;
  6754. }
  6755. }
  6756. break;
  6757. case EMarketMode::RESOURCE_PLAYER:
  6758. val1 = 1;
  6759. val2 = 1;
  6760. break;
  6761. case EMarketMode::RESOURCE_ARTIFACT:
  6762. {
  6763. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  6764. double r = VLC->objh->resVals[id1], //value of offered resource
  6765. g = VLC->arth->artifacts[id2]->price / effectiveness; //value of bought artifact in gold
  6766. if(id1 != 6) //non-gold prices are doubled
  6767. r /= 2;
  6768. val1 = std::max(1, (int)((g / r) + 0.5)); //don't sell arts for less than 1 resource
  6769. val2 = 1;
  6770. }
  6771. break;
  6772. case EMarketMode::ARTIFACT_RESOURCE:
  6773. {
  6774. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  6775. double r = VLC->arth->artifacts[id1]->price * effectiveness,
  6776. g = VLC->objh->resVals[id2];
  6777. // if(id2 != 6) //non-gold prices are doubled
  6778. // r /= 2;
  6779. val1 = 1;
  6780. val2 = std::max(1, (int)((r / g) + 0.5)); //at least one resource is given in return
  6781. }
  6782. break;
  6783. case EMarketMode::CREATURE_EXP:
  6784. {
  6785. val1 = 1;
  6786. val2 = (VLC->creh->creatures[id1]->AIValue / 40) * 5;
  6787. }
  6788. break;
  6789. case EMarketMode::ARTIFACT_EXP:
  6790. {
  6791. val1 = 1;
  6792. int givenClass = VLC->arth->artifacts[id1]->getArtClassSerial();
  6793. if(givenClass < 0 || givenClass > 3)
  6794. {
  6795. val2 = 0;
  6796. return false;
  6797. }
  6798. static const int expPerClass[] = {1000, 1500, 3000, 6000};
  6799. val2 = expPerClass[givenClass];
  6800. }
  6801. break;
  6802. default:
  6803. assert(0);
  6804. return false;
  6805. }
  6806. return true;
  6807. }
  6808. bool IMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  6809. {
  6810. return false;
  6811. }
  6812. int IMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  6813. {
  6814. switch(mode)
  6815. {
  6816. case EMarketMode::RESOURCE_RESOURCE:
  6817. case EMarketMode::ARTIFACT_RESOURCE:
  6818. case EMarketMode::CREATURE_RESOURCE:
  6819. return -1;
  6820. default:
  6821. return 1;
  6822. }
  6823. }
  6824. std::vector<int> IMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6825. {
  6826. std::vector<int> ret;
  6827. switch(mode)
  6828. {
  6829. case EMarketMode::RESOURCE_RESOURCE:
  6830. case EMarketMode::ARTIFACT_RESOURCE:
  6831. case EMarketMode::CREATURE_RESOURCE:
  6832. for (int i = 0; i < 7; i++)
  6833. ret.push_back(i);
  6834. }
  6835. return ret;
  6836. }
  6837. const IMarket * IMarket::castFrom(const CGObjectInstance *obj, bool verbose /*= true*/)
  6838. {
  6839. switch(obj->ID)
  6840. {
  6841. case Obj::TOWN:
  6842. return static_cast<const CGTownInstance*>(obj);
  6843. case Obj::ALTAR_OF_SACRIFICE:
  6844. case Obj::BLACK_MARKET:
  6845. case Obj::TRADING_POST:
  6846. case Obj::TRADING_POST_SNOW:
  6847. case Obj::FREELANCERS_GUILD:
  6848. return static_cast<const CGMarket*>(obj);
  6849. case Obj::UNIVERSITY:
  6850. return static_cast<const CGUniversity*>(obj);
  6851. default:
  6852. if(verbose)
  6853. logGlobal->errorStream() << "Cannot cast to IMarket object with ID " << obj->ID;
  6854. return nullptr;
  6855. }
  6856. }
  6857. IMarket::IMarket(const CGObjectInstance *O)
  6858. :o(O)
  6859. {
  6860. }
  6861. std::vector<EMarketMode::EMarketMode> IMarket::availableModes() const
  6862. {
  6863. std::vector<EMarketMode::EMarketMode> ret;
  6864. for (int i = 0; i < EMarketMode::MARTKET_AFTER_LAST_PLACEHOLDER; i++)
  6865. if(allowsTrade((EMarketMode::EMarketMode)i))
  6866. ret.push_back((EMarketMode::EMarketMode)i);
  6867. return ret;
  6868. }
  6869. void CGMarket::onHeroVisit(const CGHeroInstance * h) const
  6870. {
  6871. openWindow(OpenWindow::MARKET_WINDOW,id.getNum(),h->id.getNum());
  6872. }
  6873. int CGMarket::getMarketEfficiency() const
  6874. {
  6875. return 5;
  6876. }
  6877. bool CGMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  6878. {
  6879. switch(mode)
  6880. {
  6881. case EMarketMode::RESOURCE_RESOURCE:
  6882. case EMarketMode::RESOURCE_PLAYER:
  6883. switch(ID)
  6884. {
  6885. case Obj::TRADING_POST:
  6886. case Obj::TRADING_POST_SNOW:
  6887. return true;
  6888. default:
  6889. return false;
  6890. }
  6891. case EMarketMode::CREATURE_RESOURCE:
  6892. return ID == Obj::FREELANCERS_GUILD;
  6893. //case ARTIFACT_RESOURCE:
  6894. case EMarketMode::RESOURCE_ARTIFACT:
  6895. return ID == Obj::BLACK_MARKET;
  6896. case EMarketMode::ARTIFACT_EXP:
  6897. case EMarketMode::CREATURE_EXP:
  6898. return ID == Obj::ALTAR_OF_SACRIFICE; //TODO? check here for alignment of visiting hero? - would not be coherent with other checks here
  6899. case EMarketMode::RESOURCE_SKILL:
  6900. return ID == Obj::UNIVERSITY;
  6901. default:
  6902. return false;
  6903. }
  6904. }
  6905. int CGMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  6906. {
  6907. return -1;
  6908. }
  6909. std::vector<int> CGMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6910. {
  6911. switch(mode)
  6912. {
  6913. case EMarketMode::RESOURCE_RESOURCE:
  6914. case EMarketMode::RESOURCE_PLAYER:
  6915. return IMarket::availableItemsIds(mode);
  6916. default:
  6917. return std::vector<int>();
  6918. }
  6919. }
  6920. CGMarket::CGMarket()
  6921. :IMarket(this)
  6922. {
  6923. }
  6924. std::vector<int> CGBlackMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6925. {
  6926. switch(mode)
  6927. {
  6928. case EMarketMode::ARTIFACT_RESOURCE:
  6929. return IMarket::availableItemsIds(mode);
  6930. case EMarketMode::RESOURCE_ARTIFACT:
  6931. {
  6932. std::vector<int> ret;
  6933. for(const CArtifact *a : artifacts)
  6934. if(a)
  6935. ret.push_back(a->id);
  6936. else
  6937. ret.push_back(-1);
  6938. return ret;
  6939. }
  6940. default:
  6941. return std::vector<int>();
  6942. }
  6943. }
  6944. void CGBlackMarket::newTurn() const
  6945. {
  6946. if(cb->getDate(Date::DAY_OF_MONTH) != 1) //new month
  6947. return;
  6948. SetAvailableArtifacts saa;
  6949. saa.id = id.getNum();
  6950. cb->pickAllowedArtsSet(saa.arts);
  6951. cb->sendAndApply(&saa);
  6952. }
  6953. void CGUniversity::initObj()
  6954. {
  6955. std::vector<int> toChoose;
  6956. for(int i = 0; i < GameConstants::SKILL_QUANTITY; ++i)
  6957. {
  6958. if(cb->isAllowed(2, i))
  6959. {
  6960. toChoose.push_back(i);
  6961. }
  6962. }
  6963. if(toChoose.size() < 4)
  6964. {
  6965. logGlobal->warnStream()<<"Warning: less then 4 available skills was found by University initializer!";
  6966. return;
  6967. }
  6968. // get 4 skills
  6969. for(int i = 0; i < 4; ++i)
  6970. {
  6971. // move randomly one skill to selected and remove from list
  6972. auto it = RandomGeneratorUtil::nextItem(toChoose, cb->gameState()->getRandomGenerator());
  6973. skills.push_back(*it);
  6974. toChoose.erase(it);
  6975. }
  6976. }
  6977. std::vector<int> CGUniversity::availableItemsIds(EMarketMode::EMarketMode mode) const
  6978. {
  6979. switch (mode)
  6980. {
  6981. case EMarketMode::RESOURCE_SKILL:
  6982. return skills;
  6983. default:
  6984. return std::vector <int> ();
  6985. }
  6986. }
  6987. void CGUniversity::onHeroVisit(const CGHeroInstance * h) const
  6988. {
  6989. openWindow(OpenWindow::UNIVERSITY_WINDOW,id.getNum(),h->id.getNum());
  6990. }
  6991. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  6992. : count(_count)
  6993. {
  6994. description = boost::str(boost::format(format) % count);
  6995. }
  6996. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  6997. : count(_count)
  6998. {
  6999. description = boost::str(boost::format("%s %+d") % VLC->townh->factions[subID]->town->buildings.at(building)->Name() % count);
  7000. }
  7001. CTownAndVisitingHero::CTownAndVisitingHero()
  7002. {
  7003. setNodeType(TOWN_AND_VISITOR);
  7004. }
  7005. int GrowthInfo::totalGrowth() const
  7006. {
  7007. int ret = 0;
  7008. for(const Entry &entry : entries)
  7009. ret += entry.count;
  7010. return ret;
  7011. }