vending.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. // Copyright (c) rAthena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "vending.hpp"
  4. #include <cstdlib> // atoi
  5. #include <common/malloc.hpp> // aMalloc, aFree
  6. #include <common/nullpo.hpp>
  7. #include <common/showmsg.hpp> // ShowInfo
  8. #include <common/strlib.hpp>
  9. #include <common/timer.hpp> // DIFF_TICK
  10. #include "achievement.hpp"
  11. #include "atcommand.hpp"
  12. #include "battle.hpp"
  13. #include "buyingstore.hpp"
  14. #include "buyingstore.hpp" // struct s_autotrade_entry, struct s_autotrader
  15. #include "chrif.hpp"
  16. #include "clif.hpp"
  17. #include "itemdb.hpp"
  18. #include "log.hpp"
  19. #include "npc.hpp"
  20. #include "path.hpp"
  21. #include "pc.hpp"
  22. #include "pc_groups.hpp"
  23. static uint32 vending_nextid = 0; ///Vending_id counter
  24. static DBMap *vending_db; ///DB holder the vender : charid -> map_session_data
  25. //Autotrader
  26. static DBMap *vending_autotrader_db; /// Holds autotrader info: char_id -> struct s_autotrader
  27. static void vending_autotrader_remove(struct s_autotrader *at, bool remove);
  28. static int32 vending_autotrader_free(DBKey key, DBData *data, va_list ap);
  29. /**
  30. * Lookup to get the vending_db outside module
  31. * @return the vending_db
  32. */
  33. DBMap * vending_getdb()
  34. {
  35. return vending_db;
  36. }
  37. /**
  38. * Create an unique vending shop id.
  39. * @return the next vending_id
  40. */
  41. static int32 vending_getuid(void)
  42. {
  43. return ++vending_nextid;
  44. }
  45. /**
  46. * Make a player close his shop
  47. * @param sd : player session
  48. */
  49. void vending_closevending(map_session_data* sd)
  50. {
  51. nullpo_retv(sd);
  52. if( sd->state.vending ) {
  53. if( Sql_Query( mmysql_handle, "DELETE FROM `%s` WHERE vending_id = %d;", vending_items_table, sd->vender_id ) != SQL_SUCCESS ||
  54. Sql_Query( mmysql_handle, "DELETE FROM `%s` WHERE `id` = %d;", vendings_table, sd->vender_id ) != SQL_SUCCESS ) {
  55. Sql_ShowDebug(mmysql_handle);
  56. }
  57. sd->state.vending = false;
  58. sd->vender_id = 0;
  59. clif_closevendingboard(&sd->bl, 0);
  60. idb_remove(vending_db, sd->status.char_id);
  61. }
  62. }
  63. /**
  64. * Player request a shop's item list (a player shop)
  65. * @param sd : player requestion the list
  66. * @param id : vender account id (gid)
  67. */
  68. void vending_vendinglistreq(map_session_data* sd, int32 id)
  69. {
  70. map_session_data* vsd;
  71. nullpo_retv(sd);
  72. if( (vsd = map_id2sd(id)) == nullptr )
  73. return;
  74. if( !vsd->state.vending )
  75. return; // not vending
  76. if (!pc_can_give_items(sd) || !pc_can_give_items(vsd)) { //check if both GMs are allowed to trade
  77. clif_displaymessage( sd->fd, msg_txt( sd, 246 ) ); // Your GM level doesn't authorize you to perform this action.
  78. return;
  79. }
  80. sd->vended_id = vsd->vender_id; // register vending uid
  81. clif_vendinglist( *sd, *vsd );
  82. }
  83. /**
  84. * Calculates taxes for vending
  85. * @param sd: Vender
  86. * @param zeny: Total amount to tax
  87. * @return Total amount after taxes
  88. */
  89. static double vending_calc_tax(map_session_data *sd, double zeny)
  90. {
  91. if (battle_config.vending_tax && zeny >= battle_config.vending_tax_min)
  92. zeny -= zeny * (battle_config.vending_tax / 10000.);
  93. return zeny;
  94. }
  95. /**
  96. * Purchase item(s) from a shop
  97. * @param sd : buyer player session
  98. * @param aid : account id of vender
  99. * @param uid : shop unique id
  100. * @param data : items data who would like to purchase \n
  101. * data := {<index>.w <amount>.w }[count]
  102. * @param count : number of different items he's trying to buy
  103. */
  104. void vending_purchasereq(map_session_data* sd, int32 aid, int32 uid, const uint8* data, int32 count)
  105. {
  106. int32 i, j, cursor, w, new_ = 0, blank, vend_list[MAX_VENDING];
  107. double z;
  108. struct s_vending vending[MAX_VENDING]; // against duplicate packets
  109. map_session_data* vsd = map_id2sd(aid);
  110. nullpo_retv(sd);
  111. if( vsd == nullptr || !vsd->state.vending || vsd->bl.id == sd->bl.id )
  112. return; // invalid shop
  113. if( vsd->vender_id != uid ) { // shop has changed
  114. clif_buyvending( *sd, 0, 0, PURCHASEMC_STORE_INCORRECT ); // store information was incorrect
  115. return;
  116. }
  117. if( !searchstore_queryremote(*sd, aid) && ( sd->bl.m != vsd->bl.m || !check_distance_bl(&sd->bl, &vsd->bl, AREA_SIZE) ) )
  118. return; // shop too far away
  119. searchstore_clearremote(*sd);
  120. if( count < 1 || count > MAX_VENDING || count > vsd->vend_num )
  121. return; // invalid amount of purchased items
  122. blank = pc_inventoryblank(sd); //number of free cells in the buyer's inventory
  123. // duplicate item in vending to check hacker with multiple packets
  124. memcpy(&vending, &vsd->vending, sizeof(vsd->vending)); // copy vending list
  125. // some checks
  126. z = 0.; // zeny counter
  127. w = 0; // weight counter
  128. for( i = 0; i < count; i++ ) {
  129. short amount = *(uint16*)(data + 4*i + 0);
  130. short idx = *(uint16*)(data + 4*i + 2);
  131. idx -= 2;
  132. if( amount <= 0 )
  133. return;
  134. // check of item index in the cart
  135. if( idx < 0 || idx >= MAX_CART )
  136. return;
  137. ARR_FIND( 0, vsd->vend_num, j, vsd->vending[j].index == idx );
  138. if( j == vsd->vend_num )
  139. return; //picked non-existing item
  140. else
  141. vend_list[i] = j;
  142. z += ((double)vsd->vending[j].value * (double)amount);
  143. if( z > (double)sd->status.zeny || z < 0. || z > (double)MAX_ZENY ) {
  144. clif_buyvending( *sd, idx, amount, PURCHASEMC_NO_ZENY ); // you don't have enough zeny
  145. return;
  146. }
  147. if( z + (double)vsd->status.zeny > (double)MAX_ZENY ) {
  148. clif_buyvending( *sd, idx, vsd->vending[j].amount, PURCHASEMC_OUT_OF_STOCK ); // too much zeny = overflow
  149. return;
  150. }
  151. w += itemdb_weight(vsd->cart.u.items_cart[idx].nameid) * amount;
  152. if( w + sd->weight > sd->max_weight ) {
  153. clif_buyvending( *sd, idx, amount, PURCHASEMC_OVERWEIGHT );
  154. return;
  155. }
  156. //Check to see if cart/vend info is in sync.
  157. if( vending[j].amount > vsd->cart.u.items_cart[idx].amount )
  158. vending[j].amount = vsd->cart.u.items_cart[idx].amount;
  159. // if they try to add packets (example: get twice or more 2 apples if marchand has only 3 apples).
  160. // here, we check cumulative amounts
  161. if( vending[j].amount < amount ) {
  162. // send more quantity is not a hack (an other player can have buy items just before)
  163. clif_buyvending( *sd, idx, vsd->vending[j].amount, PURCHASEMC_OUT_OF_STOCK );
  164. return;
  165. }
  166. vending[j].amount -= amount;
  167. switch( pc_checkadditem(sd, vsd->cart.u.items_cart[idx].nameid, amount) ) {
  168. case CHKADDITEM_EXIST:
  169. break; //We'd add this item to the existing one (in buyers inventory)
  170. case CHKADDITEM_NEW:
  171. new_++;
  172. if (new_ > blank)
  173. return; //Buyer has no space in his inventory
  174. break;
  175. case CHKADDITEM_OVERAMOUNT:
  176. return; //too many items
  177. }
  178. }
  179. pc_payzeny(sd, (int)z, LOG_TYPE_VENDING, vsd->status.char_id);
  180. achievement_update_objective(sd, AG_SPEND_ZENY, 1, (int)z);
  181. z = vending_calc_tax(sd, z);
  182. pc_getzeny(vsd, (int)z, LOG_TYPE_VENDING, sd->status.char_id);
  183. for( i = 0; i < count; i++ ) {
  184. short amount = *(uint16*)(data + 4*i + 0);
  185. short idx = *(uint16*)(data + 4*i + 2);
  186. idx -= 2;
  187. z = 0.; // zeny counter
  188. // vending item
  189. pc_additem(sd, &vsd->cart.u.items_cart[idx], amount, LOG_TYPE_VENDING);
  190. vsd->vending[vend_list[i]].amount -= amount;
  191. z += ((double)vsd->vending[vend_list[i]].value * (double)amount);
  192. if( vsd->vending[vend_list[i]].amount ) {
  193. if( Sql_Query( mmysql_handle, "UPDATE `%s` SET `amount` = %d WHERE `vending_id` = %d and `cartinventory_id` = %d", vending_items_table, vsd->vending[vend_list[i]].amount, vsd->vender_id, vsd->cart.u.items_cart[idx].id ) != SQL_SUCCESS ) {
  194. Sql_ShowDebug( mmysql_handle );
  195. }
  196. } else {
  197. if( Sql_Query( mmysql_handle, "DELETE FROM `%s` WHERE `vending_id` = %d and `cartinventory_id` = %d", vending_items_table, vsd->vender_id, vsd->cart.u.items_cart[idx].id ) != SQL_SUCCESS ) {
  198. Sql_ShowDebug( mmysql_handle );
  199. }
  200. }
  201. pc_cart_delitem(vsd, idx, amount, 0, LOG_TYPE_VENDING);
  202. z = vending_calc_tax(sd, z);
  203. clif_vendingreport( *vsd, idx, amount, sd->status.char_id, (int)z );
  204. //print32 buyer's name
  205. if( battle_config.buyer_name ) {
  206. char temp[256];
  207. sprintf(temp, msg_txt(sd,265), sd->status.name);
  208. clif_messagecolor(&vsd->bl, color_table[COLOR_LIGHT_GREEN], temp, false, SELF);
  209. }
  210. }
  211. // compact the vending list
  212. for( i = 0, cursor = 0; i < vsd->vend_num; i++ ) {
  213. if( vsd->vending[i].amount == 0 )
  214. continue;
  215. if( cursor != i ) { // speedup
  216. vsd->vending[cursor].index = vsd->vending[i].index;
  217. vsd->vending[cursor].amount = vsd->vending[i].amount;
  218. vsd->vending[cursor].value = vsd->vending[i].value;
  219. }
  220. cursor++;
  221. }
  222. vsd->vend_num = cursor;
  223. //Always save BOTH: customer (buyer) and vender
  224. if( save_settings&CHARSAVE_VENDING ) {
  225. chrif_save(sd, CSAVE_INVENTORY|CSAVE_CART);
  226. chrif_save(vsd, CSAVE_INVENTORY|CSAVE_CART);
  227. }
  228. //check for @AUTOTRADE users [durf]
  229. if( vsd->state.autotrade ) {
  230. //see if there is anything left in the shop
  231. ARR_FIND( 0, vsd->vend_num, i, vsd->vending[i].amount > 0 );
  232. if( i == vsd->vend_num ) {
  233. //Close Vending (this was automatically done by the client, we have to do it manually for autovenders) [Skotlex]
  234. vending_closevending(vsd);
  235. map_quit(vsd); //They have no reason to stay around anymore, do they?
  236. }
  237. }
  238. }
  239. /**
  240. * Player setup a new shop
  241. * @param sd : player opening the shop
  242. * @param message : shop title
  243. * @param data : itemlist data
  244. * data := {<index>.w <amount>.w <value>.l}[count]
  245. * @param count : number of different items
  246. * @param at Autotrader info, or nullptr if requetsed not from autotrade persistance
  247. * @return 0 If success, 1 - Cannot open (die, not state.prevend, trading), 2 - No cart, 3 - Count issue, 4 - Cart data isn't saved yet, 5 - No valid item found
  248. */
  249. int8 vending_openvending( map_session_data& sd, const char* message, const uint8* data, int32 count, struct s_autotrader *at ){
  250. int32 i, j;
  251. int32 vending_skill_lvl;
  252. char message_sql[MESSAGE_SIZE*2];
  253. StringBuf buf;
  254. if ( pc_isdead(&sd) || !sd.state.prevend || pc_istrading(&sd)) {
  255. return 1; // can't open vendings lying dead || didn't use via the skill (wpe/hack) || can't have 2 shops at once
  256. }
  257. vending_skill_lvl = pc_checkskill(&sd, MC_VENDING);
  258. // skill level and cart check
  259. if( !vending_skill_lvl || !pc_iscarton(&sd) ) {
  260. clif_skill_fail( sd, MC_VENDING );
  261. sd.state.prevend = 0;
  262. sd.state.workinprogress = WIP_DISABLE_NONE;
  263. clif_openvending_ack( sd, OPENSTORE2_FAILED );
  264. return 2;
  265. }
  266. // check number of items in shop
  267. if( count < 1 || count > MAX_VENDING || count > 2 + vending_skill_lvl ) { // invalid item count
  268. clif_skill_fail( sd, MC_VENDING );
  269. sd.state.prevend = 0;
  270. sd.state.workinprogress = WIP_DISABLE_NONE;
  271. clif_openvending_ack( sd, OPENSTORE2_FAILED );
  272. return 3;
  273. }
  274. if (save_settings&CHARSAVE_VENDING) // Avoid invalid data from saving
  275. chrif_save(&sd, CSAVE_INVENTORY|CSAVE_CART);
  276. // filter out invalid items
  277. i = 0;
  278. int64 total = 0;
  279. for( j = 0; j < count; j++ ) {
  280. short index = *(uint16*)(data + 8*j + 0);
  281. short amount = *(uint16*)(data + 8*j + 2);
  282. uint32 value = *(uint32*)(data + 8*j + 4);
  283. index -= 2; // offset adjustment (client says that the first cart position is 2)
  284. if( index < 0 || index >= MAX_CART // invalid position
  285. || pc_cartitem_amount(&sd, index, amount) < 0 // invalid item or insufficient quantity
  286. //NOTE: official server does not do any of the following checks!
  287. || !sd.cart.u.items_cart[index].identify // unidentified item
  288. || sd.cart.u.items_cart[index].attribute == 1 // broken item
  289. || sd.cart.u.items_cart[index].expire_time // It should not be in the cart but just in case
  290. || (sd.cart.u.items_cart[index].bound && !pc_can_give_bounded_items(&sd)) // can't trade account bound items and has no permission
  291. || !itemdb_cantrade(&sd.cart.u.items_cart[index], pc_get_group_level(&sd), pc_get_group_level(&sd)) ) // untradeable item
  292. continue;
  293. sd.vending[i].index = index;
  294. sd.vending[i].amount = amount;
  295. sd.vending[i].value = min(value, (uint32)battle_config.vending_max_value);
  296. total += static_cast<int64>(sd.vending[i].value) * amount;
  297. i++; // item successfully added
  298. }
  299. // check if the total value of the items plus the current zeny is over the limit
  300. if ( !battle_config.vending_over_max && (static_cast<int64>(sd.status.zeny) + total) > MAX_ZENY ) {
  301. #if PACKETVER >= 20200819
  302. clif_msg_color( &sd, MSI_MERCHANTSHOP_TOTA_LOVER_ZENY_ERR, color_table[COLOR_RED] );
  303. #endif
  304. clif_skill_fail( sd, MC_VENDING );
  305. sd.state.prevend = 0;
  306. sd.state.workinprogress = WIP_DISABLE_NONE;
  307. clif_openvending_ack( sd, OPENSTORE2_FAILED );
  308. return 1;
  309. }
  310. if (i != j) {
  311. clif_displaymessage(sd.fd, msg_txt(&sd, 266)); //"Some of your items cannot be vended and were removed from the shop."
  312. clif_skill_fail( sd, MC_VENDING ); // custom reply packet
  313. sd.state.prevend = 0;
  314. sd.state.workinprogress = WIP_DISABLE_NONE;
  315. clif_openvending_ack( sd, OPENSTORE2_FAILED );
  316. return 5;
  317. }
  318. if( i == 0 ) { // no valid item found
  319. clif_skill_fail( sd, MC_VENDING ); // custom reply packet
  320. sd.state.prevend = 0;
  321. sd.state.workinprogress = WIP_DISABLE_NONE;
  322. clif_openvending_ack( sd, OPENSTORE2_FAILED );
  323. return 5;
  324. }
  325. sd.state.prevend = 0;
  326. sd.state.vending = true;
  327. sd.state.workinprogress = WIP_DISABLE_NONE;
  328. sd.vender_id = vending_getuid();
  329. sd.vend_num = i;
  330. safestrncpy(sd.message, message, MESSAGE_SIZE);
  331. Sql_EscapeString( mmysql_handle, message_sql, sd.message );
  332. if( Sql_Query( mmysql_handle, "INSERT INTO `%s`(`id`, `account_id`, `char_id`, `sex`, `map`, `x`, `y`, `title`, `autotrade`, `body_direction`, `head_direction`, `sit`) "
  333. "VALUES( %d, %d, %d, '%c', '%s', %d, %d, '%s', %d, '%d', '%d', '%d' );",
  334. vendings_table, sd.vender_id, sd.status.account_id, sd.status.char_id, sd.status.sex == SEX_FEMALE ? 'F' : 'M', map_getmapdata(sd.bl.m)->name, sd.bl.x, sd.bl.y, message_sql, sd.state.autotrade, at ? at->dir : sd.ud.dir, at ? at->head_dir : sd.head_dir, at ? at->sit : pc_issit(&sd) ) != SQL_SUCCESS ) {
  335. Sql_ShowDebug(mmysql_handle);
  336. }
  337. StringBuf_Init(&buf);
  338. StringBuf_Printf(&buf, "INSERT INTO `%s`(`vending_id`,`index`,`cartinventory_id`,`amount`,`price`) VALUES", vending_items_table);
  339. for (j = 0; j < i; j++) {
  340. StringBuf_Printf(&buf, "(%d,%d,%d,%d,%d)", sd.vender_id, j, sd.cart.u.items_cart[sd.vending[j].index].id, sd.vending[j].amount, sd.vending[j].value);
  341. if (j < i-1)
  342. StringBuf_AppendStr(&buf, ",");
  343. }
  344. if (SQL_ERROR == Sql_QueryStr(mmysql_handle, StringBuf_Value(&buf)))
  345. Sql_ShowDebug(mmysql_handle);
  346. StringBuf_Destroy(&buf);
  347. clif_openvending( sd );
  348. clif_showvendingboard( sd );
  349. idb_put(vending_db, sd.status.char_id, &sd);
  350. return 0;
  351. }
  352. /**
  353. * Checks if an item is being sold in given player's vending.
  354. * @param sd : vender session (player)
  355. * @param nameid : item id
  356. * @return 0:not selling it, 1: yes
  357. */
  358. bool vending_search(map_session_data* sd, t_itemid nameid)
  359. {
  360. int32 i;
  361. if( !sd->state.vending ) { // not vending
  362. return false;
  363. }
  364. ARR_FIND( 0, sd->vend_num, i, sd->cart.u.items_cart[sd->vending[i].index].nameid == nameid );
  365. if( i == sd->vend_num ) { // not found
  366. return false;
  367. }
  368. return true;
  369. }
  370. /**
  371. * Searches for all items in a vending, that match given ids, price and possible cards.
  372. * @param sd : The vender session to search into
  373. * @param s : parameter of the search (see s_search_store_search)
  374. * @return Whether or not the search should be continued.
  375. */
  376. bool vending_searchall(map_session_data* sd, const struct s_search_store_search* s)
  377. {
  378. int32 i, c, slot;
  379. uint32 idx, cidx;
  380. struct item* it;
  381. if( !sd->state.vending ) // not vending
  382. return true;
  383. for( idx = 0; idx < s->item_count; idx++ ) {
  384. ARR_FIND( 0, sd->vend_num, i, sd->cart.u.items_cart[sd->vending[i].index].nameid == s->itemlist[idx].itemId );
  385. if( i == sd->vend_num ) { // not found
  386. continue;
  387. }
  388. it = &sd->cart.u.items_cart[sd->vending[i].index];
  389. if( s->min_price && s->min_price > sd->vending[i].value ) { // too low price
  390. continue;
  391. }
  392. if( s->max_price && s->max_price < sd->vending[i].value ) { // too high price
  393. continue;
  394. }
  395. if( s->card_count ) { // check cards
  396. if( itemdb_isspecial(it->card[0]) ) { // something, that is not a carded
  397. continue;
  398. }
  399. slot = itemdb_slots(it->nameid);
  400. for( c = 0; c < slot && it->card[c]; c ++ ) {
  401. ARR_FIND( 0, s->card_count, cidx, s->cardlist[cidx].itemId == it->card[c] );
  402. if( cidx != s->card_count ) { // found
  403. break;
  404. }
  405. }
  406. if( c == slot || !it->card[c] ) { // no card match
  407. continue;
  408. }
  409. }
  410. // Check if the result set is full
  411. if( s->search_sd->searchstore.items.size() >= (uint32)battle_config.searchstore_maxresults ){
  412. return false;
  413. }
  414. std::shared_ptr<s_search_store_info_item> ssitem = std::make_shared<s_search_store_info_item>();
  415. ssitem->store_id = sd->vender_id;
  416. ssitem->account_id = sd->status.account_id;
  417. safestrncpy( ssitem->store_name, sd->message, sizeof( ssitem->store_name ) );
  418. ssitem->nameid = it->nameid;
  419. ssitem->amount = sd->vending[i].amount;
  420. ssitem->price = sd->vending[i].value;
  421. for( int32 j = 0; j < MAX_SLOTS; j++ ){
  422. ssitem->card[j] = it->card[j];
  423. }
  424. ssitem->refine = it->refine;
  425. ssitem->enchantgrade = it->enchantgrade;
  426. s->search_sd->searchstore.items.push_back( ssitem );
  427. }
  428. return true;
  429. }
  430. /**
  431. * Open vending for Autotrader
  432. * @param sd Player as autotrader
  433. */
  434. void vending_reopen( map_session_data& sd )
  435. {
  436. struct s_autotrader *at = nullptr;
  437. int8 fail = -1;
  438. // Open vending for this autotrader
  439. if ((at = (struct s_autotrader *)uidb_get(vending_autotrader_db, sd.status.char_id)) && at->count && at->entries) {
  440. uint8 *data, *p;
  441. uint16 j, count;
  442. // Init vending data for autotrader
  443. CREATE(data, uint8, at->count * 8);
  444. for (j = 0, p = data, count = at->count; j < at->count; j++) {
  445. struct s_autotrade_entry *entry = at->entries[j];
  446. uint16 *index = (uint16*)(p + 0);
  447. uint16 *amount = (uint16*)(p + 2);
  448. uint32 *value = (uint32*)(p + 4);
  449. // Find item position in cart
  450. ARR_FIND(0, MAX_CART, entry->index, sd.cart.u.items_cart[entry->index].id == entry->cartinventory_id);
  451. if (entry->index == MAX_CART) {
  452. count--;
  453. continue;
  454. }
  455. *index = entry->index + 2;
  456. *amount = itemdb_isstackable(sd.cart.u.items_cart[entry->index].nameid) ? entry->amount : 1;
  457. *value = entry->price;
  458. p += 8;
  459. }
  460. sd.state.prevend = 1; // Set him into a hacked prevend state
  461. sd.state.autotrade = 1;
  462. // Make sure abort all NPCs
  463. npc_event_dequeue(&sd);
  464. pc_cleareventtimer(&sd);
  465. // Open the vending again
  466. if( (fail = vending_openvending(sd, at->title, data, count, at)) == 0 ) {
  467. // Make vendor look perfect
  468. pc_setdir(&sd, at->dir, at->head_dir);
  469. clif_changed_dir(sd.bl, AREA_WOS);
  470. if( at->sit ) {
  471. pc_setsit(&sd);
  472. skill_sit(&sd, 1);
  473. clif_sitting(sd.bl);
  474. }
  475. // Immediate save
  476. chrif_save(&sd, CSAVE_AUTOTRADE);
  477. ShowInfo("Vending loaded for '" CL_WHITE "%s" CL_RESET "' with '" CL_WHITE "%d" CL_RESET "' items at " CL_WHITE "%s (%d,%d)" CL_RESET "\n",
  478. sd.status.name, count, mapindex_id2name(sd.mapindex), sd.bl.x, sd.bl.y);
  479. }
  480. aFree(data);
  481. }
  482. if (at) {
  483. vending_autotrader_remove(at, true);
  484. if (db_size(vending_autotrader_db) == 0)
  485. vending_autotrader_db->clear(vending_autotrader_db, vending_autotrader_free);
  486. }
  487. if (fail != 0) {
  488. ShowError("vending_reopen: (Error:%d) Load failed for autotrader '" CL_WHITE "%s" CL_RESET "' (CID=%d/AID=%d)\n", fail, sd.status.name, sd.status.char_id, sd.status.account_id);
  489. map_quit(&sd);
  490. }
  491. }
  492. /**
  493. * Initializing autotraders from table
  494. */
  495. void do_init_vending_autotrade(void)
  496. {
  497. if (battle_config.feature_autotrade) {
  498. if (Sql_Query(mmysql_handle,
  499. "SELECT `id`, `account_id`, `char_id`, `sex`, `title`, `body_direction`, `head_direction`, `sit` "
  500. "FROM `%s` "
  501. "WHERE `autotrade` = 1 AND (SELECT COUNT(`vending_id`) FROM `%s` WHERE `vending_id` = `id`) > 0 "
  502. "ORDER BY `id`;",
  503. vendings_table, vending_items_table ) != SQL_SUCCESS )
  504. {
  505. Sql_ShowDebug(mmysql_handle);
  506. return;
  507. }
  508. if( Sql_NumRows(mmysql_handle) > 0 ) {
  509. uint16 items = 0;
  510. DBIterator *iter = nullptr;
  511. struct s_autotrader *at = nullptr;
  512. // Init each autotrader data
  513. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle)) {
  514. size_t len;
  515. char* data;
  516. at = nullptr;
  517. CREATE(at, struct s_autotrader, 1);
  518. Sql_GetData(mmysql_handle, 0, &data, nullptr); at->id = atoi(data);
  519. Sql_GetData(mmysql_handle, 1, &data, nullptr); at->account_id = atoi(data);
  520. Sql_GetData(mmysql_handle, 2, &data, nullptr); at->char_id = atoi(data);
  521. Sql_GetData(mmysql_handle, 3, &data, nullptr); at->sex = (data[0] == 'F') ? SEX_FEMALE : SEX_MALE;
  522. Sql_GetData(mmysql_handle, 4, &data, &len); safestrncpy(at->title, data, zmin(len + 1, MESSAGE_SIZE));
  523. Sql_GetData(mmysql_handle, 5, &data, nullptr); at->dir = atoi(data);
  524. Sql_GetData(mmysql_handle, 6, &data, nullptr); at->head_dir = atoi(data);
  525. Sql_GetData(mmysql_handle, 7, &data, nullptr); at->sit = atoi(data);
  526. at->count = 0;
  527. if (battle_config.feature_autotrade_direction >= 0)
  528. at->dir = battle_config.feature_autotrade_direction;
  529. if (battle_config.feature_autotrade_head_direction >= 0)
  530. at->head_dir = battle_config.feature_autotrade_head_direction;
  531. if (battle_config.feature_autotrade_sit >= 0)
  532. at->sit = battle_config.feature_autotrade_sit;
  533. // initialize player
  534. CREATE(at->sd, map_session_data, 1); // TODO: Dont use Memory Manager allocation anymore and rely on the C++ container
  535. new (at->sd) map_session_data();
  536. pc_setnewpc(at->sd, at->account_id, at->char_id, 0, gettick(), at->sex, 0);
  537. at->sd->state.autotrade = 1|2;
  538. if (battle_config.autotrade_monsterignore)
  539. at->sd->state.block_action |= PCBLOCK_IMMUNE;
  540. else
  541. at->sd->state.block_action &= ~PCBLOCK_IMMUNE;
  542. chrif_authreq(at->sd, true);
  543. uidb_put(vending_autotrader_db, at->char_id, at);
  544. }
  545. Sql_FreeResult(mmysql_handle);
  546. // Init items for each autotraders
  547. iter = db_iterator(vending_autotrader_db);
  548. for (at = (struct s_autotrader *)dbi_first(iter); dbi_exists(iter); at = (struct s_autotrader *)dbi_next(iter)) {
  549. uint16 j = 0;
  550. if (SQL_ERROR == Sql_Query(mmysql_handle,
  551. "SELECT `cartinventory_id`, `amount`, `price` "
  552. "FROM `%s` "
  553. "WHERE `vending_id` = %d "
  554. "ORDER BY `index` ASC;",
  555. vending_items_table, at->id ) )
  556. {
  557. Sql_ShowDebug(mmysql_handle);
  558. continue;
  559. }
  560. if (!(at->count = (uint16)Sql_NumRows(mmysql_handle))) {
  561. map_quit(at->sd);
  562. vending_autotrader_remove(at, true);
  563. continue;
  564. }
  565. //Init the list
  566. CREATE(at->entries, struct s_autotrade_entry *, at->count);
  567. //Add the item into list
  568. j = 0;
  569. while (SQL_SUCCESS == Sql_NextRow(mmysql_handle) && j < at->count) {
  570. char *data;
  571. CREATE(at->entries[j], struct s_autotrade_entry, 1);
  572. Sql_GetData(mmysql_handle, 0, &data, nullptr); at->entries[j]->cartinventory_id = atoi(data);
  573. Sql_GetData(mmysql_handle, 1, &data, nullptr); at->entries[j]->amount = atoi(data);
  574. Sql_GetData(mmysql_handle, 2, &data, nullptr); at->entries[j]->price = atoi(data);
  575. j++;
  576. }
  577. items += j;
  578. Sql_FreeResult(mmysql_handle);
  579. }
  580. dbi_destroy(iter);
  581. ShowStatus("Done loading '" CL_WHITE "%d" CL_RESET "' vending autotraders with '" CL_WHITE "%d" CL_RESET "' items.\n", db_size(vending_autotrader_db), items);
  582. }
  583. }
  584. // Everything is loaded fine, their entries will be reinserted once they are loaded
  585. if (Sql_Query( mmysql_handle, "DELETE FROM `%s`;", vendings_table ) != SQL_SUCCESS ||
  586. Sql_Query( mmysql_handle, "DELETE FROM `%s`;", vending_items_table ) != SQL_SUCCESS) {
  587. Sql_ShowDebug(mmysql_handle);
  588. }
  589. }
  590. /**
  591. * Remove an autotrader's data
  592. * @param at Autotrader
  593. * @param remove If true will removes from vending_autotrader_db
  594. **/
  595. static void vending_autotrader_remove(struct s_autotrader *at, bool remove) {
  596. nullpo_retv(at);
  597. if (at->count && at->entries) {
  598. uint16 i = 0;
  599. for (i = 0; i < at->count; i++) {
  600. if (at->entries[i])
  601. aFree(at->entries[i]);
  602. }
  603. aFree(at->entries);
  604. }
  605. if (remove)
  606. uidb_remove(vending_autotrader_db, at->char_id);
  607. aFree(at);
  608. }
  609. /**
  610. * Clear all autotraders
  611. * @author [Cydh]
  612. */
  613. static int32 vending_autotrader_free(DBKey key, DBData *data, va_list ap) {
  614. struct s_autotrader *at = (struct s_autotrader *)db_data2ptr(data);
  615. if (at)
  616. vending_autotrader_remove(at, false);
  617. return 0;
  618. }
  619. /**
  620. * Update vendor location
  621. * @param sd: Player's session data
  622. */
  623. void vending_update(map_session_data &sd)
  624. {
  625. if (Sql_Query(mmysql_handle, "UPDATE `%s` SET `map` = '%s', `x` = '%d', `y` = '%d', `body_direction` = '%d', `head_direction` = '%d', `sit` = '%d', `autotrade` = '%d' WHERE `id` = '%d'",
  626. vendings_table, map_getmapdata(sd.bl.m)->name, sd.bl.x, sd.bl.y, sd.ud.dir, sd.head_dir, pc_issit(&sd), sd.state.autotrade,
  627. sd.vender_id
  628. ) != SQL_SUCCESS) {
  629. Sql_ShowDebug(mmysql_handle);
  630. }
  631. }
  632. /**
  633. * Initialise the vending module
  634. * called in map::do_init
  635. */
  636. void do_final_vending(void)
  637. {
  638. db_destroy(vending_db);
  639. vending_autotrader_db->destroy(vending_autotrader_db, vending_autotrader_free);
  640. }
  641. /**
  642. * Destory the vending module
  643. * called in map::do_final
  644. */
  645. void do_init_vending(void)
  646. {
  647. vending_db = idb_alloc(DB_OPT_BASE);
  648. vending_autotrader_db = uidb_alloc(DB_OPT_BASE);
  649. vending_nextid = 0;
  650. }