CObjectHandler.cpp 202 KB

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