npc.cpp 188 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274
  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( requirement_index >= MAX_BARTER_REQUIREMENTS ){
  494. this->invalidWarning( requiredItemNode["Index"], "barter_parseBodyNode: Index %hu is out of bounds. Barters support up to %d requirements.\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 = 200;
  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. unsigned int 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. unsigned int 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, 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. if( itemdb_isequip(sd->inventory.u.items_inventory[idx].nameid) )
  2436. {// process equipment based information into the arrays
  2437. script_setarray_pc( sd, "@sold_refine", i, sd->inventory.u.items_inventory[idx].refine, &key_refine );
  2438. script_setarray_pc( sd, "@sold_attribute", i, sd->inventory.u.items_inventory[idx].attribute, &key_attribute );
  2439. script_setarray_pc( sd, "@sold_identify", i, sd->inventory.u.items_inventory[idx].identify, &key_identify );
  2440. script_setarray_pc( sd, "@sold_enchantgrade", i, sd->inventory.u.items_inventory[idx].enchantgrade, &key_enchantgrade );
  2441. for( j = 0; j < MAX_SLOTS; j++ )
  2442. {// store each of the cards from the equipment in the array
  2443. snprintf(card_slot, sizeof(card_slot), "@sold_card%d", j + 1);
  2444. script_setarray_pc( sd, card_slot, i, sd->inventory.u.items_inventory[idx].card[j], &key_card[j] );
  2445. }
  2446. for (j = 0; j < MAX_ITEM_RDM_OPT; j++) { // Store each of the item options in the array
  2447. snprintf(option_id, sizeof(option_id), "@sold_option_id%d", j + 1);
  2448. script_setarray_pc( sd, option_id, i, sd->inventory.u.items_inventory[idx].option[j].id, &key_option_id[j] );
  2449. snprintf(option_val, sizeof(option_val), "@sold_option_val%d", j + 1);
  2450. script_setarray_pc( sd, option_val, i, sd->inventory.u.items_inventory[idx].option[j].value, &key_option_val[j] );
  2451. snprintf(option_param, sizeof(option_param), "@sold_option_param%d", j + 1);
  2452. script_setarray_pc( sd, option_param, i, sd->inventory.u.items_inventory[idx].option[j].param, &key_option_param[j] );
  2453. }
  2454. }
  2455. }
  2456. // invoke event
  2457. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::%s", nd->exname, script_config.onsell_event_name);
  2458. npc_event(sd, npc_ev, 0);
  2459. return 0;
  2460. }
  2461. /// Player item selling to npc shop.
  2462. ///
  2463. /// @param item_list 'n' pairs <index,amount>
  2464. /// @return result code for clif_parse_NpcSellListSend
  2465. uint8 npc_selllist(map_session_data* sd, int list_length, PACKET_CZ_PC_SELL_ITEMLIST_sub* item_list)
  2466. {
  2467. double z;
  2468. int i,skill;
  2469. struct npc_data *nd;
  2470. nullpo_retr(1, sd);
  2471. nullpo_retr(1, item_list);
  2472. if( ( nd = npc_checknear(sd, map_id2bl(sd->npc_shopid)) ) == nullptr || nd->subtype != NPCTYPE_SHOP )
  2473. {
  2474. return 1;
  2475. }
  2476. z = 0;
  2477. // verify the sell list
  2478. for( i = 0; i < list_length; i++ )
  2479. {
  2480. t_itemid nameid;
  2481. int amount, idx, value;
  2482. idx = item_list[i].index - 2;
  2483. amount = item_list[i].amount;
  2484. if( idx >= MAX_INVENTORY || idx < 0 || amount < 0 )
  2485. {
  2486. return 1;
  2487. }
  2488. nameid = sd->inventory.u.items_inventory[idx].nameid;
  2489. if( !nameid || !sd->inventory_data[idx] || sd->inventory.u.items_inventory[idx].amount < amount)
  2490. {
  2491. return 1;
  2492. }
  2493. if( nd->master_nd )
  2494. {// Script-controlled shops decide by themselves, what can be sold and at what price.
  2495. continue;
  2496. }
  2497. if (!pc_can_sell_item(sd, &sd->inventory.u.items_inventory[idx], nd->subtype)) {
  2498. return 1; // In official server, this illegal attempt the player will be disconnected
  2499. }
  2500. if (battle_config.rental_item_novalue && sd->inventory.u.items_inventory[idx].expire_time)
  2501. value = 0;
  2502. else
  2503. value = pc_modifysellvalue(sd, sd->inventory_data[idx]->value_sell);
  2504. z+= (double)value*amount;
  2505. }
  2506. if( nd->master_nd )
  2507. {// Script-controlled shops
  2508. return npc_selllist_sub(sd, list_length, item_list, nd->master_nd);
  2509. }
  2510. // delete items
  2511. for( i = 0; i < list_length; i++ )
  2512. {
  2513. int amount, idx;
  2514. idx = item_list[i].index - 2;
  2515. amount = item_list[i].amount;
  2516. // Forged packet, we do not care if he loses items
  2517. if( sd->inventory_data[idx] == nullptr ){
  2518. return 1;
  2519. }
  2520. if( sd->inventory_data[idx]->type == IT_PETEGG && sd->inventory.u.items_inventory[idx].card[0] == CARD0_PET )
  2521. {
  2522. if( pet_db_search(sd->inventory.u.items_inventory[idx].nameid, PET_EGG) )
  2523. {
  2524. intif_delete_petdata(MakeDWord(sd->inventory.u.items_inventory[idx].card[1], sd->inventory.u.items_inventory[idx].card[2]));
  2525. }
  2526. }
  2527. if (pc_delitem(sd, idx, amount, 0, 6, LOG_TYPE_NPC)) {
  2528. return 1;
  2529. }
  2530. }
  2531. if( z > MAX_ZENY )
  2532. z = MAX_ZENY;
  2533. pc_getzeny(sd, (int)z, LOG_TYPE_NPC);
  2534. // custom merchant shop exp bonus
  2535. if( battle_config.shop_exp > 0 && z > 0 && ( skill = pc_checkskill(sd,MC_OVERCHARGE) ) > 0)
  2536. {
  2537. uint16 sk_idx = skill_get_index(MC_OVERCHARGE);
  2538. if( sd->status.skill[sk_idx].flag >= SKILL_FLAG_REPLACED_LV_0 )
  2539. skill = sd->status.skill[sk_idx].flag - SKILL_FLAG_REPLACED_LV_0;
  2540. if( skill > 0 )
  2541. {
  2542. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  2543. if( z < 1 )
  2544. z = 1;
  2545. pc_gainexp(sd, nullptr, 0, (int)z, 0);
  2546. }
  2547. }
  2548. return 0;
  2549. }
  2550. e_purchase_result npc_barter_purchase( map_session_data& sd, std::shared_ptr<s_npc_barter> barter, std::vector<s_barter_purchase>& purchases ){
  2551. uint64 requiredZeny = 0;
  2552. uint32 requiredWeight = 0;
  2553. uint32 reducedWeight = 0;
  2554. uint16 requiredSlots = 0;
  2555. uint32 requiredItems[MAX_INVENTORY] = { 0 };
  2556. for( s_barter_purchase& purchase : purchases ){
  2557. purchase.data = item_db.find( purchase.item->nameid ).get();
  2558. if( purchase.data == nullptr ){
  2559. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2560. }
  2561. uint32 amount = purchase.amount;
  2562. if( purchase.item->stockLimited && purchase.item->stock < amount ){
  2563. return e_purchase_result::PURCHASE_FAIL_STOCK_EMPTY;
  2564. }
  2565. char result = pc_checkadditem( &sd, purchase.item->nameid, amount );
  2566. if( result == CHKADDITEM_OVERAMOUNT ){
  2567. return e_purchase_result::PURCHASE_FAIL_COUNT;
  2568. }else if( result == CHKADDITEM_NEW ){
  2569. requiredSlots += purchase.data->inventorySlotNeeded( amount );
  2570. }
  2571. requiredZeny += ( purchase.item->price * amount );
  2572. requiredWeight += ( purchase.data->weight * amount );
  2573. for( const auto& requirementPair : purchase.item->requirements ){
  2574. std::shared_ptr<s_npc_barter_requirement> requirement = requirementPair.second;
  2575. std::shared_ptr<item_data> id = item_db.find(requirement->nameid);
  2576. if( id == nullptr ){
  2577. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2578. }
  2579. if( itemdb_isstackable2( id.get() ) ){
  2580. int j;
  2581. for( j = 0; j < MAX_INVENTORY; j++ ){
  2582. if( sd.inventory.u.items_inventory[j].nameid == requirement->nameid ){
  2583. // Equipped items are not taken into account
  2584. if( sd.inventory.u.items_inventory[j].equip != 0 ){
  2585. continue;
  2586. }
  2587. // Items in equip switch are not taken into account
  2588. if( sd.inventory.u.items_inventory[j].equipSwitch != 0 ){
  2589. continue;
  2590. }
  2591. // Server is configured to hide favorite items on selling
  2592. if( battle_config.hide_fav_sell && sd.inventory.u.items_inventory[j].favorite != 0 ){
  2593. continue;
  2594. }
  2595. // Actually stackable items should never be refinable, but who knows...
  2596. if( requirement->refine >= 0 && sd.inventory.u.items_inventory[j].refine != requirement->refine ){
  2597. // Refine does not match, continue with next item
  2598. continue;
  2599. }
  2600. // Found a match, accumulate required amount
  2601. requiredItems[j] += requirement->amount * amount;
  2602. // Check if there are still enough items available
  2603. if( requiredItems[j] > sd.inventory.u.items_inventory[j].amount ){
  2604. return e_purchase_result::PURCHASE_FAIL_GOODS;
  2605. }
  2606. // Cancel the loop
  2607. break;
  2608. }
  2609. }
  2610. // Required item not found
  2611. if( j == MAX_INVENTORY ){
  2612. return e_purchase_result::PURCHASE_FAIL_GOODS;
  2613. }
  2614. }else{
  2615. for( int i = 0; i < (requirement->amount * amount); i++ ){
  2616. int j;
  2617. for( j = 0; j < MAX_INVENTORY; j++ ){
  2618. if( sd.inventory.u.items_inventory[j].nameid == requirement->nameid ){
  2619. // Equipped items are not taken into account
  2620. if( sd.inventory.u.items_inventory[j].equip != 0 ){
  2621. continue;
  2622. }
  2623. // Items in equip switch are not taken into account
  2624. if( sd.inventory.u.items_inventory[j].equipSwitch != 0 ){
  2625. continue;
  2626. }
  2627. // Server is configured to hide favorite items on selling
  2628. if( battle_config.hide_fav_sell && sd.inventory.u.items_inventory[j].favorite != 0 ){
  2629. continue;
  2630. }
  2631. // If necessary, check if the refine rate matches
  2632. if( requirement->refine >= 0 && sd.inventory.u.items_inventory[j].refine != requirement->refine ){
  2633. // Refine does not match, continue with next item
  2634. continue;
  2635. }
  2636. // Found a match, since it is not stackable, check if it was already taken
  2637. if( requiredItems[j] > 0 ){
  2638. // Item was already taken, try to find another match
  2639. continue;
  2640. }
  2641. // Mark it as taken
  2642. requiredItems[j] = 1;
  2643. // Cancel the loop
  2644. break;
  2645. }
  2646. }
  2647. // Required item not found
  2648. if( j == MAX_INVENTORY ){
  2649. // Maybe the refine level did not match
  2650. if( requirement->refine >= 0 ){
  2651. int refine;
  2652. // Try to find a higher refine level, going from the next lowest to the highest possible
  2653. for( refine = requirement->refine + 1; refine <= MAX_REFINE; refine++ ){
  2654. for( j = 0; j < MAX_INVENTORY; j++ ){
  2655. if( sd.inventory.u.items_inventory[j].nameid == requirement->nameid ){
  2656. // Equipped items are not taken into account
  2657. if( sd.inventory.u.items_inventory[j].equip != 0 ){
  2658. continue;
  2659. }
  2660. // Items in equip switch are not taken into account
  2661. if( sd.inventory.u.items_inventory[j].equipSwitch != 0 ){
  2662. continue;
  2663. }
  2664. // Server is configured to hide favorite items on selling
  2665. if( battle_config.hide_fav_sell && sd.inventory.u.items_inventory[j].favorite != 0 ){
  2666. continue;
  2667. }
  2668. // If necessary, check if the refine rate matches
  2669. if( requirement->refine >= 0 && sd.inventory.u.items_inventory[j].refine != refine ){
  2670. // Refine does not match, continue with next item
  2671. continue;
  2672. }
  2673. // Found a match, since it is not stackable, check if it was already taken
  2674. if( requiredItems[j] > 0 ){
  2675. // Item was already taken, try to find another match
  2676. continue;
  2677. }
  2678. // Mark it as taken
  2679. requiredItems[j] = 1;
  2680. // Cancel the loop
  2681. break;
  2682. }
  2683. }
  2684. // If a match was found, make sure to cancel the loop
  2685. if( j < MAX_INVENTORY ){
  2686. // Cancel the loop
  2687. break;
  2688. }
  2689. }
  2690. // No matching entry found
  2691. if( refine > MAX_REFINE ){
  2692. return e_purchase_result::PURCHASE_FAIL_GOODS;
  2693. }
  2694. }else{
  2695. return e_purchase_result::PURCHASE_FAIL_GOODS;
  2696. }
  2697. }
  2698. }
  2699. }
  2700. reducedWeight += ( purchase.amount * requirement->amount * id->weight );
  2701. }
  2702. }
  2703. // Check if there is enough Zeny
  2704. if( sd.status.zeny < requiredZeny ){
  2705. return e_purchase_result::PURCHASE_FAIL_MONEY;
  2706. }
  2707. // Check if there is enough Weight Limit
  2708. if( ( sd.weight + requiredWeight - reducedWeight ) > sd.max_weight ){
  2709. return e_purchase_result::PURCHASE_FAIL_WEIGHT;
  2710. }
  2711. if( pc_inventoryblank( &sd ) < requiredSlots ){
  2712. return e_purchase_result::PURCHASE_FAIL_COUNT;
  2713. }
  2714. for( int i = 0; i < MAX_INVENTORY; i++ ){
  2715. if( requiredItems[i] > 0 ){
  2716. if( pc_delitem( &sd, i, requiredItems[i], 0, 0, LOG_TYPE_BARTER ) != 0 ){
  2717. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2718. }
  2719. }
  2720. }
  2721. if( pc_payzeny( &sd, (int)requiredZeny, LOG_TYPE_BARTER ) != 0 ){
  2722. return e_purchase_result::PURCHASE_FAIL_MONEY;
  2723. }
  2724. for( s_barter_purchase& purchase : purchases ){
  2725. if( purchase.item->stockLimited ){
  2726. purchase.item->stock -= purchase.amount;
  2727. 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 ){
  2728. Sql_ShowDebug( mmysql_handle );
  2729. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2730. }
  2731. }
  2732. if( itemdb_isstackable2( purchase.data ) ){
  2733. struct item it = {};
  2734. it.nameid = purchase.item->nameid;
  2735. it.identify = true;
  2736. if( pc_additem( &sd, &it, purchase.amount, LOG_TYPE_BARTER ) != ADDITEM_SUCCESS ){
  2737. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2738. }
  2739. }else{
  2740. if( purchase.data->type == IT_PETEGG ){
  2741. for( int i = 0; i < purchase.amount; i++ ){
  2742. if( !pet_create_egg( &sd, purchase.item->nameid ) ){
  2743. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2744. }
  2745. }
  2746. }else{
  2747. for( int i = 0; i < purchase.amount; i++ ){
  2748. struct item it = {};
  2749. it.nameid = purchase.item->nameid;
  2750. it.identify = true;
  2751. if( pc_additem( &sd, &it, 1, LOG_TYPE_BARTER ) != ADDITEM_SUCCESS ){
  2752. return e_purchase_result::PURCHASE_FAIL_EXCHANGE_FAILED;
  2753. }
  2754. }
  2755. }
  2756. }
  2757. }
  2758. return e_purchase_result::PURCHASE_SUCCEED;
  2759. }
  2760. //Atempt to remove an npc from a map
  2761. //This doesn't remove it from map_db
  2762. int npc_remove_map(struct npc_data* nd)
  2763. {
  2764. int i;
  2765. nullpo_retr(1, nd);
  2766. if(nd->bl.prev == nullptr || nd->bl.m < 0)
  2767. return 1; //Not assigned to a map.
  2768. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  2769. if (nd->subtype == NPCTYPE_SCRIPT)
  2770. skill_clear_unitgroup(&nd->bl);
  2771. clif_clearunit_area( nd->bl, CLR_RESPAWN );
  2772. npc_unsetcells(nd);
  2773. map_delblock(&nd->bl);
  2774. //Remove npc from map[].npc list. [Skotlex]
  2775. ARR_FIND( 0, mapdata->npc_num, i, mapdata->npc[i] == nd );
  2776. if( i == mapdata->npc_num ) return 2; //failed to find it?
  2777. mapdata->npc_num--;
  2778. if (i >= mapdata->npc_num_area)
  2779. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num ];
  2780. else if (i >= mapdata->npc_num_warp) {
  2781. mapdata->npc_num_area--;
  2782. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num_area ];
  2783. mapdata->npc[ mapdata->npc_num_area ] = mapdata->npc[ mapdata->npc_num ];
  2784. }
  2785. else {
  2786. mapdata->npc_num_warp--;
  2787. mapdata->npc_num_area--;
  2788. mapdata->npc[i] = mapdata->npc[ mapdata->npc_num_warp ];
  2789. mapdata->npc[ mapdata->npc_num_warp ] = mapdata->npc[ mapdata->npc_num_area ];
  2790. mapdata->npc[ mapdata->npc_num_area ] = mapdata->npc[ mapdata->npc_num ];
  2791. }
  2792. mapdata->npc[ mapdata->npc_num ] = nullptr;
  2793. return 0;
  2794. }
  2795. /**
  2796. * @see DBApply
  2797. */
  2798. static int npc_unload_ev(DBKey key, DBData *data, va_list ap)
  2799. {
  2800. struct event_data* ev = (struct event_data*)db_data2ptr(data);
  2801. char* npcname = va_arg(ap, char *);
  2802. if(strcmp(ev->nd->exname,npcname)==0){
  2803. db_remove(ev_db, key);
  2804. return 1;
  2805. }
  2806. return 0;
  2807. }
  2808. //Chk if npc matches src_id, then unload.
  2809. //Sub-function used to find duplicates.
  2810. static int npc_unload_dup_sub(struct npc_data* nd, va_list args)
  2811. {
  2812. int src_id;
  2813. src_id = va_arg(args, int);
  2814. if (nd->src_id == src_id)
  2815. npc_unload(nd, true);
  2816. return 0;
  2817. }
  2818. //Removes all npcs that are duplicates of the passed one. [Skotlex]
  2819. void npc_unload_duplicates(struct npc_data* nd)
  2820. {
  2821. map_foreachnpc(npc_unload_dup_sub,nd->bl.id);
  2822. }
  2823. //Removes an npc from map and db.
  2824. //Single is to free name (for duplicates).
  2825. int npc_unload(struct npc_data* nd, bool single) {
  2826. nullpo_ret(nd);
  2827. status_change_clear(&nd->bl, 1);
  2828. npc_remove_map(nd);
  2829. map_deliddb(&nd->bl);
  2830. if( single )
  2831. strdb_remove(npcname_db, nd->exname);
  2832. if (nd->chat_id) // remove npc chatroom object and kick users
  2833. chat_deletenpcchat(nd);
  2834. #ifdef PCRE_SUPPORT
  2835. npc_chat_finalize(nd); // deallocate npc PCRE data structures
  2836. #endif
  2837. if( single && nd->path ) {
  2838. struct npc_path_data* npd = nullptr;
  2839. if( nd->path ) {
  2840. npd = (struct npc_path_data*)strdb_get(npc_path_db, nd->path);
  2841. }
  2842. if( npd && --npd->references == 0 ) {
  2843. strdb_remove(npc_path_db, nd->path);/* remove from db */
  2844. aFree(nd->path);/* remove now that no other instances exist */
  2845. if (npd == npc_last_npd) {
  2846. npc_last_npd = nullptr;
  2847. npc_last_path = nullptr;
  2848. }
  2849. }
  2850. }
  2851. if( single && nd->bl.m != -1 )
  2852. map_remove_questinfo(nd->bl.m, nd);
  2853. 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]
  2854. aFree(nd->u.shop.shop_item);
  2855. else if( nd->subtype == NPCTYPE_SCRIPT ) {
  2856. struct s_mapiterator* iter;
  2857. struct block_list* bl;
  2858. if( single )
  2859. ev_db->foreach(ev_db,npc_unload_ev,nd->exname); //Clean up all events related
  2860. iter = mapit_geteachpc();
  2861. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) ) {
  2862. map_session_data *sd = ((TBL_PC*)bl);
  2863. if( sd && sd->npc_timer_id != INVALID_TIMER ) {
  2864. const struct TimerData *td = get_timer(sd->npc_timer_id);
  2865. if( td && td->id != nd->bl.id )
  2866. continue;
  2867. if( td && td->data )
  2868. ers_free(timer_event_ers, (void*)td->data);
  2869. delete_timer(sd->npc_timer_id, npc_timerevent);
  2870. sd->npc_timer_id = INVALID_TIMER;
  2871. }
  2872. }
  2873. mapit_free(iter);
  2874. if (nd->u.scr.timerid != INVALID_TIMER) {
  2875. const struct TimerData *td;
  2876. td = get_timer(nd->u.scr.timerid);
  2877. if (td && td->data)
  2878. ers_free(timer_event_ers, (void*)td->data);
  2879. delete_timer(nd->u.scr.timerid, npc_timerevent);
  2880. }
  2881. if (nd->u.scr.timer_event)
  2882. aFree(nd->u.scr.timer_event);
  2883. if (nd->src_id == 0) {
  2884. if(nd->u.scr.script) {
  2885. script_free_code(nd->u.scr.script);
  2886. nd->u.scr.script = nullptr;
  2887. }
  2888. if (nd->u.scr.label_list) {
  2889. aFree(nd->u.scr.label_list);
  2890. nd->u.scr.label_list = nullptr;
  2891. nd->u.scr.label_list_num = 0;
  2892. }
  2893. }
  2894. if( nd->u.scr.guild_id )
  2895. guild_flag_remove(nd);
  2896. if( nd->sc_display_count ){
  2897. unsigned char i;
  2898. for( i = 0; i < nd->sc_display_count; i++ )
  2899. ers_free(npc_sc_display_ers, nd->sc_display[i]);
  2900. nd->sc_display_count = 0;
  2901. aFree(nd->sc_display);
  2902. nd->sc_display = nullptr;
  2903. }
  2904. }
  2905. nd->qi_data.clear();
  2906. script_stop_sleeptimers(nd->bl.id);
  2907. if( nd->dynamicnpc.removal_tid != INVALID_TIMER ){
  2908. delete_timer( nd->dynamicnpc.removal_tid, npc_dynamicnpc_removal_timer );
  2909. nd->dynamicnpc.removal_tid = INVALID_TIMER;
  2910. }
  2911. if( nd->dynamicnpc.owner_char_id != 0 ){
  2912. map_session_data* owner = map_charid2sd( nd->dynamicnpc.owner_char_id );
  2913. if( owner != nullptr ){
  2914. util::vector_erase_if_exists(owner->npc_id_dynamic, nd->bl.id);
  2915. }
  2916. }
  2917. nd->~npc_data();
  2918. aFree(nd);
  2919. return 0;
  2920. }
  2921. //
  2922. // NPC Source Files
  2923. //
  2924. /**
  2925. * Adds a npc source file (or removes all)
  2926. * @param name : file to add
  2927. * @param loadscript : flag to parse the script immediately after adding the src file
  2928. * @return 0=error, 1=sucess
  2929. */
  2930. int npc_addsrcfile(const char* name, bool loadscript)
  2931. {
  2932. if( strcmpi(name, "clear") == 0 )
  2933. {
  2934. npc_src_files.clear();
  2935. return 1;
  2936. }
  2937. //Check if this is not a file
  2938. if(check_filepath(name)!=2){
  2939. ShowError("npc_addsrcfile: Can't find source file \"%s\"\n", name );
  2940. return 0;
  2941. }
  2942. if (util::vector_exists(npc_src_files, name)) {
  2943. return 0; // found the file, no need to insert it again
  2944. }
  2945. npc_src_files.push_back(name);
  2946. if (loadscript)
  2947. return npc_parsesrcfile(name);
  2948. return 1;
  2949. }
  2950. /// Removes a npc source file (or all)
  2951. void npc_delsrcfile(const char* name)
  2952. {
  2953. if( strcmpi(name, "all") == 0 )
  2954. {
  2955. npc_src_files.clear();
  2956. return;
  2957. }
  2958. util::vector_erase_if_exists(npc_src_files, name);
  2959. }
  2960. /**
  2961. * Load all npc files
  2962. */
  2963. void npc_loadsrcfiles() {
  2964. ShowStatus("Loading NPCs...\n");
  2965. for (const auto& file : npc_src_files) {
  2966. #ifdef DETAILED_LOADING_OUTPUT
  2967. ShowStatus("Loading NPC file: %s" CL_CLL "\r", file.c_str());
  2968. #endif
  2969. npc_parsesrcfile(file.c_str());
  2970. }
  2971. int npc_total = npc_warp + npc_shop + npc_script;
  2972. ShowInfo ("Done loading '" CL_WHITE "%d" CL_RESET "' NPCs:" CL_CLL "\n"
  2973. "\t-'" CL_WHITE "%d" CL_RESET "' Warps\n"
  2974. "\t-'" CL_WHITE "%d" CL_RESET "' Shops\n"
  2975. "\t-'" CL_WHITE "%d" CL_RESET "' Scripts\n"
  2976. "\t-'" CL_WHITE "%d" CL_RESET "' Spawn sets\n"
  2977. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Cached\n"
  2978. "\t-'" CL_WHITE "%d" CL_RESET "' Mobs Not Cached\n",
  2979. npc_total, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  2980. }
  2981. /// Parses and sets the name and exname of a npc.
  2982. /// Assumes that m, x and y are already set in nd.
  2983. static void npc_parsename(struct npc_data* nd, const char* name, const char* start, const char* buffer, const char* filepath)
  2984. {
  2985. const char* p;
  2986. struct npc_data* dnd;// duplicate npc
  2987. char newname[NPC_NAME_LENGTH+1];
  2988. // parse name
  2989. p = strstr(name,"::");
  2990. if( p ) { // <Display name>::<Unique name>
  2991. size_t len = p-name;
  2992. if( len > NPC_NAME_LENGTH ) {
  2993. ShowWarning("npc_parsename: Display name of '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  2994. safestrncpy(nd->name, name, sizeof(nd->name));
  2995. } else {
  2996. memcpy(nd->name, name, len);
  2997. memset(nd->name+len, 0, sizeof(nd->name)-len);
  2998. }
  2999. len = strlen(p+2);
  3000. if( len > NPC_NAME_LENGTH )
  3001. ShowWarning("npc_parsename: Unique name of '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  3002. safestrncpy(nd->exname, p+2, sizeof(nd->exname));
  3003. } else {// <Display name>
  3004. size_t len = strlen(name);
  3005. if( len > NPC_NAME_LENGTH )
  3006. ShowWarning("npc_parsename: Name '%s' is too long (len=%u) in file '%s', line'%d'. Truncating to %u characters.\n", name, (unsigned int)len, filepath, strline(buffer,start-buffer), NPC_NAME_LENGTH);
  3007. safestrncpy(nd->name, name, sizeof(nd->name));
  3008. safestrncpy(nd->exname, name, sizeof(nd->exname));
  3009. }
  3010. if( *nd->exname == '\0' || strstr(nd->exname,"::") != nullptr ) {// invalid
  3011. snprintf(newname, ARRAYLENGTH(newname), "0_%d_%d_%d", nd->bl.m, nd->bl.x, nd->bl.y);
  3012. ShowWarning("npc_parsename: Invalid unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  3013. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  3014. }
  3015. if( (dnd=npc_name2id(nd->exname)) != nullptr ) {// duplicate unique name, generate new one
  3016. char this_mapname[MAP_NAME_LENGTH_EXT];
  3017. char other_mapname[MAP_NAME_LENGTH_EXT];
  3018. int i = 0;
  3019. do {
  3020. ++i;
  3021. snprintf(newname, ARRAYLENGTH(newname), "%d_%d_%d_%d", i, nd->bl.m, nd->bl.x, nd->bl.y);
  3022. } while( npc_name2id(newname) != nullptr );
  3023. strcpy(this_mapname, (nd->bl.m==-1?"(not on a map)":mapindex_id2name(map_getmapdata(nd->bl.m)->index)));
  3024. strcpy(other_mapname, (dnd->bl.m==-1?"(not on a map)":mapindex_id2name(map_getmapdata(dnd->bl.m)->index)));
  3025. ShowWarning("npc_parsename: Duplicate unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  3026. 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);
  3027. 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);
  3028. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  3029. }
  3030. if( npc_last_path != filepath ) {
  3031. struct npc_path_data * npd = nullptr;
  3032. if( !(npd = (struct npc_path_data *)strdb_get(npc_path_db,filepath) ) ) {
  3033. CREATE(npd, struct npc_path_data, 1);
  3034. strdb_put(npc_path_db, filepath, npd);
  3035. CREATE(npd->path, char, strlen(filepath)+1);
  3036. safestrncpy(npd->path, filepath, strlen(filepath)+1);
  3037. npd->references = 0;
  3038. }
  3039. nd->path = npd->path;
  3040. npd->references++;
  3041. npc_last_npd = npd;
  3042. npc_last_path = npd->path;
  3043. } else {
  3044. nd->path = npc_last_path;
  3045. if( npc_last_npd )
  3046. npc_last_npd->references++;
  3047. }
  3048. }
  3049. /**
  3050. * Parses NPC view.
  3051. * Support for using Constants in place of NPC View IDs.
  3052. */
  3053. int npc_parseview(const char* w4, const char* start, const char* buffer, const char* filepath) {
  3054. int i = 0;
  3055. char viewid[1024]; // Max size of name from const.yml, see ConstantDatabase::parseBodyNode.
  3056. // Extract view ID / constant
  3057. while (w4[i] != '\0') {
  3058. if (ISSPACE(w4[i]) || w4[i] == '/' || w4[i] == ',')
  3059. break;
  3060. i++;
  3061. }
  3062. safestrncpy(viewid, w4, i+=1);
  3063. char *pid;
  3064. int val = strtol(viewid, &pid, 0);
  3065. // Check if view id is not an ID (only numbers).
  3066. if (pid != nullptr && *pid != '\0') {
  3067. int64 val_tmp;
  3068. // Check if constant exists and get its value.
  3069. if(!script_get_constant(viewid, &val_tmp)) {
  3070. std::shared_ptr<s_mob_db> mob = mobdb_search_aegisname(viewid);
  3071. if (mob != nullptr)
  3072. val = static_cast<int>(mob->id);
  3073. else {
  3074. ShowWarning("npc_parseview: Invalid NPC constant '%s' specified in file '%s', line'%d'. Defaulting to INVISIBLE. \n", viewid, filepath, strline(buffer,start-buffer));
  3075. val = JT_INVISIBLE;
  3076. }
  3077. } else
  3078. val = static_cast<int>(val_tmp);
  3079. }
  3080. return val;
  3081. }
  3082. /**
  3083. * Create a bare NPC object.
  3084. * @param m: Map ID
  3085. * @param x: X location
  3086. * @param y: Y location
  3087. * @return npc_data
  3088. */
  3089. struct npc_data *npc_create_npc(int16 m, int16 x, int16 y){
  3090. struct npc_data *nd = nullptr;
  3091. CREATE(nd, struct npc_data, 1);
  3092. new (nd) npc_data();
  3093. nd->bl.id = npc_get_new_npc_id();
  3094. nd->bl.prev = nd->bl.next = nullptr;
  3095. nd->bl.m = m;
  3096. nd->bl.x = x;
  3097. nd->bl.y = y;
  3098. nd->sc_display = nullptr;
  3099. nd->sc_display_count = 0;
  3100. nd->progressbar.timeout = 0;
  3101. nd->vd = npc_viewdb[0]; // Default to JT_INVISIBLE
  3102. nd->dynamicnpc.owner_char_id = 0;
  3103. nd->dynamicnpc.last_interaction = 0;
  3104. nd->dynamicnpc.removal_tid = INVALID_TIMER;
  3105. #ifdef MAP_GENERATOR
  3106. nd->navi.pos = {m, x, y};
  3107. nd->navi.id = 0;
  3108. nd->navi.npc = nd;
  3109. #endif
  3110. return nd;
  3111. }
  3112. /**
  3113. * Add then display an npc warp on map
  3114. * @param name : warp unique name
  3115. * @param from_mapid : mapid to warp from
  3116. * @param from_x : x coordinate of warp
  3117. * @param from_y : y coordinate of warp
  3118. * @param xs : x lenght of warp (for trigger activation)
  3119. * @param ys : y lenght of warp (for trigger activation)
  3120. * @param to_mapindex : mapid to warp to
  3121. * @param to_x : x coordinate to warp to
  3122. * @param to_y : y coordinate to warp to
  3123. * @return nullptr:failed creation, npc_data* new warp
  3124. */
  3125. 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)
  3126. {
  3127. int i, flag = 0;
  3128. struct npc_data *nd;
  3129. nd = npc_create_npc(from_mapid, from_x, from_y);
  3130. safestrncpy(nd->exname, name, ARRAYLENGTH(nd->exname));
  3131. if (npc_name2id(nd->exname) != nullptr)
  3132. flag = 1;
  3133. if (flag == 1)
  3134. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp_%d_%d_%d", from_mapid, from_x, from_y);
  3135. for( i = 0; npc_name2id(nd->exname) != nullptr; ++i )
  3136. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp%d_%d_%d_%d", i, from_mapid, from_x, from_y);
  3137. safestrncpy(nd->name, nd->exname, ARRAYLENGTH(nd->name));
  3138. if( battle_config.warp_point_debug )
  3139. nd->class_ = JT_GUILD_FLAG;
  3140. else
  3141. nd->class_ = JT_WARPNPC;
  3142. nd->speed = 200;
  3143. nd->u.warp.mapindex = to_mapindex;
  3144. nd->u.warp.x = to_x;
  3145. nd->u.warp.y = to_y;
  3146. nd->u.warp.xs = xs;
  3147. nd->u.warp.ys = ys;
  3148. nd->bl.type = BL_NPC;
  3149. nd->subtype = NPCTYPE_WARP;
  3150. nd->trigger_on_hidden = false;
  3151. map_addnpc(from_mapid, nd);
  3152. npc_setcells(nd);
  3153. if(map_addblock(&nd->bl))
  3154. return nullptr;
  3155. status_set_viewdata(&nd->bl, nd->class_);
  3156. status_change_init(&nd->bl);
  3157. unit_dataset(&nd->bl);
  3158. if( map_getmapdata(nd->bl.m)->users )
  3159. clif_spawn(&nd->bl);
  3160. strdb_put(npcname_db, nd->exname, nd);
  3161. return nd;
  3162. }
  3163. /**
  3164. * Parses a warp npc.
  3165. * Line definition <from mapname>,<fromX>,<fromY>,<facing>%TAB%warp(<state)%TAB%<warp name>%TAB%<spanx>,<spany>,<to mapname>,<toX>,<toY>
  3166. * Line definition <from mapname>,<fromX>,<fromY>,<facing>%TAB%warp2(<state)%TAB%<warp name>%TAB%<spanx>,<spany>,<to mapname>,<toX>,<toY>
  3167. * @param w1 : word 1 before tab (<from map name>,<fromX>,<fromY>,<facing>)
  3168. * @param w2 : word 2 before tab (warp), keyword that sent us in this parsing
  3169. * @param w3 : word 3 before tab (<warp name>)
  3170. * @param w4 : word 4 before tab (<spanx>,<spany>,<to mapname>,<toX>,<toY>)
  3171. * @param start : index to start parsing
  3172. * @param buffer : lines to parses
  3173. * @param filepath : filename with path wich we are parsing
  3174. * @return new index for next parsing
  3175. */
  3176. static const char* npc_parse_warp(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  3177. {
  3178. short x, y, xs, ys, to_x, to_y;
  3179. char mapname[MAP_NAME_LENGTH_EXT], to_mapname[MAP_NAME_LENGTH_EXT];
  3180. // w1=<from map name>,<fromX>,<fromY>,<facing>
  3181. // w4=<spanx>,<spany>,<to map name>,<toX>,<toY>
  3182. 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 ) {
  3183. 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);
  3184. return strchr(start,'\n');// skip and continue
  3185. }
  3186. int m = map_mapname2mapid(mapname);
  3187. unsigned short i = mapindex_name2id(to_mapname);
  3188. if( i == 0 ) {
  3189. 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);
  3190. return strchr(start,'\n');// skip and continue
  3191. }
  3192. struct map_data *mapdata = map_getmapdata(m);
  3193. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  3194. 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));
  3195. }
  3196. struct npc_data *nd = npc_create_npc(m, x, y);
  3197. npc_parsename(nd, w3, start, buffer, filepath);
  3198. bool is_type_warp2 = (strncasecmp(w2, "warp2", 5) == 0);
  3199. if (!battle_config.warp_point_debug)
  3200. nd->class_ = JT_WARPNPC;
  3201. else
  3202. nd->class_ = JT_GUILD_FLAG;
  3203. nd->speed = 200;
  3204. nd->u.warp.mapindex = i;
  3205. nd->u.warp.x = to_x;
  3206. nd->u.warp.y = to_y;
  3207. nd->u.warp.xs = xs;
  3208. nd->u.warp.ys = ys;
  3209. #ifdef MAP_GENERATOR
  3210. nd->navi.warp_dest = {map_mapindex2mapid(i), to_x, to_y};
  3211. #endif
  3212. npc_warp++;
  3213. nd->bl.type = BL_NPC;
  3214. nd->subtype = NPCTYPE_WARP;
  3215. if (is_type_warp2)
  3216. nd->trigger_on_hidden = true;
  3217. else
  3218. nd->trigger_on_hidden = false;
  3219. map_addnpc(m, nd);
  3220. npc_setcells(nd);
  3221. if(map_addblock(&nd->bl)) //couldn't add on map
  3222. return strchr(start,'\n');
  3223. status_set_viewdata(&nd->bl, nd->class_);
  3224. status_change_init(&nd->bl);
  3225. unit_dataset(&nd->bl);
  3226. if( map_getmapdata(nd->bl.m)->users )
  3227. clif_spawn(&nd->bl);
  3228. strdb_put(npcname_db, nd->exname, nd);
  3229. // Check if there is a <state> in w2
  3230. if (is_type_warp2 && strcasecmp("warp2", w2) < 0 || !is_type_warp2 && strcasecmp("warp", w2) < 0) {
  3231. char state_name[128];
  3232. size_t length = strlen(w2);
  3233. int shift = (is_type_warp2 ? 6 : 5);
  3234. // state name
  3235. if (w2[shift-1] != '(' || w2[length-1] != ')' || length <= shift || length-shift >= sizeof(state_name))
  3236. ShowWarning("npc_parse_warp: Invalid npc state in file '%s', line '%d', defaulting to visible. w2=%s\n", filepath, strline(buffer,start-buffer), w2);
  3237. else {
  3238. safestrncpy(state_name, w2+shift, length-shift);
  3239. if (strcasecmp("CLOAKED", state_name) == 0)
  3240. nd->state = NPCVIEW_CLOAKON;
  3241. else if (strcasecmp("HIDDEN", state_name) == 0)
  3242. nd->state = NPCVIEW_HIDEON;
  3243. else if (strcasecmp("DISABLED", state_name) == 0)
  3244. nd->state = NPCVIEW_DISABLE;
  3245. else
  3246. ShowWarning("npc_parse_warp: Invalid npc state in file '%s', line '%d', defaulting to visible. w2=%s\n", filepath, strline(buffer,start-buffer), w2);
  3247. if (nd->state != NPCVIEW_ENABLE)
  3248. npc_enable_target(*nd, 0, nd->state);
  3249. }
  3250. }
  3251. return strchr(start,'\n');// continue
  3252. }
  3253. /**
  3254. * Parses a shop/cashshop npc.
  3255. * Line definition :
  3256. * <map name>,<x>,<y>,<facing>%TAB%shop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>{,<itemid>:<price>...}
  3257. * <map name>,<x>,<y>,<facing>%TAB%cashshop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>{,<itemid>:<price>...}
  3258. * <map name>,<x>,<y>,<facing>%TAB%itemshop%TAB%<NPC Name>%TAB%<sprite id>,<costitemid>{:<discount>},<itemid>:<price>{,<itemid>:<price>...}
  3259. * <map name>,<x>,<y>,<facing>%TAB%pointshop%TAB%<NPC Name>%TAB%<sprite id>,<costvariable>{:<discount>},<itemid>:<price>{,<itemid>:<price>...}
  3260. * <map name>,<x>,<y>,<facing>%TAB%marketshop%TAB%<NPC Name>%TAB%<sprite id>,<itemid>:<price>:<quantity>{,<itemid>:<price>:<quantity>...}
  3261. * @param w1 : word 1 before tab (<from map name>,<x>,<y>,<facing>)
  3262. * @param w2 : word 2 before tab (shop|cashshop|itemshop|pointshop|marketshop), keyword that sent us in this parsing
  3263. * @param w3 : word 3 before tab (<NPC Name>)
  3264. * @param w4 : word 4 before tab (<sprited id>,<shop definition...>)
  3265. * @param start : index to start parsing
  3266. * @param buffer : lines to parses
  3267. * @param filepath : filename with path wich we are parsing
  3268. * @return new index for next parsing
  3269. */
  3270. static const char* npc_parse_shop(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  3271. {
  3272. char *p, point_str[32];
  3273. int m, is_discount = 0;
  3274. uint16 dir;
  3275. short x, y;
  3276. t_itemid nameid = 0;
  3277. struct npc_data *nd;
  3278. enum npc_subtype type;
  3279. if( strcmp(w1,"-") == 0 )
  3280. {// 'floating' shop?
  3281. x = y = dir = 0;
  3282. m = -1;
  3283. }
  3284. else
  3285. {// w1=<map name>,<x>,<y>,<facing>
  3286. char mapname[MAP_NAME_LENGTH_EXT];
  3287. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4
  3288. || strchr(w4, ',') == nullptr )
  3289. {
  3290. 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);
  3291. return strchr(start,'\n');// skip and continue
  3292. }
  3293. m = map_mapname2mapid(mapname);
  3294. }
  3295. struct map_data *mapdata = map_getmapdata(m);
  3296. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  3297. 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));
  3298. }
  3299. if( !strcasecmp(w2,"cashshop") )
  3300. type = NPCTYPE_CASHSHOP;
  3301. else if( !strcasecmp(w2,"itemshop") )
  3302. type = NPCTYPE_ITEMSHOP;
  3303. else if( !strcasecmp(w2,"pointshop") )
  3304. type = NPCTYPE_POINTSHOP;
  3305. else if( !strcasecmp(w2, "marketshop") )
  3306. type = NPCTYPE_MARKETSHOP;
  3307. else
  3308. type = NPCTYPE_SHOP;
  3309. p = strchr(w4,',');
  3310. memset(point_str,'\0',sizeof(point_str));
  3311. switch(type) {
  3312. case NPCTYPE_ITEMSHOP: {
  3313. if (sscanf(p,",%u:%11d,",&nameid,&is_discount) < 1) {
  3314. 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);
  3315. return strchr(start,'\n'); // skip and continue
  3316. }
  3317. if (!item_db.exists(nameid)) {
  3318. ShowWarning("npc_parse_shop: Invalid item ID cost in file '%s', line '%d' (id '%u').\n", filepath, strline(buffer,start-buffer), nameid);
  3319. return strchr(start,'\n'); // skip and continue
  3320. }
  3321. p = strchr(p+1,',');
  3322. break;
  3323. }
  3324. case NPCTYPE_POINTSHOP: {
  3325. if (sscanf(p, ",%32[^,:]:%11d,",point_str,&is_discount) < 1) {
  3326. 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);
  3327. return strchr(start,'\n'); // skip and continue
  3328. }
  3329. switch(point_str[0]) {
  3330. case '$':
  3331. case '.':
  3332. case '\'':
  3333. 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);
  3334. return strchr(start,'\n'); // skip and continue
  3335. break;
  3336. }
  3337. if (point_str[strlen(point_str) - 1] == '$') {
  3338. 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);
  3339. return strchr(start,'\n'); // skip and continue
  3340. }
  3341. p = strchr(p+1,',');
  3342. break;
  3343. }
  3344. case NPCTYPE_MARKETSHOP:
  3345. #if PACKETVER < 20131223
  3346. 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);
  3347. return strchr(start, '\n'); // skip and continue
  3348. #else
  3349. is_discount = 0;
  3350. break;
  3351. #endif
  3352. default:
  3353. if( sscanf( p, ",%32[^,:]:%11d,", point_str, &is_discount ) == 2 ){
  3354. is_discount = 1;
  3355. }else{
  3356. if( !strcasecmp( point_str, "yes" ) ){
  3357. is_discount = 1;
  3358. }else if( !strcasecmp( point_str, "no" ) ){
  3359. is_discount = 0;
  3360. }else{
  3361. ShowError( "npc_parse_shop: unknown discount setting %s\n", point_str );
  3362. return strchr( start, '\n' ); // skip and continue
  3363. }
  3364. p = strchr( p + 1, ',' );
  3365. }
  3366. break;
  3367. }
  3368. nd = npc_create_npc(m, x, y);
  3369. nd->u.shop.count = 0;
  3370. while ( p ) {
  3371. t_itemid nameid2;
  3372. int32 qty = -1;
  3373. int value;
  3374. bool skip = false;
  3375. if( p == nullptr )
  3376. break;
  3377. switch(type) {
  3378. case NPCTYPE_MARKETSHOP:
  3379. #if PACKETVER >= 20131223
  3380. if (sscanf(p, ",%u:%11d:%11d", &nameid2, &value, &qty) != 3) {
  3381. 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);
  3382. skip = true;
  3383. }
  3384. #endif
  3385. break;
  3386. default:
  3387. if (sscanf(p, ",%u:%11d", &nameid2, &value) != 2) {
  3388. 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);
  3389. skip = true;
  3390. }
  3391. break;
  3392. }
  3393. if (skip)
  3394. break;
  3395. std::shared_ptr<item_data> id = item_db.find(nameid2);
  3396. if( id == nullptr ) {
  3397. ShowWarning("npc_parse_shop: Invalid sell item in file '%s', line '%d' (id '%u').\n", filepath, strline(buffer,start-buffer), nameid2);
  3398. p = strchr(p+1,',');
  3399. continue;
  3400. }
  3401. if( value < 0 ) {
  3402. if (type == NPCTYPE_SHOP || type == NPCTYPE_MARKETSHOP) value = id->value_buy;
  3403. else value = 0; // Cashshop doesn't have a "buy price" in the item_db
  3404. }
  3405. if (value == 0 && (type == NPCTYPE_SHOP || type == NPCTYPE_MARKETSHOP)) { // NPC selling items for free!
  3406. ShowWarning("npc_parse_shop: Item %s [%u] is being sold for FREE in file '%s', line '%d'.\n",
  3407. id->name.c_str(), nameid2, filepath, strline(buffer,start-buffer));
  3408. }
  3409. 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
  3410. 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",
  3411. id->name.c_str(), nameid2, value, (int)(value*0.75), id->value_sell, (int)(id->value_sell*1.24), filepath, strline(buffer,start-buffer));
  3412. }
  3413. if (type == NPCTYPE_MARKETSHOP && qty < -1) {
  3414. ShowWarning("npc_parse_shop: Item %s [%u] is stocked with invalid value %hd, changed to unlimited (-1). File '%s', line '%d'.\n",
  3415. id->name.c_str(), nameid2, qty, filepath, strline(buffer,start-buffer));
  3416. qty = -1;
  3417. }
  3418. //for logs filters, atcommands and iteminfo script command
  3419. if( id->maxchance == 0 )
  3420. id->maxchance = -1; // -1 would show that the item's sold in NPC Shop
  3421. #if PACKETVER >= 20131223
  3422. if (nd->u.shop.count && type == NPCTYPE_MARKETSHOP) {
  3423. uint16 i;
  3424. // Duplicate entry? Replace the value
  3425. ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid);
  3426. if (i != nd->u.shop.count) {
  3427. nd->u.shop.shop_item[i].qty = qty;
  3428. nd->u.shop.shop_item[i].value = value;
  3429. p = strchr(p+1,',');
  3430. continue;
  3431. }
  3432. }
  3433. #endif
  3434. RECREATE(nd->u.shop.shop_item, struct npc_item_list,nd->u.shop.count+1);
  3435. nd->u.shop.shop_item[nd->u.shop.count].nameid = nameid2;
  3436. nd->u.shop.shop_item[nd->u.shop.count].value = value;
  3437. #if PACKETVER >= 20131223
  3438. nd->u.shop.shop_item[nd->u.shop.count].flag = 0;
  3439. if (type == NPCTYPE_MARKETSHOP )
  3440. nd->u.shop.shop_item[nd->u.shop.count].qty = qty;
  3441. #endif
  3442. nd->u.shop.count++;
  3443. p = strchr(p+1,',');
  3444. }
  3445. if( nd->u.shop.count == 0 ) {
  3446. ShowWarning("npc_parse_shop: Ignoring empty shop in file '%s', line '%d'.\n", filepath, strline(buffer,start-buffer));
  3447. nd->~npc_data();
  3448. aFree(nd);
  3449. return strchr(start,'\n');// continue
  3450. }
  3451. if( type == NPCTYPE_ITEMSHOP ){
  3452. // Item shop currency
  3453. nd->u.shop.itemshop_nameid = nameid;
  3454. }else if( type == NPCTYPE_POINTSHOP ){
  3455. // Point shop currency
  3456. safestrncpy( nd->u.shop.pointshop_str, point_str, strlen( point_str ) + 1 );
  3457. }
  3458. nd->u.shop.discount = is_discount > 0;
  3459. npc_parsename(nd, w3, start, buffer, filepath);
  3460. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  3461. nd->speed = 200;
  3462. ++npc_shop;
  3463. nd->bl.type = BL_NPC;
  3464. nd->subtype = type;
  3465. #if PACKETVER >= 20131223
  3466. // Insert market data to table
  3467. if (nd->subtype == NPCTYPE_MARKETSHOP) {
  3468. uint16 i;
  3469. for (i = 0; i < nd->u.shop.count; i++)
  3470. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[i]);
  3471. }
  3472. #endif
  3473. if( m >= 0 )
  3474. {// normal shop npc
  3475. map_addnpc(m,nd);
  3476. if(map_addblock(&nd->bl))
  3477. return strchr(start,'\n');
  3478. status_change_init(&nd->bl);
  3479. unit_dataset(&nd->bl);
  3480. nd->ud.dir = (uint8)dir;
  3481. if( nd->class_ != JT_FAKENPC ){
  3482. status_set_viewdata(&nd->bl, nd->class_);
  3483. if( map_getmapdata(nd->bl.m)->users )
  3484. clif_spawn(&nd->bl);
  3485. }
  3486. } else
  3487. {// 'floating' shop?
  3488. map_addiddb(&nd->bl);
  3489. }
  3490. strdb_put(npcname_db, nd->exname, nd);
  3491. return strchr(start,'\n');// continue
  3492. }
  3493. /** [Cydh]
  3494. * Check if the shop is affected by discount or not
  3495. * @param type Type of NPC shop (enum npc_subtype)
  3496. * @param discount Discount flag of NPC shop
  3497. * @return bool 'true' is discountable, 'false' otherwise
  3498. */
  3499. bool npc_shop_discount( struct npc_data* nd ){
  3500. switch( nd->subtype ){
  3501. case NPCTYPE_ITEMSHOP:
  3502. return nd->u.shop.discount || ( battle_config.discount_item_point_shop&1 );
  3503. case NPCTYPE_POINTSHOP:
  3504. return nd->u.shop.discount || ( battle_config.discount_item_point_shop&2 );
  3505. default:
  3506. return nd->u.shop.discount;
  3507. }
  3508. }
  3509. /**
  3510. * NPC other label
  3511. * Not sure, seem to add label in a chainlink
  3512. * @see DBApply
  3513. */
  3514. int npc_convertlabel_db(DBKey key, DBData *data, va_list ap)
  3515. {
  3516. const char* lname = (const char*)key.str;
  3517. int lpos = db_data2i(data);
  3518. struct npc_label_list** label_list;
  3519. int* label_list_num;
  3520. const char* filepath;
  3521. struct npc_label_list* label;
  3522. const char *p;
  3523. int len;
  3524. nullpo_ret(label_list = va_arg(ap,struct npc_label_list**));
  3525. nullpo_ret(label_list_num = va_arg(ap,int*));
  3526. nullpo_ret(filepath = va_arg(ap,const char*));
  3527. // In case of labels not terminated with ':', for user defined function support
  3528. p = lname;
  3529. while( ISALNUM(*p) || *p == '_' )
  3530. ++p;
  3531. len = p-lname;
  3532. // here we check if the label fit into the buffer
  3533. if( len > NAME_LENGTH )
  3534. {
  3535. ShowError("npc_parse_script: label name longer than %d chars! '%s'\n (%s)", NAME_LENGTH, lname, filepath);
  3536. return 0;
  3537. }
  3538. if( *label_list == nullptr )
  3539. {
  3540. *label_list = (struct npc_label_list *) aCalloc (1, sizeof(struct npc_label_list));
  3541. *label_list_num = 0;
  3542. } else
  3543. *label_list = (struct npc_label_list *) aRealloc (*label_list, sizeof(struct npc_label_list)*(*label_list_num+1));
  3544. label = *label_list+*label_list_num;
  3545. safestrncpy(label->name, lname, sizeof(label->name));
  3546. label->pos = lpos;
  3547. ++(*label_list_num);
  3548. return 0;
  3549. }
  3550. // Skip the contents of a script.
  3551. static const char* npc_skip_script(const char* start, const char* buffer, const char* filepath)
  3552. {
  3553. const char* p;
  3554. int curly_count;
  3555. if( start == nullptr )
  3556. return nullptr;// nothing to skip
  3557. // initial bracket (assumes the previous part is ok)
  3558. p = strchr(start,'{');
  3559. if( p == nullptr )
  3560. {
  3561. ShowError("npc_skip_script: Missing left curly in file '%s', line'%d'.", filepath, strline(buffer,start-buffer));
  3562. return nullptr;// can't continue
  3563. }
  3564. // skip everything
  3565. for( curly_count = 1; curly_count > 0 ; )
  3566. {
  3567. p = skip_space(p+1) ;
  3568. if( *p == '}' )
  3569. {// right curly
  3570. --curly_count;
  3571. }
  3572. else if( *p == '{' )
  3573. {// left curly
  3574. ++curly_count;
  3575. }
  3576. else if( *p == '"' )
  3577. {// string
  3578. for( ++p; *p != '"' ; ++p )
  3579. {
  3580. if( *p == '\\' && (unsigned char)p[-1] <= 0x7e )
  3581. ++p;// escape sequence (not part of a multibyte character)
  3582. else if( *p == '\0' )
  3583. {
  3584. script_error(buffer, filepath, 0, "Unexpected end of string.", p);
  3585. return nullptr;// can't continue
  3586. }
  3587. else if( *p == '\n' )
  3588. {
  3589. script_error(buffer, filepath, 0, "Unexpected newline at string.", p);
  3590. return nullptr;// can't continue
  3591. }
  3592. }
  3593. }
  3594. else if( *p == '\0' )
  3595. {// end of buffer
  3596. ShowError("Missing %d right curlys at file '%s', line '%d'.\n", curly_count, filepath, strline(buffer,p-buffer));
  3597. return nullptr;// can't continue
  3598. }
  3599. }
  3600. return p+1;// return after the last '}'
  3601. }
  3602. /**
  3603. * Parses a npc script.
  3604. * Line definition :
  3605. * <map name>,<x>,<y>,<facing>%TAB%script(<state)%TAB%<NPC Name>%TAB%<sprite id>,{<code>}
  3606. * <map name>,<x>,<y>,<facing>%TAB%script(<state)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>,{<code>} * @TODO missing cashshop line definition
  3607. * @param w1 : word 1 before tab (<from map name>,<x>,<y>,<facing>)
  3608. * @param w2 : word 2 before tab (script), keyword that sent us in this parsing
  3609. * @param w3 : word 3 before tab (<NPC Name>)
  3610. * @param w4 : word 4 before tab (<sprited id>,<code>)
  3611. * @param start : index to start parsing
  3612. * @param buffer : lines to parses
  3613. * @param filepath : filename with path wich we are parsing
  3614. * @return new index for next parsing
  3615. */
  3616. static const char* npc_parse_script(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath) {
  3617. int16 dir = 0;
  3618. short m, x, y, xs = 0, ys = 0; // [Valaris] thanks to fov
  3619. struct script_code *script;
  3620. int i;
  3621. const char* end;
  3622. const char* script_start;
  3623. struct npc_label_list* label_list;
  3624. int label_list_num;
  3625. struct npc_data* nd;
  3626. if( strcmp(w1, "-") == 0 )
  3627. {// floating npc
  3628. x = 0;
  3629. y = 0;
  3630. m = -1;
  3631. }
  3632. else
  3633. {// npc in a map
  3634. char mapname[MAP_NAME_LENGTH_EXT];
  3635. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4 )
  3636. {
  3637. 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);
  3638. return nullptr;// unknown format, don't continue
  3639. }
  3640. m = map_mapname2mapid(mapname);
  3641. }
  3642. script_start = strstr(start,",{");
  3643. end = strchr(start,'\n');
  3644. if( strstr(w4,",{") == nullptr || script_start == nullptr || (end != nullptr && script_start > end) )
  3645. {
  3646. 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);
  3647. return nullptr;// can't continue
  3648. }
  3649. ++script_start;
  3650. end = npc_skip_script(script_start, buffer, filepath);
  3651. if( end == nullptr )
  3652. return nullptr;// (simple) parse error, don't continue
  3653. script = parse_script(script_start, filepath, strline(buffer,script_start-buffer), SCRIPT_USE_LABEL_DB);
  3654. label_list = nullptr;
  3655. label_list_num = 0;
  3656. if( script )
  3657. {
  3658. DBMap* label_db = script_get_label_db();
  3659. label_db->foreach(label_db, npc_convertlabel_db, &label_list, &label_list_num, filepath);
  3660. db_clear(label_db); // not needed anymore, so clear the db
  3661. }
  3662. nd = npc_create_npc(m, x, y);
  3663. if( sscanf(w4, "%*[^,],%6hd,%6hd", &xs, &ys) == 2 )
  3664. {// OnTouch area defined
  3665. nd->u.scr.xs = xs;
  3666. nd->u.scr.ys = ys;
  3667. }
  3668. else
  3669. {// no OnTouch area
  3670. nd->u.scr.xs = -1;
  3671. nd->u.scr.ys = -1;
  3672. }
  3673. npc_parsename(nd, w3, start, buffer, filepath);
  3674. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  3675. nd->speed = 200;
  3676. nd->u.scr.script = script;
  3677. nd->u.scr.label_list = label_list;
  3678. nd->u.scr.label_list_num = label_list_num;
  3679. ++npc_script;
  3680. nd->bl.type = BL_NPC;
  3681. nd->subtype = NPCTYPE_SCRIPT;
  3682. if( m >= 0 )
  3683. {
  3684. map_addnpc(m, nd);
  3685. status_change_init(&nd->bl);
  3686. unit_dataset(&nd->bl);
  3687. nd->ud.dir = (uint8)dir;
  3688. npc_setcells(nd);
  3689. if(map_addblock(&nd->bl))
  3690. return nullptr;
  3691. if( nd->class_ != JT_FAKENPC )
  3692. {
  3693. status_set_viewdata(&nd->bl, nd->class_);
  3694. if( map_getmapdata(nd->bl.m)->users )
  3695. clif_spawn(&nd->bl);
  3696. }
  3697. }
  3698. else
  3699. {
  3700. // we skip map_addnpc, but still add it to the list of ID's
  3701. map_addiddb(&nd->bl);
  3702. }
  3703. strdb_put(npcname_db, nd->exname, nd);
  3704. // Check if there is a <state> in w2
  3705. if (strcasecmp("script", w2) < 0) {
  3706. char state_name[128];
  3707. size_t length = strlen(w2);
  3708. int shift = 7;
  3709. // state name
  3710. if (w2[shift-1] != '(' || w2[length-1] != ')' || length <= shift || length-shift >= sizeof(state_name))
  3711. ShowWarning("npc_parse_script: Invalid npc state in file '%s', line '%d', defaulting to visible. w2=%s\n", filepath, strline(buffer,start-buffer), w2);
  3712. else {
  3713. safestrncpy(state_name, w2+shift, length-shift);
  3714. if (strcasecmp("CLOAKED", state_name) == 0)
  3715. nd->state = NPCVIEW_CLOAKON;
  3716. else if (strcasecmp("HIDDEN", state_name) == 0)
  3717. nd->state = NPCVIEW_HIDEON;
  3718. else if (strcasecmp("DISABLED", state_name) == 0)
  3719. nd->state = NPCVIEW_DISABLE;
  3720. else
  3721. ShowWarning("npc_parse_script: Invalid npc state in file '%s', line '%d', defaulting to visible. w2=%s\n", filepath, strline(buffer,start-buffer), w2);
  3722. if (nd->state != NPCVIEW_ENABLE)
  3723. npc_enable_target(*nd, 0, nd->state);
  3724. }
  3725. }
  3726. //-----------------------------------------
  3727. // Loop through labels to export them as necessary
  3728. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  3729. if (npc_event_export(nd, i)) {
  3730. ShowWarning("npc_parse_script : duplicate event %s::%s (%s)\n",
  3731. nd->exname, nd->u.scr.label_list[i].name, filepath);
  3732. }
  3733. npc_timerevent_export(nd, i);
  3734. }
  3735. nd->u.scr.timerid = INVALID_TIMER;
  3736. return end;
  3737. }
  3738. /// Duplicate a warp, shop, cashshop or script. [Orcao]
  3739. /// warp: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<spanx>,<spany>
  3740. /// shop/cashshop/npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  3741. /// shop/cashshop/npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  3742. /// npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  3743. /// npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  3744. 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 ){
  3745. short x, y, m, xs = -1, ys = -1;
  3746. int16 dir;
  3747. char srcname[128];
  3748. int i;
  3749. const char* end;
  3750. size_t length;
  3751. int src_id;
  3752. int type;
  3753. struct npc_data* nd;
  3754. struct npc_data* dnd;
  3755. end = strchr(start,'\n');
  3756. length = strlen(w2);
  3757. // get the npc being duplicated
  3758. if( w2[length-1] != ')' || length <= 11 || length-11 >= sizeof(srcname) )
  3759. {// does not match 'duplicate(%127s)', name is empty or too long
  3760. ShowError("npc_parse_script: bad duplicate name in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), w2);
  3761. return end;// next line, try to continue
  3762. }
  3763. safestrncpy(srcname, w2+10, length-10);
  3764. dnd = npc_name2id(srcname);
  3765. if( dnd == nullptr) {
  3766. ShowError("npc_parse_script: original npc not found for duplicate in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), srcname);
  3767. return end;// next line, try to continue
  3768. }
  3769. src_id = dnd->src_id ? dnd->src_id : dnd->bl.id;
  3770. type = dnd->subtype;
  3771. // get placement
  3772. 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
  3773. x = y = dir = 0;
  3774. m = -1;
  3775. } else {
  3776. char mapname[MAP_NAME_LENGTH_EXT];
  3777. if( sscanf(w1, "%15[^,],%6hd,%6hd,%4hd", mapname, &x, &y, &dir) != 4 ) { // <map name>,<x>,<y>,<facing>
  3778. 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);
  3779. return end;// next line, try to continue
  3780. }
  3781. m = map_mapname2mapid(mapname);
  3782. }
  3783. struct map_data *mapdata = map_getmapdata(m);
  3784. if( m != -1 && ( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys ) ) {
  3785. 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));
  3786. }
  3787. if( type == NPCTYPE_WARP && sscanf(w4, "%6hd,%6hd", &xs, &ys) == 2 );// <spanx>,<spany>
  3788. else if( type == NPCTYPE_SCRIPT && sscanf(w4, "%*[^,],%6hd,%6hd", &xs, &ys) == 2);// <sprite id>,<triggerX>,<triggerY>
  3789. else if( type == NPCTYPE_WARP ) {
  3790. 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);
  3791. return end;// next line, try to continue
  3792. }
  3793. nd = npc_create_npc(m, x, y);
  3794. npc_parsename(nd, w3, start, buffer, filepath);
  3795. nd->class_ = m == -1 ? JT_FAKENPC : npc_parseview(w4, start, buffer, filepath);
  3796. nd->speed = 200;
  3797. nd->src_id = src_id;
  3798. nd->bl.type = BL_NPC;
  3799. nd->subtype = (enum npc_subtype)type;
  3800. if( owner != nullptr ){
  3801. nd->dynamicnpc.owner_char_id = owner->status.char_id;
  3802. owner->npc_id_dynamic.push_back(nd->bl.id);
  3803. }
  3804. switch( type ) {
  3805. case NPCTYPE_SCRIPT:
  3806. ++npc_script;
  3807. nd->u.scr.xs = xs;
  3808. nd->u.scr.ys = ys;
  3809. nd->u.scr.script = dnd->u.scr.script;
  3810. nd->u.scr.label_list = dnd->u.scr.label_list;
  3811. nd->u.scr.label_list_num = dnd->u.scr.label_list_num;
  3812. break;
  3813. case NPCTYPE_SHOP:
  3814. case NPCTYPE_CASHSHOP:
  3815. case NPCTYPE_ITEMSHOP:
  3816. case NPCTYPE_POINTSHOP:
  3817. case NPCTYPE_MARKETSHOP:
  3818. ++npc_shop;
  3819. safestrncpy( nd->u.shop.pointshop_str, dnd->u.shop.pointshop_str, strlen( dnd->u.shop.pointshop_str ) );
  3820. nd->u.shop.itemshop_nameid = dnd->u.shop.itemshop_nameid;
  3821. nd->u.shop.shop_item = dnd->u.shop.shop_item;
  3822. nd->u.shop.count = dnd->u.shop.count;
  3823. nd->u.shop.discount = dnd->u.shop.discount;
  3824. break;
  3825. case NPCTYPE_WARP:
  3826. ++npc_warp;
  3827. if( !battle_config.warp_point_debug )
  3828. nd->class_ = JT_WARPNPC;
  3829. else
  3830. nd->class_ = JT_GUILD_FLAG;
  3831. nd->u.warp.xs = xs;
  3832. nd->u.warp.ys = ys;
  3833. nd->u.warp.mapindex = dnd->u.warp.mapindex;
  3834. nd->u.warp.x = dnd->u.warp.x;
  3835. nd->u.warp.y = dnd->u.warp.y;
  3836. nd->trigger_on_hidden = dnd->trigger_on_hidden;
  3837. break;
  3838. }
  3839. //Add the npc to its location
  3840. if( m >= 0 ) {
  3841. map_addnpc(m, nd);
  3842. status_change_init(&nd->bl);
  3843. unit_dataset(&nd->bl);
  3844. nd->ud.dir = (uint8)dir;
  3845. npc_setcells(nd);
  3846. if(map_addblock(&nd->bl))
  3847. return end;
  3848. if( nd->class_ != JT_FAKENPC ) {
  3849. status_set_viewdata(&nd->bl, nd->class_);
  3850. if( map_getmapdata(nd->bl.m)->users )
  3851. clif_spawn(&nd->bl);
  3852. }
  3853. } else {
  3854. // we skip map_addnpc, but still add it to the list of ID's
  3855. map_addiddb(&nd->bl);
  3856. }
  3857. strdb_put(npcname_db, nd->exname, nd);
  3858. // copy the original npc state
  3859. if (dnd->state != NPCVIEW_ENABLE)
  3860. npc_enable_target(*nd, 0, dnd->state);
  3861. nd->state = dnd->state;
  3862. if( type != NPCTYPE_SCRIPT )
  3863. return end;
  3864. //-----------------------------------------
  3865. // Loop through labels to export them as necessary
  3866. for (i = 0; i < nd->u.scr.label_list_num; i++) {
  3867. if (npc_event_export(nd, i)) {
  3868. ShowWarning("npc_parse_duplicate : duplicate event %s::%s (%s)\n",
  3869. nd->exname, nd->u.scr.label_list[i].name, filepath);
  3870. }
  3871. npc_timerevent_export(nd, i);
  3872. }
  3873. if(!strcmp(filepath,"INSTANCING")) //Instance NPCs will use this for commands
  3874. nd->instance_id = mapdata->instance_id;
  3875. nd->u.scr.timerid = INVALID_TIMER;
  3876. return end;
  3877. }
  3878. int npc_duplicate4instance(struct npc_data *snd, int16 m) {
  3879. char newname[NPC_NAME_LENGTH+1];
  3880. struct map_data *mapdata = map_getmapdata(m);
  3881. if( mapdata->instance_id <= 0 )
  3882. return 1;
  3883. snprintf(newname, ARRAYLENGTH(newname), "dup_%d_%d", mapdata->instance_id, snd->bl.id);
  3884. if( npc_name2id(newname) != nullptr ) { // Name already in use
  3885. 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);
  3886. return 1;
  3887. }
  3888. if( snd->subtype == NPCTYPE_WARP ) { // Adjust destination, if instanced
  3889. struct npc_data *wnd = nullptr; // New NPC
  3890. std::shared_ptr<s_instance_data> idata = util::umap_find(instances, mapdata->instance_id);
  3891. int dm = map_mapindex2mapid(snd->u.warp.mapindex), imap = 0;
  3892. if( dm < 0 ) return 1;
  3893. for (const auto &it : idata->map) {
  3894. if (it.m && map_mapname2mapid(map_getmapdata(it.src_m)->name) == dm) {
  3895. imap = map_mapname2mapid(map_getmapdata(it.m)->name);
  3896. break; // Instance map matches destination, update to instance map
  3897. }
  3898. }
  3899. if(!imap)
  3900. imap = map_mapname2mapid(map_getmapdata(dm)->name);
  3901. if( imap == -1 ) {
  3902. 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);
  3903. return 1;
  3904. }
  3905. wnd = npc_create_npc(m, snd->bl.x, snd->bl.y);
  3906. safestrncpy(wnd->name, "", ARRAYLENGTH(wnd->name));
  3907. safestrncpy(wnd->exname, newname, ARRAYLENGTH(wnd->exname));
  3908. wnd->class_ = JT_WARPNPC;
  3909. wnd->speed = 200;
  3910. wnd->u.warp.mapindex = map_id2index(imap);
  3911. wnd->u.warp.x = snd->u.warp.x;
  3912. wnd->u.warp.y = snd->u.warp.y;
  3913. wnd->u.warp.xs = snd->u.warp.xs;
  3914. wnd->u.warp.ys = snd->u.warp.ys;
  3915. wnd->bl.type = BL_NPC;
  3916. wnd->subtype = NPCTYPE_WARP;
  3917. wnd->trigger_on_hidden = snd->trigger_on_hidden;
  3918. wnd->src_id = snd->src_id ? snd->src_id : snd->bl.id;
  3919. map_addnpc(m, wnd);
  3920. npc_setcells(wnd);
  3921. if(map_addblock(&wnd->bl))
  3922. return 1;
  3923. status_set_viewdata(&wnd->bl, wnd->class_);
  3924. status_change_init(&wnd->bl);
  3925. unit_dataset(&wnd->bl);
  3926. if( map_getmapdata(wnd->bl.m)->users )
  3927. clif_spawn(&wnd->bl);
  3928. strdb_put(npcname_db, wnd->exname, wnd);
  3929. // copy the original npc state
  3930. if (snd->state != NPCVIEW_ENABLE)
  3931. npc_enable_target(*wnd, 0, snd->state);
  3932. wnd->state = snd->state;
  3933. } else {
  3934. static char w1[128], w2[128], w3[128], w4[128];
  3935. const char* stat_buf = "- call from instancing subsystem -\n";
  3936. snprintf(w1, sizeof(w1), "%s,%d,%d,%d", mapdata->name, snd->bl.x, snd->bl.y, snd->ud.dir);
  3937. snprintf(w2, sizeof(w2), "duplicate(%s)", snd->exname);
  3938. snprintf(w3, sizeof(w3), "%s::%s", snd->name, newname);
  3939. if( snd->u.scr.xs >= 0 && snd->u.scr.ys >= 0 )
  3940. snprintf(w4, sizeof(w4), "%d,%d,%d", snd->class_, snd->u.scr.xs, snd->u.scr.ys); // Touch Area
  3941. else
  3942. snprintf(w4, sizeof(w4), "%d", snd->class_);
  3943. npc_parse_duplicate(w1, w2, w3, w4, stat_buf, stat_buf, "INSTANCING");
  3944. }
  3945. return 0;
  3946. }
  3947. int npc_instanceinit(struct npc_data* nd)
  3948. {
  3949. struct event_data *ev;
  3950. char evname[EVENT_NAME_LENGTH];
  3951. snprintf(evname, ARRAYLENGTH(evname), "%s::%s", nd->exname, script_config.instance_init_event_name);
  3952. if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) )
  3953. run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
  3954. return 0;
  3955. }
  3956. int npc_instancedestroy(struct npc_data* nd)
  3957. {
  3958. struct event_data *ev;
  3959. char evname[EVENT_NAME_LENGTH];
  3960. snprintf(evname, ARRAYLENGTH(evname), "%s::%s", nd->exname, script_config.instance_destroy_event_name);
  3961. if( ( ev = (struct event_data*)strdb_get(ev_db, evname) ) )
  3962. run_script(nd->u.scr.script,ev->pos,0,nd->bl.id);
  3963. return 0;
  3964. }
  3965. #if PACKETVER >= 20131223
  3966. /**
  3967. * Saves persistent NPC Market Data into SQL
  3968. * @param exname NPC exname
  3969. * @param nameid Item ID
  3970. * @param qty Stock
  3971. **/
  3972. void npc_market_tosql(const char *exname, struct npc_item_list *list) {
  3973. SqlStmt* stmt = SqlStmt_Malloc(mmysql_handle);
  3974. if (SQL_ERROR == SqlStmt_Prepare(stmt, "REPLACE INTO `%s` (`name`,`nameid`,`price`,`amount`,`flag`) VALUES ('%s','%u','%d','%d','%" PRIu8 "')",
  3975. market_table, exname, list->nameid, list->value, list->qty, list->flag) ||
  3976. SQL_ERROR == SqlStmt_Execute(stmt))
  3977. SqlStmt_ShowDebug(stmt);
  3978. SqlStmt_Free(stmt);
  3979. }
  3980. /**
  3981. * Removes persistent NPC Market Data from SQL
  3982. * @param exname NPC exname
  3983. * @param nameid Item ID
  3984. * @param clear True: will removes all records related with the NPC
  3985. **/
  3986. void npc_market_delfromsql_(const char *exname, t_itemid nameid, bool clear) {
  3987. SqlStmt* stmt = SqlStmt_Malloc(mmysql_handle);
  3988. if (clear) {
  3989. if( SQL_ERROR == SqlStmt_Prepare(stmt, "DELETE FROM `%s` WHERE `name`='%s'", market_table, exname) ||
  3990. SQL_ERROR == SqlStmt_Execute(stmt))
  3991. SqlStmt_ShowDebug(stmt);
  3992. } else {
  3993. if (SQL_ERROR == SqlStmt_Prepare(stmt, "DELETE FROM `%s` WHERE `name`='%s' AND `nameid`='%u' LIMIT 1", market_table, exname, nameid) ||
  3994. SQL_ERROR == SqlStmt_Execute(stmt))
  3995. SqlStmt_ShowDebug(stmt);
  3996. }
  3997. SqlStmt_Free(stmt);
  3998. }
  3999. /**
  4000. * Check NPC Market Shop for each entry
  4001. **/
  4002. static int npc_market_checkall_sub(DBKey key, DBData *data, va_list ap) {
  4003. struct s_npc_market *market = (struct s_npc_market *)db_data2ptr(data);
  4004. struct npc_data *nd = nullptr;
  4005. uint16 i;
  4006. if (!market)
  4007. return 1;
  4008. nd = npc_name2id(market->exname);
  4009. if (!nd) {
  4010. ShowInfo("npc_market_checkall_sub: NPC '%s' not found, removing...\n", market->exname);
  4011. npc_market_clearfromsql(market->exname);
  4012. return 1;
  4013. }
  4014. else if (nd->subtype != NPCTYPE_MARKETSHOP || !nd->u.shop.shop_item || !nd->u.shop.count ) {
  4015. ShowError("npc_market_checkall_sub: NPC '%s' is not proper for market, removing...\n", nd->exname);
  4016. npc_market_clearfromsql(nd->exname);
  4017. return 1;
  4018. }
  4019. if (!market->count || !market->list)
  4020. return 1;
  4021. for (i = 0; i < market->count; i++) {
  4022. struct npc_item_list *list = &market->list[i];
  4023. uint16 j;
  4024. if (!item_db.exists(list->nameid)) {
  4025. ShowError("npc_market_checkall_sub: NPC '%s' sells invalid item '%u', deleting...\n", nd->exname, list->nameid);
  4026. npc_market_delfromsql(nd->exname, list->nameid);
  4027. continue;
  4028. }
  4029. // Reloading stock from `market` table
  4030. ARR_FIND(0, nd->u.shop.count, j, nd->u.shop.shop_item[j].nameid == list->nameid);
  4031. if (j != nd->u.shop.count) {
  4032. nd->u.shop.shop_item[j].value = list->value;
  4033. if (nd->u.shop.shop_item[j].qty > -1)
  4034. nd->u.shop.shop_item[j].qty = list->qty;
  4035. nd->u.shop.shop_item[j].flag = list->flag;
  4036. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[j]);
  4037. continue;
  4038. }
  4039. if (list->flag&1) { // Item added by npcshopitem/npcshopadditem, add new entry
  4040. RECREATE(nd->u.shop.shop_item, struct npc_item_list, nd->u.shop.count+1);
  4041. nd->u.shop.shop_item[j].nameid = list->nameid;
  4042. nd->u.shop.shop_item[j].value = list->value;
  4043. if (nd->u.shop.shop_item[j].qty > -1)
  4044. nd->u.shop.shop_item[j].qty = list->qty;
  4045. nd->u.shop.shop_item[j].flag = list->flag;
  4046. nd->u.shop.count++;
  4047. npc_market_tosql(nd->exname, &nd->u.shop.shop_item[j]);
  4048. }
  4049. else { // Removing "out-of-date" entry
  4050. ShowError("npc_market_checkall_sub: NPC '%s' does not sell item %u (qty %d), deleting...\n", nd->exname, list->nameid, list->qty);
  4051. npc_market_delfromsql(nd->exname, list->nameid);
  4052. }
  4053. }
  4054. return 0;
  4055. }
  4056. /**
  4057. * Clear NPC market single entry
  4058. **/
  4059. static int npc_market_free(DBKey key, DBData *data, va_list ap) {
  4060. struct s_npc_market *market = (struct s_npc_market *)db_data2ptr(data);
  4061. if (!market)
  4062. return 0;
  4063. if (market->list) {
  4064. aFree(market->list);
  4065. market->list = nullptr;
  4066. }
  4067. aFree(market);
  4068. return 1;
  4069. }
  4070. /**
  4071. * Check all existing NPC Market Shop after first loading map-server or after reloading scripts.
  4072. * Overwrite stocks from NPC by using stock entries from `market` table.
  4073. **/
  4074. static void npc_market_checkall(void) {
  4075. if (!db_size(NPCMarketDB))
  4076. return;
  4077. else {
  4078. ShowInfo("Checking '" CL_WHITE "%d" CL_RESET "' NPC Markets...\n", db_size(NPCMarketDB));
  4079. NPCMarketDB->foreach(NPCMarketDB, npc_market_checkall_sub);
  4080. ShowStatus("Done checking '" CL_WHITE "%d" CL_RESET "' NPC Markets.\n", db_size(NPCMarketDB));
  4081. NPCMarketDB->clear(NPCMarketDB, npc_market_free);
  4082. }
  4083. }
  4084. /**
  4085. * Loads persistent NPC Market Data from SQL, use the records after NPCs init'd to reuse the stock values.
  4086. **/
  4087. static void npc_market_fromsql(void) {
  4088. uint32 count = 0;
  4089. if (SQL_ERROR == Sql_Query(mmysql_handle, "SELECT `name`,`nameid`,`price`,`amount`,`flag` FROM `%s` ORDER BY `name`", market_table)) {
  4090. Sql_ShowDebug(mmysql_handle);
  4091. return;
  4092. }
  4093. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle)) {
  4094. char *data;
  4095. struct s_npc_market *market;
  4096. struct npc_item_list list;
  4097. Sql_GetData(mmysql_handle, 0, &data, nullptr);
  4098. if (!(market = (struct s_npc_market *)strdb_get(NPCMarketDB,data))) {
  4099. CREATE(market, struct s_npc_market, 1);
  4100. market->count = 0;
  4101. safestrncpy(market->exname, data, NPC_NAME_LENGTH);
  4102. strdb_put(NPCMarketDB, market->exname, market);
  4103. }
  4104. Sql_GetData(mmysql_handle, 1, &data, nullptr); list.nameid = strtoul(data, nullptr, 10);
  4105. Sql_GetData(mmysql_handle, 2, &data, nullptr); list.value = atoi(data);
  4106. Sql_GetData(mmysql_handle, 3, &data, nullptr); list.qty = atoi(data);
  4107. Sql_GetData(mmysql_handle, 4, &data, nullptr); list.flag = atoi(data);
  4108. std::shared_ptr<item_data> id = item_db.find(list.nameid);
  4109. if (id == nullptr) {
  4110. ShowWarning("npc_market_fromsql: Invalid sell item in table '%s' (id '%u').\n", market_table, list.nameid);
  4111. continue;
  4112. }
  4113. if (list.value * 0.75 < id->value_sell * 1.24) { // Exploit possible: you can buy and sell back with profit
  4114. 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",
  4115. id->name.c_str(), list.nameid, list.value, (int)(list.value * 0.75), id->value_sell, (int)(id->value_sell * 1.24), market_table);
  4116. list.value = id->value_sell;
  4117. }
  4118. RECREATE(market->list, struct npc_item_list, market->count+1);
  4119. market->list[market->count++] = list;
  4120. count++;
  4121. }
  4122. Sql_FreeResult(mmysql_handle);
  4123. 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);
  4124. }
  4125. #endif
  4126. //Set mapcell CELL_NPC to trigger event later
  4127. void npc_setcells(struct npc_data* nd)
  4128. {
  4129. int16 m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  4130. int i,j;
  4131. switch(nd->subtype)
  4132. {
  4133. case NPCTYPE_WARP:
  4134. xs = nd->u.warp.xs;
  4135. ys = nd->u.warp.ys;
  4136. break;
  4137. case NPCTYPE_SCRIPT:
  4138. xs = nd->u.scr.xs;
  4139. ys = nd->u.scr.ys;
  4140. break;
  4141. default:
  4142. return; // Other types doesn't have touch area
  4143. }
  4144. if (m < 0 || xs < 0 || ys < 0) //invalid range or map
  4145. return;
  4146. for (i = y-ys; i <= y+ys; i++) {
  4147. for (j = x-xs; j <= x+xs; j++) {
  4148. if (map_getcell(m, j, i, CELL_CHKNOPASS))
  4149. continue;
  4150. map_setcell(m, j, i, CELL_NPC, true);
  4151. }
  4152. }
  4153. }
  4154. int npc_unsetcells_sub(struct block_list* bl, va_list ap)
  4155. {
  4156. struct npc_data *nd = (struct npc_data*)bl;
  4157. int id = va_arg(ap,int);
  4158. if (nd->bl.id == id) return 0;
  4159. npc_setcells(nd);
  4160. return 1;
  4161. }
  4162. void npc_unsetcells(struct npc_data* nd)
  4163. {
  4164. int16 m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  4165. int i,j, x0, x1, y0, y1;
  4166. if (nd->subtype == NPCTYPE_WARP) {
  4167. xs = nd->u.warp.xs;
  4168. ys = nd->u.warp.ys;
  4169. } else {
  4170. xs = nd->u.scr.xs;
  4171. ys = nd->u.scr.ys;
  4172. }
  4173. if (m < 0 || xs < 0 || ys < 0)
  4174. return;
  4175. struct map_data *mapdata = map_getmapdata(m);
  4176. //Locate max range on which we can locate npc cells
  4177. //FIXME: does this really do what it's supposed to do? [ultramage]
  4178. for(x0 = x-xs; x0 > 0 && map_getcell(m, x0, y, CELL_CHKNPC); x0--);
  4179. for(x1 = x+xs; x1 < mapdata->xs-1 && map_getcell(m, x1, y, CELL_CHKNPC); x1++);
  4180. for(y0 = y-ys; y0 > 0 && map_getcell(m, x, y0, CELL_CHKNPC); y0--);
  4181. for(y1 = y+ys; y1 < mapdata->ys-1 && map_getcell(m, x, y1, CELL_CHKNPC); y1++);
  4182. //Erase this npc's cells
  4183. for (i = y-ys; i <= y+ys; i++)
  4184. for (j = x-xs; j <= x+xs; j++)
  4185. map_setcell(m, j, i, CELL_NPC, false);
  4186. //Re-deploy NPC cells for other nearby npcs.
  4187. map_foreachinallarea( npc_unsetcells_sub, m, x0, y0, x1, y1, BL_NPC, nd->bl.id );
  4188. }
  4189. bool npc_movenpc(struct npc_data* nd, int16 x, int16 y)
  4190. {
  4191. if (nd->bl.m < 0 || nd->bl.prev == nullptr)
  4192. return false; //Not on a map.
  4193. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  4194. x = cap_value(x, 0, mapdata->xs-1);
  4195. y = cap_value(y, 0, mapdata->ys-1);
  4196. map_foreachinallrange(clif_outsight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  4197. map_moveblock(&nd->bl, x, y, gettick());
  4198. map_foreachinallrange(clif_insight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  4199. return true;
  4200. }
  4201. /// Changes the display name of the npc.
  4202. ///
  4203. /// @param nd Target npc
  4204. /// @param newname New display name
  4205. void npc_setdisplayname(struct npc_data* nd, const char* newname)
  4206. {
  4207. nullpo_retv(nd);
  4208. struct map_data *mapdata = map_getmapdata(nd->bl.m);
  4209. safestrncpy(nd->name, newname, sizeof(nd->name));
  4210. if( mapdata && mapdata->users )
  4211. clif_name_area(&nd->bl);
  4212. }
  4213. /// Changes the display class of the npc.
  4214. ///
  4215. /// @param nd Target npc
  4216. /// @param class_ New display class
  4217. void npc_setclass(struct npc_data* nd, short class_)
  4218. {
  4219. nullpo_retv(nd);
  4220. if( nd->class_ == class_ )
  4221. return;
  4222. nd->class_ = class_;
  4223. status_set_viewdata(&nd->bl, class_);
  4224. unit_refresh(&nd->bl);
  4225. }
  4226. // @commands (script based)
  4227. int npc_do_atcmd_event(map_session_data* sd, const char* command, const char* message, const char* eventname)
  4228. {
  4229. struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
  4230. struct npc_data *nd;
  4231. struct script_state *st;
  4232. int i = 0, j = 0, k = 0;
  4233. char *temp;
  4234. nullpo_ret(sd);
  4235. if( ev == nullptr || (nd = ev->nd) == nullptr ) {
  4236. ShowError("npc_event: event not found [%s]\n", eventname);
  4237. return 0;
  4238. }
  4239. if( sd->npc_id != 0 ) { // Enqueue the event trigger.
  4240. int l;
  4241. ARR_FIND( 0, MAX_EVENTQUEUE, l, sd->eventqueue[l][0] == '\0' );
  4242. if( l < MAX_EVENTQUEUE ) {
  4243. safestrncpy(sd->eventqueue[l],eventname,EVENT_NAME_LENGTH); //Event enqueued.
  4244. return 0;
  4245. }
  4246. ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
  4247. return 1;
  4248. }
  4249. if( ev->nd->is_invisible ) { // Disabled npc, shouldn't trigger event.
  4250. npc_event_dequeue(sd);
  4251. return 2;
  4252. }
  4253. st = script_alloc_state(ev->nd->u.scr.script, ev->pos, sd->bl.id, ev->nd->bl.id);
  4254. setd_sub_str( st, nullptr, ".@atcmd_command$", 0, command, nullptr );
  4255. // split atcmd parameters based on spaces
  4256. temp = (char*)aMalloc(strlen(message) + 1);
  4257. for( i = 0; i < ( strlen( message ) + 1 ) && k < 127; i ++ ) {
  4258. if( message[i] == ' ' || message[i] == '\0' ) {
  4259. if (i > 0 && message[i - 1] == ' ') {
  4260. continue; // To prevent "@atcmd [space][space]" and .@atcmd_numparameters return 1 without any parameter.
  4261. }
  4262. temp[k] = '\0';
  4263. k = 0;
  4264. if( temp[0] != '\0' ) {
  4265. setd_sub_str( st, nullptr, ".@atcmd_parameters$", j++, temp, nullptr );
  4266. }
  4267. } else {
  4268. temp[k] = message[i];
  4269. k++;
  4270. }
  4271. }
  4272. setd_sub_num( st, nullptr, ".@atcmd_numparameters", 0, j, nullptr );
  4273. aFree(temp);
  4274. run_script_main(st);
  4275. return 0;
  4276. }
  4277. /// Parses a function.
  4278. /// function%TAB%script%TAB%<function name>%TAB%{<code>}
  4279. static const char* npc_parse_function(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  4280. {
  4281. DBMap* func_db;
  4282. DBData old_data;
  4283. struct script_code *script;
  4284. const char* end;
  4285. const char* script_start;
  4286. script_start = strstr(start,"\t{");
  4287. end = strchr(start,'\n');
  4288. if (*w4 != '{' || script_start == nullptr || (end != nullptr && script_start > end)) {
  4289. 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);
  4290. return nullptr;// can't continue
  4291. }
  4292. ++script_start;
  4293. end = npc_skip_script(script_start,buffer,filepath);
  4294. if( end == nullptr )
  4295. return nullptr;// (simple) parse error, don't continue
  4296. script = parse_script(script_start, filepath, strline(buffer,start-buffer), SCRIPT_RETURN_EMPTY_SCRIPT);
  4297. if( script == nullptr )// parse error, continue
  4298. return end;
  4299. func_db = script_get_userfunc_db();
  4300. if (func_db->put(func_db, db_str2key(w3), db_ptr2data(script), &old_data)) {
  4301. struct script_code *oldscript = (struct script_code*)db_data2ptr(&old_data);
  4302. ShowInfo("npc_parse_function: Overwriting user function [%s] (%s:%d)\n", w3, filepath, strline(buffer,start-buffer));
  4303. script_free_code( oldscript );
  4304. }
  4305. return end;
  4306. }
  4307. /*==========================================
  4308. * Parse Mob 1 - Parse mob list into each map
  4309. * Parse Mob 2 - Actually Spawns Mob
  4310. * [Wizputer]
  4311. *------------------------------------------*/
  4312. void npc_parse_mob2(struct spawn_data* mob)
  4313. {
  4314. int i;
  4315. for( i = mob->active; i < mob->num; ++i )
  4316. {
  4317. struct mob_data* md = mob_spawn_dataset(mob);
  4318. md->spawn = mob;
  4319. // Determine center cell for each mob in the spawn line
  4320. if (battle_config.randomize_center_cell) {
  4321. if (mob->xs > 1)
  4322. md->centerX = rnd_value(mob->x - mob->xs + 1, mob->x + mob->xs - 1);
  4323. if (mob->ys > 1)
  4324. md->centerY = rnd_value(mob->y - mob->ys + 1, mob->y + mob->ys - 1);
  4325. }
  4326. md->spawn->active++;
  4327. mob_spawn(md);
  4328. }
  4329. }
  4330. static const char* npc_parse_mob(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  4331. {
  4332. int num, mob_id, mob_lv = -1, delay = 5000, size = -1, w1count, w4count;
  4333. short m, x = 0, y = 0, xs = 0, ys = 0;
  4334. char mapname[MAP_NAME_LENGTH_EXT], mobname[NAME_LENGTH], sprite[NAME_LENGTH];
  4335. struct spawn_data mob, *data;
  4336. int ai = AI_NONE; // mob_ai
  4337. memset(&mob, 0, sizeof(struct spawn_data));
  4338. mob.state.boss = !strcmpi(w2,"boss_monster");
  4339. // w1=<map name>{,<x>,<y>{,<xs>,<ys>}}
  4340. // w3=<mob name>{,<mob level>}
  4341. // w4=<mob id>,<amount>{,<delay1>{,<delay2>{,<event>{,<mob size>{,<mob ai>}}}}}
  4342. if( ( w1count = sscanf(w1, "%15[^,],%6hd,%6hd,%6hd,%6hd", mapname, &x, &y, &xs, &ys) ) < 1
  4343. || sscanf(w3, "%23[^,],%11d", mobname, &mob_lv) < 1
  4344. || ( w4count = sscanf(w4, "%23[^,],%11d,%11u,%11u,%77[^,],%11d,%11d[^\t\r\n]", sprite, &num, &delay, &mob.delay2, mob.eventname, &size, &ai) ) < 2 )
  4345. {
  4346. 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);
  4347. return strchr(start,'\n');// skip and continue
  4348. }
  4349. if( mapindex_name2id(mapname) == 0 )
  4350. {
  4351. ShowError("npc_parse_mob: Unknown map '%s' in file '%s', line '%d'.\n", mapname, filepath, strline(buffer,start-buffer));
  4352. return strchr(start,'\n');// skip and continue
  4353. }
  4354. m = map_mapname2mapid(mapname);
  4355. if( m < 0 )//Not loaded on this map-server instance.
  4356. return strchr(start,'\n');// skip and continue
  4357. mob.m = (unsigned short)m;
  4358. struct map_data *mapdata = map_getmapdata(m);
  4359. if( x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys )
  4360. {
  4361. 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));
  4362. return strchr(start,'\n');// skip and continue
  4363. }
  4364. // Check if sprite is the mob name or ID
  4365. char *pid;
  4366. sprite[NAME_LENGTH-1] = '\0';
  4367. mob_id = strtol(sprite, &pid, 0);
  4368. if (pid != nullptr && *pid != '\0') {
  4369. std::shared_ptr<s_mob_db> mob = mobdb_search_aegisname(sprite);
  4370. if (mob == nullptr) {
  4371. ShowError("npc_parse_mob: Unknown mob name %s (file '%s', line '%d').\n", sprite, filepath, strline(buffer,start-buffer));
  4372. return strchr(start,'\n');// skip and continue
  4373. }
  4374. mob_id = mob->id;
  4375. }
  4376. else if (mobdb_checkid(mob_id) == 0) { // check monster ID if exists!
  4377. ShowError("npc_parse_mob: Unknown mob ID %d (file '%s', line '%d').\n", mob_id, filepath, strline(buffer,start-buffer));
  4378. return strchr(start,'\n');// skip and continue
  4379. }
  4380. if( num < 1 || num > 1000 )
  4381. {
  4382. 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));
  4383. return strchr(start,'\n');// skip and continue
  4384. }
  4385. if (w4count > 2 && delay != 5000 && delay < battle_config.mob_respawn_time) {
  4386. 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));
  4387. mob.delay1 = 5000;
  4388. } else
  4389. mob.delay1 = delay;
  4390. if( mob.state.size > SZ_BIG && size != -1 )
  4391. {
  4392. 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));
  4393. return strchr(start, '\n');
  4394. }
  4395. if( (mob.state.ai < AI_NONE || mob.state.ai >= AI_MAX) && ai != -1 )
  4396. {
  4397. 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));
  4398. return strchr(start, '\n');
  4399. }
  4400. if( (mob_lv == 0 || mob_lv > MAX_LEVEL) && mob_lv != -1 )
  4401. {
  4402. 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));
  4403. return strchr(start, '\n');
  4404. }
  4405. mob.num = (unsigned short)num;
  4406. mob.active = 0;
  4407. mob.id = (short) mob_id;
  4408. mob.x = (unsigned short)x;
  4409. mob.y = (unsigned short)y;
  4410. mob.xs = (signed short)xs;
  4411. mob.ys = (signed short)ys;
  4412. if (mob_lv > 0 && mob_lv <= MAX_LEVEL)
  4413. mob.level = mob_lv;
  4414. if (size > SZ_SMALL && size <= SZ_BIG)
  4415. mob.state.size = size;
  4416. if (ai > AI_NONE && ai <= AI_MAX)
  4417. mob.state.ai = static_cast<enum mob_ai>(ai);
  4418. if (mob.xs < 0) {
  4419. 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));
  4420. mob.xs = 0;
  4421. }
  4422. else if (mob.xs == 0 && mob.x > 0) {
  4423. // Fixed X coordinate
  4424. // Need to set this to 1 as we reduce it by 1 when calling the search function
  4425. mob.xs = 1;
  4426. }
  4427. if (mob.ys < 0) {
  4428. 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));
  4429. mob.ys = 0;
  4430. }
  4431. else if (mob.ys == 0 && mob.y > 0) {
  4432. // Fixed Y coordinate
  4433. // Need to set this to 1 as we reduce it by 1 when calling the search function
  4434. mob.ys = 1;
  4435. }
  4436. if (mob.num > 1 && battle_config.mob_count_rate != 100) {
  4437. if ((mob.num = mob.num * battle_config.mob_count_rate / 100) < 1)
  4438. mob.num = 1;
  4439. }
  4440. if (battle_config.force_random_spawn || (mob.x == 0 && mob.y == 0)
  4441. || (mob.xs == 1 && mob.ys == 1 && !map_getcell(mob.m, mob.x, mob.y, CELL_CHKREACH)))
  4442. { //Force a random spawn anywhere on the map.
  4443. mob.x = mob.y = 0;
  4444. mob.xs = mob.ys = 0;
  4445. }
  4446. // Check if monsters should have variance applied to their respawn time
  4447. if( ( ( battle_config.mob_spawn_variance & 1 ) == 0 && mob.state.boss ) || ( ( battle_config.mob_spawn_variance & 2 ) == 0 && !mob.state.boss ) ){
  4448. // Remove the variance
  4449. mob.delay2 = 0;
  4450. }
  4451. if(mob.delay1>0xfffffff || mob.delay2>0xfffffff) {
  4452. ShowError("npc_parse_mob: Invalid spawn delays %u %u (file '%s', line '%d').\n", mob.delay1, mob.delay2, filepath, strline(buffer,start-buffer));
  4453. return strchr(start,'\n');// skip and continue
  4454. }
  4455. //Use db names instead of the spawn file ones.
  4456. if(battle_config.override_mob_names==1)
  4457. strcpy(mob.name,"--en--");
  4458. else if (battle_config.override_mob_names==2)
  4459. strcpy(mob.name,"--ja--");
  4460. else
  4461. safestrncpy(mob.name, mobname, sizeof(mob.name));
  4462. //Verify dataset.
  4463. if( !mob_parse_dataset(&mob) )
  4464. {
  4465. ShowError("npc_parse_mob: Invalid dataset for monster ID %d (file '%s', line '%d').\n", mob_id, filepath, strline(buffer,start-buffer));
  4466. return strchr(start,'\n');// skip and continue
  4467. }
  4468. //Update mob spawn lookup database
  4469. struct spawn_info spawn = { mapdata->index, mob.num };
  4470. mob_add_spawn(mob_id, spawn);
  4471. //Now that all has been validated. We allocate the actual memory that the re-spawn data will use.
  4472. data = (struct spawn_data*)aMalloc(sizeof(struct spawn_data));
  4473. memcpy(data, &mob, sizeof(struct spawn_data));
  4474. // spawn / cache the new mobs
  4475. if( battle_config.dynamic_mobs && map_addmobtolist(data->m, data) >= 0 )
  4476. {
  4477. data->state.dynamic = true;
  4478. npc_cache_mob += data->num;
  4479. // check if target map has players
  4480. // (usually shouldn't occur when map server is just starting,
  4481. // but not the case when we do @reloadscript
  4482. if( map_getmapdata(data->m)->users > 0 )
  4483. npc_parse_mob2(data);
  4484. }
  4485. else
  4486. {
  4487. data->state.dynamic = false;
  4488. npc_parse_mob2(data);
  4489. npc_delay_mob += data->num;
  4490. }
  4491. npc_mob++;
  4492. return strchr(start,'\n');// continue
  4493. }
  4494. /*==========================================
  4495. * Set or disable mapflag on map
  4496. * eg : bat_c01 mapflag battleground 2
  4497. * also chking if mapflag conflict with another
  4498. *------------------------------------------*/
  4499. const char* npc_parse_mapflag(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  4500. {
  4501. int16 m;
  4502. char mapname[MAP_NAME_LENGTH_EXT];
  4503. bool state = true;
  4504. enum e_mapflag mapflag;
  4505. // w1=<mapname>
  4506. if (sscanf(w1, "%15[^,]", mapname) != 1) {
  4507. 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);
  4508. return strchr(start,'\n');// skip and continue
  4509. }
  4510. m = map_mapname2mapid(mapname);
  4511. if (m < 0) {
  4512. 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);
  4513. return strchr(start,'\n');// skip and continue
  4514. }
  4515. if (w4 && !strcmpi(w4, "off"))
  4516. state = false; //Disable mapflag rather than enable it. [Skotlex]
  4517. mapflag = map_getmapflag_by_name(w3);
  4518. switch( mapflag ){
  4519. case MF_INVALID:
  4520. ShowError("npc_parse_mapflag: unrecognized mapflag '%s' (file '%s', line '%d').\n", w3, filepath, strline(buffer,start-buffer));
  4521. break;
  4522. case MF_NOSAVE: {
  4523. char savemap[MAP_NAME_LENGTH_EXT];
  4524. union u_mapflag_args args = {};
  4525. if (state && !strcmpi(w4, "SavePoint")) {
  4526. args.nosave.map = 0;
  4527. args.nosave.x = -1;
  4528. args.nosave.y = -1;
  4529. } else if (state && sscanf(w4, "%15[^,],%6hd,%6hd", savemap, &args.nosave.x, &args.nosave.y) == 3) {
  4530. args.nosave.map = mapindex_name2id(savemap);
  4531. if (!args.nosave.map) {
  4532. 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);
  4533. args.nosave.x = -1;
  4534. args.nosave.y = -1;
  4535. }
  4536. }
  4537. map_setmapflag_sub(m, MF_NOSAVE, state, &args);
  4538. break;
  4539. }
  4540. case MF_PVP_NIGHTMAREDROP: {
  4541. char drop_arg1[16], drop_arg2[16];
  4542. union u_mapflag_args args = {};
  4543. if (sscanf(w4, "%15[^,],%15[^,],%11d", drop_arg1, drop_arg2, &args.nightmaredrop.drop_per) == 3) {
  4544. if (!strcmpi(drop_arg1, "random"))
  4545. args.nightmaredrop.drop_id = -1;
  4546. else if (!item_db.exists((args.nightmaredrop.drop_id = strtol(drop_arg1, nullptr, 10)))) {
  4547. args.nightmaredrop.drop_id = 0;
  4548. 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);
  4549. break;
  4550. }
  4551. if (!strcmpi(drop_arg2, "inventory"))
  4552. args.nightmaredrop.drop_type = NMDT_INVENTORY;
  4553. else if (!strcmpi(drop_arg2, "equip"))
  4554. args.nightmaredrop.drop_type = NMDT_EQUIP;
  4555. else if (!strcmpi(drop_arg2, "all"))
  4556. args.nightmaredrop.drop_type = NMDT_ALL;
  4557. if (args.nightmaredrop.drop_id != 0)
  4558. map_setmapflag_sub(m, MF_PVP_NIGHTMAREDROP, true, &args);
  4559. } else if (!state)
  4560. map_setmapflag(m, MF_PVP_NIGHTMAREDROP, false);
  4561. break;
  4562. }
  4563. case MF_BATTLEGROUND:
  4564. if (state) {
  4565. union u_mapflag_args args = {};
  4566. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  4567. args.flag_val = 1; // Default value
  4568. map_setmapflag_sub(m, MF_BATTLEGROUND, true, &args);
  4569. } else
  4570. map_setmapflag(m, MF_BATTLEGROUND, false);
  4571. break;
  4572. case MF_NOCOMMAND:
  4573. if (state) {
  4574. union u_mapflag_args args = {};
  4575. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  4576. args.flag_val = 100; // No level specified, block everyone.
  4577. map_setmapflag_sub(m, MF_NOCOMMAND, true, &args);
  4578. } else
  4579. map_setmapflag(m, MF_NOCOMMAND, false);
  4580. break;
  4581. case MF_JEXP:
  4582. case MF_BEXP: {
  4583. union u_mapflag_args args = {};
  4584. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  4585. args.flag_val = 0;
  4586. map_setmapflag_sub(m, mapflag, state, &args);
  4587. }
  4588. break;
  4589. case MF_SKILL_DAMAGE: {
  4590. char skill_name[SKILL_NAME_LENGTH];
  4591. char caster_constant[NAME_LENGTH];
  4592. union u_mapflag_args args = {};
  4593. memset(skill_name, 0, sizeof(skill_name));
  4594. if (!state)
  4595. map_setmapflag_sub(m, MF_SKILL_DAMAGE, false, &args);
  4596. else {
  4597. 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) {
  4598. if (ISDIGIT(caster_constant[0]))
  4599. args.skill_damage.caster = atoi(caster_constant);
  4600. else {
  4601. int64 val_tmp;
  4602. if (!script_get_constant(caster_constant, &val_tmp)) {
  4603. ShowError( "npc_parse_mapflag: Unknown constant '%s'. Skipping (file '%s', line '%d').\n", caster_constant, filepath, strline(buffer, start - buffer) );
  4604. break;
  4605. }
  4606. args.skill_damage.caster = static_cast<uint16>(val_tmp);
  4607. }
  4608. if (args.skill_damage.caster == 0)
  4609. args.skill_damage.caster = BL_ALL;
  4610. for (int i = SKILLDMG_PC; i < SKILLDMG_MAX; i++)
  4611. args.skill_damage.rate[i] = cap_value(args.skill_damage.rate[i], -100, 100000);
  4612. trim(skill_name);
  4613. if (strcmp(skill_name, "all") == 0) // Adjust damage for all skills
  4614. map_setmapflag_sub(m, MF_SKILL_DAMAGE, true, &args);
  4615. else if (skill_name2id(skill_name) <= 0)
  4616. 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));
  4617. else { // Adjusted damage for specified skill
  4618. args.flag_val = 1;
  4619. map_setmapflag_sub(m, MF_SKILL_DAMAGE, true, &args);
  4620. map_skill_damage_add(map_getmapdata(m), skill_name2id(skill_name), &args);
  4621. }
  4622. }
  4623. }
  4624. break;
  4625. }
  4626. case MF_SKILL_DURATION: {
  4627. union u_mapflag_args args = {};
  4628. if (!state)
  4629. map_setmapflag_sub(m, MF_SKILL_DURATION, false, &args);
  4630. else {
  4631. char skill_name[SKILL_NAME_LENGTH];
  4632. if (sscanf(w4, "%30[^,],%5hu[^\n]", skill_name, &args.skill_duration.per) == 2) {
  4633. args.skill_duration.skill_id = skill_name2id(skill_name);
  4634. if (!args.skill_duration.skill_id)
  4635. 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));
  4636. else {
  4637. args.skill_duration.per = cap_value(args.skill_duration.per, 0, UINT16_MAX);
  4638. map_setmapflag_sub(m, MF_SKILL_DURATION, true, &args);
  4639. }
  4640. }
  4641. }
  4642. break;
  4643. }
  4644. case MF_INVINCIBLE_TIME: {
  4645. union u_mapflag_args args = {};
  4646. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  4647. args.flag_val = 5000;
  4648. map_setmapflag_sub(m, mapflag, state, &args);
  4649. }
  4650. break;
  4651. case MF_FLEE_PENALTY: {
  4652. union u_mapflag_args args = {};
  4653. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  4654. args.flag_val = 20;
  4655. map_setmapflag_sub(m, mapflag, state, &args);
  4656. }
  4657. break;
  4658. case MF_WEAPON_DAMAGE_RATE:
  4659. case MF_MAGIC_DAMAGE_RATE:
  4660. case MF_MISC_DAMAGE_RATE:
  4661. case MF_LONG_DAMAGE_RATE:
  4662. case MF_SHORT_DAMAGE_RATE: {
  4663. union u_mapflag_args args = {};
  4664. if (sscanf(w4, "%11d", &args.flag_val) < 1)
  4665. args.flag_val = 100;
  4666. map_setmapflag_sub(m, mapflag, state, &args);
  4667. }
  4668. break;
  4669. // All others do not need special treatment
  4670. default:
  4671. map_setmapflag(m, mapflag, state);
  4672. break;
  4673. }
  4674. return strchr(start,'\n');// continue
  4675. }
  4676. /**
  4677. * Read file and create npc/func/mapflag/monster... accordingly.
  4678. * @param filepath : Relative path of file from map-serv bin
  4679. * @param runOnInit : should we exec OnInit when it's done ?
  4680. * @return 0:error, 1:success
  4681. */
  4682. int npc_parsesrcfile(const char* filepath)
  4683. {
  4684. if (check_filepath(filepath) != 2) { //this is not a file
  4685. ShowDebug("npc_parsesrcfile: Path doesn't seem to be a file skipping it : '%s'.\n", filepath);
  4686. return 0;
  4687. }
  4688. // read whole file to buffer
  4689. FILE* fp = fopen(filepath, "rb");
  4690. if (fp == nullptr) {
  4691. ShowError("npc_parsesrcfile: File not found '%s'.\n", filepath);
  4692. return 0;
  4693. }
  4694. fseek(fp, 0, SEEK_END);
  4695. size_t len = ftell(fp);
  4696. char* buffer = (char*)aMalloc(len+1);
  4697. fseek(fp, 0, SEEK_SET);
  4698. len = fread(buffer, 1, len, fp);
  4699. buffer[len] = '\0';
  4700. if (ferror(fp)) {
  4701. ShowError("npc_parsesrcfile: Failed to read file '%s' - %s\n", filepath, strerror(errno));
  4702. aFree(buffer);
  4703. fclose(fp);
  4704. return 0;
  4705. }
  4706. fclose(fp);
  4707. if ((unsigned char)buffer[0] == 0xEF && (unsigned char)buffer[1] == 0xBB && (unsigned char)buffer[2] == 0xBF) {
  4708. // UTF-8 BOM. This is most likely an error on the user's part, because:
  4709. // - BOM is discouraged in UTF-8, and the only place where you see it is Notepad and such.
  4710. // - 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.
  4711. // - If the user really wants to use UTF-8 (instead of latin1, EUC-KR, SJIS, etc), then they can still do it <without BOM>.
  4712. // More info at http://unicode.org/faq/utf_bom.html#bom5 and http://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  4713. ShowError("npc_parsesrcfile: Detected unsupported UTF-8 BOM in file '%s'. Stopping (please consider using another character set).\n", filepath);
  4714. aFree(buffer);
  4715. return 0;
  4716. }
  4717. int lines = 0;
  4718. // parse buffer
  4719. for ( const char* p = skip_space(buffer); p && *p ; p = skip_space(p) ) {
  4720. size_t pos[9];
  4721. lines++;
  4722. // w1<TAB>w2<TAB>w3<TAB>w4
  4723. bool error;
  4724. size_t count = sv_parse( p, len + buffer - p, 0, '\t', pos, ARRAYLENGTH( pos ), SV_TERMINATE_LF|SV_TERMINATE_CRLF, error );
  4725. if( error ){
  4726. ShowError("npc_parsesrcfile: Parse error in file '%s', line '%d'. Stopping...\n", filepath, strline(buffer,p-buffer));
  4727. break;
  4728. }
  4729. char w1[2048], w2[2048], w3[2048], w4[2048];
  4730. // fill w1
  4731. if( pos[3]-pos[2] > ARRAYLENGTH(w1)-1 )
  4732. ShowWarning("npc_parsesrcfile: w1 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[3]-pos[2], filepath, strline(buffer,p-buffer));
  4733. int i = min(pos[3]-pos[2], ARRAYLENGTH(w1)-1);
  4734. memcpy(w1, p+pos[2], i*sizeof(char));
  4735. w1[i] = '\0';
  4736. // fill w2
  4737. if( pos[5]-pos[4] > ARRAYLENGTH(w2)-1 )
  4738. ShowWarning("npc_parsesrcfile: w2 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[5]-pos[4], filepath, strline(buffer,p-buffer));
  4739. i = min(pos[5]-pos[4], ARRAYLENGTH(w2)-1);
  4740. memcpy(w2, p+pos[4], i*sizeof(char));
  4741. w2[i] = '\0';
  4742. // fill w3
  4743. if( pos[7]-pos[6] > ARRAYLENGTH(w3)-1 )
  4744. ShowWarning("npc_parsesrcfile: w3 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[7]-pos[6], filepath, strline(buffer,p-buffer));
  4745. i = min(pos[7]-pos[6], ARRAYLENGTH(w3)-1);
  4746. memcpy(w3, p+pos[6], i*sizeof(char));
  4747. w3[i] = '\0';
  4748. // fill w4 (to end of line)
  4749. if( pos[1]-pos[8] > ARRAYLENGTH(w4)-1 )
  4750. ShowWarning("npc_parsesrcfile: w4 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[1]-pos[8], filepath, strline(buffer,p-buffer));
  4751. if (pos[8] != -1) {
  4752. i = min(pos[1]-pos[8], ARRAYLENGTH(w4)-1);
  4753. memcpy(w4, p+pos[8], i*sizeof(char));
  4754. w4[i] = '\0';
  4755. }
  4756. else
  4757. w4[0] = '\0';
  4758. if (count < 3) {// Unknown syntax
  4759. 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);
  4760. break;
  4761. }
  4762. // Whether w2 contains word "script"
  4763. bool has_script = false;
  4764. if (count > 3 && strncasecmp(w2, "script", 6) == 0)
  4765. has_script = true;
  4766. if (strcmp(w1, "-") != 0 && strcasecmp(w1, "function") != 0) {// check the data of w1 = <map name>,<x>,<y>,<facing>
  4767. char mapname[MAP_NAME_LENGTH_EXT];
  4768. int16 x, y;
  4769. int count2 = sscanf(w1,"%15[^,],%6hd,%6hd[^,]",mapname,&x,&y);
  4770. if (count2 < 1) {
  4771. 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);
  4772. if (has_script && (p = npc_skip_script(p,buffer,filepath)) == nullptr)
  4773. break;
  4774. p = strchr(p,'\n');// next line
  4775. continue;
  4776. }
  4777. else if (count2 < 3) {
  4778. // If we were not able to parse any x and y coordinates(usually used by mapflags)
  4779. x = y = 0;
  4780. }
  4781. if (!mapindex_name2id(mapname)) {// Incorrect map, we must skip the script info...
  4782. ShowError("npc_parsesrcfile: Unknown map '%s' in file '%s', line '%d'. Skipping line...\n", mapname, filepath, strline(buffer,p-buffer));
  4783. if (has_script && (p = npc_skip_script(p,buffer,filepath)) == nullptr)
  4784. break;
  4785. p = strchr(p,'\n');// next line
  4786. continue;
  4787. }
  4788. int16 m = map_mapname2mapid(mapname);
  4789. if (m < 0) {// "mapname" is not assigned to this server, we must skip the script info...
  4790. if (has_script && (p = npc_skip_script(p,buffer,filepath)) == nullptr)
  4791. break;
  4792. p = strchr(p,'\n');// next line
  4793. continue;
  4794. }
  4795. map_data *mapdata = map_getmapdata(m);
  4796. if (x < 0 || x >= mapdata->xs || y < 0 || y >= mapdata->ys) {
  4797. 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));
  4798. if (has_script && (p = npc_skip_script(p,buffer,filepath)) == nullptr)
  4799. break;
  4800. p = strchr(p,'\n');// next line
  4801. continue;
  4802. }
  4803. }
  4804. // parse the data according to w2
  4805. if ((strncasecmp(w2, "warp", 4) == 0 || strncasecmp(w2, "warp2", 5) == 0) && count > 3)
  4806. p = npc_parse_warp(w1,w2,w3,w4, p, buffer, filepath);
  4807. else if ((!strcasecmp(w2,"shop") || !strcasecmp(w2,"cashshop") || !strcasecmp(w2,"itemshop") || !strcasecmp(w2,"pointshop") || !strcasecmp(w2,"marketshop") ) && count > 3)
  4808. p = npc_parse_shop(w1,w2,w3,w4, p, buffer, filepath);
  4809. else if (has_script) {
  4810. if (strcasecmp(w1,"function") == 0) {
  4811. if (strcasecmp(w2,"script") == 0)
  4812. p = npc_parse_function(w1, w2, w3, w4, p, buffer, filepath);
  4813. else {
  4814. 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);
  4815. p = strchr(p,'\n');// skip and continue
  4816. }
  4817. }
  4818. else
  4819. p = npc_parse_script(w1,w2,w3,w4, p, buffer, filepath);
  4820. }
  4821. else if( (i=0, sscanf(w2,"duplicate%n",&i), (i > 0 && w2[i] == '(')) && count > 3 )
  4822. p = npc_parse_duplicate(w1,w2,w3,w4, p, buffer, filepath);
  4823. else if( (strcmpi(w2,"monster") == 0 || strcmpi(w2,"boss_monster") == 0) && count > 3 )
  4824. p = npc_parse_mob(w1, w2, w3, w4, p, buffer, filepath);
  4825. else if( strcmpi(w2,"mapflag") == 0 && count >= 3 )
  4826. p = npc_parse_mapflag(w1, w2, trim(w3), trim(w4), p, buffer, filepath);
  4827. else {
  4828. 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);
  4829. p = strchr(p,'\n');// skip and continue
  4830. }
  4831. }
  4832. aFree(buffer);
  4833. return 1;
  4834. }
  4835. int npc_script_event(map_session_data* sd, enum npce_event type){
  4836. if (type == NPCE_MAX)
  4837. return 0;
  4838. if (!sd) {
  4839. ShowError("npc_script_event: nullptr sd. Event Type %d\n", type);
  4840. return 0;
  4841. }
  4842. std::vector<struct script_event_s>& vector = script_event[type];
  4843. for( struct script_event_s& evt : vector ){
  4844. npc_event_sub( sd, evt.event, evt.event_name );
  4845. }
  4846. return vector.size();
  4847. }
  4848. /**
  4849. * Duplicates a NPC.
  4850. * nd: Original NPC data
  4851. * name: Duplicate NPC name
  4852. * m: Map ID of duplicate NPC
  4853. * x: X coordinate of duplicate NPC
  4854. * y: Y coordinate of duplicate NPC
  4855. * class_: View of duplicate NPC
  4856. * dir: Facing direction of duplicate NPC
  4857. * Returns duplicate NPC data on success
  4858. */
  4859. 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 ){
  4860. static char w1[128], w2[128], w3[128], w4[128];
  4861. const char* stat_buf = "- call from duplicate subsystem -\n";
  4862. char exname[NPC_NAME_LENGTH + 1];
  4863. snprintf(w1, sizeof(w1), "%s,%d,%d,%d", map_getmapdata(mapid)->name, x, y, dir);
  4864. snprintf(w2, sizeof(w2), "duplicate(%s)", nd.exname);
  4865. //Making sure the generated name is not used for another npc.
  4866. int i = 0;
  4867. snprintf(exname, ARRAYLENGTH(exname), "%d_%d_%d_%d", i, mapid, x, y);
  4868. while (npc_name2id(exname) != nullptr) {
  4869. ++i;
  4870. snprintf(exname, ARRAYLENGTH(exname), "%d_%d_%d_%d", i, mapid, x, y);
  4871. }
  4872. snprintf(w3, sizeof(w3), "%s::%s", name, exname);
  4873. if( xs >= 0 && ys >= 0 ){
  4874. snprintf( w4, sizeof( w4 ), "%d,%d,%d", class_, xs, ys ); // Touch Area
  4875. }else{
  4876. snprintf( w4, sizeof( w4 ), "%d", class_ );
  4877. }
  4878. npc_parse_duplicate( w1, w2, w3, w4, stat_buf, stat_buf, "DUPLICATE", owner ); //DUPLICATE means nothing for now.
  4879. npc_data* dnd = npc_name2id( exname );
  4880. // No need to try and execute any events
  4881. if( dnd == nullptr ){
  4882. return nullptr;
  4883. }
  4884. //run OnInit Events
  4885. char evname[EVENT_NAME_LENGTH];
  4886. safesnprintf(evname, EVENT_NAME_LENGTH, "%s::%s", exname, script_config.init_event_name);
  4887. if ((struct event_data*)strdb_get(ev_db, evname)) {
  4888. npc_event_do(evname);
  4889. }
  4890. return dnd;
  4891. }
  4892. TIMER_FUNC(npc_dynamicnpc_removal_timer){
  4893. struct npc_data* nd = map_id2nd( id );
  4894. if( nd == nullptr ){
  4895. return 0;
  4896. }
  4897. nd->dynamicnpc.removal_tid = INVALID_TIMER;
  4898. map_session_data* sd = map_charid2sd( nd->dynamicnpc.owner_char_id );
  4899. if( sd != nullptr ){
  4900. // Still talking to the NPC
  4901. // TODO: are there other fields to check?
  4902. if( sd->npc_id == nd->bl.id || sd->npc_shopid == nd->bl.id ){
  4903. // Retry later
  4904. nd->dynamicnpc.last_interaction = gettick();
  4905. 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 );
  4906. return 0;
  4907. }
  4908. // Last interaction is not long enough in the past
  4909. if( DIFF_TICK( gettick(), nd->dynamicnpc.last_interaction ) < battle_config.feature_dynamicnpc_timeout ){
  4910. 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 );
  4911. return 0;
  4912. }
  4913. // npc id from sd->npc_id_dynamic is removed in npc_unload
  4914. }
  4915. // Delete the NPC
  4916. npc_unload( nd, true );
  4917. // Update NPC event database
  4918. npc_read_event_script();
  4919. return 0;
  4920. }
  4921. struct npc_data* npc_duplicate_npc_for_player( struct npc_data& nd, map_session_data& sd ){
  4922. // A duplicate of a duplicate is still a duplicate of the same NPC
  4923. int src_id = nd.src_id > 0 ? nd.src_id : nd.bl.id;
  4924. for (const auto &it : sd.npc_id_dynamic) {
  4925. struct npc_data* src_nd = map_id2nd( it );
  4926. // Check if the source NPC id of currently active duplicates already exists.
  4927. if( src_nd != nullptr && src_nd->src_id == src_id ){
  4928. clif_dynamicnpc_result( sd, DYNAMICNPC_RESULT_DUPLICATE );
  4929. return nullptr;
  4930. }
  4931. }
  4932. if( map_getmapflag( sd.bl.m, MF_NODYNAMICNPC ) ){
  4933. // It has been confirmed that there is no reply to the client
  4934. return nullptr;
  4935. }
  4936. int16 new_x, new_y;
  4937. if( !map_search_freecell( &sd.bl, 0, &new_x, &new_y, battle_config.feature_dynamicnpc_rangex, battle_config.feature_dynamicnpc_rangey, 0 ) ){
  4938. 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 );
  4939. return nullptr;
  4940. }
  4941. int8 dir;
  4942. if( battle_config.feature_dynamicnpc_direction ){
  4943. // Let the NPC look to the player
  4944. dir = map_calc_dir_xy( new_x, new_y, sd.bl.x, sd.bl.y, DIR_CENTER );
  4945. }else{
  4946. // Use original NPCs direction
  4947. dir = nd.ud.dir;
  4948. }
  4949. 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 );
  4950. if( dnd == nullptr ){
  4951. return nullptr;
  4952. }
  4953. dnd->dynamicnpc.last_interaction = gettick();
  4954. 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 );
  4955. return dnd;
  4956. }
  4957. const char *npc_get_script_event_name(int npce_index)
  4958. {
  4959. switch (npce_index) {
  4960. case NPCE_LOGIN:
  4961. return script_config.login_event_name;
  4962. case NPCE_LOGOUT:
  4963. return script_config.logout_event_name;
  4964. case NPCE_LOADMAP:
  4965. return script_config.loadmap_event_name;
  4966. case NPCE_BASELVUP:
  4967. return script_config.baselvup_event_name;
  4968. case NPCE_JOBLVUP:
  4969. return script_config.joblvup_event_name;
  4970. case NPCE_DIE:
  4971. return script_config.die_event_name;
  4972. case NPCE_KILLPC:
  4973. return script_config.kill_pc_event_name;
  4974. case NPCE_KILLNPC:
  4975. return script_config.kill_mob_event_name;
  4976. default:
  4977. ShowError("npc_get_script_event_name: npce_index is outside the array limits: %d (max: %d).\n", npce_index, NPCE_MAX);
  4978. return nullptr;
  4979. }
  4980. }
  4981. void npc_read_event_script(void)
  4982. {
  4983. int i;
  4984. script_event.clear();
  4985. for (i = 0; i < NPCE_MAX; i++)
  4986. {
  4987. DBIterator* iter;
  4988. DBKey key;
  4989. DBData *data;
  4990. char name[EVENT_NAME_LENGTH];
  4991. safesnprintf(name,EVENT_NAME_LENGTH,"::%s", npc_get_script_event_name(i));
  4992. iter = db_iterator(ev_db);
  4993. for( data = iter->first(iter,&key); iter->exists(iter); data = iter->next(iter,&key) )
  4994. {
  4995. const char* p = key.str;
  4996. struct event_data* ed = (struct event_data*)db_data2ptr(data);
  4997. if( (p=strchr(p,':')) && strcmpi(name,p)==0 ){
  4998. struct script_event_s evt;
  4999. evt.event = ed;
  5000. evt.event_name = key.str;
  5001. script_event[static_cast<enum npce_event>(i)].push_back(evt);
  5002. }
  5003. }
  5004. dbi_destroy(iter);
  5005. }
  5006. if (battle_config.etc_log) {
  5007. //Print summary.
  5008. for (i = 0; i < NPCE_MAX; i++)
  5009. ShowInfo("%" PRIuPTR " '%s' events.\n", script_event[static_cast<enum npce_event>(i)].size(), npc_get_script_event_name(i));
  5010. }
  5011. }
  5012. void npc_clear_pathlist(void) {
  5013. struct npc_path_data *npd = nullptr;
  5014. DBIterator *path_list = db_iterator(npc_path_db);
  5015. /* free all npc_path_data filepaths */
  5016. for( npd = (struct npc_path_data *)dbi_first(path_list); dbi_exists(path_list); npd = (struct npc_path_data *)dbi_next(path_list) ) {
  5017. if( npd->path )
  5018. aFree(npd->path);
  5019. }
  5020. dbi_destroy(path_list);
  5021. }
  5022. //Clear then reload npcs files
  5023. int npc_reload(void) {
  5024. int npc_new_min = npc_id;
  5025. struct s_mapiterator* iter;
  5026. struct block_list* bl;
  5027. /* clear guild flag cache */
  5028. guild_flags_clear();
  5029. npc_clear_pathlist();
  5030. db_clear(npc_path_db);
  5031. db_clear(npcname_db);
  5032. db_clear(ev_db);
  5033. //Remove all npcs/mobs. [Skotlex]
  5034. #if PACKETVER >= 20131223
  5035. npc_market_fromsql();
  5036. #endif
  5037. iter = mapit_geteachiddb();
  5038. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) ) {
  5039. switch(bl->type) {
  5040. case BL_NPC:
  5041. if( bl->id != fake_nd->bl.id )// don't remove fake_nd
  5042. npc_unload((struct npc_data *)bl, false);
  5043. break;
  5044. case BL_MOB:
  5045. unit_free(bl,CLR_OUTSIGHT);
  5046. break;
  5047. }
  5048. }
  5049. mapit_free(iter);
  5050. // dynamic check by [random]
  5051. if( battle_config.dynamic_mobs ){
  5052. for (int i = 0; i < map_num; i++) {
  5053. for( int16 j = 0; j < MAX_MOB_LIST_PER_MAP; j++ ){
  5054. struct map_data *mapdata = map_getmapdata(i);
  5055. if (mapdata->moblist[j] != nullptr) {
  5056. aFree(mapdata->moblist[j]);
  5057. mapdata->moblist[j] = nullptr;
  5058. }
  5059. if( mapdata->mob_delete_timer != INVALID_TIMER )
  5060. { // Mobs were removed anyway,so delete the timer [Inkfish]
  5061. delete_timer(mapdata->mob_delete_timer, map_removemobs_timer);
  5062. mapdata->mob_delete_timer = INVALID_TIMER;
  5063. }
  5064. if( mapdata->npc_num > 0 ){
  5065. ShowWarning( "npc_reload: %d npcs weren't removed at map %s!\n", mapdata->npc_num, mapdata->name );
  5066. }
  5067. }
  5068. }
  5069. }
  5070. // clear mob spawn lookup index
  5071. mob_clear_spawninfo();
  5072. npc_warp = npc_shop = npc_script = 0;
  5073. npc_mob = npc_cache_mob = npc_delay_mob = 0;
  5074. // reset mapflags
  5075. map_flags_init();
  5076. npc_loadsrcfiles();
  5077. stylist_db.reload();
  5078. barter_db.reload();
  5079. //Re-read the NPC Script Events cache.
  5080. npc_read_event_script();
  5081. /* refresh guild castle flags on both woe setups */
  5082. npc_event_doall( script_config.agit_init_event_name );
  5083. npc_event_doall( script_config.agit_init2_event_name );
  5084. npc_event_doall( script_config.agit_init3_event_name );
  5085. //Execute the OnInit event for freshly loaded npcs. [Skotlex]
  5086. npc_event_runall(script_config.init_event_name);
  5087. map_data_copyall();
  5088. do_reload_instance();
  5089. // Execute rest of the startup events if connected to char-server. [Lance]
  5090. if(!CheckForCharServer()){
  5091. npc_event_runall(script_config.inter_init_event_name);
  5092. }
  5093. #if PACKETVER >= 20131223
  5094. npc_market_checkall();
  5095. #endif
  5096. return 0;
  5097. }
  5098. //Unload all npc in the given file
  5099. bool npc_unloadfile( const char* path ) {
  5100. DBIterator * iter = db_iterator(npcname_db);
  5101. struct npc_data* nd = nullptr;
  5102. bool found = false;
  5103. for( nd = (struct npc_data*)dbi_first(iter); dbi_exists(iter); nd = (struct npc_data*)dbi_next(iter) ) {
  5104. if( nd->path && strcasecmp(nd->path,path) == 0 ) {
  5105. found = true;
  5106. npc_unload_duplicates(nd);/* unload any npcs which could duplicate this but be in a different file */
  5107. npc_unload(nd, true);
  5108. }
  5109. }
  5110. dbi_destroy(iter);
  5111. if( found ) /* refresh event cache */
  5112. npc_read_event_script();
  5113. npc_delsrcfile(path);
  5114. return found;
  5115. }
  5116. void do_clear_npc(void) {
  5117. db_clear(npcname_db);
  5118. db_clear(ev_db);
  5119. }
  5120. /*==========================================
  5121. * Destructor
  5122. *------------------------------------------*/
  5123. void do_final_npc(void) {
  5124. npc_clear_pathlist();
  5125. script_event.clear();
  5126. ev_db->destroy(ev_db, nullptr);
  5127. npcname_db->destroy(npcname_db, nullptr);
  5128. npc_path_db->destroy(npc_path_db, nullptr);
  5129. #if PACKETVER >= 20131223
  5130. NPCMarketDB->destroy(NPCMarketDB, npc_market_free);
  5131. #endif
  5132. stylist_db.clear();
  5133. barter_db.clear();
  5134. ers_destroy(timer_event_ers);
  5135. ers_destroy(npc_sc_display_ers);
  5136. npc_src_files.clear();
  5137. }
  5138. static void npc_debug_warps_sub(struct npc_data* nd)
  5139. {
  5140. int16 m;
  5141. if (nd->bl.type != BL_NPC || nd->subtype != NPCTYPE_WARP || nd->bl.m < 0)
  5142. return;
  5143. m = map_mapindex2mapid(nd->u.warp.mapindex);
  5144. if (m < 0) return; //Warps to another map, nothing to do about it.
  5145. if (nd->u.warp.x == 0 && nd->u.warp.y == 0) return; // random warp
  5146. struct map_data *mapdata = map_getmapdata(m);
  5147. struct map_data *mapdata_nd = map_getmapdata(nd->bl.m);
  5148. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNPC)) {
  5149. ShowWarning("Warp %s at %s(%d,%d) warps directly on top of an area npc at %s(%d,%d)\n",
  5150. nd->name,
  5151. mapdata_nd->name, nd->bl.x, nd->bl.y,
  5152. mapdata->name, nd->u.warp.x, nd->u.warp.y
  5153. );
  5154. }
  5155. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNOPASS)) {
  5156. ShowWarning("Warp %s at %s(%d,%d) warps to a non-walkable tile at %s(%d,%d)\n",
  5157. nd->name,
  5158. mapdata_nd->name, nd->bl.x, nd->bl.y,
  5159. mapdata->name, nd->u.warp.x, nd->u.warp.y
  5160. );
  5161. }
  5162. }
  5163. static void npc_debug_warps(void){
  5164. for (int i = 0; i < map_num; i++) {
  5165. struct map_data *mapdata = map_getmapdata(i);
  5166. for( int i = 0; i < mapdata->npc_num; i++ ){
  5167. npc_debug_warps_sub(mapdata->npc[i]);
  5168. }
  5169. }
  5170. }
  5171. /*==========================================
  5172. * npc initialization
  5173. *------------------------------------------*/
  5174. void do_init_npc(void){
  5175. int i;
  5176. //Stock view data for normal npcs.
  5177. memset(&npc_viewdb, 0, sizeof(npc_viewdb));
  5178. npc_viewdb[0].class_ = JT_INVISIBLE; //Invisible class is stored here.
  5179. for( i = 1; i < MAX_NPC_CLASS; i++ )
  5180. npc_viewdb[i].class_ = i;
  5181. for( i = MAX_NPC_CLASS2_START; i < MAX_NPC_CLASS2_END; i++ )
  5182. npc_viewdb2[i - MAX_NPC_CLASS2_START].class_ = i;
  5183. ev_db = strdb_alloc((DBOptions)(DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA), EVENT_NAME_LENGTH);
  5184. npcname_db = strdb_alloc(DB_OPT_BASE, NPC_NAME_LENGTH+1);
  5185. npc_path_db = strdb_alloc((DBOptions)(DB_OPT_BASE|DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA),80);
  5186. #if PACKETVER >= 20131223
  5187. NPCMarketDB = strdb_alloc(DB_OPT_BASE, NPC_NAME_LENGTH+1);
  5188. npc_market_fromsql();
  5189. #endif
  5190. timer_event_ers = ers_new(sizeof(struct timer_event_data),"npc.cpp::timer_event_ers",ERS_OPT_NONE);
  5191. npc_sc_display_ers = ers_new(sizeof(struct sc_display_entry), "npc.cpp:npc_sc_display_ers", ERS_OPT_NONE);
  5192. npc_loadsrcfiles();
  5193. stylist_db.load();
  5194. barter_db.load();
  5195. // set up the events cache
  5196. npc_read_event_script();
  5197. #if PACKETVER >= 20131223
  5198. npc_market_checkall();
  5199. #endif
  5200. //Debug function to locate all endless loop warps.
  5201. if (battle_config.warp_point_debug)
  5202. npc_debug_warps();
  5203. add_timer_func_list(npc_event_do_clock,"npc_event_do_clock");
  5204. add_timer_func_list(npc_timerevent,"npc_timerevent");
  5205. add_timer_func_list( npc_dynamicnpc_removal_timer, "npc_dynamicnpc_removal_timer" );
  5206. #ifdef SECURE_NPCTIMEOUT
  5207. add_timer_func_list( npc_secure_timeout_timer, "npc_secure_timeout_timer" );
  5208. #endif
  5209. // Init dummy NPC
  5210. fake_nd = npc_create_npc( -1, 0, 0 );
  5211. fake_nd->class_ = JT_FAKENPC;
  5212. fake_nd->speed = 200;
  5213. strcpy(fake_nd->name,"FAKE_NPC");
  5214. memcpy(fake_nd->exname, fake_nd->name, 9);
  5215. npc_script++;
  5216. fake_nd->bl.type = BL_NPC;
  5217. fake_nd->subtype = NPCTYPE_SCRIPT;
  5218. strdb_put(npcname_db, fake_nd->exname, fake_nd);
  5219. fake_nd->u.scr.timerid = INVALID_TIMER;
  5220. map_addiddb(&fake_nd->bl);
  5221. // End of initialization
  5222. }