CObjectHandler.cpp 199 KB

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