npc.cpp 146 KB

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