npc.cpp 190 KB

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