PageRenderTime 77ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/src/map/npc.c

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