PageRenderTime 61ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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;

Large files files are truncated, but you can click here to view the full file