mob.cpp 201 KB

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