mob.cpp 206 KB

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