mob.cpp 217 KB

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