npc.c 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496
  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 "../common/socket.h"
  13. #include "map.h"
  14. #include "log.h"
  15. #include "clif.h"
  16. #include "intif.h"
  17. #include "pc.h"
  18. #include "status.h"
  19. #include "itemdb.h"
  20. #include "script.h"
  21. #include "mob.h"
  22. #include "pet.h"
  23. #include "instance.h"
  24. #include "battle.h"
  25. #include "skill.h"
  26. #include "unit.h"
  27. #include "npc.h"
  28. #include "chat.h"
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <math.h>
  33. #include <time.h>
  34. #include <errno.h>
  35. struct npc_data* fake_nd;
  36. // linked list of npc source files
  37. struct npc_src_list {
  38. struct npc_src_list* next;
  39. char name[4]; // dynamic array, the structure is allocated with extra bytes (string length)
  40. };
  41. static struct npc_src_list* npc_src_files = NULL;
  42. static int npc_id=START_NPC_NUM;
  43. static int npc_warp=0;
  44. static int npc_shop=0;
  45. static int npc_script=0;
  46. static int npc_mob=0;
  47. static int npc_delay_mob=0;
  48. static int npc_cache_mob=0;
  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. {
  53. if( npc_id >= START_NPC_NUM && map_id2bl(npc_id) == NULL )
  54. return npc_id++;// available
  55. {// find next id
  56. int base_id = npc_id;
  57. while( base_id != ++npc_id )
  58. {
  59. if( npc_id < START_NPC_NUM )
  60. npc_id = START_NPC_NUM;
  61. if( map_id2bl(npc_id) == NULL )
  62. return npc_id++;// available
  63. }
  64. // full loop, nothing available
  65. ShowFatalError("npc_get_new_npc_id: All ids are taken. Exiting...");
  66. exit(1);
  67. }
  68. }
  69. static DBMap* ev_db; // const char* event_name -> struct event_data*
  70. DBMap* npcname_db; // const char* npc_name -> struct npc_data*
  71. struct event_data {
  72. struct npc_data *nd;
  73. int pos;
  74. };
  75. static struct eri *timer_event_ers; //For the npc timer data. [Skotlex]
  76. //For holding the view data of npc classes. [Skotlex]
  77. static struct view_data npc_viewdb[MAX_NPC_CLASS];
  78. static struct script_event_s
  79. { //Holds pointers to the commonly executed scripts for speedup. [Skotlex]
  80. struct event_data *event[UCHAR_MAX];
  81. const char *event_name[UCHAR_MAX];
  82. uint8 event_count;
  83. } script_event[NPCE_MAX];
  84. struct view_data* npc_get_viewdata(int class_)
  85. { //Returns the viewdata for normal npc classes.
  86. if (class_ == INVISIBLE_CLASS)
  87. return &npc_viewdb[0];
  88. if (npcdb_checkid(class_) || class_ == WARP_CLASS)
  89. return &npc_viewdb[class_];
  90. return NULL;
  91. }
  92. int npc_ontouch_event(struct map_session_data *sd, struct npc_data *nd)
  93. {
  94. char name[NAME_LENGTH*2+3];
  95. if( nd->touching_id )
  96. return 0; // Attached a player already. Can't trigger on anyone else.
  97. if( pc_ishiding(sd) )
  98. return 1; // Can't trigger 'OnTouch_'. try 'OnTouch' later.
  99. snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_name);
  100. return npc_event(sd,name,1);
  101. }
  102. int npc_ontouch2_event(struct map_session_data *sd, struct npc_data *nd)
  103. {
  104. char name[NAME_LENGTH*2+3];
  105. if( sd->areanpc_id == nd->bl.id )
  106. return 0;
  107. snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch2_name);
  108. return npc_event(sd,name,2);
  109. }
  110. /*==========================================
  111. * NPCの無効化/有効化
  112. * npc_enable
  113. * npc_enable_sub 有効時にOnTouchイベントを実行
  114. *------------------------------------------*/
  115. int npc_enable_sub(struct block_list *bl, va_list ap)
  116. {
  117. struct npc_data *nd;
  118. nullpo_ret(bl);
  119. nullpo_ret(nd=va_arg(ap,struct npc_data *));
  120. if(bl->type == BL_PC)
  121. {
  122. TBL_PC *sd = (TBL_PC*)bl;
  123. if (nd->sc.option&OPTION_INVISIBLE)
  124. return 1;
  125. if( npc_ontouch_event(sd,nd) > 0 && npc_ontouch2_event(sd,nd) > 0 )
  126. { // failed to run OnTouch event, so just click the npc
  127. if (sd->npc_id != 0)
  128. return 0;
  129. pc_stop_walking(sd,1);
  130. npc_click(sd,nd);
  131. }
  132. }
  133. return 0;
  134. }
  135. int npc_enable(const char* name, int flag)
  136. {
  137. struct npc_data* nd = (struct npc_data*)strdb_get(npcname_db, name);
  138. if (nd==NULL)
  139. return 0;
  140. if (flag&1)
  141. nd->sc.option&=~OPTION_INVISIBLE;
  142. else if (flag&2)
  143. nd->sc.option&=~OPTION_HIDE;
  144. else if (flag&4)
  145. nd->sc.option|= OPTION_HIDE;
  146. else //Can't change the view_data to invisible class because the view_data for all npcs is shared! [Skotlex]
  147. nd->sc.option|= OPTION_INVISIBLE;
  148. if (nd->class_ == WARP_CLASS || nd->class_ == FLAG_CLASS)
  149. { //Client won't display option changes for these classes [Toms]
  150. if (nd->sc.option&(OPTION_HIDE|OPTION_INVISIBLE))
  151. clif_clearunit_area(&nd->bl, CLR_OUTSIGHT);
  152. else
  153. clif_spawn(&nd->bl);
  154. } else
  155. clif_changeoption(&nd->bl);
  156. if( flag&3 && (nd->u.scr.xs >= 0 || nd->u.scr.ys >= 0) )
  157. 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 );
  158. return 0;
  159. }
  160. /*==========================================
  161. * NPCを名前で探す
  162. *------------------------------------------*/
  163. struct npc_data* npc_name2id(const char* name)
  164. {
  165. return (struct npc_data *) strdb_get(npcname_db, name);
  166. }
  167. /*==========================================
  168. * イベントキューのイベント処理
  169. *------------------------------------------*/
  170. int npc_event_dequeue(struct map_session_data* sd)
  171. {
  172. nullpo_ret(sd);
  173. if(sd->npc_id)
  174. { //Current script is aborted.
  175. if(sd->state.using_fake_npc){
  176. clif_clearunit_single(sd->npc_id, CLR_OUTSIGHT, sd->fd);
  177. sd->state.using_fake_npc = 0;
  178. }
  179. if (sd->st) {
  180. script_free_state(sd->st);
  181. sd->st = NULL;
  182. }
  183. sd->npc_id = 0;
  184. }
  185. if (!sd->eventqueue[0][0])
  186. return 0; //Nothing to dequeue
  187. if (!pc_addeventtimer(sd,100,sd->eventqueue[0]))
  188. { //Failed to dequeue, couldn't set a timer.
  189. ShowWarning("npc_event_dequeue: event timer is full !\n");
  190. return 0;
  191. }
  192. //Event dequeued successfully, shift other elements.
  193. memmove(sd->eventqueue[0], sd->eventqueue[1], (MAX_EVENTQUEUE-1)*sizeof(sd->eventqueue[0]));
  194. sd->eventqueue[MAX_EVENTQUEUE-1][0]=0;
  195. return 1;
  196. }
  197. /*==========================================
  198. * exports a npc event label
  199. * npc_parse_script->strdb_foreachから呼ばれる
  200. *------------------------------------------*/
  201. int npc_event_export(char* lname, void* data, va_list ap)
  202. {
  203. int pos = (int)data;
  204. struct npc_data* nd = va_arg(ap, struct npc_data *);
  205. if ((lname[0]=='O' || lname[0]=='o')&&(lname[1]=='N' || lname[1]=='n')) {
  206. struct event_data *ev;
  207. char buf[NAME_LENGTH*2+3];
  208. char* p = strchr(lname, ':');
  209. // エクスポートされる
  210. ev = (struct event_data *) aMalloc(sizeof(struct event_data));
  211. if (ev==NULL) {
  212. ShowFatalError("npc_event_export: out of memory !\n");
  213. exit(EXIT_FAILURE);
  214. }else if (p==NULL || (p-lname)>NAME_LENGTH) {
  215. ShowFatalError("npc_event_export: label name error !\n");
  216. exit(EXIT_FAILURE);
  217. }else{
  218. ev->nd = nd;
  219. ev->pos = pos;
  220. *p = '\0';
  221. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, lname);
  222. *p = ':';
  223. strdb_put(ev_db, buf, ev);
  224. }
  225. }
  226. return 0;
  227. }
  228. int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname); //[Lance]
  229. /*==========================================
  230. * 全てのNPCのOn*イベント実行
  231. *------------------------------------------*/
  232. int npc_event_doall_sub(DBKey key, void* data, va_list ap)
  233. {
  234. const char* p = key.str;
  235. struct event_data* ev;
  236. int* c;
  237. const char* name;
  238. int rid;
  239. nullpo_ret(ev = (struct event_data *)data);
  240. nullpo_ret(c = va_arg(ap, int *));
  241. nullpo_ret(name = va_arg(ap, const char *));
  242. rid = va_arg(ap, int);
  243. p = strchr(p, ':'); // match only the event name
  244. if( p && strcmpi(name, p) == 0 /* && !ev->nd->src_id */ ) // Do not run on duplicates. [Paradox924X]
  245. {
  246. if(rid) // a player may only have 1 script running at the same time
  247. npc_event_sub(map_id2sd(rid),ev,key.str);
  248. else
  249. run_script(ev->nd->u.scr.script,ev->pos,rid,ev->nd->bl.id);
  250. (*c)++;
  251. }
  252. return 0;
  253. }
  254. static int npc_event_do_sub(DBKey key, void* data, va_list ap)
  255. {
  256. const char* p = key.str;
  257. struct event_data* ev;
  258. int* c;
  259. const char* name;
  260. nullpo_ret(ev = (struct event_data *)data);
  261. nullpo_ret(c = va_arg(ap, int *));
  262. nullpo_ret(name = va_arg(ap, const char *));
  263. if( p && strcmpi(name, p) == 0 )
  264. {
  265. run_script(ev->nd->u.scr.script,ev->pos,0,ev->nd->bl.id);
  266. (*c)++;
  267. }
  268. return 0;
  269. }
  270. // runs the specified event (supports both single-npc and global events)
  271. int npc_event_do(const char* name)
  272. {
  273. int c = 0;
  274. if( name[0] == ':' && name[1] == ':' )
  275. ev_db->foreach(ev_db,npc_event_doall_sub,&c,name,0);
  276. else
  277. ev_db->foreach(ev_db,npc_event_do_sub,&c,name);
  278. return c;
  279. }
  280. // runs the specified event (global only)
  281. int npc_event_doall(const char* name)
  282. {
  283. return npc_event_doall_id(name, 0);
  284. }
  285. // runs the specified event, with a RID attached (global only)
  286. int npc_event_doall_id(const char* name, int rid)
  287. {
  288. int c = 0;
  289. char buf[64];
  290. safesnprintf(buf, sizeof(buf), "::%s", name);
  291. ev_db->foreach(ev_db,npc_event_doall_sub,&c,buf,rid);
  292. return c;
  293. }
  294. /*==========================================
  295. * 時計イベント実行
  296. *------------------------------------------*/
  297. int npc_event_do_clock(int tid, unsigned int tick, int id, intptr data)
  298. {
  299. static struct tm ev_tm_b; // tracks previous execution time
  300. time_t timer;
  301. struct tm* t;
  302. char buf[64];
  303. char* day;
  304. int c = 0;
  305. timer = time(NULL);
  306. t = localtime(&timer);
  307. switch (t->tm_wday) {
  308. case 0: day = "Sun"; break;
  309. case 1: day = "Mon"; break;
  310. case 2: day = "Tue"; break;
  311. case 3: day = "Wed"; break;
  312. case 4: day = "Thu"; break;
  313. case 5: day = "Fri"; break;
  314. case 6: day = "Sat"; break;
  315. default:day = ""; break;
  316. }
  317. if (t->tm_min != ev_tm_b.tm_min ) {
  318. sprintf(buf,"OnMinute%02d",t->tm_min);
  319. c+=npc_event_doall(buf);
  320. sprintf(buf,"OnClock%02d%02d",t->tm_hour,t->tm_min);
  321. c+=npc_event_doall(buf);
  322. sprintf(buf,"On%s%02d%02d",day,t->tm_hour,t->tm_min);
  323. c+=npc_event_doall(buf);
  324. }
  325. if (t->tm_hour!= ev_tm_b.tm_hour) {
  326. sprintf(buf,"OnHour%02d",t->tm_hour);
  327. c+=npc_event_doall(buf);
  328. }
  329. if (t->tm_mday!= ev_tm_b.tm_mday) {
  330. sprintf(buf,"OnDay%02d%02d",t->tm_mon+1,t->tm_mday);
  331. c+=npc_event_doall(buf);
  332. }
  333. memcpy(&ev_tm_b,t,sizeof(ev_tm_b));
  334. return c;
  335. }
  336. /*==========================================
  337. * OnInitイベント実行(&時計イベント開始)
  338. *------------------------------------------*/
  339. void npc_event_do_oninit(void)
  340. {
  341. ShowStatus("Event '"CL_WHITE"OnInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs."CL_CLL"\n", npc_event_doall("OnInit"));
  342. add_timer_interval(gettick()+100,npc_event_do_clock,0,0,1000);
  343. }
  344. /*==========================================
  345. * タイマーイベント用ラベルの取り込み
  346. * npc_parse_script->strdb_foreachから呼ばれる
  347. *------------------------------------------*/
  348. int npc_timerevent_import(char* lname, void* data, va_list ap)
  349. {
  350. int pos = (int)data;
  351. struct npc_data *nd = va_arg(ap,struct npc_data *);
  352. int t = 0, i = 0;
  353. if( sscanf(lname,"OnTimer%d%n",&t,&i)==1 && lname[i]==':' )
  354. {
  355. struct npc_timerevent_list *te= nd->u.scr.timer_event;
  356. int j, i = nd->u.scr.timeramount;
  357. if( te == NULL )
  358. te = (struct npc_timerevent_list*)aMallocA( sizeof(struct npc_timerevent_list) );
  359. else
  360. te = (struct npc_timerevent_list*)aRealloc( te, sizeof(struct npc_timerevent_list) * (i+1) );
  361. if( te == NULL )
  362. {
  363. ShowFatalError("npc_timerevent_import: out of memory !\n");
  364. exit(EXIT_FAILURE);
  365. }
  366. ARR_FIND( 0, i, j, te[j].timer > t );
  367. if( j < i )
  368. memmove(te+j+1,te+j,sizeof(struct npc_timerevent_list)*(i-j));
  369. te[j].timer = t;
  370. te[j].pos = pos;
  371. nd->u.scr.timer_event = te;
  372. nd->u.scr.timeramount++;
  373. }
  374. return 0;
  375. }
  376. struct timer_event_data {
  377. int rid; //Attached player for this timer.
  378. int next; //timer index (starts with 0, then goes up to nd->u.scr.timeramount)
  379. int time; //holds total time elapsed for the script from when timer was started to when last time the event triggered.
  380. };
  381. /*==========================================
  382. * triger 'OnTimerXXXX' events
  383. *------------------------------------------*/
  384. int npc_timerevent(int tid, unsigned int tick, int id, intptr data)
  385. {
  386. int next;
  387. int old_rid, old_timer;
  388. unsigned int old_tick;
  389. struct npc_data* nd=(struct npc_data *)map_id2bl(id);
  390. struct npc_timerevent_list *te;
  391. struct timer_event_data *ted = (struct timer_event_data*)data;
  392. struct map_session_data *sd=NULL;
  393. if( nd == NULL )
  394. {
  395. ShowError("npc_timerevent: NPC not found??\n");
  396. return 0;
  397. }
  398. if( ted->rid && !(sd = map_id2sd(ted->rid)) )
  399. {
  400. ShowError("npc_timerevent: Attached player not found.\n");
  401. ers_free(timer_event_ers, ted);
  402. return 0;
  403. }
  404. // These stuffs might need to be restored.
  405. old_rid = nd->u.scr.rid;
  406. old_tick = nd->u.scr.timertick;
  407. old_timer = nd->u.scr.timer;
  408. // Set the values of the timer
  409. nd->u.scr.rid = sd?sd->bl.id:0; //attached rid
  410. nd->u.scr.timertick = tick; //current time tick
  411. nd->u.scr.timer = ted->time; //total time from beginning to now
  412. // Locate the event
  413. te = nd->u.scr.timer_event + ted->next;
  414. // Arrange for the next event
  415. ted->next++;
  416. if( nd->u.scr.timeramount > ted->next )
  417. {
  418. next = nd->u.scr.timer_event[ ted->next ].timer - nd->u.scr.timer_event[ ted->next - 1 ].timer;
  419. ted->time += next;
  420. if( sd )
  421. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,id,(intptr)ted);
  422. else
  423. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,id,(intptr)ted);
  424. }
  425. else
  426. {
  427. if( sd )
  428. sd->npc_timer_id = -1;
  429. else
  430. {
  431. nd->u.scr.timerid = -1;
  432. nd->u.scr.timertick = 0; // NPC timer stopped
  433. }
  434. ers_free(timer_event_ers, ted);
  435. }
  436. // Run the script
  437. run_script(nd->u.scr.script,te->pos,nd->u.scr.rid,nd->bl.id);
  438. nd->u.scr.rid = old_rid; // Attached-rid should be restored anyway.
  439. if( sd )
  440. { // Restore previous data, only if this timer is a player-attached one.
  441. nd->u.scr.timer = old_timer;
  442. nd->u.scr.timertick = old_tick;
  443. }
  444. return 0;
  445. }
  446. /*==========================================
  447. * Start/Resume NPC timer
  448. *------------------------------------------*/
  449. int npc_timerevent_start(struct npc_data* nd, int rid)
  450. {
  451. int j, next;
  452. unsigned int tick = gettick();
  453. struct map_session_data *sd = NULL; //Player to whom script is attached.
  454. struct timer_event_data *ted;
  455. nullpo_ret(nd);
  456. // No need to start because of no events
  457. if( nd->u.scr.timeramount == 0 )
  458. return 0;
  459. // Check if there is an OnTimer Event
  460. ARR_FIND( 0, nd->u.scr.timeramount, j, nd->u.scr.timer_event[j].timer > nd->u.scr.timer );
  461. if( j >= nd->u.scr.timeramount ) // No need to start because of no events left to trigger
  462. return 0;
  463. if( nd->u.scr.rid > 0 && !(sd = map_id2sd(nd->u.scr.rid)) )
  464. { // Failed to attach timer to this player.
  465. ShowError("npc_timerevent_start: Attached player not found!\n");
  466. return 1;
  467. }
  468. // Check if timer is already started.
  469. if( sd )
  470. {
  471. if( sd->npc_timer_id != -1 )
  472. return 0;
  473. }
  474. else if( nd->u.scr.timerid != -1 )
  475. return 0;
  476. // Arrange for the next event
  477. ted = ers_alloc(timer_event_ers, struct timer_event_data);
  478. ted->next = j; // Set event index
  479. ted->time = nd->u.scr.timer_event[j].timer;
  480. next = nd->u.scr.timer_event[j].timer - nd->u.scr.timer;
  481. if( sd )
  482. {
  483. ted->rid = sd->bl.id; // Attach only the player if attachplayerrid was used.
  484. sd->npc_timer_id = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr)ted);
  485. }
  486. else
  487. {
  488. ted->rid = 0;
  489. nd->u.scr.timertick = tick; // Set when timer is started
  490. nd->u.scr.timerid = add_timer(tick+next,npc_timerevent,nd->bl.id,(intptr)ted);
  491. }
  492. return 0;
  493. }
  494. /*==========================================
  495. * Stop NPC timer
  496. *------------------------------------------*/
  497. int npc_timerevent_stop(struct npc_data* nd)
  498. {
  499. struct map_session_data *sd = NULL;
  500. const struct TimerData *td = NULL;
  501. int *tid;
  502. nullpo_ret(nd);
  503. if( nd->u.scr.rid && !(sd = map_id2sd(nd->u.scr.rid)) )
  504. {
  505. ShowError("npc_timerevent_stop: Attached player not found!\n");
  506. return 1;
  507. }
  508. tid = sd?&sd->npc_timer_id:&nd->u.scr.timerid;
  509. if( *tid == -1 ) // Nothing to stop
  510. return 0;
  511. // Delete timer
  512. td = get_timer(*tid);
  513. if( td && td->data )
  514. ers_free(timer_event_ers, (void*)td->data);
  515. delete_timer(*tid,npc_timerevent);
  516. *tid = -1;
  517. if( !sd )
  518. {
  519. 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
  520. nd->u.scr.timertick = 0; // Set 'tick' to zero so that we know it's off.
  521. }
  522. return 0;
  523. }
  524. /*==========================================
  525. * Aborts a running NPC timer that is attached to a player.
  526. *------------------------------------------*/
  527. void npc_timerevent_quit(struct map_session_data* sd)
  528. {
  529. const struct TimerData *td;
  530. struct npc_data* nd;
  531. struct timer_event_data *ted;
  532. // Check timer existance
  533. if( sd->npc_timer_id == -1 )
  534. return;
  535. if( !(td = get_timer(sd->npc_timer_id)) )
  536. {
  537. sd->npc_timer_id = -1;
  538. return;
  539. }
  540. // Delete timer
  541. nd = (struct npc_data *)map_id2bl(td->id);
  542. ted = (struct timer_event_data*)td->data;
  543. delete_timer(sd->npc_timer_id, npc_timerevent);
  544. sd->npc_timer_id = -1;
  545. // Execute OnTimerQuit
  546. if( nd && nd->bl.type == BL_NPC )
  547. {
  548. char buf[NAME_LENGTH*2+3];
  549. struct event_data *ev;
  550. snprintf(buf, ARRAYLENGTH(buf), "%s::OnTimerQuit", nd->exname);
  551. ev = (struct event_data*)strdb_get(ev_db, buf);
  552. if( ev && ev->nd != nd )
  553. {
  554. ShowWarning("npc_timerevent_quit: Unable to execute \"OnTimerQuit\", two NPCs have the same event name [%s]!\n",buf);
  555. ev = NULL;
  556. }
  557. if( ev )
  558. {
  559. int old_rid,old_timer;
  560. unsigned int old_tick;
  561. //Set timer related info.
  562. old_rid = (nd->u.scr.rid == sd->bl.id ? 0 : nd->u.scr.rid); // Detach rid if the last attached player logged off.
  563. old_tick = nd->u.scr.timertick;
  564. old_timer = nd->u.scr.timer;
  565. nd->u.scr.rid = sd->bl.id;
  566. nd->u.scr.timertick = gettick();
  567. nd->u.scr.timer = ted->time;
  568. //Execute label
  569. run_script(nd->u.scr.script,ev->pos,sd->bl.id,nd->bl.id);
  570. //Restore previous data.
  571. nd->u.scr.rid = old_rid;
  572. nd->u.scr.timer = old_timer;
  573. nd->u.scr.timertick = old_tick;
  574. }
  575. }
  576. ers_free(timer_event_ers, ted);
  577. }
  578. /*==========================================
  579. * Get the tick value of an NPC timer
  580. * If it's stopped, return stopped time
  581. *------------------------------------------*/
  582. int npc_gettimerevent_tick(struct npc_data* nd)
  583. {
  584. int tick;
  585. nullpo_ret(nd);
  586. // TODO: Get player attached timer's tick. Now we can just get it by using 'getnpctimer' inside OnTimer event.
  587. tick = nd->u.scr.timer; // The last time it's active(start, stop or event trigger)
  588. if( nd->u.scr.timertick ) // It's a running timer
  589. tick += DIFF_TICK(gettick(), nd->u.scr.timertick);
  590. return tick;
  591. }
  592. /*==========================================
  593. * Set tick for running and stopped timer
  594. *------------------------------------------*/
  595. int npc_settimerevent_tick(struct npc_data* nd, int newtimer)
  596. {
  597. bool flag;
  598. int old_rid;
  599. //struct map_session_data *sd = NULL;
  600. nullpo_ret(nd);
  601. // TODO: Set player attached timer's tick.
  602. old_rid = nd->u.scr.rid;
  603. nd->u.scr.rid = 0;
  604. // Check if timer is started
  605. flag = (nd->u.scr.timerid != INVALID_TIMER);
  606. if( flag ) npc_timerevent_stop(nd);
  607. nd->u.scr.timer = newtimer;
  608. if( flag ) npc_timerevent_start(nd, -1);
  609. nd->u.scr.rid = old_rid;
  610. return 0;
  611. }
  612. int npc_event_sub(struct map_session_data* sd, struct event_data* ev, const char* eventname)
  613. {
  614. if ( sd->npc_id != 0 )
  615. {
  616. //Enqueue the event trigger.
  617. int i;
  618. ARR_FIND( 0, MAX_EVENTQUEUE, i, sd->eventqueue[i][0] == '\0' );
  619. if( i < MAX_EVENTQUEUE )
  620. {
  621. safestrncpy(sd->eventqueue[i],eventname,50); //Event enqueued.
  622. return 0;
  623. }
  624. ShowWarning("npc_event: player's event queue is full, can't add event '%s' !\n", eventname);
  625. return 1;
  626. }
  627. if( ev->nd->sc.option&OPTION_INVISIBLE )
  628. {
  629. //Disabled npc, shouldn't trigger event.
  630. npc_event_dequeue(sd);
  631. return 2;
  632. }
  633. run_script(ev->nd->u.scr.script,ev->pos,sd->bl.id,ev->nd->bl.id);
  634. return 0;
  635. }
  636. /*==========================================
  637. * イベント型のNPC処理
  638. *------------------------------------------*/
  639. int npc_event(struct map_session_data* sd, const char* eventname, int ontouch)
  640. {
  641. struct event_data* ev = (struct event_data*)strdb_get(ev_db, eventname);
  642. struct npc_data *nd;
  643. nullpo_ret(sd);
  644. if( ev == NULL || (nd = ev->nd) == NULL )
  645. {
  646. if( !ontouch )
  647. ShowError("npc_event: event not found [%s]\n", eventname);
  648. return ontouch;
  649. }
  650. switch(ontouch)
  651. {
  652. case 1:
  653. nd->touching_id = sd->bl.id;
  654. sd->touching_id = nd->bl.id;
  655. break;
  656. case 2:
  657. sd->areanpc_id = nd->bl.id;
  658. break;
  659. }
  660. return npc_event_sub(sd,ev,eventname);
  661. }
  662. int npc_touch_areanpc_sub(struct block_list *bl, va_list ap)
  663. {
  664. struct map_session_data *sd;
  665. int pc_id,npc_id;
  666. char *name;
  667. nullpo_ret(bl);
  668. nullpo_ret((sd = map_id2sd(bl->id)));
  669. pc_id = va_arg(ap,int);
  670. npc_id = va_arg(ap,int);
  671. name = va_arg(ap,char*);
  672. if( pc_ishiding(sd) )
  673. return 0;
  674. if( pc_id == sd->bl.id )
  675. return 0;
  676. npc_event(sd,name,1);
  677. return 1;
  678. }
  679. int npc_touchnext_areanpc(struct map_session_data* sd, bool leavemap)
  680. {
  681. struct npc_data *nd = map_id2nd(sd->touching_id);
  682. short xs, ys;
  683. if( !nd || nd->touching_id != sd->bl.id )
  684. return 1;
  685. xs = nd->u.scr.xs;
  686. ys = nd->u.scr.ys;
  687. if( sd->bl.m != nd->bl.m ||
  688. sd->bl.x < nd->bl.x - xs || sd->bl.x > nd->bl.x + xs ||
  689. sd->bl.y < nd->bl.y - ys || sd->bl.y > nd->bl.y + ys ||
  690. pc_ishiding(sd) || leavemap )
  691. {
  692. char name[NAME_LENGTH*2+3];
  693. nd->touching_id = sd->touching_id = 0;
  694. snprintf(name, ARRAYLENGTH(name), "%s::%s", nd->exname, script_config.ontouch_name);
  695. map_forcountinarea(npc_touch_areanpc_sub,nd->bl.m,nd->bl.m - xs,nd->bl.y - ys,nd->bl.x + xs,nd->bl.y + ys,1,BL_PC,sd->bl.id,nd->bl.id,name);
  696. }
  697. return 0;
  698. }
  699. /*==========================================
  700. * 接触型のNPC処理
  701. *------------------------------------------*/
  702. int npc_touch_areanpc(struct map_session_data* sd, int m, int x, int y)
  703. {
  704. int xs,ys;
  705. int f = 1;
  706. int i;
  707. nullpo_retr(1, sd);
  708. // Why not enqueue it? [Inkfish]
  709. //if(sd->npc_id)
  710. // return 1;
  711. for(i=0;i<map[m].npc_num;i++)
  712. {
  713. if (map[m].npc[i]->sc.option&OPTION_INVISIBLE) {
  714. f=0; // a npc was found, but it is disabled; don't print warning
  715. continue;
  716. }
  717. switch(map[m].npc[i]->subtype) {
  718. case WARP:
  719. xs=map[m].npc[i]->u.warp.xs;
  720. ys=map[m].npc[i]->u.warp.ys;
  721. break;
  722. case SCRIPT:
  723. xs=map[m].npc[i]->u.scr.xs;
  724. ys=map[m].npc[i]->u.scr.ys;
  725. break;
  726. default:
  727. continue;
  728. }
  729. if( x >= map[m].npc[i]->bl.x-xs && x <= map[m].npc[i]->bl.x+xs
  730. && y >= map[m].npc[i]->bl.y-ys && y <= map[m].npc[i]->bl.y+ys )
  731. break;
  732. }
  733. if( i == map[m].npc_num )
  734. {
  735. if( f == 1 ) // no npc found
  736. ShowError("npc_touch_areanpc : stray NPC cell on coordinates '%s',%d,%d\n", map[m].name, x, y);
  737. return 1;
  738. }
  739. switch(map[m].npc[i]->subtype) {
  740. case WARP:
  741. if( pc_ishiding(sd) )
  742. break; // hidden chars cannot use warps
  743. 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);
  744. break;
  745. case SCRIPT:
  746. if( npc_ontouch_event(sd,map[m].npc[i]) > 0 && npc_ontouch2_event(sd,map[m].npc[i]) > 0 )
  747. { // failed to run OnTouch event, so just click the npc
  748. struct unit_data *ud = unit_bl2ud(&sd->bl);
  749. if( ud && ud->walkpath.path_pos < ud->walkpath.path_len )
  750. { // Since walktimer always == -1 at this time, we stop walking manually. [Inkfish]
  751. clif_fixpos(&sd->bl);
  752. ud->walkpath.path_pos = ud->walkpath.path_len;
  753. }
  754. sd->areanpc_id = map[m].npc[i]->bl.id;
  755. npc_click(sd,map[m].npc[i]);
  756. }
  757. break;
  758. }
  759. return 0;
  760. }
  761. // OnTouch NPC or Warp for Mobs
  762. // Return 1 if Warped
  763. int npc_touch_areanpc2(struct mob_data *md)
  764. {
  765. int i, m = md->bl.m, x = md->bl.x, y = md->bl.y, id;
  766. char eventname[NAME_LENGTH*2+3];
  767. struct event_data* ev;
  768. int xs, ys;
  769. for( i = 0; i < map[m].npc_num; i++ )
  770. {
  771. if( map[m].npc[i]->sc.option&OPTION_INVISIBLE )
  772. continue;
  773. switch( map[m].npc[i]->subtype )
  774. {
  775. case WARP:
  776. if( !battle_config.mob_warp&1 )
  777. continue;
  778. xs = map[m].npc[i]->u.warp.xs;
  779. ys = map[m].npc[i]->u.warp.ys;
  780. break;
  781. case SCRIPT:
  782. xs = map[m].npc[i]->u.scr.xs;
  783. ys = map[m].npc[i]->u.scr.ys;
  784. break;
  785. default:
  786. continue; // Keep Searching
  787. }
  788. 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 )
  789. { // In the npc touch area
  790. switch( map[m].npc[i]->subtype )
  791. {
  792. case WARP:
  793. xs = map_mapindex2mapid(map[m].npc[i]->u.warp.mapindex);
  794. if( m < 0 )
  795. break; // Cannot Warp between map servers
  796. if( unit_warp(&md->bl, xs, map[m].npc[i]->u.warp.x, map[m].npc[i]->u.warp.y, CLR_OUTSIGHT) == 0 )
  797. return 1; // Warped
  798. break;
  799. case SCRIPT:
  800. if( map[m].npc[i]->bl.id == md->areanpc_id )
  801. break; // Already touch this NPC
  802. snprintf(eventname, ARRAYLENGTH(eventname), "%s::OnTouchNPC", map[m].npc[i]->exname);
  803. if( (ev = (struct event_data*)strdb_get(ev_db, eventname)) == NULL || ev->nd == NULL )
  804. break; // No OnTouchNPC Event
  805. md->areanpc_id = map[m].npc[i]->bl.id;
  806. id = md->bl.id; // Stores Unique ID
  807. run_script(ev->nd->u.scr.script, ev->pos, md->bl.id, ev->nd->bl.id);
  808. if( map_id2md(id) == NULL ) return 1; // Not Warped, but killed
  809. break;
  810. }
  811. return 0;
  812. }
  813. }
  814. return 0;
  815. }
  816. //Checks if there are any NPC on-touch objects on the given range.
  817. //Flag determines the type of object to check for:
  818. //&1: NPC Warps
  819. //&2: NPCs with on-touch events.
  820. int npc_check_areanpc(int flag, int m, int x, int y, int range)
  821. {
  822. int i;
  823. int x0,y0,x1,y1;
  824. int xs,ys;
  825. if (range < 0) return 0;
  826. x0 = max(x-range, 0);
  827. y0 = max(y-range, 0);
  828. x1 = min(x+range, map[m].xs-1);
  829. y1 = min(y+range, map[m].ys-1);
  830. //First check for npc_cells on the range given
  831. i = 0;
  832. for (ys = y0; ys <= y1 && !i; ys++) {
  833. for(xs = x0; xs <= x1 && !i; xs++){
  834. if (map_getcell(m,xs,ys,CELL_CHKNPC))
  835. i = 1;
  836. }
  837. }
  838. if (!i) return 0; //No NPC_CELLs.
  839. //Now check for the actual NPC on said range.
  840. for(i=0;i<map[m].npc_num;i++)
  841. {
  842. if (map[m].npc[i]->sc.option&OPTION_INVISIBLE)
  843. continue;
  844. switch(map[m].npc[i]->subtype)
  845. {
  846. case WARP:
  847. if (!(flag&1))
  848. continue;
  849. xs=map[m].npc[i]->u.warp.xs;
  850. ys=map[m].npc[i]->u.warp.ys;
  851. break;
  852. case SCRIPT:
  853. if (!(flag&2))
  854. continue;
  855. xs=map[m].npc[i]->u.scr.xs;
  856. ys=map[m].npc[i]->u.scr.ys;
  857. break;
  858. default:
  859. continue;
  860. }
  861. if( x1 >= map[m].npc[i]->bl.x-xs && x0 <= map[m].npc[i]->bl.x+xs
  862. && y1 >= map[m].npc[i]->bl.y-ys && y0 <= map[m].npc[i]->bl.y+ys )
  863. break; // found a npc
  864. }
  865. if (i==map[m].npc_num)
  866. return 0;
  867. return (map[m].npc[i]->bl.id);
  868. }
  869. struct npc_data* npc_checknear(struct map_session_data* sd, struct block_list* bl)
  870. {
  871. struct npc_data *nd;
  872. nullpo_retr(NULL, sd);
  873. if(bl == NULL) return NULL;
  874. if(bl->type != BL_NPC) return NULL;
  875. nd = (TBL_NPC*)bl;
  876. if(sd->state.using_fake_npc && sd->npc_id == bl->id)
  877. return nd;
  878. if (nd->class_<0) //Class-less npc, enable click from anywhere.
  879. return nd;
  880. if (bl->m!=sd->bl.m ||
  881. bl->x<sd->bl.x-AREA_SIZE-1 || bl->x>sd->bl.x+AREA_SIZE+1 ||
  882. bl->y<sd->bl.y-AREA_SIZE-1 || bl->y>sd->bl.y+AREA_SIZE+1)
  883. return NULL;
  884. return nd;
  885. }
  886. /*==========================================
  887. * NPCのオープンチャット発言
  888. *------------------------------------------*/
  889. int npc_globalmessage(const char* name, const char* mes)
  890. {
  891. struct npc_data* nd = (struct npc_data *) strdb_get(npcname_db, name);
  892. char temp[100];
  893. if (!nd)
  894. return 0;
  895. snprintf(temp, sizeof(temp), "%s : %s", name, mes);
  896. clif_GlobalMessage(&nd->bl,temp);
  897. return 0;
  898. }
  899. /*==========================================
  900. * クリック時のNPC処理
  901. *------------------------------------------*/
  902. int npc_click(struct map_session_data* sd, struct npc_data* nd)
  903. {
  904. nullpo_retr(1, sd);
  905. if (sd->npc_id != 0) {
  906. ShowError("npc_click: npc_id != 0\n");
  907. return 1;
  908. }
  909. if(!nd) return 1;
  910. if ((nd = npc_checknear(sd,&nd->bl)) == NULL)
  911. return 1;
  912. //Hidden/Disabled npc.
  913. if (nd->class_ < 0 || nd->sc.option&(OPTION_INVISIBLE|OPTION_HIDE))
  914. return 1;
  915. switch(nd->subtype) {
  916. case SHOP:
  917. clif_npcbuysell(sd,nd->bl.id);
  918. break;
  919. case CASHSHOP:
  920. clif_cashshop_show(sd,nd);
  921. break;
  922. case SCRIPT:
  923. run_script(nd->u.scr.script,0,sd->bl.id,nd->bl.id);
  924. break;
  925. }
  926. return 0;
  927. }
  928. /*==========================================
  929. *
  930. *------------------------------------------*/
  931. int npc_scriptcont(struct map_session_data* sd, int id)
  932. {
  933. nullpo_retr(1, sd);
  934. if( id != sd->npc_id ){
  935. TBL_NPC* nd_sd=(TBL_NPC*)map_id2bl(sd->npc_id);
  936. TBL_NPC* nd=(TBL_NPC*)map_id2bl(id);
  937. ShowDebug("npc_scriptcont: %s (sd->npc_id=%d) is not %s (id=%d).\n",
  938. nd_sd?(char*)nd_sd->name:"'Unknown NPC'", (int)sd->npc_id,
  939. nd?(char*)nd->name:"'Unknown NPC'", (int)id);
  940. return 1;
  941. }
  942. if(id != fake_nd->bl.id) { // Not item script
  943. if ((npc_checknear(sd,map_id2bl(id))) == NULL){
  944. ShowWarning("npc_scriptcont: failed npc_checknear test.\n");
  945. return 1;
  946. }
  947. }
  948. run_script_main(sd->st);
  949. return 0;
  950. }
  951. /*==========================================
  952. *
  953. *------------------------------------------*/
  954. int npc_buysellsel(struct map_session_data* sd, int id, int type)
  955. {
  956. struct npc_data *nd;
  957. nullpo_retr(1, sd);
  958. if ((nd = npc_checknear(sd,map_id2bl(id))) == NULL)
  959. return 1;
  960. if (nd->subtype!=SHOP) {
  961. ShowError("no such shop npc : %d\n",id);
  962. if (sd->npc_id == id)
  963. sd->npc_id=0;
  964. return 1;
  965. }
  966. if (nd->sc.option&OPTION_INVISIBLE) // 無効化されている
  967. return 1;
  968. sd->npc_shopid=id;
  969. if (type==0) {
  970. clif_buylist(sd,nd);
  971. } else {
  972. clif_selllist(sd);
  973. }
  974. return 0;
  975. }
  976. //npc_buylist for script-controlled shops.
  977. static int npc_buylist_sub(struct map_session_data* sd, int n, unsigned short* item_list, struct npc_data* nd)
  978. {
  979. char npc_ev[NAME_LENGTH*2+3];
  980. int i;
  981. int key_nameid = 0;
  982. int key_amount = 0;
  983. // discard old contents
  984. script_cleararray_pc(sd, "@bought_nameid", (void*)0);
  985. script_cleararray_pc(sd, "@bought_quantity", (void*)0);
  986. // save list of bought items
  987. for( i = 0; i < n; i++ )
  988. {
  989. script_setarray_pc(sd, "@bought_nameid", i, (void*)item_list[i*2+1], &key_nameid);
  990. script_setarray_pc(sd, "@bought_quantity", i, (void*)item_list[i*2], &key_amount);
  991. }
  992. // invoke event
  993. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::OnBuyItem", nd->exname);
  994. npc_event(sd, npc_ev, 0);
  995. return 0;
  996. }
  997. /*==========================================
  998. * Cash Shop Buy
  999. *------------------------------------------*/
  1000. int npc_cashshop_buy(struct map_session_data *sd, int nameid, int amount, int points)
  1001. {
  1002. struct npc_data *nd = (struct npc_data *)map_id2bl(sd->npc_shopid);
  1003. struct item_data *item;
  1004. int i, price, w;
  1005. if( amount <= 0 )
  1006. return 5;
  1007. if( points < 0 )
  1008. return 6;
  1009. if( !nd || nd->subtype != CASHSHOP )
  1010. return 1;
  1011. if( sd->state.trading )
  1012. return 4;
  1013. if( (item = itemdb_search(nameid)) == NULL )
  1014. return 5; // Invalid Item
  1015. ARR_FIND(0, nd->u.shop.count, i, nd->u.shop.shop_item[i].nameid == nameid);
  1016. if( i == nd->u.shop.count )
  1017. return 5;
  1018. if( nd->u.shop.shop_item[i].value <= 0 )
  1019. return 5;
  1020. if(!itemdb_isstackable(nameid) && amount > 1)
  1021. {
  1022. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %d!\n",
  1023. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1024. amount = 1;
  1025. }
  1026. switch( pc_checkadditem(sd, nameid, amount) )
  1027. {
  1028. case ADDITEM_NEW:
  1029. if( pc_inventoryblank(sd) == 0 )
  1030. return 3;
  1031. break;
  1032. case ADDITEM_OVERAMOUNT:
  1033. return 3;
  1034. }
  1035. w = item->weight * amount;
  1036. if( w + sd->weight > sd->max_weight )
  1037. return 3;
  1038. if( (double)nd->u.shop.shop_item[i].value * amount > INT_MAX )
  1039. {
  1040. ShowWarning("npc_cashshop_buy: Item '%s' (%d) price overflow attempt!\n", item->name, nameid);
  1041. ShowDebug("(NPC:'%s' (%s,%d,%d), player:'%s' (%d/%d), value:%d, amount:%d)\n", 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);
  1042. return 5;
  1043. }
  1044. price = nd->u.shop.shop_item[i].value * amount;
  1045. if( points > price )
  1046. points = price;
  1047. if( (sd->kafraPoints < points) || (sd->cashPoints < price - points) )
  1048. return 6;
  1049. pc_paycash(sd, price, points);
  1050. if( !pet_create_egg(sd, nameid) )
  1051. {
  1052. struct item item_tmp;
  1053. memset(&item_tmp, 0, sizeof(struct item));
  1054. item_tmp.nameid = nameid;
  1055. item_tmp.identify = 1;
  1056. pc_additem(sd,&item_tmp, amount);
  1057. }
  1058. if(log_config.enable_logs&0x20)
  1059. log_pick_pc(sd, "S", nameid, amount, NULL);
  1060. return 0;
  1061. }
  1062. /// Player item purchase from npc shop.
  1063. ///
  1064. /// @param item_list 'n' pairs <amount,itemid>
  1065. /// @return result code for clif_parse_NpcBuyListSend
  1066. int npc_buylist(struct map_session_data* sd, int n, unsigned short* item_list)
  1067. {
  1068. struct npc_data* nd;
  1069. double z;
  1070. int i,j,w,skill,new_;
  1071. nullpo_retr(3, sd);
  1072. nullpo_retr(3, item_list);
  1073. nd = npc_checknear(sd,map_id2bl(sd->npc_shopid));
  1074. if( nd == NULL )
  1075. return 3;
  1076. if( nd->master_nd != NULL ) //Script-based shops.
  1077. return npc_buylist_sub(sd,n,item_list,nd->master_nd);
  1078. if( nd->subtype != SHOP )
  1079. return 3;
  1080. z = 0;
  1081. w = 0;
  1082. new_ = 0;
  1083. // process entries in buy list, one by one
  1084. for( i = 0; i < n; ++i )
  1085. {
  1086. int nameid, amount, value;
  1087. // find this entry in the shop's sell list
  1088. ARR_FIND( 0, nd->u.shop.count, j,
  1089. item_list[i*2+1] == nd->u.shop.shop_item[j].nameid || //Normal items
  1090. item_list[i*2+1] == itemdb_viewid(nd->u.shop.shop_item[j].nameid) //item_avail replacement
  1091. );
  1092. if( j == nd->u.shop.count )
  1093. return 3; // no such item in shop
  1094. amount = item_list[i*2+0];
  1095. nameid = item_list[i*2+1] = nd->u.shop.shop_item[j].nameid; //item_avail replacement
  1096. value = nd->u.shop.shop_item[j].value;
  1097. if( !itemdb_exists(nameid) )
  1098. return 3; // item no longer in itemdb
  1099. if( !itemdb_isstackable(nameid) && amount > 1 )
  1100. { //Exploit? You can't buy more than 1 of equipment types o.O
  1101. ShowWarning("Player %s (%d:%d) sent a hexed packet trying to buy %d of nonstackable item %d!\n",
  1102. sd->status.name, sd->status.account_id, sd->status.char_id, amount, nameid);
  1103. amount = item_list[i*2+0] = 1;
  1104. }
  1105. switch( pc_checkadditem(sd,nameid,amount) )
  1106. {
  1107. case ADDITEM_EXIST:
  1108. break;
  1109. case ADDITEM_NEW:
  1110. new_++;
  1111. break;
  1112. case ADDITEM_OVERAMOUNT:
  1113. return 2;
  1114. }
  1115. value = pc_modifybuyvalue(sd,value);
  1116. z += (double)value * amount;
  1117. w += itemdb_weight(nameid) * amount;
  1118. }
  1119. if( z > (double)sd->status.zeny )
  1120. return 1; // Not enough Zeny
  1121. if( w + sd->weight > sd->max_weight )
  1122. return 2; // Too heavy
  1123. if( pc_inventoryblank(sd) < new_ )
  1124. return 3; // Not enough space to store items
  1125. //Logs (S)hopping Zeny [Lupus]
  1126. if( log_config.zeny > 0 )
  1127. log_zeny(sd, "S", sd, -(int)z);
  1128. //Logs
  1129. pc_payzeny(sd,(int)z);
  1130. for( i = 0; i < n; ++i )
  1131. {
  1132. int nameid = item_list[i*2+1];
  1133. int amount = item_list[i*2+0];
  1134. struct item item_tmp;
  1135. memset(&item_tmp,0,sizeof(item_tmp));
  1136. item_tmp.nameid = nameid;
  1137. item_tmp.identify = 1;
  1138. pc_additem(sd,&item_tmp,amount);
  1139. //Logs items, Bought in NPC (S)hop [Lupus]
  1140. if( log_config.enable_logs&0x20 )
  1141. log_pick_pc(sd, "S", item_tmp.nameid, amount, NULL);
  1142. //Logs
  1143. }
  1144. // custom merchant shop exp bonus
  1145. if( battle_config.shop_exp > 0 && z > 0 && (skill = pc_checkskill(sd,MC_DISCOUNT)) > 0 )
  1146. {
  1147. if( sd->status.skill[MC_DISCOUNT].flag != 0 )
  1148. skill = sd->status.skill[MC_DISCOUNT].flag - 2;
  1149. if( skill > 0 )
  1150. {
  1151. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  1152. if( z < 1 )
  1153. z = 1;
  1154. pc_gainexp(sd,NULL,0,(int)z, false);
  1155. }
  1156. }
  1157. return 0;
  1158. }
  1159. /*==========================================
  1160. *
  1161. *------------------------------------------*/
  1162. int npc_selllist(struct map_session_data* sd, int n, unsigned short* item_list)
  1163. {
  1164. double z;
  1165. int i,skill;
  1166. int key_nameid = 0;
  1167. int key_amount = 0;
  1168. struct npc_data *nd;
  1169. nullpo_retr(1, sd);
  1170. nullpo_retr(1, item_list);
  1171. if ((nd = npc_checknear(sd,map_id2bl(sd->npc_shopid))) == NULL)
  1172. return 1;
  1173. nd = nd->master_nd; //For OnSell triggers.
  1174. if( nd )
  1175. {
  1176. // discard old contents
  1177. script_cleararray_pc(sd, "@sold_nameid", (void*)0);
  1178. script_cleararray_pc(sd, "@sold_quantity", (void*)0);
  1179. }
  1180. for(i=0,z=0;i<n;i++) {
  1181. int nameid, idx;
  1182. short qty;
  1183. idx = item_list[i*2]-2;
  1184. qty = (short)item_list[i*2+1];
  1185. if (idx <0 || idx >=MAX_INVENTORY || qty < 0)
  1186. break;
  1187. nameid=sd->status.inventory[idx].nameid;
  1188. if (nameid == 0 || !sd->inventory_data[idx] ||
  1189. sd->status.inventory[idx].amount < qty)
  1190. break;
  1191. z+=(double)qty*pc_modifysellvalue(sd,sd->inventory_data[idx]->value_sell);
  1192. if(sd->inventory_data[idx]->type == IT_PETEGG &&
  1193. sd->status.inventory[idx].card[0] == CARD0_PET)
  1194. {
  1195. if(search_petDB_index(sd->status.inventory[idx].nameid, PET_EGG) >= 0)
  1196. intif_delete_petdata(MakeDWord(sd->status.inventory[idx].card[1],sd->status.inventory[idx].card[2]));
  1197. }
  1198. if(log_config.enable_logs&0x20) //Logs items, Sold to NPC (S)hop [Lupus]
  1199. log_pick_pc(sd, "S", nameid, -qty, &sd->status.inventory[idx]);
  1200. if( nd )
  1201. {
  1202. script_setarray_pc(sd, "@sold_nameid", i, (void*)sd->status.inventory[idx].nameid, &key_nameid);
  1203. script_setarray_pc(sd, "@sold_quantity", i, (void*)qty, &key_amount);
  1204. }
  1205. pc_delitem(sd,idx,qty,0,6);
  1206. }
  1207. if (z > MAX_ZENY) z = MAX_ZENY;
  1208. if(log_config.zeny) //Logs (S)hopping Zeny [Lupus]
  1209. log_zeny(sd, "S", sd, (int)z);
  1210. pc_getzeny(sd,(int)z);
  1211. if (battle_config.shop_exp > 0 && z > 0 && (skill = pc_checkskill(sd,MC_OVERCHARGE)) > 0) {
  1212. if (sd->status.skill[MC_OVERCHARGE].flag != 0)
  1213. skill = sd->status.skill[MC_OVERCHARGE].flag - 2;
  1214. if (skill > 0) {
  1215. z = z * (double)skill * (double)battle_config.shop_exp/10000.;
  1216. if (z < 1)
  1217. z = 1;
  1218. pc_gainexp(sd,NULL,0,(int)z, false);
  1219. }
  1220. }
  1221. if(nd) {
  1222. char npc_ev[NAME_LENGTH*2+3];
  1223. snprintf(npc_ev, ARRAYLENGTH(npc_ev), "%s::OnSellItem", nd->exname);
  1224. npc_event(sd, npc_ev, 0);
  1225. }
  1226. if (i<n) {
  1227. //Error/Exploit... of some sort. If we return 1, the client will not mark
  1228. //any item as deleted even though a few were sold. In such a case, we
  1229. //have no recourse but to kick them out so their inventory will refresh
  1230. //correctly on relog. [Skotlex]
  1231. if (i) set_eof(sd->fd);
  1232. return 1;
  1233. }
  1234. return 0;
  1235. }
  1236. int npc_remove_map(struct npc_data* nd)
  1237. {
  1238. int m,i;
  1239. nullpo_retr(1, nd);
  1240. if(nd->bl.prev == NULL || nd->bl.m < 0)
  1241. return 1; //Not assigned to a map.
  1242. m = nd->bl.m;
  1243. clif_clearunit_area(&nd->bl,CLR_RESPAWN);
  1244. npc_unsetcells(nd);
  1245. map_delblock(&nd->bl);
  1246. //Remove npc from map[].npc list. [Skotlex]
  1247. ARR_FIND( 0, map[m].npc_num, i, map[m].npc[i] == nd );
  1248. if( i == map[m].npc_num ) return 2; //failed to find it?
  1249. map[m].npc_num--;
  1250. map[m].npc[i] = map[m].npc[map[m].npc_num];
  1251. map[m].npc[map[m].npc_num] = NULL;
  1252. return 0;
  1253. }
  1254. static int npc_unload_ev(DBKey key, void* data, va_list ap)
  1255. {
  1256. struct event_data* ev = (struct event_data *)data;
  1257. char* npcname = va_arg(ap, char *);
  1258. if(strcmp(ev->nd->exname,npcname)==0){
  1259. db_remove(ev_db, key);
  1260. return 1;
  1261. }
  1262. return 0;
  1263. }
  1264. static int npc_unload_dup_sub(struct npc_data* nd, va_list args)
  1265. {
  1266. int src_id;
  1267. src_id = va_arg(args, int);
  1268. if (nd->src_id == src_id)
  1269. npc_unload(nd);
  1270. return 0;
  1271. }
  1272. //Removes all npcs that are duplicates of the passed one. [Skotlex]
  1273. void npc_unload_duplicates(struct npc_data* nd)
  1274. {
  1275. map_foreachnpc(npc_unload_dup_sub,nd->bl.id);
  1276. }
  1277. int npc_unload(struct npc_data* nd)
  1278. {
  1279. nullpo_ret(nd);
  1280. npc_remove_map(nd);
  1281. map_deliddb(&nd->bl);
  1282. strdb_remove(npcname_db, nd->exname);
  1283. if (nd->chat_id) // remove npc chatroom object and kick users
  1284. chat_deletenpcchat(nd);
  1285. #ifdef PCRE_SUPPORT
  1286. npc_chat_finalize(nd); // deallocate npc PCRE data structures
  1287. #endif
  1288. if( (nd->subtype == SHOP || nd->subtype == CASHSHOP) && nd->src_id == 0) //src check for duplicate shops [Orcao]
  1289. aFree(nd->u.shop.shop_item);
  1290. else
  1291. if( nd->subtype == SCRIPT )
  1292. {
  1293. struct s_mapiterator* iter;
  1294. struct block_list* bl;
  1295. ev_db->foreach(ev_db,npc_unload_ev,nd->exname); //Clean up all events related
  1296. iter = mapit_geteachpc();
  1297. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) )
  1298. {
  1299. struct map_session_data *sd = map_id2sd(bl->id);
  1300. if( sd && sd->npc_timer_id != INVALID_TIMER )
  1301. {
  1302. const struct TimerData *td = get_timer(sd->npc_timer_id);
  1303. if( td && td->id != nd->bl.id )
  1304. continue;
  1305. if( td && td->data )
  1306. ers_free(timer_event_ers, (void*)td->data);
  1307. delete_timer(sd->npc_timer_id, npc_timerevent);
  1308. sd->npc_timer_id = INVALID_TIMER;
  1309. }
  1310. }
  1311. mapit_free(iter);
  1312. if (nd->u.scr.timerid != -1) {
  1313. const struct TimerData *td = NULL;
  1314. td = get_timer(nd->u.scr.timerid);
  1315. if (td && td->data)
  1316. ers_free(timer_event_ers, (void*)td->data);
  1317. delete_timer(nd->u.scr.timerid, npc_timerevent);
  1318. }
  1319. if (nd->u.scr.timer_event)
  1320. aFree(nd->u.scr.timer_event);
  1321. if (nd->src_id == 0) {
  1322. if(nd->u.scr.script) {
  1323. script_free_code(nd->u.scr.script);
  1324. nd->u.scr.script = NULL;
  1325. }
  1326. if (nd->u.scr.label_list) {
  1327. aFree(nd->u.scr.label_list);
  1328. nd->u.scr.label_list = NULL;
  1329. nd->u.scr.label_list_num = 0;
  1330. }
  1331. }
  1332. }
  1333. script_stop_sleeptimers(nd->bl.id);
  1334. aFree(nd);
  1335. return 0;
  1336. }
  1337. //
  1338. // NPC Source Files
  1339. //
  1340. /// Clears the npc source file list
  1341. static void npc_clearsrcfile(void)
  1342. {
  1343. struct npc_src_list* file = npc_src_files;
  1344. struct npc_src_list* file_tofree;
  1345. while( file != NULL )
  1346. {
  1347. file_tofree = file;
  1348. file = file->next;
  1349. aFree(file_tofree);
  1350. }
  1351. npc_src_files = NULL;
  1352. }
  1353. /// Adds a npc source file (or removes all)
  1354. void npc_addsrcfile(const char* name)
  1355. {
  1356. struct npc_src_list* file;
  1357. struct npc_src_list* file_prev = NULL;
  1358. if( strcmpi(name, "clear") == 0 )
  1359. {
  1360. npc_clearsrcfile();
  1361. return;
  1362. }
  1363. // prevent multiple insert of source files
  1364. file = npc_src_files;
  1365. while( file != NULL )
  1366. {
  1367. if( strcmp(name, file->name) == 0 )
  1368. return;// found the file, no need to insert it again
  1369. file_prev = file;
  1370. file = file->next;
  1371. }
  1372. file = (struct npc_src_list*)aMalloc(sizeof(struct npc_src_list) + strlen(name));
  1373. file->next = NULL;
  1374. strncpy(file->name, name, strlen(name) + 1);
  1375. if( file_prev == NULL )
  1376. npc_src_files = file;
  1377. else
  1378. file_prev->next = file;
  1379. }
  1380. /// Removes a npc source file (or all)
  1381. void npc_delsrcfile(const char* name)
  1382. {
  1383. struct npc_src_list* file = npc_src_files;
  1384. struct npc_src_list* file_prev = NULL;
  1385. if( strcmpi(name, "all") == 0 )
  1386. {
  1387. npc_clearsrcfile();
  1388. return;
  1389. }
  1390. while( file != NULL )
  1391. {
  1392. if( strcmp(file->name, name) == 0 )
  1393. {
  1394. if( npc_src_files == file )
  1395. npc_src_files = file->next;
  1396. else
  1397. file_prev->next = file->next;
  1398. aFree(file);
  1399. break;
  1400. }
  1401. file_prev = file;
  1402. file = file->next;
  1403. }
  1404. }
  1405. /// Parses and sets the name and exname of a npc.
  1406. /// Assumes that m, x and y are already set in nd.
  1407. static void npc_parsename(struct npc_data* nd, const char* name, const char* start, const char* buffer, const char* filepath)
  1408. {
  1409. const char* p;
  1410. struct npc_data* dnd;// duplicate npc
  1411. char newname[NAME_LENGTH];
  1412. // parse name
  1413. p = strstr(name,"::");
  1414. if( p )
  1415. {// <Display name>::<Unique name>
  1416. size_t len = p-name;
  1417. if( len > NAME_LENGTH )
  1418. {
  1419. 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);
  1420. safestrncpy(nd->name, name, sizeof(nd->name));
  1421. }
  1422. else
  1423. {
  1424. memcpy(nd->name, name, len);
  1425. memset(nd->name+len, 0, sizeof(nd->name)-len);
  1426. }
  1427. len = strlen(p+2);
  1428. if( len > NAME_LENGTH )
  1429. 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);
  1430. safestrncpy(nd->exname, p+2, sizeof(nd->exname));
  1431. }
  1432. else
  1433. {// <Display name>
  1434. size_t len = strlen(name);
  1435. if( len > NAME_LENGTH )
  1436. 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);
  1437. safestrncpy(nd->name, name, sizeof(nd->name));
  1438. safestrncpy(nd->exname, name, sizeof(nd->exname));
  1439. }
  1440. if( *nd->exname == '\0' || strstr(nd->exname,"::") != NULL )
  1441. {// invalid
  1442. snprintf(newname, ARRAYLENGTH(newname), "0_%d_%d_%d", nd->bl.m, nd->bl.x, nd->bl.y);
  1443. ShowWarning("npc_parsename: Invalid unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  1444. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  1445. }
  1446. if( (dnd=npc_name2id(nd->exname)) != NULL )
  1447. {// duplicate unique name, generate new one
  1448. char this_mapname[32];
  1449. char other_mapname[32];
  1450. int i = 0;
  1451. do
  1452. {
  1453. ++i;
  1454. snprintf(newname, ARRAYLENGTH(newname), "%d_%d_%d_%d", i, nd->bl.m, nd->bl.x, nd->bl.y);
  1455. }
  1456. while( npc_name2id(newname) != NULL );
  1457. strcpy(this_mapname, (nd->bl.m==-1?"(not on a map)":mapindex_id2name(map[nd->bl.m].index)));
  1458. strcpy(other_mapname, (dnd->bl.m==-1?"(not on a map)":mapindex_id2name(map[dnd->bl.m].index)));
  1459. ShowWarning("npc_parsename: Duplicate unique name in file '%s', line'%d'. Renaming '%s' to '%s'.\n", filepath, strline(buffer,start-buffer), nd->exname, newname);
  1460. 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);
  1461. ShowDebug("other npc:\n display name '%s'\n unique name '%s'\n map=%s, x=%d, y=%d\n", dnd->name, dnd->exname, other_mapname, dnd->bl.x, dnd->bl.y);
  1462. safestrncpy(nd->exname, newname, sizeof(nd->exname));
  1463. }
  1464. }
  1465. struct npc_data* npc_add_warp(short from_mapid, short from_x, short from_y, short xs, short ys, unsigned short to_mapindex, short to_x, short to_y)
  1466. {
  1467. int i;
  1468. struct npc_data *nd;
  1469. CREATE(nd, struct npc_data, 1);
  1470. nd->bl.id = npc_get_new_npc_id();
  1471. map_addnpc(from_mapid, nd);
  1472. nd->bl.prev = nd->bl.next = NULL;
  1473. nd->bl.m = from_mapid;
  1474. nd->bl.x = from_x;
  1475. nd->bl.y = from_y;
  1476. safestrncpy(nd->name, "", ARRAYLENGTH(nd->name));// empty display name
  1477. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp_%d_%d_%d", from_mapid, from_x, from_y);
  1478. for( i = 0; npc_name2id(nd->exname) != NULL; ++i )
  1479. snprintf(nd->exname, ARRAYLENGTH(nd->exname), "warp%d_%d_%d_%d", i, from_mapid, from_x, from_y);
  1480. if( battle_config.warp_point_debug )
  1481. nd->class_ = WARP_DEBUG_CLASS;
  1482. else
  1483. nd->class_ = WARP_CLASS;
  1484. nd->speed = 200;
  1485. nd->u.warp.mapindex = to_mapindex;
  1486. nd->u.warp.x = to_x;
  1487. nd->u.warp.y = to_y;
  1488. nd->u.warp.xs = xs;
  1489. nd->u.warp.ys = xs;
  1490. nd->bl.type = BL_NPC;
  1491. nd->subtype = WARP;
  1492. npc_setcells(nd);
  1493. map_addblock(&nd->bl);
  1494. status_set_viewdata(&nd->bl, nd->class_);
  1495. status_change_init(&nd->bl);
  1496. unit_dataset(&nd->bl);
  1497. clif_spawn(&nd->bl);
  1498. strdb_put(npcname_db, nd->exname, nd);
  1499. return nd;
  1500. }
  1501. /// Parses a warp npc.
  1502. static const char* npc_parse_warp(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  1503. {
  1504. int x, y, xs, ys, to_x, to_y, m;
  1505. unsigned short i;
  1506. char mapname[32], to_mapname[32];
  1507. struct npc_data *nd;
  1508. // w1=<from map name>,<fromX>,<fromY>,<facing>
  1509. // w4=<spanx>,<spany>,<to map name>,<toX>,<toY>
  1510. if( sscanf(w1, "%31[^,],%d,%d", mapname, &x, &y) != 3
  1511. || sscanf(w4, "%d,%d,%31[^,],%d,%d", &xs, &ys, to_mapname, &to_x, &to_y) != 5 )
  1512. {
  1513. 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);
  1514. return strchr(start,'\n');// skip and continue
  1515. }
  1516. m = map_mapname2mapid(mapname);
  1517. i = mapindex_name2id(to_mapname);
  1518. if( i == 0 )
  1519. {
  1520. 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);
  1521. return strchr(start,'\n');// skip and continue
  1522. }
  1523. CREATE(nd, struct npc_data, 1);
  1524. nd->bl.id = npc_get_new_npc_id();
  1525. map_addnpc(m, nd);
  1526. nd->bl.prev = nd->bl.next = NULL;
  1527. nd->bl.m = m;
  1528. nd->bl.x = x;
  1529. nd->bl.y = y;
  1530. npc_parsename(nd, w3, start, buffer, filepath);
  1531. if (!battle_config.warp_point_debug)
  1532. nd->class_ = WARP_CLASS;
  1533. else
  1534. nd->class_ = WARP_DEBUG_CLASS;
  1535. nd->speed = 200;
  1536. nd->u.warp.mapindex = i;
  1537. nd->u.warp.x = to_x;
  1538. nd->u.warp.y = to_y;
  1539. nd->u.warp.xs = xs;
  1540. nd->u.warp.ys = ys;
  1541. npc_warp++;
  1542. nd->bl.type = BL_NPC;
  1543. nd->subtype = WARP;
  1544. npc_setcells(nd);
  1545. map_addblock(&nd->bl);
  1546. status_set_viewdata(&nd->bl, nd->class_);
  1547. status_change_init(&nd->bl);
  1548. unit_dataset(&nd->bl);
  1549. clif_spawn(&nd->bl);
  1550. strdb_put(npcname_db, nd->exname, nd);
  1551. return strchr(start,'\n');// continue
  1552. }
  1553. /// Parses a shop/cashshop npc.
  1554. static const char* npc_parse_shop(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  1555. {
  1556. //TODO: could be rewritten to NOT need this temp array [ultramage]
  1557. #define MAX_SHOPITEM 100
  1558. struct npc_item_list items[MAX_SHOPITEM];
  1559. char *p;
  1560. int x, y, dir, m, i;
  1561. struct npc_data *nd;
  1562. enum npc_subtype type;
  1563. if( strcmp(w1,"-") == 0 )
  1564. {// 'floating' shop?
  1565. x = y = dir = 0;
  1566. m = -1;
  1567. }
  1568. else
  1569. {// w1=<map name>,<x>,<y>,<facing>
  1570. char mapname[32];
  1571. if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4
  1572. || strchr(w4, ',') == NULL )
  1573. {
  1574. 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);
  1575. return strchr(start,'\n');// skip and continue
  1576. }
  1577. m = map_mapname2mapid(mapname);
  1578. }
  1579. if( !strcasecmp(w2,"cashshop") )
  1580. type = CASHSHOP;
  1581. else
  1582. type = SHOP;
  1583. p = strchr(w4,',');
  1584. for( i = 0; i < ARRAYLENGTH(items) && p; ++i )
  1585. {
  1586. int nameid, value;
  1587. struct item_data* id;
  1588. if( sscanf(p, ",%d:%d", &nameid, &value) != 2 )
  1589. {
  1590. 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);
  1591. break;
  1592. }
  1593. if( (id = itemdb_exists(nameid)) == NULL )
  1594. {
  1595. ShowWarning("npc_parse_shop: Invalid sell item in file '%s', line '%d' (id '%d').\n", filepath, strline(buffer,start-buffer), nameid);
  1596. p = strchr(p+1,',');
  1597. continue;
  1598. }
  1599. if( value < 0 )
  1600. {
  1601. if( type == SHOP ) value = id->value_buy;
  1602. else value = 0; // Cashshop doesn't have a "buy price" in the item_db
  1603. }
  1604. if( type == SHOP && value*0.75 < id->value_sell*1.24 )
  1605. {// Exploit possible: you can buy and sell back with profit
  1606. ShowWarning("npc_parse_shop: Item %s [%d] discounted buying price (%d->%d) is less than overcharged selling price (%d->%d) at file '%s', line '%d'.\n",
  1607. id->name, nameid, value, (int)(value*0.75), id->value_sell, (int)(id->value_sell*1.24), filepath, strline(buffer,start-buffer));
  1608. }
  1609. //for logs filters, atcommands and iteminfo script command
  1610. if( id->maxchance <= 0 )
  1611. id->maxchance = 10000; //10000 (100% drop chance)would show that the item's sold in NPC Shop
  1612. items[i].nameid = nameid;
  1613. items[i].value = value;
  1614. p = strchr(p+1,',');
  1615. }
  1616. if( i == 0 )
  1617. {
  1618. ShowWarning("npc_parse_shop: Ignoring empty shop in file '%s', line '%d'.\n", filepath, strline(buffer,start-buffer));
  1619. return strchr(start,'\n');// continue
  1620. }
  1621. CREATE(nd, struct npc_data, 1);
  1622. CREATE(nd->u.shop.shop_item, struct npc_item_list, i);
  1623. memcpy(nd->u.shop.shop_item, items, sizeof(struct npc_item_list)*i);
  1624. nd->u.shop.count = i;
  1625. nd->bl.prev = nd->bl.next = NULL;
  1626. nd->bl.m = m;
  1627. nd->bl.x = x;
  1628. nd->bl.y = y;
  1629. nd->bl.id = npc_get_new_npc_id();
  1630. npc_parsename(nd, w3, start, buffer, filepath);
  1631. nd->class_ = m==-1?-1:atoi(w4);
  1632. nd->speed = 200;
  1633. ++npc_shop;
  1634. nd->bl.type = BL_NPC;
  1635. nd->subtype = type;
  1636. if( m >= 0 )
  1637. {// normal shop npc
  1638. map_addnpc(m,nd);
  1639. map_addblock(&nd->bl);
  1640. status_set_viewdata(&nd->bl, nd->class_);
  1641. status_change_init(&nd->bl);
  1642. unit_dataset(&nd->bl);
  1643. nd->ud.dir = dir;
  1644. clif_spawn(&nd->bl);
  1645. } else
  1646. {// 'floating' shop?
  1647. map_addiddb(&nd->bl);
  1648. }
  1649. strdb_put(npcname_db, nd->exname, nd);
  1650. return strchr(start,'\n');// continue
  1651. }
  1652. /*==========================================
  1653. * NPCのラベルデータコンバート
  1654. *------------------------------------------*/
  1655. int npc_convertlabel_db(DBKey key, void* data, va_list ap)
  1656. {
  1657. const char* lname = (const char*)key.str;
  1658. int lpos = (int)data;
  1659. struct npc_label_list** label_list;
  1660. int* label_list_num;
  1661. const char* filepath;
  1662. struct npc_label_list* label;
  1663. const char *p;
  1664. int len;
  1665. nullpo_ret(label_list = va_arg(ap,struct npc_label_list**));
  1666. nullpo_ret(label_list_num = va_arg(ap,int*));
  1667. nullpo_ret(filepath = va_arg(ap,const char*));
  1668. // In case of labels not terminated with ':', for user defined function support
  1669. p = lname;
  1670. while( ISALNUM(*p) || *p == '_' )
  1671. ++p;
  1672. len = p-lname;
  1673. // here we check if the label fit into the buffer
  1674. if( len > 23 )
  1675. {
  1676. ShowError("npc_parse_script: label name longer than 23 chars! '%s'\n (%s)", lname, filepath);
  1677. return 0;
  1678. }
  1679. if( *label_list == NULL )
  1680. {
  1681. *label_list = (struct npc_label_list *) aCallocA (1, sizeof(struct npc_label_list));
  1682. *label_list_num = 0;
  1683. } else
  1684. *label_list = (struct npc_label_list *) aRealloc (*label_list, sizeof(struct npc_label_list)*(*label_list_num+1));
  1685. label = *label_list+*label_list_num;
  1686. safestrncpy(label->name, lname, sizeof(label->name));
  1687. label->pos = lpos;
  1688. ++(*label_list_num);
  1689. return 0;
  1690. }
  1691. // Skip the contents of a script.
  1692. static const char* npc_skip_script(const char* start, const char* buffer, const char* filepath)
  1693. {
  1694. const char* p;
  1695. int curly_count;
  1696. if( start == NULL )
  1697. return NULL;// nothing to skip
  1698. // initial bracket (assumes the previous part is ok)
  1699. p = strchr(start,'{');
  1700. if( p == NULL )
  1701. {
  1702. ShowError("npc_skip_script: Missing left curly in file '%s', line'%d'.", filepath, strline(buffer,start-buffer));
  1703. return NULL;// can't continue
  1704. }
  1705. // skip everything
  1706. for( curly_count = 1; curly_count > 0 ; )
  1707. {
  1708. p = skip_space(p+1) ;
  1709. if( *p == '}' )
  1710. {// right curly
  1711. --curly_count;
  1712. }
  1713. else if( *p == '{' )
  1714. {// left curly
  1715. ++curly_count;
  1716. }
  1717. else if( *p == '"' )
  1718. {// string
  1719. for( ++p; *p != '"' ; ++p )
  1720. {
  1721. if( *p == '\\' && (unsigned char)p[-1] <= 0x7e )
  1722. ++p;// escape sequence (not part of a multibyte character)
  1723. else if( *p == '\0' )
  1724. {
  1725. script_error(buffer, filepath, 0, "Unexpected end of string.", p);
  1726. return NULL;// can't continue
  1727. }
  1728. else if( *p == '\n' )
  1729. {
  1730. script_error(buffer, filepath, 0, "Unexpected newline at string.", p);
  1731. return NULL;// can't continue
  1732. }
  1733. }
  1734. }
  1735. else if( *p == '\0' )
  1736. {// end of buffer
  1737. ShowError("Missing %d right curlys at file '%s', line '%d'.\n", curly_count, filepath, strline(buffer,p-buffer));
  1738. return NULL;// can't continue
  1739. }
  1740. }
  1741. return p+1;// return after the last '}'
  1742. }
  1743. /// Parses a npc script.
  1744. ///
  1745. /// -%TAB%script%TAB%<NPC Name>%TAB%-1,{<code>}
  1746. /// <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,{<code>}
  1747. /// <map name>,<x>,<y>,<facing>%TAB%script%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>,{<code>}
  1748. static const char* npc_parse_script(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  1749. {
  1750. int x, y, dir = 0, m, xs = 0, ys = 0, class_ = 0; // [Valaris] thanks to fov
  1751. char mapname[32];
  1752. struct script_code *script;
  1753. int i;
  1754. const char* end;
  1755. const char* script_start;
  1756. struct npc_label_list* label_list;
  1757. int label_list_num;
  1758. struct npc_data* nd;
  1759. if( strcmp(w1, "-") == 0 )
  1760. {// floating npc
  1761. x = 0;
  1762. y = 0;
  1763. m = -1;
  1764. }
  1765. else
  1766. {// npc in a map
  1767. if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4 )
  1768. {
  1769. 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);
  1770. return NULL;// unknown format, don't continue
  1771. }
  1772. m = map_mapname2mapid(mapname);
  1773. }
  1774. script_start = strstr(start,",{");
  1775. end = strchr(start,'\n');
  1776. if( strstr(w4,",{") == NULL || script_start == NULL || (end != NULL && script_start > end) )
  1777. {
  1778. 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);
  1779. return NULL;// can't continue
  1780. }
  1781. ++script_start;
  1782. end = npc_skip_script(script_start, buffer, filepath);
  1783. if( end == NULL )
  1784. return NULL;// (simple) parse error, don't continue
  1785. script = parse_script(script_start, filepath, strline(buffer,script_start-buffer), SCRIPT_USE_LABEL_DB);
  1786. label_list = NULL;
  1787. label_list_num = 0;
  1788. if( script )
  1789. {
  1790. DBMap* label_db = script_get_label_db();
  1791. label_db->foreach(label_db, npc_convertlabel_db, &label_list, &label_list_num, filepath);
  1792. label_db->clear(label_db, NULL); // not needed anymore, so clear the db
  1793. }
  1794. CREATE(nd, struct npc_data, 1);
  1795. if( sscanf(w4, "%d,%d,%d", &class_, &xs, &ys) == 3 )
  1796. {// OnTouch area defined
  1797. nd->u.scr.xs = xs;
  1798. nd->u.scr.ys = ys;
  1799. }
  1800. else
  1801. {// no OnTouch area
  1802. class_ = atoi(w4);
  1803. nd->u.scr.xs = -1;
  1804. nd->u.scr.ys = -1;
  1805. }
  1806. nd->bl.prev = nd->bl.next = NULL;
  1807. nd->bl.m = m;
  1808. nd->bl.x = x;
  1809. nd->bl.y = y;
  1810. npc_parsename(nd, w3, start, buffer, filepath);
  1811. nd->bl.id = npc_get_new_npc_id();
  1812. nd->class_ = class_;
  1813. nd->speed = 200;
  1814. nd->u.scr.script = script;
  1815. nd->u.scr.label_list = label_list;
  1816. nd->u.scr.label_list_num = label_list_num;
  1817. ++npc_script;
  1818. nd->bl.type = BL_NPC;
  1819. nd->subtype = SCRIPT;
  1820. if( m >= 0 )
  1821. {
  1822. map_addnpc(m, nd);
  1823. status_change_init(&nd->bl);
  1824. unit_dataset(&nd->bl);
  1825. nd->ud.dir = dir;
  1826. npc_setcells(nd);
  1827. map_addblock(&nd->bl);
  1828. if( class_ >= 0 )
  1829. {
  1830. status_set_viewdata(&nd->bl, nd->class_);
  1831. clif_spawn(&nd->bl);
  1832. }
  1833. }
  1834. else
  1835. {
  1836. // we skip map_addnpc, but still add it to the list of ID's
  1837. map_addiddb(&nd->bl);
  1838. }
  1839. strdb_put(npcname_db, nd->exname, nd);
  1840. //-----------------------------------------
  1841. // イベント用ラベルデータのエクスポート
  1842. for (i = 0; i < nd->u.scr.label_list_num; i++)
  1843. {
  1844. char* lname = nd->u.scr.label_list[i].name;
  1845. int pos = nd->u.scr.label_list[i].pos;
  1846. if ((lname[0] == 'O' || lname[0] == 'o') && (lname[1] == 'N' || lname[1] == 'n'))
  1847. {
  1848. struct event_data* ev;
  1849. char buf[NAME_LENGTH*2+3]; // 24 for npc name + 24 for label + 2 for a "::" and 1 for EOS
  1850. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, lname);
  1851. // generate the data and insert it
  1852. CREATE(ev, struct event_data, 1);
  1853. ev->nd = nd;
  1854. ev->pos = pos;
  1855. if( strdb_put(ev_db, buf, ev) != NULL )// There was already another event of the same name?
  1856. ShowWarning("npc_parse_script : duplicate event %s (%s)\n", buf, filepath);
  1857. }
  1858. }
  1859. //-----------------------------------------
  1860. // ラベルデータからタイマーイベント取り込み
  1861. for (i = 0; i < nd->u.scr.label_list_num; i++){
  1862. int t = 0, k = 0;
  1863. char *lname = nd->u.scr.label_list[i].name;
  1864. int pos = nd->u.scr.label_list[i].pos;
  1865. if (sscanf(lname, "OnTimer%d%n", &t, &k) == 1 && lname[k] == '\0') {
  1866. // タイマーイベント
  1867. struct npc_timerevent_list *te = nd->u.scr.timer_event;
  1868. int j, k = nd->u.scr.timeramount;
  1869. if (te == NULL)
  1870. te = (struct npc_timerevent_list *)aMallocA(sizeof(struct npc_timerevent_list));
  1871. else
  1872. te = (struct npc_timerevent_list *)aRealloc( te, sizeof(struct npc_timerevent_list) * (k+1) );
  1873. for (j = 0; j < k; j++){
  1874. if (te[j].timer > t){
  1875. memmove(te+j+1, te+j, sizeof(struct npc_timerevent_list)*(k-j));
  1876. break;
  1877. }
  1878. }
  1879. te[j].timer = t;
  1880. te[j].pos = pos;
  1881. nd->u.scr.timer_event = te;
  1882. nd->u.scr.timeramount++;
  1883. }
  1884. }
  1885. nd->u.scr.timerid = -1;
  1886. return end;
  1887. }
  1888. /// Duplicate a warp, shop, cashshop or script. [Orcao]
  1889. /// warp: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<spanx>,<spany>
  1890. /// shop/cashshop/npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  1891. /// shop/cashshop/npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>
  1892. /// npc: -%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  1893. /// npc: <map name>,<x>,<y>,<facing>%TAB%duplicate(<name of target>)%TAB%<NPC Name>%TAB%<sprite id>,<triggerX>,<triggerY>
  1894. const char* npc_parse_duplicate(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  1895. {
  1896. int x, y, dir, m, xs = -1, ys = -1, class_ = 0;
  1897. char mapname[32];
  1898. char srcname[128];
  1899. int i;
  1900. const char* end;
  1901. int src_id;
  1902. int type;
  1903. struct npc_data* nd;
  1904. struct npc_data* dnd;
  1905. end = strchr(start,'\n');
  1906. // get the npc being duplicated
  1907. if( sscanf(w2,"duplicate(%127[^)])",srcname) != 1 )
  1908. {
  1909. ShowError("npc_parse_script: bad duplicate name in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), w2);
  1910. return end;// next line, try to continue
  1911. }
  1912. dnd = npc_name2id(srcname);
  1913. if( dnd == NULL) {
  1914. ShowError("npc_parse_script: original npc not found for duplicate in file '%s', line '%d' : %s\n", filepath, strline(buffer,start-buffer), srcname);
  1915. return end;// next line, try to continue
  1916. }
  1917. src_id = dnd->bl.id;
  1918. type = dnd->subtype;
  1919. // get placement
  1920. if( (type==SHOP || type==CASHSHOP || type==SCRIPT) && strcmp(w1, "-") == 0 )
  1921. {// floating shop/chashshop/script
  1922. x = y = dir = 0;
  1923. m = -1;
  1924. }
  1925. else
  1926. {
  1927. if( sscanf(w1, "%31[^,],%d,%d,%d", mapname, &x, &y, &dir) != 4 )// <map name>,<x>,<y>,<facing>
  1928. {
  1929. 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);
  1930. return end;// next line, try to continue
  1931. }
  1932. m = map_mapname2mapid(mapname);
  1933. }
  1934. if( type == WARP && sscanf(w4, "%d,%d", &xs, &ys) == 2 );// <spanx>,<spany>
  1935. else if( type == SCRIPT && sscanf(w4, "%d,%d,%d", &class_, &xs, &ys) == 3);// <sprite id>,<triggerX>,<triggerY>
  1936. else if( type != WARP ) class_ = atoi(w4);// <sprite id>
  1937. else
  1938. {
  1939. 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);
  1940. return end;// next line, try to continue
  1941. }
  1942. CREATE(nd, struct npc_data, 1);
  1943. nd->bl.prev = nd->bl.next = NULL;
  1944. nd->bl.m = m;
  1945. nd->bl.x = x;
  1946. nd->bl.y = y;
  1947. npc_parsename(nd, w3, start, buffer, filepath);
  1948. nd->bl.id = npc_get_new_npc_id();
  1949. nd->class_ = class_;
  1950. nd->speed = 200;
  1951. nd->src_id = src_id;
  1952. nd->bl.type = BL_NPC;
  1953. nd->subtype = type;
  1954. switch( type )
  1955. {
  1956. case SCRIPT:
  1957. ++npc_script;
  1958. nd->u.scr.xs = xs;
  1959. nd->u.scr.ys = ys;
  1960. nd->u.scr.script = dnd->u.scr.script;
  1961. nd->u.scr.label_list = dnd->u.scr.label_list;
  1962. nd->u.scr.label_list_num = dnd->u.scr.label_list_num;
  1963. break;
  1964. case SHOP:
  1965. case CASHSHOP:
  1966. ++npc_shop;
  1967. nd->u.shop.shop_item = dnd->u.shop.shop_item;
  1968. nd->u.shop.count = dnd->u.shop.count;
  1969. break;
  1970. case WARP:
  1971. ++npc_warp;
  1972. if( !battle_config.warp_point_debug )
  1973. nd->class_ = WARP_CLASS;
  1974. else
  1975. nd->class_ = WARP_DEBUG_CLASS;
  1976. nd->u.warp.xs = xs;
  1977. nd->u.warp.ys = ys;
  1978. nd->u.warp.mapindex = dnd->u.warp.mapindex;
  1979. nd->u.warp.x = dnd->u.warp.x;
  1980. nd->u.warp.y = dnd->u.warp.y;
  1981. break;
  1982. }
  1983. //Add the npc to its location
  1984. if( m >= 0 )
  1985. {
  1986. map_addnpc(m, nd);
  1987. status_change_init(&nd->bl);
  1988. unit_dataset(&nd->bl);
  1989. nd->ud.dir = dir;
  1990. npc_setcells(nd);
  1991. map_addblock(&nd->bl);
  1992. if( class_ >= 0 )
  1993. {
  1994. status_set_viewdata(&nd->bl, nd->class_);
  1995. clif_spawn(&nd->bl);
  1996. }
  1997. }
  1998. else
  1999. {
  2000. // we skip map_addnpc, but still add it to the list of ID's
  2001. map_addiddb(&nd->bl);
  2002. }
  2003. strdb_put(npcname_db, nd->exname, nd);
  2004. if( type != SCRIPT )
  2005. return end;
  2006. //Handle labels
  2007. //-----------------------------------------
  2008. // イベント用ラベルデータのエクスポート
  2009. for (i = 0; i < nd->u.scr.label_list_num; i++)
  2010. {
  2011. char* lname = nd->u.scr.label_list[i].name;
  2012. int pos = nd->u.scr.label_list[i].pos;
  2013. if ((lname[0] == 'O' || lname[0] == 'o') && (lname[1] == 'N' || lname[1] == 'n'))
  2014. {
  2015. struct event_data* ev;
  2016. char buf[NAME_LENGTH*2+3]; // 24 for npc name + 24 for label + 2 for a "::" and 1 for EOS
  2017. snprintf(buf, ARRAYLENGTH(buf), "%s::%s", nd->exname, lname);
  2018. // generate the data and insert it
  2019. CREATE(ev, struct event_data, 1);
  2020. ev->nd = nd;
  2021. ev->pos = pos;
  2022. if( strdb_put(ev_db, buf, ev) != NULL )// There was already another event of the same name?
  2023. ShowWarning("npc_parse_duplicate : duplicate event %s (%s)\n", buf, filepath);
  2024. }
  2025. }
  2026. //-----------------------------------------
  2027. // ラベルデータからタイマーイベント取り込み
  2028. for (i = 0; i < nd->u.scr.label_list_num; i++){
  2029. int t = 0, k = 0;
  2030. char *lname = nd->u.scr.label_list[i].name;
  2031. int pos = nd->u.scr.label_list[i].pos;
  2032. if (sscanf(lname, "OnTimer%d%n", &t, &k) == 1 && lname[k] == '\0') {
  2033. // タイマーイベント
  2034. struct npc_timerevent_list *te = nd->u.scr.timer_event;
  2035. int j, k = nd->u.scr.timeramount;
  2036. if (te == NULL)
  2037. te = (struct npc_timerevent_list *)aMallocA(sizeof(struct npc_timerevent_list));
  2038. else
  2039. te = (struct npc_timerevent_list *)aRealloc( te, sizeof(struct npc_timerevent_list) * (k+1) );
  2040. for (j = 0; j < k; j++){
  2041. if (te[j].timer > t){
  2042. memmove(te+j+1, te+j, sizeof(struct npc_timerevent_list)*(k-j));
  2043. break;
  2044. }
  2045. }
  2046. te[j].timer = t;
  2047. te[j].pos = pos;
  2048. nd->u.scr.timer_event = te;
  2049. nd->u.scr.timeramount++;
  2050. }
  2051. }
  2052. nd->u.scr.timerid = -1;
  2053. return end;
  2054. }
  2055. int npc_duplicate4instance(struct npc_data *snd, int m)
  2056. {
  2057. char newname[NAME_LENGTH];
  2058. if( map[m].instance_id == 0 )
  2059. return 1;
  2060. snprintf(newname, ARRAYLENGTH(newname), "dup_%d_%d", map[m].instance_id, snd->bl.id);
  2061. if( npc_name2id(newname) != NULL )
  2062. { // Name already in use
  2063. 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);
  2064. return 1;
  2065. }
  2066. if( snd->subtype == WARP )
  2067. { // Adjust destination, if instanced
  2068. struct npc_data *wnd = NULL; // New NPC
  2069. int dm = map_mapindex2mapid(snd->u.warp.mapindex), im;
  2070. if( dm < 0 ) return 1;
  2071. im = instance_mapid2imapid(dm, map[m].instance_id);
  2072. if( im == -1 )
  2073. {
  2074. 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);
  2075. return 1;
  2076. }
  2077. CREATE(wnd, struct npc_data, 1);
  2078. wnd->bl.id = npc_get_new_npc_id();
  2079. map_addnpc(m, wnd);
  2080. wnd->bl.prev = wnd->bl.next = NULL;
  2081. wnd->bl.m = m;
  2082. wnd->bl.x = snd->bl.x;
  2083. wnd->bl.y = snd->bl.y;
  2084. safestrncpy(wnd->name, "", ARRAYLENGTH(wnd->name));
  2085. safestrncpy(wnd->exname, newname, ARRAYLENGTH(wnd->exname));
  2086. wnd->class_ = WARP_CLASS;
  2087. wnd->speed = 200;
  2088. wnd->u.warp.mapindex = map_id2index(im);
  2089. wnd->u.warp.x = snd->u.warp.x;
  2090. wnd->u.warp.y = snd->u.warp.y;
  2091. wnd->u.warp.xs = snd->u.warp.xs;
  2092. wnd->u.warp.ys = snd->u.warp.ys;
  2093. wnd->bl.type = BL_NPC;
  2094. wnd->subtype = WARP;
  2095. npc_setcells(wnd);
  2096. map_addblock(&wnd->bl);
  2097. status_set_viewdata(&wnd->bl, wnd->class_);
  2098. status_change_init(&wnd->bl);
  2099. unit_dataset(&wnd->bl);
  2100. clif_spawn(&wnd->bl);
  2101. strdb_put(npcname_db, wnd->exname, wnd);
  2102. }
  2103. else
  2104. {
  2105. static char w1[50], w2[50], w3[50], w4[50];
  2106. const char* stat_buf = "- call from instancing subsystem -\n";
  2107. snprintf(w1, sizeof(w1), "%s,%d,%d,%d", map[m].name, snd->bl.x, snd->bl.y, snd->ud.dir);
  2108. snprintf(w2, sizeof(w2), "duplicate(%s)", snd->exname);
  2109. snprintf(w3, sizeof(w3), "%s::%s", snd->name, newname);
  2110. if( snd->u.scr.xs >= 0 && snd->u.scr.ys >= 0 )
  2111. snprintf(w4, sizeof(w4), "%d,%d,%d", snd->class_, snd->u.scr.xs, snd->u.scr.ys); // Touch Area
  2112. else
  2113. snprintf(w4, sizeof(w4), "%d", snd->class_);
  2114. npc_parse_duplicate(w1, w2, w3, w4, stat_buf, stat_buf, "INSTANCING");
  2115. }
  2116. return 0;
  2117. }
  2118. void npc_setcells(struct npc_data* nd)
  2119. {
  2120. int m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  2121. int i,j;
  2122. switch(nd->subtype)
  2123. {
  2124. case WARP:
  2125. xs = nd->u.warp.xs;
  2126. ys = nd->u.warp.ys;
  2127. break;
  2128. case SCRIPT:
  2129. xs = nd->u.scr.xs;
  2130. ys = nd->u.scr.ys;
  2131. break;
  2132. default:
  2133. return; // Other types doesn't have touch area
  2134. }
  2135. if (m < 0 || xs < 0 || ys < 0)
  2136. return;
  2137. for (i = y-ys; i <= y+ys; i++) {
  2138. for (j = x-xs; j <= x+xs; j++) {
  2139. if (map_getcell(m, j, i, CELL_CHKNOPASS))
  2140. continue;
  2141. map_setcell(m, j, i, CELL_NPC, true);
  2142. }
  2143. }
  2144. }
  2145. int npc_unsetcells_sub(struct block_list* bl, va_list ap)
  2146. {
  2147. struct npc_data *nd = (struct npc_data*)bl;
  2148. int id = va_arg(ap,int);
  2149. if (nd->bl.id == id) return 0;
  2150. npc_setcells(nd);
  2151. return 1;
  2152. }
  2153. void npc_unsetcells(struct npc_data* nd)
  2154. {
  2155. int m = nd->bl.m, x = nd->bl.x, y = nd->bl.y, xs, ys;
  2156. int i,j, x0, x1, y0, y1;
  2157. if (nd->subtype == WARP) {
  2158. xs = nd->u.warp.xs;
  2159. ys = nd->u.warp.ys;
  2160. } else {
  2161. xs = nd->u.scr.xs;
  2162. ys = nd->u.scr.ys;
  2163. }
  2164. if (m < 0 || xs < 0 || ys < 0)
  2165. return;
  2166. //Locate max range on which we can locate npc cells
  2167. //FIXME: does this really do what it's supposed to do? [ultramage]
  2168. for(x0 = x-xs; x0 > 0 && map_getcell(m, x0, y, CELL_CHKNPC); x0--);
  2169. for(x1 = x+xs; x1 < map[m].xs-1 && map_getcell(m, x1, y, CELL_CHKNPC); x1++);
  2170. for(y0 = y-ys; y0 > 0 && map_getcell(m, x, y0, CELL_CHKNPC); y0--);
  2171. for(y1 = y+ys; y1 < map[m].ys-1 && map_getcell(m, x, y1, CELL_CHKNPC); y1++);
  2172. //Erase this npc's cells
  2173. for (i = y-ys; i <= y+ys; i++)
  2174. for (j = x-xs; j <= x+xs; j++)
  2175. map_setcell(m, j, i, CELL_NPC, false);
  2176. //Re-deploy NPC cells for other nearby npcs.
  2177. map_foreachinarea( npc_unsetcells_sub, m, x0, y0, x1, y1, BL_NPC, nd->bl.id );
  2178. }
  2179. void npc_movenpc(struct npc_data* nd, int x, int y)
  2180. {
  2181. const int m = nd->bl.m;
  2182. if (m < 0 || nd->bl.prev == NULL) return; //Not on a map.
  2183. x = cap_value(x, 0, map[m].xs-1);
  2184. y = cap_value(y, 0, map[m].ys-1);
  2185. map_foreachinrange(clif_outsight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  2186. map_moveblock(&nd->bl, x, y, gettick());
  2187. map_foreachinrange(clif_insight, &nd->bl, AREA_SIZE, BL_PC, &nd->bl);
  2188. }
  2189. /// Changes the display name of the npc.
  2190. ///
  2191. /// @param nd Target npc
  2192. /// @param newname New display name
  2193. void npc_setdisplayname(struct npc_data* nd, const char* newname)
  2194. {
  2195. nullpo_retv(nd);
  2196. safestrncpy(nd->name, newname, sizeof(nd->name));
  2197. clif_charnameack(0, &nd->bl);
  2198. }
  2199. /// Changes the display class of the npc.
  2200. ///
  2201. /// @param nd Target npc
  2202. /// @param class_ New display class
  2203. void npc_setclass(struct npc_data* nd, short class_)
  2204. {
  2205. nullpo_retv(nd);
  2206. if( nd->class_ == class_ )
  2207. return;
  2208. clif_clearunit_area(&nd->bl, CLR_OUTSIGHT);// fade out
  2209. nd->class_ = class_;
  2210. status_set_viewdata(&nd->bl, class_);
  2211. clif_spawn(&nd->bl);// fade in
  2212. }
  2213. /// Parses a function.
  2214. /// function%TAB%script%TAB%<function name>%TAB%{<code>}
  2215. static const char* npc_parse_function(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2216. {
  2217. DBMap* func_db;
  2218. struct script_code *script;
  2219. struct script_code *oldscript;
  2220. const char* end;
  2221. const char* script_start;
  2222. script_start = strstr(start,"\t{");
  2223. end = strchr(start,'\n');
  2224. if( *w4 != '{' || script_start == NULL || (end != NULL && script_start > end) )
  2225. {
  2226. 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);
  2227. return NULL;// can't continue
  2228. }
  2229. ++script_start;
  2230. end = npc_skip_script(script_start,buffer,filepath);
  2231. if( end == NULL )
  2232. return NULL;// (simple) parse error, don't continue
  2233. script = parse_script(script_start, filepath, strline(buffer,start-buffer), SCRIPT_RETURN_EMPTY_SCRIPT);
  2234. if( script == NULL )// parse error, continue
  2235. return end;
  2236. func_db = script_get_userfunc_db();
  2237. oldscript = (struct script_code*)strdb_put(func_db, w3, script);
  2238. if( oldscript != NULL )
  2239. {
  2240. ShowInfo("npc_parse_function: Overwriting user function [%s] (%s:%d)\n", w3, filepath, strline(buffer,start-buffer));
  2241. script_free_vars(&oldscript->script_vars);
  2242. aFree(oldscript->script_buf);
  2243. aFree(oldscript);
  2244. }
  2245. return end;
  2246. }
  2247. /*==========================================
  2248. * Parse Mob 1 - Parse mob list into each map
  2249. * Parse Mob 2 - Actually Spawns Mob
  2250. * [Wizputer]
  2251. *------------------------------------------*/
  2252. void npc_parse_mob2(struct spawn_data* mob)
  2253. {
  2254. int i;
  2255. for( i = mob->active; i < mob->num; ++i )
  2256. {
  2257. struct mob_data* md = mob_spawn_dataset(mob);
  2258. md->spawn = mob;
  2259. md->spawn->active++;
  2260. mob_spawn(md);
  2261. }
  2262. }
  2263. static const char* npc_parse_mob(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2264. {
  2265. int num, class_, mode, m,x,y,xs,ys, i,j;
  2266. char mapname[32];
  2267. struct spawn_data mob, *data;
  2268. struct mob_db* db;
  2269. memset(&mob, 0, sizeof(struct spawn_data));
  2270. mob.boss = !strcmpi(w2,"boss_monster");
  2271. // w1=<map name>,<x>,<y>,<xs>,<ys>
  2272. // w4=<mob id>,<amount>,<delay1>,<delay2>,<event>
  2273. if( sscanf(w1, "%31[^,],%d,%d,%d,%d", mapname, &x, &y, &xs, &ys) < 3
  2274. || sscanf(w4, "%d,%d,%u,%u,%127[^\t\r\n]", &class_, &num, &mob.delay1, &mob.delay2, mob.eventname) < 2 )
  2275. {
  2276. 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);
  2277. return strchr(start,'\n');// skip and continue
  2278. }
  2279. if( mapindex_name2id(mapname) == 0 )
  2280. {
  2281. ShowError("npc_parse_mob: Unknown map '%s' in file '%s', line '%d'.\n", mapname, filepath, strline(buffer,start-buffer));
  2282. return strchr(start,'\n');// skip and continue
  2283. }
  2284. m = map_mapname2mapid(mapname);
  2285. if( m < 0 )//Not loaded on this map-server instance.
  2286. return strchr(start,'\n');// skip and continue
  2287. mob.m = (unsigned short)m;
  2288. if( x < 0 || x >= map[mob.m].xs || y < 0 || y >= map[mob.m].ys )
  2289. {
  2290. 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));
  2291. return strchr(start,'\n');// skip and continue
  2292. }
  2293. // check monster ID if exists!
  2294. if( mobdb_checkid(class_) == 0 )
  2295. {
  2296. ShowError("npc_parse_mob: Unknown mob ID : %s %s (file '%s', line '%d').\n", w3, w4, filepath, strline(buffer,start-buffer));
  2297. return strchr(start,'\n');// skip and continue
  2298. }
  2299. if( num < 1 || num > 1000 )
  2300. {
  2301. ShowError("npc_parse_mob: Invalid number of monsters (must be inside the range [1,1000]) : %s %s (file '%s', line '%d').\n", w3, w4, filepath, strline(buffer,start-buffer));
  2302. return strchr(start,'\n');// skip and continue
  2303. }
  2304. mob.num = (unsigned short)num;
  2305. mob.active = 0;
  2306. mob.class_ = (short) class_;
  2307. mob.x = (unsigned short)x;
  2308. mob.y = (unsigned short)y;
  2309. mob.xs = (signed short)xs;
  2310. mob.ys = (signed short)ys;
  2311. if (mob.num > 1 && battle_config.mob_count_rate != 100) {
  2312. if ((mob.num = mob.num * battle_config.mob_count_rate / 100) < 1)
  2313. mob.num = 1;
  2314. }
  2315. if (battle_config.force_random_spawn || (mob.x == 0 && mob.y == 0))
  2316. { //Force a random spawn anywhere on the map.
  2317. mob.x = mob.y = 0;
  2318. mob.xs = mob.ys = -1;
  2319. }
  2320. db = mob_db(class_);
  2321. //Apply the spawn delay fix [Skotlex]
  2322. mode = db->status.mode;
  2323. if (mode & MD_BOSS) { //Bosses
  2324. if (battle_config.boss_spawn_delay != 100)
  2325. { // Divide by 100 first to prevent overflows
  2326. //(precision loss is minimal as duration is in ms already)
  2327. mob.delay1 = mob.delay1/100*battle_config.boss_spawn_delay;
  2328. mob.delay2 = mob.delay2/100*battle_config.boss_spawn_delay;
  2329. }
  2330. } else if (mode&MD_PLANT) { //Plants
  2331. if (battle_config.plant_spawn_delay != 100)
  2332. {
  2333. mob.delay1 = mob.delay1/100*battle_config.plant_spawn_delay;
  2334. mob.delay2 = mob.delay2/100*battle_config.plant_spawn_delay;
  2335. }
  2336. } else if (battle_config.mob_spawn_delay != 100)
  2337. { //Normal mobs
  2338. mob.delay1 = mob.delay1/100*battle_config.mob_spawn_delay;
  2339. mob.delay2 = mob.delay2/100*battle_config.mob_spawn_delay;
  2340. }
  2341. if(mob.delay1>0xfffffff || mob.delay2>0xfffffff) {
  2342. ShowError("npc_parse_mob: wrong monsters spawn delays : %s %s (file '%s', line '%d').\n", w3, w4, filepath, strline(buffer,start-buffer));
  2343. return strchr(start,'\n');// skip and continue
  2344. }
  2345. //Use db names instead of the spawn file ones.
  2346. if(battle_config.override_mob_names==1)
  2347. strcpy(mob.name,"--en--");
  2348. else if (battle_config.override_mob_names==2)
  2349. strcpy(mob.name,"--ja--");
  2350. else
  2351. safestrncpy(mob.name, w3, sizeof(mob.name));
  2352. //Verify dataset.
  2353. if( !mob_parse_dataset(&mob) )
  2354. {
  2355. ShowError("npc_parse_mob: Invalid dataset : %s %s (file '%s', line '%d').\n", w3, w4, filepath, strline(buffer,start-buffer));
  2356. return strchr(start,'\n');// skip and continue
  2357. }
  2358. //Update mob spawn lookup database
  2359. for( i = 0; i < ARRAYLENGTH(db->spawn); ++i )
  2360. {
  2361. if (map[mob.m].index == db->spawn[i].mapindex)
  2362. { //Update total
  2363. db->spawn[i].qty += mob.num;
  2364. //Re-sort list
  2365. for( j = i; j > 0 && db->spawn[j-1].qty < db->spawn[i].qty; --j );
  2366. if( j != i )
  2367. {
  2368. xs = db->spawn[i].mapindex;
  2369. ys = db->spawn[i].qty;
  2370. memmove(&db->spawn[j+1], &db->spawn[j], (i-j)*sizeof(db->spawn[0]));
  2371. db->spawn[j].mapindex = xs;
  2372. db->spawn[j].qty = ys;
  2373. }
  2374. break;
  2375. }
  2376. if (mob.num > db->spawn[i].qty)
  2377. { //Insert into list
  2378. memmove(&db->spawn[i+1], &db->spawn[i], sizeof(db->spawn) -(i+1)*sizeof(db->spawn[0]));
  2379. db->spawn[i].mapindex = map[mob.m].index;
  2380. db->spawn[i].qty = mob.num;
  2381. break;
  2382. }
  2383. }
  2384. //Now that all has been validated. We allocate the actual memory that the re-spawn data will use.
  2385. data = (struct spawn_data*)aMalloc(sizeof(struct spawn_data));
  2386. memcpy(data, &mob, sizeof(struct spawn_data));
  2387. // spawn / cache the new mobs
  2388. if( battle_config.dynamic_mobs && map_addmobtolist(data->m, data) >= 0 )
  2389. {
  2390. data->state.dynamic = true;
  2391. npc_cache_mob += data->num;
  2392. // check if target map has players
  2393. // (usually shouldn't occur when map server is just starting,
  2394. // but not the case when we do @reloadscript
  2395. if( map[data->m].users > 0 )
  2396. npc_parse_mob2(data);
  2397. }
  2398. else
  2399. {
  2400. data->state.dynamic = false;
  2401. npc_parse_mob2(data);
  2402. npc_delay_mob += data->num;
  2403. }
  2404. npc_mob++;
  2405. return strchr(start,'\n');// continue
  2406. }
  2407. /*==========================================
  2408. * マップフラグ行の解析
  2409. *------------------------------------------*/
  2410. static const char* npc_parse_mapflag(char* w1, char* w2, char* w3, char* w4, const char* start, const char* buffer, const char* filepath)
  2411. {
  2412. int m;
  2413. char mapname[32];
  2414. int state = 1;
  2415. // w1=<mapname>
  2416. if( sscanf(w1, "%31[^,]", mapname) != 1 )
  2417. {
  2418. 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);
  2419. return strchr(start,'\n');// skip and continue
  2420. }
  2421. m = map_mapname2mapid(mapname);
  2422. if( m < 0 )
  2423. {
  2424. 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);
  2425. return strchr(start,'\n');// skip and continue
  2426. }
  2427. if (w4 && !strcmpi(w4, "off"))
  2428. state = 0; //Disable mapflag rather than enable it. [Skotlex]
  2429. if (!strcmpi(w3, "nosave")) {
  2430. char savemap[32];
  2431. int savex, savey;
  2432. if (state == 0)
  2433. ; //Map flag disabled.
  2434. else if (!strcmpi(w4, "SavePoint")) {
  2435. map[m].save.map = 0;
  2436. map[m].save.x = -1;
  2437. map[m].save.y = -1;
  2438. } else if (sscanf(w4, "%31[^,],%d,%d", savemap, &savex, &savey) == 3) {
  2439. map[m].save.map = mapindex_name2id(savemap);
  2440. map[m].save.x = savex;
  2441. map[m].save.y = savey;
  2442. if (!map[m].save.map) {
  2443. 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);
  2444. map[m].save.x = -1;
  2445. map[m].save.y = -1;
  2446. }
  2447. }
  2448. map[m].flag.nosave = state;
  2449. }
  2450. else if (!strcmpi(w3,"autotrade"))
  2451. map[m].flag.autotrade=state;
  2452. else if (!strcmpi(w3,"allowks"))
  2453. map[m].flag.allowks=state; // [Kill Steal Protection]
  2454. else if (!strcmpi(w3,"town"))
  2455. map[m].flag.town=state;
  2456. else if (!strcmpi(w3,"nomemo"))
  2457. map[m].flag.nomemo=state;
  2458. else if (!strcmpi(w3,"noteleport"))
  2459. map[m].flag.noteleport=state;
  2460. else if (!strcmpi(w3,"nowarp"))
  2461. map[m].flag.nowarp=state;
  2462. else if (!strcmpi(w3,"nowarpto"))
  2463. map[m].flag.nowarpto=state;
  2464. else if (!strcmpi(w3,"noreturn"))
  2465. map[m].flag.noreturn=state;
  2466. else if (!strcmpi(w3,"monster_noteleport"))
  2467. map[m].flag.monster_noteleport=state;
  2468. else if (!strcmpi(w3,"nobranch"))
  2469. map[m].flag.nobranch=state;
  2470. else if (!strcmpi(w3,"nopenalty")) {
  2471. map[m].flag.noexppenalty=state;
  2472. map[m].flag.nozenypenalty=state;
  2473. }
  2474. else if (!strcmpi(w3,"pvp")) {
  2475. map[m].flag.pvp = state;
  2476. if( state && (map[m].flag.gvg || map[m].flag.gvg_dungeon || map[m].flag.gvg_castle) )
  2477. {
  2478. map[m].flag.gvg = 0;
  2479. map[m].flag.gvg_dungeon = 0;
  2480. map[m].flag.gvg_castle = 0;
  2481. 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));
  2482. }
  2483. if( state && map[m].flag.battleground )
  2484. {
  2485. map[m].flag.battleground = 0;
  2486. 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));
  2487. }
  2488. }
  2489. else if (!strcmpi(w3,"pvp_noparty"))
  2490. map[m].flag.pvp_noparty=state;
  2491. else if (!strcmpi(w3,"pvp_noguild"))
  2492. map[m].flag.pvp_noguild=state;
  2493. else if (!strcmpi(w3, "pvp_nightmaredrop")) {
  2494. char drop_arg1[16], drop_arg2[16];
  2495. int drop_id = 0, drop_type = 0, drop_per = 0;
  2496. if (sscanf(w4, "%[^,],%[^,],%d", drop_arg1, drop_arg2, &drop_per) == 3) {
  2497. int i;
  2498. if (!strcmpi(drop_arg1, "random"))
  2499. drop_id = -1;
  2500. else if (itemdb_exists((drop_id = atoi(drop_arg1))) == NULL)
  2501. drop_id = 0;
  2502. if (!strcmpi(drop_arg2, "inventory"))
  2503. drop_type = 1;
  2504. else if (!strcmpi(drop_arg2,"equip"))
  2505. drop_type = 2;
  2506. else if (!strcmpi(drop_arg2,"all"))
  2507. drop_type = 3;
  2508. if (drop_id != 0){
  2509. for (i = 0; i < MAX_DROP_PER_MAP; i++) {
  2510. if (map[m].drop_list[i].drop_id == 0){
  2511. map[m].drop_list[i].drop_id = drop_id;
  2512. map[m].drop_list[i].drop_type = drop_type;
  2513. map[m].drop_list[i].drop_per = drop_per;
  2514. break;
  2515. }
  2516. }
  2517. map[m].flag.pvp_nightmaredrop = 1;
  2518. }
  2519. } else if (!state) //Disable
  2520. map[m].flag.pvp_nightmaredrop = 0;
  2521. }
  2522. else if (!strcmpi(w3,"pvp_nocalcrank"))
  2523. map[m].flag.pvp_nocalcrank=state;
  2524. else if (!strcmpi(w3,"gvg")) {
  2525. map[m].flag.gvg = state;
  2526. if( state && map[m].flag.pvp )
  2527. {
  2528. map[m].flag.pvp = 0;
  2529. 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));
  2530. }
  2531. if( state && map[m].flag.battleground )
  2532. {
  2533. map[m].flag.battleground = 0;
  2534. 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));
  2535. }
  2536. }
  2537. else if (!strcmpi(w3,"gvg_noparty"))
  2538. map[m].flag.gvg_noparty=state;
  2539. else if (!strcmpi(w3,"gvg_dungeon")) {
  2540. map[m].flag.gvg_dungeon=state;
  2541. if (state) map[m].flag.pvp=0;
  2542. }
  2543. else if (!strcmpi(w3,"gvg_castle")) {
  2544. map[m].flag.gvg_castle=state;
  2545. if (state) map[m].flag.pvp=0;
  2546. }
  2547. else if (!strcmpi(w3,"battleground")) {
  2548. if( state )
  2549. {
  2550. if( sscanf(w4, "%d", &state) == 1 )
  2551. map[m].flag.battleground = state;
  2552. else
  2553. map[m].flag.battleground = 1; // Default value
  2554. }
  2555. else
  2556. map[m].flag.battleground = 0;
  2557. if( map[m].flag.battleground && map[m].flag.pvp )
  2558. {
  2559. map[m].flag.pvp = 0;
  2560. 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));
  2561. }
  2562. if( map[m].flag.battleground && (map[m].flag.gvg || map[m].flag.gvg_dungeon || map[m].flag.gvg_castle) )
  2563. {
  2564. map[m].flag.gvg = 0;
  2565. map[m].flag.gvg_dungeon = 0;
  2566. map[m].flag.gvg_castle = 0;
  2567. 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));
  2568. }
  2569. }
  2570. else if (!strcmpi(w3,"noexppenalty"))
  2571. map[m].flag.noexppenalty=state;
  2572. else if (!strcmpi(w3,"nozenypenalty"))
  2573. map[m].flag.nozenypenalty=state;
  2574. else if (!strcmpi(w3,"notrade"))
  2575. map[m].flag.notrade=state;
  2576. else if (!strcmpi(w3,"novending"))
  2577. map[m].flag.novending=state;
  2578. else if (!strcmpi(w3,"nodrop"))
  2579. map[m].flag.nodrop=state;
  2580. else if (!strcmpi(w3,"noskill"))
  2581. map[m].flag.noskill=state;
  2582. else if (!strcmpi(w3,"noicewall"))
  2583. map[m].flag.noicewall=state;
  2584. else if (!strcmpi(w3,"snow"))
  2585. map[m].flag.snow=state;
  2586. else if (!strcmpi(w3,"clouds"))
  2587. map[m].flag.clouds=state;
  2588. else if (!strcmpi(w3,"clouds2"))
  2589. map[m].flag.clouds2=state;
  2590. else if (!strcmpi(w3,"fog"))
  2591. map[m].flag.fog=state;
  2592. else if (!strcmpi(w3,"fireworks"))
  2593. map[m].flag.fireworks=state;
  2594. else if (!strcmpi(w3,"sakura"))
  2595. map[m].flag.sakura=state;
  2596. else if (!strcmpi(w3,"leaves"))
  2597. map[m].flag.leaves=state;
  2598. else if (!strcmpi(w3,"rain"))
  2599. map[m].flag.rain=state;
  2600. else if (!strcmpi(w3,"nightenabled"))
  2601. map[m].flag.nightenabled=state;
  2602. else if (!strcmpi(w3,"nogo"))
  2603. map[m].flag.nogo=state;
  2604. else if (!strcmpi(w3,"noexp")) {
  2605. map[m].flag.nobaseexp=state;
  2606. map[m].flag.nojobexp=state;
  2607. }
  2608. else if (!strcmpi(w3,"nobaseexp"))
  2609. map[m].flag.nobaseexp=state;
  2610. else if (!strcmpi(w3,"nojobexp"))
  2611. map[m].flag.nojobexp=state;
  2612. else if (!strcmpi(w3,"noloot")) {
  2613. map[m].flag.nomobloot=state;
  2614. map[m].flag.nomvploot=state;
  2615. }
  2616. else if (!strcmpi(w3,"nomobloot"))
  2617. map[m].flag.nomobloot=state;
  2618. else if (!strcmpi(w3,"nomvploot"))
  2619. map[m].flag.nomvploot=state;
  2620. else if (!strcmpi(w3,"nocommand")) {
  2621. if (state) {
  2622. if (sscanf(w4, "%d", &state) == 1)
  2623. map[m].nocommand =state;
  2624. else //No level specified, block everyone.
  2625. map[m].nocommand =100;
  2626. } else
  2627. map[m].nocommand=0;
  2628. }
  2629. else if (!strcmpi(w3,"restricted")) {
  2630. if (state) {
  2631. map[m].flag.restricted=1;
  2632. sscanf(w4, "%d", &state);
  2633. map[m].zone |= 1<<(state+1);
  2634. } else {
  2635. map[m].flag.restricted=0;
  2636. map[m].zone = 0;
  2637. }
  2638. }
  2639. else if (!strcmpi(w3,"jexp")) {
  2640. map[m].jexp = (state) ? atoi(w4) : 100;
  2641. if( map[m].jexp < 0 ) map[m].jexp = 100;
  2642. map[m].flag.nojobexp = (map[m].jexp==0)?1:0;
  2643. }
  2644. else if (!strcmpi(w3,"bexp")) {
  2645. map[m].bexp = (state) ? atoi(w4) : 100;
  2646. if( map[m].bexp < 0 ) map[m].bexp = 100;
  2647. map[m].flag.nobaseexp = (map[m].bexp==0)?1:0;
  2648. }
  2649. else if (!strcmpi(w3,"loadevent"))
  2650. map[m].flag.loadevent=state;
  2651. else if (!strcmpi(w3,"nochat"))
  2652. map[m].flag.nochat=state;
  2653. else if (!strcmpi(w3,"partylock"))
  2654. map[m].flag.partylock=state;
  2655. else if (!strcmpi(w3,"guildlock"))
  2656. map[m].flag.guildlock=state;
  2657. else
  2658. ShowError("npc_parse_mapflag: unrecognized mapflag '%s' (file '%s', line '%d').\n", w3, filepath, strline(buffer,start-buffer));
  2659. return strchr(start,'\n');// continue
  2660. }
  2661. void npc_parsesrcfile(const char* filepath)
  2662. {
  2663. int m, lines = 0;
  2664. FILE* fp;
  2665. size_t len;
  2666. char* buffer;
  2667. const char* p;
  2668. // read whole file to buffer
  2669. fp = fopen(filepath, "rb");
  2670. if( fp == NULL )
  2671. {
  2672. ShowError("npc_parsesrcfile: File not found '%s'.\n", filepath);
  2673. return;
  2674. }
  2675. fseek(fp, 0, SEEK_END);
  2676. len = ftell(fp);
  2677. buffer = (char*)aMalloc(len+1);
  2678. fseek(fp, 0, SEEK_SET);
  2679. len = fread(buffer, sizeof(char), len, fp);
  2680. buffer[len] = '\0';
  2681. if( ferror(fp) )
  2682. {
  2683. ShowError("npc_parsesrcfile: Failed to read file '%s' - %s\n", filepath, strerror(errno));
  2684. aFree(buffer);
  2685. fclose(fp);
  2686. return;
  2687. }
  2688. fclose(fp);
  2689. // parse buffer
  2690. for( p = skip_space(buffer); p && *p ; p = skip_space(p) )
  2691. {
  2692. int pos[9];
  2693. char w1[2048], w2[2048], w3[2048], w4[2048];
  2694. int i, count;
  2695. lines++;
  2696. // w1<TAB>w2<TAB>w3<TAB>w4
  2697. count = sv_parse(p, len+buffer-p, 0, '\t', pos, ARRAYLENGTH(pos), (e_svopt)(SV_TERMINATE_LF|SV_TERMINATE_CRLF));
  2698. if( count < 0 )
  2699. {
  2700. ShowError("npc_parsesrcfile: Parse error in file '%s', line '%d'. Stopping...\n", filepath, strline(buffer,p-buffer));
  2701. break;
  2702. }
  2703. // fill w1
  2704. if( pos[3]-pos[2] > ARRAYLENGTH(w1)-1 )
  2705. ShowWarning("npc_parsesrcfile: w1 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[3]-pos[2], filepath, strline(buffer,p-buffer));
  2706. i = min(pos[3]-pos[2], ARRAYLENGTH(w1)-1);
  2707. memcpy(w1, p+pos[2], i*sizeof(char));
  2708. w1[i] = '\0';
  2709. // fill w2
  2710. if( pos[5]-pos[4] > ARRAYLENGTH(w2)-1 )
  2711. ShowWarning("npc_parsesrcfile: w2 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[5]-pos[4], filepath, strline(buffer,p-buffer));
  2712. i = min(pos[5]-pos[4], ARRAYLENGTH(w2)-1);
  2713. memcpy(w2, p+pos[4], i*sizeof(char));
  2714. w2[i] = '\0';
  2715. // fill w3
  2716. if( pos[7]-pos[6] > ARRAYLENGTH(w3)-1 )
  2717. ShowWarning("npc_parsesrcfile: w3 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[7]-pos[6], filepath, strline(buffer,p-buffer));
  2718. i = min(pos[7]-pos[6], ARRAYLENGTH(w3)-1);
  2719. memcpy(w3, p+pos[6], i*sizeof(char));
  2720. w3[i] = '\0';
  2721. // fill w4 (to end of line)
  2722. if( pos[1]-pos[8] > ARRAYLENGTH(w4)-1 )
  2723. ShowWarning("npc_parsesrcfile: w4 truncated, too much data (%d) in file '%s', line '%d'.\n", pos[1]-pos[8], filepath, strline(buffer,p-buffer));
  2724. if( pos[8] != -1 )
  2725. {
  2726. i = min(pos[1]-pos[8], ARRAYLENGTH(w4)-1);
  2727. memcpy(w4, p+pos[8], i*sizeof(char));
  2728. w4[i] = '\0';
  2729. }
  2730. else
  2731. w4[0] = '\0';
  2732. if( count < 3 )
  2733. {// Unknown syntax
  2734. 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);
  2735. break;
  2736. }
  2737. if( strcmp(w1,"-") !=0 && strcasecmp(w1,"function") != 0 )
  2738. {// w1 = <map name>,<x>,<y>,<facing>
  2739. char mapname[2048];
  2740. sscanf(w1,"%[^,]",mapname);
  2741. if( !mapindex_name2id(mapname) )
  2742. {// Incorrect map, we must skip the script info...
  2743. ShowError("npc_parsesrcfile: Unknown map '%s' in file '%s', line '%d'. Skipping line...\n", mapname, filepath, strline(buffer,p-buffer));
  2744. if( strcasecmp(w2,"script") == 0 && count > 3 )
  2745. {
  2746. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  2747. {
  2748. break;
  2749. }
  2750. }
  2751. p = strchr(p,'\n');// next line
  2752. continue;
  2753. }
  2754. m = map_mapname2mapid(mapname);
  2755. if( m < 0 )
  2756. {// "mapname" is not assigned to this server, we must skip the script info...
  2757. if( strcasecmp(w2,"script") == 0 && count > 3 )
  2758. {
  2759. if((p = npc_skip_script(p,buffer,filepath)) == NULL)
  2760. {
  2761. break;
  2762. }
  2763. }
  2764. p = strchr(p,'\n');// next line
  2765. continue;
  2766. }
  2767. }
  2768. if( strcasecmp(w2,"warp") == 0 && count > 3 )
  2769. {
  2770. p = npc_parse_warp(w1,w2,w3,w4, p, buffer, filepath);
  2771. }
  2772. else if( (!strcasecmp(w2,"shop") || !strcasecmp(w2,"cashshop")) && count > 3 )
  2773. {
  2774. p = npc_parse_shop(w1,w2,w3,w4, p, buffer, filepath);
  2775. }
  2776. else if( strcasecmp(w2,"script") == 0 && count > 3 )
  2777. {
  2778. if( strcasecmp(w1,"function") == 0 )
  2779. p = npc_parse_function(w1, w2, w3, w4, p, buffer, filepath);
  2780. else
  2781. p = npc_parse_script(w1,w2,w3,w4, p, buffer, filepath);
  2782. }
  2783. else if( (i=0, sscanf(w2,"duplicate%n",&i), (i > 0 && w2[i] == '(')) && count > 3 )
  2784. {
  2785. p = npc_parse_duplicate(w1,w2,w3,w4, p, buffer, filepath);
  2786. }
  2787. else if( (strcmpi(w2,"monster") == 0 || strcmpi(w2,"boss_monster") == 0) && count > 3 )
  2788. {
  2789. p = npc_parse_mob(w1, w2, w3, w4, p, buffer, filepath);
  2790. }
  2791. else if( strcmpi(w2,"mapflag") == 0 && count >= 3 )
  2792. {
  2793. p = npc_parse_mapflag(w1, w2, trim(w3), trim(w4), p, buffer, filepath);
  2794. }
  2795. else
  2796. {
  2797. 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);
  2798. p = strchr(p,'\n');// skip and continue
  2799. }
  2800. }
  2801. aFree(buffer);
  2802. return;
  2803. }
  2804. int npc_script_event(struct map_session_data* sd, enum npce_event type)
  2805. {
  2806. int i;
  2807. if (type == NPCE_MAX)
  2808. return 0;
  2809. if (!sd) {
  2810. ShowError("npc_script_event: NULL sd. Event Type %d\n", type);
  2811. return 0;
  2812. }
  2813. for (i = 0; i<script_event[type].event_count; i++)
  2814. npc_event_sub(sd,script_event[type].event[i],script_event[type].event_name[i]);
  2815. return i;
  2816. }
  2817. void npc_read_event_script(void)
  2818. {
  2819. int i;
  2820. struct {
  2821. char *name;
  2822. const char *event_name;
  2823. } config[] = {
  2824. {"Login Event",script_config.login_event_name},
  2825. {"Logout Event",script_config.logout_event_name},
  2826. {"Load Map Event",script_config.loadmap_event_name},
  2827. {"Base LV Up Event",script_config.baselvup_event_name},
  2828. {"Job LV Up Event",script_config.joblvup_event_name},
  2829. {"Die Event",script_config.die_event_name},
  2830. {"Kill PC Event",script_config.kill_pc_event_name},
  2831. {"Kill NPC Event",script_config.kill_mob_event_name},
  2832. };
  2833. for (i = 0; i < NPCE_MAX; i++)
  2834. {
  2835. DBIterator* iter;
  2836. DBKey key;
  2837. void* data;
  2838. char name[64]="::";
  2839. strncpy(name+2,config[i].event_name,62);
  2840. script_event[i].event_count = 0;
  2841. iter = ev_db->iterator(ev_db);
  2842. for( data = iter->first(iter,&key); iter->exists(iter); data = iter->next(iter,&key) )
  2843. {
  2844. const char* p = key.str;
  2845. struct event_data* ed = (struct event_data*) data;
  2846. unsigned char count = script_event[i].event_count;
  2847. if( count >= ARRAYLENGTH(script_event[i].event) )
  2848. {
  2849. ShowWarning("npc_read_event_script: too many occurences of event '%s'!\n", config[i].event_name);
  2850. break;
  2851. }
  2852. if( (p=strchr(p,':')) && p && strcmpi(name,p)==0 )
  2853. {
  2854. script_event[i].event[count] = ed;
  2855. script_event[i].event_name[count] = key.str;
  2856. script_event[i].event_count++;
  2857. }
  2858. }
  2859. iter->destroy(iter);
  2860. }
  2861. if (battle_config.etc_log) {
  2862. //Print summary.
  2863. for (i = 0; i < NPCE_MAX; i++)
  2864. ShowInfo("%s: %d '%s' events.\n", config[i].name, script_event[i].event_count, config[i].event_name);
  2865. }
  2866. }
  2867. int npc_reload(void)
  2868. {
  2869. struct npc_src_list *nsl;
  2870. int m, i;
  2871. int npc_new_min = npc_id;
  2872. struct s_mapiterator* iter;
  2873. struct block_list* bl;
  2874. //Remove all npcs/mobs. [Skotlex]
  2875. iter = mapit_geteachiddb();
  2876. for( bl = (struct block_list*)mapit_first(iter); mapit_exists(iter); bl = (struct block_list*)mapit_next(iter) )
  2877. {
  2878. switch(bl->type) {
  2879. case BL_NPC:
  2880. if( bl->id != fake_nd->bl.id )// don't remove fake_nd
  2881. npc_unload((struct npc_data *)bl);
  2882. break;
  2883. case BL_MOB:
  2884. unit_free(bl,CLR_OUTSIGHT);
  2885. break;
  2886. }
  2887. }
  2888. mapit_free(iter);
  2889. if(battle_config.dynamic_mobs)
  2890. {// dynamic check by [random]
  2891. for (m = 0; m < map_num; m++) {
  2892. for (i = 0; i < MAX_MOB_LIST_PER_MAP; i++) {
  2893. if (map[m].moblist[i] != NULL) {
  2894. aFree(map[m].moblist[i]);
  2895. map[m].moblist[i] = NULL;
  2896. }
  2897. if( map[m].mob_delete_timer != INVALID_TIMER )
  2898. { // Mobs were removed anyway,so delete the timer [Inkfish]
  2899. delete_timer(map[m].mob_delete_timer, map_removemobs_timer);
  2900. map[m].mob_delete_timer = INVALID_TIMER;
  2901. }
  2902. }
  2903. }
  2904. if (map[m].npc_num > 0)
  2905. ShowWarning("npc_reload: %d npcs weren't removed at map %s!\n", map[m].npc_num, map[m].name);
  2906. }
  2907. // clear mob spawn lookup index
  2908. mob_clear_spawninfo();
  2909. // clear npc-related data structures
  2910. ev_db->clear(ev_db,NULL);
  2911. npcname_db->clear(npcname_db,NULL);
  2912. npc_warp = npc_shop = npc_script = 0;
  2913. npc_mob = npc_cache_mob = npc_delay_mob = 0;
  2914. // reset mapflags
  2915. map_flags_init();
  2916. //TODO: the following code is copy-pasted from do_init_npc(); clean it up
  2917. // Reloading npcs now
  2918. for (nsl = npc_src_files; nsl; nsl = nsl->next)
  2919. {
  2920. ShowStatus("Loading NPC file: %s"CL_CLL"\r", nsl->name);
  2921. npc_parsesrcfile(nsl->name);
  2922. }
  2923. ShowInfo ("Done loading '"CL_WHITE"%d"CL_RESET"' NPCs:"CL_CLL"\n"
  2924. "\t-'"CL_WHITE"%d"CL_RESET"' Warps\n"
  2925. "\t-'"CL_WHITE"%d"CL_RESET"' Shops\n"
  2926. "\t-'"CL_WHITE"%d"CL_RESET"' Scripts\n"
  2927. "\t-'"CL_WHITE"%d"CL_RESET"' Spawn sets\n"
  2928. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Cached\n"
  2929. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Not Cached\n",
  2930. npc_id - npc_new_min, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  2931. for( i = 0; i < ARRAYLENGTH(instance); ++i )
  2932. instance_init(instance[i].instance_id);
  2933. //Re-read the NPC Script Events cache.
  2934. npc_read_event_script();
  2935. //Execute the OnInit event for freshly loaded npcs. [Skotlex]
  2936. ShowStatus("Event '"CL_WHITE"OnInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n",npc_event_doall("OnInit"));
  2937. // Execute rest of the startup events if connected to char-server. [Lance]
  2938. if(!CheckForCharServer()){
  2939. ShowStatus("Event '"CL_WHITE"OnInterIfInit"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n", npc_event_doall("OnInterIfInit"));
  2940. ShowStatus("Event '"CL_WHITE"OnInterIfInitOnce"CL_RESET"' executed with '"CL_WHITE"%d"CL_RESET"' NPCs.\n", npc_event_doall("OnInterIfInitOnce"));
  2941. }
  2942. return 0;
  2943. }
  2944. /*==========================================
  2945. * 終了
  2946. *------------------------------------------*/
  2947. int do_final_npc(void)
  2948. {
  2949. int i;
  2950. struct block_list *bl;
  2951. for (i = START_NPC_NUM; i < npc_id; i++){
  2952. if ((bl = map_id2bl(i))){
  2953. if (bl->type == BL_NPC)
  2954. npc_unload((struct npc_data *)bl);
  2955. else if (bl->type&(BL_MOB|BL_PET|BL_HOM|BL_MER))
  2956. unit_free(bl, CLR_OUTSIGHT);
  2957. }
  2958. }
  2959. ev_db->destroy(ev_db, NULL);
  2960. //There is no free function for npcname_db because at this point there shouldn't be any npcs left!
  2961. //So if there is anything remaining, let the memory manager catch it and report it.
  2962. npcname_db->destroy(npcname_db, NULL);
  2963. ers_destroy(timer_event_ers);
  2964. npc_clearsrcfile();
  2965. return 0;
  2966. }
  2967. static void npc_debug_warps_sub(struct npc_data* nd)
  2968. {
  2969. int m;
  2970. if (nd->bl.type != BL_NPC || nd->subtype != WARP || nd->bl.m < 0)
  2971. return;
  2972. m = map_mapindex2mapid(nd->u.warp.mapindex);
  2973. if (m < 0) return; //Warps to another map, nothing to do about it.
  2974. if (nd->u.warp.x == 0 && nd->u.warp.y == 0) return; // random warp
  2975. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNPC)) {
  2976. ShowWarning("Warp %s at %s(%d,%d) warps directly on top of an area npc at %s(%d,%d)\n",
  2977. nd->name,
  2978. map[nd->bl.m].name, nd->bl.x, nd->bl.y,
  2979. map[m].name, nd->u.warp.x, nd->u.warp.y
  2980. );
  2981. }
  2982. if (map_getcell(m, nd->u.warp.x, nd->u.warp.y, CELL_CHKNOPASS)) {
  2983. ShowWarning("Warp %s at %s(%d,%d) warps to a non-walkable tile at %s(%d,%d)\n",
  2984. nd->name,
  2985. map[nd->bl.m].name, nd->bl.x, nd->bl.y,
  2986. map[m].name, nd->u.warp.x, nd->u.warp.y
  2987. );
  2988. }
  2989. }
  2990. static void npc_debug_warps(void)
  2991. {
  2992. int m, i;
  2993. for (m = 0; m < map_num; m++)
  2994. for (i = 0; i < map[m].npc_num; i++)
  2995. npc_debug_warps_sub(map[m].npc[i]);
  2996. }
  2997. /*==========================================
  2998. * npc initialization
  2999. *------------------------------------------*/
  3000. int do_init_npc(void)
  3001. {
  3002. struct npc_src_list *file;
  3003. int i;
  3004. //Stock view data for normal npcs.
  3005. memset(&npc_viewdb, 0, sizeof(npc_viewdb));
  3006. npc_viewdb[0].class_ = INVISIBLE_CLASS; //Invisible class is stored here.
  3007. for( i = 1; i < MAX_NPC_CLASS; i++ )
  3008. npc_viewdb[i].class_ = i;
  3009. ev_db = strdb_alloc((DBOptions)(DB_OPT_DUP_KEY|DB_OPT_RELEASE_DATA),2*NAME_LENGTH+2+1);
  3010. npcname_db = strdb_alloc(DB_OPT_BASE,NAME_LENGTH);
  3011. timer_event_ers = ers_new(sizeof(struct timer_event_data));
  3012. // process all npc files
  3013. ShowStatus("Loading NPCs...\r");
  3014. for( file = npc_src_files; file != NULL; file = file->next )
  3015. {
  3016. ShowStatus("Loading NPC file: %s"CL_CLL"\r", file->name);
  3017. npc_parsesrcfile(file->name);
  3018. }
  3019. ShowInfo ("Done loading '"CL_WHITE"%d"CL_RESET"' NPCs:"CL_CLL"\n"
  3020. "\t-'"CL_WHITE"%d"CL_RESET"' Warps\n"
  3021. "\t-'"CL_WHITE"%d"CL_RESET"' Shops\n"
  3022. "\t-'"CL_WHITE"%d"CL_RESET"' Scripts\n"
  3023. "\t-'"CL_WHITE"%d"CL_RESET"' Spawn sets\n"
  3024. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Cached\n"
  3025. "\t-'"CL_WHITE"%d"CL_RESET"' Mobs Not Cached\n",
  3026. npc_id - START_NPC_NUM, npc_warp, npc_shop, npc_script, npc_mob, npc_cache_mob, npc_delay_mob);
  3027. // set up the events cache
  3028. memset(script_event, 0, sizeof(script_event));
  3029. npc_read_event_script();
  3030. //Debug function to locate all endless loop warps.
  3031. if (battle_config.warp_point_debug)
  3032. npc_debug_warps();
  3033. add_timer_func_list(npc_event_do_clock,"npc_event_do_clock");
  3034. add_timer_func_list(npc_timerevent,"npc_timerevent");
  3035. // Init dummy NPC
  3036. fake_nd = (struct npc_data *)aCalloc(1,sizeof(struct npc_data));
  3037. fake_nd->bl.m = -1;
  3038. fake_nd->bl.id = npc_get_new_npc_id();
  3039. fake_nd->class_ = -1;
  3040. fake_nd->speed = 200;
  3041. strcpy(fake_nd->name,"FAKE_NPC");
  3042. memcpy(fake_nd->exname, fake_nd->name, 9);
  3043. npc_script++;
  3044. fake_nd->bl.type = BL_NPC;
  3045. fake_nd->subtype = SCRIPT;
  3046. strdb_put(npcname_db, fake_nd->exname, fake_nd);
  3047. fake_nd->u.scr.timerid = -1;
  3048. map_addiddb(&fake_nd->bl);
  3049. // End of initialization
  3050. return 0;
  3051. }