npc.c 136 KB

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