npc.cpp 184 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "npc.hpp"
  4. #include <errno.h>
  5. #include <map>
  6. #include <stdlib.h>
  7. #include <vector>
  8. #include "../common/cbasetypes.hpp"
  9. #include "../common/db.hpp"
  10. #include "../common/ers.hpp"
  11. #include "../common/malloc.hpp"
  12. #include "../common/nullpo.hpp"
  13. #include "../common/showmsg.hpp"
  14. #include "../common/strlib.hpp"
  15. #include "../common/timer.hpp"
  16. #include "../common/utilities.hpp"
  17. #include "../common/utils.hpp"
  18. #include "battle.hpp"
  19. #include "chat.hpp"
  20. #include "clif.hpp"
  21. #include "date.hpp" // days of week enum
  22. #include "guild.hpp"
  23. #include "instance.hpp"
  24. #include "intif.hpp"
  25. #include "log.hpp"
  26. #include "log.hpp"
  27. #include "map.hpp"
  28. #include "mob.hpp"
  29. #include "navi.hpp"
  30. #include "pc.hpp"
  31. #include "pet.hpp"
  32. #include "script.hpp" // script_config
  33. using namespace rathena;
  34. struct npc_data* fake_nd;
  35. // linked list of npc source files
  36. struct npc_src_list {
  37. struct npc_src_list* next;
  38. char name[4]; // dynamic array, the structure is allocated with extra bytes (string length)
  39. };
  40. static struct npc_src_list* npc_src_files = NULL;
  41. static int npc_id=START_NPC_NUM;
  42. static int npc_warp=0;
  43. static int npc_shop=0;
  44. static int npc_script=0;
  45. static int npc_mob=0;
  46. static int npc_delay_mob=0;
  47. static int npc_cache_mob=0;
  48. struct eri *npc_sc_display_ers;
  49. // Market Shop
  50. #if PACKETVER >= 20131223
  51. struct s_npc_market {
  52. struct npc_item_list *list;
  53. char exname[NPC_NAME_LENGTH+1];
  54. uint16 count;
  55. };
  56. static DBMap *NPCMarketDB; /// Stock persistency! Temporary market stocks from `market` table. struct s_npc_market, key: NPC exname
  57. static void npc_market_checkall(void);
  58. static void npc_market_fromsql(void);
  59. #define npc_market_delfromsql(exname,nameid) (npc_market_delfromsql_((exname), (nameid), false))
  60. #define npc_market_clearfromsql(exname) (npc_market_delfromsql_((exname), 0, true))
  61. #endif
  62. TIMER_FUNC(npc_dynamicnpc_removal_timer);
  63. /// Returns a new npc id that isn't being used in id_db.
  64. /// Fatal error if nothing is available.
  65. int npc_get_new_npc_id(void) {
  66. if( npc_id >= START_NPC_NUM && !map_blid_exists(npc_id) )
  67. return npc_id++;// available
  68. else {// find next id
  69. int base_id = npc_id;
  70. while( base_id != ++npc_id ) {
  71. if( npc_id < START_NPC_NUM )
  72. npc_id = START_NPC_NUM;
  73. if( !map_blid_exists(npc_id) )
  74. return npc_id++;// available
  75. }
  76. // full loop, nothing available
  77. ShowFatalError("npc_get_new_npc_id: All ids are taken. Exiting...");
  78. exit(1);
  79. }
  80. }
  81. static DBMap* ev_db; // const char* event_name -> struct event_data*
  82. static DBMap* npcname_db; // const char* npc_name -> struct npc_data*
  83. struct event_data {
  84. struct npc_data *nd;
  85. int pos;
  86. };
  87. static struct eri *timer_event_ers; //For the npc timer data. [Skotlex]
  88. /* hello */
  89. static char *npc_last_path;
  90. static char *npc_last_ref;
  91. struct npc_path_data {
  92. char* path;
  93. unsigned short references;
  94. };
  95. struct npc_path_data *npc_last_npd;
  96. static DBMap *npc_path_db;
  97. //For holding the view data of npc classes. [Skotlex]
  98. static struct view_data npc_viewdb[MAX_NPC_CLASS];
  99. static struct view_data npc_viewdb2[MAX_NPC_CLASS2_END-MAX_NPC_CLASS2_START];
  100. struct script_event_s{
  101. struct event_data *event;
  102. const char *event_name;
  103. };
  104. // Holds pointers to the commonly executed scripts for speedup. [Skotlex]
  105. std::map<enum npce_event, std::vector<struct script_event_s>> script_event;
  106. // Static functions
  107. static struct npc_data* npc_create_npc( int16 m, int16 x, int16 y );
  108. static void npc_parsename( struct npc_data* nd, const char* name, const char* start, const char* buffer, const char* filepath );
  109. const std::string StylistDatabase::getDefaultLocation(){
  110. return std::string(db_path) + "/stylist.yml";
  111. }
  112. bool StylistDatabase::parseCostNode( std::shared_ptr<s_stylist_entry> entry, bool doram, const ryml::NodeRef& node ){
  113. std::shared_ptr<s_stylist_costs> costs = doram ? entry->doram : entry->human;
  114. bool costs_exists = costs != nullptr;
  115. if( !costs_exists ){
  116. costs = std::make_shared<s_stylist_costs>();
  117. }
  118. if( this->nodeExists( node, "Price" ) ){
  119. uint32 price;
  120. if( !this->asUInt32( node, "Price", price ) ){
  121. return false;
  122. }
  123. if( price > MAX_ZENY ){
  124. this->invalidWarning( node["Price"], "stylist_parseCostNode: Price %u is too high, capping to MAX_ZENY...\n", price );
  125. price = MAX_ZENY;
  126. }
  127. costs->price = price;
  128. }else{
  129. if( !costs_exists ){
  130. costs->price = 0;
  131. }
  132. }
  133. if( this->nodeExists( node, "RequiredItem" ) ){
  134. std::string item;
  135. if( !this->asString( node, "RequiredItem", item ) ){
  136. return false;
  137. }
  138. std::shared_ptr<item_data> id = item_db.search_aegisname( item.c_str() );
  139. if( id == nullptr ){
  140. this->invalidWarning( node["RequiredItem"], "stylist_parseCostNode: Unknown item \"%s\"...\n", item.c_str() );
  141. return false;
  142. }
  143. costs->requiredItem = id->nameid;
  144. }else{
  145. if( !costs_exists ){
  146. costs->requiredItem = 0;
  147. }
  148. }
  149. if( this->nodeExists( node, "RequiredItemBox" ) ){
  150. std::string item;
  151. if( !this->asString( node, "RequiredItemBox", item ) ){
  152. return false;
  153. }
  154. std::shared_ptr<item_data> id = item_db.search_aegisname( item.c_str() );
  155. if( id == nullptr ){
  156. this->invalidWarning( node["RequiredItemBox"], "stylist_parseCostNode: Unknown item \"%s\"...\n", item.c_str() );
  157. return false;
  158. }
  159. costs->requiredItemBox = id->nameid;
  160. }else{
  161. if( !costs_exists ){
  162. costs->requiredItemBox = 0;
  163. }
  164. }
  165. if( !costs_exists ){
  166. if( doram ){
  167. entry->doram = costs;
  168. }else{
  169. entry->human = costs;
  170. }
  171. }
  172. return true;
  173. }
  174. uint64 StylistDatabase::parseBodyNode( const ryml::NodeRef& node ){
  175. if( !this->nodesExist( node, { "Look", "Options" } ) ){
  176. return 0;
  177. }
  178. std::string look_str;
  179. if( !this->asString( node, "Look", look_str ) ){
  180. return 0;
  181. }
  182. int64 constant;
  183. if( !script_get_constant( ( "LOOK_" + look_str ).c_str(), &constant ) ){
  184. this->invalidWarning( node["Look"], "stylist_parseBodyNode: Invalid look %s.\n", look_str.c_str() );
  185. return 0;
  186. }
  187. switch( constant ){
  188. case LOOK_HEAD_TOP:
  189. case LOOK_HEAD_MID:
  190. case LOOK_HEAD_BOTTOM:
  191. case LOOK_HAIR:
  192. case LOOK_HAIR_COLOR:
  193. case LOOK_CLOTHES_COLOR:
  194. case LOOK_BODY2:
  195. break;
  196. default:
  197. this->invalidWarning( node["Look"], "stylist_parseBodyNode: Unsupported look value \"%s\"...\n", look_str.c_str() );
  198. return 0;
  199. }
  200. std::shared_ptr<s_stylist_list> list = this->find( (uint32)constant );
  201. bool exists = list != nullptr;
  202. uint64 count = 0;
  203. if( !exists ){
  204. list = std::make_shared<s_stylist_list>();
  205. list->look = (uint16)constant;
  206. }
  207. for( const ryml::NodeRef& optionNode : node["Options"] ){
  208. int16 index;
  209. if( !this->asInt16( optionNode, "Index", index ) ){
  210. return 0;
  211. }
  212. if( index == 0 ){
  213. this->invalidWarning( optionNode["Index"], "stylist_parseBodyNode: Unsupported index value \"%hd\"...\n", index );
  214. return 0;
  215. }
  216. std::shared_ptr<s_stylist_entry> entry = util::umap_find( list->entries, index );
  217. bool entry_exists = entry != nullptr;
  218. if( !entry_exists ){
  219. entry = std::make_shared<s_stylist_entry>();
  220. entry->look = list->look;
  221. entry->index = index;
  222. if( !this->nodesExist( optionNode, { "Value" } ) ){
  223. return 0;
  224. }
  225. }
  226. if( this->nodeExists( optionNode, "Value" ) ){
  227. uint32 value;
  228. switch( list->look ){
  229. case LOOK_HEAD_TOP:
  230. case LOOK_HEAD_MID:
  231. case LOOK_HEAD_BOTTOM: {
  232. std::string item;
  233. if( !this->asString( optionNode, "Value", item ) ){
  234. return 0;
  235. }
  236. std::shared_ptr<item_data> id = item_db.search_aegisname( item.c_str() );
  237. if( id == nullptr ){
  238. this->invalidWarning( optionNode["Value"], "stylist_parseBodyNode: Unknown item \"%s\"...\n", item.c_str() );
  239. return 0;
  240. }
  241. value = id->nameid;
  242. } break;
  243. case LOOK_HAIR:
  244. if( !this->asUInt32( optionNode, "Value", value ) ){
  245. return 0;
  246. }
  247. if( value < MIN_HAIR_STYLE ){
  248. this->invalidWarning( optionNode["Value"], "stylist_parseBodyNode: hair style \"%u\" is too low...\n", value );
  249. return 0;
  250. }else if( value > MAX_HAIR_STYLE ){
  251. this->invalidWarning( optionNode["Value"], "stylist_parseBodyNode: hair style \"%u\" is too high...\n", value );
  252. return 0;
  253. }
  254. break;
  255. case LOOK_HAIR_COLOR:
  256. if( !this->asUInt32( optionNode, "Value", value ) ){
  257. return 0;
  258. }
  259. if( value < MIN_HAIR_COLOR ){
  260. this->invalidWarning( optionNode["Value"], "stylist_parseBodyNode: hair color \"%u\" is too low...\n", value );
  261. return 0;
  262. }else if( value > MAX_HAIR_COLOR ){
  263. this->invalidWarning( optionNode["Value"], "stylist_parseBodyNode: hair color \"%u\" is too high...\n", value );
  264. return 0;
  265. }
  266. break;
  267. case LOOK_CLOTHES_COLOR:
  268. if( !this->asUInt32( optionNode, "Value", value ) ){
  269. return 0;
  270. }
  271. if( value < MIN_CLOTH_COLOR ){
  272. this->invalidWarning( optionNode["Value"], "stylist_parseBodyNode: cloth color \"%u\" is too low...\n", value );
  273. return 0;
  274. }else if( value > MAX_CLOTH_COLOR ){
  275. this->invalidWarning( optionNode["Value"], "stylist_parseBodyNode: cloth color \"%u\" is too high...\n", value );
  276. return 0;
  277. }
  278. break;
  279. case LOOK_BODY2:
  280. if( !this->asUInt32( optionNode, "Value", value ) ){
  281. return 0;
  282. }
  283. if( value < MIN_BODY_STYLE ){
  284. this->invalidWarning( optionNode["Value"], "stylist_parseBodyNode: body style \"%u\" is too low...\n", value );
  285. return 0;
  286. }else if( value > MAX_BODY_STYLE ){
  287. this->invalidWarning( optionNode["Value"], "stylist_parseBodyNode: body style \"%u\" is too high...\n", value );
  288. return 0;
  289. }
  290. break;
  291. }
  292. entry->value = value;
  293. }
  294. if( this->nodeExists( optionNode, "CostsHuman" ) ) {
  295. if( !this->parseCostNode( entry, false, optionNode["CostsHuman"] ) ){
  296. return 0;
  297. }
  298. }else{
  299. if( !entry_exists ){
  300. entry->human = nullptr;
  301. }
  302. }
  303. if( this->nodeExists( optionNode, "CostsDoram" ) ) {
  304. if( !this->parseCostNode( entry, true, optionNode["CostsDoram"] ) ){
  305. return 0;
  306. }
  307. }else{
  308. if( !entry_exists ){
  309. entry->doram = nullptr;
  310. }
  311. }
  312. if( !entry_exists ){
  313. list->entries[index] = entry;
  314. }
  315. count++;
  316. }
  317. if( !exists ){
  318. this->put( (uint32)constant, list );
  319. }
  320. return count;
  321. }
  322. StylistDatabase stylist_db;
  323. const std::string BarterDatabase::getDefaultLocation(){
  324. return "npc/barters.yml";
  325. }
  326. uint64 BarterDatabase::parseBodyNode( const ryml::NodeRef& node ){
  327. std::string npcname;
  328. if( !this->asString( node, "Name", npcname ) ){
  329. return 0;
  330. }
  331. std::shared_ptr<s_npc_barter> barter = this->find( npcname );
  332. bool exists = barter != nullptr;
  333. if( !exists ){
  334. barter = std::make_shared<s_npc_barter>();
  335. barter->name = npcname;
  336. }
  337. if( this->nodeExists( node, "Map" ) ){
  338. std::string map;
  339. if( !this->asString( node, "Map", map ) ){
  340. return 0;
  341. }
  342. uint16 index = mapindex_name2idx( map.c_str(), nullptr );
  343. if( index == 0 ){
  344. this->invalidWarning( node["Map"], "barter_parseBodyNode: Unknown mapname %s, skipping.\n", map.c_str());
  345. return 0;
  346. }
  347. barter->m = map_mapindex2mapid( index );
  348. // Skip silently if the map is not on this map-server
  349. if( barter->m < 0 ){
  350. return 1;
  351. }
  352. }else{
  353. if( !exists ){
  354. barter->m = -1;
  355. }
  356. }
  357. struct map_data* mapdata = nullptr;
  358. if( barter->m >= 0 ){
  359. mapdata = map_getmapdata( barter->m );
  360. }
  361. if( this->nodeExists( node, "X" ) ){
  362. uint16 x;
  363. if( !this->asUInt16( node, "X", x ) ){
  364. return 0;
  365. }
  366. if( mapdata == nullptr ){
  367. this->invalidWarning( node["X"], "barter_parseBodyNode: Barter NPC is not on a map. Ignoring X coordinate...\n" );
  368. x = 0;
  369. }else if( x >= mapdata->xs ){
  370. this->invalidWarning( node["X"], "barter_parseBodyNode: X coordinate %hu is out of bound %hu...\n", x, mapdata->xs );
  371. return 0;
  372. }
  373. barter->x = x;
  374. }else{
  375. if( !exists ){
  376. barter->x = 0;
  377. }
  378. }
  379. if( this->nodeExists( node, "Y" ) ){
  380. uint16 y;
  381. if( !this->asUInt16( node, "Y", y ) ){
  382. return 0;
  383. }
  384. if( mapdata == nullptr ){
  385. this->invalidWarning( node["Y"], "barter_parseBodyNode: Barter NPC is not on a map. Ignoring Y coordinate...\n" );
  386. y = 0;
  387. }else if( y >= mapdata->ys ){
  388. this->invalidWarning( node["Y"], "barter_parseBodyNode: Y coordinate %hu is out of bound %hu...\n", y, mapdata->ys );
  389. return 0;
  390. }
  391. barter->y = y;
  392. }else{
  393. if( !exists ){
  394. barter->y = 0;
  395. }
  396. }
  397. if( this->nodeExists( node, "Direction" ) ){
  398. std::string direction_name;
  399. if( !this->asString( node, "Direction", direction_name ) ){
  400. return 0;
  401. }
  402. int64 constant;
  403. if( !script_get_constant( ( "DIR_" + direction_name ).c_str(), &constant ) ){
  404. this->invalidWarning( node["Direction"], "barter_parseBodyNode: Unknown direction %s, skipping.\n", direction_name.c_str() );
  405. return 0;
  406. }
  407. if( constant < DIR_NORTH || constant >= DIR_MAX ){
  408. this->invalidWarning( node["Direction"], "barter_parseBodyNode: Invalid direction %s, defaulting to North.\n", direction_name.c_str() );
  409. constant = DIR_NORTH;
  410. }
  411. barter->dir = (uint8)constant;
  412. }else{
  413. if( !exists ){
  414. barter->dir = (uint8)DIR_NORTH;
  415. }
  416. }
  417. if( this->nodeExists( node, "Sprite" ) ){
  418. std::string sprite_name;
  419. if( !this->asString( node, "Sprite", sprite_name ) ){
  420. return 0;
  421. }
  422. int64 constant;
  423. if( !script_get_constant( sprite_name.c_str(), &constant ) ){
  424. this->invalidWarning( node["Sprite"], "barter_parseBodyNode: Unknown sprite name %s, skipping.\n", sprite_name.c_str());
  425. return 0;
  426. }
  427. if( constant != JT_FAKENPC && !npcdb_checkid( constant ) ){
  428. this->invalidWarning( node["Sprite"], "barter_parseBodyNode: Invalid sprite name %s, skipping.\n", sprite_name.c_str());
  429. return 0;
  430. }
  431. barter->sprite = (int16)constant;
  432. }else{
  433. if( !exists ){
  434. barter->sprite = JT_FAKENPC;
  435. }
  436. }
  437. if( this->nodeExists( node, "Items" ) ){
  438. for( const ryml::NodeRef& itemNode : node["Items"] ){
  439. uint16 index;
  440. if( !this->asUInt16( itemNode, "Index", index ) ){
  441. return 0;
  442. }
  443. std::shared_ptr<s_npc_barter_item> item = util::map_find( barter->items, index );
  444. bool item_exists = item != nullptr;
  445. if( !item_exists ){
  446. if( !this->nodesExist( itemNode, { "Item" } ) ){
  447. return 0;
  448. }
  449. item = std::make_shared<s_npc_barter_item>();
  450. item->index = index;
  451. }
  452. if( this->nodeExists( itemNode, "Item" ) ){
  453. std::string aegis_name;
  454. if( !this->asString( itemNode, "Item", aegis_name ) ){
  455. return 0;
  456. }
  457. std::shared_ptr<item_data> id = item_db.search_aegisname( aegis_name.c_str() );
  458. if( id == nullptr ){
  459. this->invalidWarning( itemNode["Item"], "barter_parseBodyNode: Unknown item %s.\n", aegis_name.c_str() );
  460. return 0;
  461. }
  462. item->nameid = id->nameid;
  463. }
  464. if( this->nodeExists( itemNode, "Stock" ) ){
  465. uint32 stock;
  466. if( !this->asUInt32( itemNode, "Stock", stock ) ){
  467. return 0;
  468. }
  469. item->stock = stock;
  470. item->stockLimited = ( stock > 0 );
  471. }else{
  472. if( !item_exists ){
  473. item->stock = 0;
  474. item->stockLimited = false;
  475. }
  476. }
  477. if( this->nodeExists( itemNode, "Zeny" ) ){
  478. uint32 zeny;
  479. if( !this->asUInt32( itemNode, "Zeny", zeny ) ){
  480. return 0;
  481. }
  482. if( zeny > MAX_ZENY ){
  483. this->invalidWarning( itemNode["Zeny"], "barter_parseBodyNode: Zeny price %u is above MAX_ZENY (%u), capping...\n", zeny, MAX_ZENY );
  484. zeny = MAX_ZENY;
  485. }
  486. item->price = zeny;
  487. }else{
  488. if( !item_exists ){
  489. item->price = 0;
  490. }
  491. }
  492. if( this->nodeExists( itemNode, "RequiredItems" ) ){
  493. for( const ryml::NodeRef& requiredItemNode : itemNode["RequiredItems"] ){
  494. uint16 requirement_index;
  495. if( !this->asUInt16( requiredItemNode, "Index", requirement_index ) ){
  496. return 0;
  497. }
  498. if( requirement_index >= MAX_BARTER_REQUIREMENTS ){
  499. this->invalidWarning( requiredItemNode["Index"], "barter_parseBodyNode: Index %hu is out of bounds. Barters support up to %d requirements.\n", requirement_index, MAX_BARTER_REQUIREMENTS );
  500. return 0;
  501. }
  502. std::shared_ptr<s_npc_barter_requirement> requirement = util::map_find( item->requirements, requirement_index );
  503. bool requirement_exists = requirement != nullptr;
  504. if( !requirement_exists ){
  505. if( !this->nodesExist( requiredItemNode, { "Item" } ) ){
  506. return 0;
  507. }
  508. requirement = std::make_shared<s_npc_barter_requirement>();
  509. requirement->index = requirement_index;
  510. }
  511. if( this->nodeExists( requiredItemNode, "Item" ) ){
  512. std::string aegis_name;
  513. if( !this->asString( requiredItemNode, "Item", aegis_name ) ){
  514. return 0;
  515. }
  516. std::shared_ptr<item_data> data = item_db.search_aegisname( aegis_name.c_str() );
  517. if( data == nullptr ){
  518. this->invalidWarning( requiredItemNode["Item"], "barter_parseBodyNode: Unknown required item %s.\n", aegis_name.c_str() );
  519. return 0;
  520. }
  521. requirement->nameid = data->nameid;
  522. }
  523. if( this->nodeExists( requiredItemNode, "Amount" ) ){
  524. uint16 amount;
  525. if( !this->asUInt16( requiredItemNode, "Amount", amount ) ){
  526. return 0;
  527. }
  528. if( amount > MAX_AMOUNT ){
  529. this->invalidWarning( requiredItemNode["Amount"], "barter_parseBodyNode: Amount %hu is too high, capping to %hu...\n", amount, MAX_AMOUNT );
  530. amount = MAX_AMOUNT;
  531. }
  532. requirement->amount = amount;
  533. }else{
  534. if( !requirement_exists ){
  535. requirement->amount = 1;
  536. }
  537. }
  538. if( this->nodeExists( requiredItemNode, "Refine" ) ){
  539. std::shared_ptr<item_data> data = item_db.find( requirement->nameid );
  540. if( data->flag.no_refine ){
  541. this->invalidWarning( requiredItemNode["Refine"], "barter_parseBodyNode: Item %s is not refineable.\n", data->name.c_str() );
  542. return 0;
  543. }
  544. int16 refine;
  545. if( !this->asInt16( requiredItemNode, "Refine", refine ) ){
  546. return 0;
  547. }
  548. if( refine > MAX_REFINE ){
  549. this->invalidWarning( requiredItemNode["Amount"], "barter_parseBodyNode: Refine %hd is too high, capping to %d.\n", refine, MAX_REFINE );
  550. refine = MAX_REFINE;
  551. }
  552. requirement->refine = (int8)refine;
  553. }else{
  554. if( !requirement_exists ){
  555. requirement->refine = -1;
  556. }
  557. }
  558. if( !requirement_exists ){
  559. item->requirements[requirement->index] = requirement;
  560. }
  561. }
  562. }
  563. if( !item_exists ){
  564. barter->items[index] = item;
  565. }
  566. }
  567. }
  568. if( !exists ){
  569. this->put( npcname, barter );
  570. }
  571. return 1;
  572. }
  573. void BarterDatabase::loadingFinished(){
  574. for( const auto& pair : *this ){
  575. if( !battle_config.feature_barter && !battle_config.feature_barter_extended ){
  576. #ifndef BUILDBOT
  577. ShowError( "Barter system is not enabled.\n" );
  578. #endif
  579. return;
  580. }
  581. std::shared_ptr<s_npc_barter> barter = pair.second;
  582. struct npc_data* nd = npc_create_npc( barter->m, barter->x, barter->y );
  583. npc_parsename( nd, barter->name.c_str(), nullptr, nullptr, __FILE__ ":" QUOTE(__LINE__) );
  584. nd->class_ = barter->sprite;
  585. nd->speed = 200;
  586. nd->bl.type = BL_NPC;
  587. nd->subtype = NPCTYPE_BARTER;
  588. nd->u.barter.extended = false;
  589. // Check if it has to use the extended barter feature or not
  590. for( const auto& itemPair : barter->items ){
  591. // Normal barter cannot have zeny requirements
  592. if( itemPair.second->price > 0 ){
  593. nd->u.barter.extended = true;
  594. break;
  595. }
  596. // Normal barter needs to have exchange items defined
  597. if( itemPair.second->requirements.empty() ){
  598. nd->u.barter.extended = true;
  599. break;
  600. }
  601. // Normal barter can only exchange 1:1
  602. if( itemPair.second->requirements.size() > 1 ){
  603. nd->u.barter.extended = true;
  604. break;
  605. }
  606. // Normal barter cannot handle refine
  607. for( const auto& requirement : itemPair.second->requirements ){
  608. if( requirement.second->refine >= 0 ){
  609. nd->u.barter.extended = true;
  610. break;
  611. }
  612. }
  613. // Check if a refine requirement has been set in the loop above
  614. if( nd->u.barter.extended ){
  615. break;
  616. }
  617. }
  618. if( nd->u.barter.extended && !battle_config.feature_barter_extended ){
  619. #ifndef BUILDBOT
  620. ShowError( "Barter %s uses extended mechanics but this is not enabled.\n", nd->name );
  621. #endif
  622. continue;
  623. }
  624. if( nd->bl.m >= 0 ){
  625. map_addnpc( nd->bl.m, nd );
  626. npc_setcells( nd );
  627. // Couldn't add on map
  628. if( map_addblock( &nd->bl ) ){
  629. continue;
  630. }
  631. status_change_init( &nd->bl );
  632. unit_dataset( &nd->bl );
  633. nd->ud.dir = barter->dir;
  634. if( nd->class_ != JT_FAKENPC ){
  635. status_set_viewdata( &nd->bl, nd->class_ );
  636. if( map_getmapdata( nd->bl.m )->users ){
  637. clif_spawn( &nd->bl );
  638. }
  639. }
  640. }else{
  641. map_addiddb( &nd->bl );
  642. }
  643. strdb_put( npcname_db, nd->exname, nd );
  644. for( const auto& itemPair : barter->items ){
  645. if( itemPair.second->stockLimited ){
  646. if( Sql_Query( mmysql_handle, "SELECT `amount` FROM `%s` WHERE `name` = '%s' AND `index` = '%hu'", barter_table, barter->name.c_str(), itemPair.first ) != SQL_SUCCESS ){
  647. Sql_ShowDebug( mmysql_handle );
  648. continue;
  649. }
  650. // Previous amount found
  651. if( SQL_SUCCESS == Sql_NextRow( mmysql_handle ) ){
  652. char* data;
  653. Sql_GetData( mmysql_handle, 0, &data, nullptr );
  654. itemPair.second->stock = strtoul( data, nullptr, 10 );
  655. }
  656. Sql_FreeResult( mmysql_handle );
  657. // Save or refresh the amount
  658. if( Sql_Query( mmysql_handle, "REPLACE INTO `%s` (`name`,`index`,`amount`) VALUES ( '%s', '%hu', '%hu' )", barter_table, barter->name.c_str(), itemPair.first, itemPair.second->stock ) != SQL_SUCCESS ){
  659. Sql_ShowDebug( mmysql_handle );
  660. }
  661. }else{
  662. if( Sql_Query( mmysql_handle, "DELETE FROM `%s` WHERE `name` = '%s' AND `index` = '%hu'", barter_table, barter->name.c_str(), itemPair.first ) != SQL_SUCCESS ){
  663. Sql_ShowDebug( mmysql_handle );
  664. }
  665. }
  666. }
  667. }
  668. TypesafeYamlDatabase::loadingFinished();
  669. }
  670. BarterDatabase barter_db;
  671. /**
  672. * Returns the viewdata for normal NPC classes.
  673. * @param class_: NPC class ID
  674. * @return viewdata or nullptr if the ID is invalid
  675. */
  676. struct view_data* npc_get_viewdata(int class_) {
  677. if( class_ == JT_INVISIBLE )
  678. return &npc_viewdb[0];
  679. if (npcdb_checkid(class_)){
  680. if( class_ > MAX_NPC_CLASS2_START ){
  681. return &npc_viewdb2[class_-MAX_NPC_CLASS2_START];
  682. }else{
  683. return &npc_viewdb[class_];
  684. }
  685. }
  686. return nullptr;
  687. }
  688. int npc_isnear_sub(struct block_list* bl, va_list args) {
  689. struct npc_data *nd = (struct npc_data*)bl;
  690. if (nd->sc.option & (OPTION_HIDE|OPTION_INVISIBLE))
  691. return 0;
  692. if( nd->dynamicnpc.owner_char_id != 0 ){
  693. return 0;
  694. }
  695. int skill_id = va_arg(args, int);
  696. if (skill_id > 0) { //If skill_id > 0 that means is used for INF2_DISABLENEARNPC [Cydh]
  697. std::shared_ptr<s_skill_db> skill = skill_db.find(skill_id);
  698. if (skill && skill->unit_nonearnpc_type) {
  699. if (skill->unit_nonearnpc_type&SKILL_NONEAR_WARPPORTAL && nd->subtype == NPCTYPE_WARP)
  700. return 1;
  701. if (skill->unit_nonearnpc_type&SKILL_NONEAR_SHOP && nd->subtype == NPCTYPE_SHOP)
  702. return 1;
  703. if (skill->unit_nonearnpc_type&SKILL_NONEAR_NPC && nd->subtype == NPCTYPE_SCRIPT)
  704. return 1;
  705. if (skill->unit_nonearnpc_type&SKILL_NONEAR_TOMB && nd->subtype == NPCTYPE_TOMB)
  706. return 1;
  707. }
  708. return 0;
  709. }
  710. return 1;
  711. }
  712. bool npc_isnear(struct block_list * bl) {
  713. if( battle_config.min_npc_vendchat_distance > 0 &&
  714. map_foreachinallrange(npc_isnear_sub,bl, battle_config.min_npc_vendchat_distance, BL_NPC, 0) )
  715. return true;
  716. return false;
  717. }
  718. int npc_ontouch_event(map_session_data *sd, struct npc_data *nd)
  719. {
  720. char name[EVENT_NAME_LENGTH];
  721. if (pc_isdead(sd)) // Dead player don't trigger 'OnTouch_'
  722. return 0;
  723. if( nd->touching_id )
  724. return 0; // Attached a player already. Can't trigger on anyone else.
  725. // pc_ishiding moved in npc_event for now.
  726. // If OnTouch_ event exists hiding player doesn't click the npc.
  727. // if( pc_ishiding(sd) )
  728. // return 1; // Can't trigger 'OnTouch_'.
  729. if (util::vector_exists(sd->npc_ontouch_, nd->bl.id))
  730. return 0;
  731. safesnprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_event_name);
  732. return npc_event(sd,name,1);
  733. }
  734. int npc_ontouch2_event(map_session_data *sd, struct npc_data *nd)
  735. {
  736. char name[EVENT_NAME_LENGTH];
  737. if (util::vector_exists(sd->areanpc, nd->bl.id))
  738. return 0;
  739. safesnprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch2_event_name);
  740. return npc_event(sd,name,2);
  741. }
  742. int npc_touch_areanpc(map_session_data* sd, int16 m, int16 x, int16 y, struct npc_data *nd);
  743. /*==========================================
  744. * Sub-function of npc_enable, runs OnTouch event when enabled
  745. *------------------------------------------*/
  746. int npc_enable_sub(struct block_list *bl, va_list ap)
  747. {
  748. struct npc_data *nd;
  749. nullpo_ret(bl);
  750. nullpo_ret(nd=va_arg(ap,struct npc_data *));
  751. if(bl->type == BL_PC)
  752. {
  753. TBL_PC *sd = (TBL_PC*)bl;
  754. npc_touch_areanpc(sd, bl->m, bl->x, bl->y, nd);
  755. }
  756. return 0;
  757. }
  758. bool npc_is_cloaked(struct npc_data* nd, map_session_data* sd) {
  759. bool npc_cloaked = (nd->sc.option & OPTION_CLOAK) ? true : false;
  760. if (std::find(sd->cloaked_npc.begin(), sd->cloaked_npc.end(), nd->bl.id) != sd->cloaked_npc.end())
  761. return (!npc_cloaked);
  762. return npc_cloaked;
  763. }
  764. bool npc_is_hidden_dynamicnpc( struct npc_data& nd, map_session_data& tsd ){
  765. // If the NPC is dynamic and the target character is not the owner of the dynamic NPC
  766. return nd.dynamicnpc.owner_char_id != 0 && nd.dynamicnpc.owner_char_id != tsd.status.char_id;
  767. }
  768. static int npc_cloaked_sub(struct block_list *bl, va_list ap)
  769. {
  770. map_session_data* sd;
  771. nullpo_ret(bl);
  772. nullpo_ret(sd = (map_session_data *)bl);
  773. int id = va_arg(ap, int);
  774. auto it = std::find(sd->cloaked_npc.begin(), sd->cloaked_npc.end(), id);
  775. if (it != sd->cloaked_npc.end())
  776. sd->cloaked_npc.erase(it);
  777. return 1;
  778. }
  779. /*==========================================
  780. * Disable / Enable NPC
  781. *------------------------------------------*/
  782. bool npc_enable_target(npc_data& nd, uint32 char_id, e_npcv_status flag)
  783. {
  784. if (char_id > 0 && (flag & NPCVIEW_CLOAK)) {
  785. map_session_data *sd = map_charid2sd(char_id);
  786. if (!sd) {
  787. ShowError("npc_enable: Attempted to %s a NPC '%s' on an invalid target %d.\n", (flag & NPCVIEW_VISIBLE) ? "show" : "hide", nd.name, char_id);
  788. return false;
  789. }
  790. unsigned int option = nd.sc.option;
  791. if (flag & NPCVIEW_CLOAKOFF)
  792. nd.sc.option &= ~OPTION_CLOAK;
  793. else
  794. nd.sc.option |= OPTION_CLOAK;
  795. auto it = std::find(sd->cloaked_npc.begin(), sd->cloaked_npc.end(), nd.bl.id);
  796. if (it == sd->cloaked_npc.end() && option != nd.sc.option)
  797. sd->cloaked_npc.push_back(nd.bl.id);
  798. else if (it != sd->cloaked_npc.end() && option == nd.sc.option)
  799. sd->cloaked_npc.erase(it);
  800. if (nd.class_ != JT_WARPNPC && nd.class_ != JT_GUILD_FLAG)
  801. clif_changeoption_target(&nd.bl, &sd->bl);
  802. else {
  803. if (nd.sc.option&(OPTION_HIDE|OPTION_INVISIBLE|OPTION_CLOAK))
  804. clif_clearunit_single(nd.bl.id, CLR_OUTSIGHT, sd->fd);
  805. else
  806. clif_spawn(&nd.bl);
  807. }
  808. nd.sc.option = option;
  809. }
  810. else {
  811. if (flag & NPCVIEW_ENABLE) {
  812. nd.sc.option &= ~OPTION_INVISIBLE;
  813. clif_spawn(&nd.bl);
  814. }
  815. else if (flag & NPCVIEW_HIDEOFF)
  816. nd.sc.option &= ~OPTION_HIDE;
  817. else if (flag & NPCVIEW_HIDEON)
  818. nd.sc.option |= OPTION_HIDE;
  819. else if (flag & NPCVIEW_CLOAKOFF)
  820. nd.sc.option &= ~OPTION_CLOAK;
  821. else if (flag & NPCVIEW_CLOAKON)
  822. nd.sc.option |= OPTION_CLOAK;
  823. else { //Can't change the view_data to invisible class because the view_data for all npcs is shared! [Skotlex]
  824. nd.sc.option |= OPTION_INVISIBLE;
  825. clif_clearunit_area(&nd.bl,CLR_OUTSIGHT); // Hack to trick maya purple card [Xazax]
  826. }
  827. if (nd.class_ != JT_WARPNPC && nd.class_ != JT_GUILD_FLAG) //Client won't display option changes for these classes [Toms]
  828. clif_changeoption(&nd.bl);
  829. else {
  830. if (nd.sc.option&(OPTION_HIDE|OPTION_INVISIBLE|OPTION_CLOAK))
  831. clif_clearunit_area(&nd.bl,CLR_OUTSIGHT);
  832. else
  833. clif_spawn(&nd.bl);
  834. }
  835. map_foreachinmap(npc_cloaked_sub, nd.bl.m, BL_PC, nd.bl.id); // Because npc option has been updated we remove the npc id from sd->cloaked_npc
  836. }
  837. if (flag & NPCVIEW_VISIBLE) { // check if player standing on a OnTouchArea
  838. int xs = -1, ys = -1;
  839. switch (nd.subtype) {
  840. case NPCTYPE_SCRIPT:
  841. xs = nd.u.scr.xs;
  842. ys = nd.u.scr.ys;
  843. break;
  844. case NPCTYPE_WARP:
  845. xs = nd.u.warp.xs;
  846. ys = nd.u.warp.ys;
  847. break;
  848. }
  849. if (xs > -1 && ys > -1)
  850. map_foreachinallarea( npc_enable_sub, nd.bl.m, nd.bl.x-xs, nd.bl.y-ys, nd.bl.x+xs, nd.bl.y+ys, BL_PC, &nd );
  851. }
  852. return true;
  853. }
  854. /*==========================================
  855. * NPC lookup (get npc_data through npcname)
  856. *------------------------------------------*/
  857. struct npc_data* npc_name2id(const char* name)
  858. {
  859. return (struct npc_data *) strdb_get(npcname_db, name);
  860. }
  861. /**
  862. * For the Secure NPC Timeout option (check src/config/secure.hpp)
  863. * @author RR
  864. **/
  865. #ifdef SECURE_NPCTIMEOUT
  866. /**
  867. * Timer to check for idle time and timeout the dialog if necessary
  868. **/
  869. TIMER_FUNC(npc_secure_timeout_timer){
  870. map_session_data* sd = NULL;
  871. unsigned int timeout = NPC_SECURE_TIMEOUT_NEXT;
  872. t_tick cur_tick = gettick(); //ensure we are on last tick
  873. if ((sd = map_id2sd(id)) == NULL || !sd->npc_id || sd->state.ignoretimeout) {
  874. if( sd && sd->npc_idle_timer != INVALID_TIMER ){
  875. delete_timer( sd->npc_idle_timer, npc_secure_timeout_timer );
  876. sd->npc_idle_timer = INVALID_TIMER;
  877. }
  878. return 0; // Not logged in anymore OR no longer attached to a NPC OR using 'ignoretimeout' script command
  879. }
  880. switch( sd->npc_idle_type ) {
  881. case NPCT_INPUT:
  882. timeout = NPC_SECURE_TIMEOUT_INPUT;
  883. break;
  884. case NPCT_MENU:
  885. timeout = NPC_SECURE_TIMEOUT_MENU;
  886. break;
  887. //case NPCT_WAIT: var starts with this value
  888. }
  889. if( DIFF_TICK(cur_tick,sd->npc_idle_tick) > (timeout*1000) ) {
  890. pc_close_npc(sd,1);
  891. } else if(sd->st && (sd->st->state == END || sd->st->state == CLOSE)){
  892. // stop timer the script is already ending
  893. if( sd->npc_idle_timer != INVALID_TIMER ){
  894. delete_timer( sd->npc_idle_timer, npc_secure_timeout_timer );
  895. sd->npc_idle_timer = INVALID_TIMER;
  896. }
  897. } else { //Create a new instance of ourselves to continue
  898. sd->npc_idle_timer = add_timer(cur_tick + (SECURE_NPCTIMEOUT_INTERVAL*1000),npc_secure_timeout_timer,sd->bl.id,0);
  899. }
  900. return 0;
  901. }
  902. #endif
  903. /*==========================================
  904. * Dequeue event and add timer for execution (100ms)
  905. *------------------------------------------*/
  906. int npc_event_dequeue(map_session_data* sd,bool free_script_stack)
  907. {
  908. nullpo_ret(sd);
  909. if(sd->npc_id)
  910. { //Current script is aborted.
  911. if(sd->state.using_fake_npc){
  912. clif_clearunit_single(sd->npc_id, CLR_OUTSIGHT, sd->fd);
  913. sd->state.using_fake_npc = 0;
  914. }
  915. if (free_script_stack&&sd->st) {
  916. script_free_state(sd->st);
  917. sd->st = NULL;
  918. }
  919. sd->npc_id = 0;
  920. }
  921. if (!sd->eventqueue[0][0])
  922. return 0; //Nothing to dequeue
  923. if (!pc_addeventtimer(sd,100,sd->eventqueue[0]))
  924. { //Failed to dequeue, couldn't set a timer.
  925. ShowWarning("npc_event_dequeue: event timer is full !\n");
  926. return 0;
  927. }
  928. //Event dequeued successfully, shift other elements.
  929. memmove(sd->eventqueue[0], sd->eventqueue[1], (MAX_EVENTQUEUE-1)*sizeof(sd->eventqueue[0]));
  930. sd->eventqueue[MAX_EVENTQUEUE-1][0]=0;
  931. return 1;
  932. }
  933. /*==========================================
  934. * exports a npc event label
  935. * called from npc_parse_script
  936. *------------------------------------------*/
  937. static int npc_event_export(struct npc_data *nd, int i)
  938. {
  939. char* lname = nd->u.scr.label_list[i].name;
  940. int pos = nd->u.scr.label_list[i].pos;
  941. if ((lname[0] == 'O' || lname[0] == 'o') && (lname[1] == 'N' || lname[1] == 'n')) {
  942. struct event_data *ev;
  943. char buf[EVENT_NAME_LENGTH];
  944. if (nd->bl.m > -1 && map_getmapdata(nd->bl.m)->instance_id > 0) { // Block script events in instances
  945. int j;
  946. for (j = 0; j < NPCE_MAX; j++) {
  947. if (strcmpi(npc_get_script_event_name(j), lname) == 0) {
  948. ShowWarning("npc_event_export: attempting to duplicate a script event in an instance (%s::%s), ignoring\n", nd->name, lname);
  949. return 0;
  950. }
  951. }
  952. }
  953. // NPC:<name> the prefix uses 4 characters
  954. if( !strncasecmp( lname, script_config.onwhisper_event_name, NAME_LENGTH ) && strlen(nd->exname) > ( NAME_LENGTH - 4 ) ){
  955. // The client only allows that many character so that NPC could not be whispered by unmodified clients
  956. ShowWarning( "Whisper event in npc '" CL_WHITE "%s" CL_RESET "' was ignored, because it's name is too long.\n", nd->exname );
  957. return 0;
  958. }
  959. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, lname);
  960. // generate the data and insert it
  961. CREATE(ev, struct event_data, 1);
  962. ev->nd = nd;
  963. ev->pos = pos;
  964. if (strdb_put(ev_db, buf, ev)) // There was already another event of the same name?
  965. return 1;
  966. }
  967. return 0;
  968. }
  969. int npc_event_sub(map_session_data* sd, struct event_data* ev, const char* eventname); //[Lance]
  970. /**
  971. * Exec name (NPC events) on player or global
  972. * Do on all NPC when called with foreach
  973. * @see DBApply
  974. */
  975. int npc_event_doall_sub(DBKey key, DBData *data, va_list ap)
  976. {
  977. const char* p = key.str;
  978. struct event_data* ev;
  979. int* c;
  980. const char* name;
  981. int rid;
  982. nullpo_ret(ev = (struct event_data*)db_data2ptr(data));
  983. nullpo_ret(c = va_arg(ap, int *));
  984. nullpo_ret(name = va_arg(ap, const char *));
  985. rid = va_arg(ap, int);
  986. p = strchr(p, ':'); // match only the event name
  987. if( p && strcmpi(name, p) == 0 /* && !ev->nd->src_id */ ) // Do not run on duplicates. [Paradox924X]
  988. {
  989. if(rid) // a player may only have 1 script running at the same time
  990. npc_event_sub(map_id2sd(rid),ev,key.str);
  991. else
  992. run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
  993. (*c)++;
  994. }
  995. return 0;
  996. }
  997. /**
  998. * @see DBApply
  999. */
  1000. static int npc_event_do_sub(DBKey key, DBData *data, va_list ap)
  1001. {
  1002. const char* p = key.str;
  1003. struct event_data* ev;
  1004. int* c, rid;
  1005. const char* name;
  1006. nullpo_ret(ev = (struct event_data*)db_data2ptr(data));
  1007. nullpo_ret(c = va_arg(ap, int *));
  1008. nullpo_ret(name = va_arg(ap, const char *));
  1009. rid = va_arg(ap, int);
  1010. if( p && strcmpi(name, p) == 0 )
  1011. {
  1012. run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
  1013. (*c)++;
  1014. }
  1015. return 0;
  1016. }
  1017. int npc_event_do_id(const char* name, int rid) {
  1018. int c = 0;
  1019. if( name[0] == ':' && name[1] == ':' )
  1020. ev_db->foreach(ev_db,npc_event_doall_sub,&c,name,0,rid);
  1021. else
  1022. ev_db->foreach(ev_db,npc_event_do_sub,&c,name,rid);
  1023. return c;
  1024. }
  1025. // runs the specified event (supports both single-npc and global events)
  1026. int npc_event_do(const char* name) {
  1027. return npc_event_do_id(name, 0);
  1028. }
  1029. // runs the specified event (global only)
  1030. int npc_event_doall(const char* name)
  1031. {
  1032. return npc_event_doall_id(name, 0);
  1033. }
  1034. // runs the specified event(global only) and reports call count
  1035. void npc_event_runall( const char* eventname ){
  1036. ShowStatus( "Event '" CL_WHITE "%s" CL_RESET "' executed with '" CL_WHITE "%d" CL_RESET "' NPCs.\n", eventname, npc_event_doall( eventname ) );
  1037. }
  1038. // runs the specified event, with a RID attached (global only)
  1039. int npc_event_doall_id(const char* name, int rid)
  1040. {
  1041. int c = 0;
  1042. char buf[EVENT_NAME_LENGTH];
  1043. safesnprintf(buf, sizeof(buf), "::%s", name);
  1044. ev_db->foreach(ev_db,npc_event_doall_sub,&c,buf,rid);
  1045. return c;
  1046. }
  1047. // runs the specified event on all NPCs with the given path
  1048. int npc_event_doall_path( const char* event_name, const char* path ){
  1049. s_mapiterator* iter = mapit_geteachnpc();
  1050. npc_data* nd;
  1051. int count = 0;
  1052. while( ( nd = (npc_data*)mapit_next( iter ) ) != nullptr ){
  1053. if( nd->path && strcasecmp( nd->path, path ) == 0 ){
  1054. char name[EVENT_NAME_LENGTH];
  1055. safesnprintf( name, EVENT_NAME_LENGTH, "%s::%s", nd->exname, event_name );
  1056. count += npc_event_do( name );
  1057. }
  1058. }
  1059. ShowStatus( "Event '" CL_WHITE "%s" CL_RESET "' executed with '" CL_WHITE "%d" CL_RESET "' NPCs.\n", event_name, count );
  1060. mapit_free(iter);
  1061. return count;
  1062. }
  1063. /*==========================================
  1064. * Clock event execution
  1065. * OnMinute/OnClock/OnHour/OnDay/OnDDHHMM
  1066. *------------------------------------------*/
  1067. TIMER_FUNC(npc_event_do_clock){
  1068. static struct tm ev_tm_b; // tracks previous execution time
  1069. time_t timer;
  1070. struct tm* t;
  1071. char buf[EVENT_NAME_LENGTH];
  1072. int c = 0;
  1073. timer = time(NULL);
  1074. t = localtime(&timer);
  1075. if (t->tm_min != ev_tm_b.tm_min ) {
  1076. const char* day = NULL;
  1077. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d",script_config.timer_minute_event_name,t->tm_min);
  1078. c += npc_event_doall(buf);
  1079. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d%02d",script_config.timer_clock_event_name,t->tm_hour,t->tm_min);
  1080. c += npc_event_doall(buf);
  1081. switch (t->tm_wday) {
  1082. case SUNDAY: day = script_config.timer_sunday_event_name; break;
  1083. case MONDAY: day = script_config.timer_monday_event_name; break;
  1084. case TUESDAY: day = script_config.timer_tuesday_event_name; break;
  1085. case WEDNESDAY: day = script_config.timer_wednesday_event_name; break;
  1086. case THURSDAY: day = script_config.timer_thursday_event_name; break;
  1087. case FRIDAY: day = script_config.timer_friday_event_name; break;
  1088. case SATURDAY: day = script_config.timer_saturday_event_name; break;
  1089. }
  1090. if( day != NULL ){
  1091. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d%02d",day,t->tm_hour,t->tm_min);
  1092. c += npc_event_doall(buf);
  1093. }
  1094. }
  1095. if (t->tm_hour != ev_tm_b.tm_hour) {
  1096. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d",script_config.timer_hour_event_name,t->tm_hour);
  1097. c += npc_event_doall(buf);
  1098. }
  1099. if (t->tm_mday != ev_tm_b.tm_mday) {
  1100. safesnprintf(buf,EVENT_NAME_LENGTH,"%s%02d%02d",script_config.timer_day_event_name,t->tm_mon+1,t->tm_mday);
  1101. c += npc_event_doall(buf);
  1102. }
  1103. memcpy(&ev_tm_b,t,sizeof(ev_tm_b));
  1104. return c;
  1105. }
  1106. /*==========================================
  1107. * OnInit Event execution (the start of the event and watch)
  1108. *------------------------------------------*/
  1109. void npc_event_do_oninit(void)
  1110. {
  1111. npc_event_runall(script_config.init_event_name);
  1112. add_timer_interval(gettick()+100,npc_event_do_clock,0,0,1000);
  1113. }
  1114. /*==========================================
  1115. * Incorporation of the label for the timer event
  1116. * called from npc_parse_script
  1117. *------------------------------------------*/
  1118. int npc_timerevent_export(struct npc_data *nd, int i)
  1119. {
  1120. int t = 0, k = 0;
  1121. char *lname = nd->u.scr.label_list[i].name;
  1122. int pos = nd->u.scr.label_list[i].pos;
  1123. size_t len = strlen(script_config.timer_event_name);
  1124. // Check if the label name starts with OnTimer(default) and then parse the seconds right after it
  1125. if ( !strncmp(lname,script_config.timer_event_name,len) && sscanf( (lname += len), "%11d%n", &t, &k) == 1 && lname[k] == '\0') {
  1126. // Timer event
  1127. struct npc_timerevent_list *te = nd->u.scr.timer_event;
  1128. int j, k2 = nd->u.scr.timeramount;
  1129. if (te == NULL)
  1130. te = (struct npc_timerevent_list *)aMalloc(sizeof(struct npc_timerevent_list));
  1131. else
  1132. te = (struct npc_timerevent_list *)aRealloc( te, sizeof(struct npc_timerevent_list) * (k2+1) );
  1133. for (j = 0; j < k2; j++) {
  1134. if (te[j].timer > t) {
  1135. memmove(te+j+1, te+j, sizeof(struct npc_timerevent_list)*(k2-j));
  1136. break;
  1137. }
  1138. }
  1139. te[j].timer = t;
  1140. te[j].pos = pos;
  1141. nd->u.scr.timer_event = te;
  1142. nd->u.scr.timeramount++;
  1143. }
  1144. return 0;
  1145. }
  1146. struct timer_event_data {
  1147. int rid; //Attached player for this timer.
  1148. int next; //timer index (starts with 0, then goes up to nd->u.scr.timeramount)
  1149. int time; //holds total time elapsed for the script from when timer was started to when last time the event triggered.
  1150. };
  1151. /*==========================================
  1152. * triger 'OnTimerXXXX' events
  1153. *------------------------------------------*/
  1154. TIMER_FUNC(npc_timerevent){
  1155. int old_rid;
  1156. t_tick old_timer;
  1157. t_tick old_tick;
  1158. struct npc_data* nd=(struct npc_data *)map_id2bl(id);
  1159. struct npc_timerevent_list *te;
  1160. struct timer_event_data *ted = (struct timer_event_data*)data;
  1161. map_session_data *sd=NULL;
  1162. if( nd == NULL )
  1163. {
  1164. ShowError("npc_timerevent: NPC not found??\n");
  1165. return 0;
  1166. }
  1167. if( ted->rid && !(sd = map_id2sd(ted->rid)) )
  1168. {
  1169. ShowError("npc_timerevent: Attached player not found.\n");
  1170. ers_free(timer_event_ers, ted);
  1171. return 0;
  1172. }
  1173. // These stuffs might need to be restored.
  1174. old_rid = nd->u.scr.rid;
  1175. old_tick = nd->u.scr.timertick;
  1176. old_timer = nd->u.scr.timer;
  1177. // Set the values of the timer
  1178. nd->u.scr.rid = sd?sd->bl.id:0; //attached rid
  1179. nd->u.scr.timertick = tick; //current time tick
  1180. nd->u.scr.timer = ted->time; //total time from beginning to now
  1181. // Locate the event
  1182. te = nd->u.scr.timer_event + ted->next;
  1183. // Arrange for the next event
  1184. ted->next++;
  1185. if( nd->u.scr.timeramount > ted->next )
  1186. {
  1187. int next;
  1188. next = nd->u.scr.timer_event[ ted->next ].timer - nd->u.scr.timer_event[ ted->next - 1 ].timer;
  1189. ted->time += next;
  1190. if( sd )
  1191. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
  1192. else
  1193. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,id,(intptr_t)ted);
  1194. }
  1195. else
  1196. {
  1197. if( sd )
  1198. sd->npc_timer_id = INVALID_TIMER;
  1199. else
  1200. nd->u.scr.timerid = INVALID_TIMER;
  1201. ers_free(timer_event_ers, ted);
  1202. }
  1203. // Run the script
  1204. run_script(nd->u.scr.script,te->pos,nd->u.scr.rid,nd->bl.id);
  1205. nd->u.scr.rid = old_rid; // Attached-rid should be restored anyway.
  1206. if( sd )
  1207. { // Restore previous data, only if this timer is a player-attached one.
  1208. nd->u.scr.timer = old_timer;
  1209. nd->u.scr.timertick = old_tick;
  1210. }
  1211. return 0;
  1212. }
  1213. /*==========================================
  1214. * Start/Resume NPC timer
  1215. *------------------------------------------*/
  1216. int npc_timerevent_start(struct npc_data* nd, int rid)
  1217. {
  1218. int j;
  1219. t_tick tick = gettick();
  1220. map_session_data *sd = NULL; //Player to whom script is attached.
  1221. nullpo_ret(nd);
  1222. // Check if there is an OnTimer Event
  1223. ARR_FIND( 0, nd->u.scr.timeramount, j, nd->u.scr.timer_event[j].timer > nd->u.scr.timer );
  1224. if( nd->u.scr.rid > 0 && !(sd = map_id2sd(nd->u.scr.rid)) )
  1225. { // Failed to attach timer to this player.
  1226. ShowError("npc_timerevent_start: Attached player not found!\n");
  1227. return 1;
  1228. }
  1229. // Check if timer is already started.
  1230. if( sd )
  1231. {
  1232. if( sd->npc_timer_id != INVALID_TIMER )
  1233. return 0;
  1234. }
  1235. else if( nd->u.scr.timerid != INVALID_TIMER || nd->u.scr.timertick )
  1236. return 0;
  1237. if (j < nd->u.scr.timeramount)
  1238. {
  1239. t_tick next;
  1240. struct timer_event_data *ted;
  1241. // Arrange for the next event
  1242. ted = ers_alloc(timer_event_ers, struct timer_event_data);
  1243. ted->next = j; // Set event index
  1244. ted->time = nd->u.scr.timer_event[j].timer;
  1245. next = nd->u.scr.timer_event[j].timer - nd->u.scr.timer;
  1246. if( sd )
  1247. {
  1248. ted->rid = sd->bl.id; // Attach only the player if attachplayerrid was used.
  1249. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
  1250. }
  1251. else
  1252. {
  1253. ted->rid = 0;
  1254. nd->u.scr.timertick = tick; // Set when timer is started
  1255. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr_t)ted);
  1256. }
  1257. }
  1258. else if (!sd)
  1259. {
  1260. nd->u.scr.timertick = tick;
  1261. }
  1262. return 0;
  1263. }
  1264. /*==========================================
  1265. * Stop NPC timer
  1266. *------------------------------------------*/
  1267. int npc_timerevent_stop(struct npc_data* nd)
  1268. {
  1269. map_session_data *sd = NULL;
  1270. int *tid;
  1271. nullpo_ret(nd);
  1272. if( nd->u.scr.rid && !(sd = map_id2sd(nd->u.scr.rid)) )
  1273. {
  1274. ShowError("npc_timerevent_stop: Attached player not found!\n");
  1275. return 1;
  1276. }
  1277. tid = sd?&sd->npc_timer_id:&nd->u.scr.timerid;
  1278. if( *tid == INVALID_TIMER && (sd || !nd->u.scr.timertick) ) // Nothing to stop
  1279. return 0;
  1280. // Delete timer
  1281. if ( *tid != INVALID_TIMER )
  1282. {
  1283. const struct TimerData *td = NULL;
  1284. td = get_timer(*tid);
  1285. if( td && td->data )
  1286. ers_free(timer_event_ers, (void*)td->data);
  1287. delete_timer(*tid,npc_timerevent);
  1288. *tid = INVALID_TIMER;
  1289. }
  1290. if( !sd && nd->u.scr.timertick )
  1291. {
  1292. nd->u.scr.timer += DIFF_TICK(gettick(),nd->u.scr.timertick); // Set 'timer' to the time that has passed since the beginning of the timers
  1293. nd->u.scr.timertick = 0; // Set 'tick' to zero so that we know it's off.
  1294. }
  1295. return 0;
  1296. }
  1297. /*==========================================
  1298. * Aborts a running NPC timer that is attached to a player.
  1299. *------------------------------------------*/
  1300. void npc_timerevent_quit(map_session_data* sd)
  1301. {
  1302. const struct TimerData *td;
  1303. struct npc_data* nd;
  1304. struct timer_event_data *ted;
  1305. // Check timer existance
  1306. if( sd->npc_timer_id == INVALID_TIMER )
  1307. return;
  1308. if( !(td = get_timer(sd->npc_timer_id)) )
  1309. {
  1310. sd->npc_timer_id = INVALID_TIMER;
  1311. return;
  1312. }
  1313. // Delete timer
  1314. nd = (struct npc_data *)map_id2bl(td->id);
  1315. ted = (struct timer_event_data*)td->data;
  1316. delete_timer(sd->npc_timer_id, npc_timerevent);
  1317. sd->npc_timer_id = INVALID_TIMER;
  1318. // Execute OnTimerQuit
  1319. if( nd && nd->bl.type == BL_NPC )
  1320. {
  1321. char buf[EVENT_NAME_LENGTH];
  1322. struct event_data *ev;
  1323. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, script_config.timer_quit_event_name);
  1324. ev = (struct event_data*)strdb_get(ev_db, buf);
  1325. if( ev && ev->nd != nd )
  1326. {
  1327. ShowWarning("npc_timerevent_quit: Unable to execute \"%s\", two NPCs have the same event name [%s]!\n",script_config.timer_quit_event_name,buf);
  1328. ev = NULL;
  1329. }
  1330. if( ev )
  1331. {
  1332. int old_rid;
  1333. t_tick old_timer;
  1334. t_tick old_tick;
  1335. //Set timer related info.
  1336. old_rid = (nd->u.scr.rid == sd->bl.id ? 0 : nd->u.scr.rid); // Detach rid if the last attached player logged off.
  1337. old_tick = nd->u.scr.timertick;
  1338. old_timer = nd->u.scr.timer;
  1339. nd->u.scr.rid = sd->bl.id;
  1340. nd->u.scr.timertick = gettick();
  1341. nd->u.scr.timer = ted->time;
  1342. //Execute label
  1343. run_script(nd->u.scr.script,ev->pos,sd->bl.id,nd->bl.id);
  1344. //Restore previous data.
  1345. nd->u.scr.rid = old_rid;
  1346. nd->u.scr.timer = old_timer;
  1347. nd->u.scr.timertick = old_tick;
  1348. }
  1349. }
  1350. ers_free(timer_event_ers, ted);
  1351. }
  1352. /*==========================================
  1353. * Get the tick value of an NPC timer
  1354. * If it's stopped, return stopped time
  1355. *------------------------------------------*/
  1356. t_tick npc_gettimerevent_tick(struct npc_data* nd)
  1357. {
  1358. t_tick tick;
  1359. nullpo_ret(nd);
  1360. // TODO: Get player attached timer's tick. Now we can just get it by using 'getnpctimer' inside OnTimer event.
  1361. tick = nd->u.scr.timer; // The last time it's active(start, stop or event trigger)
  1362. if( nd->u.scr.timertick ) // It's a running timer
  1363. tick += DIFF_TICK(gettick(), nd->u.scr.timertick);
  1364. return tick;
  1365. }
  1366. /*==========================================
  1367. * Set tick for running and stopped timer
  1368. *------------------------------------------*/
  1369. int npc_settimerevent_tick(struct npc_data* nd, int newtimer)
  1370. {
  1371. bool flag;
  1372. int old_rid;
  1373. //map_session_data *sd = NULL;
  1374. nullpo_ret(nd);
  1375. // TODO: Set player attached timer's tick.
  1376. old_rid = nd->u.scr.rid;
  1377. nd->u.scr.rid = 0;
  1378. // Check if timer is started
  1379. flag = (nd->u.scr.timerid != INVALID_TIMER || nd->u.scr.timertick);
  1380. if( flag ) npc_timerevent_stop(nd);
  1381. nd->u.scr.timer = newtimer;
  1382. if( flag ) npc_timerevent_start(nd, -1);
  1383. nd->u.scr.rid = old_rid;
  1384. return 0;
  1385. }
  1386. int npc_event_sub(map_session_data* sd, struct event_data* ev, const char* eventname)
  1387. {
  1388. if ( sd->npc_id != 0 )
  1389. {
  1390. //Enqueue the event trigger.
  1391. int i;
  1392. ARR_FIND( 0, MAX_EVENTQUEUE, i, sd->eventqueue[i][0] == '\0' );
  1393. if( i < MAX_EVENTQUEUE )
  1394. {
  1395. safestrncpy(sd->eventqueue[i],eventname,EVENT_NAME_LENGTH); //Event enqueued.
  1396. return 0;
  1397. }
  1398. ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
  1399. return 1;
  1400. }
  1401. if( ev->nd->sc.option&OPTION_INVISIBLE )
  1402. {
  1403. //Disabled npc, shouldn't trigger event.
  1404. npc_event_dequeue(sd);
  1405. return 2;
  1406. }
  1407. char ontouch_event_name[EVENT_NAME_LENGTH];
  1408. char ontouch2_event_name[EVENT_NAME_LENGTH];
  1409. safesnprintf(ontouch_event_name, ARRAYLENGTH(ontouch_event_name), "%s::%s", ev->nd->exname, script_config.ontouch_event_name);
  1410. safesnprintf(ontouch2_event_name, ARRAYLENGTH(ontouch2_event_name), "%s::%s", ev->nd->exname, script_config.ontouch2_event_name);
  1411. // recheck some conditions for OnTouch/OnTouch_
  1412. if (strcmp(eventname, ontouch_event_name) == 0 || strcmp(eventname, ontouch2_event_name) == 0) {
  1413. int xs = ev->nd->u.scr.xs;
  1414. int ys = ev->nd->u.scr.ys;
  1415. int x = ev->nd->bl.x;
  1416. int y = ev->nd->bl.y;
  1417. if (x > 0 && y > 0 && (xs > -1 && ys > -1) && ((sd->bl.x < x - xs) || (sd->bl.x > x + xs) || (sd->bl.y < y - ys) || (sd->bl.y > y + ys)) ||
  1418. (sd->state.block_action & PCBLOCK_NPCCLICK) || npc_is_cloaked(ev->nd, sd)) {
  1419. npc_event_dequeue(sd);
  1420. return 2;
  1421. }
  1422. }
  1423. run_script(ev->nd->u.scr.script,ev->pos,sd->bl.id,ev->nd->bl.id);
  1424. return 0;
  1425. }
  1426. /*==========================================
  1427. * NPC processing event type
  1428. *------------------------------------------*/
  1429. int npc_event(map_session_data* sd, const char* eventname, int ontouch)
  1430. {
  1431. struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
  1432. struct npc_data *nd;
  1433. nullpo_ret(sd);
  1434. if( ev == NULL || (nd = ev->nd) == NULL )
  1435. {
  1436. if( !ontouch )
  1437. ShowError("npc_event: event not found [%s]\n", eventname);
  1438. return ontouch;
  1439. }
  1440. if (ontouch == 1) { // OnTouch_
  1441. if (pc_ishiding(sd))
  1442. return 0;
  1443. nd->touching_id = sd->bl.id;
  1444. if (!util::vector_exists(sd->npc_ontouch_, nd->bl.id))
  1445. sd->npc_ontouch_.push_back(nd->bl.id);
  1446. } else if (ontouch == 2) { // OnTouch
  1447. if (!util::vector_exists(sd->areanpc, nd->bl.id))
  1448. sd->areanpc.push_back(nd->bl.id);
  1449. }
  1450. npc_event_sub(sd,ev,eventname); // Don't return this value so npc_enable_sub doesn't attempt to "click" the NPC if OnTouch fails.
  1451. return 0;
  1452. }
  1453. /*==========================================
  1454. * Sub chk then execute area event type
  1455. *------------------------------------------*/
  1456. int npc_touch_areanpc_sub(struct block_list *bl, va_list ap)
  1457. {
  1458. map_session_data *sd;
  1459. int pc_id;
  1460. char *name;
  1461. nullpo_ret(bl);
  1462. nullpo_ret((sd = map_id2sd(bl->id)));
  1463. pc_id = va_arg(ap,int);
  1464. name = va_arg(ap,char*);
  1465. if( sd->state.warping )
  1466. return 0;
  1467. if( pc_ishiding(sd) )
  1468. return 0;
  1469. if( pc_isdead(sd) )
  1470. return 0;
  1471. if( pc_id == sd->bl.id )
  1472. return 0;
  1473. npc_event(sd,name,1);
  1474. return 1;
  1475. }
  1476. /*==========================================
  1477. * Chk if sd is still touching his assigned npc.
  1478. * If not, it unsets it and searches for another player in range.
  1479. *------------------------------------------*/
  1480. int npc_touchnext_areanpc(map_session_data* sd, bool leavemap)
  1481. {
  1482. if (sd->npc_ontouch_.empty())
  1483. return 0;
  1484. bool found = false;
  1485. sd->npc_ontouch_.erase(std::remove_if(sd->npc_ontouch_.begin(), sd->npc_ontouch_.end(), [&] (const int &current_npc_id) {
  1486. struct npc_data *nd = map_id2nd(current_npc_id);
  1487. if (!nd) {
  1488. return true;
  1489. } else {
  1490. int16 xs = nd->u.scr.xs;
  1491. int16 ys = nd->u.scr.ys;
  1492. // note : hiding doesn't reset the previous trigger status
  1493. // player must leave the area to reset nd->touching_id on official
  1494. if (sd->bl.m != nd->bl.m || sd->bl.x < nd->bl.x - xs || sd->bl.x > nd->bl.x + xs || sd->bl.y < nd->bl.y - ys || sd->bl.y > nd->bl.y + ys || leavemap) {
  1495. char name[EVENT_NAME_LENGTH];
  1496. if (nd->touching_id && nd->touching_id == sd->bl.id) {// empty when reload script
  1497. found = true;
  1498. nd->touching_id = 0;
  1499. safesnprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_event_name);
  1500. map_forcountinarea(npc_touch_areanpc_sub,nd->bl.m,nd->bl.x - xs,nd->bl.y - ys,nd->bl.x + xs,nd->bl.y + ys,1,BL_PC,sd->bl.id,name);
  1501. }
  1502. return true;
  1503. }
  1504. }
  1505. return false;
  1506. }), sd->npc_ontouch_.end());
  1507. return found;
  1508. }
  1509. int npc_touch_areanpc(map_session_data* sd, int16 m, int16 x, int16 y, struct npc_data *nd)
  1510. {
  1511. nullpo_retr(0, sd);
  1512. nullpo_retr(0, nd);
  1513. if (nd->sc.option&OPTION_INVISIBLE)
  1514. return 1; // a npc was found, but it is disabled
  1515. if (npc_is_cloaked(nd, sd))
  1516. return 1;
  1517. if( npc_is_hidden_dynamicnpc( *nd, *sd ) ){
  1518. return 1;
  1519. }
  1520. int xs = -1, ys = -1;
  1521. switch(nd->subtype) {
  1522. case NPCTYPE_WARP:
  1523. xs = nd->u.warp.xs;
  1524. ys = nd->u.warp.ys;
  1525. break;
  1526. case NPCTYPE_SCRIPT:
  1527. xs = nd->u.scr.xs;
  1528. ys = nd->u.scr.ys;
  1529. break;
  1530. default:
  1531. return 0;
  1532. }
  1533. if (xs < 0 || ys < 0)
  1534. return 0;
  1535. if (x < (nd->bl.x - xs) || x > (nd->bl.x + xs) || y < (nd->bl.y - ys) || y > (nd->bl.y + ys))
  1536. return 0;
  1537. switch (nd->subtype) {
  1538. case NPCTYPE_WARP:
  1539. if ((!nd->trigger_on_hidden && (pc_ishiding(sd) || (sd->sc.count && sd->sc.getSCE(SC_CAMOUFLAGE)))) || pc_isdead(sd))
  1540. break; // hidden or dead chars cannot use warps
  1541. if (!pc_job_can_entermap((enum e_job)sd->status.class_, map_mapindex2mapid(nd->u.warp.mapindex), pc_get_group_level(sd)))
  1542. break;
  1543. if (sd->count_rewarp > 10) {
  1544. ShowWarning("Prevented infinite warp loop for player (%d:%d). Please fix NPC: '%s', path: '%s'\n", sd->status.account_id, sd->status.char_id, nd->exname, nd->path);
  1545. sd->count_rewarp = 0;
  1546. break;
  1547. }
  1548. pc_setpos(sd, nd->u.warp.mapindex, nd->u.warp.x, nd->u.warp.y, CLR_OUTSIGHT);
  1549. return 2;
  1550. case NPCTYPE_SCRIPT:
  1551. // warp type sorted first, no need to check if they override any other OnTouch areas.
  1552. if (npc_ontouch_event(sd, nd) > 0 && npc_ontouch2_event(sd, nd) > 0) { // failed to run OnTouch event, so just click the npc
  1553. if (!util::vector_exists(sd->areanpc, nd->bl.id))
  1554. sd->areanpc.push_back(nd->bl.id);
  1555. if (sd->npc_id == 0)
  1556. npc_click(sd, nd);
  1557. }
  1558. break;
  1559. }
  1560. return 1;
  1561. }
  1562. /*==========================================
  1563. * Exec OnTouch for player if in range of area event
  1564. *------------------------------------------*/
  1565. int npc_touch_area_allnpc(map_session_data* sd, int16 m, int16 x, int16 y)
  1566. {
  1567. nullpo_retr(1, sd);
  1568. // Remove NPCs that are no longer within the OnTouch area
  1569. for (size_t i = 0; i < sd->areanpc.size(); i++) {
  1570. struct npc_data *nd = map_id2nd(sd->areanpc[i]);
  1571. if (!nd || nd->subtype != NPCTYPE_SCRIPT || !(nd->bl.m == m && x >= nd->bl.x - nd->u.scr.xs && x <= nd->bl.x + nd->u.scr.xs && y >= nd->bl.y - nd->u.scr.ys && y <= nd->bl.y + nd->u.scr.ys))
  1572. util::erase_at(sd->areanpc, i);
  1573. }
  1574. if (sd->state.block_action & PCBLOCK_NPCCLICK)
  1575. return 0;
  1576. struct map_data *mapdata = map_getmapdata(m);
  1577. int f = 1;
  1578. for (int i = 0; i < mapdata->npc_num_area; i++) {
  1579. switch( npc_touch_areanpc(sd, m, x, y, mapdata->npc[i]) ) {
  1580. case 0:
  1581. break;
  1582. case 1:
  1583. f = 0;
  1584. break;
  1585. case 2:
  1586. return 0;
  1587. }
  1588. }
  1589. if (f == 1) {
  1590. ShowError("npc_touch_area_allnpc : stray NPC cell/NPC not found in the block on coordinates '%s',%d,%d\n", mapdata->name, x, y);
  1591. return 1;
  1592. }
  1593. return 0;
  1594. }
  1595. // OnTouch NPC or Warp for Mobs
  1596. // Return 1 if Warped
  1597. int npc_touch_areanpc2(struct mob_data *md)
  1598. {
  1599. int i, x = md->bl.x, y = md->bl.y, id;
  1600. char eventname[EVENT_NAME_LENGTH];
  1601. struct event_data* ev;
  1602. int xs, ys;
  1603. struct map_data *mapdata = map_getmapdata(md->bl.m);
  1604. for( i = 0; i < mapdata->npc_num_area; i++ )
  1605. {
  1606. if( mapdata->npc[i]->sc.option&(OPTION_INVISIBLE|OPTION_CLOAK) )
  1607. continue;
  1608. if( mapdata->npc[i]->dynamicnpc.owner_char_id != 0 ){
  1609. continue;
  1610. }
  1611. switch( mapdata->npc[i]->subtype )
  1612. {
  1613. case NPCTYPE_WARP:
  1614. if( !( battle_config.mob_warp&1 ) )
  1615. continue;
  1616. xs = mapdata->npc[i]->u.warp.xs;
  1617. ys = mapdata->npc[i]->u.warp.ys;
  1618. break;
  1619. case NPCTYPE_SCRIPT:
  1620. xs = mapdata->npc[i]->u.scr.xs;
  1621. ys = mapdata->npc[i]->u.scr.ys;
  1622. break;
  1623. default:
  1624. continue; // Keep Searching
  1625. }
  1626. if (xs < 0 || ys < 0)
  1627. continue;
  1628. if( x >= mapdata->npc[i]->bl.x-xs && x <= mapdata->npc[i]->bl.x+xs && y >= mapdata->npc[i]->bl.y-ys && y <= mapdata->npc[i]->bl.y+ys )
  1629. { // In the npc touch area
  1630. switch( mapdata->npc[i]->subtype )
  1631. {
  1632. case NPCTYPE_WARP: {
  1633. int16 warp_m = map_mapindex2mapid(mapdata->npc[i]->u.warp.mapindex);
  1634. if( warp_m < 0 )
  1635. break; // Cannot Warp between map servers
  1636. if( unit_warp(&md->bl, warp_m, mapdata->npc[i]->u.warp.x, mapdata->npc[i]->u.warp.y, CLR_OUTSIGHT) == 0 )
  1637. return 1; // Warped
  1638. }
  1639. break;
  1640. case NPCTYPE_SCRIPT:
  1641. if( mapdata->npc[i]->bl.id == md->areanpc_id )
  1642. break; // Already touch this NPC
  1643. safesnprintf(eventname, ARRAYLENGTH(eventname), "%s::%s", mapdata->npc[i]->exname, script_config.ontouchnpc_event_name);
  1644. if( (ev = (struct event_data*)strdb_get(ev_db, eventname)) == NULL || ev->nd == NULL )
  1645. break; // No OnTouchNPC Event
  1646. md->areanpc_id = mapdata->npc[i]->bl.id;
  1647. id = md->bl.id; // Stores Unique ID
  1648. run_script(ev->nd->u.scr.script, ev->pos, md->bl.id, ev->nd->bl.id);
  1649. if( map_id2md(id) == NULL ) return 1; // Not Warped, but killed
  1650. break;
  1651. }
  1652. return 0;
  1653. }
  1654. }
  1655. return 0;
  1656. }
  1657. /**
  1658. * Checks if there are any NPC on-touch objects on the given range.
  1659. * @param flag : Flag determines the type of object to check for
  1660. * &1: NPC Warps
  1661. * &2: NPCs with on-touch events.
  1662. * @param m : mapindex
  1663. * @param x : x coord
  1664. * @param y : y coord
  1665. * @param range : range to check
  1666. * @return 0: no npc on target cells, x: npc_id
  1667. */
  1668. int npc_check_areanpc(int flag, int16 m, int16 x, int16 y, int16 range)
  1669. {
  1670. int i;
  1671. int x0,y0,x1,y1;
  1672. int xs,ys;
  1673. if (range < 0) return 0;
  1674. struct map_data *mapdata = map_getmapdata(m);
  1675. x0 = i16max(x-range, 0);
  1676. y0 = i16max(y-range, 0);
  1677. x1 = i16min(x+range, mapdata->xs-1);
  1678. y1 = i16min(y+range, mapdata->ys-1);
  1679. //First check for npc_cells on the range given
  1680. i = 0;
  1681. for (ys = y0; ys <= y1 && !i; ys++) {
  1682. for(xs = x0; xs <= x1 && !i; xs++){
  1683. if (map_getcell(m,xs,ys,CELL_CHKNPC))
  1684. i = 1;
  1685. }
  1686. }
  1687. if (!i) return 0; //No NPC_CELLs.
  1688. //Now check for the actual NPC on said range.
  1689. for (i = 0; i < mapdata->npc_num_area; i++)
  1690. {
  1691. if (mapdata->npc[i]->sc.option&OPTION_INVISIBLE)
  1692. continue;
  1693. if( mapdata->npc[i]->dynamicnpc.owner_char_id != 0 ){
  1694. continue;
  1695. }
  1696. switch(mapdata->npc[i]->subtype)
  1697. {
  1698. case NPCTYPE_WARP:
  1699. if (!(flag&1))
  1700. continue;
  1701. xs=mapdata->npc[i]->u.warp.xs;
  1702. ys=mapdata->npc[i]->u.warp.ys;
  1703. break;
  1704. case NPCTYPE_SCRIPT:
  1705. if (!(flag&2))
  1706. continue;
  1707. xs=mapdata->npc[i]->u.scr.xs;
  1708. ys=mapdata->npc[i]->u.scr.ys;
  1709. break;
  1710. default:
  1711. continue;
  1712. }
  1713. if( x1 >= mapdata->npc[i]->bl.x-xs && x0 <= mapdata->npc[i]->bl.x+xs
  1714. && y1 >= mapdata->npc[i]->bl.y-ys && y0 <= mapdata->npc[i]->bl.y+ys )
  1715. break; // found a npc
  1716. }
  1717. if (i == mapdata->npc_num_area)
  1718. return 0;
  1719. return (mapdata->npc[i]->bl.id);
  1720. }
  1721. /*==========================================
  1722. * Chk if player not too far to access the npc.
  1723. * Returns npc_data (success) or NULL (fail).
  1724. *------------------------------------------*/
  1725. struct npc_data* npc_checknear(map_session_data* sd, struct block_list* bl)
  1726. {
  1727. struct npc_data *nd;
  1728. nullpo_retr(NULL, sd);
  1729. if(bl == NULL) return NULL;
  1730. if(bl->type != BL_NPC) return NULL;
  1731. nd = (TBL_NPC*)bl;
  1732. if(sd->state.using_fake_npc && sd->npc_id == bl->id)
  1733. return nd;
  1734. if (nd->class_<0) //Class-less npc, enable click from anywhere.
  1735. return nd;
  1736. if (bl->m!=sd->bl.m ||
  1737. bl->x<sd->bl.x-AREA_SIZE-1 || bl->x>sd->bl.x+AREA_SIZE+1 ||
  1738. bl->y<sd->bl.y-AREA_SIZE-1 || bl->y>sd->bl.y+AREA_SIZE+1)
  1739. return NULL;
  1740. return nd;
  1741. }
  1742. /*==========================================
  1743. * Make NPC talk in global chat (like npctalk)
  1744. *------------------------------------------*/
  1745. int npc_globalmessage(const char* name, const char* mes)
  1746. {
  1747. struct npc_data* nd = npc_name2id(name);
  1748. char temp[100];
  1749. if (!nd)
  1750. return 0;
  1751. snprintf(temp, sizeof(temp), "%s", mes);
  1752. clif_GlobalMessage(&nd->bl,temp,ALL_CLIENT);
  1753. return 0;
  1754. }
  1755. // MvP tomb [GreenBox]
  1756. void run_tomb(map_session_data* sd, struct npc_data* nd)
  1757. {
  1758. char buffer[200];
  1759. char time[10];
  1760. strftime(time, sizeof(time), "%H:%M", localtime(&nd->u.tomb.kill_time));
  1761. // TODO: Find exact color?
  1762. snprintf( buffer, sizeof( buffer ), msg_txt( sd, 657 ), nd->u.tomb.md->db->name.c_str() ); // [ ^EE0000%s^000000 ]
  1763. clif_scriptmes( *sd, nd->bl.id, buffer );
  1764. clif_scriptmes( *sd, nd->bl.id, msg_txt( sd, 658 ) ); // Has met its demise
  1765. snprintf( buffer, sizeof( buffer ), msg_txt( sd, 659 ), time ); // Time of death : ^EE0000%s^000000
  1766. clif_scriptmes( *sd, nd->bl.id, buffer );
  1767. clif_scriptmes( *sd, nd->bl.id, msg_txt( sd, 660 ) ); // Defeated by
  1768. snprintf( buffer, sizeof( buffer ), msg_txt( sd, 661 ), nd->u.tomb.killer_name[0] ? nd->u.tomb.killer_name : "Unknown" ); // [^EE0000%s^000000]
  1769. clif_scriptmes( *sd, nd->bl.id, buffer );
  1770. clif_scriptclose(sd, nd->bl.id);
  1771. }
  1772. /*==========================================
  1773. * NPC 1st call when clicking on npc
  1774. * Do specific action for NPC type (openshop, run scripts...)
  1775. *------------------------------------------*/
  1776. int npc_click(map_session_data* sd, struct npc_data* nd)
  1777. {
  1778. nullpo_retr(1, sd);
  1779. if (sd->npc_id != 0) {
  1780. ShowError("npc_click: npc_id != 0\n");
  1781. return 1;
  1782. }
  1783. if(!nd) return 1;
  1784. if ((nd = npc_checknear(sd,&nd->bl)) == NULL)
  1785. return 1;
  1786. //Hidden/Disabled npc.
  1787. if (nd->class_ < 0 || nd->sc.option&(OPTION_INVISIBLE|OPTION_HIDE))
  1788. return 1;
  1789. if( npc_is_hidden_dynamicnpc( *nd, *sd ) ){
  1790. return 1;
  1791. }
  1792. if (sd->state.block_action & PCBLOCK_NPCCLICK) {
  1793. clif_msg(sd, WORK_IN_PROGRESS);
  1794. return 1;
  1795. }
  1796. if( nd->dynamicnpc.owner_char_id != 0 ){
  1797. nd->dynamicnpc.last_interaction = gettick();
  1798. }
  1799. switch(nd->subtype) {
  1800. case NPCTYPE_SHOP:
  1801. clif_npcbuysell(sd,nd->bl.id);
  1802. break;
  1803. case NPCTYPE_CASHSHOP:
  1804. case NPCTYPE_ITEMSHOP:
  1805. case NPCTYPE_POINTSHOP:
  1806. clif_cashshop_show(sd,nd);
  1807. break;
  1808. case NPCTYPE_MARKETSHOP:
  1809. #if PACKETVER >= 20131223
  1810. {
  1811. unsigned short i;
  1812. for (i = 0; i < nd->u.shop.count; i++) {
  1813. if (nd->u.shop.shop_item[i].qty)
  1814. break;
  1815. }
  1816. if (i == nd->u.shop.count) {
  1817. clif_messagecolor(&sd->bl, color_table[COLOR_RED], msg_txt(sd, 534), false, SELF);
  1818. return false;
  1819. }
  1820. sd->npc_shopid = nd->bl.id;
  1821. clif_npc_market_open(sd, nd);
  1822. }
  1823. #endif
  1824. break;
  1825. case NPCTYPE_SCRIPT:
  1826. run_script(nd->u.scr.script,0,sd->bl.id,nd->bl.id);
  1827. break;
  1828. case NPCTYPE_TOMB:
  1829. run_tomb(sd,nd);
  1830. break;
  1831. case NPCTYPE_BARTER:
  1832. sd->npc_shopid = nd->bl.id;
  1833. if( nd->u.barter.extended ){
  1834. clif_barter_extended_open( *sd, *nd );
  1835. }else{
  1836. clif_barter_open( *sd, *nd );
  1837. }
  1838. break;
  1839. }
  1840. return 0;
  1841. }
  1842. /*==========================================
  1843. *
  1844. *------------------------------------------*/
  1845. bool npc_scriptcont(map_session_data* sd, int id, bool closing){
  1846. struct block_list *target = map_id2bl(id);
  1847. struct npc_data* nd = BL_CAST( BL_NPC, target );
  1848. nullpo_retr(true, sd);
  1849. #ifdef SECURE_NPCTIMEOUT
  1850. if( !closing && sd->npc_idle_timer == INVALID_TIMER && !sd->state.ignoretimeout )
  1851. return true;
  1852. #endif
  1853. if( id != sd->npc_id ){
  1854. TBL_NPC* nd_sd = (TBL_NPC*)map_id2bl(sd->npc_id);
  1855. ShowDebug("npc_scriptcont: %s (sd->npc_id=%d) is not %s (id=%d).\n",
  1856. nd_sd?(char*)nd_sd->name:"'Unknown NPC'", (int)sd->npc_id,
  1857. nd?(char*)nd->name:"'Unknown NPC'", (int)id);
  1858. return true;
  1859. }
  1860. if(id != fake_nd->bl.id) { // Not item script
  1861. if ((npc_checknear(sd, target)) == NULL) {
  1862. ShowWarning("npc_scriptcont: failed npc_checknear test.\n");
  1863. return true;
  1864. }
  1865. }
  1866. #ifdef SECURE_NPCTIMEOUT
  1867. if( !closing )
  1868. sd->npc_idle_tick = gettick(); //Update the last NPC iteration
  1869. #endif
  1870. if( nd != nullptr && nd->dynamicnpc.owner_char_id != 0 ){
  1871. nd->dynamicnpc.last_interaction = gettick();
  1872. }
  1873. /**
  1874. * WPE can get to this point with a progressbar; we deny it.
  1875. **/
  1876. if( sd->progressbar.npc_id && DIFF_TICK(sd->progressbar.timeout,gettick()) > 0 )
  1877. return true;
  1878. if( sd->st == nullptr ){
  1879. return true;
  1880. }
  1881. if( closing ){
  1882. switch( sd->st->state ){
  1883. // close
  1884. case CLOSE:
  1885. sd->st->state = END;
  1886. if (sd->st->clear_cutin)
  1887. clif_cutin(sd,"",255);
  1888. break;
  1889. // close2
  1890. case STOP:
  1891. sd->st->state = RUN;
  1892. break;
  1893. default:
  1894. sd->st->state = END;
  1895. ShowError( "npc_scriptcont: unexpected state '%d' for closing call. (AID: %u CID: %u)\n", sd->st->state, sd->status.account_id, sd->status.char_id );
  1896. break;
  1897. }
  1898. }else{
  1899. switch( sd->st->state ){
  1900. // next
  1901. // progressbar
  1902. case STOP:
  1903. sd->st->state = RUN;
  1904. break;
  1905. // input
  1906. // menu
  1907. // select
  1908. case RERUNLINE:
  1909. // keep state as it is
  1910. break;
  1911. default:
  1912. sd->st->state = END;
  1913. ShowError( "npc_scriptcont: unexpected state '%d' for continue call. (AID: %u CID: %u)\n", sd->st->state, sd->status.account_id, sd->status.char_id );
  1914. break;
  1915. }
  1916. }
  1917. // Call this even, if it was set to end, because it will free the script state
  1918. run_script_main(sd->st);
  1919. return false;
  1920. }
  1921. /**
  1922. * Open the shop Buy or Sell list
  1923. * @param sd: Player data
  1924. * @param id: NPC ID
  1925. * @param type: 0 - Buy, 1 - Sell
  1926. * @return 0 on success or 1 on failure
  1927. */
  1928. int npc_buysellsel(map_session_data* sd, int id, int type)
  1929. {
  1930. struct npc_data *nd;
  1931. nullpo_retr(1, sd);
  1932. if ((nd = npc_checknear(sd,map_id2bl(id))) == NULL)
  1933. return 1;
  1934. if (nd->subtype != NPCTYPE_SHOP) {
  1935. ShowError("no such shop npc : %d\n",id);
  1936. if (sd->npc_id == id)
  1937. sd->npc_id=0;
  1938. return 1;
  1939. }
  1940. if (nd->sc.option & OPTION_INVISIBLE) // can't buy if npc is not visible (hack?)
  1941. return 1;
  1942. if( npc_is_hidden_dynamicnpc( *nd, *sd ) ){
  1943. return 1;
  1944. }
  1945. sd->npc_shopid = id;
  1946. if (type == 0) {
  1947. clif_buylist(sd,nd);
  1948. } else {
  1949. clif_selllist(sd);
  1950. }
  1951. return 0;
  1952. }
  1953. /** Payment Process for NPCTYPE_CASHSHOP, NPCTYPE_ITEMSHOP, and NPCTYPE_POINTSHOP
  1954. * @param nd NPC Shop data
  1955. * @param price Price must be paid
  1956. * @param points Amount of secondary points that player requested
  1957. * @param sd Player data
  1958. * @return e_CASHSHOP_ACK
  1959. **/
  1960. static enum e_CASHSHOP_ACK npc_cashshop_process_payment(struct npc_data *nd, int price, int points, map_session_data *sd) {
  1961. int cost[2] = { 0, 0 };
  1962. npc_shop_currency_type(sd, nd, cost, false);
  1963. switch(nd->subtype) {
  1964. case NPCTYPE_CASHSHOP:
  1965. if (cost[1] < points || cost[0] < (price - points))
  1966. return ERROR_TYPE_MONEY;
  1967. if (pc_paycash(sd, price, points, LOG_TYPE_NPC) <= 0) {
  1968. return ERROR_TYPE_MONEY;
  1969. }
  1970. break;
  1971. case NPCTYPE_ITEMSHOP:
  1972. {
  1973. std::shared_ptr<item_data> id = item_db.find(nd->u.shop.itemshop_nameid);
  1974. int delete_amount = price, i;
  1975. if (!id) { // Item Data is checked at script parsing but in case of item_db reload, check again.
  1976. ShowWarning("Failed to find sellitem %u for itemshop NPC '%s' (%s, %d, %d)!\n", nd->u.shop.itemshop_nameid, nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y);
  1977. return ERROR_TYPE_PURCHASE_FAIL;
  1978. }
  1979. if (cost[1] < points || cost[0] < (price - points)) {
  1980. char output[CHAT_SIZE_MAX];
  1981. memset(output, '\0', sizeof(output));
  1982. sprintf(output, msg_txt(sd, 712), id->ename.c_str(), id->nameid); // You do not have enough %s (%u).
  1983. clif_messagecolor(&sd->bl, color_table[COLOR_RED], output, false, SELF);
  1984. return ERROR_TYPE_PURCHASE_FAIL;
  1985. }
  1986. for (i = 0; i < MAX_INVENTORY && delete_amount > 0; i++) {
  1987. struct item *it;
  1988. int amount = 0;
  1989. if (sd->inventory.u.items_inventory[i].nameid == 0 || sd->inventory_data[i] == NULL || !(it = &sd->inventory.u.items_inventory[i]) || it->nameid != nd->u.shop.itemshop_nameid)
  1990. continue;
  1991. if (!pc_can_sell_item(sd, it, nd->subtype))
  1992. continue;
  1993. amount = it->amount;
  1994. if (amount > delete_amount)
  1995. amount = delete_amount;
  1996. if (pc_delitem(sd, i, amount, 0, 0, LOG_TYPE_NPC)) {
  1997. ShowWarning("Failed to delete item %u from '%s' at itemshop NPC '%s' (%s, %d, %d)!\n", nd->u.shop.itemshop_nameid, sd->status.name, nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y);
  1998. return ERROR_TYPE_PURCHASE_FAIL;
  1999. }
  2000. delete_amount -= amount;
  2001. }
  2002. if (delete_amount > 0) {
  2003. ShowError("Item %u is not enough as payment at itemshop NPC '%s' (%s, %d, %d, AID=%d, CID=%d)!\n", nd->u.shop.itemshop_nameid, nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y, sd->status.account_id, sd->status.char_id);
  2004. return ERROR_TYPE_PURCHASE_FAIL;
  2005. }
  2006. }
  2007. break;
  2008. case NPCTYPE_POINTSHOP:
  2009. {
  2010. char output[CHAT_SIZE_MAX];
  2011. memset(output, '\0', sizeof(output));
  2012. if (cost[1] < points || cost[0] < (price - points)) {
  2013. sprintf(output, msg_txt(sd, 713), nd->u.shop.pointshop_str); // You do not have enough '%s'.
  2014. clif_messagecolor(&sd->bl, color_table[COLOR_RED], output, false, SELF);
  2015. return ERROR_TYPE_PURCHASE_FAIL;
  2016. }
  2017. pc_setreg2(sd, nd->u.shop.pointshop_str, cost[0] - (price - points));
  2018. sprintf(output, msg_txt(sd, 716), nd->u.shop.pointshop_str, cost[0] - (price - points)); // Your '%s' is now: %d
  2019. clif_messagecolor(&sd->bl, color_table[COLOR_LIGHT_GREEN], output, false, SELF);
  2020. }
  2021. break;
  2022. }
  2023. return ERROR_TYPE_NONE;
  2024. }
  2025. /**
  2026. * Cash Shop Buy List for clients 2010-11-16 and newer
  2027. * @param sd: Player data
  2028. * @param points: Secondary point
  2029. * @param count: Amount of items to purchase
  2030. * @param item_list: List of items to purchase
  2031. * @return clif_cashshop_ack value to display
  2032. */
  2033. int npc_cashshop_buylist( map_session_data *sd, int points, std::vector<s_npc_buy_list>& item_list ){
  2034. int i, j, amount, new_, w, vt;
  2035. t_itemid nameid;
  2036. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  2037. enum e_CASHSHOP_ACK res;
  2038. if( !nd || ( nd->subtype != NPCTYPE_CASHSHOP && nd->subtype != NPCTYPE_ITEMSHOP && nd->subtype != NPCTYPE_POINTSHOP ) )
  2039. return ERROR_TYPE_NPC;
  2040. if( sd->state.trading )
  2041. return ERROR_TYPE_EXCHANGE;
  2042. new_ = 0;
  2043. w = 0;
  2044. vt = 0; // Global Value
  2045. // Validating Process ----------------------------------------------------
  2046. for( i = 0; i < item_list.size(); i++ )
  2047. {
  2048. nameid = item_list[i].nameid;
  2049. amount = item_list[i].qty;
  2050. std::shared_ptr<item_data> id = item_db.find(nameid);
  2051. if( !id || amount <= 0 )
  2052. return ERROR_TYPE_ITEM_ID;
  2053. ARR_FIND(0,nd->u.shop.count,j,nd->u.shop.shop_item[j].nameid == nameid || itemdb_viewid(nd->u.shop.shop_item[j].nameid) == nameid);
  2054. if( j == nd->u.shop.count || nd->u.shop.shop_item[j].value <= 0 )
  2055. return ERROR_TYPE_ITEM_ID;
  2056. nameid = item_list[i].nameid = nd->u.shop.shop_item[j].nameid; //item_avail replacement
  2057. if( !itemdb_isstackable2(id.get()) && amount > 1 )
  2058. {
  2059. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %u!\n", sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  2060. amount = item_list[i].qty = 1;
  2061. }
  2062. if( nd->master_nd ) { // Script-controlled shops decide by themselves, what can be bought and for what price.
  2063. continue;
  2064. }
  2065. switch( pc_checkadditem(sd,nameid,amount) )
  2066. {
  2067. case CHKADDITEM_NEW:
  2068. new_ += id->inventorySlotNeeded(amount);
  2069. break;
  2070. case CHKADDITEM_OVERAMOUNT:
  2071. return ERROR_TYPE_INVENTORY_WEIGHT;
  2072. }
  2073. vt += nd->u.shop.shop_item[j].value * amount;
  2074. w += itemdb_weight(nameid) * amount;
  2075. }
  2076. if (nd->master_nd) //Script-based shops.
  2077. return npc_buylist_sub(sd,item_list,nd->master_nd);
  2078. if( w + sd->weight > sd->max_weight )
  2079. return ERROR_TYPE_INVENTORY_WEIGHT;
  2080. if( pc_inventoryblank(sd) < new_ )
  2081. return ERROR_TYPE_INVENTORY_WEIGHT;
  2082. if( points > vt ) points = vt;
  2083. if ((res = npc_cashshop_process_payment(nd, vt, points, sd)) != ERROR_TYPE_NONE)
  2084. return res;
  2085. // Delivery Process ----------------------------------------------------
  2086. for( i = 0; i < item_list.size(); i++ ) {
  2087. nameid = item_list[i].nameid;
  2088. amount = item_list[i].qty;
  2089. if( !pet_create_egg(sd,nameid) ) {
  2090. struct item item_tmp;
  2091. unsigned short get_amt = amount;
  2092. memset(&item_tmp, 0, sizeof(item_tmp));
  2093. item_tmp.nameid = nameid;
  2094. item_tmp.identify = 1;
  2095. if ((itemdb_search(nameid))->flag.guid)
  2096. get_amt = 1;
  2097. for (j = 0; j < amount; j += get_amt)
  2098. pc_additem(sd,&item_tmp,get_amt,LOG_TYPE_NPC);
  2099. }
  2100. }
  2101. return ERROR_TYPE_NONE;
  2102. }
  2103. /**
  2104. * Returns the shop currency type
  2105. * @param sd: Player data
  2106. * @param nd: NPC data
  2107. * @param cost: Reference to cost variable
  2108. * @param display: Display cost type to player?
  2109. */
  2110. void npc_shop_currency_type(map_session_data *sd, struct npc_data *nd, int cost[2], bool display)
  2111. {
  2112. nullpo_retv(sd);
  2113. if (!nd) { // Assume it's Cash Shop through the button
  2114. cost[0] = sd->cashPoints;
  2115. cost[1] = sd->kafraPoints;
  2116. return;
  2117. }
  2118. switch(nd->subtype) {
  2119. case NPCTYPE_CASHSHOP:
  2120. cost[0] = sd->cashPoints;
  2121. cost[1] = sd->kafraPoints;
  2122. break;
  2123. case NPCTYPE_ITEMSHOP:
  2124. {
  2125. int total = 0, i;
  2126. std::shared_ptr<item_data> id = item_db.find(nd->u.shop.itemshop_nameid);
  2127. if (id) { // Item Data is checked at script parsing but in case of item_db reload, check again.
  2128. if (display) {
  2129. char output[CHAT_SIZE_MAX];
  2130. memset(output, '\0', sizeof(output));
  2131. sprintf(output, msg_txt(sd, 714), id->ename.c_str(), id->nameid); // Item Shop List: %s (%u)
  2132. clif_broadcast(&sd->bl, output, strlen(output) + 1, BC_BLUE,SELF);
  2133. }
  2134. for (i = 0; i < MAX_INVENTORY; i++) {
  2135. if (sd->inventory.u.items_inventory[i].amount > 0 && sd->inventory.u.items_inventory[i].nameid == id->nameid && pc_can_sell_item(sd, &sd->inventory.u.items_inventory[i], nd->subtype))
  2136. total += sd->inventory.u.items_inventory[i].amount;
  2137. }
  2138. }
  2139. cost[0] = total;
  2140. }
  2141. break;
  2142. case NPCTYPE_POINTSHOP:
  2143. if (display) {
  2144. char output[CHAT_SIZE_MAX];
  2145. memset(output, '\0', sizeof(output));
  2146. sprintf(output, msg_txt(sd, 715), nd->u.shop.pointshop_str); // Point Shop List: '%s'
  2147. clif_broadcast(&sd->bl, output, strlen(output) + 1, BC_BLUE,SELF);
  2148. }
  2149. cost[0] = static_cast<int>(pc_readreg2(sd, nd->u.shop.pointshop_str));
  2150. break;
  2151. }
  2152. }
  2153. /**
  2154. * Cash Shop Buy List for clients 2010-11-15 and older
  2155. * @param sd: Player data
  2156. * @param nameid: Item to purchase
  2157. * @param amount: Amount of items to purchase
  2158. * @param points: Cost of total items
  2159. * @return clif_cashshop_ack value to display
  2160. */
  2161. int npc_cashshop_buy(map_session_data *sd, t_itemid nameid, int amount, int points)
  2162. {
  2163. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  2164. int i, price, w;
  2165. enum e_CASHSHOP_ACK res;
  2166. if( amount <= 0 )
  2167. return ERROR_TYPE_ITEM_ID;
  2168. if( points < 0 )
  2169. return ERROR_TYPE_MONEY;
  2170. if( !nd || (nd->subtype != NPCTYPE_CASHSHOP && nd->subtype != NPCTYPE_ITEMSHOP && nd->subtype != NPCTYPE_POINTSHOP) )
  2171. return ERROR_TYPE_NPC;
  2172. if( sd->state.trading )
  2173. return ERROR_TYPE_EXCHANGE;
  2174. std::shared_ptr<item_data> id = item_db.find(nameid);
  2175. if( id == nullptr )
  2176. return ERROR_TYPE_ITEM_ID; // Invalid Item
  2177. ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid || itemdb_viewid(nd->u.shop.shop_item[i].nameid) == nameid);
  2178. if( i == nd->u.shop.count )
  2179. return ERROR_TYPE_ITEM_ID;
  2180. if( nd->u.shop.shop_item[i].value <= 0 )
  2181. return ERROR_TYPE_ITEM_ID;
  2182. nameid = nd->u.shop.shop_item[i].nameid; //item_avail replacement
  2183. if(!itemdb_isstackable2(id.get()) && amount > 1)
  2184. {
  2185. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %u!\n",
  2186. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  2187. amount = 1;
  2188. }
  2189. switch( pc_checkadditem(sd, nameid, amount) )
  2190. {
  2191. case CHKADDITEM_NEW:
  2192. if( pc_inventoryblank(sd) < id->inventorySlotNeeded(amount) )
  2193. return ERROR_TYPE_INVENTORY_WEIGHT;
  2194. break;
  2195. case CHKADDITEM_OVERAMOUNT:
  2196. return ERROR_TYPE_INVENTORY_WEIGHT;
  2197. }
  2198. w = id->weight * amount;
  2199. if( w + sd->weight > sd->max_weight )
  2200. return ERROR_TYPE_INVENTORY_WEIGHT;
  2201. if( (double)nd->u.shop.shop_item[i].value * amount > INT_MAX )
  2202. {
  2203. ShowWarning("npc_cashshop_buy: Item '%s' (%u) price overflow attempt!\n", id->name.c_str(), nameid);
  2204. ShowDebug("(NPC:'%s' (%s,%d,%d), player:'%s' (%d/%d), value:%d, amount:%d)\n",
  2205. nd->exname, map_mapid2mapname(nd->bl.m), nd->bl.x, nd->bl.y, sd->status.name, sd->status.account_id, sd->status.char_id, nd->u.shop.shop_item[i].value, amount);
  2206. return ERROR_TYPE_ITEM_ID;
  2207. }
  2208. price = nd->u.shop.shop_item[i].value * amount;
  2209. if( points > price )
  2210. points = price;
  2211. if ((res = npc_cashshop_process_payment(nd, price, points, sd)) != ERROR_TYPE_NONE)
  2212. return res;
  2213. if( !pet_create_egg(sd, nameid) ) {
  2214. unsigned short get_amt = amount;
  2215. struct item item_tmp = {};
  2216. item_tmp.nameid = nameid;
  2217. item_tmp.identify = 1;
  2218. if (id->flag.guid)
  2219. get_amt = 1;
  2220. for (int j = 0; j < amount; j += get_amt)
  2221. pc_additem(sd,&item_tmp, get_amt, LOG_TYPE_NPC);
  2222. }
  2223. return ERROR_TYPE_NONE;
  2224. }
  2225. /**
  2226. * NPC buylist for script-controlled shops
  2227. * @param sd: Player who bought
  2228. * @param n: Number of items
  2229. * @param item_list: List of items
  2230. * @param nd: Attached NPC
  2231. */
  2232. static int npc_buylist_sub(map_session_data* sd, std::vector<s_npc_buy_list>& item_list, struct npc_data* nd) {
  2233. char npc_ev[EVENT_NAME_LENGTH];
  2234. int key_nameid = 0, key_amount = 0;
  2235. // discard old contents
  2236. script_cleararray_pc( sd, "@bought_nameid" );
  2237. script_cleararray_pc( sd, "@bought_quantity" );
  2238. // save list of bought items
  2239. for( int i = 0; i < item_list.size(); i++ ){
  2240. script_setarray_pc( sd, "@bought_nameid", i, item_list[i].nameid, &key_nameid );
  2241. script_setarray_pc( sd, "@bought_quantity", i, item_list[i].qty, &key_amount );
  2242. }
  2243. // invoke event
  2244. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::%s", nd->exname, script_config.onbuy_event_name);
  2245. npc_event(sd, npc_ev, 0);
  2246. return 0;
  2247. }
  2248. /**
  2249. * Shop buylist that the player is attempting to purchase
  2250. * @param sd: Player who attempt to buy
  2251. * @param n: Number of items
  2252. * @param item_list: List of items
  2253. * @return result code for clif_parse_NpcBuyListSend/clif_npc_market_purchase_ack
  2254. */
  2255. e_purchase_result npc_buylist( map_session_data* sd, std::vector<s_npc_buy_list>& item_list ){
  2256. struct npc_data* nd;
  2257. struct npc_item_list *shop = NULL;
  2258. double z;
  2259. int j,k,w,skill,new_;
  2260. uint8 market_index[MAX_INVENTORY];
  2261. nullpo_retr(e_purchase_result::PURCHASE_FAIL_COUNT, sd);
  2262. nd = npc_checknear(sd,map_id2bl(sd->npc_shopid));
  2263. if( nd == NULL )
  2264. return e_purchase_result::PURCHASE_FAIL_COUNT;
  2265. if( nd->subtype != NPCTYPE_SHOP && nd->subtype != NPCTYPE_MARKETSHOP )
  2266. return e_purchase_result::PURCHASE_FAIL_COUNT;
  2267. if( item_list.empty() ){
  2268. return e_purchase_result::PURCHASE_FAIL_COUNT;
  2269. }
  2270. z = 0;
  2271. w = 0;
  2272. new_ = 0;
  2273. shop = nd->u.shop.shop_item;
  2274. memset(market_index, 0, sizeof(market_index));
  2275. // process entries in buy list, one by one
  2276. for( int i = 0; i < item_list.size(); ++i ){
  2277. t_itemid nameid;
  2278. unsigned short amount;
  2279. int value;
  2280. // find this entry in the shop's sell list
  2281. ARR_FIND( 0, nd->u.shop.count, j,
  2282. item_list[i].nameid == shop[j].nameid || //Normal items
  2283. item_list[i].nameid == itemdb_viewid(shop[j].nameid) //item_avail replacement
  2284. );
  2285. if( j == nd->u.shop.count )
  2286. return e_purchase_result::PURCHASE_FAIL_COUNT; // no such item in shop
  2287. #if PACKETVER >= 20131223
  2288. if (nd->subtype == NPCTYPE_MARKETSHOP) {
  2289. if (shop[j].qty >= 0 && item_list[i].qty > shop[j].qty)
  2290. return e_purchase_result::PURCHASE_FAIL_COUNT;
  2291. market_index[i] = j;
  2292. }
  2293. #endif
  2294. amount = item_list[i].qty;
  2295. nameid = item_list[i].nameid = shop[j].nameid; //item_avail replacement
  2296. value = shop[j].value;
  2297. std::shared_ptr<item_data> id = item_db.find(nameid);
  2298. if( !id )
  2299. return e_purchase_result::PURCHASE_FAIL_COUNT; // item no longer in itemdb
  2300. if( !itemdb_isstackable2(id.get()) && amount > 1 ) { //Exploit? You can't buy more than 1 of equipment types o.O
  2301. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %u!\n",
  2302. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  2303. amount = item_list[i].qty = 1;
  2304. }
  2305. if( nd->master_nd ) { // Script-controlled shops decide by themselves, what can be bought and for what price.
  2306. continue;
  2307. }
  2308. switch( pc_checkadditem(sd,nameid,amount) ) {
  2309. case CHKADDITEM_EXIST:
  2310. break;
  2311. case CHKADDITEM_NEW:
  2312. new_ += id->inventorySlotNeeded(amount);
  2313. break;
  2314. case CHKADDITEM_OVERAMOUNT:
  2315. return e_purchase_result::PURCHASE_FAIL_WEIGHT;
  2316. }
  2317. if (npc_shop_discount(nd))
  2318. value = pc_modifybuyvalue(sd,value);
  2319. z += (double)value * amount;
  2320. w += itemdb_weight(nameid) * amount;
  2321. }
  2322. if (nd->master_nd){ //Script-based shops.
  2323. npc_buylist_sub(sd,item_list,nd->master_nd);
  2324. return e_purchase_result::PURCHASE_SUCCEED;
  2325. }
  2326. if (z > (double)sd->status.zeny)
  2327. return e_purchase_result::PURCHASE_FAIL_MONEY; // Not enough Zeny
  2328. if( w + sd->weight > sd->max_weight )
  2329. return e_purchase_result::PURCHASE_FAIL_WEIGHT; // Too heavy
  2330. if( pc_inventoryblank(sd) < new_ )
  2331. return e_purchase_result::PURCHASE_FAIL_COUNT; // Not enough space to store items
  2332. pc_payzeny(sd, (int)z, LOG_TYPE_NPC, NULL);
  2333. for( int i = 0; i < item_list.size(); ++i ) {
  2334. t_itemid nameid = item_list[i].nameid;
  2335. unsigned short amount = item_list[i].qty;
  2336. #if PACKETVER >= 20131223
  2337. if (nd->subtype == NPCTYPE_MARKETSHOP) {
  2338. j = market_index[i];
  2339. if( shop[j].qty >= 0 ){
  2340. if (amount > shop[j].qty)
  2341. return e_purchase_result::PURCHASE_FAIL_COUNT;
  2342. shop[j].qty -= amount;
  2343. npc_market_tosql(nd->exname, &shop[j]);
  2344. }
  2345. }
  2346. #endif
  2347. if (itemdb_type(nameid) == IT_PETEGG)
  2348. pet_create_egg(sd, nameid);
  2349. else {
  2350. unsigned short get_amt = amount;
  2351. if ((itemdb_search(nameid))->flag.guid)
  2352. get_amt = 1;
  2353. for (k = 0; k < amount; k += get_amt) {
  2354. struct item item_tmp;
  2355. memset(&item_tmp, 0, sizeof(item_tmp));
  2356. item_tmp.nameid = nameid;
  2357. item_tmp.identify = 1;
  2358. pc_additem(sd,&item_tmp,get_amt,LOG_TYPE_NPC);
  2359. }
  2360. }
  2361. }
  2362. // custom merchant shop exp bonus
  2363. if( battle_config.shop_exp > 0 && z > 0 && (skill = pc_checkskill(sd,MC_DISCOUNT)) > 0 ) {
  2364. uint16 sk_idx = skill_get_index(MC_DISCOUNT);
  2365. if( sd->status.skill[sk_idx].flag >= SKILL_FLAG_REPLACED_LV_0 )
  2366. skill = sd->status.skill[sk_idx].flag - SKILL_FLAG_REPLACED_LV_0;
  2367. if( skill > 0 ) {
  2368. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  2369. if( z < 1 )
  2370. z = 1;
  2371. pc_gainexp(sd,NULL,0,(int)z, 0);
  2372. }
  2373. }
  2374. return e_purchase_result::PURCHASE_SUCCEED;
  2375. }
  2376. /// npc_selllist for script-controlled shops
  2377. static int npc_selllist_sub(map_session_data* sd, int list_length, PACKET_CZ_PC_SELL_ITEMLIST_sub* item_list, struct npc_data* nd)
  2378. {
  2379. char npc_ev[EVENT_NAME_LENGTH];
  2380. char card_slot[NAME_LENGTH];
  2381. char option_id[NAME_LENGTH], option_val[NAME_LENGTH], option_param[NAME_LENGTH];
  2382. int i, j;
  2383. int key_nameid = 0;
  2384. int key_amount = 0;
  2385. int key_refine = 0;
  2386. int key_attribute = 0;
  2387. int key_identify = 0;
  2388. int key_enchantgrade = 0;
  2389. int key_card[MAX_SLOTS];
  2390. int key_option_id[MAX_ITEM_RDM_OPT], key_option_val[MAX_ITEM_RDM_OPT], key_option_param[MAX_ITEM_RDM_OPT];
  2391. // discard old contents
  2392. script_cleararray_pc( sd, "@sold_nameid" );
  2393. script_cleararray_pc( sd, "@sold_quantity" );
  2394. script_cleararray_pc( sd, "@sold_refine" );
  2395. script_cleararray_pc( sd, "@sold_attribute" );
  2396. script_cleararray_pc( sd, "@sold_identify" );
  2397. script_cleararray_pc( sd, "@sold_enchantgrade" );
  2398. for( j = 0; j < MAX_SLOTS; j++ )
  2399. {// clear each of the card slot entries
  2400. key_card[j] = 0;
  2401. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  2402. script_cleararray_pc( sd, card_slot );
  2403. }
  2404. for (j = 0; j < MAX_ITEM_RDM_OPT; j++) { // Clear each of the item option entries
  2405. key_option_id[j] = key_option_val[j] = key_option_param[j] = 0;
  2406. snprintf(option_id, sizeof(option_id), "@sold_option_id%d", j + 1);
  2407. script_cleararray_pc( sd, option_id );
  2408. snprintf(option_val, sizeof(option_val), "@sold_option_val%d", j + 1);
  2409. script_cleararray_pc( sd, option_val );
  2410. snprintf(option_param, sizeof(option_param), "@sold_option_param%d", j + 1);
  2411. script_cleararray_pc( sd, option_param );
  2412. }
  2413. // save list of to be sold items
  2414. for( i = 0; i < list_length; i++ )
  2415. {
  2416. int idx = item_list[i].index - 2;
  2417. script_setarray_pc( sd, "@sold_nameid", i, sd->inventory.u.items_inventory[idx].nameid, &key_nameid );
  2418. script_setarray_pc( sd, "@sold_quantity", i, item_list[i].amount, &key_amount );
  2419. if( itemdb_isequip(sd->inventory.u.items_inventory[idx].nameid) )
  2420. {// process equipment based information into the arrays
  2421. script_setarray_pc( sd, "@sold_refine", i, sd->inventory.u.items_inventory[idx].refine, &key_refine );
  2422. script_setarray_pc( sd, "@sold_attribute", i, sd->inventory.u.items_inventory[idx].attribute, &key_attribute );
  2423. script_setarray_pc( sd, "@sold_identify", i, sd->inventory.u.items_inventory[idx].identify, &key_identify );
  2424. script_setarray_pc( sd, "@sold_enchantgrade", i, sd->inventory.u.items_inventory[idx].enchantgrade, &key_enchantgrade );
  2425. for( j = 0; j < MAX_SLOTS; j++ )
  2426. {// store each of the cards from the equipment in the array
  2427. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  2428. script_setarray_pc( sd, card_slot, i, sd->inventory.u.items_inventory[idx].card[j], &key_card[j] );
  2429. }
  2430. for (j = 0; j < MAX_ITEM_RDM_OPT; j++) { // Store each of the item options in the array
  2431. snprintf(option_id, sizeof(option_id), "@sold_option_id%d", j + 1);
  2432. script_setarray_pc( sd, option_id, i, sd->inventory.u.items_inventory[idx].option[j].id, &key_option_id[j] );
  2433. snprintf(option_val, sizeof(option_val), "@sold_option_val%d", j + 1);
  2434. script_setarray_pc( sd, option_val, i, sd->inventory.u.items_inventory[idx].option[j].value, &key_option_val[j] );
  2435. snprintf(option_param, sizeof(option_param), "@sold_option_param%d", j + 1);
  2436. script_setarray_pc( sd, option_param, i, sd->inventory.u.items_inventory[idx].option[j].param, &key_option_param[j] );
  2437. }
  2438. }
  2439. }
  2440. // invoke event
  2441. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::%s", nd->exname, script_config.onsell_event_name);
  2442. npc_event(sd, npc_ev, 0);
  2443. return 0;
  2444. }
  2445. /// Player item selling to npc shop.
  2446. ///
  2447. /// @param item_list 'n' pairs <index,amount>
  2448. /// @return result code for clif_parse_NpcSellListSend
  2449. uint8 npc_selllist(map_session_data* sd, int list_length, PACKET_CZ_PC_SELL_ITEMLIST_sub* item_list)
  2450. {
  2451. double z;
  2452. int i,skill;
  2453. struct npc_data *nd;
  2454. nullpo_retr(1, sd);
  2455. nullpo_retr(1, item_list);
  2456. if( ( nd = npc_checknear(sd, map_id2bl(sd->npc_shopid)) ) == NULL || nd->subtype != NPCTYPE_SHOP )
  2457. {
  2458. return 1;
  2459. }
  2460. z = 0;
  2461. // verify the sell list
  2462. for( i = 0; i < list_length; i++ )
  2463. {
  2464. t_itemid nameid;
  2465. int amount, idx, value;
  2466. idx = item_list[i].index - 2;
  2467. amount = item_list[i].amount;
  2468. if( idx >= MAX_INVENTORY || idx < 0 || amount < 0 )
  2469. {
  2470. return 1;
  2471. }
  2472. nameid = sd->inventory.u.items_inventory[idx].nameid;
  2473. if( !nameid || !sd->inventory_data[idx] || sd->inventory.u.items_inventory[idx].amount < amount)
  2474. {
  2475. return 1;
  2476. }
  2477. if( nd->master_nd )
  2478. {// Script-controlled shops decide by themselves, what can be sold and at what price.
  2479. continue;
  2480. }
  2481. if (!pc_can_sell_item(sd, &sd->inventory.u.items_inventory[idx], nd->subtype)) {
  2482. return 1; // In official server, this illegal attempt the player will be disconnected
  2483. }
  2484. if (battle_config.rental_item_novalue && sd->inventory.u.items_inventory[idx].expire_time)
  2485. value = 0;
  2486. else
  2487. value = pc_modifysellvalue(sd, sd->inventory_data[idx]->value_sell);
  2488. z+= (double)value*amount;
  2489. }
  2490. if( nd->master_nd )
  2491. {// Script-controlled shops
  2492. return npc_selllist_sub(sd, list_length, item_list, nd->master_nd);
  2493. }
  2494. // delete items
  2495. for( i = 0; i < list_length; i++ )
  2496. {
  2497. int amount, idx;
  2498. idx = item_list[i].index - 2;
  2499. amount = item_list[i].amount;
  2500. // Forged packet, we do not care if he loses items
  2501. if( sd->inventory_data[idx] == nullptr ){
  2502. return 1;
  2503. }
  2504. if( sd->inventory_data[idx]->type == IT_PETEGG && sd->inventory.u.items_inventory[idx].card[0] == CARD0_PET )
  2505. {
  2506. if( pet_db_search(sd->inventory.u.items_inventory[idx].nameid, PET_EGG) )
  2507. {
  2508. intif_delete_petdata(MakeDWord(sd->inventory.u.items_inventory[idx].card[1], sd->inventory.u.items_inventory[idx].card[2]));
  2509. }
  2510. }
  2511. if (pc_delitem(sd, idx, amount, 0, 6, LOG_TYPE_NPC)) {
  2512. return 1;
  2513. }
  2514. }
  2515. if( z > MAX_ZENY )
  2516. z = MAX_ZENY;
  2517. pc_getzeny(sd, (int)z, LOG_TYPE_NPC, NULL);
  2518. // custom merchant shop exp bonus
  2519. if( battle_config.shop_exp > 0 && z > 0 && ( skill = pc_checkskill(sd,MC_OVERCHARGE) ) > 0)
  2520. {
  2521. uint16 sk_idx = skill_get_index(MC_OVERCHARGE);
  2522. if( sd->status.skill[sk_idx].flag >= SKILL_FLAG_REPLACED_LV_0 )
  2523. skill = sd->status.skill[sk_idx].flag - SKILL_FLAG_REPLACED_LV_0;
  2524. if( skill > 0 )
  2525. {
  2526. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  2527. if( z < 1 )
  2528. z = 1;
  2529. pc_gainexp(sd, NULL, 0, (int)z, 0);
  2530. }
  2531. }
  2532. return 0;
  2533. }
  2534. e_purchase_result npc_barter_purchase( map_session_data& sd, std::shared_ptr<s_npc_barter> barter, std::vector<s_barter_purchase>& purchases ){
  2535. uint64 requiredZeny = 0;
  2536. uint32 requiredWeight = 0;
  2537. uint32 reducedWeight = 0;
  2538. uint16 requiredSlots = 0;
  2539. uint32 requiredItems[MAX_INVENTORY] = { 0 };
  2540. for( s_barter_purchase& purchase : purchases ){
  2541. purchase.data = item_db.find( purchase.item->nameid ).get();
  2542. if( purchase.data == nullptr ){
  2543. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2544. }
  2545. uint32 amount = purchase.amount;
  2546. if( purchase.item->stockLimited && purchase.item->stock < amount ){
  2547. return e_purchase_result::PURCHASE_FAIL_STOCK_EMPTY;
  2548. }
  2549. char result = pc_checkadditem( &sd, purchase.item->nameid, amount );
  2550. if( result == CHKADDITEM_OVERAMOUNT ){
  2551. return e_purchase_result::PURCHASE_FAIL_COUNT;
  2552. }else if( result == CHKADDITEM_NEW ){
  2553. requiredSlots += purchase.data->inventorySlotNeeded( amount );
  2554. }
  2555. requiredZeny += ( purchase.item->price * amount );
  2556. requiredWeight += ( purchase.data->weight * amount );
  2557. for( const auto& requirementPair : purchase.item->requirements ){
  2558. std::shared_ptr<s_npc_barter_requirement> requirement = requirementPair.second;
  2559. std::shared_ptr<item_data> id = item_db.find(requirement->nameid);
  2560. if( id == nullptr ){
  2561. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2562. }
  2563. if( itemdb_isstackable2( id.get() ) ){
  2564. int j;
  2565. for( j = 0; j < MAX_INVENTORY; j++ ){
  2566. if( sd.inventory.u.items_inventory[j].nameid == requirement->nameid ){
  2567. // Equipped items are not taken into account
  2568. if( sd.inventory.u.items_inventory[j].equip != 0 ){
  2569. continue;
  2570. }
  2571. // Items in equip switch are not taken into account
  2572. if( sd.inventory.u.items_inventory[j].equipSwitch != 0 ){
  2573. continue;
  2574. }
  2575. // Server is configured to hide favorite items on selling
  2576. if( battle_config.hide_fav_sell && sd.inventory.u.items_inventory[j].favorite ){
  2577. continue;
  2578. }
  2579. // Actually stackable items should never be refinable, but who knows...
  2580. if( requirement->refine >= 0 && sd.inventory.u.items_inventory[j].refine != requirement->refine ){
  2581. // Refine does not match, continue with next item
  2582. continue;
  2583. }
  2584. // Found a match, accumulate required amount
  2585. requiredItems[j] += requirement->amount * amount;
  2586. // Check if there are still enough items available
  2587. if( requiredItems[j] > sd.inventory.u.items_inventory[j].amount ){
  2588. return e_purchase_result::PURCHASE_FAIL_GOODS;
  2589. }
  2590. // Cancel the loop
  2591. break;
  2592. }
  2593. }
  2594. // Required item not found
  2595. if( j == MAX_INVENTORY ){
  2596. return e_purchase_result::PURCHASE_FAIL_GOODS;
  2597. }
  2598. }else{
  2599. for( int i = 0; i < (requirement->amount * amount); i++ ){
  2600. int j;
  2601. for( j = 0; j < MAX_INVENTORY; j++ ){
  2602. if( sd.inventory.u.items_inventory[j].nameid == requirement->nameid ){
  2603. // Equipped items are not taken into account
  2604. if( sd.inventory.u.items_inventory[j].equip != 0 ){
  2605. continue;
  2606. }
  2607. // Items in equip switch are not taken into account
  2608. if( sd.inventory.u.items_inventory[j].equipSwitch != 0 ){
  2609. continue;
  2610. }
  2611. // Server is configured to hide favorite items on selling
  2612. if( battle_config.hide_fav_sell && sd.inventory.u.items_inventory[j].favorite ){
  2613. continue;
  2614. }
  2615. // If necessary, check if the refine rate matches
  2616. if( requirement->refine >= 0 && sd.inventory.u.items_inventory[j].refine != requirement->refine ){
  2617. // Refine does not match, continue with next item
  2618. continue;
  2619. }
  2620. // Found a match, since it is not stackable, check if it was already taken
  2621. if( requiredItems[j] > 0 ){
  2622. // Item was already taken, try to find another match
  2623. continue;
  2624. }
  2625. // Mark it as taken
  2626. requiredItems[j] = 1;
  2627. // Cancel the loop
  2628. break;
  2629. }
  2630. }
  2631. // Required item not found
  2632. if( j == MAX_INVENTORY ){
  2633. // Maybe the refine level did not match
  2634. if( requirement->refine >= 0 ){
  2635. int refine;
  2636. // Try to find a higher refine level, going from the next lowest to the highest possible
  2637. for( refine = requirement->refine + 1; refine <= MAX_REFINE; refine++ ){
  2638. for( j = 0; j < MAX_INVENTORY; j++ ){
  2639. if( sd.inventory.u.items_inventory[j].nameid == requirement->nameid ){
  2640. // Equipped items are not taken into account
  2641. if( sd.inventory.u.items_inventory[j].equip != 0 ){
  2642. continue;
  2643. }
  2644. // Items in equip switch are not taken into account
  2645. if( sd.inventory.u.items_inventory[j].equipSwitch != 0 ){
  2646. continue;
  2647. }
  2648. // Server is configured to hide favorite items on selling
  2649. if( battle_config.hide_fav_sell && sd.inventory.u.items_inventory[j].favorite ){
  2650. continue;
  2651. }
  2652. // If necessary, check if the refine rate matches
  2653. if( requirement->refine >= 0 && sd.inventory.u.items_inventory[j].refine != refine ){
  2654. // Refine does not match, continue with next item
  2655. continue;
  2656. }
  2657. // Found a match, since it is not stackable, check if it was already taken
  2658. if( requiredItems[j] > 0 ){
  2659. // Item was already taken, try to find another match
  2660. continue;
  2661. }
  2662. // Mark it as taken
  2663. requiredItems[j] = 1;
  2664. // Cancel the loop
  2665. break;
  2666. }
  2667. }
  2668. // If a match was found, make sure to cancel the loop
  2669. if( j < MAX_INVENTORY ){
  2670. // Cancel the loop
  2671. break;
  2672. }
  2673. }
  2674. // No matching entry found
  2675. if( refine > MAX_REFINE ){
  2676. return e_purchase_result::PURCHASE_FAIL_GOODS;
  2677. }
  2678. }else{
  2679. return e_purchase_result::PURCHASE_FAIL_GOODS;
  2680. }
  2681. }
  2682. }
  2683. }
  2684. reducedWeight += ( purchase.amount * requirement->amount * id->weight );
  2685. }
  2686. }
  2687. // Check if there is enough Zeny
  2688. if( sd.status.zeny < requiredZeny ){
  2689. return e_purchase_result::PURCHASE_FAIL_MONEY;
  2690. }
  2691. // Check if there is enough Weight Limit
  2692. if( ( sd.weight + requiredWeight - reducedWeight ) > sd.max_weight ){
  2693. return e_purchase_result::PURCHASE_FAIL_WEIGHT;
  2694. }
  2695. if( pc_inventoryblank( &sd ) < requiredSlots ){
  2696. return e_purchase_result::PURCHASE_FAIL_COUNT;
  2697. }
  2698. for( int i = 0; i < MAX_INVENTORY; i++ ){
  2699. if( requiredItems[i] > 0 ){
  2700. if( pc_delitem( &sd, i, requiredItems[i], 0, 0, LOG_TYPE_BARTER ) != 0 ){
  2701. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2702. }
  2703. }
  2704. }
  2705. if( pc_payzeny( &sd, (int)requiredZeny, LOG_TYPE_BARTER, nullptr ) != 0 ){
  2706. return e_purchase_result::PURCHASE_FAIL_MONEY;
  2707. }
  2708. for( s_barter_purchase& purchase : purchases ){
  2709. if( purchase.item->stockLimited ){
  2710. purchase.item->stock -= purchase.amount;
  2711. if( Sql_Query( mmysql_handle, "REPLACE INTO `%s` (`name`,`index`,`amount`) VALUES ( '%s', '%hu', '%hu' )", barter_table, barter->name.c_str(), purchase.item->index, purchase.item->stock ) != SQL_SUCCESS ){
  2712. Sql_ShowDebug( mmysql_handle );
  2713. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2714. }
  2715. }
  2716. if( itemdb_isstackable2( purchase.data ) ){
  2717. struct item it = {};
  2718. it.nameid = purchase.item->nameid;
  2719. it.identify = true;
  2720. if( pc_additem( &sd, &it, purchase.amount, LOG_TYPE_BARTER ) != ADDITEM_SUCCESS ){
  2721. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2722. }
  2723. }else{
  2724. if( purchase.data->type == IT_PETEGG ){
  2725. for( int i = 0; i < purchase.amount; i++ ){
  2726. if( !pet_create_egg( &sd, purchase.item->nameid ) ){
  2727. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2728. }
  2729. }
  2730. }else{
  2731. for( int i = 0; i < purchase.amount; i++ ){
  2732. struct item it = {};
  2733. it.nameid = purchase.item->nameid;
  2734. it.identify = true;
  2735. if( pc_additem( &sd, &it, 1, LOG_TYPE_BARTER ) != ADDITEM_SUCCESS ){
  2736. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2737. }
  2738. }
  2739. }
  2740. }
  2741. }
  2742. return e_purchase_result::PURCHASE_SUCCEED;
  2743. }
  2744. //Atempt to remove an npc from a map
  2745. //This doesn't remove it from map_db
  2746. int npc_remove_map(struct npc_data* nd)
  2747. {
  2748. int i;
  2749. nullpo_retr(1, nd);
  2750. if(nd->bl.prev == NULL || nd->bl.m < 0)
  2751. return 1; //Not assigned to a map.
  2752. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  2753. if (nd->subtype == NPCTYPE_SCRIPT)
  2754. skill_clear_unitgroup(&nd->bl);
  2755. clif_clearunit_area(&nd->bl,CLR_RESPAWN);
  2756. npc_unsetcells(nd);
  2757. map_delblock(&nd->bl);
  2758. //Remove npc from map[].npc list. [Skotlex]
  2759. ARR_FIND( 0, mapdata->npc_num, i, mapdata->npc[i] == nd );
  2760. if( i == mapdata->npc_num ) return 2; //failed to find it?
  2761. mapdata->npc_num--;
  2762. if (i >= mapdata->npc_num_area)
  2763. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num ];
  2764. else if (i >= mapdata->npc_num_warp) {
  2765. mapdata->npc_num_area--;
  2766. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num_area ];
  2767. mapdata->npc[ mapdata->npc_num_area ] = mapdata->npc[ mapdata->npc_num ];
  2768. }
  2769. else {
  2770. mapdata->npc_num_warp--;
  2771. mapdata->npc_num_area--;
  2772. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num_warp ];
  2773. mapdata->npc[ mapdata->npc_num_warp ] = mapdata->npc[ mapdata->npc_num_area ];
  2774. mapdata->npc[ mapdata->npc_num_area ] = mapdata->npc[ mapdata->npc_num ];
  2775. }
  2776. mapdata->npc[ mapdata->npc_num ] = NULL;
  2777. return 0;
  2778. }
  2779. /**
  2780. * @see DBApply
  2781. */
  2782. static int npc_unload_ev(DBKey key, DBData *data, va_list ap)
  2783. {
  2784. struct event_data* ev = (struct event_data*)db_data2ptr(data);
  2785. char* npcname = va_arg(ap, char *);
  2786. if(strcmp(ev->nd->exname,npcname)==0){
  2787. db_remove(ev_db, key);
  2788. return 1;
  2789. }
  2790. return 0;
  2791. }
  2792. //Chk if npc matches src_id, then unload.
  2793. //Sub-function used to find duplicates.
  2794. static int npc_unload_dup_sub(struct npc_data* nd, va_list args)
  2795. {
  2796. int src_id;
  2797. src_id = va_arg(args, int);
  2798. if (nd->src_id == src_id)
  2799. npc_unload(nd, true);
  2800. return 0;
  2801. }
  2802. //Removes all npcs that are duplicates of the passed one. [Skotlex]
  2803. void npc_unload_duplicates(struct npc_data* nd)
  2804. {
  2805. map_foreachnpc(npc_unload_dup_sub,nd->bl.id);
  2806. }
  2807. //Removes an npc from map and db.
  2808. //Single is to free name (for duplicates).
  2809. int npc_unload(struct npc_data* nd, bool single) {
  2810. nullpo_ret(nd);
  2811. status_change_clear(&nd->bl, 1);
  2812. npc_remove_map(nd);
  2813. map_deliddb(&nd->bl);
  2814. if( single )
  2815. strdb_remove(npcname_db, nd->exname);
  2816. if (nd->chat_id) // remove npc chatroom object and kick users
  2817. chat_deletenpcchat(nd);
  2818. #ifdef PCRE_SUPPORT
  2819. npc_chat_finalize(nd); // deallocate npc PCRE data structures
  2820. #endif
  2821. if( single && nd->path ) {
  2822. struct npc_path_data* npd = NULL;
  2823. if( nd->path ) {
  2824. npd = (struct npc_path_data*)strdb_get(npc_path_db, nd->path);
  2825. }
  2826. if( npd && --npd->references == 0 ) {
  2827. strdb_remove(npc_path_db, nd->path);/* remove from db */
  2828. aFree(nd->path);/* remove now that no other instances exist */
  2829. if (npd == npc_last_npd) {
  2830. npc_last_npd = NULL;
  2831. npc_last_ref = NULL;
  2832. npc_last_path = NULL;
  2833. }
  2834. }
  2835. }
  2836. if( single && nd->bl.m != -1 )
  2837. map_remove_questinfo(nd->bl.m, nd);
  2838. if( (nd->subtype == NPCTYPE_SHOP || nd->subtype == NPCTYPE_CASHSHOP || nd->subtype == NPCTYPE_ITEMSHOP || nd->subtype == NPCTYPE_POINTSHOP || nd->subtype == NPCTYPE_MARKETSHOP) && nd->src_id == 0) //src check for duplicate shops [Orcao]
  2839. aFree(nd->u.shop.shop_item);
  2840. else if( nd->subtype == NPCTYPE_SCRIPT ) {
  2841. struct s_mapiterator* iter;
  2842. struct block_list* bl;
  2843. if( single )
  2844. ev_db->foreach(ev_db,npc_unload_ev,nd->exname); //Clean up all events related
  2845. iter = mapit_geteachpc();
  2846. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) ) {
  2847. map_session_data *sd = ((TBL_PC*)bl);
  2848. if( sd && sd->npc_timer_id != INVALID_TIMER ) {
  2849. const struct TimerData *td = get_timer(sd->npc_timer_id);
  2850. if( td && td->id != nd->bl.id )
  2851. continue;
  2852. if( td && td->data )
  2853. ers_free(timer_event_ers, (void*)td->data);
  2854. delete_timer(sd->npc_timer_id, npc_timerevent);
  2855. sd->npc_timer_id = INVALID_TIMER;
  2856. }
  2857. }
  2858. mapit_free(iter);
  2859. if (nd->u.scr.timerid != INVALID_TIMER) {
  2860. const struct TimerData *td;
  2861. td = get_timer(nd->u.scr.timerid);
  2862. if (td && td->data)
  2863. ers_free(timer_event_ers, (void*)td->data);
  2864. delete_timer(nd->u.scr.timerid, npc_timerevent);
  2865. }
  2866. if (nd->u.scr.timer_event)
  2867. aFree(nd->u.scr.timer_event);
  2868. if (nd->src_id == 0) {
  2869. if(nd->u.scr.script) {
  2870. script_free_code(nd->u.scr.script);
  2871. nd->u.scr.script = NULL;
  2872. }
  2873. if (nd->u.scr.label_list) {
  2874. aFree(nd->u.scr.label_list);
  2875. nd->u.scr.label_list = NULL;
  2876. nd->u.scr.label_list_num = 0;
  2877. }
  2878. }
  2879. if( nd->u.scr.guild_id )
  2880. guild_flag_remove(nd);
  2881. if( nd->sc_display_count ){
  2882. unsigned char i;
  2883. for( i = 0; i < nd->sc_display_count; i++ )
  2884. ers_free(npc_sc_display_ers, nd->sc_display[i]);
  2885. nd->sc_display_count = 0;
  2886. aFree(nd->sc_display);
  2887. nd->sc_display = NULL;
  2888. }
  2889. }
  2890. nd->qi_data.clear();
  2891. script_stop_sleeptimers(nd->bl.id);
  2892. if( nd->dynamicnpc.removal_tid != INVALID_TIMER ){
  2893. delete_timer( nd->dynamicnpc.removal_tid, npc_dynamicnpc_removal_timer );
  2894. nd->dynamicnpc.removal_tid = INVALID_TIMER;
  2895. }
  2896. if( nd->dynamicnpc.owner_char_id != 0 ){
  2897. map_session_data* owner = map_charid2sd( nd->dynamicnpc.owner_char_id );
  2898. if( owner != nullptr ){
  2899. util::vector_erase_if_exists(owner->npc_id_dynamic, nd->bl.id);
  2900. }
  2901. }
  2902. aFree(nd);
  2903. return 0;
  2904. }
  2905. //
  2906. // NPC Source Files
  2907. //
  2908. /// Clears the npc source file list
  2909. static void npc_clearsrcfile(void)
  2910. {
  2911. struct npc_src_list* file = npc_src_files;
  2912. while( file != NULL ) {
  2913. struct npc_src_list* file_tofree = file;
  2914. file = file->next;
  2915. aFree(file_tofree);
  2916. }
  2917. npc_src_files = NULL;
  2918. }
  2919. /**
  2920. * Adds a npc source file (or removes all)
  2921. * @param name : file to add
  2922. * @param loadscript : flag to parse the script immediately after adding the src file
  2923. * @return 0=error, 1=sucess
  2924. */
  2925. int npc_addsrcfile(const char* name, bool loadscript)
  2926. {
  2927. struct npc_src_list* file;
  2928. struct npc_src_list* file_prev = NULL;
  2929. if( strcmpi(name, "clear") == 0 )
  2930. {
  2931. npc_clearsrcfile();
  2932. return 1;
  2933. }
  2934. //Check if this is not a file
  2935. if(check_filepath(name)!=2){
  2936. ShowError("npc_addsrcfile: Can't find source file \"%s\"\n", name );
  2937. return 0;
  2938. }
  2939. // prevent multiple insert of source files
  2940. file = npc_src_files;
  2941. while( file != NULL )
  2942. {
  2943. if( strcmp(name, file->name) == 0 )
  2944. return 0;// found the file, no need to insert it again
  2945. file_prev = file;
  2946. file = file->next;
  2947. }
  2948. file = (struct npc_src_list*)aMalloc(sizeof(struct npc_src_list) + strlen(name));
  2949. file->next = NULL;
  2950. safestrncpy(file->name, name, strlen(name) + 1);
  2951. if( file_prev == NULL )
  2952. npc_src_files = file;
  2953. else
  2954. file_prev->next = file;
  2955. if (loadscript)
  2956. return npc_parsesrcfile(file->name);
  2957. return 1;
  2958. }
  2959. /// Removes a npc source file (or all)
  2960. void npc_delsrcfile(const char* name)
  2961. {
  2962. struct npc_src_list* file = npc_src_files;
  2963. struct npc_src_list* file_prev = NULL;
  2964. if( strcmpi(name, "all") == 0 )
  2965. {
  2966. npc_clearsrcfile();
  2967. return;
  2968. }
  2969. while( file != NULL )
  2970. {
  2971. if( strcmp(file->name, name) == 0 )
  2972. {
  2973. if( npc_src_files == file )
  2974. npc_src_files = file->next;
  2975. else
  2976. file_prev->next = file->next;
  2977. aFree(file);
  2978. break;
  2979. }
  2980. file_prev = file;
  2981. file = file->next;
  2982. }
  2983. }
  2984. /// Parses and sets the name and exname of a npc.
  2985. /// Assumes that m, x and y are already set in nd.
  2986. static void npc_parsename(struct npc_data* nd, const char* name, const char* start, const char* buffer, const char* filepath)
  2987. {
  2988. const char* p;
  2989. struct npc_data* dnd;// duplicate npc
  2990. char newname[NPC_NAME_LENGTH+1];
  2991. // parse name
  2992. p = strstr(name,"::");
  2993. if( p ) { // <Display name>::<Unique name>
  2994. size_t len = p-name;
  2995. if( len > NPC_NAME_LENGTH ) {
  2996. ShowWarning("npc_parsename: Display name of '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  2997. safestrncpy(nd->name, name, sizeof(nd->name));
  2998. } else {
  2999. memcpy(nd->name, name, len);
  3000. memset(nd->name+len, 0, sizeof(nd->name)-len);
  3001. }
  3002. len = strlen(p+2);
  3003. if( len > NPC_NAME_LENGTH )
  3004. ShowWarning("npc_parsename: Unique name of '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  3005. safestrncpy(nd->exname, p+2, sizeof(nd->exname));
  3006. } else {// <Display name>
  3007. size_t len = strlen(name);
  3008. if( len > NPC_NAME_LENGTH )
  3009. ShowWarning("npc_parsename: Name '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  3010. safestrncpy(nd->name, name, sizeof(nd->name));
  3011. safestrncpy(nd->exname, name, sizeof(nd->exname));
  3012. }
  3013. if( *nd->exname == '\0' || strstr(nd->exname,"::") != NULL ) {// invalid
  3014. snprintf(newname, ARRAYLENGTH(newname), "0_%d_%d_%d", nd->bl.m, nd->bl.x, nd->bl.y);
  3015. ShowWarning("npc_parsename: Invalid unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  3016. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  3017. }
  3018. if( (dnd=npc_name2id(nd->exname)) != NULL ) {// duplicate unique name, generate new one
  3019. char this_mapname[MAP_NAME_LENGTH_EXT];
  3020. char other_mapname[MAP_NAME_LENGTH_EXT];
  3021. int i = 0;
  3022. do {
  3023. ++i;
  3024. snprintf(newname, ARRAYLENGTH(newname), "%d_%d_%d_%d", i, nd->bl.m, nd->bl.x, nd->bl.y);
  3025. } while( npc_name2id(newname) != NULL );
  3026. strcpy(this_mapname, (nd->bl.m==-1?"(not on a map)":mapindex_id2name(map_getmapdata(nd->bl.m)->index)));
  3027. strcpy(other_mapname, (dnd->bl.m==-1?"(not on a map)":mapindex_id2name(map_getmapdata(dnd->bl.m)->index)));
  3028. ShowWarning("npc_parsename: Duplicate unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  3029. ShowDebug("this npc:\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n", nd->name, nd->exname, this_mapname, nd->bl.x, nd->bl.y);
  3030. ShowDebug("other npc in '%s' :\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n",dnd->path, dnd->name, dnd->exname, other_mapname, dnd->bl.x, dnd->bl.y);
  3031. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  3032. }
  3033. if( npc_last_path != filepath ) {
  3034. struct npc_path_data * npd = NULL;
  3035. if( !(npd = (struct npc_path_data *)strdb_get(npc_path_db,filepath) ) ) {
  3036. CREATE(npd, struct npc_path_data, 1);
  3037. strdb_put(npc_path_db, filepath, npd);
  3038. CREATE(npd->path, char, strlen(filepath)+1);
  3039. safestrncpy(npd->path, filepath, strlen(filepath)+1);
  3040. npd->references = 0;
  3041. }
  3042. nd->path = npd->path;
  3043. npd->references++;
  3044. npc_last_npd = npd;
  3045. npc_last_ref = npd->path;
  3046. npc_last_path = (char*) filepath;
  3047. } else {
  3048. nd->path = npc_last_ref;
  3049. if( npc_last_npd )
  3050. npc_last_npd->references++;
  3051. }
  3052. }
  3053. /**
  3054. * Parses NPC view.
  3055. * Support for using Constants in place of NPC View IDs.
  3056. */
  3057. int npc_parseview(const char* w4, const char* start, const char* buffer, const char* filepath) {
  3058. int i = 0;
  3059. char viewid[1024]; // Max size of name from const.yml, see ConstantDatabase::parseBodyNode.
  3060. // Extract view ID / constant
  3061. while (w4[i] != '\0') {
  3062. if (ISSPACE(w4[i]) || w4[i] == '/' || w4[i] == ',')
  3063. break;
  3064. i++;
  3065. }
  3066. safestrncpy(viewid, w4, i+=1);
  3067. char *pid;
  3068. int val = strtol(viewid, &pid, 0);
  3069. // Check if view id is not an ID (only numbers).
  3070. if (pid != nullptr && *pid != '\0') {
  3071. int64 val_tmp;
  3072. // Check if constant exists and get its value.
  3073. if(!script_get_constant(viewid, &val_tmp)) {
  3074. std::shared_ptr<s_mob_db> mob = mobdb_search_aegisname(viewid);
  3075. if (mob != nullptr)
  3076. val = static_cast<int>(mob->id);
  3077. else {
  3078. ShowWarning("npc_parseview: Invalid NPC constant '%s' specified in file '%s', line'%d'. Defaulting to INVISIBLE. \n", viewid, filepath, strline(buffer,start-buffer));
  3079. val = JT_INVISIBLE;
  3080. }
  3081. } else
  3082. val = static_cast<int>(val_tmp);
  3083. }
  3084. return val;
  3085. }
  3086. /**
  3087. * Create a bare NPC object.
  3088. * @param m: Map ID
  3089. * @param x: X location
  3090. * @param y: Y location
  3091. * @return npc_data
  3092. */
  3093. struct npc_data *npc_create_npc(int16 m, int16 x, int16 y){
  3094. struct npc_data *nd = nullptr;
  3095. CREATE(nd, struct npc_data, 1);
  3096. new (nd) npc_data();
  3097. nd->bl.id = npc_get_new_npc_id();
  3098. nd->bl.prev = nd->bl.next = nullptr;
  3099. nd->bl.m = m;
  3100. nd->bl.x = x;
  3101. nd->bl.y = y;
  3102. nd->sc_display = nullptr;
  3103. nd->sc_display_count = 0;
  3104. nd->progressbar.timeout = 0;
  3105. nd->vd = npc_viewdb[0]; // Default to JT_INVISIBLE
  3106. nd->dynamicnpc.owner_char_id = 0;
  3107. nd->dynamicnpc.last_interaction = 0;
  3108. nd->dynamicnpc.removal_tid = INVALID_TIMER;
  3109. #ifdef MAP_GENERATOR
  3110. nd->navi.pos = {m, x, y};
  3111. nd->navi.id = 0;
  3112. nd->navi.npc = nd;
  3113. #endif
  3114. return nd;
  3115. }
  3116. /**
  3117. * Add then display an npc warp on map
  3118. * @param name : warp unique name
  3119. * @param from_mapid : mapid to warp from
  3120. * @param from_x : x coordinate of warp
  3121. * @param from_y : y coordinate of warp
  3122. * @param xs : x lenght of warp (for trigger activation)
  3123. * @param ys : y lenght of warp (for trigger activation)
  3124. * @param to_mapindex : mapid to warp to
  3125. * @param to_x : x coordinate to warp to
  3126. * @param to_y : y coordinate to warp to
  3127. * @return NULL:failed creation, npc_data* new warp
  3128. */
  3129. struct npc_data* npc_add_warp(char* name, short from_mapid, short from_x, short from_y, short xs, short ys, unsigned short to_mapindex, short to_x, short to_y)
  3130. {
  3131. int i, flag = 0;
  3132. struct npc_data *nd;
  3133. nd = npc_create_npc(from_mapid, from_x, from_y);
  3134. safestrncpy(nd->exname, name, ARRAYLENGTH(nd->exname));
  3135. if (npc_name2id(nd->exname) != NULL)
  3136. flag = 1;
  3137. if (flag == 1)
  3138. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp_%d_%d_%d", from_mapid, from_x, from_y);
  3139. for( i = 0; npc_name2id(nd->exname) != NULL; ++i )
  3140. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp%d_%d_%d_%d", i, from_mapid, from_x, from_y);
  3141. safestrncpy(nd->name, nd->exname, ARRAYLENGTH(nd->name));
  3142. if( battle_config.warp_point_debug )
  3143. nd->class_ = JT_GUILD_FLAG;
  3144. else
  3145. nd->class_ = JT_WARPNPC;
  3146. nd->speed = 200;
  3147. nd->u.warp.mapindex = to_mapindex;
  3148. nd->u.warp.x = to_x;
  3149. nd->u.warp.y = to_y;
  3150. nd->u.warp.xs = xs;
  3151. nd->u.warp.ys = ys;
  3152. nd->bl.type = BL_NPC;
  3153. nd->subtype = NPCTYPE_WARP;
  3154. nd->trigger_on_hidden = false;
  3155. map_addnpc(from_mapid, nd);
  3156. npc_setcells(nd);
  3157. if(map_addblock(&nd->bl))
  3158. return NULL;
  3159. status_set_viewdata(&nd->bl, nd->class_);
  3160. status_change_init(&nd->bl);
  3161. unit_dataset(&nd->bl);
  3162. if( map_getmapdata(nd->bl.m)->users )
  3163. clif_spawn(&nd->bl);
  3164. strdb_put(npcname_db, nd->exname, nd);
  3165. return nd;
  3166. }
  3167. /**
  3168. * Parses a warp npc.
  3169. * Line definition <from mapname>,<fromX>,<fromY>,<facing>%TAB%warp%TAB%<warp name>%TAB%<spanx>,<spany>,<to mapname>,<toX>,<toY>
  3170. * @param w1 : word 1 before tab (<from map name>,<fromX>,<fromY>,<facing>)
  3171. * @param w2 : word 2 before tab (warp), keyword that sent us in this parsing
  3172. * @param w3 : word 3 before tab (<warp name>)
  3173. * @param w4 : word 4 before tab (<spanx>,<spany>,<to mapname>,<toX>,<toY>)
  3174. * @param start : index to start parsing
  3175. * @param buffer : lines to parses
  3176. * @param filepath : filename with path wich we are parsing
  3177. * @return new index for next parsing
  3178. */
  3179. static const char* npc_parse_warp(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  3180. {
  3181. int m;
  3182. short x, y, xs, ys, to_x, to_y;
  3183. unsigned short i;
  3184. char mapname[MAP_NAME_LENGTH_EXT], to_mapname[MAP_NAME_LENGTH_EXT];
  3185. struct npc_data *nd;
  3186. // w1=<from map name>,<fromX>,<fromY>,<facing>
  3187. // w4=<spanx>,<spany>,<to map name>,<toX>,<toY>
  3188. if( sscanf(w1, "%15[^,],%6hd,%6hd", mapname, &x, &y) != 3
  3189. || sscanf(w4, "%6hd,%6hd,%15[^,],%6hd,%6hd", &xs, &ys, to_mapname, &to_x, &to_y) != 5 )
  3190. {
  3191. ShowError("npc_parse_warp: Invalid warp definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3192. return strchr(start,'\n');// skip and continue
  3193. }
  3194. m = map_mapname2mapid(mapname);
  3195. i = mapindex_name2id(to_mapname);
  3196. if( i == 0 )
  3197. {
  3198. ShowError("npc_parse_warp: Unknown destination map in file '%s', line '%d' : %s\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), to_mapname, w1, w2, w3, w4);
  3199. return strchr(start,'\n');// skip and continue
  3200. }
  3201. struct map_data *mapdata = map_getmapdata(m);
  3202. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  3203. ShowWarning("npc_parse_warp: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, mapdata->name, mapdata->xs, mapdata->ys,filepath,strline(buffer,start-buffer));
  3204. }
  3205. nd = npc_create_npc(m, x, y);
  3206. npc_parsename(nd, w3, start, buffer, filepath);
  3207. if (!battle_config.warp_point_debug)
  3208. nd->class_ = JT_WARPNPC;
  3209. else
  3210. nd->class_ = JT_GUILD_FLAG;
  3211. nd->speed = 200;
  3212. nd->u.warp.mapindex = i;
  3213. nd->u.warp.x = to_x;
  3214. nd->u.warp.y = to_y;
  3215. nd->u.warp.xs = xs;
  3216. nd->u.warp.ys = ys;
  3217. #ifdef MAP_GENERATOR
  3218. nd->navi.warp_dest = {map_mapindex2mapid(i), to_x, to_y};
  3219. #endif
  3220. npc_warp++;
  3221. nd->bl.type = BL_NPC;
  3222. nd->subtype = NPCTYPE_WARP;
  3223. if (strcasecmp("warp2", w2) == 0)
  3224. nd->trigger_on_hidden = true;
  3225. else
  3226. nd->trigger_on_hidden = false;
  3227. map_addnpc(m, nd);
  3228. npc_setcells(nd);
  3229. if(map_addblock(&nd->bl)) //couldn't add on map
  3230. return strchr(start,'\n');
  3231. status_set_viewdata(&nd->bl, nd->class_);
  3232. status_change_init(&nd->bl);
  3233. unit_dataset(&nd->bl);
  3234. if( map_getmapdata(nd->bl.m)->users )
  3235. clif_spawn(&nd->bl);
  3236. strdb_put(npcname_db, nd->exname, nd);
  3237. return strchr(start,'\n');// continue
  3238. }
  3239. /**
  3240. * Parses a shop/cashshop npc.
  3241. * Line definition :
  3242. * <map name>,<x>,<y>,<facing>%TAB%shop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>{,<itemid>:<price>...}
  3243. * <map name>,<x>,<y>,<facing>%TAB%cashshop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>{,<itemid>:<price>...}
  3244. * <map name>,<x>,<y>,<facing>%TAB%itemshop%TAB%<NPC Name>%TAB%<sprite id>,<costitemid>{:<discount>},<itemid>:<price>{,<itemid>:<price>...}
  3245. * <map name>,<x>,<y>,<facing>%TAB%pointshop%TAB%<NPC Name>%TAB%<sprite id>,<costvariable>{:<discount>},<itemid>:<price>{,<itemid>:<price>...}
  3246. * <map name>,<x>,<y>,<facing>%TAB%marketshop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>:<quantity>{,<itemid>:<price>:<quantity>...}
  3247. * @param w1 : word 1 before tab (<from map name>,<x>,<y>,<facing>)
  3248. * @param w2 : word 2 before tab (shop|cashshop|itemshop|pointshop|marketshop), keyword that sent us in this parsing
  3249. * @param w3 : word 3 before tab (<NPC Name>)
  3250. * @param w4 : word 4 before tab (<sprited id>,<shop definition...>)
  3251. * @param start : index to start parsing
  3252. * @param buffer : lines to parses
  3253. * @param filepath : filename with path wich we are parsing
  3254. * @return new index for next parsing
  3255. */
  3256. static const char* npc_parse_shop(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  3257. {
  3258. char *p, point_str[32];
  3259. int m, is_discount = 0;
  3260. uint16 dir;
  3261. short x, y;
  3262. t_itemid nameid = 0;
  3263. struct npc_data *nd;
  3264. enum npc_subtype type;
  3265. if( strcmp(w1,"-") == 0 )
  3266. {// 'floating' shop?
  3267. x = y = dir = 0;
  3268. m = -1;
  3269. }
  3270. else
  3271. {// w1=<map name>,<x>,<y>,<facing>
  3272. char mapname[MAP_NAME_LENGTH_EXT];
  3273. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4
  3274. || strchr(w4, ',') == NULL )
  3275. {
  3276. ShowError("npc_parse_shop: Invalid shop definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3277. return strchr(start,'\n');// skip and continue
  3278. }
  3279. m = map_mapname2mapid(mapname);
  3280. }
  3281. struct map_data *mapdata = map_getmapdata(m);
  3282. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  3283. ShowWarning("npc_parse_shop: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, mapdata->name, mapdata->xs, mapdata->ys,filepath,strline(buffer,start-buffer));
  3284. }
  3285. if( !strcasecmp(w2,"cashshop") )
  3286. type = NPCTYPE_CASHSHOP;
  3287. else if( !strcasecmp(w2,"itemshop") )
  3288. type = NPCTYPE_ITEMSHOP;
  3289. else if( !strcasecmp(w2,"pointshop") )
  3290. type = NPCTYPE_POINTSHOP;
  3291. else if( !strcasecmp(w2, "marketshop") )
  3292. type = NPCTYPE_MARKETSHOP;
  3293. else
  3294. type = NPCTYPE_SHOP;
  3295. p = strchr(w4,',');
  3296. memset(point_str,'\0',sizeof(point_str));
  3297. switch(type) {
  3298. case NPCTYPE_ITEMSHOP: {
  3299. if (sscanf(p,",%u:%11d,",&nameid,&is_discount) < 1) {
  3300. ShowError("npc_parse_shop: Invalid item cost definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3301. return strchr(start,'\n'); // skip and continue
  3302. }
  3303. if (!item_db.exists(nameid)) {
  3304. ShowWarning("npc_parse_shop: Invalid item ID cost in file '%s', line '%d' (id '%u').\n", filepath, strline(buffer,start-buffer), nameid);
  3305. return strchr(start,'\n'); // skip and continue
  3306. }
  3307. p = strchr(p+1,',');
  3308. break;
  3309. }
  3310. case NPCTYPE_POINTSHOP: {
  3311. if (sscanf(p, ",%32[^,:]:%11d,",point_str,&is_discount) < 1) {
  3312. ShowError("npc_parse_shop: Invalid item cost definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3313. return strchr(start,'\n'); // skip and continue
  3314. }
  3315. switch(point_str[0]) {
  3316. case '$':
  3317. case '.':
  3318. case '\'':
  3319. ShowWarning("npc_parse_shop: Invalid item cost variable type (must be permanent character or account based) in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3320. return strchr(start,'\n'); // skip and continue
  3321. break;
  3322. }
  3323. if (point_str[strlen(point_str) - 1] == '$') {
  3324. ShowWarning("npc_parse_shop: Invalid item cost variable type (must be integer) in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3325. return strchr(start,'\n'); // skip and continue
  3326. }
  3327. p = strchr(p+1,',');
  3328. break;
  3329. }
  3330. case NPCTYPE_MARKETSHOP:
  3331. #if PACKETVER < 20131223
  3332. ShowError("npc_parse_shop: (MARKETSHOP) Feature is disabled, need client 20131223 or newer. Ignoring file '%s', line '%d\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  3333. return strchr(start, '\n'); // skip and continue
  3334. #else
  3335. is_discount = 0;
  3336. break;
  3337. #endif
  3338. default:
  3339. if( sscanf( p, ",%32[^,:]:%11d,", point_str, &is_discount ) == 2 ){
  3340. is_discount = 1;
  3341. }else{
  3342. if( !strcasecmp( point_str, "yes" ) ){
  3343. is_discount = 1;
  3344. }else if( !strcasecmp( point_str, "no" ) ){
  3345. is_discount = 0;
  3346. }else{
  3347. ShowError( "npc_parse_shop: unknown discount setting %s\n", point_str );
  3348. return strchr( start, '\n' ); // skip and continue
  3349. }
  3350. p = strchr( p + 1, ',' );
  3351. }
  3352. break;
  3353. }
  3354. nd = npc_create_npc(m, x, y);
  3355. nd->u.shop.count = 0;
  3356. while ( p ) {
  3357. t_itemid nameid2;
  3358. int32 qty = -1;
  3359. int value;
  3360. bool skip = false;
  3361. if( p == NULL )
  3362. break;
  3363. switch(type) {
  3364. case NPCTYPE_MARKETSHOP:
  3365. #if PACKETVER >= 20131223
  3366. if (sscanf(p, ",%u:%11d:%11d", &nameid2, &value, &qty) != 3) {
  3367. ShowError("npc_parse_shop: (MARKETSHOP) Invalid item definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  3368. skip = true;
  3369. }
  3370. #endif
  3371. break;
  3372. default:
  3373. if (sscanf(p, ",%u:%11d", &nameid2, &value) != 2) {
  3374. ShowError("npc_parse_shop: Invalid item definition in file '%s', line '%d'. Ignoring the rest of the line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  3375. skip = true;
  3376. }
  3377. break;
  3378. }
  3379. if (skip)
  3380. break;
  3381. std::shared_ptr<item_data> id = item_db.find(nameid2);
  3382. if( id == nullptr ) {
  3383. ShowWarning("npc_parse_shop: Invalid sell item in file '%s', line '%d' (id '%u').\n", filepath, strline(buffer,start-buffer), nameid2);
  3384. p = strchr(p+1,',');
  3385. continue;
  3386. }
  3387. if( value < 0 ) {
  3388. if (type == NPCTYPE_SHOP || type == NPCTYPE_MARKETSHOP) value = id->value_buy;
  3389. else value = 0; // Cashshop doesn't have a "buy price" in the item_db
  3390. }
  3391. if (value == 0 && (type == NPCTYPE_SHOP || type == NPCTYPE_MARKETSHOP)) { // NPC selling items for free!
  3392. ShowWarning("npc_parse_shop: Item %s [%u] is being sold for FREE in file '%s', line '%d'.\n",
  3393. id->name.c_str(), nameid2, filepath, strline(buffer,start-buffer));
  3394. }
  3395. if( type == NPCTYPE_SHOP && value*0.75 < id->value_sell*1.24 ) { // Exploit possible: you can buy and sell back with profit
  3396. ShowWarning("npc_parse_shop: Item %s [%u] discounted buying price (%d->%d) is less than overcharged selling price (%d->%d) at file '%s', line '%d'.\n",
  3397. id->name.c_str(), nameid2, value, (int)(value*0.75), id->value_sell, (int)(id->value_sell*1.24), filepath, strline(buffer,start-buffer));
  3398. }
  3399. if (type == NPCTYPE_MARKETSHOP && qty < -1) {
  3400. ShowWarning("npc_parse_shop: Item %s [%u] is stocked with invalid value %hd, changed to unlimited (-1). File '%s', line '%d'.\n",
  3401. id->name.c_str(), nameid2, qty, filepath, strline(buffer,start-buffer));
  3402. qty = -1;
  3403. }
  3404. //for logs filters, atcommands and iteminfo script command
  3405. if( id->maxchance == 0 )
  3406. id->maxchance = -1; // -1 would show that the item's sold in NPC Shop
  3407. #if PACKETVER >= 20131223
  3408. if (nd->u.shop.count && type == NPCTYPE_MARKETSHOP) {
  3409. uint16 i;
  3410. // Duplicate entry? Replace the value
  3411. ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid);
  3412. if (i != nd->u.shop.count) {
  3413. nd->u.shop.shop_item[i].qty = qty;
  3414. nd->u.shop.shop_item[i].value = value;
  3415. p = strchr(p+1,',');
  3416. continue;
  3417. }
  3418. }
  3419. #endif
  3420. RECREATE(nd->u.shop.shop_item, struct npc_item_list,nd->u.shop.count+1);
  3421. nd->u.shop.shop_item[nd->u.shop.count].nameid = nameid2;
  3422. nd->u.shop.shop_item[nd->u.shop.count].value = value;
  3423. #if PACKETVER >= 20131223
  3424. nd->u.shop.shop_item[nd->u.shop.count].flag = 0;
  3425. if (type == NPCTYPE_MARKETSHOP )
  3426. nd->u.shop.shop_item[nd->u.shop.count].qty = qty;
  3427. #endif
  3428. nd->u.shop.count++;
  3429. p = strchr(p+1,',');
  3430. }
  3431. if( nd->u.shop.count == 0 ) {
  3432. ShowWarning("npc_parse_shop: Ignoring empty shop in file '%s', line '%d'.\n", filepath, strline(buffer,start-buffer));
  3433. aFree(nd);
  3434. return strchr(start,'\n');// continue
  3435. }
  3436. if( type == NPCTYPE_ITEMSHOP ){
  3437. // Item shop currency
  3438. nd->u.shop.itemshop_nameid = nameid;
  3439. }else if( type == NPCTYPE_POINTSHOP ){
  3440. // Point shop currency
  3441. safestrncpy( nd->u.shop.pointshop_str, point_str, strlen( point_str ) + 1 );
  3442. }
  3443. nd->u.shop.discount = is_discount > 0;
  3444. npc_parsename(nd, w3, start, buffer, filepath);
  3445. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  3446. nd->speed = 200;
  3447. ++npc_shop;
  3448. nd->bl.type = BL_NPC;
  3449. nd->subtype = type;
  3450. #if PACKETVER >= 20131223
  3451. // Insert market data to table
  3452. if (nd->subtype == NPCTYPE_MARKETSHOP) {
  3453. uint16 i;
  3454. for (i = 0; i < nd->u.shop.count; i++)
  3455. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[i]);
  3456. }
  3457. #endif
  3458. if( m >= 0 )
  3459. {// normal shop npc
  3460. map_addnpc(m,nd);
  3461. if(map_addblock(&nd->bl))
  3462. return strchr(start,'\n');
  3463. status_change_init(&nd->bl);
  3464. unit_dataset(&nd->bl);
  3465. nd->ud.dir = (uint8)dir;
  3466. if( nd->class_ != JT_FAKENPC ){
  3467. status_set_viewdata(&nd->bl, nd->class_);
  3468. if( map_getmapdata(nd->bl.m)->users )
  3469. clif_spawn(&nd->bl);
  3470. }
  3471. } else
  3472. {// 'floating' shop?
  3473. map_addiddb(&nd->bl);
  3474. }
  3475. strdb_put(npcname_db, nd->exname, nd);
  3476. return strchr(start,'\n');// continue
  3477. }
  3478. /** [Cydh]
  3479. * Check if the shop is affected by discount or not
  3480. * @param type Type of NPC shop (enum npc_subtype)
  3481. * @param discount Discount flag of NPC shop
  3482. * @return bool 'true' is discountable, 'false' otherwise
  3483. */
  3484. bool npc_shop_discount( struct npc_data* nd ){
  3485. switch( nd->subtype ){
  3486. case NPCTYPE_ITEMSHOP:
  3487. return nd->u.shop.discount || ( battle_config.discount_item_point_shop&1 );
  3488. case NPCTYPE_POINTSHOP:
  3489. return nd->u.shop.discount || ( battle_config.discount_item_point_shop&2 );
  3490. default:
  3491. return nd->u.shop.discount;
  3492. }
  3493. }
  3494. /**
  3495. * NPC other label
  3496. * Not sure, seem to add label in a chainlink
  3497. * @see DBApply
  3498. */
  3499. int npc_convertlabel_db(DBKey key, DBData *data, va_list ap)
  3500. {
  3501. const char* lname = (const char*)key.str;
  3502. int lpos = db_data2i(data);
  3503. struct npc_label_list** label_list;
  3504. int* label_list_num;
  3505. const char* filepath;
  3506. struct npc_label_list* label;
  3507. const char *p;
  3508. int len;
  3509. nullpo_ret(label_list = va_arg(ap,struct npc_label_list**));
  3510. nullpo_ret(label_list_num = va_arg(ap,int*));
  3511. nullpo_ret(filepath = va_arg(ap,const char*));
  3512. // In case of labels not terminated with ':', for user defined function support
  3513. p = lname;
  3514. while( ISALNUM(*p) || *p == '_' )
  3515. ++p;
  3516. len = p-lname;
  3517. // here we check if the label fit into the buffer
  3518. if( len > NAME_LENGTH )
  3519. {
  3520. ShowError("npc_parse_script: label name longer than %d chars! '%s'\n (%s)", NAME_LENGTH, lname, filepath);
  3521. return 0;
  3522. }
  3523. if( *label_list == NULL )
  3524. {
  3525. *label_list = (struct npc_label_list *) aCalloc (1, sizeof(struct npc_label_list));
  3526. *label_list_num = 0;
  3527. } else
  3528. *label_list = (struct npc_label_list *) aRealloc (*label_list, sizeof(struct npc_label_list)*(*label_list_num+1));
  3529. label = *label_list+*label_list_num;
  3530. safestrncpy(label->name, lname, sizeof(label->name));
  3531. label->pos = lpos;
  3532. ++(*label_list_num);
  3533. return 0;
  3534. }
  3535. // Skip the contents of a script.
  3536. static const char* npc_skip_script(const char* start, const char* buffer, const char* filepath)
  3537. {
  3538. const char* p;
  3539. int curly_count;
  3540. if( start == NULL )
  3541. return NULL;// nothing to skip
  3542. // initial bracket (assumes the previous part is ok)
  3543. p = strchr(start,'{');
  3544. if( p == NULL )
  3545. {
  3546. ShowError("npc_skip_script: Missing left curly in file '%s', line'%d'.", filepath, strline(buffer,start-buffer));
  3547. return NULL;// can't continue
  3548. }
  3549. // skip everything
  3550. for( curly_count = 1; curly_count > 0 ; )
  3551. {
  3552. p = skip_space(p+1) ;
  3553. if( *p == '}' )
  3554. {// right curly
  3555. --curly_count;
  3556. }
  3557. else if( *p == '{' )
  3558. {// left curly
  3559. ++curly_count;
  3560. }
  3561. else if( *p == '"' )
  3562. {// string
  3563. for( ++p; *p != '"' ; ++p )
  3564. {
  3565. if( *p == '\\' && (unsigned char)p[-1] <= 0x7e )
  3566. ++p;// escape sequence (not part of a multibyte character)
  3567. else if( *p == '\0' )
  3568. {
  3569. script_error(buffer, filepath, 0, "Unexpected end of string.", p);
  3570. return NULL;// can't continue
  3571. }
  3572. else if( *p == '\n' )
  3573. {
  3574. script_error(buffer, filepath, 0, "Unexpected newline at string.", p);
  3575. return NULL;// can't continue
  3576. }
  3577. }
  3578. }
  3579. else if( *p == '\0' )
  3580. {// end of buffer
  3581. ShowError("Missing %d right curlys at file '%s', line '%d'.\n", curly_count, filepath, strline(buffer,p-buffer));
  3582. return NULL;// can't continue
  3583. }
  3584. }
  3585. return p+1;// return after the last '}'
  3586. }
  3587. /**
  3588. * Parses a npc script.
  3589. * Line definition :
  3590. * <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,{<code>}
  3591. * <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>,{<code>} * @TODO missing cashshop line definition
  3592. * @param w1 : word 1 before tab (<from map name>,<x>,<y>,<facing>)
  3593. * @param w2 : word 2 before tab (script), keyword that sent us in this parsing
  3594. * @param w3 : word 3 before tab (<NPC Name>)
  3595. * @param w4 : word 4 before tab (<sprited id>,<code>)
  3596. * @param start : index to start parsing
  3597. * @param buffer : lines to parses
  3598. * @param filepath : filename with path wich we are parsing
  3599. * @return new index for next parsing
  3600. */
  3601. static const char* npc_parse_script(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath) {
  3602. int16 dir = 0;
  3603. short m, x, y, xs = 0, ys = 0; // [Valaris] thanks to fov
  3604. struct script_code *script;
  3605. int i;
  3606. const char* end;
  3607. const char* script_start;
  3608. struct npc_label_list* label_list;
  3609. int label_list_num;
  3610. struct npc_data* nd;
  3611. if( strcmp(w1, "-") == 0 )
  3612. {// floating npc
  3613. x = 0;
  3614. y = 0;
  3615. m = -1;
  3616. }
  3617. else
  3618. {// npc in a map
  3619. char mapname[MAP_NAME_LENGTH_EXT];
  3620. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4 )
  3621. {
  3622. ShowError("npc_parse_script: Invalid placement format for a script in file '%s', line '%d'. Skipping the rest of file...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3623. return NULL;// unknown format, don't continue
  3624. }
  3625. m = map_mapname2mapid(mapname);
  3626. }
  3627. script_start = strstr(start,",{");
  3628. end = strchr(start,'\n');
  3629. if( strstr(w4,",{") == NULL || script_start == NULL || (end != NULL && script_start > end) )
  3630. {
  3631. ShowError("npc_parse_script: Missing left curly ',{' in file '%s', line '%d'. Skipping the rest of the file.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3632. return NULL;// can't continue
  3633. }
  3634. ++script_start;
  3635. end = npc_skip_script(script_start, buffer, filepath);
  3636. if( end == NULL )
  3637. return NULL;// (simple) parse error, don't continue
  3638. script = parse_script(script_start, filepath, strline(buffer,script_start-buffer), SCRIPT_USE_LABEL_DB);
  3639. label_list = NULL;
  3640. label_list_num = 0;
  3641. if( script )
  3642. {
  3643. DBMap* label_db = script_get_label_db();
  3644. label_db->foreach(label_db, npc_convertlabel_db, &label_list, &label_list_num, filepath);
  3645. db_clear(label_db); // not needed anymore, so clear the db
  3646. }
  3647. nd = npc_create_npc(m, x, y);
  3648. if( sscanf(w4, "%*[^,],%6hd,%6hd", &xs, &ys) == 2 )
  3649. {// OnTouch area defined
  3650. nd->u.scr.xs = xs;
  3651. nd->u.scr.ys = ys;
  3652. }
  3653. else
  3654. {// no OnTouch area
  3655. nd->u.scr.xs = -1;
  3656. nd->u.scr.ys = -1;
  3657. }
  3658. npc_parsename(nd, w3, start, buffer, filepath);
  3659. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  3660. nd->speed = 200;
  3661. nd->u.scr.script = script;
  3662. nd->u.scr.label_list = label_list;
  3663. nd->u.scr.label_list_num = label_list_num;
  3664. ++npc_script;
  3665. nd->bl.type = BL_NPC;
  3666. nd->subtype = NPCTYPE_SCRIPT;
  3667. if( m >= 0 )
  3668. {
  3669. map_addnpc(m, nd);
  3670. status_change_init(&nd->bl);
  3671. unit_dataset(&nd->bl);
  3672. nd->ud.dir = (uint8)dir;
  3673. npc_setcells(nd);
  3674. if(map_addblock(&nd->bl))
  3675. return NULL;
  3676. if( nd->class_ != JT_FAKENPC )
  3677. {
  3678. status_set_viewdata(&nd->bl, nd->class_);
  3679. if( map_getmapdata(nd->bl.m)->users )
  3680. clif_spawn(&nd->bl);
  3681. }
  3682. }
  3683. else
  3684. {
  3685. // we skip map_addnpc, but still add it to the list of ID's
  3686. map_addiddb(&nd->bl);
  3687. }
  3688. strdb_put(npcname_db, nd->exname, nd);
  3689. //-----------------------------------------
  3690. // Loop through labels to export them as necessary
  3691. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  3692. if (npc_event_export(nd, i)) {
  3693. ShowWarning("npc_parse_script : duplicate event %s::%s (%s)\n",
  3694. nd->exname, nd->u.scr.label_list[i].name, filepath);
  3695. }
  3696. npc_timerevent_export(nd, i);
  3697. }
  3698. nd->u.scr.timerid = INVALID_TIMER;
  3699. return end;
  3700. }
  3701. /// Duplicate a warp, shop, cashshop or script. [Orcao]
  3702. /// warp: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<spanx>,<spany>
  3703. /// shop/cashshop/npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  3704. /// shop/cashshop/npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  3705. /// npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  3706. /// npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  3707. const char* npc_parse_duplicate( char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath, map_session_data* owner = nullptr ){
  3708. short x, y, m, xs = -1, ys = -1;
  3709. int16 dir;
  3710. char srcname[128];
  3711. int i;
  3712. const char* end;
  3713. size_t length;
  3714. int src_id;
  3715. int type;
  3716. struct npc_data* nd;
  3717. struct npc_data* dnd;
  3718. end = strchr(start,'\n');
  3719. length = strlen(w2);
  3720. // get the npc being duplicated
  3721. if( w2[length-1] != ')' || length <= 11 || length-11 >= sizeof(srcname) )
  3722. {// does not match 'duplicate(%127s)', name is empty or too long
  3723. ShowError("npc_parse_script: bad duplicate name in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), w2);
  3724. return end;// next line, try to continue
  3725. }
  3726. safestrncpy(srcname, w2+10, length-10);
  3727. dnd = npc_name2id(srcname);
  3728. if( dnd == NULL) {
  3729. ShowError("npc_parse_script: original npc not found for duplicate in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), srcname);
  3730. return end;// next line, try to continue
  3731. }
  3732. src_id = dnd->src_id ? dnd->src_id : dnd->bl.id;
  3733. type = dnd->subtype;
  3734. // get placement
  3735. if ((type == NPCTYPE_SHOP || type == NPCTYPE_CASHSHOP || type == NPCTYPE_ITEMSHOP || type == NPCTYPE_POINTSHOP || type == NPCTYPE_SCRIPT || type == NPCTYPE_MARKETSHOP) && strcmp(w1, "-") == 0) {// floating shop/chashshop/itemshop/pointshop/script
  3736. x = y = dir = 0;
  3737. m = -1;
  3738. } else {
  3739. char mapname[MAP_NAME_LENGTH_EXT];
  3740. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4 ) { // <map name>,<x>,<y>,<facing>
  3741. ShowError("npc_parse_duplicate: Invalid placement format for duplicate in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3742. return end;// next line, try to continue
  3743. }
  3744. m = map_mapname2mapid(mapname);
  3745. }
  3746. struct map_data *mapdata = map_getmapdata(m);
  3747. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  3748. ShowError("npc_parse_duplicate: coordinates %d/%d are out of bounds in map %s(%dx%d), in file '%s', line '%d'\n", x, y, mapdata->name, mapdata->xs, mapdata->ys,filepath,strline(buffer,start-buffer));
  3749. }
  3750. if( type == NPCTYPE_WARP && sscanf(w4, "%6hd,%6hd", &xs, &ys) == 2 );// <spanx>,<spany>
  3751. else if( type == NPCTYPE_SCRIPT && sscanf(w4, "%*[^,],%6hd,%6hd", &xs, &ys) == 2);// <sprite id>,<triggerX>,<triggerY>
  3752. else if( type == NPCTYPE_WARP ) {
  3753. ShowError("npc_parse_duplicate: Invalid span format for duplicate warp in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  3754. return end;// next line, try to continue
  3755. }
  3756. nd = npc_create_npc(m, x, y);
  3757. npc_parsename(nd, w3, start, buffer, filepath);
  3758. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  3759. nd->speed = 200;
  3760. nd->src_id = src_id;
  3761. nd->bl.type = BL_NPC;
  3762. nd->subtype = (enum npc_subtype)type;
  3763. if( owner != nullptr ){
  3764. nd->dynamicnpc.owner_char_id = owner->status.char_id;
  3765. owner->npc_id_dynamic.push_back(nd->bl.id);
  3766. }
  3767. switch( type ) {
  3768. case NPCTYPE_SCRIPT:
  3769. ++npc_script;
  3770. nd->u.scr.xs = xs;
  3771. nd->u.scr.ys = ys;
  3772. nd->u.scr.script = dnd->u.scr.script;
  3773. nd->u.scr.label_list = dnd->u.scr.label_list;
  3774. nd->u.scr.label_list_num = dnd->u.scr.label_list_num;
  3775. break;
  3776. case NPCTYPE_SHOP:
  3777. case NPCTYPE_CASHSHOP:
  3778. case NPCTYPE_ITEMSHOP:
  3779. case NPCTYPE_POINTSHOP:
  3780. case NPCTYPE_MARKETSHOP:
  3781. ++npc_shop;
  3782. safestrncpy( nd->u.shop.pointshop_str, dnd->u.shop.pointshop_str, strlen( dnd->u.shop.pointshop_str ) );
  3783. nd->u.shop.itemshop_nameid = dnd->u.shop.itemshop_nameid;
  3784. nd->u.shop.shop_item = dnd->u.shop.shop_item;
  3785. nd->u.shop.count = dnd->u.shop.count;
  3786. nd->u.shop.discount = dnd->u.shop.discount;
  3787. break;
  3788. case NPCTYPE_WARP:
  3789. ++npc_warp;
  3790. if( !battle_config.warp_point_debug )
  3791. nd->class_ = JT_WARPNPC;
  3792. else
  3793. nd->class_ = JT_GUILD_FLAG;
  3794. nd->u.warp.xs = xs;
  3795. nd->u.warp.ys = ys;
  3796. nd->u.warp.mapindex = dnd->u.warp.mapindex;
  3797. nd->u.warp.x = dnd->u.warp.x;
  3798. nd->u.warp.y = dnd->u.warp.y;
  3799. nd->trigger_on_hidden = dnd->trigger_on_hidden;
  3800. break;
  3801. }
  3802. //Add the npc to its location
  3803. if( m >= 0 ) {
  3804. map_addnpc(m, nd);
  3805. status_change_init(&nd->bl);
  3806. unit_dataset(&nd->bl);
  3807. nd->ud.dir = (uint8)dir;
  3808. npc_setcells(nd);
  3809. if(map_addblock(&nd->bl))
  3810. return end;
  3811. if( nd->class_ != JT_FAKENPC ) {
  3812. status_set_viewdata(&nd->bl, nd->class_);
  3813. if( map_getmapdata(nd->bl.m)->users )
  3814. clif_spawn(&nd->bl);
  3815. }
  3816. } else {
  3817. // we skip map_addnpc, but still add it to the list of ID's
  3818. map_addiddb(&nd->bl);
  3819. }
  3820. strdb_put(npcname_db, nd->exname, nd);
  3821. if( type != NPCTYPE_SCRIPT )
  3822. return end;
  3823. //-----------------------------------------
  3824. // Loop through labels to export them as necessary
  3825. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  3826. if (npc_event_export(nd, i)) {
  3827. ShowWarning("npc_parse_duplicate : duplicate event %s::%s (%s)\n",
  3828. nd->exname, nd->u.scr.label_list[i].name, filepath);
  3829. }
  3830. npc_timerevent_export(nd, i);
  3831. }
  3832. if(!strcmp(filepath,"INSTANCING")) //Instance NPCs will use this for commands
  3833. nd->instance_id = mapdata->instance_id;
  3834. nd->u.scr.timerid = INVALID_TIMER;
  3835. return end;
  3836. }
  3837. int npc_duplicate4instance(struct npc_data *snd, int16 m) {
  3838. char newname[NPC_NAME_LENGTH+1];
  3839. struct map_data *mapdata = map_getmapdata(m);
  3840. if( mapdata->instance_id <= 0 )
  3841. return 1;
  3842. snprintf(newname, ARRAYLENGTH(newname), "dup_%d_%d", mapdata->instance_id, snd->bl.id);
  3843. if( npc_name2id(newname) != NULL ) { // Name already in use
  3844. ShowError("npc_duplicate4instance: the npcname (%s) is already in use while trying to duplicate npc %s in instance %d.\n", newname, snd->exname, mapdata->instance_id);
  3845. return 1;
  3846. }
  3847. if( snd->subtype == NPCTYPE_WARP ) { // Adjust destination, if instanced
  3848. struct npc_data *wnd = NULL; // New NPC
  3849. std::shared_ptr<s_instance_data> idata = util::umap_find(instances, mapdata->instance_id);
  3850. int dm = map_mapindex2mapid(snd->u.warp.mapindex), imap = 0;
  3851. if( dm < 0 ) return 1;
  3852. for (const auto &it : idata->map) {
  3853. if (it.m && map_mapname2mapid(map_getmapdata(it.src_m)->name) == dm) {
  3854. imap = map_mapname2mapid(map_getmapdata(it.m)->name);
  3855. break; // Instance map matches destination, update to instance map
  3856. }
  3857. }
  3858. if(!imap)
  3859. imap = map_mapname2mapid(map_getmapdata(dm)->name);
  3860. if( imap == -1 ) {
  3861. ShowError("npc_duplicate4instance: warp (%s) leading to instanced map (%s), but instance map is not attached to current instance.\n", map_mapid2mapname(dm), snd->exname);
  3862. return 1;
  3863. }
  3864. wnd = npc_create_npc(m, snd->bl.x, snd->bl.y);
  3865. safestrncpy(wnd->name, "", ARRAYLENGTH(wnd->name));
  3866. safestrncpy(wnd->exname, newname, ARRAYLENGTH(wnd->exname));
  3867. wnd->class_ = JT_WARPNPC;
  3868. wnd->speed = 200;
  3869. wnd->u.warp.mapindex = map_id2index(imap);
  3870. wnd->u.warp.x = snd->u.warp.x;
  3871. wnd->u.warp.y = snd->u.warp.y;
  3872. wnd->u.warp.xs = snd->u.warp.xs;
  3873. wnd->u.warp.ys = snd->u.warp.ys;
  3874. wnd->bl.type = BL_NPC;
  3875. wnd->subtype = NPCTYPE_WARP;
  3876. wnd->trigger_on_hidden = snd->trigger_on_hidden;
  3877. wnd->src_id = snd->src_id ? snd->src_id : snd->bl.id;
  3878. map_addnpc(m, wnd);
  3879. npc_setcells(wnd);
  3880. if(map_addblock(&wnd->bl))
  3881. return 1;
  3882. status_set_viewdata(&wnd->bl, wnd->class_);
  3883. status_change_init(&wnd->bl);
  3884. unit_dataset(&wnd->bl);
  3885. if( map_getmapdata(wnd->bl.m)->users )
  3886. clif_spawn(&wnd->bl);
  3887. strdb_put(npcname_db, wnd->exname, wnd);
  3888. } else {
  3889. static char w1[128], w2[128], w3[128], w4[128];
  3890. const char* stat_buf = "- call from instancing subsystem -\n";
  3891. snprintf(w1, sizeof(w1), "%s,%d,%d,%d", mapdata->name, snd->bl.x, snd->bl.y, snd->ud.dir);
  3892. snprintf(w2, sizeof(w2), "duplicate(%s)", snd->exname);
  3893. snprintf(w3, sizeof(w3), "%s::%s", snd->name, newname);
  3894. if( snd->u.scr.xs >= 0 && snd->u.scr.ys >= 0 )
  3895. snprintf(w4, sizeof(w4), "%d,%d,%d", snd->class_, snd->u.scr.xs, snd->u.scr.ys); // Touch Area
  3896. else
  3897. snprintf(w4, sizeof(w4), "%d", snd->class_);
  3898. npc_parse_duplicate(w1, w2, w3, w4, stat_buf, stat_buf, "INSTANCING");
  3899. }
  3900. return 0;
  3901. }
  3902. int npc_instanceinit(struct npc_data* nd)
  3903. {
  3904. struct event_data *ev;
  3905. char evname[EVENT_NAME_LENGTH];
  3906. snprintf(evname, ARRAYLENGTH(evname), "%s::%s", nd->exname, script_config.instance_init_event_name);
  3907. if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) )
  3908. run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
  3909. return 0;
  3910. }
  3911. int npc_instancedestroy(struct npc_data* nd)
  3912. {
  3913. struct event_data *ev;
  3914. char evname[EVENT_NAME_LENGTH];
  3915. snprintf(evname, ARRAYLENGTH(evname), "%s::%s", nd->exname, script_config.instance_destroy_event_name);
  3916. if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) )
  3917. run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
  3918. return 0;
  3919. }
  3920. #if PACKETVER >= 20131223
  3921. /**
  3922. * Saves persistent NPC Market Data into SQL
  3923. * @param exname NPC exname
  3924. * @param nameid Item ID
  3925. * @param qty Stock
  3926. **/
  3927. void npc_market_tosql(const char *exname, struct npc_item_list *list) {
  3928. SqlStmt* stmt = SqlStmt_Malloc(mmysql_handle);
  3929. if (SQL_ERROR == SqlStmt_Prepare(stmt, "REPLACE INTO `%s` (`name`,`nameid`,`price`,`amount`,`flag`) VALUES ('%s','%u','%d','%d','%" PRIu8 "')",
  3930. market_table, exname, list->nameid, list->value, list->qty, list->flag) ||
  3931. SQL_ERROR == SqlStmt_Execute(stmt))
  3932. SqlStmt_ShowDebug(stmt);
  3933. SqlStmt_Free(stmt);
  3934. }
  3935. /**
  3936. * Removes persistent NPC Market Data from SQL
  3937. * @param exname NPC exname
  3938. * @param nameid Item ID
  3939. * @param clear True: will removes all records related with the NPC
  3940. **/
  3941. void npc_market_delfromsql_(const char *exname, t_itemid nameid, bool clear) {
  3942. SqlStmt* stmt = SqlStmt_Malloc(mmysql_handle);
  3943. if (clear) {
  3944. if( SQL_ERROR == SqlStmt_Prepare(stmt, "DELETE FROM `%s` WHERE `name`='%s'", market_table, exname) ||
  3945. SQL_ERROR == SqlStmt_Execute(stmt))
  3946. SqlStmt_ShowDebug(stmt);
  3947. } else {
  3948. if (SQL_ERROR == SqlStmt_Prepare(stmt, "DELETE FROM `%s` WHERE `name`='%s' AND `nameid`='%u' LIMIT 1", market_table, exname, nameid) ||
  3949. SQL_ERROR == SqlStmt_Execute(stmt))
  3950. SqlStmt_ShowDebug(stmt);
  3951. }
  3952. SqlStmt_Free(stmt);
  3953. }
  3954. /**
  3955. * Check NPC Market Shop for each entry
  3956. **/
  3957. static int npc_market_checkall_sub(DBKey key, DBData *data, va_list ap) {
  3958. struct s_npc_market *market = (struct s_npc_market *)db_data2ptr(data);
  3959. struct npc_data *nd = NULL;
  3960. uint16 i;
  3961. if (!market)
  3962. return 1;
  3963. nd = npc_name2id(market->exname);
  3964. if (!nd) {
  3965. ShowInfo("npc_market_checkall_sub: NPC '%s' not found, removing...\n", market->exname);
  3966. npc_market_clearfromsql(market->exname);
  3967. return 1;
  3968. }
  3969. else if (nd->subtype != NPCTYPE_MARKETSHOP || !nd->u.shop.shop_item || !nd->u.shop.count ) {
  3970. ShowError("npc_market_checkall_sub: NPC '%s' is not proper for market, removing...\n", nd->exname);
  3971. npc_market_clearfromsql(nd->exname);
  3972. return 1;
  3973. }
  3974. if (!market->count || !market->list)
  3975. return 1;
  3976. for (i = 0; i < market->count; i++) {
  3977. struct npc_item_list *list = &market->list[i];
  3978. uint16 j;
  3979. if (!item_db.exists(list->nameid)) {
  3980. ShowError("npc_market_checkall_sub: NPC '%s' sells invalid item '%u', deleting...\n", nd->exname, list->nameid);
  3981. npc_market_delfromsql(nd->exname, list->nameid);
  3982. continue;
  3983. }
  3984. // Reloading stock from `market` table
  3985. ARR_FIND(0, nd->u.shop.count, j, nd->u.shop.shop_item[j].nameid == list->nameid);
  3986. if (j != nd->u.shop.count) {
  3987. nd->u.shop.shop_item[j].value = list->value;
  3988. if (nd->u.shop.shop_item[j].qty > -1)
  3989. nd->u.shop.shop_item[j].qty = list->qty;
  3990. nd->u.shop.shop_item[j].flag = list->flag;
  3991. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[j]);
  3992. continue;
  3993. }
  3994. if (list->flag&1) { // Item added by npcshopitem/npcshopadditem, add new entry
  3995. RECREATE(nd->u.shop.shop_item, struct npc_item_list, nd->u.shop.count+1);
  3996. nd->u.shop.shop_item[j].nameid = list->nameid;
  3997. nd->u.shop.shop_item[j].value = list->value;
  3998. if (nd->u.shop.shop_item[j].qty > -1)
  3999. nd->u.shop.shop_item[j].qty = list->qty;
  4000. nd->u.shop.shop_item[j].flag = list->flag;
  4001. nd->u.shop.count++;
  4002. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[j]);
  4003. }
  4004. else { // Removing "out-of-date" entry
  4005. ShowError("npc_market_checkall_sub: NPC '%s' does not sell item %u (qty %d), deleting...\n", nd->exname, list->nameid, list->qty);
  4006. npc_market_delfromsql(nd->exname, list->nameid);
  4007. }
  4008. }
  4009. return 0;
  4010. }
  4011. /**
  4012. * Clear NPC market single entry
  4013. **/
  4014. static int npc_market_free(DBKey key, DBData *data, va_list ap) {
  4015. struct s_npc_market *market = (struct s_npc_market *)db_data2ptr(data);
  4016. if (!market)
  4017. return 0;
  4018. if (market->list) {
  4019. aFree(market->list);
  4020. market->list = NULL;
  4021. }
  4022. aFree(market);
  4023. return 1;
  4024. }
  4025. /**
  4026. * Check all existing NPC Market Shop after first loading map-server or after reloading scripts.
  4027. * Overwrite stocks from NPC by using stock entries from `market` table.
  4028. **/
  4029. static void npc_market_checkall(void) {
  4030. if (!db_size(NPCMarketDB))
  4031. return;
  4032. else {
  4033. ShowInfo("Checking '" CL_WHITE "%d" CL_RESET "' NPC Markets...\n", db_size(NPCMarketDB));
  4034. NPCMarketDB->foreach(NPCMarketDB, npc_market_checkall_sub);
  4035. ShowStatus("Done checking '" CL_WHITE "%d" CL_RESET "' NPC Markets.\n", db_size(NPCMarketDB));
  4036. NPCMarketDB->clear(NPCMarketDB, npc_market_free);
  4037. }
  4038. }
  4039. /**
  4040. * Loads persistent NPC Market Data from SQL, use the records after NPCs init'd to reuse the stock values.
  4041. **/
  4042. static void npc_market_fromsql(void) {
  4043. uint32 count = 0;
  4044. if (SQL_ERROR == Sql_Query(mmysql_handle, "SELECT `name`,`nameid`,`price`,`amount`,`flag` FROM `%s` ORDER BY `name`", market_table)) {
  4045. Sql_ShowDebug(mmysql_handle);
  4046. return;
  4047. }
  4048. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle)) {
  4049. char *data;
  4050. struct s_npc_market *market;
  4051. struct npc_item_list list;
  4052. Sql_GetData(mmysql_handle, 0, &data, NULL);
  4053. if (!(market = (struct s_npc_market *)strdb_get(NPCMarketDB,data))) {
  4054. CREATE(market, struct s_npc_market, 1);
  4055. market->count = 0;
  4056. safestrncpy(market->exname, data, NPC_NAME_LENGTH);
  4057. strdb_put(NPCMarketDB, market->exname, market);
  4058. }
  4059. Sql_GetData(mmysql_handle, 1, &data, NULL); list.nameid = strtoul(data, nullptr, 10);
  4060. Sql_GetData(mmysql_handle, 2, &data, NULL); list.value = atoi(data);
  4061. Sql_GetData(mmysql_handle, 3, &data, NULL); list.qty = atoi(data);
  4062. Sql_GetData(mmysql_handle, 4, &data, NULL); list.flag = atoi(data);
  4063. RECREATE(market->list, struct npc_item_list, market->count+1);
  4064. market->list[market->count++] = list;
  4065. count++;
  4066. }
  4067. Sql_FreeResult(mmysql_handle);
  4068. ShowStatus("Done loading '" CL_WHITE "%d" CL_RESET "' entries for '" CL_WHITE "%d" CL_RESET "' NPC Markets from '" CL_WHITE "%s" CL_RESET "' table.\n", count, db_size(NPCMarketDB), market_table);
  4069. }
  4070. #endif
  4071. //Set mapcell CELL_NPC to trigger event later
  4072. void npc_setcells(struct npc_data* nd)
  4073. {
  4074. int16 m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  4075. int i,j;
  4076. switch(nd->subtype)
  4077. {
  4078. case NPCTYPE_WARP:
  4079. xs = nd->u.warp.xs;
  4080. ys = nd->u.warp.ys;
  4081. break;
  4082. case NPCTYPE_SCRIPT:
  4083. xs = nd->u.scr.xs;
  4084. ys = nd->u.scr.ys;
  4085. break;
  4086. default:
  4087. return; // Other types doesn't have touch area
  4088. }
  4089. if (m < 0 || xs < 0 || ys < 0) //invalid range or map
  4090. return;
  4091. for (i = y-ys; i <= y+ys; i++) {
  4092. for (j = x-xs; j <= x+xs; j++) {
  4093. if (map_getcell(m, j, i, CELL_CHKNOPASS))
  4094. continue;
  4095. map_setcell(m, j, i, CELL_NPC, true);
  4096. }
  4097. }
  4098. }
  4099. int npc_unsetcells_sub(struct block_list* bl, va_list ap)
  4100. {
  4101. struct npc_data *nd = (struct npc_data*)bl;
  4102. int id = va_arg(ap,int);
  4103. if (nd->bl.id == id) return 0;
  4104. npc_setcells(nd);
  4105. return 1;
  4106. }
  4107. void npc_unsetcells(struct npc_data* nd)
  4108. {
  4109. int16 m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  4110. int i,j, x0, x1, y0, y1;
  4111. if (nd->subtype == NPCTYPE_WARP) {
  4112. xs = nd->u.warp.xs;
  4113. ys = nd->u.warp.ys;
  4114. } else {
  4115. xs = nd->u.scr.xs;
  4116. ys = nd->u.scr.ys;
  4117. }
  4118. if (m < 0 || xs < 0 || ys < 0)
  4119. return;
  4120. struct map_data *mapdata = map_getmapdata(m);
  4121. //Locate max range on which we can locate npc cells
  4122. //FIXME: does this really do what it's supposed to do? [ultramage]
  4123. for(x0 = x-xs; x0 > 0 && map_getcell(m, x0, y, CELL_CHKNPC); x0--);
  4124. for(x1 = x+xs; x1 < mapdata->xs-1 && map_getcell(m, x1, y, CELL_CHKNPC); x1++);
  4125. for(y0 = y-ys; y0 > 0 && map_getcell(m, x, y0, CELL_CHKNPC); y0--);
  4126. for(y1 = y+ys; y1 < mapdata->ys-1 && map_getcell(m, x, y1, CELL_CHKNPC); y1++);
  4127. //Erase this npc's cells
  4128. for (i = y-ys; i <= y+ys; i++)
  4129. for (j = x-xs; j <= x+xs; j++)
  4130. map_setcell(m, j, i, CELL_NPC, false);
  4131. //Re-deploy NPC cells for other nearby npcs.
  4132. map_foreachinallarea( npc_unsetcells_sub, m, x0, y0, x1, y1, BL_NPC, nd->bl.id );
  4133. }
  4134. bool npc_movenpc(struct npc_data* nd, int16 x, int16 y)
  4135. {
  4136. if (nd->bl.m < 0 || nd->bl.prev == NULL)
  4137. return false; //Not on a map.
  4138. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  4139. x = cap_value(x, 0, mapdata->xs-1);
  4140. y = cap_value(y, 0, mapdata->ys-1);
  4141. map_foreachinallrange(clif_outsight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  4142. map_moveblock(&nd->bl, x, y, gettick());
  4143. map_foreachinallrange(clif_insight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  4144. return true;
  4145. }
  4146. /// Changes the display name of the npc.
  4147. ///
  4148. /// @param nd Target npc
  4149. /// @param newname New display name
  4150. void npc_setdisplayname(struct npc_data* nd, const char* newname)
  4151. {
  4152. nullpo_retv(nd);
  4153. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  4154. safestrncpy(nd->name, newname, sizeof(nd->name));
  4155. if( mapdata && mapdata->users )
  4156. clif_name_area(&nd->bl);
  4157. }
  4158. /// Changes the display class of the npc.
  4159. ///
  4160. /// @param nd Target npc
  4161. /// @param class_ New display class
  4162. void npc_setclass(struct npc_data* nd, short class_)
  4163. {
  4164. nullpo_retv(nd);
  4165. if( nd->class_ == class_ )
  4166. return;
  4167. nd->class_ = class_;
  4168. status_set_viewdata(&nd->bl, class_);
  4169. unit_refresh(&nd->bl);
  4170. }
  4171. // @commands (script based)
  4172. int npc_do_atcmd_event(map_session_data* sd, const char* command, const char* message, const char* eventname)
  4173. {
  4174. struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
  4175. struct npc_data *nd;
  4176. struct script_state *st;
  4177. int i = 0, j = 0, k = 0;
  4178. char *temp;
  4179. nullpo_ret(sd);
  4180. if( ev == NULL || (nd = ev->nd) == NULL ) {
  4181. ShowError("npc_event: event not found [%s]\n", eventname);
  4182. return 0;
  4183. }
  4184. if( sd->npc_id != 0 ) { // Enqueue the event trigger.
  4185. int l;
  4186. ARR_FIND( 0, MAX_EVENTQUEUE, l, sd->eventqueue[l][0] == '\0' );
  4187. if( l < MAX_EVENTQUEUE ) {
  4188. safestrncpy(sd->eventqueue[l],eventname,EVENT_NAME_LENGTH); //Event enqueued.
  4189. return 0;
  4190. }
  4191. ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
  4192. return 1;
  4193. }
  4194. if( ev->nd->sc.option&OPTION_INVISIBLE ) { // Disabled npc, shouldn't trigger event.
  4195. npc_event_dequeue(sd);
  4196. return 2;
  4197. }
  4198. st = script_alloc_state(ev->nd->u.scr.script, ev->pos, sd->bl.id, ev->nd->bl.id);
  4199. setd_sub_str( st, NULL, ".@atcmd_command$", 0, command, NULL );
  4200. // split atcmd parameters based on spaces
  4201. temp = (char*)aMalloc(strlen(message) + 1);
  4202. for( i = 0; i < ( strlen( message ) + 1 ) && k < 127; i ++ ) {
  4203. if( message[i] == ' ' || message[i] == '\0' ) {
  4204. if (i > 0 && message[i - 1] == ' ') {
  4205. continue; // To prevent "@atcmd [space][space]" and .@atcmd_numparameters return 1 without any parameter.
  4206. }
  4207. temp[k] = '\0';
  4208. k = 0;
  4209. if( temp[0] != '\0' ) {
  4210. setd_sub_str( st, NULL, ".@atcmd_parameters$", j++, temp, NULL );
  4211. }
  4212. } else {
  4213. temp[k] = message[i];
  4214. k++;
  4215. }
  4216. }
  4217. setd_sub_num( st, NULL, ".@atcmd_numparameters", 0, j, NULL );
  4218. aFree(temp);
  4219. run_script_main(st);
  4220. return 0;
  4221. }
  4222. /// Parses a function.
  4223. /// function%TAB%script%TAB%<function name>%TAB%{<code>}
  4224. static const char* npc_parse_function(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  4225. {
  4226. DBMap* func_db;
  4227. DBData old_data;
  4228. struct script_code *script;
  4229. const char* end;
  4230. const char* script_start;
  4231. script_start = strstr(start,"\t{");
  4232. end = strchr(start,'\n');
  4233. if (*w4 != '{' || script_start == NULL || (end != NULL && script_start > end)) {
  4234. ShowError("npc_parse_function: Missing left curly '%%TAB%%{' in file '%s', line '%d'. Skipping the rest of the file.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  4235. return NULL;// can't continue
  4236. }
  4237. ++script_start;
  4238. end = npc_skip_script(script_start,buffer,filepath);
  4239. if( end == NULL )
  4240. return NULL;// (simple) parse error, don't continue
  4241. script = parse_script(script_start, filepath, strline(buffer,start-buffer), SCRIPT_RETURN_EMPTY_SCRIPT);
  4242. if( script == NULL )// parse error, continue
  4243. return end;
  4244. func_db = script_get_userfunc_db();
  4245. if (func_db->put(func_db, db_str2key(w3), db_ptr2data(script), &old_data)) {
  4246. struct script_code *oldscript = (struct script_code*)db_data2ptr(&old_data);
  4247. ShowInfo("npc_parse_function: Overwriting user function [%s] (%s:%d)\n", w3, filepath, strline(buffer,start-buffer));
  4248. script_stop_scriptinstances(oldscript);
  4249. script_free_vars(oldscript->local.vars);
  4250. aFree(oldscript->script_buf);
  4251. aFree(oldscript);
  4252. }
  4253. return end;
  4254. }
  4255. /*==========================================
  4256. * Parse Mob 1 - Parse mob list into each map
  4257. * Parse Mob 2 - Actually Spawns Mob
  4258. * [Wizputer]
  4259. *------------------------------------------*/
  4260. void npc_parse_mob2(struct spawn_data* mob)
  4261. {
  4262. int i;
  4263. for( i = mob->active; i < mob->num; ++i )
  4264. {
  4265. struct mob_data* md = mob_spawn_dataset(mob);
  4266. md->spawn = mob;
  4267. md->spawn->active++;
  4268. mob_spawn(md);
  4269. }
  4270. }
  4271. static const char* npc_parse_mob(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  4272. {
  4273. int num, mob_id, mob_lv = -1, delay = 5000, size = -1, w1count, w4count;
  4274. short m, x = 0, y = 0, xs = -1, ys = -1;
  4275. char mapname[MAP_NAME_LENGTH_EXT], mobname[NAME_LENGTH], sprite[NAME_LENGTH];
  4276. struct spawn_data mob, *data;
  4277. int ai = AI_NONE; // mob_ai
  4278. memset(&mob, 0, sizeof(struct spawn_data));
  4279. mob.state.boss = !strcmpi(w2,"boss_monster");
  4280. // w1=<map name>{,<x>,<y>,<xs>{,<ys>}}
  4281. // w3=<mob name>{,<mob level>}
  4282. // w4=<mob id>,<amount>{,<delay1>{,<delay2>{,<event>{,<mob size>{,<mob ai>}}}}}
  4283. if( ( w1count = sscanf(w1, "%15[^,],%6hd,%6hd,%6hd,%6hd", mapname, &x, &y, &xs, &ys) ) < 1
  4284. || sscanf(w3, "%23[^,],%11d", mobname, &mob_lv) < 1
  4285. || ( w4count = sscanf(w4, "%23[^,],%11d,%11u,%11u,%77[^,],%11d,%11d[^\t\r\n]", sprite, &num, &delay, &mob.delay2, mob.eventname, &size, &ai) ) < 2 )
  4286. {
  4287. ShowError("npc_parse_mob: Invalid mob definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  4288. return strchr(start,'\n');// skip and continue
  4289. }
  4290. if( mapindex_name2id(mapname) == 0 )
  4291. {
  4292. ShowError("npc_parse_mob: Unknown map '%s' in file '%s', line '%d'.\n", mapname, filepath, strline(buffer,start-buffer));
  4293. return strchr(start,'\n');// skip and continue
  4294. }
  4295. m = map_mapname2mapid(mapname);
  4296. if( m < 0 )//Not loaded on this map-server instance.
  4297. return strchr(start,'\n');// skip and continue
  4298. mob.m = (unsigned short)m;
  4299. struct map_data *mapdata = map_getmapdata(m);
  4300. if( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys )
  4301. {
  4302. ShowError("npc_parse_mob: Spawn coordinates out of range: %s (%d,%d), map size is (%d,%d) - %s %s (file '%s', line '%d').\n", mapdata->name, x, y, (mapdata->xs-1), (mapdata->ys-1), w1, w3, filepath, strline(buffer,start-buffer));
  4303. return strchr(start,'\n');// skip and continue
  4304. }
  4305. // Check if sprite is the mob name or ID
  4306. char *pid;
  4307. sprite[NAME_LENGTH-1] = '\0';
  4308. mob_id = strtol(sprite, &pid, 0);
  4309. if (pid != nullptr && *pid != '\0') {
  4310. std::shared_ptr<s_mob_db> mob = mobdb_search_aegisname(sprite);
  4311. if (mob == nullptr) {
  4312. ShowError("npc_parse_mob: Unknown mob name %s (file '%s', line '%d').\n", sprite, filepath, strline(buffer,start-buffer));
  4313. return strchr(start,'\n');// skip and continue
  4314. }
  4315. mob_id = mob->id;
  4316. }
  4317. else if (mobdb_checkid(mob_id) == 0) { // check monster ID if exists!
  4318. ShowError("npc_parse_mob: Unknown mob ID %d (file '%s', line '%d').\n", mob_id, filepath, strline(buffer,start-buffer));
  4319. return strchr(start,'\n');// skip and continue
  4320. }
  4321. if( num < 1 || num > 1000 )
  4322. {
  4323. ShowError("npc_parse_mob: Invalid number of monsters %d, must be inside the range [1,1000] (file '%s', line '%d').\n", num, filepath, strline(buffer,start-buffer));
  4324. return strchr(start,'\n');// skip and continue
  4325. }
  4326. if (w4count > 2 && delay != 5000 && delay < battle_config.mob_respawn_time) {
  4327. ShowWarning("npc_parse_mob: Invalid delay %u for mob ID %d (file '%s', line '%d'), defaulting to 5 seconds.\n", delay, mob_id, filepath, strline(buffer, start - buffer));
  4328. mob.delay1 = 5000;
  4329. } else
  4330. mob.delay1 = delay;
  4331. if( mob.state.size > SZ_BIG && size != -1 )
  4332. {
  4333. ShowError("npc_parse_mob: Invalid size number %d for mob ID %d (file '%s', line '%d').\n", mob.state.size, mob_id, filepath, strline(buffer, start - buffer));
  4334. return strchr(start, '\n');
  4335. }
  4336. if( (mob.state.ai < AI_NONE || mob.state.ai >= AI_MAX) && ai != -1 )
  4337. {
  4338. ShowError("npc_parse_mob: Invalid ai %d for mob ID %d (file '%s', line '%d').\n", mob.state.ai, mob_id, filepath, strline(buffer, start - buffer));
  4339. return strchr(start, '\n');
  4340. }
  4341. if( (mob_lv == 0 || mob_lv > MAX_LEVEL) && mob_lv != -1 )
  4342. {
  4343. ShowError("npc_parse_mob: Invalid level %d for mob ID %d (file '%s', line '%d').\n", mob_lv, mob_id, filepath, strline(buffer, start - buffer));
  4344. return strchr(start, '\n');
  4345. }
  4346. mob.num = (unsigned short)num;
  4347. mob.active = 0;
  4348. mob.id = (short) mob_id;
  4349. mob.x = (unsigned short)x;
  4350. mob.y = (unsigned short)y;
  4351. mob.xs = (signed short)xs;
  4352. mob.ys = (signed short)ys;
  4353. if (mob_lv > 0 && mob_lv <= MAX_LEVEL)
  4354. mob.level = mob_lv;
  4355. if (size > SZ_SMALL && size <= SZ_BIG)
  4356. mob.state.size = size;
  4357. if (ai > AI_NONE && ai <= AI_MAX)
  4358. mob.state.ai = static_cast<enum mob_ai>(ai);
  4359. if (mob.xs < 0) {
  4360. if (w1count > 3) {
  4361. ShowWarning("npc_parse_mob: Negative x-span %hd for mob ID %d (file '%s', line '%d').\n", mob.xs, mob_id, filepath, strline(buffer, start - buffer));
  4362. }
  4363. mob.xs = 0;
  4364. }
  4365. if (mob.ys < 0) {
  4366. if (w1count > 4) {
  4367. ShowWarning("npc_parse_mob: Negative y-span %hd for mob ID %d (file '%s', line '%d').\n", mob.ys, mob_id, filepath, strline(buffer, start - buffer));
  4368. }
  4369. mob.ys = 0;
  4370. }
  4371. if (mob.num > 1 && battle_config.mob_count_rate != 100) {
  4372. if ((mob.num = mob.num * battle_config.mob_count_rate / 100) < 1)
  4373. mob.num = 1;
  4374. }
  4375. if (battle_config.force_random_spawn || (mob.x == 0 && mob.y == 0))
  4376. { //Force a random spawn anywhere on the map.
  4377. mob.x = mob.y = 0;
  4378. mob.xs = mob.ys = -1;
  4379. }
  4380. // Check if monsters should have variance applied to their respawn time
  4381. if( ( ( battle_config.mob_spawn_variance & 1 ) == 0 && mob.state.boss ) || ( ( battle_config.mob_spawn_variance & 2 ) == 0 && !mob.state.boss ) ){
  4382. // Remove the variance
  4383. mob.delay2 = 0;
  4384. }
  4385. if(mob.delay1>0xfffffff || mob.delay2>0xfffffff) {
  4386. ShowError("npc_parse_mob: Invalid spawn delays %u %u (file '%s', line '%d').\n", mob.delay1, mob.delay2, filepath, strline(buffer,start-buffer));
  4387. return strchr(start,'\n');// skip and continue
  4388. }
  4389. //Use db names instead of the spawn file ones.
  4390. if(battle_config.override_mob_names==1)
  4391. strcpy(mob.name,"--en--");
  4392. else if (battle_config.override_mob_names==2)
  4393. strcpy(mob.name,"--ja--");
  4394. else
  4395. safestrncpy(mob.name, mobname, sizeof(mob.name));
  4396. //Verify dataset.
  4397. if( !mob_parse_dataset(&mob) )
  4398. {
  4399. ShowError("npc_parse_mob: Invalid dataset for monster ID %d (file '%s', line '%d').\n", mob_id, filepath, strline(buffer,start-buffer));
  4400. return strchr(start,'\n');// skip and continue
  4401. }
  4402. //Update mob spawn lookup database
  4403. struct spawn_info spawn = { mapdata->index, mob.num };
  4404. mob_add_spawn(mob_id, spawn);
  4405. //Now that all has been validated. We allocate the actual memory that the re-spawn data will use.
  4406. data = (struct spawn_data*)aMalloc(sizeof(struct spawn_data));
  4407. memcpy(data, &mob, sizeof(struct spawn_data));
  4408. // spawn / cache the new mobs
  4409. if( battle_config.dynamic_mobs && map_addmobtolist(data->m, data) >= 0 )
  4410. {
  4411. data->state.dynamic = true;
  4412. npc_cache_mob += data->num;
  4413. // check if target map has players
  4414. // (usually shouldn't occur when map server is just starting,
  4415. // but not the case when we do @reloadscript
  4416. if( map_getmapdata(data->m)->users > 0 )
  4417. npc_parse_mob2(data);
  4418. }
  4419. else
  4420. {
  4421. data->state.dynamic = false;
  4422. npc_parse_mob2(data);
  4423. npc_delay_mob += data->num;
  4424. }
  4425. npc_mob++;
  4426. return strchr(start,'\n');// continue
  4427. }
  4428. /*==========================================
  4429. * Set or disable mapflag on map
  4430. * eg : bat_c01 mapflag battleground 2
  4431. * also chking if mapflag conflict with another
  4432. *------------------------------------------*/
  4433. static const char* npc_parse_mapflag(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  4434. {
  4435. int16 m;
  4436. char mapname[MAP_NAME_LENGTH_EXT];
  4437. bool state = true;
  4438. enum e_mapflag mapflag;
  4439. // w1=<mapname>
  4440. if (sscanf(w1, "%15[^,]", mapname) != 1) {
  4441. ShowError("npc_parse_mapflag: Invalid mapflag definition in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  4442. return strchr(start,'\n');// skip and continue
  4443. }
  4444. m = map_mapname2mapid(mapname);
  4445. if (m < 0) {
  4446. ShowWarning("npc_parse_mapflag: Unknown map '%s' in file '%s', line '%d'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", mapname, filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  4447. return strchr(start,'\n');// skip and continue
  4448. }
  4449. if (w4 && !strcmpi(w4, "off"))
  4450. state = false; //Disable mapflag rather than enable it. [Skotlex]
  4451. mapflag = map_getmapflag_by_name(w3);
  4452. switch( mapflag ){
  4453. case MF_INVALID:
  4454. ShowError("npc_parse_mapflag: unrecognized mapflag '%s' (file '%s', line '%d').\n", w3, filepath, strline(buffer,start-buffer));
  4455. break;
  4456. case MF_NOSAVE: {
  4457. char savemap[MAP_NAME_LENGTH_EXT];
  4458. union u_mapflag_args args = {};
  4459. if (state && !strcmpi(w4, "SavePoint")) {
  4460. args.nosave.map = 0;
  4461. args.nosave.x = -1;
  4462. args.nosave.y = -1;
  4463. } else if (state && sscanf(w4, "%15[^,],%6hd,%6hd", savemap, &args.nosave.x, &args.nosave.y) == 3) {
  4464. args.nosave.map = mapindex_name2id(savemap);
  4465. if (!args.nosave.map) {
  4466. ShowWarning("npc_parse_mapflag: Specified save point map '%s' for mapflag 'nosave' not found (file '%s', line '%d'), using 'SavePoint'.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", savemap, filepath, strline(buffer,start-buffer), w1, w2, w3, w4);
  4467. args.nosave.x = -1;
  4468. args.nosave.y = -1;
  4469. }
  4470. }
  4471. map_setmapflag_sub(m, MF_NOSAVE, state, &args);
  4472. break;
  4473. }
  4474. case MF_PVP_NIGHTMAREDROP: {
  4475. char drop_arg1[16], drop_arg2[16];
  4476. union u_mapflag_args args = {};
  4477. if (sscanf(w4, "%15[^,],%15[^,],%11d", drop_arg1, drop_arg2, &args.nightmaredrop.drop_per) == 3) {
  4478. if (!strcmpi(drop_arg1, "random"))
  4479. args.nightmaredrop.drop_id = -1;
  4480. else if (!item_db.exists((args.nightmaredrop.drop_id = strtol(drop_arg1, nullptr, 10)))) {
  4481. args.nightmaredrop.drop_id = 0;
  4482. ShowWarning("npc_parse_mapflag: Invalid item ID '%d' supplied for mapflag 'pvp_nightmaredrop' (file '%s', line '%d'), removing.\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", args.nightmaredrop.drop_id, filepath, strline(buffer, start - buffer), w1, w2, w3, w4);
  4483. break;
  4484. }
  4485. if (!strcmpi(drop_arg2, "inventory"))
  4486. args.nightmaredrop.drop_type = NMDT_INVENTORY;
  4487. else if (!strcmpi(drop_arg2, "equip"))
  4488. args.nightmaredrop.drop_type = NMDT_EQUIP;
  4489. else if (!strcmpi(drop_arg2, "all"))
  4490. args.nightmaredrop.drop_type = NMDT_ALL;
  4491. if (args.nightmaredrop.drop_id != 0)
  4492. map_setmapflag_sub(m, MF_PVP_NIGHTMAREDROP, true, &args);
  4493. } else if (!state)
  4494. map_setmapflag(m, MF_PVP_NIGHTMAREDROP, false);
  4495. break;
  4496. }
  4497. case MF_BATTLEGROUND:
  4498. if (state) {
  4499. union u_mapflag_args args = {};
  4500. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  4501. args.flag_val = 1; // Default value
  4502. map_setmapflag_sub(m, MF_BATTLEGROUND, true, &args);
  4503. } else
  4504. map_setmapflag(m, MF_BATTLEGROUND, false);
  4505. break;
  4506. case MF_NOCOMMAND:
  4507. if (state) {
  4508. union u_mapflag_args args = {};
  4509. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  4510. args.flag_val = 100; // No level specified, block everyone.
  4511. map_setmapflag_sub(m, MF_NOCOMMAND, true, &args);
  4512. } else
  4513. map_setmapflag(m, MF_NOCOMMAND, false);
  4514. break;
  4515. case MF_RESTRICTED:
  4516. if (state) {
  4517. union u_mapflag_args args = {};
  4518. if (sscanf(w4, "%11d", &args.flag_val) == 1)
  4519. map_setmapflag_sub(m, MF_RESTRICTED, true, &args);
  4520. else // Could not be read, no value defined; don't remove as other restrictions may be set on the map
  4521. ShowWarning("npc_parse_mapflag: Zone value not set for the restricted mapflag! Skipped flag from %s (file '%s', line '%d').\n", map_mapid2mapname(m), filepath, strline(buffer,start-buffer));
  4522. } else
  4523. map_setmapflag(m, MF_RESTRICTED, false);
  4524. break;
  4525. case MF_JEXP:
  4526. case MF_BEXP: {
  4527. union u_mapflag_args args = {};
  4528. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  4529. args.flag_val = 0;
  4530. map_setmapflag_sub(m, mapflag, state, &args);
  4531. }
  4532. break;
  4533. case MF_SKILL_DAMAGE: {
  4534. char skill_name[SKILL_NAME_LENGTH];
  4535. char caster_constant[NAME_LENGTH];
  4536. union u_mapflag_args args = {};
  4537. memset(skill_name, 0, sizeof(skill_name));
  4538. if (!state)
  4539. map_setmapflag_sub(m, MF_SKILL_DAMAGE, false, &args);
  4540. else {
  4541. if (sscanf(w4, "%30[^,],%23[^,],%11d,%11d,%11d,%11d[^\n]", skill_name, caster_constant, &args.skill_damage.rate[SKILLDMG_PC], &args.skill_damage.rate[SKILLDMG_MOB], &args.skill_damage.rate[SKILLDMG_BOSS], &args.skill_damage.rate[SKILLDMG_OTHER]) >= 3) {
  4542. if (ISDIGIT(caster_constant[0]))
  4543. args.skill_damage.caster = atoi(caster_constant);
  4544. else {
  4545. int64 val_tmp;
  4546. if (!script_get_constant(caster_constant, &val_tmp)) {
  4547. ShowError( "npc_parse_mapflag: Unknown constant '%s'. Skipping (file '%s', line '%d').\n", caster_constant, filepath, strline(buffer, start - buffer) );
  4548. break;
  4549. }
  4550. args.skill_damage.caster = static_cast<uint16>(val_tmp);
  4551. }
  4552. if (args.skill_damage.caster == 0)
  4553. args.skill_damage.caster = BL_ALL;
  4554. for (int i = SKILLDMG_PC; i < SKILLDMG_MAX; i++)
  4555. args.skill_damage.rate[i] = cap_value(args.skill_damage.rate[i], -100, 100000);
  4556. trim(skill_name);
  4557. if (strcmp(skill_name, "all") == 0) // Adjust damage for all skills
  4558. map_setmapflag_sub(m, MF_SKILL_DAMAGE, true, &args);
  4559. else if (skill_name2id(skill_name) <= 0)
  4560. ShowWarning("npc_parse_mapflag: Invalid skill name '%s' for Skill Damage mapflag. Skipping (file '%s', line '%d').\n", skill_name, filepath, strline(buffer, start - buffer));
  4561. else { // Adjusted damage for specified skill
  4562. args.flag_val = 1;
  4563. map_setmapflag_sub(m, MF_SKILL_DAMAGE, true, &args);
  4564. map_skill_damage_add(map_getmapdata(m), skill_name2id(skill_name), &args);
  4565. }
  4566. }
  4567. }
  4568. break;
  4569. }
  4570. case MF_SKILL_DURATION: {
  4571. union u_mapflag_args args = {};
  4572. if (!state)
  4573. map_setmapflag_sub(m, MF_SKILL_DURATION, false, &args);
  4574. else {
  4575. char skill_name[SKILL_NAME_LENGTH];
  4576. if (sscanf(w4, "%30[^,],%5hu[^\n]", skill_name, &args.skill_duration.per) == 2) {
  4577. args.skill_duration.skill_id = skill_name2id(skill_name);
  4578. if (!args.skill_duration.skill_id)
  4579. ShowError("npc_parse_mapflag: skill_duration: Invalid skill name '%s' for Skill Duration mapflag. Skipping (file '%s', line '%d')\n", skill_name, filepath, strline(buffer, start - buffer));
  4580. else {
  4581. args.skill_duration.per = cap_value(args.skill_duration.per, 0, UINT16_MAX);
  4582. map_setmapflag_sub(m, MF_SKILL_DURATION, true, &args);
  4583. }
  4584. }
  4585. }
  4586. break;
  4587. }
  4588. // All others do not need special treatment
  4589. default:
  4590. map_setmapflag(m, mapflag, state);
  4591. break;
  4592. }
  4593. return strchr(start,'\n');// continue
  4594. }
  4595. /**
  4596. * Read file and create npc/func/mapflag/monster... accordingly.
  4597. * @param filepath : Relative path of file from map-serv bin
  4598. * @param runOnInit : should we exec OnInit when it's done ?
  4599. * @return 0:error, 1:success
  4600. */
  4601. int npc_parsesrcfile(const char* filepath)
  4602. {
  4603. int16 m, x, y;
  4604. int lines = 0;
  4605. FILE* fp;
  4606. size_t len;
  4607. char* buffer;
  4608. const char* p;
  4609. if(check_filepath(filepath)!=2) { //this is not a file
  4610. ShowDebug("npc_parsesrcfile: Path doesn't seem to be a file skipping it : '%s'.\n", filepath);
  4611. return 0;
  4612. }
  4613. // read whole file to buffer
  4614. fp = fopen(filepath, "rb");
  4615. if( fp == NULL )
  4616. {
  4617. ShowError("npc_parsesrcfile: File not found '%s'.\n", filepath);
  4618. return 0;
  4619. }
  4620. fseek(fp, 0, SEEK_END);
  4621. len = ftell(fp);
  4622. buffer = (char*)aMalloc(len+1);
  4623. fseek(fp, 0, SEEK_SET);
  4624. len = fread(buffer, 1, len, fp);
  4625. buffer[len] = '\0';
  4626. if( ferror(fp) )
  4627. {
  4628. ShowError("npc_parsesrcfile: Failed to read file '%s' - %s\n", filepath, strerror(errno));
  4629. aFree(buffer);
  4630. fclose(fp);
  4631. return 0;
  4632. }
  4633. fclose(fp);
  4634. if ((unsigned char)buffer[0] == 0xEF && (unsigned char)buffer[1] == 0xBB && (unsigned char)buffer[2] == 0xBF) {
  4635. // UTF-8 BOM. This is most likely an error on the user's part, because:
  4636. // - BOM is discouraged in UTF-8, and the only place where you see it is Notepad and such.
  4637. // - It's unlikely that the user wants to use UTF-8 data here, since we don't really support it, nor does the client by default.
  4638. // - If the user really wants to use UTF-8 (instead of latin1, EUC-KR, SJIS, etc), then they can still do it <without BOM>.
  4639. // More info at http://unicode.org/faq/utf_bom.html#bom5 and http://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  4640. ShowError("npc_parsesrcfile: Detected unsupported UTF-8 BOM in file '%s'. Stopping (please consider using another character set).\n", filepath);
  4641. aFree(buffer);
  4642. return 0;
  4643. }
  4644. // parse buffer
  4645. for( p = skip_space(buffer); p && *p ; p = skip_space(p) )
  4646. {
  4647. int pos[9];
  4648. char w1[2048], w2[2048], w3[2048], w4[2048];
  4649. int i, count;
  4650. lines++;
  4651. // w1<TAB>w2<TAB>w3<TAB>w4
  4652. count = sv_parse(p, len+buffer-p, 0, '\t', pos, ARRAYLENGTH(pos), (e_svopt)(SV_TERMINATE_LF|SV_TERMINATE_CRLF));
  4653. if( count < 0 )
  4654. {
  4655. ShowError("npc_parsesrcfile: Parse error in file '%s', line '%d'. Stopping...\n", filepath, strline(buffer,p-buffer));
  4656. break;
  4657. }
  4658. // fill w1
  4659. if( pos[3]-pos[2] > ARRAYLENGTH(w1)-1 )
  4660. ShowWarning("npc_parsesrcfile: w1 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[3]-pos[2], filepath, strline(buffer,p-buffer));
  4661. i = min(pos[3]-pos[2], ARRAYLENGTH(w1)-1);
  4662. memcpy(w1, p+pos[2], i*sizeof(char));
  4663. w1[i] = '\0';
  4664. // fill w2
  4665. if( pos[5]-pos[4] > ARRAYLENGTH(w2)-1 )
  4666. ShowWarning("npc_parsesrcfile: w2 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[5]-pos[4], filepath, strline(buffer,p-buffer));
  4667. i = min(pos[5]-pos[4], ARRAYLENGTH(w2)-1);
  4668. memcpy(w2, p+pos[4], i*sizeof(char));
  4669. w2[i] = '\0';
  4670. // fill w3
  4671. if( pos[7]-pos[6] > ARRAYLENGTH(w3)-1 )
  4672. ShowWarning("npc_parsesrcfile: w3 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[7]-pos[6], filepath, strline(buffer,p-buffer));
  4673. i = min(pos[7]-pos[6], ARRAYLENGTH(w3)-1);
  4674. memcpy(w3, p+pos[6], i*sizeof(char));
  4675. w3[i] = '\0';
  4676. // fill w4 (to end of line)
  4677. if( pos[1]-pos[8] > ARRAYLENGTH(w4)-1 )
  4678. ShowWarning("npc_parsesrcfile: w4 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[1]-pos[8], filepath, strline(buffer,p-buffer));
  4679. if( pos[8] != -1 )
  4680. {
  4681. i = min(pos[1]-pos[8], ARRAYLENGTH(w4)-1);
  4682. memcpy(w4, p+pos[8], i*sizeof(char));
  4683. w4[i] = '\0';
  4684. }
  4685. else
  4686. w4[0] = '\0';
  4687. if( count < 3 )
  4688. {// Unknown syntax
  4689. ShowError("npc_parsesrcfile: Unknown syntax in file '%s', line '%d'. Stopping...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
  4690. break;
  4691. }
  4692. if( strcmp(w1,"-") !=0 && strcasecmp(w1,"function") != 0 )
  4693. {// w1 = <map name>,<x>,<y>,<facing>
  4694. char mapname[MAP_NAME_LENGTH_EXT];
  4695. int count2;
  4696. count2 = sscanf(w1,"%15[^,],%6hd,%6hd[^,]",mapname,&x,&y);
  4697. if ( count2 < 1 ) {
  4698. ShowError("npc_parsesrcfile: Invalid script definition in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
  4699. if (strcasecmp(w2,"script") == 0 && count > 3) {
  4700. if ((p = npc_skip_script(p,buffer,filepath)) == NULL)
  4701. break;
  4702. }
  4703. p = strchr(p,'\n');// next line
  4704. continue;
  4705. }else if( count2 < 3 ){
  4706. // If we were not able to parse any x and y coordinates(usually used by mapflags)
  4707. x = y = 0;
  4708. }
  4709. if( !mapindex_name2id(mapname) )
  4710. {// Incorrect map, we must skip the script info...
  4711. ShowError("npc_parsesrcfile: Unknown map '%s' in file '%s', line '%d'. Skipping line...\n", mapname, filepath, strline(buffer,p-buffer));
  4712. if( strcasecmp(w2,"script") == 0 && count > 3 )
  4713. {
  4714. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  4715. {
  4716. break;
  4717. }
  4718. }
  4719. p = strchr(p,'\n');// next line
  4720. continue;
  4721. }
  4722. m = map_mapname2mapid(mapname);
  4723. if( m < 0 )
  4724. {// "mapname" is not assigned to this server, we must skip the script info...
  4725. if( strcasecmp(w2,"script") == 0 && count > 3 )
  4726. {
  4727. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  4728. {
  4729. break;
  4730. }
  4731. }
  4732. p = strchr(p,'\n');// next line
  4733. continue;
  4734. }
  4735. struct map_data *mapdata = map_getmapdata(m);
  4736. if (x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys) {
  4737. ShowError("npc_parsesrcfile: Unknown coordinates ('%d', '%d') for map '%s' in file '%s', line '%d'. Skipping line...\n", x, y, mapname, filepath, strline(buffer,p-buffer));
  4738. if( strcasecmp(w2,"script") == 0 && count > 3 )
  4739. {
  4740. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  4741. {
  4742. break;
  4743. }
  4744. }
  4745. p = strchr(p,'\n');// next line
  4746. continue;
  4747. }
  4748. }
  4749. if((strcasecmp(w2,"warp") == 0 || strcasecmp(w2,"warp2") == 0) && count > 3)
  4750. p = npc_parse_warp(w1,w2,w3,w4, p, buffer, filepath);
  4751. else if( (!strcasecmp(w2,"shop") || !strcasecmp(w2,"cashshop") || !strcasecmp(w2,"itemshop") || !strcasecmp(w2,"pointshop") || !strcasecmp(w2,"marketshop") ) && count > 3 )
  4752. p = npc_parse_shop(w1,w2,w3,w4, p, buffer, filepath);
  4753. else if( strcasecmp(w2,"script") == 0 && count > 3 ) {
  4754. if( strcasecmp(w1,"function") == 0 )
  4755. p = npc_parse_function(w1, w2, w3, w4, p, buffer, filepath);
  4756. else
  4757. p = npc_parse_script(w1,w2,w3,w4, p, buffer, filepath);
  4758. }
  4759. else if( (i=0, sscanf(w2,"duplicate%n",&i), (i > 0 && w2[i] == '(')) && count > 3 )
  4760. p = npc_parse_duplicate(w1,w2,w3,w4, p, buffer, filepath);
  4761. else if( (strcmpi(w2,"monster") == 0 || strcmpi(w2,"boss_monster") == 0) && count > 3 )
  4762. p = npc_parse_mob(w1, w2, w3, w4, p, buffer, filepath);
  4763. else if( strcmpi(w2,"mapflag") == 0 && count >= 3 )
  4764. p = npc_parse_mapflag(w1, w2, trim(w3), trim(w4), p, buffer, filepath);
  4765. else {
  4766. ShowError("npc_parsesrcfile: Unable to parse, probably a missing or extra TAB in file '%s', line '%d'. Skipping line...\n * w1=%s\n * w2=%s\n * w3=%s\n * w4=%s\n", filepath, strline(buffer,p-buffer), w1, w2, w3, w4);
  4767. p = strchr(p,'\n');// skip and continue
  4768. }
  4769. }
  4770. aFree(buffer);
  4771. return 1;
  4772. }
  4773. int npc_script_event(map_session_data* sd, enum npce_event type){
  4774. if (type == NPCE_MAX)
  4775. return 0;
  4776. if (!sd) {
  4777. ShowError("npc_script_event: NULL sd. Event Type %d\n", type);
  4778. return 0;
  4779. }
  4780. std::vector<struct script_event_s>& vector = script_event[type];
  4781. for( struct script_event_s& evt : vector ){
  4782. npc_event_sub( sd, evt.event, evt.event_name );
  4783. }
  4784. return vector.size();
  4785. }
  4786. /**
  4787. * Duplicates a NPC.
  4788. * nd: Original NPC data
  4789. * name: Duplicate NPC name
  4790. * m: Map ID of duplicate NPC
  4791. * x: X coordinate of duplicate NPC
  4792. * y: Y coordinate of duplicate NPC
  4793. * class_: View of duplicate NPC
  4794. * dir: Facing direction of duplicate NPC
  4795. * Returns duplicate NPC data on success
  4796. */
  4797. npc_data* npc_duplicate_npc( npc_data& nd, char name[NPC_NAME_LENGTH + 1], int16 mapid, int16 x, int16 y, int class_, uint8 dir, int16 xs, int16 ys, map_session_data* owner ){
  4798. static char w1[128], w2[128], w3[128], w4[128];
  4799. const char* stat_buf = "- call from duplicate subsystem -\n";
  4800. char exname[NPC_NAME_LENGTH + 1];
  4801. snprintf(w1, sizeof(w1), "%s,%d,%d,%d", map_getmapdata(mapid)->name, x, y, dir);
  4802. snprintf(w2, sizeof(w2), "duplicate(%s)", nd.exname);
  4803. //Making sure the generated name is not used for another npc.
  4804. int i = 0;
  4805. snprintf(exname, ARRAYLENGTH(exname), "%d_%d_%d_%d", i, mapid, x, y);
  4806. while (npc_name2id(exname) != nullptr) {
  4807. ++i;
  4808. snprintf(exname, ARRAYLENGTH(exname), "%d_%d_%d_%d", i, mapid, x, y);
  4809. }
  4810. snprintf(w3, sizeof(w3), "%s::%s", name, exname);
  4811. if( xs >= 0 && ys >= 0 ){
  4812. snprintf( w4, sizeof( w4 ), "%d,%d,%d", class_, xs, ys ); // Touch Area
  4813. }else{
  4814. snprintf( w4, sizeof( w4 ), "%d", class_ );
  4815. }
  4816. npc_parse_duplicate( w1, w2, w3, w4, stat_buf, stat_buf, "DUPLICATE", owner ); //DUPLICATE means nothing for now.
  4817. npc_data* dnd = npc_name2id( exname );
  4818. // No need to try and execute any events
  4819. if( dnd == nullptr ){
  4820. return nullptr;
  4821. }
  4822. //run OnInit Events
  4823. char evname[EVENT_NAME_LENGTH];
  4824. safesnprintf(evname, EVENT_NAME_LENGTH, "%s::%s", exname, script_config.init_event_name);
  4825. if ((struct event_data*)strdb_get(ev_db, evname)) {
  4826. npc_event_do(evname);
  4827. }
  4828. return dnd;
  4829. }
  4830. TIMER_FUNC(npc_dynamicnpc_removal_timer){
  4831. struct npc_data* nd = map_id2nd( id );
  4832. if( nd == nullptr ){
  4833. return 0;
  4834. }
  4835. nd->dynamicnpc.removal_tid = INVALID_TIMER;
  4836. map_session_data* sd = map_charid2sd( nd->dynamicnpc.owner_char_id );
  4837. if( sd != nullptr ){
  4838. // Still talking to the NPC
  4839. // TODO: are there other fields to check?
  4840. if( sd->npc_id == nd->bl.id || sd->npc_shopid == nd->bl.id ){
  4841. // Retry later
  4842. nd->dynamicnpc.last_interaction = gettick();
  4843. nd->dynamicnpc.removal_tid = add_timer( nd->dynamicnpc.last_interaction + battle_config.feature_dynamicnpc_timeout, npc_dynamicnpc_removal_timer, nd->bl.id, NULL );
  4844. return 0;
  4845. }
  4846. // Last interaction is not long enough in the past
  4847. if( DIFF_TICK( gettick(), nd->dynamicnpc.last_interaction ) < battle_config.feature_dynamicnpc_timeout ){
  4848. nd->dynamicnpc.removal_tid = add_timer( nd->dynamicnpc.last_interaction + DIFF_TICK( gettick(), nd->dynamicnpc.last_interaction ), npc_dynamicnpc_removal_timer, nd->bl.id, NULL );
  4849. return 0;
  4850. }
  4851. // npc id from sd->npc_id_dynamic is removed in npc_unload
  4852. }
  4853. // Delete the NPC
  4854. npc_unload( nd, true );
  4855. // Update NPC event database
  4856. npc_read_event_script();
  4857. return 0;
  4858. }
  4859. struct npc_data* npc_duplicate_npc_for_player( struct npc_data& nd, map_session_data& sd ){
  4860. // A duplicate of a duplicate is still a duplicate of the same NPC
  4861. int src_id = nd.src_id > 0 ? nd.src_id : nd.bl.id;
  4862. for (const auto &it : sd.npc_id_dynamic) {
  4863. struct npc_data* src_nd = map_id2nd( it );
  4864. // Check if the source NPC id of currently active duplicates already exists.
  4865. if( src_nd != nullptr && src_nd->src_id == src_id ){
  4866. clif_msg_color( &sd, C_DYNAMICNPC_TWICE, color_table[COLOR_LIGHT_YELLOW] );
  4867. return nullptr;
  4868. }
  4869. }
  4870. if( map_getmapflag( sd.bl.m, MF_NODYNAMICNPC ) ){
  4871. // It has been confirmed that there is no reply to the client
  4872. return nullptr;
  4873. }
  4874. int16 new_x, new_y;
  4875. if( !map_search_freecell( &sd.bl, 0, &new_x, &new_y, battle_config.feature_dynamicnpc_rangex, battle_config.feature_dynamicnpc_rangey, 0 ) ){
  4876. ShowError( "npc_duplicate_npc_for_player: Unable to find a free cell to duplicate NPC \"%s\" for player \"%s\"(AID: %u, CID: %u)\n", nd.exname, sd.status.name, sd.status.account_id, sd.status.char_id );
  4877. return nullptr;
  4878. }
  4879. int8 dir;
  4880. if( battle_config.feature_dynamicnpc_direction ){
  4881. // Let the NPC look to the player
  4882. dir = map_calc_dir_xy( new_x, new_y, sd.bl.x, sd.bl.y, DIR_CENTER );
  4883. }else{
  4884. // Use original NPCs direction
  4885. dir = nd.ud.dir;
  4886. }
  4887. struct npc_data* dnd = npc_duplicate_npc( nd, nd.name, sd.bl.m, new_x, new_y, nd.class_, dir, nd.u.scr.xs, nd.u.scr.ys, &sd );
  4888. if( dnd == nullptr ){
  4889. return nullptr;
  4890. }
  4891. dnd->dynamicnpc.last_interaction = gettick();
  4892. dnd->dynamicnpc.removal_tid = add_timer( dnd->dynamicnpc.last_interaction + battle_config.feature_dynamicnpc_timeout, npc_dynamicnpc_removal_timer, dnd->bl.id, NULL );
  4893. return dnd;
  4894. }
  4895. const char *npc_get_script_event_name(int npce_index)
  4896. {
  4897. switch (npce_index) {
  4898. case NPCE_LOGIN:
  4899. return script_config.login_event_name;
  4900. case NPCE_LOGOUT:
  4901. return script_config.logout_event_name;
  4902. case NPCE_LOADMAP:
  4903. return script_config.loadmap_event_name;
  4904. case NPCE_BASELVUP:
  4905. return script_config.baselvup_event_name;
  4906. case NPCE_JOBLVUP:
  4907. return script_config.joblvup_event_name;
  4908. case NPCE_DIE:
  4909. return script_config.die_event_name;
  4910. case NPCE_KILLPC:
  4911. return script_config.kill_pc_event_name;
  4912. case NPCE_KILLNPC:
  4913. return script_config.kill_mob_event_name;
  4914. default:
  4915. ShowError("npc_get_script_event_name: npce_index is outside the array limits: %d (max: %d).\n", npce_index, NPCE_MAX);
  4916. return NULL;
  4917. }
  4918. }
  4919. void npc_read_event_script(void)
  4920. {
  4921. int i;
  4922. script_event.clear();
  4923. for (i = 0; i < NPCE_MAX; i++)
  4924. {
  4925. DBIterator* iter;
  4926. DBKey key;
  4927. DBData *data;
  4928. char name[EVENT_NAME_LENGTH];
  4929. safesnprintf(name,EVENT_NAME_LENGTH,"::%s", npc_get_script_event_name(i));
  4930. iter = db_iterator(ev_db);
  4931. for( data = iter->first(iter,&key); iter->exists(iter); data = iter->next(iter,&key) )
  4932. {
  4933. const char* p = key.str;
  4934. struct event_data* ed = (struct event_data*)db_data2ptr(data);
  4935. if( (p=strchr(p,':')) && strcmpi(name,p)==0 ){
  4936. struct script_event_s evt;
  4937. evt.event = ed;
  4938. evt.event_name = key.str;
  4939. script_event[static_cast<enum npce_event>(i)].push_back(evt);
  4940. }
  4941. }
  4942. dbi_destroy(iter);
  4943. }
  4944. if (battle_config.etc_log) {
  4945. //Print summary.
  4946. for (i = 0; i < NPCE_MAX; i++)
  4947. ShowInfo("%" PRIuPTR " '%s' events.\n", script_event[static_cast<enum npce_event>(i)].size(), npc_get_script_event_name(i));
  4948. }
  4949. }
  4950. void npc_clear_pathlist(void) {
  4951. struct npc_path_data *npd = NULL;
  4952. DBIterator *path_list = db_iterator(npc_path_db);
  4953. /* free all npc_path_data filepaths */
  4954. for( npd = (struct npc_path_data *)dbi_first(path_list); dbi_exists(path_list); npd = (struct npc_path_data *)dbi_next(path_list) ) {
  4955. if( npd->path )
  4956. aFree(npd->path);
  4957. }
  4958. dbi_destroy(path_list);
  4959. }
  4960. //Clear then reload npcs files
  4961. int npc_reload(void) {
  4962. struct npc_src_list *nsl;
  4963. int npc_new_min = npc_id;
  4964. struct s_mapiterator* iter;
  4965. struct block_list* bl;
  4966. /* clear guild flag cache */
  4967. guild_flags_clear();
  4968. npc_clear_pathlist();
  4969. db_clear(npc_path_db);
  4970. db_clear(npcname_db);
  4971. db_clear(ev_db);
  4972. //Remove all npcs/mobs. [Skotlex]
  4973. #if PACKETVER >= 20131223
  4974. npc_market_fromsql();
  4975. #endif
  4976. iter = mapit_geteachiddb();
  4977. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) ) {
  4978. switch(bl->type) {
  4979. case BL_NPC:
  4980. if( bl->id != fake_nd->bl.id )// don't remove fake_nd
  4981. npc_unload((struct npc_data *)bl, false);
  4982. break;
  4983. case BL_MOB:
  4984. unit_free(bl,CLR_OUTSIGHT);
  4985. break;
  4986. }
  4987. }
  4988. mapit_free(iter);
  4989. // dynamic check by [random]
  4990. if( battle_config.dynamic_mobs ){
  4991. for (int i = 0; i < map_num; i++) {
  4992. for( int16 j = 0; j < MAX_MOB_LIST_PER_MAP; j++ ){
  4993. struct map_data *mapdata = map_getmapdata(i);
  4994. if (mapdata->moblist[j] != NULL) {
  4995. aFree(mapdata->moblist[j]);
  4996. mapdata->moblist[j] = NULL;
  4997. }
  4998. if( mapdata->mob_delete_timer != INVALID_TIMER )
  4999. { // Mobs were removed anyway,so delete the timer [Inkfish]
  5000. delete_timer(mapdata->mob_delete_timer, map_removemobs_timer);
  5001. mapdata->mob_delete_timer = INVALID_TIMER;
  5002. }
  5003. if( mapdata->npc_num > 0 ){
  5004. ShowWarning( "npc_reload: %d npcs weren't removed at map %s!\n", mapdata->npc_num, mapdata->name );
  5005. }
  5006. }
  5007. }
  5008. }
  5009. // clear mob spawn lookup index
  5010. mob_clear_spawninfo();
  5011. npc_warp = npc_shop = npc_script = 0;
  5012. npc_mob = npc_cache_mob = npc_delay_mob = 0;
  5013. // reset mapflags
  5014. map_flags_init();
  5015. //TODO: the following code is copy-pasted from do_init_npc(); clean it up
  5016. // Reloading npcs now
  5017. for (nsl = npc_src_files; nsl; nsl = nsl->next) {
  5018. ShowStatus("Loading NPC file: %s" CL_CLL "\r", nsl->name);
  5019. npc_parsesrcfile(nsl->name);
  5020. }
  5021. ShowInfo ("Done loading '" CL_WHITE "%d" CL_RESET "' NPCs:" CL_CLL "\n"
  5022. "\t-'" CL_WHITE "%d" CL_RESET "' Warps\n"
  5023. "\t-'" CL_WHITE "%d" CL_RESET "' Shops\n"
  5024. "\t-'" CL_WHITE "%d" CL_RESET "' Scripts\n"
  5025. "\t-'" CL_WHITE "%d" CL_RESET "' Spawn sets\n"
  5026. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Cached\n"
  5027. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Not Cached\n",
  5028. npc_id - npc_new_min, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  5029. stylist_db.reload();
  5030. barter_db.reload();
  5031. //Re-read the NPC Script Events cache.
  5032. npc_read_event_script();
  5033. /* refresh guild castle flags on both woe setups */
  5034. npc_event_doall( script_config.agit_init_event_name );
  5035. npc_event_doall( script_config.agit_init2_event_name );
  5036. npc_event_doall( script_config.agit_init3_event_name );
  5037. //Execute the OnInit event for freshly loaded npcs. [Skotlex]
  5038. npc_event_runall(script_config.init_event_name);
  5039. map_data_copyall();
  5040. do_reload_instance();
  5041. // Execute rest of the startup events if connected to char-server. [Lance]
  5042. if(!CheckForCharServer()){
  5043. npc_event_runall(script_config.inter_init_event_name);
  5044. }
  5045. #if PACKETVER >= 20131223
  5046. npc_market_checkall();
  5047. #endif
  5048. return 0;
  5049. }
  5050. //Unload all npc in the given file
  5051. bool npc_unloadfile( const char* path ) {
  5052. DBIterator * iter = db_iterator(npcname_db);
  5053. struct npc_data* nd = NULL;
  5054. bool found = false;
  5055. for( nd = (struct npc_data*)dbi_first(iter); dbi_exists(iter); nd = (struct npc_data*)dbi_next(iter) ) {
  5056. if( nd->path && strcasecmp(nd->path,path) == 0 ) {
  5057. found = true;
  5058. npc_unload_duplicates(nd);/* unload any npcs which could duplicate this but be in a different file */
  5059. npc_unload(nd, true);
  5060. }
  5061. }
  5062. dbi_destroy(iter);
  5063. if( found ) /* refresh event cache */
  5064. npc_read_event_script();
  5065. npc_delsrcfile(path);
  5066. return found;
  5067. }
  5068. void do_clear_npc(void) {
  5069. db_clear(npcname_db);
  5070. db_clear(ev_db);
  5071. }
  5072. /*==========================================
  5073. * Destructor
  5074. *------------------------------------------*/
  5075. void do_final_npc(void) {
  5076. npc_clear_pathlist();
  5077. script_event.clear();
  5078. ev_db->destroy(ev_db, NULL);
  5079. npcname_db->destroy(npcname_db, NULL);
  5080. npc_path_db->destroy(npc_path_db, NULL);
  5081. #if PACKETVER >= 20131223
  5082. NPCMarketDB->destroy(NPCMarketDB, npc_market_free);
  5083. #endif
  5084. stylist_db.clear();
  5085. barter_db.clear();
  5086. ers_destroy(timer_event_ers);
  5087. ers_destroy(npc_sc_display_ers);
  5088. npc_clearsrcfile();
  5089. }
  5090. static void npc_debug_warps_sub(struct npc_data* nd)
  5091. {
  5092. int16 m;
  5093. if (nd->bl.type != BL_NPC || nd->subtype != NPCTYPE_WARP || nd->bl.m < 0)
  5094. return;
  5095. m = map_mapindex2mapid(nd->u.warp.mapindex);
  5096. if (m < 0) return; //Warps to another map, nothing to do about it.
  5097. if (nd->u.warp.x == 0 && nd->u.warp.y == 0) return; // random warp
  5098. struct map_data *mapdata = map_getmapdata(m);
  5099. struct map_data *mapdata_nd = map_getmapdata(nd->bl.m);
  5100. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNPC)) {
  5101. ShowWarning("Warp %s at %s(%d,%d) warps directly on top of an area npc at %s(%d,%d)\n",
  5102. nd->name,
  5103. mapdata_nd->name, nd->bl.x, nd->bl.y,
  5104. mapdata->name, nd->u.warp.x, nd->u.warp.y
  5105. );
  5106. }
  5107. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNOPASS)) {
  5108. ShowWarning("Warp %s at %s(%d,%d) warps to a non-walkable tile at %s(%d,%d)\n",
  5109. nd->name,
  5110. mapdata_nd->name, nd->bl.x, nd->bl.y,
  5111. mapdata->name, nd->u.warp.x, nd->u.warp.y
  5112. );
  5113. }
  5114. }
  5115. static void npc_debug_warps(void){
  5116. for (int i = 0; i < map_num; i++) {
  5117. struct map_data *mapdata = map_getmapdata(i);
  5118. for( int i = 0; i < mapdata->npc_num; i++ ){
  5119. npc_debug_warps_sub(mapdata->npc[i]);
  5120. }
  5121. }
  5122. }
  5123. /*==========================================
  5124. * npc initialization
  5125. *------------------------------------------*/
  5126. void do_init_npc(void){
  5127. struct npc_src_list *file;
  5128. int i;
  5129. //Stock view data for normal npcs.
  5130. memset(&npc_viewdb, 0, sizeof(npc_viewdb));
  5131. npc_viewdb[0].class_ = JT_INVISIBLE; //Invisible class is stored here.
  5132. for( i = 1; i < MAX_NPC_CLASS; i++ )
  5133. npc_viewdb[i].class_ = i;
  5134. for( i = MAX_NPC_CLASS2_START; i < MAX_NPC_CLASS2_END; i++ )
  5135. npc_viewdb2[i - MAX_NPC_CLASS2_START].class_ = i;
  5136. ev_db = strdb_alloc((DBOptions)(DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA), EVENT_NAME_LENGTH);
  5137. npcname_db = strdb_alloc(DB_OPT_BASE, NPC_NAME_LENGTH+1);
  5138. npc_path_db = strdb_alloc((DBOptions)(DB_OPT_BASE|DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA),80);
  5139. #if PACKETVER >= 20131223
  5140. NPCMarketDB = strdb_alloc(DB_OPT_BASE, NPC_NAME_LENGTH+1);
  5141. npc_market_fromsql();
  5142. #endif
  5143. timer_event_ers = ers_new(sizeof(struct timer_event_data),"npc.cpp::timer_event_ers",ERS_OPT_NONE);
  5144. npc_sc_display_ers = ers_new(sizeof(struct sc_display_entry), "npc.cpp:npc_sc_display_ers", ERS_OPT_NONE);
  5145. // process all npc files
  5146. ShowStatus("Loading NPCs...\r");
  5147. for( file = npc_src_files; file != NULL; file = file->next ) {
  5148. ShowStatus("Loading NPC file: %s" CL_CLL "\r", file->name);
  5149. npc_parsesrcfile(file->name);
  5150. }
  5151. ShowInfo ("Done loading '" CL_WHITE "%d" CL_RESET "' NPCs:" CL_CLL "\n"
  5152. "\t-'" CL_WHITE "%d" CL_RESET "' Warps\n"
  5153. "\t-'" CL_WHITE "%d" CL_RESET "' Shops\n"
  5154. "\t-'" CL_WHITE "%d" CL_RESET "' Scripts\n"
  5155. "\t-'" CL_WHITE "%d" CL_RESET "' Spawn sets\n"
  5156. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Cached\n"
  5157. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Not Cached\n",
  5158. npc_id - START_NPC_NUM, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  5159. stylist_db.load();
  5160. barter_db.load();
  5161. // set up the events cache
  5162. npc_read_event_script();
  5163. #if PACKETVER >= 20131223
  5164. npc_market_checkall();
  5165. #endif
  5166. //Debug function to locate all endless loop warps.
  5167. if (battle_config.warp_point_debug)
  5168. npc_debug_warps();
  5169. add_timer_func_list(npc_event_do_clock,"npc_event_do_clock");
  5170. add_timer_func_list(npc_timerevent,"npc_timerevent");
  5171. add_timer_func_list( npc_dynamicnpc_removal_timer, "npc_dynamicnpc_removal_timer" );
  5172. // Init dummy NPC
  5173. fake_nd = npc_create_npc( -1, 0, 0 );
  5174. fake_nd->class_ = JT_FAKENPC;
  5175. fake_nd->speed = 200;
  5176. strcpy(fake_nd->name,"FAKE_NPC");
  5177. memcpy(fake_nd->exname, fake_nd->name, 9);
  5178. npc_script++;
  5179. fake_nd->bl.type = BL_NPC;
  5180. fake_nd->subtype = NPCTYPE_SCRIPT;
  5181. strdb_put(npcname_db, fake_nd->exname, fake_nd);
  5182. fake_nd->u.scr.timerid = INVALID_TIMER;
  5183. map_addiddb(&fake_nd->bl);
  5184. // End of initialization
  5185. }