mob.cpp 203 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "mob.hpp"
  4. #include <algorithm>
  5. #include <map>
  6. #include <math.h>
  7. #include <stdlib.h>
  8. #include <unordered_map>
  9. #include <vector>
  10. #include <common/cbasetypes.hpp>
  11. #include <common/db.hpp>
  12. #include <common/ers.hpp>
  13. #include <common/malloc.hpp>
  14. #include <common/nullpo.hpp>
  15. #include <common/random.hpp>
  16. #include <common/showmsg.hpp>
  17. #include <common/socket.hpp>
  18. #include <common/strlib.hpp>
  19. #include <common/timer.hpp>
  20. #include <common/utilities.hpp>
  21. #include <common/utils.hpp>
  22. #include "achievement.hpp"
  23. #include "battle.hpp"
  24. #include "clif.hpp"
  25. #include "elemental.hpp"
  26. #include "guild.hpp"
  27. #include "homunculus.hpp"
  28. #include "intif.hpp"
  29. #include "itemdb.hpp"
  30. #include "log.hpp"
  31. #include "map.hpp"
  32. #include "mercenary.hpp"
  33. #include "npc.hpp"
  34. #include "party.hpp"
  35. #include "path.hpp"
  36. #include "pc.hpp"
  37. #include "pet.hpp"
  38. #include "quest.hpp"
  39. using namespace rathena;
  40. #define ACTIVE_AI_RANGE 2 //Distance added on top of 'AREA_SIZE' at which mobs enter active AI mode.
  41. #define IDLE_SKILL_INTERVAL 10 //Active idle skills should be triggered every 1 second (1000/MIN_MOBTHINKTIME)
  42. const t_tick MOB_MAX_DELAY = 24 * 3600 * 1000;
  43. #define RUDE_ATTACKED_COUNT 1 //After how many rude-attacks should the skill be used?
  44. // On official servers, monsters will only seek targets that are closer to walk to than their
  45. // search range. The search range is affected depending on if the monster is walking or not.
  46. // On some maps there can be a quite long path for just walking two cells in a direction and
  47. // the client does not support displaying walk paths that are longer than 14 cells, so this
  48. // option reduces position lag in such situation. But doing a complex search for every possible
  49. // target, might be CPU intensive.
  50. // Disable this to make monsters not do any path search when looking for a target (old behavior).
  51. #define ACTIVEPATHSEARCH
  52. // Limits for the monster database
  53. #define MIN_MOB_DB 1000
  54. #define MAX_MOB_DB 3999
  55. #define MIN_MOB_DB2 20020
  56. #define MAX_MOB_DB2 31999
  57. // These define the range of available IDs for clones. [Valaris]
  58. #define MOB_CLONE_START MAX_MOB_DB
  59. #define MOB_CLONE_END MIN_MOB_DB2
  60. // holds Monster Spawn informations
  61. std::unordered_map<uint16, std::vector<spawn_info>> mob_spawn_data;
  62. MobItemRatioDatabase mob_item_drop_ratio;
  63. /// Mob skill struct for temporary storage
  64. struct s_mob_skill_db {
  65. int32 mob_id; ///< Monster ID. -1 boss types, -2 normal types, -3 all monsters
  66. std::vector<std::shared_ptr<s_mob_skill>> skill; ///< Skills
  67. };
  68. std::unordered_map<int32, std::shared_ptr<s_mob_skill_db>> mob_skill_db; /// Monster skill temporary db. s_mob_skill_db -> mobid
  69. static struct eri *item_drop_ers; //For loot drops delay structures.
  70. static struct eri *item_drop_list_ers;
  71. MobSummonDatabase mob_summon_db;
  72. MobChatDatabase mob_chat_db;
  73. MapDropDatabase map_drop_db;
  74. /*==========================================
  75. * Local prototype declaration (only required thing)
  76. *------------------------------------------*/
  77. static TIMER_FUNC(mob_spawn_guardian_sub);
  78. int mob_skill_id2skill_idx(int mob_id,uint16 skill_id);
  79. /*========================================== [Playtester]
  80. * Removes all characters that spotted the monster but are no longer online
  81. * @param md: Monster whose spotted log should be cleaned
  82. *------------------------------------------*/
  83. void mob_clean_spotted(struct mob_data *md) {
  84. int i;
  85. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  86. if (md->spotted_log[i] && !map_charid2sd(md->spotted_log[i]))
  87. md->spotted_log[i] = 0;
  88. }
  89. }
  90. /*========================================== [Playtester]
  91. * Adds a char_id to the spotted log of a monster
  92. * @param md: Monster to whose spotted log char_id should be added
  93. * @param char_id: Char_id to add to the spotted log
  94. *------------------------------------------*/
  95. void mob_add_spotted(struct mob_data *md, uint32 char_id) {
  96. int i;
  97. //Check if char_id is already logged
  98. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  99. if (md->spotted_log[i] == char_id)
  100. return;
  101. }
  102. //Not logged, add char_id to first empty slot
  103. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  104. if (md->spotted_log[i] == 0) {
  105. md->spotted_log[i] = char_id;
  106. return;
  107. }
  108. }
  109. }
  110. /*========================================== [Playtester]
  111. * Checks if a monster was spotted
  112. * @param md: Monster to check
  113. * @return Returns true if the monster is spotted, otherwise 0
  114. *------------------------------------------*/
  115. bool mob_is_spotted(struct mob_data *md) {
  116. int i;
  117. //Check if monster is spotted
  118. for (i = 0; i < DAMAGELOG_SIZE; i++) {
  119. if (md->spotted_log[i] != 0)
  120. return true; //Spotted
  121. }
  122. return false; //Not spotted
  123. }
  124. /**
  125. * Tomb spawn time calculations
  126. * @param nd: NPC data
  127. */
  128. int mvptomb_setdelayspawn(struct npc_data *nd) {
  129. if (nd->u.tomb.spawn_timer != INVALID_TIMER)
  130. delete_timer(nd->u.tomb.spawn_timer, mvptomb_delayspawn);
  131. nd->u.tomb.spawn_timer = add_timer(gettick() + battle_config.mvp_tomb_delay, mvptomb_delayspawn, nd->bl.id, 0);
  132. return 0;
  133. }
  134. /**
  135. * Tomb spawn with delay (timer function)
  136. * @param tid: Timer ID
  137. * @param tick: Time
  138. * @param id: Block list ID
  139. * @param data: Used for add_timer_func_list
  140. */
  141. TIMER_FUNC(mvptomb_delayspawn){
  142. struct npc_data *nd = BL_CAST(BL_NPC, map_id2bl(id));
  143. if (nd) {
  144. if (nd->u.tomb.spawn_timer != tid) {
  145. ShowError("mvptomb_delayspawn: Timer mismatch: %d != %d\n", tid, nd->u.tomb.spawn_timer);
  146. return 0;
  147. }
  148. nd->u.tomb.spawn_timer = INVALID_TIMER;
  149. clif_spawn(&nd->bl);
  150. }
  151. return 0;
  152. }
  153. /**
  154. * Create and display a tombstone on the map
  155. * @param md: the mob to create a tombstone for
  156. * @param killer: name of player who killed the mob
  157. * @param time: time of mob's death
  158. * @author [GreenBox]
  159. */
  160. void mvptomb_create(struct mob_data *md, char *killer, time_t time)
  161. {
  162. struct npc_data *nd;
  163. if ( md->tomb_nid )
  164. mvptomb_destroy(md);
  165. CREATE(nd, struct npc_data, 1);
  166. nd->bl.id = md->tomb_nid = npc_get_new_npc_id();
  167. nd->ud.dir = md->ud.dir;
  168. nd->bl.m = md->bl.m;
  169. nd->bl.x = md->bl.x;
  170. nd->bl.y = md->bl.y;
  171. nd->bl.type = BL_NPC;
  172. safestrncpy(nd->name, msg_txt(NULL,656), sizeof(nd->name));
  173. nd->class_ = 565;
  174. nd->speed = 200;
  175. nd->subtype = NPCTYPE_TOMB;
  176. nd->u.tomb.md = md;
  177. nd->u.tomb.kill_time = time;
  178. nd->u.tomb.spawn_timer = INVALID_TIMER;
  179. if (killer)
  180. safestrncpy(nd->u.tomb.killer_name, killer, NAME_LENGTH);
  181. else
  182. nd->u.tomb.killer_name[0] = '\0';
  183. map_addnpc(nd->bl.m, nd);
  184. if(map_addblock(&nd->bl))
  185. return;
  186. status_set_viewdata(&nd->bl, nd->class_);
  187. status_change_init(&nd->bl);
  188. unit_dataset(&nd->bl);
  189. mvptomb_setdelayspawn(nd);
  190. }
  191. /**
  192. * Destroys MVP Tomb
  193. * @param md: Mob data
  194. */
  195. void mvptomb_destroy(struct mob_data *md) {
  196. struct npc_data *nd;
  197. if ( (nd = map_id2nd(md->tomb_nid)) ) {
  198. int i;
  199. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  200. clif_clearunit_area(&nd->bl,CLR_OUTSIGHT);
  201. map_delblock(&nd->bl);
  202. ARR_FIND( 0, mapdata->npc_num, i, mapdata->npc[i] == nd );
  203. if( !(i == mapdata->npc_num) ) {
  204. mapdata->npc_num--;
  205. mapdata->npc[i] = mapdata->npc[mapdata->npc_num];
  206. mapdata->npc[mapdata->npc_num] = NULL;
  207. }
  208. map_deliddb(&nd->bl);
  209. aFree(nd);
  210. }
  211. md->tomb_nid = 0;
  212. }
  213. /**
  214. * Sub function for mob namesearch. Here is defined which are accepted.
  215. */
  216. static bool mobdb_searchname_sub(uint16 mob_id, const char * const str, bool full_cmp)
  217. {
  218. std::shared_ptr<s_mob_db> mob = mob_db.find(mob_id);
  219. if (mob == nullptr)
  220. return false;
  221. if( mobdb_checkid(mob_id) <= 0 )
  222. return false; // invalid mob_id (includes clone check)
  223. if(!mob->base_exp && !mob->job_exp && !mob_has_spawn(mob_id))
  224. return false; // Monsters with no base/job exp and no spawn point are, by this criteria, considered "slave mobs" and excluded from search results
  225. if( full_cmp ) {
  226. // str must equal the db value
  227. if( strcmpi(mob->name.c_str(), str) == 0 ||
  228. strcmpi(mob->jname.c_str(), str) == 0 ||
  229. strcmpi(mob->sprite.c_str(), str) == 0 )
  230. return true;
  231. } else {
  232. // str must be in the db value
  233. if( stristr(mob->name.c_str(), str) != NULL ||
  234. stristr(mob->jname.c_str(), str) != NULL ||
  235. stristr(mob->sprite.c_str(), str) != NULL )
  236. return true;
  237. }
  238. return false;
  239. }
  240. /**
  241. * Searches for the Mobname
  242. */
  243. uint16 mobdb_searchname_(const char * const str, bool full_cmp)
  244. {
  245. for( auto const &mobdb_pair : mob_db ) {
  246. const uint16 mob_id = mobdb_pair.first;
  247. if( mobdb_searchname_sub(mob_id, str, full_cmp) )
  248. return mob_id;
  249. }
  250. return 0;
  251. }
  252. uint16 mobdb_searchname(const char * const str)
  253. {
  254. return mobdb_searchname_(str, true);
  255. }
  256. std::shared_ptr<s_mob_db> mobdb_search_aegisname( const char* str ){
  257. for( auto &mobdb_pair : mob_db ){
  258. if( strcmpi( str, mobdb_pair.second->sprite.c_str() ) == 0 ){
  259. return mobdb_pair.second;
  260. }
  261. }
  262. return nullptr;
  263. }
  264. /*==========================================
  265. * Searches up to N matches. Returns number of matches [Skotlex]
  266. *------------------------------------------*/
  267. uint16 mobdb_searchname_array_(const char *str, uint16 * out, uint16 size, bool full_cmp)
  268. {
  269. uint16 count = 0;
  270. const auto &mob_list = mob_db.getCache();
  271. for( const auto &mob : mob_list ) {
  272. if (mob == nullptr)
  273. continue;
  274. if( mobdb_searchname_sub(mob->id, str, full_cmp) ) {
  275. if( count < size )
  276. out[count] = mob->id;
  277. count++;
  278. }
  279. }
  280. return count;
  281. }
  282. uint16 mobdb_searchname_array(const char *str, uint16 * out, uint16 size)
  283. {
  284. return mobdb_searchname_array_(str, out, size, false);
  285. }
  286. /*==========================================
  287. * Id Mob is checked.
  288. *------------------------------------------*/
  289. int mobdb_checkid(const int id)
  290. {
  291. if (!mob_db.exists(id))
  292. return 0;
  293. if (mob_is_clone(id)) //checkid is used mostly for random ID based code, therefore clone mobs are out of the question.
  294. return 0;
  295. return id;
  296. }
  297. /*==========================================
  298. * Returns the view data associated to this mob class.
  299. *------------------------------------------*/
  300. struct view_data * mob_get_viewdata(int mob_id)
  301. {
  302. std::shared_ptr<s_mob_db> db = mob_db.find(mob_id);
  303. if (db == nullptr)
  304. return nullptr;
  305. return &db->vd;
  306. }
  307. e_mob_bosstype s_mob_db::get_bosstype(){
  308. if( status_has_mode( &this->status, MD_MVP ) ){
  309. return BOSSTYPE_MVP;
  310. }else if( this->status.class_ == CLASS_BOSS ){
  311. return BOSSTYPE_MINIBOSS;
  312. }else{
  313. return BOSSTYPE_NONE;
  314. }
  315. }
  316. e_mob_bosstype mob_data::get_bosstype(){
  317. if( this->db != nullptr ){
  318. return this->db->get_bosstype();
  319. }else{
  320. return BOSSTYPE_NONE;
  321. }
  322. }
  323. /**
  324. * Create unique view data associated to a spawned monster.
  325. * @param md: Mob to adjust
  326. */
  327. void mob_set_dynamic_viewdata( struct mob_data* md ){
  328. // If it is a valid monster and it has not already been created
  329. if( md && !md->vd_changed ){
  330. // Allocate a dynamic entry
  331. struct view_data* vd = (struct view_data*)aMalloc( sizeof( struct view_data ) );
  332. // Copy the current values
  333. memcpy( vd, md->vd, sizeof( struct view_data ) );
  334. // Update the pointer to the new entry
  335. md->vd = vd;
  336. // Flag it as changed so it is freed later on
  337. md->vd_changed = true;
  338. }
  339. }
  340. /**
  341. * Free any view data associated to a spawned monster.
  342. * @param md: Mob to free
  343. */
  344. void mob_free_dynamic_viewdata( struct mob_data* md ){
  345. // If it is a valid monster and it has already been allocated
  346. if( md && md->vd_changed ){
  347. // Free it
  348. aFree( md->vd );
  349. // Remove the reference
  350. md->vd = NULL;
  351. // Unflag it as changed
  352. md->vd_changed = false;
  353. }
  354. }
  355. /*==========================================
  356. * Cleans up mob-spawn data to make it "valid"
  357. *------------------------------------------*/
  358. int mob_parse_dataset(struct spawn_data *data)
  359. {
  360. size_t len;
  361. if ((!mobdb_checkid(data->id) && !mob_is_clone(data->id)) || !data->num)
  362. return 0;
  363. if( ( len = strlen(data->eventname) ) > 0 )
  364. {
  365. if( data->eventname[len-1] == '"' )
  366. data->eventname[len-1] = '\0'; //Remove trailing quote.
  367. if( data->eventname[0] == '"' ) //Strip leading quotes
  368. memmove(data->eventname, data->eventname+1, len-1);
  369. }
  370. if(strcmp(data->name,"--en--")==0)
  371. safestrncpy(data->name, mob_db.find(data->id)->name.c_str(), sizeof(data->name));
  372. else if(strcmp(data->name,"--ja--")==0)
  373. safestrncpy(data->name, mob_db.find(data->id)->jname.c_str(), sizeof(data->name));
  374. return 1;
  375. }
  376. /*==========================================
  377. * Generates the basic mob data using the spawn_data provided.
  378. *------------------------------------------*/
  379. struct mob_data* mob_spawn_dataset(struct spawn_data *data)
  380. {
  381. struct mob_data *md = (struct mob_data*)aCalloc(1, sizeof(struct mob_data));
  382. new(md) mob_data();
  383. md->bl.id= npc_get_new_npc_id();
  384. md->bl.type = BL_MOB;
  385. md->bl.m = data->m;
  386. md->bl.x = data->x;
  387. md->bl.y = data->y;
  388. md->mob_id = data->id;
  389. md->state.boss = data->state.boss;
  390. md->db = mob_db.find(md->mob_id);
  391. if (data->level > 0)
  392. md->level = data->level;
  393. memcpy(md->name, data->name, NAME_LENGTH);
  394. if (data->state.ai)
  395. md->special_state.ai = data->state.ai;
  396. if (data->state.size)
  397. md->special_state.size = data->state.size;
  398. if (data->eventname[0] && strlen(data->eventname) >= 4)
  399. safestrncpy(md->npc_event, data->eventname, EVENT_NAME_LENGTH);
  400. if(status_has_mode(&md->db->status,MD_LOOTER))
  401. md->lootitems = (struct s_mob_lootitem *)aCalloc(LOOTITEM_SIZE,sizeof(struct s_mob_lootitem));
  402. md->spawn_timer = INVALID_TIMER;
  403. md->deletetimer = INVALID_TIMER;
  404. md->skill_idx = -1;
  405. status_set_viewdata(&md->bl, md->mob_id);
  406. status_change_init(&md->bl);
  407. unit_dataset(&md->bl);
  408. map_addiddb(&md->bl);
  409. return md;
  410. }
  411. /*==========================================
  412. * Fetches a random mob_id [Skotlex]
  413. * type: Where to fetch from (see enum e_random_monster)
  414. * flag: Type of checks to apply (see enum e_random_monster_flags)
  415. * lv: Mob level to check against
  416. *------------------------------------------*/
  417. int mob_get_random_id(int type, enum e_random_monster_flags flag, int lv)
  418. {
  419. std::shared_ptr<s_randomsummon_group> summon = mob_summon_db.find(type);
  420. if (type == MOBG_BLOODY_DEAD_BRANCH && flag&RMF_MOB_NOT_BOSS)
  421. flag = static_cast<e_random_monster_flags>(flag&~RMF_MOB_NOT_BOSS);
  422. if (!summon) {
  423. ShowError("mob_get_random_id: Invalid type (%d) of random monster.\n", type);
  424. return 0;
  425. }
  426. if (summon->list.empty()) {
  427. ShowError("mob_get_random_id: Random monster type %d is not defined.\n", type);
  428. return 0;
  429. }
  430. for( size_t i = 0, max = summon->list.size() * 3; i < max; i++ ){
  431. std::shared_ptr<s_randomsummon_entry> entry = util::umap_random( summon->list );
  432. std::shared_ptr<s_mob_db> mob = mob_db.find( entry->mob_id );
  433. if(mob == nullptr ||
  434. mob_is_clone( entry->mob_id ) ||
  435. (flag&RMF_DB_RATE && (entry->rate < 1000000 && entry->rate <= rnd() % 1000000)) ||
  436. (flag&RMF_CHECK_MOB_LV && lv < mob->lv) ||
  437. (flag&RMF_MOB_NOT_BOSS && status_has_mode(&mob->status,MD_STATUSIMMUNE) ) ||
  438. (flag&RMF_MOB_NOT_SPAWN && !mob_has_spawn( entry->mob_id )) ||
  439. (flag&RMF_MOB_NOT_PLANT && status_has_mode(&mob->status,MD_IGNOREMELEE|MD_IGNOREMAGIC|MD_IGNORERANGED|MD_IGNOREMISC) )
  440. ){
  441. continue;
  442. }
  443. return entry->mob_id;
  444. }
  445. if (!mob_db.exists( summon->default_mob_id )) {
  446. ShowError("mob_get_random_id: Default monster is not defined for type %d.\n", type);
  447. return 0;
  448. }
  449. return summon->default_mob_id;
  450. }
  451. /*==========================================
  452. * Kill Steal Protection [Zephyrus]
  453. *------------------------------------------*/
  454. bool mob_ksprotected (struct block_list *src, struct block_list *target)
  455. {
  456. struct block_list *s_bl, *t_bl;
  457. map_session_data
  458. *sd, // Source
  459. *t_sd; // Mob Target
  460. struct mob_data *md;
  461. t_tick tick = gettick();
  462. if( !battle_config.ksprotection )
  463. return false; // KS Protection Disabled
  464. if( !(md = BL_CAST(BL_MOB,target)) )
  465. return false; // Tarjet is not MOB
  466. if( (s_bl = battle_get_master(src)) == nullptr )
  467. s_bl = src;
  468. if( !(sd = BL_CAST(BL_PC,s_bl)) )
  469. return false; // Master is not PC
  470. t_bl = map_id2bl(md->target_id);
  471. if( !t_bl || (s_bl = battle_get_master(t_bl)) == nullptr )
  472. s_bl = t_bl;
  473. t_sd = BL_CAST(BL_PC,s_bl);
  474. do {
  475. struct status_change_entry *sce;
  476. map_session_data *pl_sd; // Owner
  477. struct map_data *mapdata = map_getmapdata(md->bl.m);
  478. char output[128];
  479. if( mapdata->getMapFlag(MF_ALLOWKS) || mapdata_flag_ks(mapdata) )
  480. return false; // Ignores GVG, PVP and AllowKS map flags
  481. if( md->get_bosstype() == BOSSTYPE_MVP || md->master_id )
  482. return false; // MVP, Slaves mobs ignores KS
  483. if( (sce = md->sc.getSCE(SC_KSPROTECTED)) == nullptr )
  484. break; // No KS Protected
  485. if( sd->bl.id == sce->val1 || // Same Owner
  486. (sce->val2 == 2 && sd->status.party_id && sd->status.party_id == sce->val3) || // Party KS allowed
  487. (sce->val2 == 3 && sd->status.guild_id && sd->status.guild_id == sce->val4) ) // Guild KS allowed
  488. break;
  489. if( t_sd && (
  490. (sce->val2 == 1 && sce->val1 != t_sd->bl.id) ||
  491. (sce->val2 == 2 && sce->val3 && sce->val3 != t_sd->status.party_id) ||
  492. (sce->val2 == 3 && sce->val4 && sce->val4 != t_sd->status.guild_id)) )
  493. break;
  494. if( (pl_sd = map_id2sd(sce->val1)) == NULL || pl_sd->bl.m != md->bl.m )
  495. break;
  496. if( !pl_sd->state.noks )
  497. return false; // No KS Protected, but normal players should be protected too
  498. // Message to KS
  499. if( DIFF_TICK(sd->ks_floodprotect_tick, tick) <= 0 )
  500. {
  501. sprintf(output, "[KS Warning!! - Owner : %s]", pl_sd->status.name);
  502. clif_messagecolor(&sd->bl, color_table[COLOR_LIGHT_GREEN], output, false, SELF);
  503. sd->ks_floodprotect_tick = tick + 2000;
  504. }
  505. // Message to Owner
  506. if( DIFF_TICK(pl_sd->ks_floodprotect_tick, tick) <= 0 )
  507. {
  508. sprintf(output, "[Watch out! %s is trying to KS you!]", sd->status.name);
  509. clif_messagecolor(&pl_sd->bl, color_table[COLOR_LIGHT_GREEN], output, false, SELF);
  510. pl_sd->ks_floodprotect_tick = tick + 2000;
  511. }
  512. return true;
  513. } while(0);
  514. status_change_start(src, target, SC_KSPROTECTED, 10000, sd->bl.id, sd->state.noks, sd->status.party_id, sd->status.guild_id, battle_config.ksprotection, SCSTART_NOAVOID);
  515. return false;
  516. }
  517. struct mob_data *mob_once_spawn_sub(struct block_list *bl, int16 m, int16 x, int16 y, const char *mobname, int mob_id, const char *event, unsigned int size, enum mob_ai ai)
  518. {
  519. struct spawn_data data;
  520. memset(&data, 0, sizeof(struct spawn_data)); //why ? this might screw attribute object and cause leak..
  521. data.m = m;
  522. data.num = 1;
  523. data.id = mob_id;
  524. data.state.size = size;
  525. data.state.ai = ai;
  526. if (mobname)
  527. safestrncpy(data.name, mobname, sizeof(data.name));
  528. else
  529. if (battle_config.override_mob_names == 1)
  530. strcpy(data.name, "--en--");
  531. else
  532. strcpy(data.name, "--ja--");
  533. if (event)
  534. safestrncpy(data.eventname, event, sizeof(data.eventname));
  535. // Locate spot next to player.
  536. if (bl && (x < 0 || y < 0))
  537. map_search_freecell(bl, m, &x, &y, 1, 1, 0);
  538. struct map_data *mapdata = map_getmapdata(m);
  539. // if none found, pick random position on map
  540. if (x <= 0 || x >= mapdata->xs || y <= 0 || y >= mapdata->ys)
  541. map_search_freecell(NULL, m, &x, &y, -1, -1, 1);
  542. data.x = x;
  543. data.y = y;
  544. if (!mob_parse_dataset(&data))
  545. return nullptr;
  546. return mob_spawn_dataset(&data);
  547. }
  548. /*==========================================
  549. * Spawn a single mob on the specified coordinates.
  550. *------------------------------------------*/
  551. int mob_once_spawn(map_session_data* sd, int16 m, int16 x, int16 y, const char* mobname, int mob_id, int amount, const char* event, unsigned int size, enum mob_ai ai)
  552. {
  553. struct mob_data* md = nullptr;
  554. int count, lv;
  555. if (m < 0 || amount <= 0)
  556. return 0; // invalid input
  557. lv = (sd) ? sd->status.base_level : 255;
  558. for (count = 0; count < amount; count++)
  559. {
  560. int c = (mob_id >= 0) ? mob_id : mob_get_random_id(-mob_id - 1, (battle_config.random_monster_checklv) ? static_cast<e_random_monster_flags>(RMF_DB_RATE|RMF_CHECK_MOB_LV) : RMF_DB_RATE, lv);
  561. md = mob_once_spawn_sub((sd) ? &sd->bl : NULL, m, x, y, mobname, c, event, size, ai);
  562. if (!md)
  563. continue;
  564. if (mob_id == MOBID_EMPERIUM)
  565. {
  566. std::shared_ptr<guild_castle> gc = castle_db.mapindex2gc(map_getmapdata(m)->index);
  567. auto g = (gc) ? guild_search(gc->guild_id) : nullptr;
  568. if (gc)
  569. {
  570. md->guardian_data = (struct guardian_data*)aCalloc(1, sizeof(struct guardian_data));
  571. new(md->guardian_data) guardian_data();
  572. md->guardian_data->castle = gc;
  573. md->guardian_data->number = MAX_GUARDIANS;
  574. md->guardian_data->guild_id = gc->guild_id;
  575. if (g)
  576. {
  577. md->guardian_data->emblem_id = g->guild.emblem_id;
  578. memcpy(md->guardian_data->guild_name, g->guild.name, NAME_LENGTH);
  579. }
  580. else if (gc->guild_id) // Guild is not yet available, retry after the configured timespan.
  581. add_timer(gettick() + battle_config.mob_respawn_time,mob_spawn_guardian_sub,md->bl.id,md->guardian_data->guild_id);
  582. }
  583. } // end addition [Valaris]
  584. mob_spawn(md);
  585. if (mob_id < 0 && battle_config.dead_branch_active)
  586. //Behold Aegis's masterful decisions yet again...
  587. //"I understand the "Aggressive" part, but the "Can Move" and "Can Attack" is just stupid" - Poki#3
  588. sc_start4(NULL,&md->bl, SC_MODECHANGE, 100, 1, 0, MD_AGGRESSIVE|MD_CANATTACK|MD_CANMOVE|MD_ANGRY, 0, 60000);
  589. }
  590. return (md) ? md->bl.id : 0; // id of last spawned mob
  591. }
  592. /*==========================================
  593. * Spawn mobs in the specified area.
  594. *------------------------------------------*/
  595. int mob_once_spawn_area(map_session_data* sd, int16 m, int16 x0, int16 y0, int16 x1, int16 y1, const char* mobname, int mob_id, int amount, const char* event, unsigned int size, enum mob_ai ai)
  596. {
  597. int i, max, id = 0;
  598. int lx = -1, ly = -1;
  599. if (m < 0 || amount <= 0)
  600. return 0; // invalid input
  601. // normalize x/y coordinates
  602. if (x0 > x1)
  603. SWAP(x0, x1);
  604. if (y0 > y1)
  605. SWAP(y0, y1);
  606. // choose a suitable max. number of attempts
  607. max = (y1 - y0 + 1)*(x1 - x0 + 1)*3;
  608. if (max > 1000)
  609. max = 1000;
  610. // spawn mobs, one by one
  611. for (i = 0; i < amount; i++)
  612. {
  613. int x, y;
  614. int j = 0;
  615. // find a suitable map cell
  616. do {
  617. x = rnd()%(x1-x0+1)+x0;
  618. y = rnd()%(y1-y0+1)+y0;
  619. j++;
  620. } while (map_getcell(m,x,y,CELL_CHKNOPASS) && j < max);
  621. if (j == max)
  622. {// attempt to find an available cell failed
  623. if (lx == -1 && ly == -1)
  624. return 0; // total failure
  625. // fallback to last good x/y pair
  626. x = lx;
  627. y = ly;
  628. }
  629. // record last successful coordinates
  630. lx = x;
  631. ly = y;
  632. id = mob_once_spawn(sd, m, x, y, mobname, mob_id, 1, event, size, ai);
  633. }
  634. return id; // id of last spawned mob
  635. }
  636. /*==========================================
  637. * Set a Guardian's guild data [Skotlex]
  638. *------------------------------------------*/
  639. static TIMER_FUNC(mob_spawn_guardian_sub){
  640. //Needed because the guild_data may not be available at guardian spawn time.
  641. struct block_list* bl = map_id2bl(id);
  642. struct mob_data* md;
  643. int guardup_lv;
  644. if (bl == nullptr) //It is possible mob was already removed from map when the castle has no owner. [Skotlex]
  645. return 0;
  646. if (bl->type != BL_MOB)
  647. {
  648. ShowError("mob_spawn_guardian_sub: Block error!\n");
  649. return 0;
  650. }
  651. md = (struct mob_data*)bl;
  652. nullpo_ret(md->guardian_data);
  653. auto g = guild_search((int)data);
  654. if (g == nullptr)
  655. { //Liberate castle, if the guild is not found this is an error! [Skotlex]
  656. ShowError("mob_spawn_guardian_sub: Couldn't load guild %d!\n", (int)data);
  657. if (md->mob_id == MOBID_EMPERIUM)
  658. { //Not sure this is the best way, but otherwise we'd be invoking this for ALL guardians spawned later on.
  659. md->guardian_data->guild_id = 0;
  660. if (md->guardian_data->castle->guild_id) //Free castle up.
  661. {
  662. ShowNotice("Clearing ownership of castle %d (%s)\n", md->guardian_data->castle->castle_id, md->guardian_data->castle->castle_name);
  663. guild_castledatasave(md->guardian_data->castle->castle_id, CD_GUILD_ID, 0);
  664. }
  665. } else {
  666. if (md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS && md->guardian_data->castle->guardian[md->guardian_data->number].visible)
  667. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number,0);
  668. unit_free(&md->bl,CLR_OUTSIGHT); //Remove guardian.
  669. }
  670. return 0;
  671. }
  672. guardup_lv = guild_checkskill(g->guild, GD_GUARDUP);
  673. md->guardian_data->emblem_id = g->guild.emblem_id;
  674. memcpy(md->guardian_data->guild_name, g->guild.name, NAME_LENGTH);
  675. md->guardian_data->guardup_lv = guardup_lv;
  676. if( guardup_lv )
  677. status_calc_mob(md, SCO_NONE); //Give bonuses.
  678. return 0;
  679. }
  680. /*==========================================
  681. * Summoning Guardians [Valaris]
  682. *------------------------------------------*/
  683. int mob_spawn_guardian(const char* mapname, int16 x, int16 y, const char* mobname, int mob_id, const char* event, int guardian, bool has_index)
  684. {
  685. struct mob_data *md=nullptr;
  686. struct spawn_data data;
  687. std::shared_ptr<MapGuild> g = nullptr;
  688. int16 m;
  689. memset(&data, 0, sizeof(struct spawn_data)); //fixme
  690. data.num = 1;
  691. m=map_mapname2mapid(mapname);
  692. if(m<0)
  693. {
  694. ShowWarning("mob_spawn_guardian: Map [%s] not found.\n", mapname);
  695. return 0;
  696. }
  697. data.m = m;
  698. data.num = 1;
  699. if(mob_id<=0) {
  700. mob_id = mob_get_random_id(-mob_id-1, RMF_DB_RATE, 0);
  701. if (!mob_id) return 0;
  702. }
  703. data.id = mob_id;
  704. if( !has_index )
  705. {
  706. guardian = -1;
  707. }
  708. else if( guardian < 0 || guardian >= MAX_GUARDIANS )
  709. {
  710. ShowError("mob_spawn_guardian: Invalid guardian index %d for guardian %d (castle map %s)\n", guardian, mob_id, mapname);
  711. return 0;
  712. }
  713. if((x<=0 || y<=0) && !map_search_freecell(NULL, m, &x, &y, -1,-1, 1))
  714. {
  715. ShowWarning("mob_spawn_guardian: Couldn't locate a spawn cell for guardian class %d (index %d) at castle map %s\n",mob_id, guardian, mapname);
  716. return 0;
  717. }
  718. data.x = x;
  719. data.y = y;
  720. safestrncpy(data.name, mobname, sizeof(data.name));
  721. safestrncpy(data.eventname, event, sizeof(data.eventname));
  722. if (!mob_parse_dataset(&data))
  723. return 0;
  724. std::shared_ptr<guild_castle> gc = castle_db.mapname2gc(mapname);
  725. if (gc == nullptr)
  726. {
  727. ShowError("mob_spawn_guardian: No castle set at map %s\n", mapname);
  728. return 0;
  729. }
  730. if (!gc->guild_id)
  731. ShowWarning("mob_spawn_guardian: Spawning guardian %d on a castle with no guild (castle map %s)\n", mob_id, mapname);
  732. else
  733. g = guild_search(gc->guild_id);
  734. if( has_index && gc->guardian[guardian].id )
  735. { //Check if guardian already exists, refuse to spawn if so.
  736. struct mob_data *md2 = (TBL_MOB*)map_id2bl(gc->guardian[guardian].id);
  737. if (md2 && md2->bl.type == BL_MOB &&
  738. md2->guardian_data && md2->guardian_data->number == guardian)
  739. {
  740. ShowError("mob_spawn_guardian: Attempted to spawn guardian in position %d which already has a guardian (castle map %s)\n", guardian, mapname);
  741. return 0;
  742. }
  743. }
  744. md = mob_spawn_dataset(&data);
  745. md->guardian_data = (struct guardian_data*)aCalloc(1, sizeof(struct guardian_data));
  746. new (md->guardian_data) guardian_data();
  747. md->guardian_data->number = guardian;
  748. md->guardian_data->guild_id = gc->guild_id;
  749. md->guardian_data->castle = gc;
  750. if( has_index )
  751. {// permanent guardian
  752. gc->guardian[guardian].id = md->bl.id;
  753. }
  754. else
  755. {// temporary guardian
  756. int i;
  757. ARR_FIND(0, gc->temp_guardians_max, i, gc->temp_guardians[i] == 0);
  758. if( i == gc->temp_guardians_max )
  759. {
  760. ++(gc->temp_guardians_max);
  761. RECREATE(gc->temp_guardians, int, gc->temp_guardians_max);
  762. }
  763. gc->temp_guardians[i] = md->bl.id;
  764. }
  765. if (g)
  766. {
  767. md->guardian_data->emblem_id = g->guild.emblem_id;
  768. memcpy (md->guardian_data->guild_name, g->guild.name, NAME_LENGTH);
  769. md->guardian_data->guardup_lv = guild_checkskill(g->guild,GD_GUARDUP);
  770. } else if (md->guardian_data->guild_id)
  771. add_timer(gettick() + battle_config.mob_respawn_time,mob_spawn_guardian_sub,md->bl.id,md->guardian_data->guild_id);
  772. mob_spawn(md);
  773. return md->bl.id;
  774. }
  775. /*==========================================
  776. * Summoning BattleGround [Zephyrus]
  777. *------------------------------------------*/
  778. int mob_spawn_bg(const char* mapname, int16 x, int16 y, const char* mobname, int mob_id, const char* event, unsigned int bg_id)
  779. {
  780. struct mob_data *md = nullptr;
  781. struct spawn_data data;
  782. int16 m;
  783. if( (m = map_mapname2mapid(mapname)) < 0 )
  784. {
  785. ShowWarning("mob_spawn_bg: Map [%s] not found.\n", mapname);
  786. return 0;
  787. }
  788. memset(&data, 0, sizeof(struct spawn_data));
  789. data.m = m;
  790. data.num = 1;
  791. if( mob_id <= 0 )
  792. {
  793. mob_id = mob_get_random_id(-mob_id-1, RMF_DB_RATE, 0);
  794. if( !mob_id ) return 0;
  795. }
  796. data.id = mob_id;
  797. if( (x <= 0 || y <= 0) && !map_search_freecell(NULL, m, &x, &y, -1,-1, 1) )
  798. {
  799. ShowWarning("mob_spawn_bg: Couldn't locate a spawn cell for guardian class %d (bg_id %d) at map %s\n",mob_id, bg_id, mapname);
  800. return 0;
  801. }
  802. data.x = x;
  803. data.y = y;
  804. safestrncpy(data.name, mobname, sizeof(data.name));
  805. safestrncpy(data.eventname, event, sizeof(data.eventname));
  806. if( !mob_parse_dataset(&data) )
  807. return 0;
  808. md = mob_spawn_dataset(&data);
  809. mob_spawn(md);
  810. md->bg_id = bg_id; // BG Team ID
  811. return md->bl.id;
  812. }
  813. /*==========================================
  814. * Returns true if a mob is currently chasing something
  815. * based on its skillstate.
  816. * Chase states: MSS_LOOT, MSS_RUSH, MSS_FOLLOW
  817. *------------------------------------------*/
  818. bool mob_is_chasing(int state)
  819. {
  820. switch (state) {
  821. case MSS_LOOT:
  822. case MSS_RUSH:
  823. case MSS_FOLLOW:
  824. return true;
  825. }
  826. return false;
  827. }
  828. /*==========================================
  829. * Checks if a monster can reach a target by walking
  830. * Range: Maximum number of cells to be walked
  831. *------------------------------------------*/
  832. int mob_can_reach(struct mob_data *md,struct block_list *bl,int range)
  833. {
  834. nullpo_ret(md);
  835. nullpo_ret(bl);
  836. return unit_can_reach_bl(&md->bl, bl, range, 0, NULL, NULL);
  837. }
  838. /*==========================================
  839. * Links nearby mobs (supportive mobs)
  840. *------------------------------------------*/
  841. int mob_linksearch(struct block_list *bl,va_list ap)
  842. {
  843. struct mob_data *md;
  844. int mob_id;
  845. struct block_list *target;
  846. t_tick tick;
  847. nullpo_ret(bl);
  848. md=(struct mob_data *)bl;
  849. mob_id = va_arg(ap, int);
  850. target = va_arg(ap, struct block_list *);
  851. tick=va_arg(ap, t_tick);
  852. if (md->mob_id == mob_id && status_has_mode(&md->status,MD_ASSIST) && DIFF_TICK(tick, md->last_linktime) >= MIN_MOBLINKTIME
  853. && !md->target_id)
  854. {
  855. md->last_linktime = tick;
  856. if( mob_can_reach(md,target,md->db->range2) ){ // Reachability judging
  857. md->target_id = target->id;
  858. md->min_chase=md->db->range3;
  859. return 1;
  860. }
  861. }
  862. return 0;
  863. }
  864. /*==========================================
  865. * mob spawn with delay (timer function)
  866. *------------------------------------------*/
  867. TIMER_FUNC(mob_delayspawn){
  868. struct block_list* bl = map_id2bl(id);
  869. struct mob_data* md = BL_CAST(BL_MOB, bl);
  870. if( md )
  871. {
  872. if( md->spawn_timer != tid )
  873. {
  874. ShowError("mob_delayspawn: Timer mismatch: %d != %d\n", tid, md->spawn_timer);
  875. return 0;
  876. }
  877. md->spawn_timer = INVALID_TIMER;
  878. mob_spawn(md);
  879. }
  880. return 0;
  881. }
  882. /*==========================================
  883. * spawn timing calculation
  884. *------------------------------------------*/
  885. int mob_setdelayspawn(struct mob_data *md)
  886. {
  887. unsigned int spawntime;
  888. if (!md->spawn) //Doesn't has respawn data!
  889. return unit_free(&md->bl,CLR_DEAD);
  890. spawntime = md->spawn->delay1; //Base respawn time
  891. if (md->spawn->delay2) //random variance
  892. spawntime+= rnd()%md->spawn->delay2;
  893. //Apply the spawn delay fix [Skotlex]
  894. std::shared_ptr<s_mob_db> db = mob_db.find(md->spawn->id);
  895. if (status_has_mode(&db->status,MD_STATUSIMMUNE)) { // Status Immune
  896. if (battle_config.boss_spawn_delay != 100) {
  897. // Divide by 100 first to prevent overflows
  898. //(precision loss is minimal as duration is in ms already)
  899. spawntime = spawntime/100*battle_config.boss_spawn_delay;
  900. }
  901. } else if (status_has_mode(&db->status,MD_IGNOREMELEE|MD_IGNOREMAGIC|MD_IGNORERANGED|MD_IGNOREMISC)) { // Plant type
  902. if (battle_config.plant_spawn_delay != 100) {
  903. spawntime = spawntime/100*battle_config.plant_spawn_delay;
  904. }
  905. } else if (battle_config.mob_spawn_delay != 100) { //Normal mobs
  906. spawntime = spawntime/100*battle_config.mob_spawn_delay;
  907. }
  908. spawntime = u32max(1000, spawntime); //Monsters should never respawn faster than 1 second
  909. if( md->spawn_timer != INVALID_TIMER )
  910. delete_timer(md->spawn_timer, mob_delayspawn);
  911. md->spawn_timer = add_timer(gettick()+spawntime, mob_delayspawn, md->bl.id, 0);
  912. return 0;
  913. }
  914. int mob_count_sub(struct block_list *bl, va_list ap) {
  915. int mobid[10], i;
  916. ARR_FIND(0, 10, i, (mobid[i] = va_arg(ap, int)) == 0); //fetch till 0
  917. if (mobid[0]) { //if there one let's check it otherwise go backward
  918. TBL_MOB *md = BL_CAST(BL_MOB, bl);
  919. ARR_FIND(0, 10, i, md->mob_id == mobid[i]);
  920. return (i < 10) ? 1 : 0;
  921. }
  922. return 1; //backward compatibility
  923. }
  924. /**
  925. * Mob spawning. Initialization is also variously here. (Spawn a mob in a map)
  926. * @param md : mob data to spawn
  927. * @return 0:spawned, 1:delayed, 2:error
  928. */
  929. int mob_spawn (struct mob_data *md)
  930. {
  931. int i=0;
  932. t_tick tick = gettick();
  933. md->last_thinktime = tick;
  934. if (md->bl.prev != NULL)
  935. unit_remove_map(&md->bl,CLR_RESPAWN);
  936. else
  937. if (md->spawn && md->mob_id != md->spawn->id)
  938. {
  939. md->mob_id = md->spawn->id;
  940. status_set_viewdata(&md->bl, md->mob_id);
  941. md->db = mob_db.find(md->mob_id);
  942. memcpy(md->name,md->spawn->name,NAME_LENGTH);
  943. }
  944. if (md->spawn) { //Respawn data
  945. md->bl.m = md->spawn->m;
  946. md->bl.x = md->spawn->x;
  947. md->bl.y = md->spawn->y;
  948. if( (md->bl.x == 0 && md->bl.y == 0) || md->spawn->xs || md->spawn->ys )
  949. { //Monster can be spawned on an area.
  950. if( !map_search_freecell(&md->bl, -1, &md->bl.x, &md->bl.y, md->spawn->xs, md->spawn->ys, battle_config.no_spawn_on_player?4:0) )
  951. { // retry again later
  952. if( md->spawn_timer != INVALID_TIMER )
  953. delete_timer(md->spawn_timer, mob_delayspawn);
  954. md->spawn_timer = add_timer(tick + battle_config.mob_respawn_time,mob_delayspawn,md->bl.id,0);
  955. return 1;
  956. }
  957. }
  958. else if( battle_config.no_spawn_on_player > 99 && map_foreachinallrange(mob_count_sub, &md->bl, AREA_SIZE, BL_PC) )
  959. { // retry again later (players on sight)
  960. if( md->spawn_timer != INVALID_TIMER )
  961. delete_timer(md->spawn_timer, mob_delayspawn);
  962. md->spawn_timer = add_timer(tick + battle_config.mob_respawn_time,mob_delayspawn,md->bl.id,0);
  963. return 1;
  964. }
  965. }
  966. memset(&md->state, 0, sizeof(md->state));
  967. status_calc_mob(md, SCO_FIRST);
  968. md->attacked_id = 0;
  969. md->norm_attacked_id = 0;
  970. md->target_id = 0;
  971. md->move_fail_count = 0;
  972. md->ud.state.attack_continue = 0;
  973. md->ud.target_to = 0;
  974. md->ud.dir = 0;
  975. if( md->spawn_timer != INVALID_TIMER ) {
  976. delete_timer(md->spawn_timer, mob_delayspawn);
  977. md->spawn_timer = INVALID_TIMER;
  978. }
  979. // md->master_id = 0;
  980. md->master_dist = 0;
  981. md->state.aggressive = status_has_mode(&md->status,MD_ANGRY)?1:0;
  982. md->state.skillstate = MSS_IDLE;
  983. md->ud.state.blockedmove = false;
  984. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME;
  985. md->last_linktime = tick;
  986. md->dmgtick = tick - 5000;
  987. md->last_pcneartime = 0;
  988. t_tick c = tick - MOB_MAX_DELAY;
  989. for (i = 0; i < MAX_MOBSKILL; i++)
  990. md->skilldelay[i] = c;
  991. for (i = 0; i < DAMAGELOG_SIZE; i++)
  992. md->spotted_log[i] = 0;
  993. memset(md->dmglog, 0, sizeof(md->dmglog));
  994. md->tdmg = 0;
  995. if (md->lootitems)
  996. memset(md->lootitems, 0, sizeof(*md->lootitems));
  997. md->lootitem_count = 0;
  998. if(md->db->option)
  999. // Added for carts, falcons and pecos for cloned monsters. [Valaris]
  1000. md->sc.option = md->db->option;
  1001. // MvP tomb [GreenBox]
  1002. if ( md->tomb_nid )
  1003. mvptomb_destroy(md);
  1004. if(map_addblock(&md->bl))
  1005. return 2;
  1006. if( map_getmapdata(md->bl.m)->users )
  1007. clif_spawn(&md->bl);
  1008. skill_unit_move(&md->bl,tick,1);
  1009. mobskill_use(md, tick, MSC_SPAWN);
  1010. return 0;
  1011. }
  1012. /*==========================================
  1013. * Determines if the mob can change target. [Skotlex]
  1014. *------------------------------------------*/
  1015. static int mob_can_changetarget(struct mob_data* md, struct block_list* target, int mode)
  1016. {
  1017. // Special feature that makes monsters always attack the person that provoked them
  1018. if(battle_config.mob_ai&0x800 && md->state.provoke_flag)
  1019. {
  1020. if (md->state.provoke_flag == target->id)
  1021. return 1;
  1022. else if (!(battle_config.mob_ai&0x4))
  1023. return 0;
  1024. }
  1025. switch (md->state.skillstate) {
  1026. case MSS_BERSERK:
  1027. if (!(mode&MD_CHANGETARGETMELEE))
  1028. return 0;
  1029. if (!(battle_config.mob_ai&0x80) && md->norm_attacked_id != target->id)
  1030. return 0;
  1031. return (battle_config.mob_ai&0x4 || check_distance_bl(&md->bl, target, md->status.rhw.range+1));
  1032. case MSS_RUSH:
  1033. return (mode&MD_CHANGETARGETCHASE);
  1034. case MSS_FOLLOW:
  1035. case MSS_ANGRY:
  1036. case MSS_IDLE:
  1037. case MSS_WALK:
  1038. case MSS_LOOT:
  1039. return 1;
  1040. default:
  1041. return 0;
  1042. }
  1043. }
  1044. /*==========================================
  1045. * Determination for an attack of a monster
  1046. *------------------------------------------*/
  1047. int mob_target(struct mob_data *md,struct block_list *bl,int dist)
  1048. {
  1049. nullpo_ret(md);
  1050. nullpo_ret(bl);
  1051. // Nothing will be carried out if there is no mind of changing TAGE by TAGE ending.
  1052. if(md->target_id && !mob_can_changetarget(md, bl, status_get_mode(&md->bl)))
  1053. return 0;
  1054. if(!status_check_skilluse(&md->bl, bl, 0, 0))
  1055. return 0;
  1056. md->target_id = bl->id; // Since there was no disturbance, it locks on to target.
  1057. if (md->state.provoke_flag && bl->id != md->state.provoke_flag)
  1058. md->state.provoke_flag = 0;
  1059. // When an angry monster is provoked, it will switch to retaliate AI
  1060. if (md->state.provoke_flag && md->state.aggressive)
  1061. md->state.aggressive = 0;
  1062. md->min_chase = cap_value(dist + md->db->range3 - md->status.rhw.range, md->db->range3, MAX_MINCHASE);
  1063. return 0;
  1064. }
  1065. /*==========================================
  1066. * The ?? routine of an active monster
  1067. *------------------------------------------*/
  1068. static int mob_ai_sub_hard_activesearch(struct block_list *bl,va_list ap)
  1069. {
  1070. struct mob_data *md;
  1071. struct block_list **target;
  1072. enum e_mode mode;
  1073. int dist;
  1074. nullpo_ret(bl);
  1075. md=va_arg(ap,struct mob_data *);
  1076. target= va_arg(ap,struct block_list**);
  1077. mode= static_cast<enum e_mode>(va_arg(ap, int));
  1078. //If can't seek yet, not an enemy, or you can't attack it, skip.
  1079. if ((*target) == bl || !status_check_skilluse(&md->bl, bl, 0, 0))
  1080. return 0;
  1081. if ((mode&MD_TARGETWEAK) && status_get_lv(bl) >= md->level-5)
  1082. return 0;
  1083. if(battle_check_target(&md->bl,bl,BCT_ENEMY)<=0)
  1084. return 0;
  1085. switch (bl->type)
  1086. {
  1087. case BL_PC:
  1088. if (((TBL_PC*)bl)->state.gangsterparadise &&
  1089. !status_has_mode(&md->status,MD_STATUSIMMUNE))
  1090. return 0; //Gangster paradise protection.
  1091. default:
  1092. if (battle_config.hom_setting&HOMSET_FIRST_TARGET &&
  1093. (*target) && (*target)->type == BL_HOM && bl->type != BL_HOM)
  1094. return 0; //For some reason Homun targets are never overriden.
  1095. dist = distance_bl(&md->bl, bl);
  1096. if(
  1097. ((*target) == NULL || !check_distance_bl(&md->bl, *target, dist)) &&
  1098. battle_check_range(&md->bl,bl,md->db->range2)
  1099. ) { //Pick closest target?
  1100. #ifdef ACTIVEPATHSEARCH
  1101. struct walkpath_data wpd;
  1102. if (!path_search(&wpd, md->bl.m, md->bl.x, md->bl.y, bl->x, bl->y, 0, CELL_CHKWALL)) // Count walk path cells
  1103. return 0;
  1104. //Standing monsters use range2, walking monsters use range3
  1105. if ((md->ud.walktimer == INVALID_TIMER && wpd.path_len > md->db->range2)
  1106. || (md->ud.walktimer != INVALID_TIMER && wpd.path_len > md->db->range3))
  1107. return 0;
  1108. #endif
  1109. (*target) = bl;
  1110. md->target_id=bl->id;
  1111. md->min_chase = cap_value(dist + md->db->range3 - md->status.rhw.range, md->db->range3, MAX_MINCHASE);
  1112. return 1;
  1113. }
  1114. break;
  1115. }
  1116. return 0;
  1117. }
  1118. /*==========================================
  1119. * chase target-change routine.
  1120. *------------------------------------------*/
  1121. static int mob_ai_sub_hard_changechase(struct block_list *bl,va_list ap)
  1122. {
  1123. struct mob_data *md;
  1124. struct block_list **target;
  1125. nullpo_ret(bl);
  1126. md=va_arg(ap,struct mob_data *);
  1127. target= va_arg(ap,struct block_list**);
  1128. //If can't seek yet, not an enemy, or you can't attack it, skip.
  1129. if ((*target) == bl ||
  1130. battle_check_target(&md->bl,bl,BCT_ENEMY)<=0 ||
  1131. !status_check_skilluse(&md->bl, bl, 0, 0))
  1132. return 0;
  1133. if(battle_check_range (&md->bl, bl, md->status.rhw.range))
  1134. {
  1135. (*target) = bl;
  1136. md->target_id=bl->id;
  1137. md->min_chase= md->db->range3;
  1138. }
  1139. return 1;
  1140. }
  1141. /*==========================================
  1142. * finds nearby bg ally for guardians looking for users to follow.
  1143. *------------------------------------------*/
  1144. static int mob_ai_sub_hard_bg_ally(struct block_list *bl,va_list ap) {
  1145. struct mob_data *md;
  1146. struct block_list **target;
  1147. nullpo_ret(bl);
  1148. md=va_arg(ap,struct mob_data *);
  1149. target= va_arg(ap,struct block_list**);
  1150. if( status_check_skilluse(&md->bl, bl, 0, 0) && battle_check_target(&md->bl,bl,BCT_ENEMY)<=0 ) {
  1151. (*target) = bl;
  1152. }
  1153. return 1;
  1154. }
  1155. /*==========================================
  1156. * loot monster item search
  1157. *------------------------------------------*/
  1158. static int mob_ai_sub_hard_lootsearch(struct block_list *bl,va_list ap)
  1159. {
  1160. struct mob_data* md;
  1161. struct block_list **target;
  1162. int dist;
  1163. md = va_arg(ap,struct mob_data *);
  1164. target = va_arg(ap,struct block_list**);
  1165. dist = distance_bl(&md->bl, bl);
  1166. if (mob_can_reach(md, bl, md->db->range3) && (
  1167. (*target) == nullptr ||
  1168. (battle_config.monster_loot_search_type && md->target_id > bl->id) ||
  1169. (!battle_config.monster_loot_search_type && !check_distance_bl(&md->bl, *target, dist)) // New target closer than previous one.
  1170. ))
  1171. {
  1172. (*target) = bl;
  1173. md->target_id = bl->id;
  1174. md->min_chase = md->db->range3;
  1175. }
  1176. else if (!battle_config.monster_loot_search_type)
  1177. mob_stop_walking(md, 1); // Stop walking immediately if item is no longer on the ground.
  1178. return 0;
  1179. }
  1180. static int mob_warpchase_sub(struct block_list *bl,va_list ap) {
  1181. struct block_list *target;
  1182. struct npc_data **target_nd;
  1183. struct npc_data *nd;
  1184. int *min_distance;
  1185. int cur_distance;
  1186. target= va_arg(ap, struct block_list*);
  1187. target_nd= va_arg(ap, struct npc_data**);
  1188. min_distance= va_arg(ap, int*);
  1189. nd = (TBL_NPC*) bl;
  1190. if(nd->subtype != NPCTYPE_WARP)
  1191. return 0; //Not a warp
  1192. if(nd->u.warp.mapindex != map_getmapdata(target->m)->index)
  1193. return 0; //Does not lead to the same map.
  1194. cur_distance = distance_blxy(target, nd->u.warp.x, nd->u.warp.y);
  1195. if (cur_distance < *min_distance)
  1196. { //Pick warp that leads closest to target.
  1197. *target_nd = nd;
  1198. *min_distance = cur_distance;
  1199. return 1;
  1200. }
  1201. return 0;
  1202. }
  1203. /*==========================================
  1204. * Processing of slave monsters
  1205. *------------------------------------------*/
  1206. static int mob_ai_sub_hard_slavemob(struct mob_data *md,t_tick tick)
  1207. {
  1208. struct block_list *bl;
  1209. bl=map_id2bl(md->master_id);
  1210. if (!bl || status_isdead(bl)) {
  1211. status_kill(&md->bl);
  1212. return 1;
  1213. }
  1214. if (bl->prev == nullptr)
  1215. return 0; //Master not on a map? Could be warping, do not process.
  1216. if(status_has_mode(&md->status,MD_CANMOVE))
  1217. { //If the mob can move, follow around. [Check by Skotlex]
  1218. int old_dist = md->master_dist;
  1219. // Distance with between slave and master is measured.
  1220. md->master_dist = distance_bl(&md->bl, bl);
  1221. if (battle_config.slave_stick_with_master || md->special_state.ai == AI_ABR || md->special_state.ai == AI_BIONIC) {
  1222. // Since the master was in near immediately before, teleport is carried out and it pursues.
  1223. if (bl->m != md->bl.m || (old_dist < 10 && md->master_dist > 18) || md->master_dist > MAX_MINCHASE) {
  1224. md->master_dist = 0;
  1225. unit_warp(&md->bl, bl->m, bl->x, bl->y, CLR_TELEPORT);
  1226. return 1;
  1227. }
  1228. }
  1229. if(md->target_id) //Slave is busy with a target.
  1230. return 0;
  1231. // Approach master if within view range, chase back to Master's area also if standing on top of the master.
  1232. if ((md->master_dist > MOB_SLAVEDISTANCE || md->master_dist == 0) && unit_can_move(&md->bl)) {
  1233. int16 x = bl->x, y = bl->y;
  1234. if (map_search_freecell(&md->bl, bl->m, &x, &y, MOB_SLAVEDISTANCE, MOB_SLAVEDISTANCE, 1)) {
  1235. if (unit_walktoxy(&md->bl, x, y, 0) == 0) { // Slave is too far from master (outside of battle_config.max_walk_path range), stay put
  1236. mob_stop_walking(md, USW_FIXPOS);
  1237. return 0; // Fail here so target will be picked back up when in range
  1238. } else { // Slave will walk back to master if in range
  1239. mob_stop_attack(md);
  1240. return 1;
  1241. }
  1242. }
  1243. }
  1244. } else if (bl->m != md->bl.m && map_flag_gvg2(md->bl.m)) {
  1245. //Delete the summoned mob if it's in a gvg ground and the master is elsewhere. [Skotlex]
  1246. status_kill(&md->bl);
  1247. return 1;
  1248. }
  1249. //Avoid attempting to lock the master's target too often to avoid unnecessary overload. [Skotlex]
  1250. if (DIFF_TICK(tick, md->last_linktime) >= MIN_MOBLINKTIME && !md->target_id)
  1251. {
  1252. struct unit_data *ud = unit_bl2ud(bl);
  1253. md->last_linktime = tick;
  1254. if (ud) {
  1255. struct block_list *tbl=nullptr;
  1256. if (ud->target && ud->state.attack_continue)
  1257. tbl = map_id2bl(ud->target);
  1258. else if (ud->target_to && ud->state.attack_continue)
  1259. tbl = map_id2bl(ud->target_to);
  1260. else if (ud->skilltarget) {
  1261. tbl = map_id2bl(ud->skilltarget);
  1262. //Required check as skilltarget is not always an enemy. [Skotlex]
  1263. if (tbl && battle_check_target(&md->bl, tbl, BCT_ENEMY) <= 0)
  1264. tbl = nullptr;
  1265. }
  1266. if (tbl && status_check_skilluse(&md->bl, tbl, 0, 0)) {
  1267. md->target_id=tbl->id;
  1268. md->min_chase = cap_value(distance_bl(&md->bl, tbl) + md->db->range3 - md->status.rhw.range, md->db->range3, MAX_MINCHASE);
  1269. return 1;
  1270. }
  1271. }
  1272. }
  1273. return 0;
  1274. }
  1275. /*==========================================
  1276. * A lock of target is stopped and mob moves to a standby state.
  1277. * This also triggers idle skill/movement since the AI can get stuck
  1278. * when trying to pick new targets when the current chosen target is
  1279. * unreachable.
  1280. *------------------------------------------*/
  1281. int mob_unlocktarget(struct mob_data *md, t_tick tick)
  1282. {
  1283. nullpo_ret(md);
  1284. // Remember if the monster was in a "chasing" state
  1285. bool chasestate = mob_is_chasing(md->state.skillstate);
  1286. switch (md->state.skillstate) {
  1287. case MSS_WALK:
  1288. if (md->ud.walktimer != INVALID_TIMER)
  1289. break;
  1290. //Because it is not unset when the mob finishes walking.
  1291. md->state.skillstate = MSS_IDLE;
  1292. case MSS_IDLE:
  1293. if( md->ud.walktimer == INVALID_TIMER && md->idle_event[0] && npc_event_do_id( md->idle_event, md->bl.id ) > 0 ){
  1294. md->idle_event[0] = 0;
  1295. break;
  1296. }
  1297. // Idle skill.
  1298. if (!(++md->ud.walk_count%IDLE_SKILL_INTERVAL) && mobskill_use(md, tick, -1))
  1299. break;
  1300. //Random walk.
  1301. if (!md->master_id &&
  1302. DIFF_TICK(md->next_walktime, tick) <= 0 &&
  1303. !mob_randomwalk(md,tick))
  1304. //Delay next random walk when this one failed.
  1305. md->next_walktime = tick+rnd()%1000;
  1306. break;
  1307. default:
  1308. mob_stop_attack(md);
  1309. mob_stop_walking(md,1); //Stop chasing.
  1310. if (status_has_mode(&md->status,MD_ANGRY) && !md->state.aggressive)
  1311. md->state.aggressive = 1; //Restore angry state when switching to idle
  1312. md->state.skillstate = MSS_IDLE;
  1313. if(battle_config.mob_ai&0x8) //Walk instantly after dropping target
  1314. md->next_walktime = tick+rnd()%1000;
  1315. else
  1316. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME;
  1317. break;
  1318. }
  1319. if (md->target_id) {
  1320. md->target_id=0;
  1321. md->ud.target_to = 0;
  1322. unit_set_target(&md->ud, 0);
  1323. }
  1324. if (!md->ud.state.ignore_cell_stack_limit && battle_config.official_cell_stack_limit > 0
  1325. && (chasestate || battle_config.mob_ai & 0x8)
  1326. && map_count_oncell(md->bl.m, md->bl.x, md->bl.y, BL_CHAR | BL_NPC, 1) > battle_config.official_cell_stack_limit) {
  1327. unit_walktoxy(&md->bl, md->bl.x, md->bl.y, 8);
  1328. }
  1329. return 0;
  1330. }
  1331. /*==========================================
  1332. * Random walk
  1333. *------------------------------------------*/
  1334. int mob_randomwalk(struct mob_data *md,t_tick tick)
  1335. {
  1336. const int d=7;
  1337. int i,c,r,rdir,dx,dy,max;
  1338. int speed;
  1339. nullpo_ret(md);
  1340. // Initialize next_walktime
  1341. if (md->next_walktime == INVALID_TIMER) {
  1342. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME;
  1343. return 1;
  1344. }
  1345. if(DIFF_TICK(md->next_walktime,tick)>0 ||
  1346. status_has_mode(&md->status,MD_NORANDOMWALK) ||
  1347. !unit_can_move(&md->bl) ||
  1348. !status_has_mode(&md->status,MD_CANMOVE))
  1349. return 0;
  1350. r=rnd();
  1351. rdir=rnd()%4; // Randomize direction in which we iterate to prevent monster cluttering up in one corner
  1352. dx=r%(d*2+1)-d;
  1353. dy=r/(d*2+1)%(d*2+1)-d;
  1354. max=(d*2+1)*(d*2+1);
  1355. for(i=0;i<max;i++){ // Search of a movable place
  1356. int x = dx + md->bl.x;
  1357. int y = dy + md->bl.y;
  1358. if(((x != md->bl.x) || (y != md->bl.y)) && map_getcell(md->bl.m,x,y,CELL_CHKPASS) && unit_walktoxy(&md->bl,x,y,0)){
  1359. break;
  1360. }
  1361. // Could not move to cell, try the 7th cell in direction randomly decided by rdir
  1362. // We don't move step-by-step because this will make monster stick to the walls
  1363. switch(rdir) {
  1364. case 0:
  1365. dx += d;
  1366. if (dx > d) {
  1367. dx -= d*2+1;
  1368. dy += d;
  1369. if (dy > d) {
  1370. dy -= d*2+1;
  1371. }
  1372. }
  1373. break;
  1374. case 1:
  1375. dx -= d;
  1376. if (dx < -d) {
  1377. dx += d*2+1;
  1378. dy -= d;
  1379. if (dy < -d) {
  1380. dy += d*2+1;
  1381. }
  1382. }
  1383. break;
  1384. case 2:
  1385. dy += d;
  1386. if (dy > d) {
  1387. dy -= d*2+1;
  1388. dx += d;
  1389. if (dx > d) {
  1390. dx -= d*2+1;
  1391. }
  1392. }
  1393. break;
  1394. case 3:
  1395. dy -= d;
  1396. if (dy < -d) {
  1397. dy += d*2+1;
  1398. dx -= d;
  1399. if (dx < -d) {
  1400. dx += d*2+1;
  1401. }
  1402. }
  1403. break;
  1404. }
  1405. }
  1406. if(i==max){
  1407. // None of the available cells worked, try again next interval
  1408. if(battle_config.mob_stuck_warning) {
  1409. md->move_fail_count++;
  1410. if(md->move_fail_count>1000){
  1411. ShowWarning("MOB can't move. random spawn %d, class = %d, at %s (%d,%d)\n",md->bl.id,md->mob_id,map_getmapdata(md->bl.m)->name, md->bl.x, md->bl.y);
  1412. md->move_fail_count=0;
  1413. mob_spawn(md);
  1414. }
  1415. }
  1416. return 0;
  1417. }
  1418. speed=status_get_speed(&md->bl);
  1419. for(i=c=0;i<md->ud.walkpath.path_len;i++){ // The next walk start time is calculated.
  1420. if( direction_diagonal( md->ud.walkpath.path[i] ) )
  1421. c+=speed*MOVE_DIAGONAL_COST/MOVE_COST;
  1422. else
  1423. c+=speed;
  1424. }
  1425. md->state.skillstate=MSS_WALK;
  1426. md->move_fail_count=0;
  1427. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME+c;
  1428. return 1;
  1429. }
  1430. int mob_warpchase(struct mob_data *md, struct block_list *target)
  1431. {
  1432. struct npc_data *warp = nullptr;
  1433. int distance = AREA_SIZE;
  1434. if (!(target && battle_config.mob_ai&0x40 && battle_config.mob_warp&1))
  1435. return 0; //Can't warp chase.
  1436. if (target->m == md->bl.m && check_distance_bl(&md->bl, target, AREA_SIZE))
  1437. return 0; //No need to do a warp chase.
  1438. if (md->ud.walktimer != INVALID_TIMER &&
  1439. map_getcell(md->bl.m,md->ud.to_x,md->ud.to_y,CELL_CHKNPC))
  1440. return 1; //Already walking to a warp.
  1441. //Search for warps within mob's viewing range.
  1442. map_foreachinallrange(mob_warpchase_sub, &md->bl,
  1443. md->db->range2, BL_NPC, target, &warp, &distance);
  1444. if (warp && unit_walktobl(&md->bl, &warp->bl, 1, 1))
  1445. return 1;
  1446. return 0;
  1447. }
  1448. /*==========================================
  1449. * AI of MOB whose is near a Player
  1450. *------------------------------------------*/
  1451. static bool mob_ai_sub_hard(struct mob_data *md, t_tick tick)
  1452. {
  1453. struct block_list *tbl = nullptr, *abl = nullptr;
  1454. int mode;
  1455. int view_range, can_move;
  1456. if(md->bl.prev == nullptr || md->status.hp == 0)
  1457. return false;
  1458. // Monsters force-walked by script commands should not be searching for targets.
  1459. if (md->ud.state.force_walk)
  1460. return false;
  1461. if (DIFF_TICK(tick, md->last_thinktime) < MIN_MOBTHINKTIME)
  1462. return false;
  1463. md->last_thinktime = tick;
  1464. if (md->ud.skilltimer != INVALID_TIMER)
  1465. return false;
  1466. // Abnormalities
  1467. if(( md->sc.opt1 && md->sc.opt1 != OPT1_STONEWAIT && md->sc.opt1 != OPT1_BURNING ) || status_db.hasSCF(&md->sc, SCF_MOBLOSETARGET)) {//Should reset targets.
  1468. md->target_id = md->attacked_id = md->norm_attacked_id = 0;
  1469. return false;
  1470. }
  1471. if (md->sc.count && md->sc.getSCE(SC_BLIND))
  1472. view_range = 3;
  1473. else
  1474. view_range = md->db->range2;
  1475. mode = status_get_mode(&md->bl);
  1476. can_move = (mode&MD_CANMOVE) && unit_can_move(&md->bl);
  1477. if (md->target_id)
  1478. { //Check validity of current target. [Skotlex]
  1479. tbl = map_id2bl(md->target_id);
  1480. if (!tbl || tbl->m != md->bl.m ||
  1481. (md->ud.attacktimer == INVALID_TIMER && !status_check_skilluse(&md->bl, tbl, 0, 0)) ||
  1482. (md->ud.walktimer != INVALID_TIMER && !(battle_config.mob_ai&0x1) && !check_distance_bl(&md->bl, tbl, md->min_chase)) ||
  1483. (
  1484. tbl->type == BL_PC &&
  1485. ((((TBL_PC*)tbl)->state.gangsterparadise && !(mode&MD_STATUSIMMUNE)) ||
  1486. ((TBL_PC*)tbl)->invincible_timer != INVALID_TIMER)
  1487. )) { //No valid target
  1488. if (mob_warpchase(md, tbl))
  1489. return true; //Chasing this target.
  1490. if (tbl && md->ud.walktimer != INVALID_TIMER && (!can_move || md->ud.walkpath.path_pos <= battle_config.mob_chase_refresh))
  1491. return true; //Walk at least "mob_chase_refresh" cells before dropping the target unless target is non-existent
  1492. mob_unlocktarget(md, tick); //Unlock target
  1493. tbl = NULL;
  1494. }
  1495. }
  1496. // Check for target change.
  1497. if( md->attacked_id && mode&MD_CANATTACK )
  1498. {
  1499. if( md->attacked_id == md->target_id )
  1500. { //Rude attacked check.
  1501. if( !battle_check_range(&md->bl, tbl, md->status.rhw.range)
  1502. && ( //Can't attack back and can't reach back.
  1503. (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0 && (battle_config.mob_ai&0x2 || md->sc.getSCE(SC_SPIDERWEB)
  1504. || md->sc.getSCE(SC_BITE) || md->sc.getSCE(SC_VACUUM_EXTREME) || md->sc.getSCE(SC_THORNSTRAP)
  1505. || md->sc.getSCE(SC__MANHOLE) // Not yet confirmed if boss will teleport once it can't reach target.
  1506. || md->walktoxy_fail_count > 0)
  1507. )
  1508. || !mob_can_reach(md, tbl, md->min_chase)
  1509. )
  1510. && md->state.attacked_count++ >= RUDE_ATTACKED_COUNT
  1511. && !mobskill_use(md, tick, MSC_RUDEATTACKED) // If can't rude Attack
  1512. && can_move && unit_escape(&md->bl, tbl, rnd()%10 +1)) // Attempt escape
  1513. { //Escaped
  1514. md->attacked_id = md->norm_attacked_id = 0;
  1515. return true;
  1516. }
  1517. }
  1518. else
  1519. if( (abl = map_id2bl(md->attacked_id)) && (!tbl || mob_can_changetarget(md, abl, mode)) )
  1520. {
  1521. int dist;
  1522. if( md->bl.m != abl->m || abl->prev == NULL
  1523. || (dist = distance_bl(&md->bl, abl)) >= MAX_MINCHASE // Attacker longer than visual area
  1524. || battle_check_target(&md->bl, abl, BCT_ENEMY) <= 0 // Attacker is not enemy of mob
  1525. || (battle_config.mob_ai&0x2 && !status_check_skilluse(&md->bl, abl, 0, 0)) // Cannot normal attack back to Attacker
  1526. || (!battle_check_range(&md->bl, abl, md->status.rhw.range) // Not on Melee Range and ...
  1527. && ( // Reach check
  1528. (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0 && (battle_config.mob_ai&0x2 || md->sc.getSCE(SC_SPIDERWEB)
  1529. || md->sc.getSCE(SC_BITE) || md->sc.getSCE(SC_VACUUM_EXTREME) || md->sc.getSCE(SC_THORNSTRAP)
  1530. || md->sc.getSCE(SC__MANHOLE) // Not yet confirmed if boss will teleport once it can't reach target.
  1531. || md->walktoxy_fail_count > 0)
  1532. )
  1533. || !mob_can_reach(md, abl, dist+md->db->range3)
  1534. )
  1535. ) )
  1536. { // Rude attacked
  1537. if (abl->id != md->bl.id //Self damage does not cause rude attack
  1538. && md->state.attacked_count++ >= RUDE_ATTACKED_COUNT
  1539. && !mobskill_use(md, tick, MSC_RUDEATTACKED) && can_move
  1540. && !tbl && unit_escape(&md->bl, abl, rnd()%10 +1))
  1541. { //Escaped.
  1542. //TODO: Maybe it shouldn't attempt to run if it has another, valid target?
  1543. md->attacked_id = md->norm_attacked_id = 0;
  1544. return true;
  1545. }
  1546. }
  1547. else
  1548. if (!(battle_config.mob_ai&0x2) && !status_check_skilluse(&md->bl, abl, 0, 0))
  1549. {
  1550. //Can't attack back, but didn't invoke a rude attacked skill...
  1551. }
  1552. else
  1553. { //Attackable
  1554. //If a monster can change the target to the attacker, it will change the target
  1555. md->target_id = md->attacked_id; // set target
  1556. if (md->state.attacked_count)
  1557. md->state.attacked_count--; //Should we reset rude attack count?
  1558. md->min_chase = cap_value(dist + md->db->range3 - md->status.rhw.range, md->db->range3, MAX_MINCHASE);
  1559. tbl = abl; //Set the new target
  1560. }
  1561. }
  1562. //Clear it since it's been checked for already.
  1563. md->attacked_id = md->norm_attacked_id = 0;
  1564. }
  1565. bool slave_lost_target = false;
  1566. // Processing of slave monster
  1567. if (md->master_id > 0) {
  1568. if (mob_ai_sub_hard_slavemob(md, tick) == 1)
  1569. return true;
  1570. slave_lost_target = true;
  1571. }
  1572. // Scan area for targets
  1573. if (!tbl && can_move && mode&MD_LOOTER && md->lootitems && DIFF_TICK(tick, md->ud.canact_tick) > 0 &&
  1574. (md->lootitem_count < LOOTITEM_SIZE || battle_config.monster_loot_type != 1))
  1575. { // Scan area for items to loot, avoid trying to loot if the mob is full and can't consume the items.
  1576. map_foreachinshootrange (mob_ai_sub_hard_lootsearch, &md->bl, view_range, BL_ITEM, md, &tbl);
  1577. }
  1578. if ((mode&MD_AGGRESSIVE && (!tbl || slave_lost_target)) || md->state.skillstate == MSS_FOLLOW)
  1579. {
  1580. map_foreachinallrange (mob_ai_sub_hard_activesearch, &md->bl, view_range, DEFAULT_ENEMY_TYPE(md), md, &tbl, mode);
  1581. }
  1582. else
  1583. if (mode&MD_CHANGECHASE && (md->state.skillstate == MSS_RUSH || md->state.skillstate == MSS_FOLLOW))
  1584. {
  1585. int search_size;
  1586. search_size = view_range<md->status.rhw.range ? view_range:md->status.rhw.range;
  1587. map_foreachinallrange (mob_ai_sub_hard_changechase, &md->bl, search_size, DEFAULT_ENEMY_TYPE(md), md, &tbl);
  1588. }
  1589. if (!tbl) { //No targets available.
  1590. /* bg guardians follow allies when no targets nearby */
  1591. if( md->bg_id && mode&MD_CANATTACK ) {
  1592. if( md->ud.walktimer != INVALID_TIMER )
  1593. return true;/* we are already moving */
  1594. map_foreachinallrange (mob_ai_sub_hard_bg_ally, &md->bl, view_range, BL_PC, md, &tbl, mode);
  1595. if( tbl ) {
  1596. if( distance_blxy(&md->bl, tbl->x, tbl->y) <= 3 || unit_walktobl(&md->bl, tbl, 1, 1) )
  1597. return true;/* we're moving or close enough don't unlock the target. */
  1598. }
  1599. }
  1600. //This handles triggering idle/walk skill.
  1601. mob_unlocktarget(md, tick);
  1602. return true;
  1603. }
  1604. //Target exists, attack or loot as applicable.
  1605. if (tbl->type == BL_ITEM)
  1606. { //Loot time.
  1607. struct flooritem_data *fitem;
  1608. if (md->ud.target == tbl->id && md->ud.walktimer != INVALID_TIMER)
  1609. return true; //Already locked.
  1610. if (md->lootitems == NULL)
  1611. { //Can't loot...
  1612. mob_unlocktarget(md, tick);
  1613. return true;
  1614. }
  1615. if (!check_distance_bl(&md->bl, tbl, 0))
  1616. { //Still not within loot range.
  1617. if (!(mode&MD_CANMOVE))
  1618. { //A looter that can't move? Real smart.
  1619. mob_unlocktarget(md, tick);
  1620. return true;
  1621. }
  1622. if (!can_move) //Stuck. Wait before walking.
  1623. return true;
  1624. md->state.skillstate = MSS_LOOT;
  1625. if (!unit_walktobl(&md->bl, tbl, 0, 0))
  1626. mob_unlocktarget(md, tick); //Can't loot...
  1627. return true;
  1628. }
  1629. //Within looting range.
  1630. if (md->ud.attacktimer != INVALID_TIMER)
  1631. return true; //Busy attacking?
  1632. fitem = (struct flooritem_data *)tbl;
  1633. //Logs items, taken by (L)ooter Mobs [Lupus]
  1634. log_pick_mob(md, LOG_TYPE_LOOT, fitem->item.amount, &fitem->item);
  1635. if (md->lootitem_count < LOOTITEM_SIZE) {
  1636. memcpy (&md->lootitems[md->lootitem_count].item, &fitem->item, sizeof(md->lootitems[0].item));
  1637. md->lootitems[md->lootitem_count].mob_id = fitem->mob_id;
  1638. md->lootitem_count++;
  1639. } else { //Destroy first looted item...
  1640. if (md->lootitems[0].item.card[0] == CARD0_PET)
  1641. intif_delete_petdata(MakeDWord(md->lootitems[0].item.card[1],md->lootitems[0].item.card[2]));
  1642. memmove(&md->lootitems[0], &md->lootitems[1], (LOOTITEM_SIZE-1)*sizeof(md->lootitems[0]));
  1643. memcpy (&md->lootitems[LOOTITEM_SIZE-1].item, &fitem->item, sizeof(md->lootitems[0].item));
  1644. md->lootitems[LOOTITEM_SIZE-1].mob_id = fitem->mob_id;
  1645. }
  1646. if (pcdb_checkid(md->vd->class_))
  1647. { //Give them walk act/delay to properly mimic players. [Skotlex]
  1648. clif_takeitem(&md->bl,tbl);
  1649. md->ud.canact_tick = tick + md->status.amotion;
  1650. unit_set_walkdelay(&md->bl, tick, md->status.amotion, 1);
  1651. }
  1652. //Clear item.
  1653. map_clearflooritem(tbl);
  1654. mob_unlocktarget(md, tick);
  1655. return true;
  1656. }
  1657. //Attempt to attack.
  1658. //At this point we know the target is attackable, we just gotta check if the range matches.
  1659. if (battle_check_range(&md->bl, tbl, md->status.rhw.range) && !(md->sc.option&OPTION_HIDE))
  1660. { //Target within range and able to use normal attack, engage
  1661. if (md->ud.target != tbl->id || md->ud.attacktimer == INVALID_TIMER)
  1662. { //Only attack if no more attack delay left
  1663. if(tbl->type == BL_PC)
  1664. mob_log_damage(md, tbl, 0); //Log interaction (counts as 'attacker' for the exp bonus)
  1665. if( !(mode&MD_RANDOMTARGET) )
  1666. unit_attack(&md->bl,tbl->id,1);
  1667. else { // Attack once and find a new random target
  1668. int search_size = (view_range < md->status.rhw.range) ? view_range : md->status.rhw.range;
  1669. unit_attack(&md->bl, tbl->id, 0);
  1670. if ((tbl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md), search_size))) {
  1671. md->target_id = tbl->id;
  1672. md->min_chase = md->db->range3;
  1673. }
  1674. }
  1675. }
  1676. return true;
  1677. }
  1678. //Monsters in berserk state, unable to use normal attacks, will always attempt a skill
  1679. if(md->ud.walktimer == INVALID_TIMER && (md->state.skillstate == MSS_BERSERK || md->state.skillstate == MSS_ANGRY))
  1680. {
  1681. if (DIFF_TICK(md->ud.canmove_tick, tick) <= MIN_MOBTHINKTIME && DIFF_TICK(md->ud.canact_tick, tick) < -MIN_MOBTHINKTIME*IDLE_SKILL_INTERVAL)
  1682. { //Only use skill if able to walk on next tick and not used a skill the last second
  1683. if (mobskill_use(md, tick, -1))
  1684. return true;
  1685. }
  1686. }
  1687. //Target still in attack range, no need to chase the target
  1688. if(battle_check_range(&md->bl, tbl, md->status.rhw.range))
  1689. return true;
  1690. //Only update target cell / drop target after having moved at least "mob_chase_refresh" cells
  1691. if(md->ud.walktimer != INVALID_TIMER && (!can_move || md->ud.walkpath.path_pos <= battle_config.mob_chase_refresh)
  1692. && mob_is_chasing(md->state.skillstate))
  1693. return true;
  1694. //Out of range...
  1695. if (!(mode&MD_CANMOVE) || (!can_move && DIFF_TICK(tick, md->ud.canmove_tick) > 0))
  1696. { //Can't chase. Immobile and trapped mobs should unlock target and use an idle skill.
  1697. if (md->ud.attacktimer == INVALID_TIMER)
  1698. { //Only unlock target if no more attack delay left
  1699. //This handles triggering idle/walk skill.
  1700. mob_unlocktarget(md,tick);
  1701. }
  1702. return true;
  1703. }
  1704. if (md->ud.walktimer != INVALID_TIMER && md->ud.target == tbl->id &&
  1705. (
  1706. !(battle_config.mob_ai&0x1) ||
  1707. check_distance_blxy(tbl, md->ud.to_x, md->ud.to_y, md->status.rhw.range)
  1708. )) //Current target tile is still within attack range.
  1709. return true;
  1710. //Follow up if possible.
  1711. //Hint: Chase skills are handled in the walktobl routine
  1712. if(!mob_can_reach(md, tbl, md->min_chase) ||
  1713. !unit_walktobl(&md->bl, tbl, md->status.rhw.range, 2))
  1714. mob_unlocktarget(md,tick);
  1715. return true;
  1716. }
  1717. static int mob_ai_sub_hard_timer(struct block_list *bl,va_list ap)
  1718. {
  1719. struct mob_data *md = (struct mob_data*)bl;
  1720. uint32 char_id = va_arg(ap, uint32);
  1721. t_tick tick = va_arg(ap, t_tick);
  1722. if (mob_ai_sub_hard(md, tick))
  1723. { //Hard AI triggered.
  1724. mob_add_spotted(md, char_id);
  1725. md->last_pcneartime = tick;
  1726. }
  1727. return 0;
  1728. }
  1729. /*==========================================
  1730. * Serious processing for mob in PC field of view (foreachclient)
  1731. *------------------------------------------*/
  1732. static int mob_ai_sub_foreachclient(map_session_data *sd,va_list ap)
  1733. {
  1734. t_tick tick=va_arg(ap,t_tick);
  1735. map_foreachinallrange(mob_ai_sub_hard_timer,&sd->bl, AREA_SIZE+ACTIVE_AI_RANGE, BL_MOB, sd->status.char_id, tick);
  1736. return 0;
  1737. }
  1738. /*==========================================
  1739. * Negligent mode MOB AI (PC is not in near)
  1740. *------------------------------------------*/
  1741. static int mob_ai_sub_lazy(struct mob_data *md, va_list args)
  1742. {
  1743. nullpo_ret(md);
  1744. if(md->bl.prev == NULL)
  1745. return 0;
  1746. // Monsters force-walked by script commands should not be searching for targets.
  1747. if (md->ud.state.force_walk)
  1748. return false;
  1749. t_tick tick = va_arg(args,t_tick);
  1750. if (battle_config.mob_ai&0x20 && map_getmapdata(md->bl.m)->users>0)
  1751. return (int)mob_ai_sub_hard(md, tick);
  1752. if (md->bl.prev==NULL || md->status.hp == 0)
  1753. return 1;
  1754. if(battle_config.mob_active_time &&
  1755. md->last_pcneartime &&
  1756. !status_has_mode(&md->status,MD_STATUSIMMUNE) &&
  1757. DIFF_TICK(tick,md->last_thinktime) > MIN_MOBTHINKTIME)
  1758. {
  1759. if (DIFF_TICK(tick,md->last_pcneartime) < battle_config.mob_active_time)
  1760. return (int)mob_ai_sub_hard(md, tick);
  1761. md->last_pcneartime = 0;
  1762. }
  1763. if(battle_config.boss_active_time &&
  1764. md->last_pcneartime &&
  1765. status_has_mode(&md->status,MD_STATUSIMMUNE) &&
  1766. DIFF_TICK(tick,md->last_thinktime) > MIN_MOBTHINKTIME)
  1767. {
  1768. if (DIFF_TICK(tick,md->last_pcneartime) < battle_config.boss_active_time)
  1769. return (int)mob_ai_sub_hard(md, tick);
  1770. md->last_pcneartime = 0;
  1771. }
  1772. //Clean the spotted log
  1773. mob_clean_spotted(md);
  1774. if(DIFF_TICK(tick,md->last_thinktime)< 10*MIN_MOBTHINKTIME)
  1775. return 0;
  1776. md->last_thinktime=tick;
  1777. if (md->master_id) {
  1778. mob_ai_sub_hard_slavemob (md,tick);
  1779. return 0;
  1780. }
  1781. if (md->ud.walktimer == INVALID_TIMER) {
  1782. // Because it is not unset when the mob finishes walking.
  1783. md->state.skillstate = MSS_IDLE;
  1784. if (md->idle_event[0] && npc_event_do_id( md->idle_event, md->bl.id ) > 0) {
  1785. md->idle_event[0] = 0;
  1786. return 0;
  1787. }
  1788. }
  1789. if( DIFF_TICK(md->next_walktime,tick) < 0 && status_has_mode(&md->status,MD_CANMOVE) && unit_can_move(&md->bl) )
  1790. {
  1791. // Move probability for mobs away from players
  1792. // In Aegis, this is 100% for mobs that have been activated by players and none otherwise.
  1793. if( mob_is_spotted(md) &&
  1794. ((!status_has_mode(&md->status,MD_STATUSIMMUNE) && rnd()%100 < battle_config.mob_nopc_move_rate) ||
  1795. (status_has_mode(&md->status,MD_STATUSIMMUNE) && rnd()%100 < battle_config.boss_nopc_move_rate)))
  1796. mob_randomwalk(md, tick);
  1797. }
  1798. else if( md->ud.walktimer == INVALID_TIMER )
  1799. {
  1800. // Probability for mobs far from players from doing their IDLE skill.
  1801. // In Aegis, this is 100% for mobs that have been activated by players and none otherwise.
  1802. if( mob_is_spotted(md) &&
  1803. ((!status_has_mode(&md->status,MD_STATUSIMMUNE) && rnd()%100 < battle_config.mob_nopc_idleskill_rate) ||
  1804. (status_has_mode(&md->status,MD_STATUSIMMUNE) && rnd()%100 < battle_config.boss_nopc_idleskill_rate)))
  1805. mobskill_use(md, tick, -1);
  1806. }
  1807. return 0;
  1808. }
  1809. /*==========================================
  1810. * Negligent processing for mob outside PC field of view (interval timer function)
  1811. *------------------------------------------*/
  1812. static TIMER_FUNC(mob_ai_lazy){
  1813. map_foreachmob(mob_ai_sub_lazy,tick);
  1814. return 0;
  1815. }
  1816. /*==========================================
  1817. * Serious processing for mob in PC field of view (interval timer function)
  1818. *------------------------------------------*/
  1819. static TIMER_FUNC(mob_ai_hard){
  1820. if (battle_config.mob_ai&0x20)
  1821. map_foreachmob(mob_ai_sub_lazy,tick);
  1822. else
  1823. map_foreachpc(mob_ai_sub_foreachclient,tick);
  1824. return 0;
  1825. }
  1826. /**
  1827. * Set random option for item when dropped from monster
  1828. * @param item: Item data
  1829. * @param mobdrop: Drop data
  1830. * @author [Cydh]
  1831. **/
  1832. void mob_setdropitem_option(item *item, s_mob_drop *mobdrop) {
  1833. if (!item || !mobdrop)
  1834. return;
  1835. std::shared_ptr<s_random_opt_group> group = random_option_group.find(mobdrop->randomopt_group);
  1836. if (group != nullptr) {
  1837. group->apply( *item );
  1838. }
  1839. }
  1840. /*==========================================
  1841. * Initializes the delay drop structure for mob-dropped items.
  1842. *------------------------------------------*/
  1843. static struct item_drop* mob_setdropitem(struct s_mob_drop *mobdrop, int qty, unsigned short mob_id)
  1844. {
  1845. struct item_drop *drop = ers_alloc(item_drop_ers, struct item_drop);
  1846. memset(&drop->item_data, 0, sizeof(struct item));
  1847. drop->item_data.nameid = mobdrop->nameid;
  1848. drop->item_data.amount = qty;
  1849. drop->item_data.identify = itemdb_isidentified(mobdrop->nameid);
  1850. mob_setdropitem_option(&drop->item_data, mobdrop);
  1851. drop->mob_id = mob_id;
  1852. drop->next = NULL;
  1853. return drop;
  1854. }
  1855. /*==========================================
  1856. * Initializes the delay drop structure for mob-looted items.
  1857. *------------------------------------------*/
  1858. static struct item_drop* mob_setlootitem(struct s_mob_lootitem *item, unsigned short mob_id)
  1859. {
  1860. struct item_drop *drop = ers_alloc(item_drop_ers, struct item_drop);
  1861. memcpy(&drop->item_data, item, sizeof(struct item));
  1862. /**
  1863. * Conditions for lotted item, so it can be announced when player pick it up
  1864. * 1. Not-dropped other than monster. (This will be done later on pc_takeitem/party_share_loot)
  1865. * 2. The mob_id is become the last lootter, instead of the real monster who drop it.
  1866. **/
  1867. drop->mob_id = item->mob_id;
  1868. drop->next = NULL;
  1869. return drop;
  1870. }
  1871. /*==========================================
  1872. * item drop with delay (timer function)
  1873. *------------------------------------------*/
  1874. static TIMER_FUNC(mob_delay_item_drop){
  1875. struct item_drop_list *list;
  1876. struct item_drop *ditem;
  1877. list = (struct item_drop_list *)data;
  1878. ditem = list->item;
  1879. while (ditem) {
  1880. struct item_drop *ditem_prev;
  1881. map_addflooritem(&ditem->item_data,ditem->item_data.amount,
  1882. list->m,list->x,list->y,
  1883. list->first_charid,list->second_charid,list->third_charid,4,ditem->mob_id,true);
  1884. ditem_prev = ditem;
  1885. ditem = ditem->next;
  1886. ers_free(item_drop_ers, ditem_prev);
  1887. }
  1888. ers_free(item_drop_list_ers, list);
  1889. return 0;
  1890. }
  1891. /*==========================================
  1892. * Sets the item_drop into the item_drop_list.
  1893. * Also performs logging and autoloot if enabled.
  1894. * rate is the drop-rate of the item, required for autoloot.
  1895. * flag : Killed only by homunculus/mercenary?
  1896. *------------------------------------------*/
  1897. static void mob_item_drop(struct mob_data *md, struct item_drop_list *dlist, struct item_drop *ditem, int loot, int drop_rate, bool flag)
  1898. {
  1899. TBL_PC* sd;
  1900. bool test_autoloot;
  1901. //Logs items, dropped by mobs [Lupus]
  1902. log_pick_mob(md, loot?LOG_TYPE_LOOT:LOG_TYPE_PICKDROP_MONSTER, -ditem->item_data.amount, &ditem->item_data);
  1903. sd = map_charid2sd(dlist->first_charid);
  1904. if( sd == NULL ) sd = map_charid2sd(dlist->second_charid);
  1905. if( sd == NULL ) sd = map_charid2sd(dlist->third_charid);
  1906. test_autoloot = sd
  1907. && (drop_rate <= sd->state.autoloot || pc_isautolooting(sd, ditem->item_data.nameid))
  1908. && (flag ? ((battle_config.homunculus_autoloot ? (battle_config.hom_idle_no_share == 0 || !pc_isidle_hom(sd)) : 0) || (battle_config.mercenary_autoloot ? (battle_config.mer_idle_no_share == 0 || !pc_isidle_mer(sd)) : 0)) :
  1909. (battle_config.idle_no_autoloot == 0 || DIFF_TICK(last_tick, sd->idletime) < battle_config.idle_no_autoloot));
  1910. #ifdef AUTOLOOT_DISTANCE
  1911. test_autoloot = test_autoloot && sd->bl.m == md->bl.m
  1912. && check_distance_blxy(&sd->bl, dlist->x, dlist->y, AUTOLOOT_DISTANCE);
  1913. #endif
  1914. if( test_autoloot ) { //Autoloot.
  1915. struct party_data *p = party_search(sd->status.party_id);
  1916. if ((itemdb_search(ditem->item_data.nameid))->flag.broadcast &&
  1917. (!p || !(p->party.item & 2)) // Somehow, if party's pickup distribution is 'Even Share', no announcemet
  1918. )
  1919. intif_broadcast_obtain_special_item(sd, ditem->item_data.nameid, md->mob_id, ITEMOBTAIN_TYPE_MONSTER_ITEM);
  1920. if (party_share_loot(party_search(sd->status.party_id),
  1921. sd, &ditem->item_data, sd->status.char_id) == 0
  1922. ) {
  1923. ers_free(item_drop_ers, ditem);
  1924. return;
  1925. }
  1926. }
  1927. ditem->next = dlist->item;
  1928. dlist->item = ditem;
  1929. }
  1930. TIMER_FUNC(mob_timer_delete){
  1931. struct block_list* bl = map_id2bl(id);
  1932. struct mob_data* md = BL_CAST(BL_MOB, bl);
  1933. if( md )
  1934. {
  1935. if( md->deletetimer != tid )
  1936. {
  1937. ShowError("mob_timer_delete: Timer mismatch: %d != %d\n", tid, md->deletetimer);
  1938. return 0;
  1939. }
  1940. //for Alchemist CANNIBALIZE [Lupus]
  1941. md->deletetimer = INVALID_TIMER;
  1942. unit_free(bl, CLR_TELEPORT);
  1943. }
  1944. return 0;
  1945. }
  1946. /*==========================================
  1947. *
  1948. *------------------------------------------*/
  1949. int mob_deleteslave_sub(struct block_list *bl,va_list ap)
  1950. {
  1951. struct mob_data *md;
  1952. int id;
  1953. nullpo_ret(bl);
  1954. nullpo_ret(md = (struct mob_data *)bl);
  1955. id=va_arg(ap,int);
  1956. if(md->master_id > 0 && md->master_id == id )
  1957. status_kill(bl);
  1958. return 0;
  1959. }
  1960. /*==========================================
  1961. *
  1962. *------------------------------------------*/
  1963. int mob_deleteslave(struct mob_data *md)
  1964. {
  1965. nullpo_ret(md);
  1966. map_foreachinmap(mob_deleteslave_sub, md->bl.m, BL_MOB,md->bl.id);
  1967. return 0;
  1968. }
  1969. // Mob respawning through KAIZEL or NPC_REBIRTH [Skotlex]
  1970. TIMER_FUNC(mob_respawn){
  1971. struct block_list *bl = map_id2bl(id);
  1972. if(!bl) return 0;
  1973. status_revive(bl, (uint8)data, 0);
  1974. return 1;
  1975. }
  1976. void mob_log_damage(struct mob_data *md, struct block_list *src, int damage)
  1977. {
  1978. uint32 char_id = 0;
  1979. int flag = MDLF_NORMAL;
  1980. if( damage < 0 )
  1981. return; //Do nothing for absorbed damage.
  1982. if( !damage && !(src->type&DEFAULT_ENEMY_TYPE(md)) )
  1983. return; //Do not log non-damaging effects from non-enemies.
  1984. switch( src->type )
  1985. {
  1986. case BL_PC:
  1987. {
  1988. map_session_data *sd = (TBL_PC*)src;
  1989. char_id = sd->status.char_id;
  1990. if( damage )
  1991. md->attacked_id = src->id;
  1992. break;
  1993. }
  1994. case BL_HOM:
  1995. {
  1996. struct homun_data *hd = (TBL_HOM*)src;
  1997. flag = MDLF_HOMUN;
  1998. if( hd->master )
  1999. char_id = hd->master->status.char_id;
  2000. if( damage )
  2001. md->attacked_id = src->id;
  2002. break;
  2003. }
  2004. case BL_MER:
  2005. {
  2006. s_mercenary_data *mer = (TBL_MER*)src;
  2007. if( mer->master )
  2008. char_id = mer->master->status.char_id;
  2009. if( damage )
  2010. md->attacked_id = src->id;
  2011. break;
  2012. }
  2013. case BL_PET:
  2014. {
  2015. struct pet_data *pd = (TBL_PET*)src;
  2016. flag = MDLF_PET;
  2017. if( pd->master )
  2018. {
  2019. char_id = pd->master->status.char_id;
  2020. if( damage ) //Let mobs retaliate against the pet's master [Skotlex]
  2021. md->attacked_id = pd->master->bl.id;
  2022. }
  2023. break;
  2024. }
  2025. case BL_MOB:
  2026. {
  2027. struct mob_data* md2 = (TBL_MOB*)src;
  2028. if( md2->special_state.ai && md2->master_id )
  2029. {
  2030. map_session_data* msd = map_id2sd(md2->master_id);
  2031. if( msd )
  2032. char_id = msd->status.char_id;
  2033. }
  2034. if( !damage )
  2035. break;
  2036. //Let players decide whether to retaliate versus the master or the mob. [Skotlex]
  2037. if( md2->master_id && battle_config.retaliate_to_master )
  2038. md->attacked_id = md2->master_id;
  2039. else
  2040. md->attacked_id = src->id;
  2041. break;
  2042. }
  2043. case BL_ELEM:
  2044. {
  2045. s_elemental_data *ele = (TBL_ELEM*)src;
  2046. if( ele->master )
  2047. char_id = ele->master->status.char_id;
  2048. if( damage )
  2049. md->attacked_id = src->id;
  2050. break;
  2051. }
  2052. default: //For all unhandled types.
  2053. md->attacked_id = src->id;
  2054. }
  2055. //Self damage increases tap bonus
  2056. if (!char_id && src->id == md->bl.id && damage > 0) {
  2057. char_id = src->id;
  2058. flag = MDLF_SELF;
  2059. }
  2060. if( char_id )
  2061. { //Log damage...
  2062. int i,minpos;
  2063. unsigned int mindmg;
  2064. for(i=0,minpos=DAMAGELOG_SIZE-1,mindmg=UINT_MAX;i<DAMAGELOG_SIZE;i++){
  2065. if(md->dmglog[i].id==char_id &&
  2066. md->dmglog[i].flag==flag)
  2067. break;
  2068. if(md->dmglog[i].id==0) { //Store data in first empty slot.
  2069. md->dmglog[i].id = char_id;
  2070. md->dmglog[i].flag= flag;
  2071. if( md->get_bosstype() == BOSSTYPE_MVP )
  2072. pc_damage_log_add(map_charid2sd(char_id),md->bl.id);
  2073. break;
  2074. }
  2075. if(md->dmglog[i].dmg<mindmg && i)
  2076. { //Never overwrite first hit slot (he gets double exp bonus)
  2077. minpos=i;
  2078. mindmg=md->dmglog[i].dmg;
  2079. }
  2080. }
  2081. if(i<DAMAGELOG_SIZE)
  2082. md->dmglog[i].dmg+=damage;
  2083. else {
  2084. md->dmglog[minpos].id = char_id;
  2085. md->dmglog[minpos].flag= flag;
  2086. md->dmglog[minpos].dmg = damage;
  2087. if( md->get_bosstype() == BOSSTYPE_MVP )
  2088. pc_damage_log_add(map_charid2sd(char_id),md->bl.id);
  2089. }
  2090. }
  2091. return;
  2092. }
  2093. //Call when a mob has received damage.
  2094. void mob_damage(struct mob_data *md, struct block_list *src, int damage)
  2095. {
  2096. if( src != nullptr && md->special_state.ai == AI_SPHERE && !md->dmglog[0].id ) {//LOne WOlf explained that ANYONE can trigger the marine countdown skill. [Skotlex]
  2097. md->state.can_escape = 1;
  2098. }
  2099. if (src && damage > 0) { //Store total damage...
  2100. if (UINT_MAX - (unsigned int)damage > md->tdmg)
  2101. md->tdmg += damage;
  2102. else if (md->tdmg == UINT_MAX)
  2103. damage = 0; //Stop recording damage once the cap has been reached.
  2104. else { //Cap damage log...
  2105. damage = (int)(UINT_MAX - md->tdmg);
  2106. md->tdmg = UINT_MAX;
  2107. }
  2108. if ((src != &md->bl) && md->state.aggressive) //No longer aggressive, change to retaliate AI.
  2109. md->state.aggressive = 0;
  2110. //Log damage
  2111. mob_log_damage(md, src, damage);
  2112. md->dmgtick = gettick();
  2113. }
  2114. if (battle_config.show_mob_info&3)
  2115. clif_name_area(&md->bl);
  2116. #if PACKETVER >= 20120404
  2117. if (battle_config.monster_hp_bars_info && !map_getmapflag(md->bl.m, MF_HIDEMOBHPBAR)) {
  2118. int i;
  2119. if (md->special_state.ai == AI_ABR || md->special_state.ai == AI_BIONIC) {
  2120. clif_summon_hp_bar(*md);
  2121. }
  2122. for(i = 0; i < DAMAGELOG_SIZE; i++){ // must show hp bar to all char who already hit the mob.
  2123. map_session_data *sd = map_charid2sd(md->dmglog[i].id);
  2124. if( sd && check_distance_bl(&md->bl, &sd->bl, AREA_SIZE) ) // check if in range
  2125. clif_monster_hp_bar(md, sd->fd);
  2126. }
  2127. }
  2128. #endif
  2129. }
  2130. /**
  2131. * Get modified drop rate
  2132. * @param src: Source object
  2133. * @param mob: Monster data
  2134. * @param base_rate: Base drop rate
  2135. * @param drop_modifier: RENEWAL_DROP level modifier
  2136. * @return Modified drop rate
  2137. */
  2138. int mob_getdroprate(struct block_list *src, std::shared_ptr<s_mob_db> mob, int base_rate, int drop_modifier, mob_data* md)
  2139. {
  2140. int drop_rate = base_rate;
  2141. if (md && battle_config.mob_size_influence) { // Change drops depending on monsters size [Valaris]
  2142. unsigned int mob_size = md->special_state.size;
  2143. if (mob_size == SZ_MEDIUM && drop_rate >= 2)
  2144. drop_rate /= 2; // SZ_MEDIUM actually is small size modification... this is not a bug!
  2145. else if (mob_size == SZ_BIG)
  2146. drop_rate *= 2;
  2147. }
  2148. if (src) {
  2149. if (battle_config.drops_by_luk) // Drops affected by luk as a fixed increase [Valaris]
  2150. drop_rate += status_get_luk(src) * battle_config.drops_by_luk / 100;
  2151. if (battle_config.drops_by_luk2) // Drops affected by luk as a % increase [Skotlex]
  2152. drop_rate += (int)(0.5 + drop_rate * status_get_luk(src) * battle_config.drops_by_luk2 / 10000.);
  2153. if (src->type == BL_PC) { // Player specific drop rate adjustments
  2154. map_session_data *sd = (map_session_data*)src;
  2155. int drop_rate_bonus = 100;
  2156. // In PK mode players get an additional drop chance bonus of 25% if there is a 20 level difference
  2157. if( battle_config.pk_mode && (int)(mob->lv - sd->status.base_level) >= 20 ){
  2158. drop_rate_bonus += 25;
  2159. }
  2160. // Add class and race specific bonuses
  2161. drop_rate_bonus += sd->indexed_bonus.dropaddclass[mob->status.class_] + sd->indexed_bonus.dropaddclass[CLASS_ALL];
  2162. drop_rate_bonus += sd->indexed_bonus.dropaddrace[mob->status.race] + sd->indexed_bonus.dropaddrace[RC_ALL];
  2163. if (sd->sc.getSCE(SC_ITEMBOOST))
  2164. drop_rate_bonus += sd->sc.getSCE(SC_ITEMBOOST)->val1;
  2165. int cap;
  2166. if (pc_isvip(sd)) { // Increase item drop rate for VIP.
  2167. // Unsure how the VIP and other bonuses should stack, this is additive.
  2168. drop_rate_bonus += battle_config.vip_drop_increase;
  2169. cap = battle_config.drop_rate_cap_vip;
  2170. } else
  2171. cap = battle_config.drop_rate_cap;
  2172. drop_rate = (int)( 0.5 + drop_rate * drop_rate_bonus / 100. );
  2173. // Now limit the drop rate to never be exceed the cap (default: 90%), unless it is originally above it already.
  2174. if( drop_rate > cap && base_rate < cap ){
  2175. drop_rate = cap;
  2176. }
  2177. }
  2178. }
  2179. #ifdef RENEWAL_DROP
  2180. drop_rate = apply_rate( drop_rate, drop_modifier );
  2181. #endif
  2182. // Cap it to 100%
  2183. drop_rate = min( drop_rate, 10000 );
  2184. // If the monster's drop rate can become 0
  2185. if( battle_config.drop_rate0item ){
  2186. drop_rate = max( drop_rate, 0 );
  2187. }else{
  2188. // If not - cap to 0.01% drop rate - as on official servers
  2189. drop_rate = max( drop_rate, 1 );
  2190. }
  2191. return drop_rate;
  2192. }
  2193. /*==========================================
  2194. * Signals death of mob.
  2195. * type&1 -> no drops, type&2 -> no exp
  2196. *------------------------------------------*/
  2197. int mob_dead(struct mob_data *md, struct block_list *src, int type)
  2198. {
  2199. struct status_data *status;
  2200. map_session_data *sd = NULL, *tmpsd[DAMAGELOG_SIZE];
  2201. map_session_data *mvp_sd = NULL, *second_sd = NULL, *third_sd = NULL;
  2202. struct {
  2203. struct party_data *p;
  2204. int id,zeny;
  2205. t_exp base_exp;
  2206. t_exp job_exp;
  2207. } pt[DAMAGELOG_SIZE];
  2208. int i, temp, count, m = md->bl.m;
  2209. int dmgbltypes = 0; // bitfield of all bl types, that caused damage to the mob and are elligible for exp distribution
  2210. unsigned int mvp_damage;
  2211. t_tick tick = gettick();
  2212. bool rebirth, homkillonly, merckillonly;
  2213. status = &md->status;
  2214. if( src && src->type == BL_PC ) {
  2215. sd = (map_session_data *)src;
  2216. mvp_sd = sd;
  2217. }
  2218. if( md->guardian_data && md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS )
  2219. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number,0);
  2220. if( src ) { // Use Dead skill only if not killed by Script or Command
  2221. md->status.hp = 1;
  2222. md->state.skillstate = MSS_DEAD;
  2223. mobskill_use(md,tick,-1);
  2224. md->status.hp = 0;
  2225. }
  2226. map_freeblock_lock();
  2227. memset(pt,0,sizeof(pt));
  2228. if(src && src->type == BL_MOB)
  2229. mob_unlocktarget((struct mob_data *)src,tick);
  2230. // filter out entries not eligible for exp distribution
  2231. memset(tmpsd,0,sizeof(tmpsd));
  2232. for(i = 0, count = 0, mvp_damage = 0; i < DAMAGELOG_SIZE && md->dmglog[i].id; i++) {
  2233. map_session_data* tsd = NULL;
  2234. if (md->dmglog[i].flag == MDLF_SELF) {
  2235. //Self damage counts as exp tap
  2236. count++;
  2237. continue;
  2238. }
  2239. tsd = map_charid2sd(md->dmglog[i].id);
  2240. if (tsd == NULL)
  2241. continue; // skip empty entries
  2242. if (tsd->bl.m != m)
  2243. continue; // skip players not on this map
  2244. count++; //Only logged into same map chars are counted for the total.
  2245. if (pc_isdead(tsd))
  2246. continue; // skip dead players
  2247. if (md->dmglog[i].flag == MDLF_HOMUN && !hom_is_active(tsd->hd))
  2248. continue; // skip homunc's share if inactive
  2249. if (md->dmglog[i].flag == MDLF_PET && (!tsd->status.pet_id || !tsd->pd))
  2250. continue; // skip pet's share if inactive
  2251. if(md->dmglog[i].dmg > mvp_damage) {
  2252. third_sd = second_sd;
  2253. second_sd = mvp_sd;
  2254. mvp_sd = tsd;
  2255. mvp_damage = md->dmglog[i].dmg;
  2256. }
  2257. tmpsd[i] = tsd; // record as valid damage-log entry
  2258. switch( md->dmglog[i].flag ) {
  2259. case MDLF_NORMAL: dmgbltypes|= BL_PC; break;
  2260. case MDLF_HOMUN: dmgbltypes|= BL_HOM; break;
  2261. case MDLF_PET: dmgbltypes|= BL_PET; break;
  2262. }
  2263. }
  2264. // determines, if the monster was killed by homunculus' damage only
  2265. homkillonly = (bool)( ( dmgbltypes&BL_HOM ) && !( dmgbltypes&~BL_HOM ) );
  2266. // determines if the monster was killed by mercenary damage only
  2267. merckillonly = (bool)((dmgbltypes & BL_MER) && !(dmgbltypes & ~BL_MER));
  2268. if(!battle_config.exp_calc_type && count > 1) { //Apply first-attacker 200% exp share bonus
  2269. //TODO: Determine if this should go before calculating the MVP player instead of after.
  2270. if (UINT_MAX - md->dmglog[0].dmg > md->tdmg) {
  2271. md->tdmg += md->dmglog[0].dmg;
  2272. md->dmglog[0].dmg *= 2;
  2273. } else {
  2274. md->dmglog[0].dmg+= UINT_MAX - md->tdmg;
  2275. md->tdmg = UINT_MAX;
  2276. }
  2277. }
  2278. if(!(type&2) && //No exp
  2279. (!map_getmapflag(m, MF_PVP) || battle_config.pvp_exp) && //Pvp no exp rule [MouseJstr]
  2280. (!md->master_id || !md->special_state.ai) && //Only player-summoned mobs do not give exp. [Skotlex]
  2281. (!map_getmapflag(m, MF_NOBASEEXP) || !map_getmapflag(m, MF_NOJOBEXP)) //Gives Exp
  2282. ) { //Experience calculation.
  2283. int bonus = 100; //Bonus on top of your share (common to all attackers).
  2284. int pnum = 0;
  2285. #ifndef RENEWAL
  2286. if (md->sc.getSCE(SC_RICHMANKIM))
  2287. bonus += md->sc.getSCE(SC_RICHMANKIM)->val2;
  2288. #else
  2289. if (sd && sd->sc.getSCE(SC_RICHMANKIM))
  2290. bonus += sd->sc.getSCE(SC_RICHMANKIM)->val2;
  2291. #endif
  2292. if(sd) {
  2293. temp = status_get_class(&md->bl);
  2294. if(sd->sc.getSCE(SC_MIRACLE)) i = 2; //All mobs are Star Targets
  2295. else
  2296. ARR_FIND(0, MAX_PC_FEELHATE, i, temp == sd->hate_mob[i] &&
  2297. (battle_config.allow_skill_without_day || sg_info[i].day_func()));
  2298. if(i<MAX_PC_FEELHATE && (temp=pc_checkskill(sd,sg_info[i].bless_id)))
  2299. bonus += (i==2?20:10)*temp;
  2300. }
  2301. if(battle_config.mobs_level_up && md->level > md->db->lv) // [Valaris]
  2302. bonus += (md->level-md->db->lv)*battle_config.mobs_level_up_exp_rate;
  2303. for(i = 0; i < DAMAGELOG_SIZE && md->dmglog[i].id; i++) {
  2304. int flag=1,zeny=0;
  2305. t_exp base_exp, job_exp;
  2306. double per; //Your share of the mob's exp
  2307. if (!tmpsd[i]) continue;
  2308. if (!battle_config.exp_calc_type && md->tdmg)
  2309. //jAthena's exp formula based on total damage.
  2310. per = (double)md->dmglog[i].dmg/(double)md->tdmg;
  2311. else {
  2312. //eAthena's exp formula based on max hp.
  2313. per = (double)md->dmglog[i].dmg/(double)status->max_hp;
  2314. if (per > 2) per = 2; // prevents unlimited exp gain
  2315. }
  2316. //Exclude rebirth tap from this calculation
  2317. count -= md->state.rebirth;
  2318. if (count>1 && battle_config.exp_bonus_attacker) {
  2319. //Exp bonus per additional attacker.
  2320. if (count > battle_config.exp_bonus_max_attacker)
  2321. count = battle_config.exp_bonus_max_attacker;
  2322. per += per*((count-1)*battle_config.exp_bonus_attacker)/100.;
  2323. }
  2324. // change experience for different sized monsters [Valaris]
  2325. if (battle_config.mob_size_influence) {
  2326. switch( md->special_state.size ) {
  2327. case SZ_MEDIUM:
  2328. per /= 2.;
  2329. break;
  2330. case SZ_BIG:
  2331. per *= 2.;
  2332. break;
  2333. }
  2334. }
  2335. if( md->dmglog[i].flag == MDLF_PET )
  2336. per *= battle_config.pet_attack_exp_rate/100.;
  2337. if(battle_config.zeny_from_mobs && md->level) {
  2338. // zeny calculation moblv + random moblv [Valaris]
  2339. zeny=(int) ((md->level+rnd()%md->level)*per*bonus/100.);
  2340. if( md->get_bosstype() == BOSSTYPE_MVP )
  2341. zeny*=rnd()%250;
  2342. }
  2343. if (map_getmapflag(m, MF_NOBASEEXP) || !md->db->base_exp)
  2344. base_exp = 0;
  2345. else {
  2346. double exp = apply_rate2(md->db->base_exp, per, 1);
  2347. exp = apply_rate(exp, bonus);
  2348. exp = apply_rate(exp, map_getmapflag(m, MF_BEXP));
  2349. base_exp = (t_exp)cap_value(exp, 1, MAX_EXP);
  2350. }
  2351. if (map_getmapflag(m, MF_NOJOBEXP) || !md->db->job_exp
  2352. #ifndef RENEWAL
  2353. || md->dmglog[i].flag == MDLF_HOMUN // Homun earned job-exp is always lost.
  2354. #endif
  2355. )
  2356. job_exp = 0;
  2357. else {
  2358. double exp = apply_rate2(md->db->job_exp, per, 1);
  2359. exp = apply_rate(exp, bonus);
  2360. exp = apply_rate(exp, map_getmapflag(m, MF_JEXP));
  2361. job_exp = (t_exp)cap_value(exp, 1, MAX_EXP);
  2362. }
  2363. if ((base_exp > 0 || job_exp > 0) && md->dmglog[i].flag == MDLF_HOMUN && homkillonly && battle_config.hom_idle_no_share && pc_isidle_hom(tmpsd[i]))
  2364. base_exp = job_exp = 0;
  2365. if ( ( temp = tmpsd[i]->status.party_id)>0 ) {
  2366. int j;
  2367. for( j = 0; j < pnum && pt[j].id != temp; j++ ); //Locate party.
  2368. if( j == pnum ) { //Possibly add party.
  2369. pt[pnum].p = party_search(temp);
  2370. if(pt[pnum].p && pt[pnum].p->party.exp) {
  2371. pt[pnum].id = temp;
  2372. pt[pnum].base_exp = base_exp;
  2373. pt[pnum].job_exp = job_exp;
  2374. pt[pnum].zeny = zeny; // zeny share [Valaris]
  2375. pnum++;
  2376. flag = 0;
  2377. }
  2378. } else { //Add to total
  2379. pt[j].base_exp = util::safe_addition_cap( pt[j].base_exp, base_exp, MAX_EXP );
  2380. pt[j].job_exp = util::safe_addition_cap( pt[j].job_exp, job_exp, MAX_EXP );
  2381. pt[j].zeny += zeny; // zeny share [Valaris]
  2382. flag = 0;
  2383. }
  2384. }
  2385. #ifdef RENEWAL
  2386. if (base_exp && tmpsd[i] && tmpsd[i]->hd)
  2387. hom_gainexp(tmpsd[i]->hd, base_exp * battle_config.homunculus_exp_gain / 100); // Homunculus only receive 10% of EXP
  2388. #else
  2389. if (base_exp && md->dmglog[i].flag == MDLF_HOMUN) //tmpsd[i] is null if it has no homunc.
  2390. hom_gainexp(tmpsd[i]->hd, base_exp);
  2391. #endif
  2392. if(flag) {
  2393. if(base_exp || job_exp) {
  2394. if( md->dmglog[i].flag != MDLF_PET || battle_config.pet_attack_exp_to_master ) {
  2395. #ifdef RENEWAL_EXP
  2396. int rate = pc_level_penalty_mod( tmpsd[i], PENALTY_EXP, nullptr, md );
  2397. if (rate != 100) {
  2398. if (base_exp)
  2399. base_exp = (t_exp)cap_value(apply_rate(base_exp, rate), 1, MAX_EXP);
  2400. if (job_exp)
  2401. job_exp = (t_exp)cap_value(apply_rate(job_exp, rate), 1, MAX_EXP);
  2402. }
  2403. #endif
  2404. pc_gainexp(tmpsd[i], &md->bl, base_exp, job_exp, 0);
  2405. }
  2406. }
  2407. if(zeny) // zeny from mobs [Valaris]
  2408. pc_getzeny(tmpsd[i], zeny, LOG_TYPE_PICKDROP_MONSTER);
  2409. }
  2410. if( md->get_bosstype() == BOSSTYPE_MVP )
  2411. pc_damage_log_clear(tmpsd[i],md->bl.id);
  2412. }
  2413. for( i = 0; i < pnum; i++ ) //Party share.
  2414. party_exp_share(pt[i].p, &md->bl, pt[i].base_exp,pt[i].job_exp,pt[i].zeny);
  2415. } //End EXP giving.
  2416. if( !(type&1) && !map_getmapflag(m, MF_NOMOBLOOT) && !md->state.rebirth && (
  2417. !md->special_state.ai || //Non special mob
  2418. battle_config.alchemist_summon_reward == 2 || //All summoned give drops
  2419. (md->special_state.ai==AI_SPHERE && battle_config.alchemist_summon_reward == 1) //Marine Sphere Drops items.
  2420. ) )
  2421. { // Item Drop
  2422. struct item_drop_list *dlist = ers_alloc(item_drop_list_ers, struct item_drop_list);
  2423. struct item_drop *ditem;
  2424. int drop_rate, drop_modifier = 100;
  2425. #ifdef RENEWAL_DROP
  2426. drop_modifier = pc_level_penalty_mod( mvp_sd != nullptr ? mvp_sd : second_sd != nullptr ? second_sd : third_sd, PENALTY_DROP, nullptr, md );
  2427. #endif
  2428. dlist->m = md->bl.m;
  2429. dlist->x = md->bl.x;
  2430. dlist->y = md->bl.y;
  2431. dlist->first_charid = (mvp_sd ? mvp_sd->status.char_id : 0);
  2432. dlist->second_charid = (second_sd ? second_sd->status.char_id : 0);
  2433. dlist->third_charid = (third_sd ? third_sd->status.char_id : 0);
  2434. dlist->item = NULL;
  2435. for (i = 0; i < MAX_MOB_DROP_TOTAL; i++) {
  2436. if (md->db->dropitem[i].nameid == 0)
  2437. continue;
  2438. std::shared_ptr<item_data> it = item_db.find(md->db->dropitem[i].nameid);
  2439. if ( it == nullptr )
  2440. continue;
  2441. drop_rate = mob_getdroprate(src, md->db, md->db->dropitem[i].rate, drop_modifier, md);
  2442. // attempt to drop the item
  2443. if (rnd() % 10000 >= drop_rate)
  2444. continue;
  2445. if( mvp_sd && it->type == IT_PETEGG ) {
  2446. pet_create_egg(mvp_sd, md->db->dropitem[i].nameid);
  2447. continue;
  2448. }
  2449. ditem = mob_setdropitem(&md->db->dropitem[i], 1, md->mob_id);
  2450. //A Rare Drop Global Announce by Lupus
  2451. if( mvp_sd && md->db->dropitem[i].rate <= battle_config.rare_drop_announce ) {
  2452. char message[128];
  2453. sprintf (message, msg_txt(NULL,541), mvp_sd->status.name, md->name, it->ename.c_str(), (float)drop_rate/100);
  2454. //MSG: "'%s' won %s's %s (chance: %0.02f%%)"
  2455. intif_broadcast(message,strlen(message)+1,BC_DEFAULT);
  2456. }
  2457. // Announce first, or else ditem will be freed. [Lance]
  2458. // By popular demand, use base drop rate for autoloot code. [Skotlex]
  2459. mob_item_drop(md, dlist, ditem, 0, battle_config.autoloot_adjust ? drop_rate : md->db->dropitem[i].rate, homkillonly || merckillonly);
  2460. }
  2461. // Ore Discovery [Celest]
  2462. if (sd == mvp_sd && pc_checkskill(sd,BS_FINDINGORE)>0 && battle_config.finding_ore_rate/10 >= rnd()%10000) {
  2463. struct s_mob_drop mobdrop = {};
  2464. mobdrop.nameid = itemdb_group.get_random_item_id(IG_FINDINGORE,1);
  2465. ditem = mob_setdropitem(&mobdrop, 1, md->mob_id);
  2466. mob_item_drop(md, dlist, ditem, 0, battle_config.finding_ore_rate/10, homkillonly || merckillonly);
  2467. }
  2468. if(sd) {
  2469. // process script-granted extra drop bonuses
  2470. t_itemid dropid = 0;
  2471. for (const auto &it : sd->add_drop) {
  2472. if (!&it || (!it.nameid && !it.group))
  2473. continue;
  2474. if ((it.race < RC_NONE_ && it.race == -md->mob_id) || //Race < RC_NONE_, use mob_id
  2475. (it.race == RC_ALL || it.race == status->race) || //Matched race
  2476. (it.class_ == CLASS_ALL || it.class_ == status->class_)) //Matched class
  2477. {
  2478. //Check if the bonus item drop rate should be multiplied with mob level/10 [Lupus]
  2479. if (it.rate < 0) {
  2480. //It's negative, then it should be multiplied. with mob_level/10
  2481. //rate = base_rate * (mob_level/10) + 1
  2482. drop_rate = (-it.rate) * md->level / 10 + 1;
  2483. drop_rate = cap_value(drop_rate, max(battle_config.item_drop_adddrop_min,1), min(battle_config.item_drop_adddrop_max,10000));
  2484. }
  2485. else
  2486. //it's positive, then it goes as it is
  2487. drop_rate = it.rate;
  2488. if (rnd()%10000 >= drop_rate)
  2489. continue;
  2490. dropid = (it.nameid > 0) ? it.nameid : itemdb_group.get_random_item_id(it.group,1);
  2491. struct s_mob_drop mobdrop = {};
  2492. mobdrop.nameid = dropid;
  2493. mob_item_drop(md, dlist, mob_setdropitem(&mobdrop,1,md->mob_id), 0, drop_rate, homkillonly || merckillonly);
  2494. }
  2495. }
  2496. // process script-granted zeny bonus (get_zeny_num) [Skotlex]
  2497. if( sd->bonus.get_zeny_num && rnd()%100 < sd->bonus.get_zeny_rate ) {
  2498. i = sd->bonus.get_zeny_num > 0 ? sd->bonus.get_zeny_num : -md->level * sd->bonus.get_zeny_num;
  2499. if (!i) i = 1;
  2500. pc_getzeny(sd, 1+rnd()%i, LOG_TYPE_PICKDROP_MONSTER);
  2501. }
  2502. }
  2503. // process items looted by the mob
  2504. if (md->lootitems) {
  2505. for (i = 0; i < md->lootitem_count; i++)
  2506. mob_item_drop(md, dlist, mob_setlootitem(&md->lootitems[i], md->mob_id), 1, 10000, homkillonly || merckillonly);
  2507. }
  2508. // Process map specific drops
  2509. std::shared_ptr<s_map_drops> mapdrops;
  2510. // If it is an instance map, we check for map specific drops of the original map
  2511. if( map[md->bl.m].instance_id > 0 ){
  2512. mapdrops = map_drop_db.find( map[md->bl.m].instance_src_map );
  2513. }else{
  2514. mapdrops = map_drop_db.find( md->bl.m );
  2515. }
  2516. if( mapdrops != nullptr ){
  2517. // Process map wide drops
  2518. for( const auto& it : mapdrops->globals ){
  2519. if( rnd_chance( it.second->rate, 100000u ) ){
  2520. // 'Cheat' for autoloot command: rate is changed from n/100000 to n/10000
  2521. int32 map_drops_rate = max(1, (it.second->rate / 10));
  2522. mob_item_drop( md, dlist, mob_setdropitem( it.second.get(), 1, md->mob_id ), 0, map_drops_rate, (homkillonly || merckillonly) );
  2523. }
  2524. }
  2525. // Process map drops for this specific mob
  2526. const auto& specific = mapdrops->specific.find( md->mob_id );
  2527. if( specific != mapdrops->specific.end() ){
  2528. for( const auto& it : specific->second ){
  2529. if( rnd_chance( it.second->rate, 100000u ) ){
  2530. // 'Cheat' for autoloot command: rate is changed from n/100000 to n/10000
  2531. int32 map_drops_rate = max(1, (it.second->rate / 10));
  2532. mob_item_drop( md, dlist, mob_setdropitem( it.second.get(), 1, md->mob_id ), 0, map_drops_rate, (homkillonly || merckillonly) );
  2533. }
  2534. }
  2535. }
  2536. }
  2537. if (dlist->item) //There are drop items.
  2538. add_timer(tick + (!battle_config.delay_battle_damage?500:0), mob_delay_item_drop, 0, (intptr_t)dlist);
  2539. else //No drops
  2540. ers_free(item_drop_list_ers, dlist);
  2541. } else if (md->lootitems && md->lootitem_count) { //Loot MUST drop!
  2542. struct item_drop_list *dlist = ers_alloc(item_drop_list_ers, struct item_drop_list);
  2543. dlist->m = md->bl.m;
  2544. dlist->x = md->bl.x;
  2545. dlist->y = md->bl.y;
  2546. dlist->first_charid = (mvp_sd ? mvp_sd->status.char_id : 0);
  2547. dlist->second_charid = (second_sd ? second_sd->status.char_id : 0);
  2548. dlist->third_charid = (third_sd ? third_sd->status.char_id : 0);
  2549. dlist->item = NULL;
  2550. for (i = 0; i < md->lootitem_count; i++)
  2551. mob_item_drop(md, dlist, mob_setlootitem(&md->lootitems[i], md->mob_id), 1, 10000, homkillonly || merckillonly);
  2552. add_timer(tick + (!battle_config.delay_battle_damage?500:0), mob_delay_item_drop, 0, (intptr_t)dlist);
  2553. }
  2554. if( mvp_sd && md->get_bosstype() == BOSSTYPE_MVP ){
  2555. t_itemid log_mvp_nameid = 0;
  2556. t_exp log_mvp_exp = 0;
  2557. clif_mvp_effect( mvp_sd );
  2558. //mapflag: noexp check [Lorky]
  2559. if( md->db->mexp > 0 && !( map_getmapflag( m, MF_NOBASEEXP ) || type&2 ) ){
  2560. log_mvp_exp = md->db->mexp;
  2561. #if defined(RENEWAL_EXP)
  2562. int penalty = pc_level_penalty_mod( mvp_sd, PENALTY_MVP_EXP, nullptr, md );
  2563. log_mvp_exp = cap_value( apply_rate( log_mvp_exp, penalty ), 0, MAX_EXP );
  2564. #endif
  2565. if( battle_config.exp_bonus_attacker > 0 && count > 1 ){
  2566. if( count > battle_config.exp_bonus_max_attacker ){
  2567. count = battle_config.exp_bonus_max_attacker;
  2568. }
  2569. log_mvp_exp += log_mvp_exp * ( battle_config.exp_bonus_attacker * ( count - 1 ) ) / 100;
  2570. }
  2571. log_mvp_exp = cap_value( log_mvp_exp, 1, MAX_EXP );
  2572. clif_mvp_exp( mvp_sd, log_mvp_exp );
  2573. pc_gainexp( mvp_sd, &md->bl, log_mvp_exp, 0, 0 );
  2574. }
  2575. if( !(map_getmapflag(m, MF_NOMVPLOOT) || type&1) ) {
  2576. //Order might be random depending on item_drop_mvp_mode config setting
  2577. struct s_mob_drop mdrop[MAX_MVP_DROP_TOTAL];
  2578. memset(&mdrop,0,sizeof(mdrop));
  2579. if(battle_config.item_drop_mvp_mode == 1) {
  2580. //Random order
  2581. for(i = 0; i < MAX_MVP_DROP_TOTAL; i++) {
  2582. while( 1 ) {
  2583. uint8 va = rnd()%MAX_MVP_DROP_TOTAL;
  2584. if (mdrop[va].nameid == 0) {
  2585. if (md->db->mvpitem[i].nameid > 0)
  2586. memcpy(&mdrop[va],&md->db->mvpitem[i],sizeof(mdrop[va]));
  2587. break;
  2588. }
  2589. }
  2590. }
  2591. } else {
  2592. //Normal order
  2593. for(i = 0; i < MAX_MVP_DROP_TOTAL; i++) {
  2594. if (md->db->mvpitem[i].nameid > 0)
  2595. memcpy(&mdrop[i],&md->db->mvpitem[i],sizeof(mdrop[i]));
  2596. }
  2597. }
  2598. #if defined(RENEWAL_DROP)
  2599. int penalty = pc_level_penalty_mod( mvp_sd, PENALTY_MVP_DROP, nullptr, md );
  2600. #endif
  2601. for(i = 0; i < MAX_MVP_DROP_TOTAL; i++) {
  2602. if(mdrop[i].nameid == 0)
  2603. continue;
  2604. std::shared_ptr<item_data> i_data = item_db.find(mdrop[i].nameid);
  2605. if (i_data == nullptr)
  2606. continue;
  2607. temp = mdrop[i].rate;
  2608. #if defined(RENEWAL_DROP)
  2609. temp = cap_value( apply_rate( temp, penalty ), 0, 10000 );
  2610. #endif
  2611. if (temp != 10000) {
  2612. if(temp <= 0 && !battle_config.drop_rate0item)
  2613. temp = 1;
  2614. if(rnd()%10000 >= temp) //if ==0, then it doesn't drop
  2615. continue;
  2616. }
  2617. struct item item = {};
  2618. item.nameid=mdrop[i].nameid;
  2619. item.identify= itemdb_isidentified(item.nameid);
  2620. clif_mvp_item(mvp_sd,item.nameid);
  2621. log_mvp_nameid = item.nameid;
  2622. //A Rare MVP Drop Global Announce by Lupus
  2623. if(temp<=battle_config.rare_drop_announce) {
  2624. char message[128];
  2625. sprintf (message, msg_txt(NULL,541), mvp_sd->status.name, md->name, i_data->ename.c_str(), temp/100.);
  2626. //MSG: "'%s' won %s's %s (chance: %0.02f%%)"
  2627. intif_broadcast(message,strlen(message)+1,BC_DEFAULT);
  2628. }
  2629. mob_setdropitem_option(&item, &mdrop[i]);
  2630. if((temp = pc_additem(mvp_sd,&item,1,LOG_TYPE_PICKDROP_PLAYER)) != 0) {
  2631. clif_additem(mvp_sd,0,0,temp);
  2632. map_addflooritem(&item,1,mvp_sd->bl.m,mvp_sd->bl.x,mvp_sd->bl.y,mvp_sd->status.char_id,(second_sd?second_sd->status.char_id:0),(third_sd?third_sd->status.char_id:0),1,0,true);
  2633. }
  2634. if (i_data->flag.broadcast)
  2635. intif_broadcast_obtain_special_item(mvp_sd, item.nameid, md->mob_id, ITEMOBTAIN_TYPE_MONSTER_ITEM);
  2636. //Logs items, MVP prizes [Lupus]
  2637. log_pick_mob(md, LOG_TYPE_MVP, -1, &item);
  2638. //If item_drop_mvp_mode is not 2, then only one item should be granted
  2639. if(battle_config.item_drop_mvp_mode != 2) {
  2640. break;
  2641. }
  2642. }
  2643. }
  2644. log_mvpdrop(mvp_sd, md->mob_id, log_mvp_nameid, log_mvp_exp);
  2645. }
  2646. if (type&2 && !sd && md->mob_id == MOBID_EMPERIUM)
  2647. //Emperium destroyed by script. Discard mvp character. [Skotlex]
  2648. mvp_sd = NULL;
  2649. rebirth = ( md->sc.getSCE(SC_KAIZEL) || md->sc.getSCE(SC_ULTIMATE_S) || (md->sc.getSCE(SC_REBIRTH) && !md->state.rebirth) );
  2650. if( !rebirth ) { // Only trigger event on final kill
  2651. if( src ) {
  2652. switch( src->type ) { //allowed type
  2653. case BL_PET:
  2654. case BL_HOM:
  2655. case BL_MER:
  2656. case BL_ELEM:
  2657. case BL_MOB:
  2658. sd = BL_CAST(BL_PC,battle_get_master(src));
  2659. }
  2660. }
  2661. if (sd) {
  2662. std::shared_ptr<s_mob_db> mission_mdb = mob_db.find(sd->mission_mobid), mob = mob_db.find(md->mob_id);
  2663. if ((sd->mission_mobid == md->mob_id) || (mission_mdb != nullptr &&
  2664. ((battle_config.taekwon_mission_mobname == 1 && util::vector_exists(status_get_race2(&md->bl), RC2_GOBLIN) && util::vector_exists(mission_mdb->race2, RC2_GOBLIN)) ||
  2665. (battle_config.taekwon_mission_mobname == 2 && mob->jname.compare(mission_mdb->jname) == 0))))
  2666. { //TK_MISSION [Skotlex]
  2667. if (++(sd->mission_count) >= 100 && (temp = mob_get_random_id(MOBG_BRANCH_OF_DEAD_TREE, static_cast<e_random_monster_flags>(RMF_CHECK_MOB_LV|RMF_MOB_NOT_BOSS|RMF_MOB_NOT_SPAWN), sd->status.base_level)))
  2668. {
  2669. pc_addfame(*sd, battle_config.fame_taekwon_mission);
  2670. sd->mission_mobid = temp;
  2671. pc_setglobalreg(sd, add_str(TKMISSIONID_VAR), temp);
  2672. sd->mission_count = 0;
  2673. clif_mission_info(sd, temp, 0);
  2674. }
  2675. pc_setglobalreg(sd, add_str(TKMISSIONCOUNT_VAR), sd->mission_count);
  2676. }
  2677. if (sd->status.party_id)
  2678. map_foreachinallrange(quest_update_objective_sub, &md->bl, AREA_SIZE, BL_PC, sd->status.party_id, md);
  2679. else if (sd->avail_quests)
  2680. quest_update_objective(sd, md);
  2681. if (achievement_db.mobexists(md->mob_id)) {
  2682. if (battle_config.achievement_mob_share > 0 && sd->status.party_id > 0)
  2683. map_foreachinallrange(achievement_update_objective_sub, &md->bl, AREA_SIZE, BL_PC, sd->status.party_id, md->mob_id);
  2684. else
  2685. achievement_update_objective(sd, AG_BATTLE, 1, md->mob_id);
  2686. }
  2687. // The master or Mercenary can increase the kill count
  2688. if (sd->md && src && (src->type == BL_PC || src->type == BL_MER) && mob->lv > sd->status.base_level / 2)
  2689. mercenary_kills(sd->md);
  2690. }
  2691. if( md->npc_event[0] && !md->state.npc_killmonster ) {
  2692. if( sd && battle_config.mob_npc_event_type ) {
  2693. pc_setparam(sd, SP_KILLEDGID, md->bl.id);
  2694. pc_setparam(sd, SP_KILLEDRID, md->mob_id);
  2695. pc_setparam(sd, SP_KILLERRID, sd->bl.id);
  2696. npc_event(sd,md->npc_event,0);
  2697. } else if( mvp_sd ) {
  2698. pc_setparam(mvp_sd, SP_KILLEDGID, md->bl.id);
  2699. pc_setparam(mvp_sd, SP_KILLEDRID, md->mob_id);
  2700. pc_setparam(mvp_sd, SP_KILLERRID, sd?sd->bl.id:0);
  2701. npc_event(mvp_sd,md->npc_event,0);
  2702. } else
  2703. npc_event_do(md->npc_event);
  2704. } else if( mvp_sd && !md->state.npc_killmonster ) {
  2705. pc_setparam(mvp_sd, SP_KILLEDGID, md->bl.id);
  2706. pc_setparam(mvp_sd, SP_KILLEDRID, md->mob_id);
  2707. npc_script_event(mvp_sd, NPCE_KILLNPC); // PCKillNPC [Lance]
  2708. }
  2709. }
  2710. if(md->deletetimer != INVALID_TIMER) {
  2711. delete_timer(md->deletetimer,mob_timer_delete);
  2712. md->deletetimer = INVALID_TIMER;
  2713. }
  2714. /**
  2715. * Only loops if necessary (e.g. a poring would never need to loop)
  2716. **/
  2717. if( md->can_summon )
  2718. mob_deleteslave(md);
  2719. map_freeblock_unlock();
  2720. if( !rebirth ) {
  2721. if( pcdb_checkid(md->vd->class_) ) {//Player mobs are not removed automatically by the client.
  2722. /* first we set them dead, then we delay the outsight effect */
  2723. clif_clearunit_area(&md->bl,CLR_DEAD);
  2724. clif_clearunit_delayed(&md->bl, CLR_OUTSIGHT,tick+3000);
  2725. } else
  2726. /**
  2727. * We give the client some time to breath and this allows it to display anything it'd like with the dead corpose
  2728. * For example, this delay allows it to display soul drain effect
  2729. **/
  2730. clif_clearunit_delayed(&md->bl, CLR_DEAD, tick+250);
  2731. }
  2732. if(!md->spawn){ //Tell status_damage to remove it from memory.
  2733. struct unit_data *ud = unit_bl2ud(&md->bl);
  2734. // If the unit is currently in a walk script, it will be removed there
  2735. return ud->state.walk_script ? 3 : 5; // Note: Actually, it's 4. Oh well...
  2736. }
  2737. // MvP tomb [GreenBox]
  2738. if (battle_config.mvp_tomb_enabled && md->spawn->state.boss && map_getmapflag(md->bl.m, MF_NOTOMB) != 1)
  2739. mvptomb_create(md, mvp_sd ? mvp_sd->status.name : NULL, time(NULL));
  2740. if( !rebirth )
  2741. mob_setdelayspawn(md); //Set respawning.
  2742. return 3; //Remove from map.
  2743. }
  2744. /**
  2745. * Resurrects a mob (reset values and respawn on map)
  2746. * @param md : mob pointer
  2747. * @param hp : hp to resurrect it with (only used for exp calculation)
  2748. */
  2749. void mob_revive(struct mob_data *md, unsigned int hp)
  2750. {
  2751. t_tick tick = gettick();
  2752. md->state.skillstate = MSS_IDLE;
  2753. md->last_thinktime = tick;
  2754. md->next_walktime = tick+rnd()%1000+MIN_RANDOMWALKTIME;
  2755. md->last_linktime = tick;
  2756. md->last_pcneartime = 0;
  2757. //We reset the damage log and then set the already lost damage as self damage so players don't get exp for it [Playtester]
  2758. memset(md->dmglog, 0, sizeof(md->dmglog));
  2759. mob_log_damage(md, &md->bl, md->status.max_hp - hp);
  2760. md->tdmg = 0;
  2761. if (!md->bl.prev){
  2762. if(map_addblock(&md->bl))
  2763. return;
  2764. }
  2765. clif_spawn(&md->bl);
  2766. skill_unit_move(&md->bl,tick,1);
  2767. mobskill_use(md, tick, MSC_SPAWN);
  2768. if (battle_config.show_mob_info&3)
  2769. clif_name_area(&md->bl);
  2770. }
  2771. int mob_guardian_guildchange(struct mob_data *md)
  2772. {
  2773. nullpo_ret(md);
  2774. if (!md->guardian_data)
  2775. return 0;
  2776. if (md->guardian_data->castle->guild_id == 0)
  2777. { //Castle with no owner? Delete the guardians.
  2778. if (md->mob_id == MOBID_EMPERIUM)
  2779. { //But don't delete the emperium, just clear it's guild-data
  2780. md->guardian_data->guild_id = 0;
  2781. md->guardian_data->emblem_id = 0;
  2782. md->guardian_data->guild_name[0] = '\0';
  2783. } else {
  2784. if (md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS && md->guardian_data->castle->guardian[md->guardian_data->number].visible)
  2785. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number, 0);
  2786. unit_free(&md->bl,CLR_OUTSIGHT); //Remove guardian.
  2787. }
  2788. return 0;
  2789. }
  2790. auto g = guild_search(md->guardian_data->castle->guild_id);
  2791. if (g == NULL)
  2792. { //Properly remove guardian info from Castle data.
  2793. ShowError("mob_guardian_guildchange: New Guild (id %d) does not exists!\n", md->guardian_data->guild_id);
  2794. if (md->guardian_data->number >= 0 && md->guardian_data->number < MAX_GUARDIANS)
  2795. guild_castledatasave(md->guardian_data->castle->castle_id, CD_ENABLED_GUARDIAN00 + md->guardian_data->number, 0);
  2796. unit_free(&md->bl,CLR_OUTSIGHT);
  2797. return 0;
  2798. }
  2799. md->guardian_data->guild_id = g->guild.guild_id;
  2800. md->guardian_data->emblem_id = g->guild.emblem_id;
  2801. md->guardian_data->guardup_lv = guild_checkskill(g->guild, GD_GUARDUP);
  2802. memcpy(md->guardian_data->guild_name, g->guild.name, NAME_LENGTH);
  2803. return 1;
  2804. }
  2805. /*==========================================
  2806. * Pick a random class for the mob
  2807. *------------------------------------------*/
  2808. int mob_random_class(int *value, size_t count)
  2809. {
  2810. nullpo_ret(value);
  2811. // no count specified, look into the array manually, but take only max 5 elements
  2812. if (count < 1) {
  2813. count = 0;
  2814. while(count < 5 && mobdb_checkid(value[count])) count++;
  2815. if(count < 1) // nothing found
  2816. return 0;
  2817. } else {
  2818. // check if at least the first value is valid
  2819. if(mobdb_checkid(value[0]) == 0)
  2820. return 0;
  2821. }
  2822. //Pick a random value, hoping it exists. [Skotlex]
  2823. return mobdb_checkid(value[rnd()%count]);
  2824. }
  2825. /**
  2826. * Returns the SpawnInfos of the mob_db entry (mob_spawn_data[mobid])
  2827. * if mobid is not in mob_spawn_data returns empty spawn_info vector
  2828. * @param mob_id - Looking for spawns of this Monster ID
  2829. */
  2830. const std::vector<spawn_info> mob_get_spawns(uint16 mob_id)
  2831. {
  2832. auto mob_spawn_it = mob_spawn_data.find(mob_id);
  2833. if ( mob_spawn_it != mob_spawn_data.end() )
  2834. return mob_spawn_it->second;
  2835. return std::vector<spawn_info>();
  2836. }
  2837. /**
  2838. * Checks if a monster is spawned. Returns true if yes, false otherwise.
  2839. * @param mob_id - Monster ID which is checked
  2840. */
  2841. bool mob_has_spawn(uint16 mob_id)
  2842. {
  2843. // It's enough to check if the monster is in mob_spawn_data, because
  2844. // none or empty spawns are ignored. Thus the monster is spawned.
  2845. return mob_spawn_data.find(mob_id) != mob_spawn_data.end();
  2846. }
  2847. /**
  2848. * Adds a spawn info to the specific mob. (To mob_spawn_data)
  2849. * @param mob_id - Monster ID spawned
  2850. * @param new_spawn - spawn_info holding the map and quantity of the spawn
  2851. */
  2852. void mob_add_spawn(uint16 mob_id, const struct spawn_info& new_spawn)
  2853. {
  2854. unsigned short m = new_spawn.mapindex;
  2855. if( new_spawn.qty <= 0 )
  2856. return; //ignore empty spawns
  2857. std::vector<spawn_info>& spawns = mob_spawn_data[mob_id];
  2858. // Search if the map is already in spawns
  2859. auto itSameMap = std::find_if(spawns.begin(), spawns.end(),
  2860. [&m] (const spawn_info &s) { return (s.mapindex == m); });
  2861. if( itSameMap != spawns.end() )
  2862. itSameMap->qty += new_spawn.qty; // add quantity, if map is found
  2863. else
  2864. spawns.push_back(new_spawn); // else, add the whole spawn info
  2865. // sort spawns by spawn quantity
  2866. std::sort(spawns.begin(), spawns.end(),
  2867. [](const spawn_info & a, const spawn_info & b) -> bool
  2868. { return a.qty > b.qty; });
  2869. /** Note
  2870. Spawns are sorted after every addition. This makes reloadscript slower, but
  2871. some spawns may be added directly by loadscript or something similar.
  2872. */
  2873. }
  2874. /*==========================================
  2875. * Change mob base class
  2876. *------------------------------------------*/
  2877. int mob_class_change (struct mob_data *md, int mob_id)
  2878. {
  2879. t_tick tick = gettick();
  2880. int i, hp_rate;
  2881. nullpo_ret(md);
  2882. if( md->bl.prev == NULL )
  2883. return 0;
  2884. if (!mob_id || !mobdb_checkid(mob_id))
  2885. return 0;
  2886. //Disable class changing for some targets...
  2887. if (md->guardian_data)
  2888. return 0; //Guardians/Emperium
  2889. if (util::vector_exists(status_get_race2(&md->bl), RC2_TREASURE))
  2890. return 0; //Treasure Boxes
  2891. if( md->special_state.ai > AI_ATTACK )
  2892. return 0; //Marine Spheres and Floras.
  2893. if( mob_is_clone(md->mob_id) )
  2894. return 0; //Clones
  2895. if( md->mob_id == mob_id )
  2896. return 0; //Nothing to change.
  2897. hp_rate = get_percentage(md->status.hp, md->status.max_hp);
  2898. md->mob_id = mob_id;
  2899. md->db = mob_db.find(mob_id);
  2900. if (battle_config.override_mob_names==1)
  2901. memcpy(md->name,md->db->name.c_str(),NAME_LENGTH);
  2902. else
  2903. memcpy(md->name,md->db->jname.c_str(),NAME_LENGTH);
  2904. status_change_end(&md->bl,SC_KEEPING); // End before calling status_calc_mob().
  2905. status_change_end(&md->bl,SC_BARRIER);
  2906. mob_stop_attack(md);
  2907. mob_stop_walking(md, 0);
  2908. unit_skillcastcancel(&md->bl, 0);
  2909. status_set_viewdata(&md->bl, mob_id);
  2910. clif_mob_class_change(md,md->vd->class_);
  2911. status_calc_mob(md,SCO_FIRST);
  2912. md->ud.state.speed_changed = 1; //Speed change update.
  2913. if (battle_config.monster_class_change_recover) {
  2914. memset(md->dmglog, 0, sizeof(md->dmglog));
  2915. md->tdmg = 0;
  2916. } else {
  2917. md->status.hp = md->status.max_hp*hp_rate/100;
  2918. if(md->status.hp < 1) md->status.hp = 1;
  2919. }
  2920. t_tick c = tick - MOB_MAX_DELAY;
  2921. for(i=0;i<MAX_MOBSKILL;i++)
  2922. md->skilldelay[i] = c;
  2923. if (md->lootitems == NULL && status_has_mode(&md->db->status,MD_LOOTER))
  2924. md->lootitems = (struct s_mob_lootitem *)aCalloc(LOOTITEM_SIZE,sizeof(struct s_mob_lootitem));
  2925. //Targets should be cleared no morph
  2926. md->target_id = md->attacked_id = md->norm_attacked_id = 0;
  2927. //Need to update name display.
  2928. clif_name_area(&md->bl);
  2929. return 0;
  2930. }
  2931. /*==========================================
  2932. * mob heal, update display hp info of mob for players
  2933. *------------------------------------------*/
  2934. void mob_heal(struct mob_data *md,unsigned int heal)
  2935. {
  2936. if (battle_config.show_mob_info&3)
  2937. clif_name_area(&md->bl);
  2938. #if PACKETVER >= 20120404
  2939. if (battle_config.monster_hp_bars_info && !map_getmapflag(md->bl.m, MF_HIDEMOBHPBAR)) {
  2940. int i;
  2941. if (md->special_state.ai == AI_ABR || md->special_state.ai == AI_BIONIC) {
  2942. clif_summon_hp_bar(*md);
  2943. }
  2944. for(i = 0; i < DAMAGELOG_SIZE; i++)// must show hp bar to all char who already hit the mob.
  2945. if( md->dmglog[i].id ) {
  2946. map_session_data *sd = map_charid2sd(md->dmglog[i].id);
  2947. if( sd && check_distance_bl(&md->bl, &sd->bl, AREA_SIZE) ) // check if in range
  2948. clif_monster_hp_bar(md, sd->fd);
  2949. }
  2950. }
  2951. #endif
  2952. }
  2953. /*==========================================
  2954. * Added by RoVeRT
  2955. *------------------------------------------*/
  2956. int mob_warpslave_sub(struct block_list *bl,va_list ap)
  2957. {
  2958. struct mob_data *md=(struct mob_data *)bl;
  2959. struct block_list *master;
  2960. short x,y,range=0;
  2961. master = va_arg(ap, struct block_list*);
  2962. range = va_arg(ap, int);
  2963. if(md->master_id!=master->id)
  2964. return 0;
  2965. map_search_freecell(master, 0, &x, &y, range, range, 0);
  2966. unit_warp(&md->bl, master->m, x, y,CLR_TELEPORT);
  2967. return 1;
  2968. }
  2969. /*==========================================
  2970. * Added by RoVeRT
  2971. * Warps slaves. Range is the area around the master that they can
  2972. * appear in randomly.
  2973. *------------------------------------------*/
  2974. int mob_warpslave(struct block_list *bl, int range)
  2975. {
  2976. if (range < 1)
  2977. range = 1; //Min range needed to avoid crashes and stuff. [Skotlex]
  2978. return map_foreachinmap(mob_warpslave_sub, bl->m, BL_MOB, bl, range);
  2979. }
  2980. /*==========================================
  2981. * Counts slave sub, curently checking if mob master is the given ID.
  2982. *------------------------------------------*/
  2983. int mob_countslave_sub(struct block_list *bl,va_list ap)
  2984. {
  2985. int id;
  2986. struct mob_data *md;
  2987. id=va_arg(ap,int);
  2988. md = (struct mob_data *)bl;
  2989. if( md->master_id==id )
  2990. return 1;
  2991. return 0;
  2992. }
  2993. /*==========================================
  2994. * Counts the number of slaves a mob has on the map.
  2995. *------------------------------------------*/
  2996. int mob_countslave(struct block_list *bl)
  2997. {
  2998. return map_foreachinmap(mob_countslave_sub, bl->m, BL_MOB,bl->id);
  2999. }
  3000. /*==========================================
  3001. * Summons amount slaves contained in the value[5] array using round-robin. [adapted by Skotlex]
  3002. *------------------------------------------*/
  3003. int mob_summonslave(struct mob_data *md2,int *value,int amount,uint16 skill_id)
  3004. {
  3005. struct mob_data *md;
  3006. struct spawn_data data;
  3007. int count = 0,k=0,hp_rate=0;
  3008. nullpo_ret(md2);
  3009. nullpo_ret(value);
  3010. memset(&data, 0, sizeof(struct spawn_data));
  3011. data.m = md2->bl.m;
  3012. data.x = md2->bl.x;
  3013. data.y = md2->bl.y;
  3014. data.num = 1;
  3015. data.state.size = md2->special_state.size;
  3016. data.state.ai = md2->special_state.ai;
  3017. if(mobdb_checkid(value[0]) == 0)
  3018. return 0;
  3019. /**
  3020. * Flags this monster is able to summon; saves a worth amount of memory upon deletion
  3021. **/
  3022. md2->can_summon = 1;
  3023. while(count < 5 && mobdb_checkid(value[count])) count++;
  3024. if(count < 1) return 0;
  3025. if (amount > 0 && amount < count) { //Do not start on 0, pick some random sub subset [Skotlex]
  3026. k = rnd()%count;
  3027. amount+=k; //Increase final value by same amount to preserve total number to summon.
  3028. }
  3029. if (!battle_config.monster_class_change_recover &&
  3030. (skill_id == NPC_TRANSFORMATION || skill_id == NPC_METAMORPHOSIS))
  3031. hp_rate = get_percentage(md2->status.hp, md2->status.max_hp);
  3032. for(;k<amount;k++) {
  3033. short x,y;
  3034. data.id = value[k%count]; //Summon slaves in round-robin fashion. [Skotlex]
  3035. if (mobdb_checkid(data.id) == 0)
  3036. continue;
  3037. if (skill_id != NPC_DEATHSUMMON && map_search_freecell(&md2->bl, 0, &x, &y, MOB_SLAVEDISTANCE, MOB_SLAVEDISTANCE, 0)) {
  3038. data.x = x;
  3039. data.y = y;
  3040. } else {
  3041. data.x = md2->bl.x;
  3042. data.y = md2->bl.y;
  3043. }
  3044. //These two need to be loaded from the db for each slave.
  3045. if(battle_config.override_mob_names==1)
  3046. strcpy(data.name,"--en--");
  3047. else
  3048. strcpy(data.name,"--ja--");
  3049. if (!mob_parse_dataset(&data))
  3050. continue;
  3051. md= mob_spawn_dataset(&data);
  3052. if(skill_id == NPC_SUMMONSLAVE){
  3053. md->master_id=md2->bl.id;
  3054. md->special_state.ai = md2->special_state.ai;
  3055. }
  3056. mob_spawn(md);
  3057. if (hp_rate) //Scale HP
  3058. md->status.hp = md->status.max_hp*hp_rate/100;
  3059. if (skill_id == NPC_SUMMONSLAVE) // Only appies to NPC_SUMMONSLAVE
  3060. status_calc_slave_mode(md, md2); // Inherit the aggressive mode of the master.
  3061. if (md2->state.copy_master_mode)
  3062. md->status.mode = md2->status.mode;
  3063. clif_skill_nodamage(&md->bl,&md->bl,skill_id,amount,1);
  3064. }
  3065. return 0;
  3066. }
  3067. /*==========================================
  3068. * MOBskill lookup (get skillindex through skill_id)
  3069. * Returns -1 if not found.
  3070. *------------------------------------------*/
  3071. int mob_skill_id2skill_idx(int mob_id,uint16 skill_id)
  3072. {
  3073. std::shared_ptr<s_mob_db> mob = mob_db.find(mob_id);
  3074. if (mob == nullptr)
  3075. return -1;
  3076. std::vector<std::shared_ptr<s_mob_skill>> &skills = mob->skill;
  3077. if (skills.empty())
  3078. return -1;
  3079. for (int i = 0; i < skills.size(); i++) {
  3080. if (skills[i]->skill_id == skill_id)
  3081. return i;
  3082. }
  3083. return -1;
  3084. }
  3085. /*==========================================
  3086. * Friendly Mob whose HP is decreasing by a nearby MOB is looked for.
  3087. *------------------------------------------*/
  3088. int mob_getfriendhprate_sub(struct block_list *bl,va_list ap)
  3089. {
  3090. int64 min_rate, max_rate,rate;
  3091. struct block_list **fr;
  3092. struct mob_data *md;
  3093. md = va_arg(ap,struct mob_data *);
  3094. min_rate=va_arg(ap,int64);
  3095. max_rate=va_arg(ap,int64);
  3096. fr=va_arg(ap,struct block_list **);
  3097. if( md->bl.id == bl->id && !(battle_config.mob_ai&0x10))
  3098. return 0;
  3099. if ((*fr) != NULL) //A friend was already found.
  3100. return 0;
  3101. if (battle_check_target(&md->bl,bl,BCT_ENEMY)>0)
  3102. return 0;
  3103. rate = get_percentage(status_get_hp(bl), status_get_max_hp(bl));
  3104. if (rate >= min_rate && rate <= max_rate)
  3105. (*fr) = bl;
  3106. return 1;
  3107. }
  3108. static struct block_list *mob_getfriendhprate(struct mob_data *md,int64 min_rate,int64 max_rate)
  3109. {
  3110. struct block_list *fr=NULL;
  3111. int type = BL_MOB;
  3112. nullpo_retr(NULL, md);
  3113. if (md->special_state.ai) //Summoned creatures. [Skotlex]
  3114. type = BL_PC;
  3115. map_foreachinallrange(mob_getfriendhprate_sub, &md->bl, 8, type,md,min_rate,max_rate,&fr);
  3116. return fr;
  3117. }
  3118. /*==========================================
  3119. * Check hp rate of its master
  3120. *------------------------------------------*/
  3121. struct block_list *mob_getmasterhpltmaxrate(struct mob_data *md,int64 rate)
  3122. {
  3123. if( md && md->master_id > 0 )
  3124. {
  3125. struct block_list *bl = map_id2bl(md->master_id);
  3126. if( bl && get_percentage(status_get_hp(bl), status_get_max_hp(bl)) < rate )
  3127. return bl;
  3128. }
  3129. return NULL;
  3130. }
  3131. bool mob_getstatus_sub( struct mob_data& md, e_mob_skill_condition condition, sc_type type ){
  3132. bool found = false;
  3133. if( type == SC_NONE ){
  3134. for( int i = SC_COMMON_MIN; i <= SC_COMMON_MAX; i++ ){
  3135. if( md.sc.getSCE( i ) != nullptr ){
  3136. // Once an effect was found, break out. [Skotlex]
  3137. found = true;
  3138. break;
  3139. }
  3140. }
  3141. }else{
  3142. found = md.sc.getSCE( type ) != nullptr;
  3143. }
  3144. switch( condition ){
  3145. case MSC_MYSTATUSON:
  3146. case MSC_FRIENDSTATUSON:
  3147. return found;
  3148. case MSC_MYSTATUSOFF:
  3149. case MSC_FRIENDSTATUSOFF:
  3150. return !found;
  3151. default:
  3152. return false;
  3153. }
  3154. }
  3155. /*==========================================
  3156. * What a status state suits by nearby MOB is looked for.
  3157. *------------------------------------------*/
  3158. int mob_getfriendstatus_sub( struct block_list *bl, va_list ap ){
  3159. struct mob_data *md, *mmd;
  3160. nullpo_ret(bl);
  3161. nullpo_ret(md=(struct mob_data *)bl);
  3162. nullpo_ret(mmd=va_arg(ap,struct mob_data *));
  3163. if( mmd->bl.id == bl->id && !(battle_config.mob_ai&0x10) )
  3164. return 0;
  3165. if (battle_check_target(&mmd->bl,bl,BCT_ENEMY)>0)
  3166. return 0;
  3167. int64 cond1 = va_arg( ap, int64 );
  3168. int64 cond2 = va_arg( ap, int64 );
  3169. struct mob_data** fr = va_arg( ap, struct mob_data** );
  3170. if( mob_getstatus_sub( *md, static_cast<e_mob_skill_condition>( cond1 ), static_cast<sc_type>( cond2 ) ) ){
  3171. *fr = md;
  3172. }
  3173. return 0;
  3174. }
  3175. struct mob_data *mob_getfriendstatus(struct mob_data *md,int64 cond1,int64 cond2)
  3176. {
  3177. struct mob_data* fr = NULL;
  3178. nullpo_ret(md);
  3179. map_foreachinallrange(mob_getfriendstatus_sub, &md->bl, 8,BL_MOB, md,cond1,cond2,&fr);
  3180. return fr;
  3181. }
  3182. // Display message from mob_chat_db.yml
  3183. bool mob_chat_display_message(mob_data &md, uint16 msg_id) {
  3184. std::shared_ptr<s_mob_chat> mc = mob_chat_db.find(msg_id);
  3185. if (mc != nullptr) {
  3186. std::string name = md.name, output;
  3187. std::size_t unique = name.find("#");
  3188. if (unique != std::string::npos)
  3189. name = name.substr(0, unique); // discard extra name identifier if present [Daegaladh]
  3190. output = name + " : " + mc->msg;
  3191. clif_messagecolor(&md.bl, mc->color, output.c_str(), true, AREA_CHAT_WOC);
  3192. return true;
  3193. }
  3194. return false;
  3195. }
  3196. /*==========================================
  3197. * Skill use judging
  3198. *------------------------------------------*/
  3199. int mobskill_use(struct mob_data *md, t_tick tick, int event, int64 damage)
  3200. {
  3201. struct block_list *fbl = NULL; //Friend bl, which can either be a BL_PC or BL_MOB depending on the situation. [Skotlex]
  3202. struct block_list *bl;
  3203. struct mob_data *fmd = NULL;
  3204. int i,j,n;
  3205. short skill_target;
  3206. nullpo_ret(md);
  3207. std::vector<std::shared_ptr<s_mob_skill>> &ms = md->db->skill;
  3208. if (!battle_config.mob_skill_rate || md->ud.skilltimer != INVALID_TIMER || ms.empty() || status_has_mode(&md->status,MD_NOCAST))
  3209. return 0;
  3210. if (event == -1 && DIFF_TICK(md->ud.canact_tick, tick) > 0)
  3211. return 0; //Skill act delay only affects non-event skills.
  3212. //Pick a starting position and loop from that.
  3213. i = battle_config.mob_ai&0x100?rnd()%ms.size():0;
  3214. for (n = 0; n < ms.size(); i++, n++) {
  3215. int64 c2;
  3216. int flag = 0;
  3217. if (i == ms.size())
  3218. i = 0;
  3219. if (DIFF_TICK(tick, md->skilldelay[i]) < ms[i]->delay)
  3220. continue;
  3221. c2 = ms[i]->cond2;
  3222. if (ms[i]->state != md->state.skillstate) {
  3223. if (md->state.skillstate != MSS_DEAD && (ms[i]->state == MSS_ANY ||
  3224. (ms[i]->state == MSS_ANYTARGET && md->target_id && md->state.skillstate != MSS_LOOT)
  3225. )) //ANYTARGET works with any state as long as there's a target. [Skotlex]
  3226. ;
  3227. else
  3228. continue;
  3229. }
  3230. if (rnd() % 10000 > ms[i]->permillage) //Lupus (max value = 10000)
  3231. continue;
  3232. if (ms[i]->cond1 == event)
  3233. flag = 1; //Trigger skill.
  3234. else if (ms[i]->cond1 == MSC_SKILLUSED)
  3235. flag = ((event & 0xffff) == MSC_SKILLUSED && ((event >> 16) == c2 || c2 == 0));
  3236. else if (ms[i]->cond1 == MSC_GROUNDATTACKED && damage > 0)
  3237. flag = ((event & 0xffff) == MSC_SKILLUSED && skill_get_inf((event >> 16))&INF_GROUND_SKILL);
  3238. else if (ms[i]->cond1 == MSC_DAMAGEDGT && damage > 0 && !((event & 0xffff) == MSC_SKILLUSED)) //Avoid double check if skill has been used [datawulf]
  3239. flag = (damage > c2);
  3240. else if(event == -1){
  3241. //Avoid entering on defined events to avoid "hyper-active skill use" due to the overflow of calls to this function in battle.
  3242. switch (ms[i]->cond1)
  3243. {
  3244. case MSC_ALWAYS:
  3245. flag = 1; break;
  3246. case MSC_MYHPLTMAXRATE: // HP< maxhp%
  3247. flag = get_percentage(md->status.hp, md->status.max_hp);
  3248. flag = (flag <= c2);
  3249. break;
  3250. case MSC_MYHPINRATE:
  3251. flag = get_percentage(md->status.hp, md->status.max_hp);
  3252. flag = (flag >= c2 && flag <= ms[i]->val[0]);
  3253. break;
  3254. case MSC_MYSTATUSON: // status[num] on
  3255. case MSC_MYSTATUSOFF: // status[num] off
  3256. if( !md->sc.count ){
  3257. flag = 0;
  3258. }else if( mob_getstatus_sub( *md, static_cast<e_mob_skill_condition>( ms[i]->cond1 ), static_cast<sc_type>( ms[i]->cond2 ) ) ){
  3259. flag = 1;
  3260. }else{
  3261. flag = 0;
  3262. }
  3263. break;
  3264. case MSC_FRIENDHPLTMAXRATE: // friend HP < maxhp%
  3265. flag = ((fbl = mob_getfriendhprate(md, 0, ms[i]->cond2)) != NULL); break;
  3266. case MSC_FRIENDHPINRATE :
  3267. flag = ((fbl = mob_getfriendhprate(md, ms[i]->cond2, ms[i]->val[0])) != NULL); break;
  3268. case MSC_FRIENDSTATUSON: // friend status[num] on
  3269. case MSC_FRIENDSTATUSOFF: // friend status[num] off
  3270. flag = ((fmd = mob_getfriendstatus(md, ms[i]->cond1, ms[i]->cond2)) != NULL); break;
  3271. case MSC_SLAVELT: // slave < num
  3272. flag = (mob_countslave(&md->bl) < c2 ); break;
  3273. case MSC_ATTACKPCGT: // attack pc > num
  3274. flag = (unit_counttargeted(&md->bl) > c2); break;
  3275. case MSC_SLAVELE: // slave <= num
  3276. flag = (mob_countslave(&md->bl) <= c2 ); break;
  3277. case MSC_ATTACKPCGE: // attack pc >= num
  3278. flag = (unit_counttargeted(&md->bl) >= c2); break;
  3279. case MSC_AFTERSKILL:
  3280. flag = (md->ud.skill_id == c2); break;
  3281. case MSC_RUDEATTACKED:
  3282. flag = (md->state.attacked_count >= RUDE_ATTACKED_COUNT);
  3283. if (flag) md->state.attacked_count = 0; //Rude attacked count should be reset after the skill condition is met. Thanks to Komurka [Skotlex]
  3284. break;
  3285. case MSC_MASTERHPLTMAXRATE:
  3286. flag = ((fbl = mob_getmasterhpltmaxrate(md, ms[i]->cond2)) != NULL); break;
  3287. case MSC_MASTERATTACKED:
  3288. flag = (md->master_id > 0 && (fbl=map_id2bl(md->master_id)) && unit_counttargeted(fbl) > 0); break;
  3289. case MSC_ALCHEMIST:
  3290. flag = (md->state.can_escape); break;
  3291. case MSC_MOBNEARBYGT:
  3292. flag = (map_foreachinallrange(mob_count_sub, &md->bl, AREA_SIZE, BL_MOB) > c2 ); break;
  3293. }
  3294. }
  3295. if (!flag)
  3296. continue; //Skill requisite failed to be fulfilled.
  3297. //Execute skill
  3298. skill_target = status_has_mode(&md->db->status,MD_RANDOMTARGET) ? MST_RANDOM : ms[i]->target;
  3299. if (skill_get_casttype(ms[i]->skill_id) == CAST_GROUND)
  3300. { //Ground skill.
  3301. short x, y;
  3302. switch (skill_target) {
  3303. case MST_RANDOM: //Pick a random enemy within skill range.
  3304. bl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md),
  3305. skill_get_range2(&md->bl, ms[i]->skill_id, ms[i]->skill_lv, true));
  3306. break;
  3307. case MST_TARGET:
  3308. case MST_AROUND5:
  3309. case MST_AROUND6:
  3310. case MST_AROUND7:
  3311. case MST_AROUND8:
  3312. bl = map_id2bl(md->target_id);
  3313. break;
  3314. case MST_MASTER:
  3315. bl = &md->bl;
  3316. if (md->master_id)
  3317. bl = map_id2bl(md->master_id);
  3318. if (bl) //Otherwise, fall through.
  3319. break;
  3320. case MST_FRIEND:
  3321. bl = fbl?fbl:(fmd?&fmd->bl:&md->bl);
  3322. break;
  3323. default:
  3324. bl = &md->bl;
  3325. break;
  3326. }
  3327. if (!bl) {
  3328. if (battle_config.mob_ai & 0x1000)
  3329. continue;
  3330. else
  3331. break;
  3332. }
  3333. x = bl->x;
  3334. y = bl->y;
  3335. // Look for an area to cast the spell around...
  3336. if (skill_target >= MST_AROUND5) {
  3337. j = skill_target >= MST_AROUND1?
  3338. (skill_target-MST_AROUND1) +1:
  3339. (skill_target-MST_AROUND5) +1;
  3340. map_search_freecell(&md->bl, md->bl.m, &x, &y, j, j, 3);
  3341. }
  3342. md->skill_idx = i;
  3343. map_freeblock_lock();
  3344. if (!battle_check_range(&md->bl, bl, skill_get_range2(&md->bl, ms[i]->skill_id, ms[i]->skill_lv, true)) ||
  3345. !unit_skilluse_pos2(&md->bl, x, y, ms[i]->skill_id, ms[i]->skill_lv, ms[i]->casttime, ms[i]->cancel))
  3346. {
  3347. map_freeblock_unlock();
  3348. if (battle_config.mob_ai & 0x1000)
  3349. continue;
  3350. else
  3351. break;
  3352. }
  3353. } else {
  3354. //Targetted skill
  3355. switch (skill_target) {
  3356. case MST_RANDOM: //Pick a random enemy within skill range.
  3357. bl = battle_getenemy(&md->bl, DEFAULT_ENEMY_TYPE(md),
  3358. skill_get_range2(&md->bl, ms[i]->skill_id, ms[i]->skill_lv, true));
  3359. break;
  3360. case MST_TARGET:
  3361. bl = map_id2bl(md->target_id);
  3362. break;
  3363. case MST_MASTER:
  3364. bl = &md->bl;
  3365. if (md->master_id)
  3366. bl = map_id2bl(md->master_id);
  3367. if (bl) //Otherwise, fall through.
  3368. break;
  3369. case MST_FRIEND:
  3370. if (fbl) {
  3371. bl = fbl;
  3372. break;
  3373. } else if (fmd) {
  3374. bl = &fmd->bl;
  3375. break;
  3376. } // else fall through
  3377. default:
  3378. bl = &md->bl;
  3379. break;
  3380. }
  3381. if (!bl) {
  3382. if (battle_config.mob_ai & 0x1000)
  3383. continue;
  3384. else
  3385. break;
  3386. }
  3387. md->skill_idx = i;
  3388. map_freeblock_lock();
  3389. if (!battle_check_range(&md->bl, bl, skill_get_range2(&md->bl, ms[i]->skill_id, ms[i]->skill_lv, true)) ||
  3390. !unit_skilluse_id2(&md->bl, bl->id, ms[i]->skill_id, ms[i]->skill_lv, ms[i]->casttime, ms[i]->cancel))
  3391. {
  3392. map_freeblock_unlock();
  3393. if (battle_config.mob_ai & 0x1000)
  3394. continue;
  3395. else
  3396. break;
  3397. }
  3398. }
  3399. //Skill used. Post-setups...
  3400. if ( ms[i]->msg_id ){ //Display color message [SnakeDrak]
  3401. mob_chat_display_message(*md, ms[i]->msg_id);
  3402. }
  3403. if(!(battle_config.mob_ai&0x200)) { //pass on delay to same skill.
  3404. for (j = 0; j < ms.size(); j++)
  3405. if (ms[j]->skill_id == ms[i]->skill_id)
  3406. md->skilldelay[j]=tick;
  3407. } else
  3408. md->skilldelay[i]=tick;
  3409. map_freeblock_unlock();
  3410. return 1;
  3411. }
  3412. //No skill was used.
  3413. md->skill_idx = -1;
  3414. return 0;
  3415. }
  3416. /*==========================================
  3417. * Skill use event processing
  3418. *------------------------------------------*/
  3419. int mobskill_event(struct mob_data *md, struct block_list *src, t_tick tick, int flag, int64 damage)
  3420. {
  3421. int target_id, res = 0;
  3422. if(md->bl.prev == NULL || md->status.hp == 0)
  3423. return 0;
  3424. target_id = md->target_id;
  3425. if (!target_id || battle_config.mob_changetarget_byskill)
  3426. md->target_id = src->id;
  3427. if (flag == -1)
  3428. res = mobskill_use(md, tick, MSC_CASTTARGETED);
  3429. else if ((flag&0xffff) == MSC_SKILLUSED)
  3430. res = mobskill_use(md, tick, flag, damage);
  3431. else if (flag&BF_SHORT)
  3432. res = mobskill_use(md, tick, MSC_CLOSEDATTACKED, damage);
  3433. else if (flag&BF_LONG && !(flag&BF_MAGIC)) //Long-attacked should not include magic.
  3434. res = mobskill_use(md, tick, MSC_LONGRANGEATTACKED, damage);
  3435. else if (damage > 0) //Trigger for any damage dealt from other attack types without affecting other triggers [datawulf]
  3436. res = mobskill_use(md, tick, -2, damage);
  3437. if (!res)
  3438. //Restore previous target only if skill condition failed to trigger. [Skotlex]
  3439. md->target_id = target_id;
  3440. //Otherwise check if the target is an enemy, and unlock if needed.
  3441. else if (battle_check_target(&md->bl, src, BCT_ENEMY) <= 0)
  3442. md->target_id = target_id;
  3443. return res;
  3444. }
  3445. // Player cloned mobs. [Valaris]
  3446. int mob_is_clone(int mob_id)
  3447. {
  3448. if(mob_id < MOB_CLONE_START || mob_id > MOB_CLONE_END)
  3449. return 0;
  3450. if (!mob_db.exists(mob_id))
  3451. return 0;
  3452. return mob_id;
  3453. }
  3454. /**
  3455. * Previously, using skill_nocast with flag 16
  3456. * @param skill_id
  3457. * @return True:If disabled, False:If enabled
  3458. * @!TODO : Move this hardcodes!
  3459. **/
  3460. static bool mob_clone_disabled_skills(uint16 skill_id) {
  3461. switch (skill_id) {
  3462. case PR_TURNUNDEAD:
  3463. case PR_MAGNUS:
  3464. return true;
  3465. }
  3466. return false;
  3467. }
  3468. //Flag values:
  3469. //&1: Set special ai (fight mobs, not players)
  3470. //If mode is not passed, a default aggressive mode is used.
  3471. //If master_id is passed, clone is attached to him.
  3472. //Returns: ID of newly crafted copy.
  3473. int mob_clone_spawn(map_session_data *sd, int16 m, int16 x, int16 y, const char *event, int master_id, enum e_mode mode, int flag, unsigned int duration)
  3474. {
  3475. int mob_id;
  3476. int inf, fd;
  3477. struct mob_data *md;
  3478. struct status_data *status;
  3479. nullpo_ret(sd);
  3480. if(pc_isdead(sd) && master_id && flag&1)
  3481. return 0;
  3482. ARR_FIND( MOB_CLONE_START, MOB_CLONE_END, mob_id, !mob_db.exists(mob_id) );
  3483. if(mob_id >= MOB_CLONE_END)
  3484. return 0;
  3485. std::shared_ptr<s_mob_db> db = std::make_shared<s_mob_db>();
  3486. mob_db.put( mob_id, db );
  3487. status = &db->status;
  3488. db->sprite = sd->status.name;
  3489. db->name = sd->status.name;
  3490. db->jname = sd->status.name;
  3491. db->lv=status_get_lv(&sd->bl);
  3492. memcpy(status, &sd->base_status, sizeof(struct status_data));
  3493. status->rhw.atk2= status->dex + status->rhw.atk + status->rhw.atk2; //Max ATK
  3494. status->rhw.atk = status->dex; //Min ATK
  3495. if (status->lhw.atk) {
  3496. status->lhw.atk2= status->dex + status->lhw.atk + status->lhw.atk2; //Max ATK
  3497. status->lhw.atk = status->dex; //Min ATK
  3498. }
  3499. if (mode > MD_NONE) //User provided mode.
  3500. status->mode = mode;
  3501. else if (flag&2)// Clone follows the creator
  3502. status->mode = MONSTER_TYPE_24;
  3503. status->hp = status->max_hp;
  3504. status->sp = status->max_sp;
  3505. memcpy(&db->vd, &sd->vd, sizeof(struct view_data));
  3506. db->base_exp=1;
  3507. db->job_exp=1;
  3508. db->range2=AREA_SIZE; //Let them have the same view-range as players.
  3509. db->range3=AREA_SIZE; //Min chase of a screen.
  3510. db->option=sd->sc.option;
  3511. /**
  3512. * We temporarily disable sd's fd so it doesn't receive the messages from skill_check_condition_castbegin
  3513. **/
  3514. fd = sd->fd;
  3515. sd->fd = 0;
  3516. //Go Backwards to give better priority to advanced skills.
  3517. std::shared_ptr<s_skill_tree> tree = skill_tree_db.find(sd->status.class_);
  3518. if( tree != nullptr && !tree->skills.empty() ){
  3519. std::vector<uint16> skill_list;
  3520. for (const auto &it : tree->skills)
  3521. skill_list.push_back(it.first);
  3522. std::sort(skill_list.rbegin(), skill_list.rend());
  3523. for (const auto &it : skill_list) {
  3524. if (db->skill.size() >= MAX_MOBSKILL)
  3525. break;
  3526. uint16 skill_id = it;
  3527. uint16 sk_idx = 0;
  3528. if (!skill_id || !(sk_idx = skill_get_index(skill_id)) || sd->status.skill[sk_idx].lv < 1 ||
  3529. skill_get_inf2_(skill_id, { INF2_ISWEDDING, INF2_ISGUILD }) ||
  3530. mob_clone_disabled_skills(skill_id)
  3531. )
  3532. continue;
  3533. //Normal aggressive mob, disable skills that cannot help them fight
  3534. //against players (those with flags UF_NOMOB and UF_NOPC are specific
  3535. //to always aid players!) [Skotlex]
  3536. if (!(flag&1) &&
  3537. skill_get_unit_id(skill_id) &&
  3538. skill_get_unit_flag_(skill_id, { UF_NOMOB, UF_NOPC }))
  3539. continue;
  3540. /**
  3541. * The clone should be able to cast the skill (e.g. have the required weapon) bugreport:5299)
  3542. **/
  3543. if( !skill_check_condition_castbegin(sd,skill_id,sd->status.skill[sk_idx].lv) )
  3544. continue;
  3545. std::shared_ptr<s_mob_skill> ms = std::make_shared<s_mob_skill>();
  3546. ms->skill_id = skill_id;
  3547. ms->skill_lv = sd->status.skill[sk_idx].lv;
  3548. ms->state = MSS_ANY;
  3549. ms->permillage = 500*battle_config.mob_skill_rate/100; //Default chance of all skills: 5%
  3550. ms->emotion = -1;
  3551. ms->cancel = 0;
  3552. ms->casttime = skill_castfix(&sd->bl,skill_id, ms->skill_lv);
  3553. ms->delay = 5000+skill_delayfix(&sd->bl,skill_id, ms->skill_lv);
  3554. ms->msg_id = 0;
  3555. inf = skill_get_inf(skill_id);
  3556. bool is_also_self = false;
  3557. if (inf&INF_ATTACK_SKILL) {
  3558. ms->target = MST_TARGET;
  3559. ms->cond1 = MSC_ALWAYS;
  3560. if (skill_get_range(skill_id, ms->skill_lv) > 3)
  3561. ms->state = MSS_ANYTARGET;
  3562. else
  3563. ms->state = MSS_BERSERK;
  3564. } else if(inf&INF_GROUND_SKILL) {
  3565. if (skill_get_inf2(skill_id, INF2_ISTRAP)) { //Traps!
  3566. ms->state = MSS_IDLE;
  3567. ms->target = MST_AROUND2;
  3568. ms->delay = 60000;
  3569. } else if (skill_get_unit_target(skill_id) == BCT_ENEMY) { //Target Enemy
  3570. ms->state = MSS_ANYTARGET;
  3571. ms->target = MST_TARGET;
  3572. ms->cond1 = MSC_ALWAYS;
  3573. } else { //Target allies
  3574. ms->target = MST_FRIEND;
  3575. ms->cond1 = MSC_FRIENDHPLTMAXRATE;
  3576. ms->cond2 = 95;
  3577. }
  3578. } else if (inf&INF_SELF_SKILL) {
  3579. if (skill_get_inf2(skill_id, INF2_NOTARGETSELF)) { //auto-select target skill.
  3580. ms->target = MST_TARGET;
  3581. ms->cond1 = MSC_ALWAYS;
  3582. if (skill_get_range(skill_id, ms->skill_lv) > 3) {
  3583. ms->state = MSS_ANYTARGET;
  3584. } else {
  3585. ms->state = MSS_BERSERK;
  3586. }
  3587. } else { //Self skill
  3588. ms->target = MST_SELF;
  3589. ms->cond1 = MSC_MYHPLTMAXRATE;
  3590. ms->cond2 = 90;
  3591. ms->permillage = 2000;
  3592. //Delay: Remove the stock 5 secs and add half of the support time.
  3593. ms->delay += -5000 +(skill_get_time(skill_id, ms->skill_lv) + skill_get_time2(skill_id, ms->skill_lv))/2;
  3594. if (ms->delay < 5000)
  3595. ms->delay = 5000; //With a minimum of 5 secs.
  3596. }
  3597. } else if (inf&INF_SUPPORT_SKILL) {
  3598. if (master_id > 0 && (flag&2)) {
  3599. ms->target = MST_MASTER;
  3600. ms->cond1 = MSC_MASTERHPLTMAXRATE;
  3601. }
  3602. else {
  3603. ms->target = MST_FRIEND;
  3604. ms->cond1 = MSC_FRIENDHPLTMAXRATE;
  3605. }
  3606. ms->cond2 = 90;
  3607. if (skill_id == AL_HEAL)
  3608. ms->permillage = 5000; //Higher skill rate usage for heal.
  3609. else if (skill_id == ALL_RESURRECTION)
  3610. ms->cond2 = 1;
  3611. //Delay: Remove the stock 5 secs and add half of the support time.
  3612. ms->delay += -5000 +(skill_get_time(skill_id, ms->skill_lv) + skill_get_time2(skill_id, ms->skill_lv))/2;
  3613. if (ms->delay < 2000)
  3614. ms->delay = 2000; //With a minimum of 2 secs.
  3615. is_also_self = true;
  3616. } else {
  3617. switch (skill_id) { //Certain Special skills that are passive, and thus, never triggered.
  3618. case MO_TRIPLEATTACK:
  3619. case TF_DOUBLE:
  3620. case GS_CHAINACTION:
  3621. ms->state = MSS_BERSERK;
  3622. ms->target = MST_TARGET;
  3623. ms->cond1 = MSC_ALWAYS;
  3624. ms->permillage = skill_id==MO_TRIPLEATTACK?(3000-ms->skill_lv*100):(ms->skill_lv*500);
  3625. ms->delay -= 5000; //Remove the added delay as these could trigger on "all hits".
  3626. break;
  3627. default: //Untreated Skill
  3628. continue;
  3629. }
  3630. }
  3631. if (battle_config.mob_skill_rate!= 100)
  3632. ms->permillage = ms->permillage*battle_config.mob_skill_rate/100;
  3633. if (battle_config.mob_skill_delay != 100)
  3634. ms->delay = ms->delay*battle_config.mob_skill_delay/100;
  3635. db->skill.push_back(ms);
  3636. // Duplicate INF_SUPPORT_SKILL so it also triggers on self.
  3637. if (is_also_self && db->skill.size() < MAX_MOBSKILL) {
  3638. std::shared_ptr<s_mob_skill> ms = std::make_shared<s_mob_skill>();
  3639. ms->skill_id = skill_id;
  3640. ms->skill_lv = sd->status.skill[sk_idx].lv;
  3641. ms->state = MSS_ANY;
  3642. ms->permillage = 500*battle_config.mob_skill_rate/100; //Default chance of all skills: 5%
  3643. ms->emotion = -1;
  3644. ms->cancel = 0;
  3645. ms->casttime = skill_castfix(&sd->bl,skill_id, ms->skill_lv);
  3646. ms->delay = 5000+skill_delayfix(&sd->bl,skill_id, ms->skill_lv);
  3647. ms->msg_id = 0;
  3648. ms->target = MST_SELF;
  3649. ms->cond1 = MSC_MYHPLTMAXRATE;
  3650. ms->cond2 = 90;
  3651. if (skill_id == AL_HEAL)
  3652. ms->permillage = 5000; //Higher skill rate usage for heal.
  3653. else if (skill_id == ALL_RESURRECTION)
  3654. ms->cond2 = 1;
  3655. //Delay: Remove the stock 5 secs and add half of the support time.
  3656. ms->delay += -5000 +(skill_get_time(skill_id, ms->skill_lv) + skill_get_time2(skill_id, ms->skill_lv))/2;
  3657. if (ms->delay < 2000)
  3658. ms->delay = 2000; //With a minimum of 2 secs.
  3659. if (battle_config.mob_skill_rate!= 100)
  3660. ms->permillage = ms->permillage*battle_config.mob_skill_rate/100;
  3661. if (battle_config.mob_skill_delay != 100)
  3662. ms->delay = ms->delay*battle_config.mob_skill_delay/100;
  3663. db->skill.push_back(ms);
  3664. }
  3665. }
  3666. }
  3667. /**
  3668. * We grant the session it's fd value back.
  3669. **/
  3670. sd->fd = fd;
  3671. //Finally, spawn it.
  3672. md = mob_once_spawn_sub(&sd->bl, m, x, y, "--en--", mob_id, event, SZ_SMALL, AI_NONE);
  3673. if (!md) return 0; //Failed?
  3674. md->special_state.clone = 1;
  3675. md->damagetaken = 100; // Avoid Green Aura reduction calculation.
  3676. if (master_id || flag || duration) { //Further manipulate crafted char.
  3677. if (flag&1) //Friendly Character
  3678. md->special_state.ai = AI_ATTACK;
  3679. if (master_id) //Attach to Master
  3680. md->master_id = master_id;
  3681. if (duration) //Auto Delete after a while.
  3682. {
  3683. if( md->deletetimer != INVALID_TIMER )
  3684. delete_timer(md->deletetimer, mob_timer_delete);
  3685. md->deletetimer = add_timer (gettick() + duration, mob_timer_delete, md->bl.id, 0);
  3686. }
  3687. }
  3688. mob_spawn(md);
  3689. return md->bl.id;
  3690. }
  3691. int mob_clone_delete(struct mob_data *md){
  3692. uint32 mob_id = md->mob_id;
  3693. if (mob_is_clone(mob_id)) {
  3694. mob_db.erase(mob_id);
  3695. //Clear references to the db
  3696. md->db = NULL;
  3697. md->vd = NULL;
  3698. return 1;
  3699. }
  3700. return 0;
  3701. }
  3702. //Adjusts the drop rate of item according to the criteria given. [Skotlex]
  3703. static unsigned int mob_drop_adjust(int baserate, int rate_adjust, unsigned short rate_min, unsigned short rate_max)
  3704. {
  3705. double rate = baserate;
  3706. if (battle_config.logarithmic_drops && rate_adjust > 0 && rate_adjust != 100 && baserate > 0) //Logarithmic drops equation by Ishizu-Chan
  3707. //Equation: Droprate(x,y) = x * (5 - log(x)) ^ (ln(y) / ln(5))
  3708. //x is the normal Droprate, y is the Modificator.
  3709. rate = rate * pow((5.0 - log10(rate)), (log(rate_adjust/100.) / log(5.0))) + 0.5;
  3710. else
  3711. //Classical linear rate adjustment.
  3712. rate = rate * rate_adjust/100;
  3713. return (unsigned int)cap_value(rate,rate_min,rate_max);
  3714. }
  3715. /**
  3716. * Check if global item drop rate is overriden for given item
  3717. * in db/mob_item_ratio.yml
  3718. * @param nameid ID of the item
  3719. * @param mob_id ID of the monster
  3720. * @param rate_adjust pointer to store ratio if found
  3721. */
  3722. static void item_dropratio_adjust(t_itemid nameid, int mob_id, int *rate_adjust)
  3723. {
  3724. std::shared_ptr<s_mob_item_drop_ratio> item_ratio = mob_item_drop_ratio.find(nameid);
  3725. if( item_ratio) {
  3726. // If it is empty it is applied to all monsters, if not it is only applied if the monster is in the vector
  3727. if( item_ratio->mob_ids.empty() || util::vector_exists( item_ratio->mob_ids, static_cast<uint16>( mob_id ) ) )
  3728. *rate_adjust = item_ratio->drop_ratio;
  3729. }
  3730. }
  3731. const std::string MobDatabase::getDefaultLocation() {
  3732. return std::string(db_path) + "/mob_db.yml";
  3733. }
  3734. bool MobDatabase::parseDropNode(std::string nodeName, const ryml::NodeRef& node, uint8 max, s_mob_drop *drops) {
  3735. const auto& dropNode = node[c4::to_csubstr(nodeName)];
  3736. uint16 i;
  3737. // Find first empty spot
  3738. for( i = 0; i < max; i++ ){
  3739. if( drops[i].nameid == 0 ){
  3740. break;
  3741. }
  3742. }
  3743. for (const auto& dropit : dropNode) {
  3744. uint16 index;
  3745. if (this->nodeExists(dropit, "Index")) {
  3746. if (!this->asUInt16(dropit, "Index", index))
  3747. return false;
  3748. if (index >= max) {
  3749. this->invalidWarning(dropit["Index"], "Invalid monster %s index %hu. Must be between 0~%hu, skipping.\n", nodeName.c_str(), index, max - 1);
  3750. continue;
  3751. }
  3752. } else {
  3753. index = i++;
  3754. if (index >= max) {
  3755. this->invalidWarning(dropit, "Maximum of %d monster %s met, skipping.\n", max, nodeName.c_str());
  3756. continue;
  3757. }
  3758. }
  3759. std::string item_name;
  3760. if (!this->asString(dropit, "Item", item_name))
  3761. return false;
  3762. std::shared_ptr<item_data> item = item_db.search_aegisname( item_name.c_str() );
  3763. if (item == nullptr) {
  3764. this->invalidWarning(dropit["Item"], "Monster %s item %s does not exist, skipping.\n", nodeName.c_str(), item_name.c_str());
  3765. continue;
  3766. }
  3767. uint16 rate;
  3768. if (!this->asUInt16Rate(dropit, "Rate", rate))
  3769. return false;
  3770. bool steal = false;
  3771. if (this->nodeExists(dropit, "StealProtected")) {
  3772. if (!this->asBool(dropit, "StealProtected", steal))
  3773. return false;
  3774. }
  3775. uint16 group = 0;
  3776. if (this->nodeExists(dropit, "RandomOptionGroup")) {
  3777. std::string group_name;
  3778. if (!this->asString(dropit, "RandomOptionGroup", group_name))
  3779. return false;
  3780. if (!random_option_group.option_get_id(group_name.c_str(), group))
  3781. this->invalidWarning(dropit["RandomOptionGroup"], "Unknown random option group %s for monster %s, defaulting to no group.\n", group_name.c_str(), nodeName.c_str());
  3782. }
  3783. drops[index].nameid = item->nameid;
  3784. drops[index].rate = rate;
  3785. drops[index].steal_protected = steal;
  3786. drops[index].randomopt_group = group;
  3787. }
  3788. return true;
  3789. }
  3790. /**
  3791. * Reads and parses an entry from the mob_db.
  3792. * @param node: YAML node containing the entry.
  3793. * @return count of successfully parsed rows
  3794. */
  3795. uint64 MobDatabase::parseBodyNode(const ryml::NodeRef& node) {
  3796. uint32 mob_id;
  3797. if (!this->asUInt32(node, "Id", mob_id))
  3798. return 0;
  3799. if (!((mob_id > MIN_MOB_DB && mob_id < MAX_MOB_DB) || (mob_id > MIN_MOB_DB2 && mob_id < MAX_MOB_DB2))) {
  3800. this->invalidWarning(node["Id"], "Invalid monster ID %d, must be in range %d-%d or %d-%d.\n", mob_id, MIN_MOB_DB, MAX_MOB_DB, MIN_MOB_DB2, MAX_MOB_DB2);
  3801. return false;
  3802. }
  3803. std::shared_ptr<s_mob_db> mob = this->find(mob_id);
  3804. bool exists = mob != nullptr;
  3805. if (!exists) {
  3806. if (!this->nodesExist(node, { "AegisName", "Name" }))
  3807. return 0;
  3808. mob = std::make_shared<s_mob_db>();
  3809. mob->id = mob_id;
  3810. mob->vd.class_ = static_cast<uint16>(mob->id);
  3811. }
  3812. if (this->nodeExists(node, "AegisName")) {
  3813. std::string name;
  3814. if (!this->asString(node, "AegisName", name))
  3815. return 0;
  3816. if (name.size() > NAME_LENGTH) {
  3817. this->invalidWarning(node["AegisName"], "AegisName \"%s\" exceeds maximum of %d characters, capping...\n", name.c_str(), NAME_LENGTH - 1);
  3818. }
  3819. name.resize(NAME_LENGTH);
  3820. mob->sprite = name;
  3821. }
  3822. if (this->nodeExists(node, "Name")) {
  3823. std::string name;
  3824. if (!this->asString(node, "Name", name))
  3825. return 0;
  3826. if (name.size() > NAME_LENGTH) {
  3827. this->invalidWarning(node["Name"], "Name \"%s\" exceeds maximum of %d characters, capping...\n", name.c_str(), NAME_LENGTH - 1);
  3828. }
  3829. name.resize(NAME_LENGTH);
  3830. mob->name = name;
  3831. }
  3832. if (this->nodeExists(node, "JapaneseName")) {
  3833. std::string name;
  3834. if (!this->asString(node, "JapaneseName", name))
  3835. return 0;
  3836. if (name.size() > NAME_LENGTH) {
  3837. this->invalidWarning(node["JapaneseName"], "JapaneseName \"%s\" exceeds maximum of %d characters, capping...\n", name.c_str(), NAME_LENGTH - 1);
  3838. }
  3839. name.resize(NAME_LENGTH);
  3840. mob->jname = name;
  3841. } else {
  3842. if (!exists)
  3843. mob->jname = mob->name;
  3844. }
  3845. if (this->nodeExists(node, "Level")) {
  3846. uint16 level;
  3847. if (!this->asUInt16(node, "Level", level))
  3848. return 0;
  3849. mob->lv = level;
  3850. } else {
  3851. if (!exists)
  3852. mob->lv = 1;
  3853. }
  3854. if (this->nodeExists(node, "Hp")) {
  3855. uint32 hp;
  3856. if (!this->asUInt32(node, "Hp", hp))
  3857. return 0;
  3858. mob->status.max_hp = hp;
  3859. } else {
  3860. if (!exists)
  3861. mob->status.max_hp = 1;
  3862. }
  3863. if (this->nodeExists(node, "Sp")) {
  3864. uint32 sp;
  3865. if (!this->asUInt32(node, "Sp", sp))
  3866. return 0;
  3867. mob->status.max_sp = sp;
  3868. } else {
  3869. if (!exists)
  3870. mob->status.max_sp = 1;
  3871. }
  3872. if (this->nodeExists(node, "BaseExp")) {
  3873. t_exp exp;
  3874. if (!this->asUInt64(node, "BaseExp", exp))
  3875. return 0;
  3876. mob->base_exp = static_cast<t_exp>(cap_value((double)exp * (double)battle_config.base_exp_rate / 100., 0, MAX_EXP));
  3877. } else {
  3878. if (!exists)
  3879. mob->base_exp = 0;
  3880. }
  3881. if (this->nodeExists(node, "JobExp")) {
  3882. t_exp exp;
  3883. if (!this->asUInt64(node, "JobExp", exp))
  3884. return 0;
  3885. mob->job_exp = static_cast<t_exp>(cap_value((double)exp * (double)battle_config.job_exp_rate / 100., 0, MAX_EXP));
  3886. } else {
  3887. if (!exists)
  3888. mob->job_exp = 0;
  3889. }
  3890. if (this->nodeExists(node, "MvpExp")) {
  3891. t_exp exp;
  3892. if (!this->asUInt64(node, "MvpExp", exp))
  3893. return 0;
  3894. mob->mexp = static_cast<t_exp>(cap_value((double)exp * (double)battle_config.mvp_exp_rate / 100., 0, MAX_EXP));
  3895. } else {
  3896. if (!exists)
  3897. mob->mexp = 0;
  3898. }
  3899. if (this->nodeExists(node, "Attack")) {
  3900. uint16 atk;
  3901. if (!this->asUInt16(node, "Attack", atk))
  3902. return 0;
  3903. mob->status.rhw.atk = atk;
  3904. } else {
  3905. if (!exists)
  3906. mob->status.rhw.atk = 0;
  3907. }
  3908. if (this->nodeExists(node, "Attack2")) {
  3909. uint16 atk;
  3910. if (!this->asUInt16(node, "Attack2", atk))
  3911. return 0;
  3912. #ifdef RENEWAL
  3913. mob->status.rhw.matk = atk;
  3914. #else
  3915. mob->status.rhw.atk2 = atk;
  3916. #endif
  3917. } else {
  3918. if (!exists)
  3919. #ifdef RENEWAL
  3920. mob->status.rhw.matk = 0;
  3921. #else
  3922. mob->status.rhw.atk2 = 0;
  3923. #endif
  3924. }
  3925. if (this->nodeExists(node, "Defense")) {
  3926. uint16 def;
  3927. if (!this->asUInt16(node, "Defense", def))
  3928. return 0;
  3929. if (def < DEFTYPE_MIN || def > DEFTYPE_MAX) {
  3930. this->invalidWarning(node["Defense"], "Invalid monster defense %d, capping...\n", def);
  3931. def = cap_value(def, DEFTYPE_MIN, DEFTYPE_MAX);
  3932. }
  3933. mob->status.def = static_cast<defType>(def);
  3934. } else {
  3935. if (!exists)
  3936. mob->status.def = 0;
  3937. }
  3938. if (this->nodeExists(node, "MagicDefense")) {
  3939. uint16 def;
  3940. if (!this->asUInt16(node, "MagicDefense", def))
  3941. return 0;
  3942. if (def < DEFTYPE_MIN || def > DEFTYPE_MAX) {
  3943. this->invalidWarning(node["MagicDefense"], "Invalid monster magic defense %d, capping...\n", def);
  3944. def = cap_value(def, DEFTYPE_MIN, DEFTYPE_MAX);
  3945. }
  3946. mob->status.mdef = static_cast<defType>(def);
  3947. } else {
  3948. if (!exists)
  3949. mob->status.mdef = 0;
  3950. }
  3951. if (this->nodeExists(node, "Resistance")) {
  3952. uint16 res;
  3953. if (!this->asUInt16(node, "Resistance", res))
  3954. return 0;
  3955. mob->status.res = res;
  3956. }
  3957. else {
  3958. if (!exists)
  3959. mob->status.res = 0;
  3960. }
  3961. if (this->nodeExists(node, "MagicResistance")) {
  3962. uint16 mres;
  3963. if (!this->asUInt16(node, "MagicResistance", mres))
  3964. return 0;
  3965. mob->status.mres = mres;
  3966. }
  3967. else {
  3968. if (!exists)
  3969. mob->status.mres = 0;
  3970. }
  3971. if (this->nodeExists(node, "Str")) {
  3972. uint16 stat;
  3973. if (!this->asUInt16(node, "Str", stat))
  3974. return 0;
  3975. mob->status.str = max(1, stat);
  3976. } else {
  3977. if (!exists)
  3978. mob->status.str = 1;
  3979. }
  3980. if (this->nodeExists(node, "Agi")) {
  3981. uint16 stat;
  3982. if (!this->asUInt16(node, "Agi", stat))
  3983. return 0;
  3984. mob->status.agi = max(1, stat);
  3985. } else {
  3986. if (!exists)
  3987. mob->status.agi = 1;
  3988. }
  3989. if (this->nodeExists(node, "Vit")) {
  3990. uint16 stat;
  3991. if (!this->asUInt16(node, "Vit", stat))
  3992. return 0;
  3993. mob->status.vit = max(1, stat);
  3994. } else {
  3995. if (!exists)
  3996. mob->status.vit = 1;
  3997. }
  3998. if (this->nodeExists(node, "Int")) {
  3999. uint16 stat;
  4000. if (!this->asUInt16(node, "Int", stat))
  4001. return 0;
  4002. mob->status.int_ = max(1, stat);
  4003. } else {
  4004. if (!exists)
  4005. mob->status.int_ = 1;
  4006. }
  4007. if (this->nodeExists(node, "Dex")) {
  4008. uint16 stat;
  4009. if (!this->asUInt16(node, "Dex", stat))
  4010. return 0;
  4011. mob->status.dex = max(1, stat);
  4012. } else {
  4013. if (!exists)
  4014. mob->status.dex = 1;
  4015. }
  4016. if (this->nodeExists(node, "Luk")) {
  4017. uint16 stat;
  4018. if (!this->asUInt16(node, "Luk", stat))
  4019. return 0;
  4020. mob->status.luk = max(1, stat);
  4021. } else {
  4022. if (!exists)
  4023. mob->status.luk = 1;
  4024. }
  4025. if (this->nodeExists(node, "AttackRange")) {
  4026. uint16 range;
  4027. if (!this->asUInt16(node, "AttackRange", range))
  4028. return 0;
  4029. mob->status.rhw.range = range;
  4030. } else {
  4031. if (!exists)
  4032. mob->status.rhw.range = 0;
  4033. }
  4034. if (this->nodeExists(node, "SkillRange")) {
  4035. uint16 range;
  4036. if (!this->asUInt16(node, "SkillRange", range))
  4037. return 0;
  4038. mob->range2 = range;
  4039. } else {
  4040. if (!exists)
  4041. mob->range2 = 0;
  4042. }
  4043. if (this->nodeExists(node, "ChaseRange")) {
  4044. uint16 range;
  4045. if (!this->asUInt16(node, "ChaseRange", range))
  4046. return 0;
  4047. mob->range3 = range;
  4048. } else {
  4049. if (!exists)
  4050. mob->range3 = 0;
  4051. }
  4052. if (this->nodeExists(node, "Size")) {
  4053. std::string size;
  4054. if (!this->asString(node, "Size", size))
  4055. return 0;
  4056. std::string size_constant = "Size_" + size;
  4057. int64 constant;
  4058. if (!script_get_constant(size_constant.c_str(), &constant)) {
  4059. this->invalidWarning(node["Size"], "Unknown monster size %s, defaulting to Small.\n", size.c_str());
  4060. constant = SZ_SMALL;
  4061. }
  4062. if (constant < SZ_SMALL || constant > SZ_BIG) {
  4063. this->invalidWarning(node["Size"], "Invalid monster size %s, defaulting to Small.\n", size.c_str());
  4064. constant = SZ_SMALL;
  4065. }
  4066. mob->status.size = static_cast<e_size>(constant);
  4067. } else {
  4068. if (!exists)
  4069. mob->status.size = SZ_SMALL;
  4070. }
  4071. if (this->nodeExists(node, "Race")) {
  4072. std::string race;
  4073. if (!this->asString(node, "Race", race))
  4074. return 0;
  4075. std::string race_constant = "RC_" + race;
  4076. int64 constant;
  4077. if (!script_get_constant(race_constant.c_str(), &constant)) {
  4078. this->invalidWarning(node["Race"], "Unknown monster race %s, defaulting to Formless.\n", race.c_str());
  4079. constant = RC_FORMLESS;
  4080. }
  4081. if (!CHK_RACE(constant)) {
  4082. this->invalidWarning(node["Race"], "Invalid monster race %s, defaulting to Formless.\n", race.c_str());
  4083. constant = RC_FORMLESS;
  4084. }
  4085. mob->status.race = static_cast<e_race>(constant);
  4086. } else {
  4087. if (!exists)
  4088. mob->status.race = RC_FORMLESS;
  4089. }
  4090. if (this->nodeExists(node, "RaceGroups")) {
  4091. const auto& raceNode = node["RaceGroups"];
  4092. for (const auto &raceit : raceNode) {
  4093. std::string raceName;
  4094. c4::from_chars(raceit.key(), &raceName);
  4095. std::string raceName_constant = "RC2_" + raceName;
  4096. int64 constant;
  4097. if (!script_get_constant(raceName_constant.c_str(), &constant)) {
  4098. this->invalidWarning(raceNode[raceit.key()], "Unknown monster race group %s, skipping.\n", raceName.c_str());
  4099. continue;
  4100. }
  4101. if (!CHK_RACE2(constant)) {
  4102. this->invalidWarning(raceNode[raceit.key()], "Invalid monster race group %s, skipping.\n", raceName.c_str());
  4103. continue;
  4104. }
  4105. bool active;
  4106. if (!this->asBool(raceNode, raceName, active))
  4107. return 0;
  4108. if (active)
  4109. mob->race2.push_back(static_cast<e_race2>(constant));
  4110. else
  4111. util::vector_erase_if_exists(mob->race2, static_cast<e_race2>(constant));
  4112. }
  4113. }
  4114. if (this->nodeExists(node, "Element")) {
  4115. std::string ele;
  4116. if (!this->asString(node, "Element", ele))
  4117. return 0;
  4118. std::string ele_constant = "ELE_" + ele;
  4119. int64 constant;
  4120. if (!script_get_constant(ele_constant.c_str(), &constant)) {
  4121. this->invalidWarning(node["Element"], "Unknown monster element %s, defaulting to Neutral.\n", ele.c_str());
  4122. constant = ELE_NEUTRAL;
  4123. }
  4124. if (!CHK_ELEMENT(constant)) {
  4125. this->invalidWarning(node["Element"], "Invalid monster element %s, defaulting to Neutral.\n", ele.c_str());
  4126. constant = ELE_NEUTRAL;
  4127. }
  4128. mob->status.def_ele = static_cast<e_element>(constant);
  4129. } else {
  4130. if (!exists)
  4131. mob->status.def_ele = ELE_NEUTRAL;
  4132. }
  4133. if (this->nodeExists(node, "ElementLevel")) {
  4134. uint16 level;
  4135. if (!this->asUInt16(node, "ElementLevel", level))
  4136. return 0;
  4137. if (!CHK_ELEMENT_LEVEL(level)) {
  4138. this->invalidWarning(node["ElementLevel"], "Invalid monster element level %hu, defaulting to 1.\n", level);
  4139. level = 1;
  4140. }
  4141. mob->status.ele_lv = static_cast<uint8>(level);
  4142. } else {
  4143. if (!exists)
  4144. mob->status.ele_lv = 1;
  4145. }
  4146. if (this->nodeExists(node, "WalkSpeed")) {
  4147. uint16 speed;
  4148. if (!this->asUInt16(node, "WalkSpeed", speed))
  4149. return 0;
  4150. if (speed < MIN_WALK_SPEED || speed > MAX_WALK_SPEED) {
  4151. this->invalidWarning(node["WalkSpeed"], "Invalid monster walk speed %hu, capping...\n", speed);
  4152. speed = cap_value(speed, MIN_WALK_SPEED, MAX_WALK_SPEED);
  4153. }
  4154. mob->status.speed = speed;
  4155. } else {
  4156. if (!exists)
  4157. mob->status.speed = DEFAULT_WALK_SPEED;
  4158. }
  4159. if (this->nodeExists(node, "AttackDelay")) {
  4160. uint16 speed;
  4161. if (!this->asUInt16(node, "AttackDelay", speed))
  4162. return 0;
  4163. mob->status.adelay = cap_value(speed, battle_config.monster_max_aspd * 2, 4000);
  4164. } else {
  4165. if (!exists)
  4166. mob->status.adelay = cap_value(0, battle_config.monster_max_aspd * 2, 4000);
  4167. }
  4168. if (this->nodeExists(node, "AttackMotion")) {
  4169. uint16 speed;
  4170. if (!this->asUInt16(node, "AttackMotion", speed))
  4171. return 0;
  4172. mob->status.amotion = cap_value(speed, battle_config.monster_max_aspd, 2000);
  4173. } else {
  4174. if (!exists)
  4175. mob->status.amotion = cap_value(0, battle_config.monster_max_aspd, 2000);
  4176. }
  4177. if (this->nodeExists(node, "DamageMotion")) {
  4178. uint16 speed;
  4179. if (!this->asUInt16(node, "DamageMotion", speed))
  4180. return 0;
  4181. if (battle_config.monster_damage_delay_rate != 100)
  4182. speed = speed * battle_config.monster_damage_delay_rate / 100;
  4183. mob->status.dmotion = speed;
  4184. } else {
  4185. if (!exists)
  4186. mob->status.dmotion = 0;
  4187. }
  4188. if (this->nodeExists(node, "DamageTaken")) {
  4189. uint16 damage;
  4190. if (!this->asUInt16Rate(node, "DamageTaken", damage, 100))
  4191. return 0;
  4192. mob->damagetaken = damage;
  4193. } else {
  4194. if (!exists)
  4195. mob->damagetaken = 100;
  4196. }
  4197. if (this->nodeExists(node, "Ai")) {
  4198. std::string ai;
  4199. if (!this->asString(node, "Ai", ai))
  4200. return 0;
  4201. std::string ai_constant = "MONSTER_TYPE_" + ai;
  4202. int64 constant;
  4203. if (!script_get_constant(ai_constant.c_str(), &constant)) {
  4204. this->invalidWarning(node["Ai"], "Unknown monster AI %s, defaulting to 06.\n", ai.c_str());
  4205. constant = MONSTER_TYPE_06;
  4206. }
  4207. if (constant < MD_NONE || constant > MD_MASK) {
  4208. this->invalidWarning(node["Ai"], "Invalid monster AI %s, defaulting to 06.\n", ai.c_str());
  4209. constant = MONSTER_TYPE_06;
  4210. }
  4211. mob->status.mode = static_cast<e_mode>(constant);
  4212. } else {
  4213. if (!exists)
  4214. mob->status.mode = static_cast<e_mode>(MONSTER_TYPE_06);
  4215. }
  4216. if (this->nodeExists(node, "Class")) {
  4217. std::string class_;
  4218. if (!this->asString(node, "Class", class_))
  4219. return 0;
  4220. std::string class_constant = "CLASS_" + class_;
  4221. int64 constant;
  4222. if (!script_get_constant(class_constant.c_str(), &constant)) {
  4223. this->invalidWarning(node["Class"], "Unknown monster class %s, defaulting to Normal.\n", class_.c_str());
  4224. constant = CLASS_NORMAL;
  4225. }
  4226. if (constant < CLASS_NORMAL || constant > CLASS_EVENT) {
  4227. this->invalidWarning(node["Class"], "Invalid monster class %s, defaulting to Normal.\n", class_.c_str());
  4228. constant = CLASS_NORMAL;
  4229. }
  4230. mob->status.class_ = static_cast<uint8>(constant);
  4231. } else {
  4232. if (!exists)
  4233. mob->status.class_ = CLASS_NORMAL;
  4234. }
  4235. if (this->nodeExists(node, "Modes")) {
  4236. const auto& modeNode = node["Modes"];
  4237. for (const auto& modeit : modeNode) {
  4238. std::string modeName;
  4239. c4::from_chars(modeit.key(), &modeName);
  4240. std::string modeName_constant = "MD_" + modeName;
  4241. int64 constant;
  4242. if (!script_get_constant(modeName_constant.c_str(), &constant)) {
  4243. this->invalidWarning(modeNode[modeit.key()], "Unknown monster mode %s, skipping.\n", modeName.c_str());
  4244. continue;
  4245. }
  4246. if (constant < MD_NONE || constant > MD_SKILLIMMUNE) {
  4247. this->invalidWarning(modeNode[modeit.key()], "Invalid monster mode %s, skipping.\n", modeName.c_str());
  4248. continue;
  4249. }
  4250. bool active;
  4251. if (!this->asBool(modeNode, modeName, active))
  4252. return 0;
  4253. if (active)
  4254. mob->status.mode = static_cast<e_mode>(mob->status.mode | constant);
  4255. else
  4256. mob->status.mode = static_cast<e_mode>(mob->status.mode & ~constant);
  4257. }
  4258. }
  4259. if (this->nodeExists(node, "MvpDrops")) {
  4260. if (!this->parseDropNode("MvpDrops", node, MAX_MVP_DROP, mob->mvpitem))
  4261. return 0;
  4262. }
  4263. if (this->nodeExists(node, "Drops")) {
  4264. if (!this->parseDropNode("Drops", node, MAX_MOB_DROP, mob->dropitem))
  4265. return 0;
  4266. }
  4267. if (!exists)
  4268. this->put(mob_id, mob);
  4269. return true;
  4270. }
  4271. void MobDatabase::loadingFinished() {
  4272. for (auto &mobdata : *this) {
  4273. std::shared_ptr<s_mob_db> mob = mobdata.second;
  4274. switch (mob->status.class_) {
  4275. case CLASS_BOSS:
  4276. mob->status.mode = static_cast<e_mode>(mob->status.mode | (MD_DETECTOR | MD_STATUSIMMUNE | MD_KNOCKBACKIMMUNE));
  4277. break;
  4278. case CLASS_GUARDIAN:
  4279. mob->status.mode = static_cast<e_mode>(mob->status.mode | MD_STATUSIMMUNE);
  4280. break;
  4281. case CLASS_BATTLEFIELD:
  4282. mob->status.mode = static_cast<e_mode>(mob->status.mode | (MD_STATUSIMMUNE | MD_SKILLIMMUNE));
  4283. break;
  4284. case CLASS_EVENT:
  4285. mob->status.mode = static_cast<e_mode>(mob->status.mode | MD_FIXEDITEMDROP);
  4286. break;
  4287. }
  4288. if (battle_config.view_range_rate != 100)
  4289. mob->range2 = max(1, mob->range2 * battle_config.view_range_rate / 100);
  4290. if (battle_config.chase_range_rate != 100)
  4291. mob->range3 = max(mob->range2, mob->range3 * battle_config.chase_range_rate / 100);
  4292. // If the attack animation is longer than the delay, the client crops the attack animation!
  4293. // On aegis there is no real visible effect of having a recharge-time less than amotion anyway.
  4294. mob->status.adelay = max(mob->status.adelay, mob->status.amotion);
  4295. mob->status.aspd_rate = 1000;
  4296. if (!battle_config.monster_active_enable)
  4297. mob->status.mode = static_cast<enum e_mode>(mob->status.mode & ~MD_AGGRESSIVE);
  4298. // Fill in remaining status data by using a dummy monster.
  4299. mob_data data;
  4300. data.bl.type = BL_MOB;
  4301. data.level = mob->lv;
  4302. memcpy(&data.status, &mob->status, sizeof(status_data));
  4303. status_calc_misc(&data.bl, &mob->status, mob->lv);
  4304. // Now that we know if it is a MVP or not, apply battle_config modifiers [Skotlex]
  4305. double maxhp = (double)mob->status.max_hp;
  4306. if (mob->get_bosstype() == BOSSTYPE_MVP) { // MVP
  4307. if (battle_config.mvp_hp_rate != 100)
  4308. maxhp = maxhp * (double)battle_config.mvp_hp_rate / 100.;
  4309. } else { // Normal mob
  4310. if (battle_config.monster_hp_rate != 100)
  4311. maxhp = maxhp * (double)battle_config.monster_hp_rate / 100.;
  4312. }
  4313. mob->status.max_hp = cap_value(static_cast<uint32>(maxhp), 1, UINT32_MAX);
  4314. mob->status.max_sp = cap_value(mob->status.max_sp, 1, UINT32_MAX);
  4315. mob->status.hp = mob->status.max_hp;
  4316. mob->status.sp = mob->status.max_sp;
  4317. }
  4318. TypesafeCachedYamlDatabase::loadingFinished();
  4319. }
  4320. MobDatabase mob_db;
  4321. /**
  4322. * Convert SQL data to YAML Node
  4323. * @param str: Array of parsed SQL data
  4324. * @return True on success or false otherwise
  4325. */
  4326. static bool mob_read_sqldb_sub(std::vector<std::string> str) {
  4327. ryml::Tree tree;
  4328. ryml::NodeRef node = tree.rootref();
  4329. node |= ryml::MAP;
  4330. int32 index = -1;
  4331. node["Id"] << str[++index];
  4332. if (!str[++index].empty())
  4333. node["AegisName"] << str[index];
  4334. if (!str[++index].empty())
  4335. node["Name"] << str[index];
  4336. if (!str[++index].empty())
  4337. node["JapaneseName"] << str[index];
  4338. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4339. node["Level"] << str[index];
  4340. if (!str[++index].empty() && std::stoul(str[index]) > 1)
  4341. node["Hp"] << str[index];
  4342. if (!str[++index].empty() && std::stoul(str[index]) > 1)
  4343. node["Sp"] << str[index];
  4344. if (!str[++index].empty())
  4345. node["BaseExp"] << str[index];
  4346. if (!str[++index].empty())
  4347. node["JobExp"] << str[index];
  4348. if (!str[++index].empty())
  4349. node["MvpExp"] << str[index];
  4350. if (!str[++index].empty())
  4351. node["Attack"] << str[index];
  4352. if (!str[++index].empty())
  4353. node["Attack2"] << str[index];
  4354. if (!str[++index].empty())
  4355. node["Defense"] << str[index];
  4356. if (!str[++index].empty())
  4357. node["MagicDefense"] << str[index];
  4358. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4359. node["Str"] << str[index];
  4360. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4361. node["Agi"] << str[index];
  4362. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4363. node["Vit"] << str[index];
  4364. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4365. node["Int"] << str[index];
  4366. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4367. node["Dex"] << str[index];
  4368. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4369. node["Luk"] << str[index];
  4370. if (!str[++index].empty())
  4371. node["AttackRange"] << str[index];
  4372. if (!str[++index].empty())
  4373. node["SkillRange"] << str[index];
  4374. if (!str[++index].empty())
  4375. node["ChaseRange"] << str[index];
  4376. if (!str[++index].empty() && strcmp(str[index].c_str(), "Small") != 0)
  4377. node["Size"] << str[index];
  4378. if (!str[++index].empty() && strcmp(str[index].c_str(), "Formless") != 0)
  4379. node["Race"] << str[index];
  4380. ryml::NodeRef raceGroupsNode = node["RaceGroups"];
  4381. raceGroupsNode |= ryml::MAP;
  4382. for (uint16 i = 1; i < RC2_MAX; i++) {
  4383. if (!str[i + index].empty()) {
  4384. raceGroupsNode[c4::to_csubstr(script_get_constant_str("RC2_", i) + 4)] << (std::stoi(str[i + index]) ? "true" : "false");
  4385. }
  4386. }
  4387. index += RC2_MAX - 1;
  4388. if (!str[++index].empty() && strcmp(str[index].c_str(), "Neutral") != 0)
  4389. node["Element"] << str[index];
  4390. if (!str[++index].empty() && std::stoi(str[index]) > 1)
  4391. node["ElementLevel"] << str[index];
  4392. if (!str[++index].empty())
  4393. node["WalkSpeed"] << str[index];
  4394. if (!str[++index].empty())
  4395. node["AttackDelay"] << str[index];
  4396. if (!str[++index].empty())
  4397. node["AttackMotion"] << str[index];
  4398. if (!str[++index].empty())
  4399. node["DamageMotion"] << str[index];
  4400. if (!str[++index].empty())
  4401. node["DamageTaken"] << str[index];
  4402. if (!str[++index].empty() && strcmp(str[index].c_str(), "06") != 0)
  4403. node["Ai"] << str[index];
  4404. if (!str[++index].empty() && strcmp(str[index].c_str(), "Normal") != 0)
  4405. node["Class"] << str[index];
  4406. ryml::NodeRef modes = node["Modes"];
  4407. modes |= ryml::MAP;
  4408. if (!str[++index].empty())
  4409. modes["CanMove"] << (std::stoi(str[index]) ? "true" : "false");
  4410. if (!str[++index].empty())
  4411. modes["Looter"] << (std::stoi(str[index]) ? "true" : "false");
  4412. if (!str[++index].empty())
  4413. modes["Aggressive"] << (std::stoi(str[index]) ? "true" : "false");
  4414. if (!str[++index].empty())
  4415. modes["Assist"] << (std::stoi(str[index]) ? "true" : "false");
  4416. if (!str[++index].empty())
  4417. modes["CastSensorIdle"] << (std::stoi(str[index]) ? "true" : "false");
  4418. if (!str[++index].empty())
  4419. modes["NoRandomWalk"] << (std::stoi(str[index]) ? "true" : "false");
  4420. if (!str[++index].empty())
  4421. modes["NoCast"] << (std::stoi(str[index]) ? "true" : "false");
  4422. if (!str[++index].empty())
  4423. modes["CanAttack"] << (std::stoi(str[index]) ? "true" : "false");
  4424. if (!str[++index].empty())
  4425. modes["CastSensorChase"] << (std::stoi(str[index]) ? "true" : "false");
  4426. if (!str[++index].empty())
  4427. modes["ChangeChase"] << (std::stoi(str[index]) ? "true" : "false");
  4428. if (!str[++index].empty())
  4429. modes["Angry"] << (std::stoi(str[index]) ? "true" : "false");
  4430. if (!str[++index].empty())
  4431. modes["ChangeTargetMelee"] << (std::stoi(str[index]) ? "true" : "false");
  4432. if (!str[++index].empty())
  4433. modes["ChangeTargetChase"] << (std::stoi(str[index]) ? "true" : "false");
  4434. if (!str[++index].empty())
  4435. modes["TargetWeak"] << (std::stoi(str[index]) ? "true" : "false");
  4436. if (!str[++index].empty())
  4437. modes["RandomTarget"] << (std::stoi(str[index]) ? "true" : "false");
  4438. if (!str[++index].empty())
  4439. modes["IgnoreMelee"] << (std::stoi(str[index]) ? "true" : "false");
  4440. if (!str[++index].empty())
  4441. modes["IgnoreMagic"] << (std::stoi(str[index]) ? "true" : "false");
  4442. if (!str[++index].empty())
  4443. modes["IgnoreRanged"] << (std::stoi(str[index]) ? "true" : "false");
  4444. if (!str[++index].empty())
  4445. modes["Mvp"] << (std::stoi(str[index]) ? "true" : "false");
  4446. if (!str[++index].empty())
  4447. modes["IgnoreMisc"] << (std::stoi(str[index]) ? "true" : "false");
  4448. if (!str[++index].empty())
  4449. modes["KnockBackImmune"] << (std::stoi(str[index]) ? "true" : "false");
  4450. if (!str[++index].empty())
  4451. modes["TeleportBlock"] << (std::stoi(str[index]) ? "true" : "false");
  4452. if (!str[++index].empty())
  4453. modes["FixedItemDrop"] << (std::stoi(str[index]) ? "true" : "false");
  4454. if (!str[++index].empty())
  4455. modes["Detector"] << (std::stoi(str[index]) ? "true" : "false");
  4456. if (!str[++index].empty())
  4457. modes["StatusImmune"] << (std::stoi(str[index]) ? "true" : "false");
  4458. if (!str[++index].empty())
  4459. modes["SkillImmune"] << (std::stoi(str[index]) ? "true" : "false");
  4460. ryml::NodeRef mvpDropsNode = node["MvpDrops"];
  4461. mvpDropsNode |= ryml::SEQ;
  4462. for (uint8 i = 0; i < MAX_MVP_DROP; i++) {
  4463. if (!str[++index].empty()) {
  4464. ryml::NodeRef entry = mvpDropsNode[i];
  4465. entry |= ryml::MAP;
  4466. entry["Item"] << str[index];
  4467. if (!str[++index].empty())
  4468. entry["Rate"] << str[index];
  4469. if (!str[++index].empty() && strcmp(str[index].c_str(), "None") != 0)
  4470. entry["RandomOptionGroup"] << str[index];
  4471. if (!str[++index].empty() && std::stoi(str[index]) >= 0)
  4472. entry["Index"] << str[index];
  4473. } else
  4474. index += 3;
  4475. }
  4476. ryml::NodeRef dropsNode = node["Drops"];
  4477. dropsNode |= ryml::SEQ;
  4478. for (uint8 i = 0; i < MAX_MOB_DROP; i++) {
  4479. if (!str[++index].empty()) {
  4480. ryml::NodeRef entry = dropsNode[i];
  4481. entry |= ryml::MAP;
  4482. entry["Item"] << str[index];
  4483. if (!str[++index].empty())
  4484. entry["Rate"] << str[index];
  4485. if (!str[++index].empty())
  4486. entry["StealProtected"] << (std::stoi(str[index]) ? "true" : "false");
  4487. if (!str[++index].empty() && strcmp(str[index].c_str(), "None") != 0)
  4488. entry["RandomOptionGroup"] << str[index];
  4489. if (!str[++index].empty() && std::stoi(str[index]) >= 0)
  4490. entry["Index"] << str[index];
  4491. } else
  4492. index += 4;
  4493. }
  4494. #ifdef RENEWAL
  4495. if (!str[++index].empty())
  4496. node["Resistance"] << std::stoi(str[index]);
  4497. if (!str[++index].empty())
  4498. node["MagicResistance"] << std::stoi(str[index]);
  4499. #endif
  4500. if( !modes.has_children() ){
  4501. node.remove_child( modes );
  4502. }
  4503. if( !mvpDropsNode.has_children() ){
  4504. node.remove_child( mvpDropsNode );
  4505. }
  4506. if( !dropsNode.has_children() ){
  4507. node.remove_child( dropsNode );
  4508. }
  4509. return mob_db.parseBodyNode(node) > 0;
  4510. }
  4511. /**
  4512. * Read SQL mob_db table
  4513. */
  4514. static int mob_read_sqldb(void)
  4515. {
  4516. const char* mob_db_name[] = {
  4517. mob_table,
  4518. mob2_table
  4519. };
  4520. for( uint8 fi = 0; fi < ARRAYLENGTH(mob_db_name); ++fi ) {
  4521. // retrieve all rows from the mob database
  4522. if( SQL_ERROR == Sql_Query(mmysql_handle, "SELECT `id`,`name_aegis`,`name_english`,`name_japanese`,`level`,`hp`,`sp`,`base_exp`,`job_exp`,`mvp_exp`,`attack`,`attack2`,`defense`,`magic_defense`,`str`,`agi`,`vit`,`int`,`dex`,`luk`,`attack_range`,`skill_range`,`chase_range`,`size`,`race`,"
  4523. "`racegroup_goblin`,`racegroup_kobold`,`racegroup_orc`,`racegroup_golem`,`racegroup_guardian`,`racegroup_ninja`,`racegroup_gvg`,`racegroup_battlefield`,`racegroup_treasure`,`racegroup_biolab`,`racegroup_manuk`,`racegroup_splendide`,`racegroup_scaraba`,`racegroup_ogh_atk_def`,`racegroup_ogh_hidden`,`racegroup_bio5_swordman_thief`,`racegroup_bio5_acolyte_merchant`,`racegroup_bio5_mage_archer`,`racegroup_bio5_mvp`,`racegroup_clocktower`,`racegroup_thanatos`,`racegroup_faceworm`,`racegroup_hearthunter`,`racegroup_rockridge`,`racegroup_werner_lab`,`racegroup_temple_demon`,`racegroup_illusion_vampire`,`racegroup_malangdo`,`racegroup_ep172alpha`,`racegroup_ep172beta`,`racegroup_ep172bath`,`racegroup_illusion_turtle`,`racegroup_rachel_sanctuary`,"
  4524. "`element`,`element_level`,`walk_speed`,`attack_delay`,`attack_motion`,`damage_motion`,`damage_taken`,`ai`,`class`,"
  4525. "`mode_canmove`,`mode_looter`,`mode_aggressive`,`mode_assist`,`mode_castsensoridle`,`mode_norandomwalk`,`mode_nocast`,`mode_canattack`,`mode_castsensorchase`,`mode_changechase`,`mode_angry`,`mode_changetargetmelee`,`mode_changetargetchase`,`mode_targetweak`,`mode_randomtarget`,`mode_ignoremelee`,`mode_ignoremagic`,`mode_ignoreranged`,`mode_mvp`,`mode_ignoremisc`,`mode_knockbackimmune`,`mode_teleportblock`,`mode_fixeditemdrop`,`mode_detector`,`mode_statusimmune`,`mode_skillimmune`,"
  4526. "`mvpdrop1_item`,`mvpdrop1_rate`,`mvpdrop1_option`,`mvpdrop1_index`,`mvpdrop2_item`,`mvpdrop2_rate`,`mvpdrop2_option`,`mvpdrop2_index`,`mvpdrop3_item`,`mvpdrop3_rate`,`mvpdrop3_option`,`mvpdrop3_index`,"
  4527. "`drop1_item`,`drop1_rate`,`drop1_nosteal`,`drop1_option`,`drop1_index`,`drop2_item`,`drop2_rate`,`drop2_nosteal`,`drop2_option`,`drop2_index`,`drop3_item`,`drop3_rate`,`drop3_nosteal`,`drop3_option`,`drop3_index`,`drop4_item`,`drop4_rate`,`drop4_nosteal`,`drop4_option`,`drop4_index`,`drop5_item`,`drop5_rate`,`drop5_nosteal`,`drop5_option`,`drop5_index`,`drop6_item`,`drop6_rate`,`drop6_nosteal`,`drop6_option`,`drop6_index`,`drop7_item`,`drop7_rate`,`drop7_nosteal`,`drop7_option`,`drop7_index`,`drop8_item`,`drop8_rate`,`drop8_nosteal`,`drop8_option`,`drop8_index`,`drop9_item`,`drop9_rate`,`drop9_nosteal`,`drop9_option`,`drop9_index`,`drop10_item`,`drop10_rate`,`drop10_nosteal`,`drop10_option`,`drop10_index`"
  4528. #ifdef RENEWAL
  4529. ",`resistance`,`magic_resistance`"
  4530. #endif
  4531. " FROM `%s`", mob_db_name[fi]) ) {
  4532. Sql_ShowDebug(mmysql_handle);
  4533. continue;
  4534. }
  4535. uint32 total_columns = Sql_NumColumns(mmysql_handle);
  4536. uint64 total_rows = Sql_NumRows(mmysql_handle), rows = 0, count = 0;
  4537. ShowStatus("Loading '" CL_WHITE "%" PRIdPTR CL_RESET "' entries in '" CL_WHITE "%s" CL_RESET "'\n", total_rows, mob_db_name[fi]);
  4538. // process rows one by one
  4539. while( SQL_SUCCESS == Sql_NextRow(mmysql_handle) ) {
  4540. #ifdef DETAILED_LOADING_OUTPUT
  4541. ShowStatus("Loading [%" PRIu64 "/%" PRIu64 "] entries in '" CL_WHITE "%s" CL_RESET "'" CL_CLL "\r", ++rows, total_rows, mob_db_name[fi]);
  4542. #endif
  4543. std::vector<std::string> data = {};
  4544. for (uint32 i = 0; i < total_columns; i++) {
  4545. char *str;
  4546. Sql_GetData(mmysql_handle, i, &str, nullptr);
  4547. if (str == nullptr)
  4548. data.push_back("");
  4549. else
  4550. data.push_back(str);
  4551. }
  4552. if (!mob_read_sqldb_sub(data))
  4553. continue;
  4554. count++;
  4555. }
  4556. // free the query result
  4557. Sql_FreeResult(mmysql_handle);
  4558. ShowStatus("Done reading '" CL_WHITE "%" PRIu64 CL_RESET "' entries in '" CL_WHITE "%s" CL_RESET "'.\n", count, mob_db_name[fi]);
  4559. }
  4560. mob_db.loadingFinished();
  4561. return 0;
  4562. }
  4563. const std::string MobAvailDatabase::getDefaultLocation() {
  4564. return std::string(db_path) + "/" + DBIMPORT + "/mob_avail.yml";
  4565. }
  4566. /**
  4567. * Reads and parses an entry from the mob_avail.
  4568. * @param node: YAML node containing the entry.
  4569. * @return count of successfully parsed rows
  4570. */
  4571. uint64 MobAvailDatabase::parseBodyNode(const ryml::NodeRef& node) {
  4572. std::string mob_name;
  4573. if (!this->asString(node, "Mob", mob_name))
  4574. return 0;
  4575. std::shared_ptr<s_mob_db> mob = mobdb_search_aegisname(mob_name.c_str());
  4576. if (mob == nullptr) {
  4577. this->invalidWarning(node["Mob"], "Unknown mob %s.\n", mob_name.c_str());
  4578. return 0;
  4579. }
  4580. if (this->nodeExists(node, "Sprite")) {
  4581. std::string sprite;
  4582. if (!this->asString(node, "Sprite", sprite))
  4583. return 0;
  4584. int64 constant;
  4585. if (script_get_constant(sprite.c_str(), &constant)) {
  4586. if (npcdb_checkid(constant) == 0 && pcdb_checkid(constant) == 0) {
  4587. this->invalidWarning(node["Sprite"], "Unknown sprite constant %s.\n", sprite.c_str());
  4588. return 0;
  4589. }
  4590. } else {
  4591. std::shared_ptr<s_mob_db> sprite_mob = mobdb_search_aegisname(sprite.c_str());
  4592. if (sprite_mob == nullptr) {
  4593. this->invalidWarning(node["Sprite"], "Unknown mob sprite constant %s.\n", sprite.c_str());
  4594. return 0;
  4595. }
  4596. constant = sprite_mob->id;
  4597. }
  4598. mob->vd.class_ = (unsigned short)constant;
  4599. } else {
  4600. this->invalidWarning(node["Sprite"], "Sprite is missing.\n");
  4601. return 0;
  4602. }
  4603. if (this->nodeExists(node, "Sex")) {
  4604. if (pcdb_checkid(mob->vd.class_) == 0) {
  4605. this->invalidWarning(node["Sex"], "Sex is only applicable to Job sprites.\n");
  4606. return 0;
  4607. }
  4608. std::string sex;
  4609. if (!this->asString(node, "Sex", sex))
  4610. return 0;
  4611. std::string sex_constant = "SEX_" + sex;
  4612. int64 constant;
  4613. if (!script_get_constant(sex_constant.c_str(), &constant)) {
  4614. this->invalidWarning(node["Sex"], "Unknown sex constant %s.\n", sex.c_str());
  4615. return 0;
  4616. }
  4617. if (constant < SEX_FEMALE || constant > SEX_MALE) {
  4618. this->invalidWarning(node["Sex"], "Sex %s is not valid.\n", sex.c_str());
  4619. return 0;
  4620. }
  4621. mob->vd.sex = (char)constant;
  4622. }
  4623. if (this->nodeExists(node, "HairStyle")) {
  4624. if (pcdb_checkid(mob->vd.class_) == 0) {
  4625. this->invalidWarning(node["HairStyle"], "HairStyle is only applicable to Job sprites.\n");
  4626. return 0;
  4627. }
  4628. uint16 hair_style;
  4629. if (!this->asUInt16(node, "HairStyle", hair_style))
  4630. return 0;
  4631. if (hair_style < MIN_HAIR_STYLE || hair_style > MAX_HAIR_STYLE) {
  4632. this->invalidWarning(node["HairStyle"], "HairStyle %d is out of range %d~%d. Setting to MIN_HAIR_STYLE.\n", hair_style, MIN_HAIR_STYLE, MAX_HAIR_STYLE);
  4633. hair_style = MIN_HAIR_STYLE;
  4634. }
  4635. mob->vd.hair_style = hair_style;
  4636. }
  4637. if (this->nodeExists(node, "HairColor")) {
  4638. if (pcdb_checkid(mob->vd.class_) == 0) {
  4639. this->invalidWarning(node["HairColor"], "HairColor is only applicable to Job sprites.\n");
  4640. return 0;
  4641. }
  4642. uint16 hair_color;
  4643. if (!this->asUInt16(node, "HairColor", hair_color))
  4644. return 0;
  4645. if (hair_color < MIN_HAIR_COLOR || hair_color > MAX_HAIR_COLOR) {
  4646. this->invalidWarning(node["HairColor"], "HairColor %d is out of range %d~%d. Setting to MIN_HAIR_COLOR.\n", hair_color, MIN_HAIR_COLOR, MAX_HAIR_COLOR);
  4647. hair_color = MIN_HAIR_COLOR;
  4648. }
  4649. mob->vd.hair_color = hair_color;
  4650. }
  4651. if (this->nodeExists(node, "ClothColor")) {
  4652. if (pcdb_checkid(mob->vd.class_) == 0) {
  4653. this->invalidWarning(node["ClothColor"], "ClothColor is only applicable to Job sprites.\n");
  4654. return 0;
  4655. }
  4656. uint32 cloth_color;
  4657. if (!this->asUInt32(node, "ClothColor", cloth_color))
  4658. return 0;
  4659. if (cloth_color < MIN_CLOTH_COLOR || cloth_color > MAX_CLOTH_COLOR) {
  4660. this->invalidWarning(node["ClothColor"], "ClothColor %d is out of range %d~%d. Setting to MIN_CLOTH_CLOR.\n", cloth_color, MIN_CLOTH_COLOR, MAX_CLOTH_COLOR);
  4661. cloth_color = MIN_CLOTH_COLOR;
  4662. }
  4663. mob->vd.cloth_color = cloth_color;
  4664. }
  4665. if (this->nodeExists(node, "Weapon")) {
  4666. if (pcdb_checkid(mob->vd.class_) == 0) {
  4667. this->invalidWarning(node["Weapon"], "Weapon is only applicable to Job sprites.\n");
  4668. return 0;
  4669. }
  4670. std::string weapon;
  4671. if (!this->asString(node, "Weapon", weapon))
  4672. return 0;
  4673. std::shared_ptr<item_data> item = item_db.search_aegisname( weapon.c_str() );
  4674. if (item == nullptr) {
  4675. this->invalidWarning(node["Weapon"], "Weapon %s is not a valid item.\n", weapon.c_str());
  4676. return 0;
  4677. }
  4678. mob->vd.weapon = item->nameid;
  4679. }
  4680. if (this->nodeExists(node, "Shield")) {
  4681. if (pcdb_checkid(mob->vd.class_) == 0) {
  4682. this->invalidWarning(node["Shield"], "Shield is only applicable to Job sprites.\n");
  4683. return 0;
  4684. }
  4685. std::string shield;
  4686. if (!this->asString(node, "Shield", shield))
  4687. return 0;
  4688. std::shared_ptr<item_data> item = item_db.search_aegisname( shield.c_str() );
  4689. if (item == nullptr) {
  4690. this->invalidWarning(node["Shield"], "Shield %s is not a valid item.\n", shield.c_str());
  4691. return 0;
  4692. }
  4693. mob->vd.shield = item->nameid;
  4694. }
  4695. if (this->nodeExists(node, "HeadTop")) {
  4696. if (pcdb_checkid(mob->vd.class_) == 0) {
  4697. this->invalidWarning(node["HeadTop"], "HeadTop is only applicable to Job sprites.\n");
  4698. return 0;
  4699. }
  4700. std::string head;
  4701. if (!this->asString(node, "HeadTop", head))
  4702. return 0;
  4703. std::shared_ptr<item_data> item = item_db.search_aegisname( head.c_str() );
  4704. if (item == nullptr) {
  4705. this->invalidWarning(node["HeadTop"], "HeadTop %s is not a valid item.\n", head.c_str());
  4706. return 0;
  4707. }
  4708. mob->vd.head_top = item->look;
  4709. }
  4710. if (this->nodeExists(node, "HeadMid")) {
  4711. if (pcdb_checkid(mob->vd.class_) == 0) {
  4712. this->invalidWarning(node["HeadMid"], "HeadMid is only applicable to Job sprites.\n");
  4713. return 0;
  4714. }
  4715. std::string head;
  4716. if (!this->asString(node, "HeadMid", head))
  4717. return 0;
  4718. std::shared_ptr<item_data> item = item_db.search_aegisname( head.c_str() );
  4719. if (item == nullptr) {
  4720. this->invalidWarning(node["HeadMid"], "HeadMid %s is not a valid item.\n", head.c_str());
  4721. return 0;
  4722. }
  4723. mob->vd.head_mid = item->look;
  4724. }
  4725. if (this->nodeExists(node, "HeadLow")) {
  4726. if (pcdb_checkid(mob->vd.class_) == 0) {
  4727. this->invalidWarning(node["HeadLow"], "HeadLow is only applicable to Job sprites.\n");
  4728. return 0;
  4729. }
  4730. std::string head;
  4731. if (!this->asString(node, "HeadLow", head))
  4732. return 0;
  4733. std::shared_ptr<item_data> item = item_db.search_aegisname( head.c_str() );
  4734. if (item == nullptr) {
  4735. this->invalidWarning(node["HeadLow"], "HeadLow %s is not a valid item.\n", head.c_str());
  4736. return 0;
  4737. }
  4738. mob->vd.head_bottom = item->look;
  4739. }
  4740. if (this->nodeExists(node, "Robe")) {
  4741. if (pcdb_checkid(mob->vd.class_) == 0) {
  4742. this->invalidWarning(node["Robe"], "Robe is only applicable to Job sprites.\n");
  4743. return 0;
  4744. }
  4745. std::string robe;
  4746. if (!this->asString(node, "Robe", robe))
  4747. return 0;
  4748. std::shared_ptr<item_data> item = item_db.search_aegisname(robe.c_str());
  4749. if (item == nullptr) {
  4750. this->invalidWarning(node["Robe"], "Robe %s is not a valid item.\n", robe.c_str());
  4751. return 0;
  4752. }
  4753. mob->vd.robe = item->look;
  4754. }
  4755. if (this->nodeExists(node, "PetEquip")) {
  4756. std::shared_ptr<s_pet_db> pet_db_ptr = pet_db.find(mob->id);
  4757. if (pet_db_ptr == nullptr) {
  4758. this->invalidWarning(node["PetEquip"], "PetEquip is only applicable to defined pets.\n");
  4759. return 0;
  4760. }
  4761. std::string equipment;
  4762. if (!this->asString(node, "PetEquip", equipment))
  4763. return 0;
  4764. std::shared_ptr<item_data> item = item_db.search_aegisname( equipment.c_str() );
  4765. if (item == nullptr) {
  4766. this->invalidWarning(node["PetEquip"], "PetEquip %s is not a valid item.\n", equipment.c_str());
  4767. return 0;
  4768. }
  4769. mob->vd.head_bottom = item->nameid;
  4770. }
  4771. if (this->nodeExists(node, "Options")) {
  4772. const auto& optionNode = node["Options"];
  4773. for (const auto& it : optionNode) {
  4774. std::string option;
  4775. c4::from_chars(it.key(), &option);
  4776. std::string option_constant = "OPTION_" + option;
  4777. int64 constant;
  4778. if (!script_get_constant(option_constant.c_str(), &constant)) {
  4779. this->invalidWarning(optionNode, "Unknown option constant %s, skipping.\n", option.c_str());
  4780. continue;
  4781. }
  4782. bool active;
  4783. if (!this->asBool(optionNode, option, active))
  4784. continue;
  4785. #ifdef NEW_CARTS
  4786. if (constant & OPTION_CART) {
  4787. this->invalidWarning(optionNode, "OPTION_CART was replace by SC_PUSH_CART, skipping.\n");
  4788. continue;
  4789. }
  4790. #endif
  4791. if (active)
  4792. mob->option |= constant;
  4793. else
  4794. mob->option &= ~constant;
  4795. }
  4796. mob->option &= ~(OPTION_HIDE | OPTION_CLOAK | OPTION_INVISIBLE | OPTION_CHASEWALK); // Remove hiding types
  4797. }
  4798. return 1;
  4799. }
  4800. MobAvailDatabase mob_avail_db;
  4801. const std::string MobSummonDatabase::getDefaultLocation() {
  4802. return std::string(db_path) + "/mob_summon.yml";
  4803. }
  4804. /**
  4805. * Reads and parses an entry from the mob_summon.
  4806. * @param node: YAML node containing the entry.
  4807. * @return count of successfully parsed rows
  4808. */
  4809. uint64 MobSummonDatabase::parseBodyNode(const ryml::NodeRef& node) {
  4810. std::string group_name;
  4811. if (!this->asString(node, "Group", group_name))
  4812. return 0;
  4813. std::string group_name_constant = "MOBG_" + group_name;
  4814. int64 constant;
  4815. if (!script_get_constant(group_name_constant.c_str(), &constant) || constant < MOBG_BRANCH_OF_DEAD_TREE || constant >= MOBG_MAX) {
  4816. this->invalidWarning(node["Group"], "Invalid monster group %s.\n", group_name.c_str());
  4817. return 0;
  4818. }
  4819. uint16 id = static_cast<uint16>(constant);
  4820. std::shared_ptr<s_randomsummon_group> summon = this->find(id);
  4821. bool exists = summon != nullptr;
  4822. if (!exists) {
  4823. if (!this->nodesExist(node, { "Default" }))
  4824. return 0;
  4825. summon = std::make_shared<s_randomsummon_group>();
  4826. summon->random_id = id;
  4827. }
  4828. if (this->nodeExists(node, "Default")) {
  4829. std::string mob_name;
  4830. if (!this->asString(node, "Default", mob_name))
  4831. return 0;
  4832. std::shared_ptr<s_mob_db> mob = mobdb_search_aegisname(mob_name.c_str());
  4833. if (mob == nullptr) {
  4834. this->invalidWarning(node["Default"], "Unknown mob %s.\n", mob_name.c_str());
  4835. return 0;
  4836. }
  4837. summon->default_mob_id = mob->id;
  4838. }
  4839. if (this->nodeExists(node, "Summon")) {
  4840. const auto& MobNode = node["Summon"];
  4841. for (const auto& mobit : MobNode) {
  4842. if (!this->nodesExist(mobit, { "Mob", "Rate" })) {
  4843. continue;
  4844. }
  4845. std::string mob_name;
  4846. if (!this->asString(mobit, "Mob", mob_name))
  4847. continue;
  4848. std::shared_ptr<s_mob_db> mob = mobdb_search_aegisname(mob_name.c_str());
  4849. if (mob == nullptr) {
  4850. this->invalidWarning(mobit["Mob"], "Unknown mob %s.\n", mob_name.c_str());
  4851. continue;
  4852. }
  4853. uint32 rate;
  4854. if (!this->asUInt32(mobit, "Rate", rate))
  4855. continue;
  4856. uint16 mob_id = mob->id;
  4857. if (rate == 0) {
  4858. if (summon->list.erase(mob_id) == 0)
  4859. this->invalidWarning(mobit["Rate"], "Failed to remove %s, the monster doesn't exist in group %s.\n", mob_name.c_str(), group_name.c_str());
  4860. continue;
  4861. }
  4862. std::shared_ptr<s_randomsummon_entry> entry = util::umap_find(summon->list, mob_id);
  4863. if (entry == nullptr) {
  4864. entry = std::make_shared<s_randomsummon_entry>();
  4865. entry->mob_id = mob_id;
  4866. summon->list[mob_id] = entry;
  4867. }
  4868. entry->rate = rate;
  4869. }
  4870. }
  4871. if (!exists)
  4872. this->put(id, summon);
  4873. return 1;
  4874. }
  4875. const std::string MobChatDatabase::getDefaultLocation() {
  4876. return std::string(db_path) + "/mob_chat_db.yml";
  4877. }
  4878. /**
  4879. * Reads and parses an entry from the mob_chat_db.
  4880. * @param node: YAML node containing the entry.
  4881. * @return count of successfully parsed rows
  4882. */
  4883. uint64 MobChatDatabase::parseBodyNode(const ryml::NodeRef& node) {
  4884. uint16 id;
  4885. if (!this->asUInt16(node, "Id", id))
  4886. return 0;
  4887. std::shared_ptr<s_mob_chat> chat = this->find(id);
  4888. bool exists = chat != nullptr;
  4889. if (!exists) {
  4890. if (!this->nodesExist(node, { "Dialog" })) {
  4891. return 0;
  4892. }
  4893. chat = std::make_shared<s_mob_chat>();
  4894. chat->msg_id = id;
  4895. }
  4896. if (this->nodeExists(node, "Color")) {
  4897. std::string hex;
  4898. if (!this->asString(node, "Color", hex))
  4899. return 0;
  4900. chat->color = strtoul(hex.c_str(), nullptr, 0);
  4901. } else {
  4902. if (!exists)
  4903. chat->color = strtoul("0xFF0000", nullptr, 0);
  4904. }
  4905. if (this->nodeExists(node, "Dialog")) {
  4906. std::string msg;
  4907. if (!this->asString(node, "Dialog", msg))
  4908. return 0;
  4909. if (msg.length() > (CHAT_SIZE_MAX-1)) {
  4910. this->invalidWarning(node["Dialog"], "Message too long!\n");
  4911. return 0;
  4912. }
  4913. chat->msg = msg;
  4914. }
  4915. if (!exists)
  4916. this->put(id, chat);
  4917. return 1;
  4918. }
  4919. /*==========================================
  4920. * processes one mob_skill_db entry
  4921. *------------------------------------------*/
  4922. static bool mob_parse_row_mobskilldb(char** str, int columns, int current)
  4923. {
  4924. static const struct {
  4925. char str[32];
  4926. enum MobSkillState id;
  4927. } state[] = {
  4928. { "any", MSS_ANY }, //All states except Dead
  4929. { "idle", MSS_IDLE },
  4930. { "walk", MSS_WALK },
  4931. { "loot", MSS_LOOT },
  4932. { "dead", MSS_DEAD },
  4933. { "attack", MSS_BERSERK }, //Retaliating attack
  4934. { "angry", MSS_ANGRY }, //Preemptive attack (aggressive mobs)
  4935. { "chase", MSS_RUSH }, //Chase escaping target
  4936. { "follow", MSS_FOLLOW }, //Preemptive chase (aggressive mobs)
  4937. { "anytarget",MSS_ANYTARGET }, //Berserk+Angry+Rush+Follow
  4938. };
  4939. static const struct {
  4940. char str[32];
  4941. int id;
  4942. } cond1[] = {
  4943. // enum e_mob_skill_condition
  4944. { "always", MSC_ALWAYS },
  4945. { "myhpltmaxrate", MSC_MYHPLTMAXRATE },
  4946. { "myhpinrate", MSC_MYHPINRATE },
  4947. { "friendhpltmaxrate", MSC_FRIENDHPLTMAXRATE },
  4948. { "friendhpinrate", MSC_FRIENDHPINRATE },
  4949. { "mystatuson", MSC_MYSTATUSON },
  4950. { "mystatusoff", MSC_MYSTATUSOFF },
  4951. { "friendstatuson", MSC_FRIENDSTATUSON },
  4952. { "friendstatusoff", MSC_FRIENDSTATUSOFF },
  4953. { "attackpcgt", MSC_ATTACKPCGT },
  4954. { "attackpcge", MSC_ATTACKPCGE },
  4955. { "slavelt", MSC_SLAVELT },
  4956. { "slavele", MSC_SLAVELE },
  4957. { "closedattacked", MSC_CLOSEDATTACKED },
  4958. { "longrangeattacked", MSC_LONGRANGEATTACKED },
  4959. { "skillused", MSC_SKILLUSED },
  4960. { "afterskill", MSC_AFTERSKILL },
  4961. { "casttargeted", MSC_CASTTARGETED },
  4962. { "rudeattacked", MSC_RUDEATTACKED },
  4963. { "masterhpltmaxrate", MSC_MASTERHPLTMAXRATE },
  4964. { "masterattacked", MSC_MASTERATTACKED },
  4965. { "alchemist", MSC_ALCHEMIST },
  4966. { "onspawn", MSC_SPAWN },
  4967. { "mobnearbygt", MSC_MOBNEARBYGT },
  4968. { "groundattacked", MSC_GROUNDATTACKED },
  4969. { "damagedgt", MSC_DAMAGEDGT },
  4970. }, cond2[] ={
  4971. { "anybad", -1 },
  4972. { "stone", SC_STONE },
  4973. { "freeze", SC_FREEZE },
  4974. { "stun", SC_STUN },
  4975. { "sleep", SC_SLEEP },
  4976. { "poison", SC_POISON },
  4977. { "curse", SC_CURSE },
  4978. { "silence", SC_SILENCE },
  4979. { "confusion", SC_CONFUSION },
  4980. { "blind", SC_BLIND },
  4981. { "hiding", SC_HIDING },
  4982. { "sight", SC_SIGHT },
  4983. }, target[] = {
  4984. // enum e_mob_skill_target
  4985. { "target", MST_TARGET },
  4986. { "randomtarget", MST_RANDOM },
  4987. { "self", MST_SELF },
  4988. { "friend", MST_FRIEND },
  4989. { "master", MST_MASTER },
  4990. { "around5", MST_AROUND5 },
  4991. { "around6", MST_AROUND6 },
  4992. { "around7", MST_AROUND7 },
  4993. { "around8", MST_AROUND8 },
  4994. { "around1", MST_AROUND1 },
  4995. { "around2", MST_AROUND2 },
  4996. { "around3", MST_AROUND3 },
  4997. { "around4", MST_AROUND4 },
  4998. { "around", MST_AROUND },
  4999. };
  5000. static int last_mob_id = 0; // ensures that only one error message per mob id is printed
  5001. int mob_id;
  5002. int j, tmp;
  5003. mob_id = atoi(str[0]);
  5004. std::shared_ptr<s_mob_db> mob = mob_db.find(mob_id);
  5005. if (mob_id > 0 && mob == nullptr)
  5006. {
  5007. if (mob_id != last_mob_id) {
  5008. ShowError("mob_parse_row_mobskilldb: Non existant Mob id %d\n", mob_id);
  5009. last_mob_id = mob_id;
  5010. }
  5011. return false;
  5012. }
  5013. else if (mob_id == 0)
  5014. return false;
  5015. // Looking for existing entry
  5016. std::shared_ptr<s_mob_skill_db> skill = util::umap_find(mob_skill_db, mob_id);
  5017. if (skill == nullptr)
  5018. skill = std::make_shared<s_mob_skill_db>();
  5019. if( strcmp(str[1],"clear") == 0 && skill->mob_id != 0 ) {
  5020. mob_skill_db.erase(skill->mob_id);
  5021. ShowInfo("Cleared skill for mob id '%d'\n", mob_id);
  5022. return true;
  5023. }
  5024. if (skill->skill.size() >= MAX_MOBSKILL) {
  5025. if (mob_id != last_mob_id) {
  5026. ShowError("mob_parse_row_mobskilldb: Too many skills for monster %d[%s]\n", mob_id, mob->sprite.c_str());
  5027. last_mob_id = mob_id;
  5028. }
  5029. return false;
  5030. }
  5031. std::shared_ptr<s_mob_skill> ms = std::make_shared<s_mob_skill>();
  5032. //State
  5033. ARR_FIND( 0, ARRAYLENGTH(state), j, strcmp(str[2],state[j].str) == 0 );
  5034. if( j < ARRAYLENGTH(state) )
  5035. ms->state = state[j].id;
  5036. else {
  5037. ShowError("mob_parse_row_mobskilldb: Unrecognized state '%s' in line %d\n", str[2], current);
  5038. return false;
  5039. }
  5040. //Skill ID
  5041. j = atoi(str[3]);
  5042. if (j <= 0 || j > MAX_SKILL_ID || !skill_get_index(j)) //fixed Lupus
  5043. {
  5044. if (mob_id < 0)
  5045. ShowError("mob_parse_row_mobskilldb: Invalid Skill ID (%d) for all mobs\n", j);
  5046. else
  5047. ShowError("mob_parse_row_mobskilldb: Invalid Skill ID (%d) for mob %d (%s)\n", j, mob_id, mob->sprite.c_str());
  5048. return false;
  5049. }
  5050. ms->skill_id = j;
  5051. //Skill lvl
  5052. j = atoi(str[4]) <= 0 ? 1 : atoi(str[4]);
  5053. ms->skill_lv = j > battle_config.mob_max_skilllvl ? battle_config.mob_max_skilllvl : j; //we strip max skill level
  5054. //Apply battle_config modifiers to rate (permillage) and delay [Skotlex]
  5055. tmp = atoi(str[5]);
  5056. if (battle_config.mob_skill_rate != 100)
  5057. tmp = tmp*battle_config.mob_skill_rate/100;
  5058. if (tmp > 10000)
  5059. ms->permillage = 10000;
  5060. else if (!tmp && battle_config.mob_skill_rate)
  5061. ms->permillage = 1;
  5062. else
  5063. ms->permillage = tmp;
  5064. ms->casttime = atoi(str[6]);
  5065. ms->delay = atoi(str[7]);
  5066. if (battle_config.mob_skill_delay != 100)
  5067. ms->delay = ms->delay*battle_config.mob_skill_delay/100;
  5068. if (ms->delay < 0 || ms->delay > MOB_MAX_DELAY) //time overflow?
  5069. ms->delay = MOB_MAX_DELAY;
  5070. ms->cancel = atoi(str[8]);
  5071. if( strcmp(str[8],"yes")==0 )
  5072. ms->cancel=1;
  5073. //Target
  5074. ARR_FIND( 0, ARRAYLENGTH(target), j, strcmp(str[9],target[j].str) == 0 );
  5075. if( j < ARRAYLENGTH(target) )
  5076. ms->target = target[j].id;
  5077. else {
  5078. ShowWarning("mob_parse_row_mobskilldb: Unrecognized target %s for %d\n", str[9], mob_id);
  5079. ms->target = MST_TARGET;
  5080. }
  5081. //Check that the target condition is right for the skill type. [Skotlex]
  5082. if (skill_get_casttype(ms->skill_id) == CAST_GROUND)
  5083. { //Ground skill.
  5084. if (ms->target > MST_AROUND)
  5085. {
  5086. ShowWarning("mob_parse_row_mobskilldb: Wrong mob skill target for ground skill %d (%s) for %s.\n",
  5087. ms->skill_id, skill_get_name(ms->skill_id),
  5088. mob_id < 0 ? "all mobs" : mob->sprite.c_str());
  5089. ms->target = MST_TARGET;
  5090. }
  5091. } else if (ms->target > MST_MASTER) {
  5092. ShowWarning("mob_parse_row_mobskilldb: Wrong mob skill target 'around' for non-ground skill %d (%s) for %s.\n",
  5093. ms->skill_id, skill_get_name(ms->skill_id),
  5094. mob_id < 0 ? "all mobs" : mob->sprite.c_str());
  5095. ms->target = MST_TARGET;
  5096. }
  5097. //Cond1
  5098. ARR_FIND( 0, ARRAYLENGTH(cond1), j, strcmp(str[10],cond1[j].str) == 0 );
  5099. if( j < ARRAYLENGTH(cond1) )
  5100. ms->cond1 = cond1[j].id;
  5101. else {
  5102. ShowWarning("mob_parse_row_mobskilldb: Unrecognized condition 1 %s for %d\n", str[10], mob_id);
  5103. ms->cond1 = -1;
  5104. }
  5105. //Cond2
  5106. // numeric value
  5107. ms->cond2 = atoi(str[11]);
  5108. // or special constant
  5109. ARR_FIND( 0, ARRAYLENGTH(cond2), j, strcmp(str[11],cond2[j].str) == 0 );
  5110. if( j < ARRAYLENGTH(cond2) )
  5111. ms->cond2 = cond2[j].id;
  5112. ms->val[0] = (int)strtol(str[12],NULL,0);
  5113. ms->val[1] = (int)strtol(str[13],NULL,0);
  5114. ms->val[2] = (int)strtol(str[14],NULL,0);
  5115. ms->val[3] = (int)strtol(str[15],NULL,0);
  5116. ms->val[4] = (int)strtol(str[16],NULL,0);
  5117. if(ms->skill_id == NPC_EMOTION && mob_id > 0 &&
  5118. ms->val[1] == mob->status.mode)
  5119. {
  5120. ms->val[1] = 0;
  5121. ms->val[4] = 1; //request to return mode to normal.
  5122. }
  5123. if(ms->skill_id == NPC_EMOTION_ON && mob_id > 0 && ms->val[1])
  5124. { //Adds a mode to the mob.
  5125. //Remove aggressive mode when the new mob type is passive.
  5126. if (!(ms->val[1]&MD_AGGRESSIVE))
  5127. ms->val[3] |= MD_AGGRESSIVE;
  5128. ms->val[2] |= ms->val[1]; //Add the new mode.
  5129. ms->val[1] = 0; //Do not "set" it.
  5130. }
  5131. if(*str[17])
  5132. ms->emotion = atoi(str[17]);
  5133. else
  5134. ms->emotion = -1;
  5135. if (*str[18]) {
  5136. uint16 id = static_cast<uint16>(strtol(str[18], nullptr, 10));
  5137. if (mob_chat_db.find(id) != nullptr)
  5138. ms->msg_id = id;
  5139. else {
  5140. ms->msg_id = 0;
  5141. ShowWarning("mob_parse_row_mobskilldb: Unknown chat ID %s for monster %d.\n", str[18], mob_id);
  5142. }
  5143. }
  5144. else
  5145. ms->msg_id = 0;
  5146. skill->skill.push_back(ms);
  5147. if (!skill->mob_id) { // Insert new entry
  5148. skill->mob_id = mob_id;
  5149. mob_skill_db.insert({ mob_id, skill });
  5150. }
  5151. return true;
  5152. }
  5153. /*==========================================
  5154. * mob_skill_db.txt reading
  5155. *------------------------------------------*/
  5156. static void mob_readskilldb(const char* basedir, bool silent) {
  5157. if( battle_config.mob_skill_rate == 0 ) {
  5158. ShowStatus("Mob skill use disabled. Not reading mob skills.\n");
  5159. return;
  5160. }
  5161. sv_readdb(basedir, "mob_skill_db.txt", ',', 19, 19, -1, &mob_parse_row_mobskilldb, silent);
  5162. }
  5163. /**
  5164. * mob_skill_db table reading [CalciumKid]
  5165. * not overly sure if this is all correct
  5166. * seems to work though...
  5167. */
  5168. static int mob_read_sqlskilldb(void)
  5169. {
  5170. const char* mob_skill_db_name[] = {
  5171. mob_skill_table,
  5172. mob_skill2_table };
  5173. int fi;
  5174. if( battle_config.mob_skill_rate == 0 ) {
  5175. ShowStatus("Mob skill use disabled. Not reading mob skills.\n");
  5176. return 0;
  5177. }
  5178. for( fi = 0; fi < ARRAYLENGTH(mob_skill_db_name); ++fi ) {
  5179. uint32 lines = 0, count = 0;
  5180. // retrieve all rows from the mob skill database
  5181. if( SQL_ERROR == Sql_Query(mmysql_handle, "SELECT * FROM `%s`", mob_skill_db_name[fi]) ) {
  5182. Sql_ShowDebug(mmysql_handle);
  5183. continue;
  5184. }
  5185. // process rows one by one
  5186. while( SQL_SUCCESS == Sql_NextRow(mmysql_handle) ) {
  5187. // wrap the result into a TXT-compatible format
  5188. char* str[19];
  5189. char dummy[255] = "";
  5190. int i;
  5191. ++lines;
  5192. for( i = 0; i < 19; ++i )
  5193. {
  5194. Sql_GetData(mmysql_handle, i, &str[i], NULL);
  5195. if( str[i] == NULL )
  5196. str[i] = dummy; // get rid of NULL columns
  5197. }
  5198. if (!mob_parse_row_mobskilldb(str, 19, count))
  5199. continue;
  5200. count++;
  5201. }
  5202. // free the query result
  5203. Sql_FreeResult(mmysql_handle);
  5204. ShowStatus("Done reading '" CL_WHITE "%u" CL_RESET "' entries in '" CL_WHITE "%s" CL_RESET "'.\n", count, mob_skill_db_name[fi]);
  5205. }
  5206. return 0;
  5207. }
  5208. const std::string MobItemRatioDatabase::getDefaultLocation() {
  5209. return std::string(db_path) + "/mob_item_ratio.yml";
  5210. }
  5211. /**
  5212. * Reads and parses an entry from the mob_item_ratio.
  5213. * @param node: YAML node containing the entry.
  5214. * @return count of successfully parsed rows
  5215. */
  5216. uint64 MobItemRatioDatabase::parseBodyNode(const ryml::NodeRef& node) {
  5217. std::string item_name;
  5218. if (!this->asString(node, "Item", item_name))
  5219. return 0;
  5220. std::shared_ptr<item_data> item = item_db.search_aegisname(item_name.c_str());
  5221. if (item == nullptr) {
  5222. this->invalidWarning(node["Item"], "Item %s does not exist, skipping.\n", item_name.c_str());
  5223. return 0;
  5224. }
  5225. t_itemid nameid = item->nameid;
  5226. std::shared_ptr<s_mob_item_drop_ratio> data = this->find(nameid);
  5227. bool exists = data != nullptr;
  5228. if (!exists) {
  5229. if (!this->nodesExist(node, { "Ratio" })) {
  5230. return 0;
  5231. }
  5232. data = std::make_shared<s_mob_item_drop_ratio>();
  5233. data->nameid = nameid;
  5234. }
  5235. if (this->nodeExists(node, "Ratio")) {
  5236. uint32 ratio;
  5237. if (!this->asUInt32(node, "Ratio", ratio))
  5238. return 0;
  5239. data->drop_ratio = ratio;
  5240. }
  5241. if (this->nodeExists(node, "List")) {
  5242. const auto& MobNode = node["List"];
  5243. for (const auto& mobit : MobNode) {
  5244. std::string mob_name;
  5245. c4::from_chars(mobit.key(), &mob_name);
  5246. std::shared_ptr<s_mob_db> mob = mobdb_search_aegisname(mob_name.c_str());
  5247. if (mob == nullptr) {
  5248. this->invalidWarning(node["List"], "Unknown mob %s, skipping.\n", mob_name.c_str());
  5249. continue;
  5250. }
  5251. uint16 mob_id = mob->id;
  5252. bool active;
  5253. if (!this->asBool(node["List"], mob_name, active))
  5254. return 0;
  5255. if (!active) {
  5256. util::vector_erase_if_exists(data->mob_ids, mob_id);
  5257. continue;
  5258. }
  5259. data->mob_ids.push_back(mob_id);
  5260. }
  5261. }
  5262. if (!exists)
  5263. this->put(nameid, data);
  5264. return 1;
  5265. }
  5266. /**
  5267. * Adjust drop ratio for each monster
  5268. **/
  5269. static void mob_drop_ratio_adjust(void){
  5270. for( auto &pair : mob_db ){
  5271. std::shared_ptr<s_mob_db> mob = pair.second;
  5272. struct item_data *id;
  5273. t_itemid nameid;
  5274. int j, rate, rate_adjust = 0, mob_id = pair.first;
  5275. if( mob_is_clone( mob_id ) ){
  5276. continue;
  5277. }
  5278. for( j = 0; j < MAX_MVP_DROP_TOTAL; j++ ){
  5279. nameid = mob->mvpitem[j].nameid;
  5280. rate = mob->mvpitem[j].rate;
  5281. if( nameid == 0 || rate == 0 ){
  5282. continue;
  5283. }
  5284. rate_adjust = battle_config.item_rate_mvp;
  5285. // Adjust the rate if there is an entry in mob_item_ratio
  5286. item_dropratio_adjust( nameid, mob_id, &rate_adjust );
  5287. // remove the item if the rate of item_dropratio_adjust is 0
  5288. if (rate_adjust == 0) {
  5289. mob->mvpitem[j].nameid = 0;
  5290. mob->mvpitem[j].rate = 0;
  5291. continue;
  5292. }
  5293. // Adjust rate with given algorithms
  5294. rate = mob_drop_adjust( rate, rate_adjust, battle_config.item_drop_mvp_min, battle_config.item_drop_mvp_max );
  5295. // calculate and store Max available drop chance of the MVP item
  5296. if( rate ){
  5297. id = itemdb_search( nameid );
  5298. // Item is not known anymore(should never happen)
  5299. if( !id ){
  5300. ShowWarning( "Monster \"%s\"(id:%u) is dropping an unknown item(id: %u)\n", mob->name.c_str(), mob_id, nameid );
  5301. mob->mvpitem[j].nameid = 0;
  5302. mob->mvpitem[j].rate = 0;
  5303. continue;
  5304. }
  5305. if( id->maxchance == -1 || ( id->maxchance < rate/10 + 1 ) ){
  5306. // item has bigger drop chance or sold in shops
  5307. id->maxchance = rate/10 + 1; // reduce MVP drop info to not spoil common drop rate
  5308. }
  5309. }
  5310. mob->mvpitem[j].rate = rate;
  5311. }
  5312. for( j = 0; j < MAX_MOB_DROP_TOTAL; j++ ){
  5313. unsigned short ratemin, ratemax;
  5314. bool is_treasurechest;
  5315. nameid = mob->dropitem[j].nameid;
  5316. rate = mob->dropitem[j].rate;
  5317. if( nameid == 0 || rate == 0 ){
  5318. continue;
  5319. }
  5320. id = itemdb_search( nameid );
  5321. // Item is not known anymore(should never happen)
  5322. if( !id ){
  5323. ShowWarning( "Monster \"%s\"(id:%hu) is dropping an unknown item(id: %u)\n", mob->name.c_str(), mob_id, nameid );
  5324. mob->dropitem[j].nameid = 0;
  5325. mob->dropitem[j].rate = 0;
  5326. continue;
  5327. }
  5328. if( battle_config.drop_rateincrease && rate < 5000 ){
  5329. rate++;
  5330. }
  5331. // Treasure box drop rates [Skotlex]
  5332. if (util::vector_exists(mob->race2, RC2_TREASURE)) {
  5333. is_treasurechest = true;
  5334. rate_adjust = battle_config.item_rate_treasure;
  5335. ratemin = battle_config.item_drop_treasure_min;
  5336. ratemax = battle_config.item_drop_treasure_max;
  5337. } else {
  5338. bool is_mvp = mob->get_bosstype() == BOSSTYPE_MVP;
  5339. bool is_boss = mob->get_bosstype() == BOSSTYPE_MINIBOSS;
  5340. is_treasurechest = false;
  5341. // Added suport to restrict normal drops of MVP's [Reddozen]
  5342. switch( id->type ){
  5343. case IT_HEALING:
  5344. rate_adjust = is_mvp ? battle_config.item_rate_heal_mvp : (is_boss ? battle_config.item_rate_heal_boss : battle_config.item_rate_heal);
  5345. ratemin = battle_config.item_drop_heal_min;
  5346. ratemax = battle_config.item_drop_heal_max;
  5347. break;
  5348. case IT_USABLE:
  5349. case IT_CASH:
  5350. rate_adjust = is_mvp ? battle_config.item_rate_use_mvp : (is_boss ? battle_config.item_rate_use_boss : battle_config.item_rate_use);
  5351. ratemin = battle_config.item_drop_use_min;
  5352. ratemax = battle_config.item_drop_use_max;
  5353. break;
  5354. case IT_WEAPON:
  5355. case IT_ARMOR:
  5356. case IT_PETARMOR:
  5357. rate_adjust = is_mvp ? battle_config.item_rate_equip_mvp : (is_boss ? battle_config.item_rate_equip_boss : battle_config.item_rate_equip);
  5358. ratemin = battle_config.item_drop_equip_min;
  5359. ratemax = battle_config.item_drop_equip_max;
  5360. break;
  5361. case IT_CARD:
  5362. rate_adjust = is_mvp ? battle_config.item_rate_card_mvp : (is_boss ? battle_config.item_rate_card_boss : battle_config.item_rate_card);
  5363. ratemin = battle_config.item_drop_card_min;
  5364. ratemax = battle_config.item_drop_card_max;
  5365. break;
  5366. default:
  5367. rate_adjust = is_mvp ? battle_config.item_rate_common_mvp : (is_boss ? battle_config.item_rate_common_boss : battle_config.item_rate_common);
  5368. ratemin = battle_config.item_drop_common_min;
  5369. ratemax = battle_config.item_drop_common_max;
  5370. break;
  5371. }
  5372. }
  5373. item_dropratio_adjust( nameid, mob_id, &rate_adjust );
  5374. // remove the item if the rate of item_dropratio_adjust is 0
  5375. if (rate_adjust == 0) {
  5376. mob->dropitem[j].nameid = 0;
  5377. mob->dropitem[j].rate = 0;
  5378. continue;
  5379. }
  5380. rate = mob_drop_adjust( rate, rate_adjust, ratemin, ratemax );
  5381. // calculate and store Max available drop chance of the item
  5382. // but skip treasure chests.
  5383. if( rate && !is_treasurechest ){
  5384. unsigned short k;
  5385. if( id->maxchance == -1 || ( id->maxchance < rate ) ){
  5386. id->maxchance = rate; // item has bigger drop chance or sold in shops
  5387. }
  5388. for( k = 0; k < MAX_SEARCH; k++ ){
  5389. if( id->mob[k].chance <= rate ){
  5390. break;
  5391. }
  5392. }
  5393. if( k != MAX_SEARCH ){
  5394. if( id->mob[k].id != mob_id ){
  5395. memmove( &id->mob[k+1], &id->mob[k], (MAX_SEARCH-k-1)*sizeof(id->mob[0]) );
  5396. }
  5397. id->mob[k].chance = rate;
  5398. id->mob[k].id = mob_id;
  5399. }
  5400. }
  5401. mob->dropitem[j].rate = rate;
  5402. }
  5403. }
  5404. // Now that we are done we can delete the stored item ratios
  5405. mob_item_drop_ratio.clear();
  5406. }
  5407. const std::string MapDropDatabase::getDefaultLocation(){
  5408. return std::string( db_path ) + "/map_drops.yml";
  5409. }
  5410. uint64 MapDropDatabase::parseBodyNode( const ryml::NodeRef& node ){
  5411. std::string mapname;
  5412. if( !this->asString( node, "Map", mapname ) ){
  5413. return 0;
  5414. }
  5415. uint16 mapindex = mapindex_name2idx( mapname.c_str(), nullptr );
  5416. if( mapindex == 0 ){
  5417. this->invalidWarning( node["Map"], "Unknown map \"%s\".\n", mapname.c_str() );
  5418. return 0;
  5419. }
  5420. int16 mapid = map_mapindex2mapid( mapindex );
  5421. if( mapid < 0 ){
  5422. // Silently ignore. Map might be on a different map-server
  5423. return 0;
  5424. }
  5425. std::shared_ptr<s_map_drops> mapdrops = this->find( mapid );
  5426. bool exists = mapdrops != nullptr;
  5427. if( !exists ){
  5428. mapdrops = std::make_shared<s_map_drops>();
  5429. mapdrops->mapid = mapid;
  5430. }
  5431. if( this->nodeExists( node, "GlobalDrops" ) ){
  5432. const ryml::NodeRef& globalNode = node["GlobalDrops"];
  5433. for( const auto& it : globalNode ){
  5434. if( !this->parseDrop( it, mapdrops->globals ) ){
  5435. return 0;
  5436. }
  5437. }
  5438. }
  5439. if( this->nodeExists( node, "SpecificDrops" ) ){
  5440. const ryml::NodeRef& specificNode = node["SpecificDrops"];
  5441. for( const auto& monsterNode : specificNode ){
  5442. if( !this->nodesExist( monsterNode, { "Monster", "Drops" } ) ){
  5443. return 0;
  5444. }
  5445. std::string mobname;
  5446. if( !this->asString( monsterNode, "Monster", mobname ) ){
  5447. return 0;
  5448. }
  5449. std::shared_ptr<s_mob_db> mob = mobdb_search_aegisname( mobname.c_str() );
  5450. if( mob == nullptr ){
  5451. this->invalidWarning( monsterNode["Monster"], "Unknown monster \"%s\".\n", mobname.c_str() );
  5452. return 0;
  5453. }
  5454. std::unordered_map<uint16, std::shared_ptr<s_mob_drop>>& specificDrops = mapdrops->specific[mob->id];
  5455. for( const auto& it : monsterNode["Drops"] ){
  5456. if( !this->parseDrop( it, specificDrops ) ){
  5457. return 0;
  5458. }
  5459. }
  5460. }
  5461. }
  5462. if( !exists ){
  5463. this->put( mapid, mapdrops );
  5464. }
  5465. return 1;
  5466. }
  5467. bool MapDropDatabase::parseDrop( const ryml::NodeRef& node, std::unordered_map<uint16, std::shared_ptr<s_mob_drop>>& drops ){
  5468. uint16 index;
  5469. if( !this->asUInt16( node, "Index", index ) ){
  5470. return false;
  5471. }
  5472. std::shared_ptr<s_mob_drop> drop = util::umap_find( drops, index );
  5473. bool exists = drop != nullptr;
  5474. if( !exists ){
  5475. if( !this->nodesExist( node, { "Item", "Rate" } ) ){
  5476. return false;
  5477. }
  5478. drop = std::make_shared<s_mob_drop>();
  5479. drop->steal_protected = true;
  5480. }
  5481. if( this->nodeExists( node, "Item" ) ){
  5482. std::string itemname;
  5483. if( !this->asString( node, "Item", itemname ) ){
  5484. return 0;
  5485. }
  5486. std::shared_ptr<item_data> item = item_db.search_aegisname( itemname.c_str() );
  5487. if( item == nullptr ){
  5488. this->invalidWarning( node["Item"], "Item %s does not exist.\n", itemname.c_str() );
  5489. return false;
  5490. }
  5491. drop->nameid = item->nameid;
  5492. }
  5493. if( this->nodeExists( node, "Rate" ) ){
  5494. uint32 rate;
  5495. if( !this->asUInt32Rate( node, "Rate", rate, 100000 ) ){
  5496. return false;
  5497. }
  5498. if( rate == 0 ){
  5499. if( exists ){
  5500. drops.erase( index );
  5501. return true;
  5502. }else{
  5503. this->invalidWarning( node["Rate"], "Rate %" PRIu32 " is below minimum of 1.\n", rate );
  5504. return false;
  5505. }
  5506. }else if( rate > 100000 ){
  5507. this->invalidWarning( node["Rate"], "Rate %" PRIu32 " exceeds maximum of 100000.\n", rate );
  5508. return false;
  5509. }
  5510. drop->rate = rate;
  5511. }
  5512. if( this->nodeExists( node, "RandomOptionGroup" ) ){
  5513. std::string name;
  5514. if( !this->asString( node, "RandomOptionGroup", name ) ){
  5515. return false;
  5516. }
  5517. if( !random_option_group.option_get_id( name, drop->randomopt_group ) ){
  5518. this->invalidWarning( node["RandomOptionGroup"], "Unknown random option group \"%s\".\n", name.c_str() );
  5519. return false;
  5520. }
  5521. }else{
  5522. if( !exists ){
  5523. drop->randomopt_group = 0;
  5524. }
  5525. }
  5526. if( !exists ){
  5527. drops[index] = drop;
  5528. }
  5529. return true;
  5530. }
  5531. /**
  5532. * Copy skill from DB to monster
  5533. * @param mob Monster DB entry
  5534. * @param skill Monster skill entries
  5535. **/
  5536. static void mob_skill_db_set_single_sub(std::shared_ptr<s_mob_db> mob, struct s_mob_skill_db *skill) {
  5537. nullpo_retv(skill);
  5538. if (mob == nullptr)
  5539. return;
  5540. size_t i = 0;
  5541. for (i = 0; mob->skill.size() < MAX_MOBSKILL && i < skill->skill.size(); i++) {
  5542. mob->skill.push_back(skill->skill[i]);
  5543. }
  5544. if (i < skill->skill.size())
  5545. ShowWarning("Monster '%s' (%d, src:%d) reaches max skill limit %d. Ignores '%zu' skills left.\n", mob->sprite.c_str(), mob->id, skill->mob_id, MAX_MOBSKILL, skill->skill.size() - i);
  5546. }
  5547. /**
  5548. * Check the skill & monster id before put the skills
  5549. * @param skill
  5550. **/
  5551. static void mob_skill_db_set_single(struct s_mob_skill_db *skill) {
  5552. nullpo_retv(skill);
  5553. // Specific monster
  5554. if (skill->mob_id >= 0) {
  5555. std::shared_ptr<s_mob_db> mob = mob_db.find(skill->mob_id);
  5556. if (mob != nullptr)
  5557. mob_skill_db_set_single_sub(mob, skill);
  5558. }
  5559. // Global skill
  5560. else {
  5561. uint16 id = skill->mob_id;
  5562. id *= -1;
  5563. for( auto &pair : mob_db ){
  5564. if ( mob_is_clone(pair.first) ){
  5565. continue;
  5566. }
  5567. if ( (!(id&1) && status_has_mode(&pair.second->status,MD_STATUSIMMUNE)) // Bosses
  5568. || (!(id&2) && !status_has_mode(&pair.second->status,MD_STATUSIMMUNE)) // Normal monsters
  5569. )
  5570. continue;
  5571. mob_skill_db_set_single_sub(pair.second, skill);
  5572. }
  5573. }
  5574. }
  5575. /**
  5576. * Set monster skills
  5577. **/
  5578. static void mob_skill_db_set(void) {
  5579. for (auto skill : mob_skill_db) {
  5580. mob_skill_db_set_single(skill.second.get());
  5581. }
  5582. //ShowStatus("Set skills to '%d' monsters.\n", db_size(mob_skill_db));
  5583. }
  5584. /**
  5585. * read all mob-related databases
  5586. */
  5587. static void mob_load(void)
  5588. {
  5589. const char* dbsubpath[] = {
  5590. "",
  5591. "/" DBIMPORT,
  5592. };
  5593. // First we parse all the possible monsters to add additional data in the second loop
  5594. if( db_use_sqldbs )
  5595. mob_read_sqldb();
  5596. else
  5597. mob_db.load();
  5598. mob_chat_db.load(); // load before mob_skill_db
  5599. for(int i = 0; i < ARRAYLENGTH(dbsubpath); i++){
  5600. int n1 = strlen(db_path)+strlen(dbsubpath[i])+1;
  5601. int n2 = strlen(db_path)+strlen(DBPATH)+strlen(dbsubpath[i])+1;
  5602. char* dbsubpath1 = (char*)aMalloc(n1+1);
  5603. char* dbsubpath2 = (char*)aMalloc(n2+1);
  5604. bool silent = i > 0;
  5605. if(i==0) {
  5606. safesnprintf(dbsubpath1,n1,"%s%s",db_path,dbsubpath[i]);
  5607. safesnprintf(dbsubpath2,n2,"%s/%s%s",db_path,DBPATH,dbsubpath[i]);
  5608. } else {
  5609. safesnprintf(dbsubpath1,n1,"%s%s",db_path,dbsubpath[i]);
  5610. safesnprintf(dbsubpath2,n1,"%s%s",db_path,dbsubpath[i]);
  5611. }
  5612. if( db_use_sqldbs && i == 0 )
  5613. mob_read_sqlskilldb();
  5614. else
  5615. mob_readskilldb(dbsubpath2, silent);
  5616. aFree(dbsubpath1);
  5617. aFree(dbsubpath2);
  5618. }
  5619. mob_item_drop_ratio.load();
  5620. mob_avail_db.load();
  5621. mob_summon_db.load();
  5622. map_drop_db.load();
  5623. mob_drop_ratio_adjust();
  5624. mob_skill_db_set();
  5625. }
  5626. /**
  5627. * Initialize monster data
  5628. */
  5629. void mob_db_load(bool is_reload){
  5630. if( !is_reload ) {
  5631. // on mobdbreload it's not neccessary to execute this
  5632. // item ers needs to be allocated only once
  5633. item_drop_ers = ers_new(sizeof(struct item_drop),"mob.cpp::item_drop_ers",ERS_OPT_CLEAN);
  5634. item_drop_list_ers = ers_new(sizeof(struct item_drop_list),"mob.cpp::item_drop_list_ers",ERS_OPT_NONE);
  5635. }
  5636. mob_load();
  5637. }
  5638. /**
  5639. * Re-link monster drop data with item data
  5640. * Fixes the need of a @reloadmobdb after a @reloaditemdb
  5641. * @author Epoque
  5642. */
  5643. void mob_reload_itemmob_data(void) {
  5644. for( auto const &pair : mob_db ){
  5645. int d, k;
  5646. if( mob_is_clone( pair.first ) ){
  5647. continue;
  5648. }
  5649. for(d = 0; d < MAX_MOB_DROP_TOTAL; d++) {
  5650. struct item_data *id;
  5651. if( !pair.second->dropitem[d].nameid )
  5652. continue;
  5653. id = itemdb_search(pair.second->dropitem[d].nameid);
  5654. for (k = 0; k < MAX_SEARCH; k++) {
  5655. if (id->mob[k].chance <= pair.second->dropitem[d].rate)
  5656. break;
  5657. }
  5658. if (k == MAX_SEARCH)
  5659. continue;
  5660. if (id->mob[k].id != pair.first)
  5661. memmove(&id->mob[k+1], &id->mob[k], (MAX_SEARCH-k-1)*sizeof(id->mob[0]));
  5662. id->mob[k].chance = pair.second->dropitem[d].rate;
  5663. id->mob[k].id = pair.first;
  5664. }
  5665. }
  5666. }
  5667. /**
  5668. * Apply the proper view data on monsters during mob_db reload.
  5669. * @param md: Mob to adjust
  5670. * @param args: va_list of arguments
  5671. * @return 0
  5672. */
  5673. static int mob_reload_sub( struct mob_data *md, va_list args ){
  5674. // Slaves have to be killed
  5675. if( md->master_id != 0 ){
  5676. unit_remove_map( &md->bl, CLR_OUTSIGHT );
  5677. return 0;
  5678. }
  5679. // Relink the mob to the new database entry
  5680. md->db = mob_db.find(md->mob_id);
  5681. if( md->db == nullptr ){
  5682. ShowWarning( "mob_reload_sub: Monster %s (ID: %hu) does not exist anymore.\n", md->name, md->mob_id );
  5683. if( md->bl.prev != nullptr ){
  5684. ShowDebug( "mob_reload_sub: The monster was removed from map %s (%hu/%hu).\n", map_mapid2mapname( md->bl.m ), md->bl.x, md->bl.y );
  5685. }
  5686. unit_remove_map( &md->bl, CLR_OUTSIGHT );
  5687. return 0;
  5688. }
  5689. // Recalculate the monster status based on the new data
  5690. status_calc_mob(md, SCO_NONE);
  5691. // If the view data was not overwritten manually
  5692. if( !md->vd_changed ){
  5693. // Get the new view data from the mob database
  5694. md->vd = mob_get_viewdata(md->mob_id);
  5695. // If they are spawned right now
  5696. if( md->bl.prev != nullptr ){
  5697. // Respawn all mobs on client side so that they are displayed correctly(if their view id changed)
  5698. clif_clearunit_area(&md->bl, CLR_OUTSIGHT);
  5699. clif_spawn(&md->bl);
  5700. }
  5701. }
  5702. return 0;
  5703. }
  5704. /**
  5705. * Apply the proper view data on NPCs during mob_db reload.
  5706. * @param md: NPC to adjust
  5707. * @param args: va_list of arguments
  5708. * @return 0
  5709. */
  5710. static int mob_reload_sub_npc( struct npc_data *nd, va_list args ){
  5711. // If the view data points to a mob
  5712. if( mobdb_checkid(nd->class_) ){
  5713. struct view_data *vd = mob_get_viewdata(nd->class_);
  5714. if (vd) // Get the new view data from the mob database
  5715. memcpy(&nd->vd, vd, sizeof(struct view_data));
  5716. if (nd->bl.prev) // If they are spawned right now
  5717. unit_refresh(&nd->bl); // Respawn all NPCs on client side so that they are displayed correctly(if their view id changed)
  5718. }
  5719. return 0;
  5720. }
  5721. /**
  5722. * Reload monster data
  5723. */
  5724. void mob_reload(void) {
  5725. do_final_mob(true);
  5726. mob_db_load(true);
  5727. map_foreachmob(mob_reload_sub);
  5728. map_foreachnpc(mob_reload_sub_npc);
  5729. }
  5730. /**
  5731. * Clear spawn data for all monsters
  5732. */
  5733. void mob_clear_spawninfo()
  5734. { //Clears spawn related information for a script reload.
  5735. mob_spawn_data.clear();
  5736. }
  5737. /*==========================================
  5738. * Circumference initialization of mob
  5739. *------------------------------------------*/
  5740. void do_init_mob(void){
  5741. mob_db_load(false);
  5742. add_timer_func_list(mob_delayspawn,"mob_delayspawn");
  5743. add_timer_func_list(mob_delay_item_drop,"mob_delay_item_drop");
  5744. add_timer_func_list(mob_ai_hard,"mob_ai_hard");
  5745. add_timer_func_list(mob_ai_lazy,"mob_ai_lazy");
  5746. add_timer_func_list(mob_timer_delete,"mob_timer_delete");
  5747. add_timer_func_list(mob_spawn_guardian_sub,"mob_spawn_guardian_sub");
  5748. add_timer_func_list(mob_respawn,"mob_respawn");
  5749. add_timer_func_list(mvptomb_delayspawn,"mvptomb_delayspawn");
  5750. add_timer_interval(gettick()+MIN_MOBTHINKTIME,mob_ai_hard,0,0,MIN_MOBTHINKTIME);
  5751. add_timer_interval(gettick()+MIN_MOBTHINKTIME*10,mob_ai_lazy,0,0,MIN_MOBTHINKTIME*10);
  5752. }
  5753. /*==========================================
  5754. * Clean memory usage.
  5755. *------------------------------------------*/
  5756. void do_final_mob(bool is_reload){
  5757. mob_db.clear();
  5758. mob_chat_db.clear();
  5759. mob_skill_db.clear();
  5760. mob_item_drop_ratio.clear();
  5761. mob_summon_db.clear();
  5762. map_drop_db.clear();
  5763. if( !is_reload ) {
  5764. ers_destroy(item_drop_ers);
  5765. ers_destroy(item_drop_list_ers);
  5766. }
  5767. }