map.c 135 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806
  1. // Copyright (c) Athena Dev Teams - Licensed under GNU GPL
  2. // For more information, see LICENCE in the main folder
  3. #include "../common/cbasetypes.h"
  4. #include "../common/core.h"
  5. #include "../common/timer.h"
  6. #include "../common/grfio.h"
  7. #include "../common/malloc.h"
  8. #include "../common/socket.h" // WFIFO*()
  9. #include "../common/showmsg.h"
  10. #include "../common/nullpo.h"
  11. #include "../common/random.h"
  12. #include "../common/strlib.h"
  13. #include "../common/utils.h"
  14. #include "../common/cli.h"
  15. #include "../common/ers.h"
  16. #include "map.h"
  17. #include "path.h"
  18. #include "chrif.h"
  19. #include "clan.h"
  20. #include "clif.h"
  21. #include "duel.h"
  22. #include "intif.h"
  23. #include "npc.h"
  24. #include "pc.h"
  25. #include "chat.h"
  26. #include "storage.h"
  27. #include "trade.h"
  28. #include "party.h"
  29. #include "battleground.h"
  30. #include "quest.h"
  31. #include "mapreg.h"
  32. #include "pet.h"
  33. #include "homunculus.h"
  34. #include "instance.h"
  35. #include "mercenary.h"
  36. #include "elemental.h"
  37. #include "cashshop.h"
  38. #include "channel.h"
  39. #include <stdlib.h>
  40. #include <math.h>
  41. #ifndef _WIN32
  42. #endif
  43. char default_codepage[32] = "";
  44. int map_server_port = 3306;
  45. char map_server_ip[32] = "127.0.0.1";
  46. char map_server_id[32] = "ragnarok";
  47. char map_server_pw[32] = "";
  48. char map_server_db[32] = "ragnarok";
  49. Sql* mmysql_handle;
  50. Sql* qsmysql_handle; /// For query_sql
  51. int db_use_sqldbs = 0;
  52. char buyingstores_table[32] = "buyingstores";
  53. char buyingstore_items_table[32] = "buyingstore_items";
  54. char item_cash_table[32] = "item_cash_db";
  55. char item_cash2_table[32] = "item_cash_db2";
  56. #ifdef RENEWAL
  57. char item_table[32] = "item_db_re";
  58. char item2_table[32] = "item_db2_re";
  59. char mob_table[32] = "mob_db_re";
  60. char mob2_table[32] = "mob_db2_re";
  61. char mob_skill_table[32] = "mob_skill_db_re";
  62. char mob_skill2_table[32] = "mob_skill_db2_re";
  63. #else
  64. char item_table[32] = "item_db";
  65. char item2_table[32] = "item_db2";
  66. char mob_table[32] = "mob_db";
  67. char mob2_table[32] = "mob_db2";
  68. char mob_skill_table[32] = "mob_skill_db";
  69. char mob_skill2_table[32] = "mob_skill_db2";
  70. #endif
  71. char sales_table[32] = "sales";
  72. char vendings_table[32] = "vendings";
  73. char vending_items_table[32] = "vending_items";
  74. char market_table[32] = "market";
  75. char roulette_table[32] = "db_roulette";
  76. // log database
  77. char log_db_ip[32] = "127.0.0.1";
  78. int log_db_port = 3306;
  79. char log_db_id[32] = "ragnarok";
  80. char log_db_pw[32] = "ragnarok";
  81. char log_db_db[32] = "log";
  82. Sql* logmysql_handle;
  83. // DBMap declaration
  84. static DBMap* id_db=NULL; /// int id -> struct block_list*
  85. static DBMap* pc_db=NULL; /// int id -> struct map_session_data*
  86. static DBMap* mobid_db=NULL; /// int id -> struct mob_data*
  87. static DBMap* bossid_db=NULL; /// int id -> struct mob_data* (MVP db)
  88. static DBMap* map_db=NULL; /// unsigned int mapindex -> struct map_data*
  89. static DBMap* nick_db=NULL; /// uint32 char_id -> struct charid2nick* (requested names of offline characters)
  90. static DBMap* charid_db=NULL; /// uint32 char_id -> struct map_session_data*
  91. static DBMap* regen_db=NULL; /// int id -> struct block_list* (status_natural_heal processing)
  92. static DBMap* map_msg_db=NULL;
  93. static int map_users=0;
  94. #define BLOCK_SIZE 8
  95. #define block_free_max 1048576
  96. struct block_list *block_free[block_free_max];
  97. static int block_free_count = 0, block_free_lock = 0;
  98. #define BL_LIST_MAX 1048576
  99. static struct block_list *bl_list[BL_LIST_MAX];
  100. static int bl_list_count = 0;
  101. #define MAP_MAX_MSG 1550
  102. struct map_data map[MAX_MAP_PER_SERVER];
  103. int map_num = 0;
  104. int map_port=0;
  105. int autosave_interval = DEFAULT_AUTOSAVE_INTERVAL;
  106. int minsave_interval = 100;
  107. unsigned char save_settings = CHARSAVE_ALL;
  108. bool agit_flag = false;
  109. bool agit2_flag = false;
  110. bool agit3_flag = false;
  111. int night_flag = 0; // 0=day, 1=night [Yor]
  112. #ifdef ADJUST_SKILL_DAMAGE
  113. struct eri *map_skill_damage_ers = NULL;
  114. #endif
  115. struct charid_request {
  116. struct charid_request* next;
  117. int charid;// who want to be notified of the nick
  118. };
  119. struct charid2nick {
  120. char nick[NAME_LENGTH];
  121. struct charid_request* requests;// requests of notification on this nick
  122. };
  123. // This is the main header found at the very beginning of the map cache
  124. struct map_cache_main_header {
  125. uint32 file_size;
  126. uint16 map_count;
  127. };
  128. // This is the header appended before every compressed map cells info in the map cache
  129. struct map_cache_map_info {
  130. char name[MAP_NAME_LENGTH];
  131. int16 xs;
  132. int16 ys;
  133. int32 len;
  134. };
  135. char motd_txt[256] = "conf/motd.txt";
  136. char help_txt[256] = "conf/help.txt";
  137. char help2_txt[256] = "conf/help2.txt";
  138. char charhelp_txt[256] = "conf/charhelp.txt";
  139. char wisp_server_name[NAME_LENGTH] = "Server"; // can be modified in char-server configuration file
  140. struct s_map_default map_default;
  141. int console = 0;
  142. int enable_spy = 0; //To enable/disable @spy commands, which consume too much cpu time when sending packets. [Skotlex]
  143. int enable_grf = 0; //To enable/disable reading maps from GRF files, bypassing mapcache [blackhole89]
  144. /*==========================================
  145. * server player count (of all mapservers)
  146. *------------------------------------------*/
  147. void map_setusers(int users)
  148. {
  149. map_users = users;
  150. }
  151. int map_getusers(void)
  152. {
  153. return map_users;
  154. }
  155. /*==========================================
  156. * server player count (this mapserver only)
  157. *------------------------------------------*/
  158. int map_usercount(void)
  159. {
  160. return pc_db->size(pc_db);
  161. }
  162. /*==========================================
  163. * Attempt to free a map blocklist
  164. *------------------------------------------*/
  165. int map_freeblock (struct block_list *bl)
  166. {
  167. nullpo_retr(block_free_lock, bl);
  168. if (block_free_lock == 0 || block_free_count >= block_free_max)
  169. {
  170. aFree(bl);
  171. bl = NULL;
  172. if (block_free_count >= block_free_max)
  173. ShowWarning("map_freeblock: too many free block! %d %d\n", block_free_count, block_free_lock);
  174. } else
  175. block_free[block_free_count++] = bl;
  176. return block_free_lock;
  177. }
  178. /*==========================================
  179. * Lock blocklist, (prevent map_freeblock usage)
  180. *------------------------------------------*/
  181. int map_freeblock_lock (void)
  182. {
  183. return ++block_free_lock;
  184. }
  185. /*==========================================
  186. * Remove the lock on map_bl
  187. *------------------------------------------*/
  188. int map_freeblock_unlock (void)
  189. {
  190. if ((--block_free_lock) == 0) {
  191. int i;
  192. for (i = 0; i < block_free_count; i++)
  193. {
  194. aFree(block_free[i]);
  195. block_free[i] = NULL;
  196. }
  197. block_free_count = 0;
  198. } else if (block_free_lock < 0) {
  199. ShowError("map_freeblock_unlock: lock count < 0 !\n");
  200. block_free_lock = 0;
  201. }
  202. return block_free_lock;
  203. }
  204. // Timer function to check if there some remaining lock and remove them if so.
  205. // Called each 1s
  206. int map_freeblock_timer(int tid, unsigned int tick, int id, intptr_t data)
  207. {
  208. if (block_free_lock > 0) {
  209. ShowError("map_freeblock_timer: block_free_lock(%d) is invalid.\n", block_free_lock);
  210. block_free_lock = 1;
  211. map_freeblock_unlock();
  212. }
  213. return 0;
  214. }
  215. //
  216. // blocklist
  217. //
  218. /*==========================================
  219. * Handling of map_bl[]
  220. * The address of bl_heal is set in bl->prev
  221. *------------------------------------------*/
  222. static struct block_list bl_head;
  223. #ifdef CELL_NOSTACK
  224. /*==========================================
  225. * These pair of functions update the counter of how many objects
  226. * lie on a tile.
  227. *------------------------------------------*/
  228. static void map_addblcell(struct block_list *bl)
  229. {
  230. if( bl->m<0 || bl->x<0 || bl->x>=map[bl->m].xs || bl->y<0 || bl->y>=map[bl->m].ys || !(bl->type&BL_CHAR) )
  231. return;
  232. map[bl->m].cell[bl->x+bl->y*map[bl->m].xs].cell_bl++;
  233. return;
  234. }
  235. static void map_delblcell(struct block_list *bl)
  236. {
  237. if( bl->m <0 || bl->x<0 || bl->x>=map[bl->m].xs || bl->y<0 || bl->y>=map[bl->m].ys || !(bl->type&BL_CHAR) )
  238. return;
  239. map[bl->m].cell[bl->x+bl->y*map[bl->m].xs].cell_bl--;
  240. }
  241. #endif
  242. /*==========================================
  243. * Adds a block to the map.
  244. * Returns 0 on success, 1 on failure (illegal coordinates).
  245. *------------------------------------------*/
  246. int map_addblock(struct block_list* bl)
  247. {
  248. int16 m, x, y;
  249. int pos;
  250. nullpo_ret(bl);
  251. if (bl->prev != NULL) {
  252. ShowError("map_addblock: bl->prev != NULL\n");
  253. return 1;
  254. }
  255. m = bl->m;
  256. x = bl->x;
  257. y = bl->y;
  258. if( m < 0 || m >= map_num )
  259. {
  260. ShowError("map_addblock: invalid map id (%d), only %d are loaded.\n", m, map_num);
  261. return 1;
  262. }
  263. if( x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys )
  264. {
  265. ShowError("map_addblock: out-of-bounds coordinates (\"%s\",%d,%d), map is %dx%d\n", map[m].name, x, y, map[m].xs, map[m].ys);
  266. return 1;
  267. }
  268. pos = x/BLOCK_SIZE+(y/BLOCK_SIZE)*map[m].bxs;
  269. if (bl->type == BL_MOB) {
  270. bl->next = map[m].block_mob[pos];
  271. bl->prev = &bl_head;
  272. if (bl->next) bl->next->prev = bl;
  273. map[m].block_mob[pos] = bl;
  274. } else {
  275. bl->next = map[m].block[pos];
  276. bl->prev = &bl_head;
  277. if (bl->next) bl->next->prev = bl;
  278. map[m].block[pos] = bl;
  279. }
  280. #ifdef CELL_NOSTACK
  281. map_addblcell(bl);
  282. #endif
  283. return 0;
  284. }
  285. /*==========================================
  286. * Removes a block from the map.
  287. *------------------------------------------*/
  288. int map_delblock(struct block_list* bl)
  289. {
  290. int pos;
  291. nullpo_ret(bl);
  292. // blocklist (2ways chainlist)
  293. if (bl->prev == NULL) {
  294. if (bl->next != NULL) {
  295. // can't delete block (already at the beginning of the chain)
  296. ShowError("map_delblock error : bl->next!=NULL\n");
  297. }
  298. return 0;
  299. }
  300. #ifdef CELL_NOSTACK
  301. map_delblcell(bl);
  302. #endif
  303. pos = bl->x/BLOCK_SIZE+(bl->y/BLOCK_SIZE)*map[bl->m].bxs;
  304. if (bl->next)
  305. bl->next->prev = bl->prev;
  306. if (bl->prev == &bl_head) {
  307. //Since the head of the list, update the block_list map of []
  308. if (bl->type == BL_MOB) {
  309. map[bl->m].block_mob[pos] = bl->next;
  310. } else {
  311. map[bl->m].block[pos] = bl->next;
  312. }
  313. } else {
  314. bl->prev->next = bl->next;
  315. }
  316. bl->next = NULL;
  317. bl->prev = NULL;
  318. return 0;
  319. }
  320. /**
  321. * Moves a block a x/y target position. [Skotlex]
  322. * Pass flag as 1 to prevent doing skill_unit_move checks
  323. * (which are executed by default on BL_CHAR types)
  324. * @param bl : block(object) to move
  325. * @param x1 : new x position
  326. * @param y1 : new y position
  327. * @param tick : when this was scheduled
  328. * @return 0:success, 1:fail
  329. */
  330. int map_moveblock(struct block_list *bl, int x1, int y1, unsigned int tick)
  331. {
  332. int x0 = bl->x, y0 = bl->y;
  333. struct status_change *sc = NULL;
  334. int moveblock = ( x0/BLOCK_SIZE != x1/BLOCK_SIZE || y0/BLOCK_SIZE != y1/BLOCK_SIZE);
  335. if (!bl->prev) {
  336. //Block not in map, just update coordinates, but do naught else.
  337. bl->x = x1;
  338. bl->y = y1;
  339. return 0;
  340. }
  341. //TODO: Perhaps some outs of bounds checking should be placed here?
  342. if (bl->type&BL_CHAR) {
  343. sc = status_get_sc(bl);
  344. skill_unit_move(bl,tick,2);
  345. status_change_end(bl, SC_CLOSECONFINE, INVALID_TIMER);
  346. status_change_end(bl, SC_CLOSECONFINE2, INVALID_TIMER);
  347. status_change_end(bl, SC_TINDER_BREAKER, INVALID_TIMER);
  348. status_change_end(bl, SC_TINDER_BREAKER2, INVALID_TIMER);
  349. // status_change_end(bl, SC_BLADESTOP, INVALID_TIMER); //Won't stop when you are knocked away, go figure...
  350. status_change_end(bl, SC_TATAMIGAESHI, INVALID_TIMER);
  351. status_change_end(bl, SC_MAGICROD, INVALID_TIMER);
  352. status_change_end(bl, SC_SU_STOOP, INVALID_TIMER);
  353. if (sc->data[SC_PROPERTYWALK] &&
  354. sc->data[SC_PROPERTYWALK]->val3 >= skill_get_maxcount(sc->data[SC_PROPERTYWALK]->val1,sc->data[SC_PROPERTYWALK]->val2) )
  355. status_change_end(bl,SC_PROPERTYWALK,INVALID_TIMER);
  356. } else
  357. if (bl->type == BL_NPC)
  358. npc_unsetcells((TBL_NPC*)bl);
  359. if (moveblock) map_delblock(bl);
  360. #ifdef CELL_NOSTACK
  361. else map_delblcell(bl);
  362. #endif
  363. bl->x = x1;
  364. bl->y = y1;
  365. if (moveblock) {
  366. if(map_addblock(bl))
  367. return 1;
  368. }
  369. #ifdef CELL_NOSTACK
  370. else map_addblcell(bl);
  371. #endif
  372. if (bl->type&BL_CHAR) {
  373. skill_unit_move(bl,tick,3);
  374. if( bl->type == BL_PC && ((TBL_PC*)bl)->shadowform_id ) {//Shadow Form Target Moving
  375. struct block_list *d_bl;
  376. if( (d_bl = map_id2bl(((TBL_PC*)bl)->shadowform_id)) == NULL || !check_distance_bl(bl,d_bl,10) ) {
  377. if( d_bl )
  378. status_change_end(d_bl,SC__SHADOWFORM,INVALID_TIMER);
  379. ((TBL_PC*)bl)->shadowform_id = 0;
  380. }
  381. }
  382. if (sc && sc->count) {
  383. if (sc->data[SC_DANCING])
  384. skill_unit_move_unit_group(skill_id2group(sc->data[SC_DANCING]->val2), bl->m, x1-x0, y1-y0);
  385. else {
  386. if (sc->data[SC_CLOAKING] && sc->data[SC_CLOAKING]->val1 < 3 && !skill_check_cloaking(bl, NULL))
  387. status_change_end(bl, SC_CLOAKING, INVALID_TIMER);
  388. if (sc->data[SC_WARM])
  389. skill_unit_move_unit_group(skill_id2group(sc->data[SC_WARM]->val4), bl->m, x1-x0, y1-y0);
  390. if (sc->data[SC_BANDING])
  391. skill_unit_move_unit_group(skill_id2group(sc->data[SC_BANDING]->val4), bl->m, x1-x0, y1-y0);
  392. if (sc->data[SC_NEUTRALBARRIER_MASTER])
  393. skill_unit_move_unit_group(skill_id2group(sc->data[SC_NEUTRALBARRIER_MASTER]->val2), bl->m, x1-x0, y1-y0);
  394. else if (sc->data[SC_STEALTHFIELD_MASTER])
  395. skill_unit_move_unit_group(skill_id2group(sc->data[SC_STEALTHFIELD_MASTER]->val2), bl->m, x1-x0, y1-y0);
  396. if( sc->data[SC__SHADOWFORM] ) {//Shadow Form Caster Moving
  397. struct block_list *d_bl;
  398. if( (d_bl = map_id2bl(sc->data[SC__SHADOWFORM]->val2)) == NULL || !check_distance_bl(bl,d_bl,10) )
  399. status_change_end(bl,SC__SHADOWFORM,INVALID_TIMER);
  400. }
  401. if (sc->data[SC_PROPERTYWALK]
  402. && sc->data[SC_PROPERTYWALK]->val3 < skill_get_maxcount(sc->data[SC_PROPERTYWALK]->val1,sc->data[SC_PROPERTYWALK]->val2)
  403. && map_find_skill_unit_oncell(bl,bl->x,bl->y,SO_ELECTRICWALK,NULL,0) == NULL
  404. && map_find_skill_unit_oncell(bl,bl->x,bl->y,SO_FIREWALK,NULL,0) == NULL
  405. && skill_unitsetting(bl,sc->data[SC_PROPERTYWALK]->val1,sc->data[SC_PROPERTYWALK]->val2,x0, y0,0)) {
  406. sc->data[SC_PROPERTYWALK]->val3++;
  407. }
  408. }
  409. /* Guild Aura Moving */
  410. if( bl->type == BL_PC && ((TBL_PC*)bl)->state.gmaster_flag ) {
  411. if (sc->data[SC_LEADERSHIP])
  412. skill_unit_move_unit_group(skill_id2group(sc->data[SC_LEADERSHIP]->val4), bl->m, x1-x0, y1-y0);
  413. if (sc->data[SC_GLORYWOUNDS])
  414. skill_unit_move_unit_group(skill_id2group(sc->data[SC_GLORYWOUNDS]->val4), bl->m, x1-x0, y1-y0);
  415. if (sc->data[SC_SOULCOLD])
  416. skill_unit_move_unit_group(skill_id2group(sc->data[SC_SOULCOLD]->val4), bl->m, x1-x0, y1-y0);
  417. if (sc->data[SC_HAWKEYES])
  418. skill_unit_move_unit_group(skill_id2group(sc->data[SC_HAWKEYES]->val4), bl->m, x1-x0, y1-y0);
  419. }
  420. }
  421. } else
  422. if (bl->type == BL_NPC)
  423. npc_setcells((TBL_NPC*)bl);
  424. return 0;
  425. }
  426. /*==========================================
  427. * Counts specified number of objects on given cell.
  428. * flag:
  429. * 0x1 - only count standing units
  430. *------------------------------------------*/
  431. int map_count_oncell(int16 m, int16 x, int16 y, int type, int flag)
  432. {
  433. int bx,by;
  434. struct block_list *bl;
  435. int count = 0;
  436. if (x < 0 || y < 0 || (x >= map[m].xs) || (y >= map[m].ys))
  437. return 0;
  438. bx = x/BLOCK_SIZE;
  439. by = y/BLOCK_SIZE;
  440. if (type&~BL_MOB)
  441. for( bl = map[m].block[bx+by*map[m].bxs] ; bl != NULL ; bl = bl->next )
  442. if(bl->x == x && bl->y == y && bl->type&type) {
  443. if(flag&1) {
  444. struct unit_data *ud = unit_bl2ud(bl);
  445. if(!ud || ud->walktimer == INVALID_TIMER)
  446. count++;
  447. } else {
  448. count++;
  449. }
  450. }
  451. if (type&BL_MOB)
  452. for( bl = map[m].block_mob[bx+by*map[m].bxs] ; bl != NULL ; bl = bl->next )
  453. if(bl->x == x && bl->y == y) {
  454. if(flag&1) {
  455. struct unit_data *ud = unit_bl2ud(bl);
  456. if(!ud || ud->walktimer == INVALID_TIMER)
  457. count++;
  458. } else {
  459. count++;
  460. }
  461. }
  462. return count;
  463. }
  464. /*
  465. * Looks for a skill unit on a given cell
  466. * flag&1: runs battle_check_target check based on unit->group->target_flag
  467. */
  468. struct skill_unit* map_find_skill_unit_oncell(struct block_list* target,int16 x,int16 y,uint16 skill_id,struct skill_unit* out_unit, int flag) {
  469. int16 m,bx,by;
  470. struct block_list *bl;
  471. struct skill_unit *unit;
  472. m = target->m;
  473. if (x < 0 || y < 0 || (x >= map[m].xs) || (y >= map[m].ys))
  474. return NULL;
  475. bx = x/BLOCK_SIZE;
  476. by = y/BLOCK_SIZE;
  477. for( bl = map[m].block[bx+by*map[m].bxs] ; bl != NULL ; bl = bl->next )
  478. {
  479. if (bl->x != x || bl->y != y || bl->type != BL_SKILL)
  480. continue;
  481. unit = (struct skill_unit *) bl;
  482. if( unit == out_unit || !unit->alive || !unit->group || unit->group->skill_id != skill_id )
  483. continue;
  484. if( !(flag&1) || battle_check_target(&unit->bl,target,unit->group->target_flag) > 0 )
  485. return unit;
  486. }
  487. return NULL;
  488. }
  489. /*==========================================
  490. * Adapted from foreachinarea for an easier invocation. [Skotlex]
  491. *------------------------------------------*/
  492. int map_foreachinrange(int (*func)(struct block_list*,va_list), struct block_list* center, int16 range, int type, ...)
  493. {
  494. int bx, by, m;
  495. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  496. struct block_list *bl;
  497. int blockcount = bl_list_count, i;
  498. int x0, x1, y0, y1;
  499. va_list ap;
  500. m = center->m;
  501. x0 = i16max(center->x - range, 0);
  502. y0 = i16max(center->y - range, 0);
  503. x1 = i16min(center->x + range, map[ m ].xs - 1);
  504. y1 = i16min(center->y + range, map[ m ].ys - 1);
  505. if ( type&~BL_MOB )
  506. for ( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  507. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  508. for( bl = map[m].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  509. if( bl->type&type
  510. && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  511. #ifdef CIRCULAR_AREA
  512. && check_distance_bl(center, bl, range)
  513. #endif
  514. && bl_list_count < BL_LIST_MAX )
  515. bl_list[ bl_list_count++ ] = bl;
  516. }
  517. }
  518. }
  519. if( type&BL_MOB )
  520. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  521. for(bx=x0/BLOCK_SIZE;bx<=x1/BLOCK_SIZE;bx++) {
  522. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  523. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  524. #ifdef CIRCULAR_AREA
  525. && check_distance_bl(center, bl, range)
  526. #endif
  527. && bl_list_count < BL_LIST_MAX )
  528. bl_list[ bl_list_count++ ] = bl;
  529. }
  530. }
  531. }
  532. if( bl_list_count >= BL_LIST_MAX )
  533. ShowWarning("map_foreachinrange: block count too many!\n");
  534. map_freeblock_lock();
  535. for( i = blockcount; i < bl_list_count; i++ )
  536. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  537. va_start(ap, type);
  538. returnCount += func(bl_list[ i ], ap);
  539. va_end(ap);
  540. }
  541. map_freeblock_unlock();
  542. bl_list_count = blockcount;
  543. return returnCount; //[Skotlex]
  544. }
  545. /*==========================================
  546. * Same as foreachinrange, but there must be a shoot-able range between center and target to be counted in. [Skotlex]
  547. *------------------------------------------*/
  548. int map_foreachinshootrange(int (*func)(struct block_list*,va_list),struct block_list* center, int16 range, int type,...)
  549. {
  550. int bx, by, m;
  551. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  552. struct block_list *bl;
  553. int blockcount = bl_list_count, i;
  554. int x0, x1, y0, y1;
  555. va_list ap;
  556. m = center->m;
  557. if ( m < 0 )
  558. return 0;
  559. x0 = i16max(center->x-range, 0);
  560. y0 = i16max(center->y-range, 0);
  561. x1 = i16min(center->x+range, map[m].xs-1);
  562. y1 = i16min(center->y+range, map[m].ys-1);
  563. if ( type&~BL_MOB )
  564. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  565. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  566. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  567. if( bl->type&type
  568. && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  569. #ifdef CIRCULAR_AREA
  570. && check_distance_bl(center, bl, range)
  571. #endif
  572. && path_search_long(NULL, center->m, center->x, center->y, bl->x, bl->y, CELL_CHKWALL)
  573. && bl_list_count < BL_LIST_MAX )
  574. bl_list[ bl_list_count++ ] = bl;
  575. }
  576. }
  577. }
  578. if( type&BL_MOB )
  579. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  580. for( bx=x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  581. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  582. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  583. #ifdef CIRCULAR_AREA
  584. && check_distance_bl(center, bl, range)
  585. #endif
  586. && path_search_long(NULL, center->m, center->x, center->y, bl->x, bl->y, CELL_CHKWALL)
  587. && bl_list_count < BL_LIST_MAX )
  588. bl_list[ bl_list_count++ ] = bl;
  589. }
  590. }
  591. }
  592. if( bl_list_count >= BL_LIST_MAX )
  593. ShowWarning("map_foreachinrange: block count too many!\n");
  594. map_freeblock_lock();
  595. for( i = blockcount; i < bl_list_count; i++ )
  596. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  597. va_start(ap, type);
  598. returnCount += func(bl_list[ i ], ap);
  599. va_end(ap);
  600. }
  601. map_freeblock_unlock();
  602. bl_list_count = blockcount;
  603. return returnCount; //[Skotlex]
  604. }
  605. /*==========================================
  606. * range = map m (x0,y0)-(x1,y1)
  607. * Apply *func with ... arguments for the range.
  608. * @type = BL_PC/BL_MOB etc..
  609. *------------------------------------------*/
  610. int map_foreachinarea(int (*func)(struct block_list*,va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int type, ...)
  611. {
  612. int bx, by;
  613. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  614. struct block_list *bl;
  615. int blockcount = bl_list_count, i;
  616. va_list ap;
  617. if ( m < 0 || m >= map_num)
  618. return 0;
  619. if ( x1 < x0 )
  620. swap(x0, x1);
  621. if ( y1 < y0 )
  622. swap(y0, y1);
  623. x0 = i16max(x0, 0);
  624. y0 = i16max(y0, 0);
  625. x1 = i16min(x1, map[ m ].xs - 1);
  626. y1 = i16min(y1, map[ m ].ys - 1);
  627. if ( type&~BL_MOB )
  628. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ )
  629. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ )
  630. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  631. if( bl->type&type && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1 && bl_list_count < BL_LIST_MAX )
  632. bl_list[ bl_list_count++ ] = bl;
  633. if( type&BL_MOB )
  634. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ )
  635. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ )
  636. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  637. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1 && bl_list_count < BL_LIST_MAX )
  638. bl_list[ bl_list_count++ ] = bl;
  639. if( bl_list_count >= BL_LIST_MAX )
  640. ShowWarning("map_foreachinarea: block count too many!\n");
  641. map_freeblock_lock();
  642. for( i = blockcount; i < bl_list_count; i++ )
  643. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  644. va_start(ap, type);
  645. returnCount += func(bl_list[ i ], ap);
  646. va_end(ap);
  647. }
  648. map_freeblock_unlock();
  649. bl_list_count = blockcount;
  650. return returnCount; //[Skotlex]
  651. }
  652. /*========================================== [Playtester]
  653. * Same as foreachinarea, but there must be a shoot-able range between area center and target.
  654. * @param m: ID of map
  655. * @param x0: West end of area
  656. * @param y0: South end of area
  657. * @param x1: East end of area
  658. * @param y1: North end of area
  659. * @param type: Type of bl to search for
  660. *------------------------------------------*/
  661. int map_foreachinshootarea(int(*func)(struct block_list*, va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int type, ...)
  662. {
  663. int bx, by, cx, cy;
  664. int returnCount = 0; //total sum of returned values of func()
  665. struct block_list *bl;
  666. int blockcount = bl_list_count, i;
  667. va_list ap;
  668. if (m < 0 || m >= map_num)
  669. return 0;
  670. if (x1 < x0)
  671. swap(x0, x1);
  672. if (y1 < y0)
  673. swap(y0, y1);
  674. x0 = i16max(x0, 0);
  675. y0 = i16max(y0, 0);
  676. x1 = i16min(x1, map[m].xs - 1);
  677. y1 = i16min(y1, map[m].ys - 1);
  678. cx = x0 + (x1 - x0) / 2;
  679. cy = y0 + (y1 - y0) / 2;
  680. if (type&~BL_MOB)
  681. for (by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++)
  682. for (bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++)
  683. for (bl = map[m].block[bx + by * map[m].bxs]; bl != NULL; bl = bl->next)
  684. if (bl->type&type && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  685. && path_search_long(NULL, m, cx, cy, bl->x, bl->y, CELL_CHKWALL)
  686. && bl_list_count < BL_LIST_MAX)
  687. bl_list[bl_list_count++] = bl;
  688. if (type&BL_MOB)
  689. for (by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++)
  690. for (bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++)
  691. for (bl = map[m].block_mob[bx + by * map[m].bxs]; bl != NULL; bl = bl->next)
  692. if (bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  693. && path_search_long(NULL, m, cx, cy, bl->x, bl->y, CELL_CHKWALL)
  694. && bl_list_count < BL_LIST_MAX)
  695. bl_list[bl_list_count++] = bl;
  696. if (bl_list_count >= BL_LIST_MAX)
  697. ShowWarning("map_foreachinshootarea: block count too many!\n");
  698. map_freeblock_lock();
  699. for (i = blockcount; i < bl_list_count; i++)
  700. if (bl_list[i]->prev) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  701. va_start(ap, type);
  702. returnCount += func(bl_list[i], ap);
  703. va_end(ap);
  704. }
  705. map_freeblock_unlock();
  706. bl_list_count = blockcount;
  707. return returnCount;
  708. }
  709. /*==========================================
  710. * Adapted from forcountinarea for an easier invocation. [pakpil]
  711. *------------------------------------------*/
  712. int map_forcountinrange(int (*func)(struct block_list*,va_list), struct block_list* center, int16 range, int count, int type, ...)
  713. {
  714. int bx, by, m;
  715. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  716. struct block_list *bl;
  717. int blockcount = bl_list_count, i;
  718. int x0, x1, y0, y1;
  719. va_list ap;
  720. m = center->m;
  721. x0 = i16max(center->x - range, 0);
  722. y0 = i16max(center->y - range, 0);
  723. x1 = i16min(center->x + range, map[ m ].xs - 1);
  724. y1 = i16min(center->y + range, map[ m ].ys - 1);
  725. if ( type&~BL_MOB )
  726. for ( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  727. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  728. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  729. if( bl->type&type
  730. && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  731. #ifdef CIRCULAR_AREA
  732. && check_distance_bl(center, bl, range)
  733. #endif
  734. && bl_list_count < BL_LIST_MAX )
  735. bl_list[ bl_list_count++ ] = bl;
  736. }
  737. }
  738. }
  739. if( type&BL_MOB )
  740. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  741. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ){
  742. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  743. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1
  744. #ifdef CIRCULAR_AREA
  745. && check_distance_bl(center, bl, range)
  746. #endif
  747. && bl_list_count < BL_LIST_MAX )
  748. bl_list[ bl_list_count++ ] = bl;
  749. }
  750. }
  751. }
  752. if( bl_list_count >= BL_LIST_MAX )
  753. ShowWarning("map_forcountinrange: block count too many!\n");
  754. map_freeblock_lock();
  755. for( i = blockcount; i < bl_list_count; i++ )
  756. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  757. va_start(ap, type);
  758. returnCount += func(bl_list[ i ], ap);
  759. va_end(ap);
  760. if( count && returnCount >= count )
  761. break;
  762. }
  763. map_freeblock_unlock();
  764. bl_list_count = blockcount;
  765. return returnCount; //[Skotlex]
  766. }
  767. int map_forcountinarea(int (*func)(struct block_list*,va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int count, int type, ...)
  768. {
  769. int bx, by;
  770. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  771. struct block_list *bl;
  772. int blockcount = bl_list_count, i;
  773. va_list ap;
  774. if ( m < 0 )
  775. return 0;
  776. if ( x1 < x0 )
  777. swap(x0, x1);
  778. if ( y1 < y0 )
  779. swap(y0, y1);
  780. x0 = i16max(x0, 0);
  781. y0 = i16max(y0, 0);
  782. x1 = i16min(x1, map[ m ].xs - 1);
  783. y1 = i16min(y1, map[ m ].ys - 1);
  784. if ( type&~BL_MOB )
  785. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ )
  786. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ )
  787. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  788. if( bl->type&type && bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1 && bl_list_count < BL_LIST_MAX )
  789. bl_list[ bl_list_count++ ] = bl;
  790. if( type&BL_MOB )
  791. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ )
  792. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ )
  793. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  794. if( bl->x >= x0 && bl->x <= x1 && bl->y >= y0 && bl->y <= y1 && bl_list_count < BL_LIST_MAX )
  795. bl_list[ bl_list_count++ ] = bl;
  796. if( bl_list_count >= BL_LIST_MAX )
  797. ShowWarning("map_foreachinarea: block count too many!\n");
  798. map_freeblock_lock();
  799. for( i = blockcount; i < bl_list_count; i++ )
  800. if(bl_list[ i ]->prev) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  801. va_start(ap, type);
  802. returnCount += func(bl_list[ i ], ap);
  803. va_end(ap);
  804. if( count && returnCount >= count )
  805. break;
  806. }
  807. map_freeblock_unlock();
  808. bl_list_count = blockcount;
  809. return returnCount; //[Skotlex]
  810. }
  811. /*==========================================
  812. * Move bl and do func* with va_list while moving.
  813. * Movement is set by dx dy which are distance in x and y
  814. *------------------------------------------*/
  815. int map_foreachinmovearea(int (*func)(struct block_list*,va_list), struct block_list* center, int16 range, int16 dx, int16 dy, int type, ...)
  816. {
  817. int bx, by, m;
  818. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  819. struct block_list *bl;
  820. int blockcount = bl_list_count, i;
  821. int16 x0, x1, y0, y1;
  822. va_list ap;
  823. if ( !range ) return 0;
  824. if ( !dx && !dy ) return 0; //No movement.
  825. m = center->m;
  826. x0 = center->x - range;
  827. x1 = center->x + range;
  828. y0 = center->y - range;
  829. y1 = center->y + range;
  830. if ( x1 < x0 )
  831. swap(x0, x1);
  832. if ( y1 < y0 )
  833. swap(y0, y1);
  834. if( dx == 0 || dy == 0 ) {
  835. //Movement along one axis only.
  836. if( dx == 0 ){
  837. if( dy < 0 ) //Moving south
  838. y0 = y1 + dy + 1;
  839. else //North
  840. y1 = y0 + dy - 1;
  841. } else { //dy == 0
  842. if( dx < 0 ) //West
  843. x0 = x1 + dx + 1;
  844. else //East
  845. x1 = x0 + dx - 1;
  846. }
  847. x0 = i16max(x0, 0);
  848. y0 = i16max(y0, 0);
  849. x1 = i16min(x1, map[ m ].xs - 1);
  850. y1 = i16min(y1, map[ m ].ys - 1);
  851. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  852. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  853. if ( type&~BL_MOB ) {
  854. for( bl = map[m].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  855. if( bl->type&type &&
  856. bl->x >= x0 && bl->x <= x1 &&
  857. bl->y >= y0 && bl->y <= y1 &&
  858. bl_list_count < BL_LIST_MAX )
  859. bl_list[ bl_list_count++ ] = bl;
  860. }
  861. }
  862. if ( type&BL_MOB ) {
  863. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  864. if( bl->x >= x0 && bl->x <= x1 &&
  865. bl->y >= y0 && bl->y <= y1 &&
  866. bl_list_count < BL_LIST_MAX )
  867. bl_list[ bl_list_count++ ] = bl;
  868. }
  869. }
  870. }
  871. }
  872. } else { // Diagonal movement
  873. x0 = i16max(x0, 0);
  874. y0 = i16max(y0, 0);
  875. x1 = i16min(x1, map[ m ].xs - 1);
  876. y1 = i16min(y1, map[ m ].ys - 1);
  877. for( by = y0 / BLOCK_SIZE; by <= y1 / BLOCK_SIZE; by++ ) {
  878. for( bx = x0 / BLOCK_SIZE; bx <= x1 / BLOCK_SIZE; bx++ ) {
  879. if ( type & ~BL_MOB ) {
  880. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  881. if( bl->type&type &&
  882. bl->x >= x0 && bl->x <= x1 &&
  883. bl->y >= y0 && bl->y <= y1 &&
  884. bl_list_count < BL_LIST_MAX )
  885. if( ( dx > 0 && bl->x < x0 + dx) ||
  886. ( dx < 0 && bl->x > x1 + dx) ||
  887. ( dy > 0 && bl->y < y0 + dy) ||
  888. ( dy < 0 && bl->y > y1 + dy) )
  889. bl_list[ bl_list_count++ ] = bl;
  890. }
  891. }
  892. if ( type&BL_MOB ) {
  893. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  894. if( bl->x >= x0 && bl->x <= x1 &&
  895. bl->y >= y0 && bl->y <= y1 &&
  896. bl_list_count < BL_LIST_MAX)
  897. if( ( dx > 0 && bl->x < x0 + dx) ||
  898. ( dx < 0 && bl->x > x1 + dx) ||
  899. ( dy > 0 && bl->y < y0 + dy) ||
  900. ( dy < 0 && bl->y > y1 + dy) )
  901. bl_list[ bl_list_count++ ] = bl;
  902. }
  903. }
  904. }
  905. }
  906. }
  907. if( bl_list_count >= BL_LIST_MAX )
  908. ShowWarning("map_foreachinmovearea: block count too many!\n");
  909. map_freeblock_lock(); // Prohibit the release from memory
  910. for( i = blockcount; i < bl_list_count; i++ )
  911. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  912. va_start(ap, type);
  913. returnCount += func(bl_list[ i ], ap);
  914. va_end(ap);
  915. }
  916. map_freeblock_unlock(); // Allow Free
  917. bl_list_count = blockcount;
  918. return returnCount;
  919. }
  920. // -- moonsoul (added map_foreachincell which is a rework of map_foreachinarea but
  921. // which only checks the exact single x/y passed to it rather than an
  922. // area radius - may be more useful in some instances)
  923. //
  924. int map_foreachincell(int (*func)(struct block_list*,va_list), int16 m, int16 x, int16 y, int type, ...)
  925. {
  926. int bx, by;
  927. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  928. struct block_list *bl;
  929. int blockcount = bl_list_count, i;
  930. va_list ap;
  931. if ( x < 0 || y < 0 || x >= map[ m ].xs || y >= map[ m ].ys ) return 0;
  932. by = y / BLOCK_SIZE;
  933. bx = x / BLOCK_SIZE;
  934. if( type&~BL_MOB )
  935. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next )
  936. if( bl->type&type && bl->x == x && bl->y == y && bl_list_count < BL_LIST_MAX )
  937. bl_list[ bl_list_count++ ] = bl;
  938. if( type&BL_MOB )
  939. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs]; bl != NULL; bl = bl->next )
  940. if( bl->x == x && bl->y == y && bl_list_count < BL_LIST_MAX)
  941. bl_list[ bl_list_count++ ] = bl;
  942. if( bl_list_count >= BL_LIST_MAX )
  943. ShowWarning("map_foreachincell: block count too many!\n");
  944. map_freeblock_lock();
  945. for( i = blockcount; i < bl_list_count; i++ )
  946. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  947. va_start(ap, type);
  948. returnCount += func(bl_list[ i ], ap);
  949. va_end(ap);
  950. }
  951. map_freeblock_unlock();
  952. bl_list_count = blockcount;
  953. return returnCount;
  954. }
  955. /*============================================================
  956. * For checking a path between two points (x0, y0) and (x1, y1)
  957. *------------------------------------------------------------*/
  958. int map_foreachinpath(int (*func)(struct block_list*,va_list),int16 m,int16 x0,int16 y0,int16 x1,int16 y1,int16 range,int length, int type,...)
  959. {
  960. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  961. //////////////////////////////////////////////////////////////
  962. //
  963. // sharp shooting 3 [Skotlex]
  964. //
  965. //////////////////////////////////////////////////////////////
  966. // problem:
  967. // Same as Sharp Shooting 1. Hits all targets within range of
  968. // the line.
  969. // (t1,t2 t3 and t4 get hit)
  970. //
  971. // target 1
  972. // x t4
  973. // t2
  974. // t3 x
  975. // x
  976. // S
  977. //////////////////////////////////////////////////////////////
  978. // Methodology:
  979. // My trigonometrics and math are a little rusty... so the approach I am writing
  980. // here is basically do a double for to check for all targets in the square that
  981. // contains the initial and final positions (area range increased to match the
  982. // radius given), then for each object to test, calculate the distance to the
  983. // path and include it if the range fits and the target is in the line (0<k<1,
  984. // as they call it).
  985. // The implementation I took as reference is found at
  986. // http://astronomy.swin.edu.au/~pbourke/geometry/pointline/
  987. // (they have a link to a C implementation, too)
  988. // This approach is a lot like #2 commented on this function, which I have no
  989. // idea why it was commented. I won't use doubles/floats, but pure int math for
  990. // speed purposes. The range considered is always the same no matter how
  991. // close/far the target is because that's how SharpShooting works currently in
  992. // kRO.
  993. //Generic map_foreach* variables.
  994. int i, blockcount = bl_list_count;
  995. struct block_list *bl;
  996. int bx, by;
  997. //method specific variables
  998. int magnitude2, len_limit; //The square of the magnitude
  999. int k, xi, yi, xu, yu;
  1000. int mx0 = x0, mx1 = x1, my0 = y0, my1 = y1;
  1001. va_list ap;
  1002. //Avoid needless calculations by not getting the sqrt right away.
  1003. #define MAGNITUDE2(x0, y0, x1, y1) ( ( ( x1 ) - ( x0 ) ) * ( ( x1 ) - ( x0 ) ) + ( ( y1 ) - ( y0 ) ) * ( ( y1 ) - ( y0 ) ) )
  1004. if ( m < 0 )
  1005. return 0;
  1006. len_limit = magnitude2 = MAGNITUDE2(x0, y0, x1, y1);
  1007. if ( magnitude2 < 1 ) //Same begin and ending point, can't trace path.
  1008. return 0;
  1009. if ( length ) { //Adjust final position to fit in the given area.
  1010. //TODO: Find an alternate method which does not requires a square root calculation.
  1011. k = (int)sqrt((float)magnitude2);
  1012. mx1 = x0 + (x1 - x0) * length / k;
  1013. my1 = y0 + (y1 - y0) * length / k;
  1014. len_limit = MAGNITUDE2(x0, y0, mx1, my1);
  1015. }
  1016. //Expand target area to cover range.
  1017. if ( mx0 > mx1 ) {
  1018. mx0 += range;
  1019. mx1 -= range;
  1020. } else {
  1021. mx0 -= range;
  1022. mx1 += range;
  1023. }
  1024. if (my0 > my1) {
  1025. my0 += range;
  1026. my1 -= range;
  1027. } else {
  1028. my0 -= range;
  1029. my1 += range;
  1030. }
  1031. //The two fors assume mx0 < mx1 && my0 < my1
  1032. if ( mx0 > mx1 )
  1033. swap(mx0, mx1);
  1034. if ( my0 > my1 )
  1035. swap(my0, my1);
  1036. mx0 = max(mx0, 0);
  1037. my0 = max(my0, 0);
  1038. mx1 = min(mx1, map[ m ].xs - 1);
  1039. my1 = min(my1, map[ m ].ys - 1);
  1040. range *= range << 8; //Values are shifted later on for higher precision using int math.
  1041. if ( type&~BL_MOB )
  1042. for ( by = my0 / BLOCK_SIZE; by <= my1 / BLOCK_SIZE; by++ ) {
  1043. for( bx = mx0 / BLOCK_SIZE; bx <= mx1 / BLOCK_SIZE; bx++ ) {
  1044. for( bl = map[ m ].block[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  1045. if( bl->prev && bl->type&type && bl_list_count < BL_LIST_MAX ) {
  1046. xi = bl->x;
  1047. yi = bl->y;
  1048. k = ( xi - x0 ) * ( x1 - x0 ) + ( yi - y0 ) * ( y1 - y0 );
  1049. if ( k < 0 || k > len_limit ) //Since more skills use this, check for ending point as well.
  1050. continue;
  1051. if ( k > magnitude2 && !path_search_long(NULL, m, x0, y0, xi, yi, CELL_CHKWALL) )
  1052. continue; //Targets beyond the initial ending point need the wall check.
  1053. //All these shifts are to increase the precision of the intersection point and distance considering how it's
  1054. //int math.
  1055. k = ( k << 4 ) / magnitude2; //k will be between 1~16 instead of 0~1
  1056. xi <<= 4;
  1057. yi <<= 4;
  1058. xu = ( x0 << 4 ) + k * ( x1 - x0 );
  1059. yu = ( y0 << 4 ) + k * ( y1 - y0 );
  1060. k = MAGNITUDE2(xi, yi, xu, yu);
  1061. //If all dot coordinates were <<4 the square of the magnitude is <<8
  1062. if ( k > range )
  1063. continue;
  1064. bl_list[ bl_list_count++ ] = bl;
  1065. }
  1066. }
  1067. }
  1068. }
  1069. if( type&BL_MOB )
  1070. for( by = my0 / BLOCK_SIZE; by <= my1 / BLOCK_SIZE; by++ ) {
  1071. for( bx = mx0 / BLOCK_SIZE; bx <= mx1 / BLOCK_SIZE; bx++ ) {
  1072. for( bl = map[ m ].block_mob[ bx + by * map[ m ].bxs ]; bl != NULL; bl = bl->next ) {
  1073. if( bl->prev && bl_list_count < BL_LIST_MAX ) {
  1074. xi = bl->x;
  1075. yi = bl->y;
  1076. k = ( xi - x0 ) * ( x1 - x0 ) + ( yi - y0 ) * ( y1 - y0 );
  1077. if ( k < 0 || k > len_limit )
  1078. continue;
  1079. if ( k > magnitude2 && !path_search_long(NULL, m, x0, y0, xi, yi, CELL_CHKWALL) )
  1080. continue; //Targets beyond the initial ending point need the wall check.
  1081. k = ( k << 4 ) / magnitude2; //k will be between 1~16 instead of 0~1
  1082. xi <<= 4;
  1083. yi <<= 4;
  1084. xu = ( x0 << 4 ) + k * ( x1 - x0 );
  1085. yu = ( y0 << 4 ) + k * ( y1 - y0 );
  1086. k = MAGNITUDE2(xi, yi, xu, yu);
  1087. //If all dot coordinates were <<4 the square of the magnitude is <<8
  1088. if ( k > range )
  1089. continue;
  1090. bl_list[ bl_list_count++ ] = bl;
  1091. }
  1092. }
  1093. }
  1094. }
  1095. if( bl_list_count >= BL_LIST_MAX )
  1096. ShowWarning("map_foreachinpath: block count too many!\n");
  1097. map_freeblock_lock();
  1098. for( i = blockcount; i < bl_list_count; i++ )
  1099. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  1100. va_start(ap, type);
  1101. returnCount += func(bl_list[ i ], ap);
  1102. va_end(ap);
  1103. }
  1104. map_freeblock_unlock();
  1105. bl_list_count = blockcount;
  1106. return returnCount; //[Skotlex]
  1107. }
  1108. /*========================================== [Playtester]
  1109. * Calls the given function for every object of a type that is on a path.
  1110. * The path goes into one of the eight directions and the direction is determined by the given coordinates.
  1111. * The path has a length, a width and an offset.
  1112. * The cost for diagonal movement is the same as for horizontal/vertical movement.
  1113. * @param m: ID of map
  1114. * @param x0: Start X
  1115. * @param y0: Start Y
  1116. * @param x1: X to calculate direction against
  1117. * @param y1: Y to calculate direction against
  1118. * @param range: Determines width of the path (width = range*2+1 cells)
  1119. * @param length: Length of the path
  1120. * @param offset: Moves the whole path, half-length for diagonal paths
  1121. * @param type: Type of bl to search for
  1122. *------------------------------------------*/
  1123. int map_foreachindir(int(*func)(struct block_list*, va_list), int16 m, int16 x0, int16 y0, int16 x1, int16 y1, int16 range, int length, int offset, int type, ...)
  1124. {
  1125. int returnCount = 0; //Total sum of returned values of func()
  1126. int i, blockcount = bl_list_count;
  1127. struct block_list *bl;
  1128. int bx, by;
  1129. int mx0, mx1, my0, my1, rx, ry;
  1130. uint8 dir = map_calc_dir_xy(x0, y0, x1, y1, 6);
  1131. short dx = dirx[dir];
  1132. short dy = diry[dir];
  1133. va_list ap;
  1134. if (m < 0)
  1135. return 0;
  1136. if (range < 0)
  1137. return 0;
  1138. if (length < 1)
  1139. return 0;
  1140. if (offset < 0)
  1141. return 0;
  1142. //Special offset handling for diagonal paths
  1143. if (offset && (dir % 2)) {
  1144. //So that diagonal paths can attach to each other, we have to work with half-tile offsets
  1145. offset = (2 * offset) - 1;
  1146. //To get the half-tiles we need to increase length by one
  1147. length++;
  1148. }
  1149. //Get area that needs to be checked
  1150. mx0 = x0 + dx*(offset / ((dir % 2) + 1));
  1151. my0 = y0 + dy*(offset / ((dir % 2) + 1));
  1152. mx1 = x0 + dx*(offset / ((dir % 2) + 1) + length - 1);
  1153. my1 = y0 + dy*(offset / ((dir % 2) + 1) + length - 1);
  1154. //The following assumes mx0 < mx1 && my0 < my1
  1155. if (mx0 > mx1)
  1156. swap(mx0, mx1);
  1157. if (my0 > my1)
  1158. swap(my0, my1);
  1159. //Apply width to the path by turning 90 degrees
  1160. mx0 -= abs(range*dirx[(dir + 2) % 8]);
  1161. my0 -= abs(range*diry[(dir + 2) % 8]);
  1162. mx1 += abs(range*dirx[(dir + 2) % 8]);
  1163. my1 += abs(range*diry[(dir + 2) % 8]);
  1164. mx0 = max(mx0, 0);
  1165. my0 = max(my0, 0);
  1166. mx1 = min(mx1, map[m].xs - 1);
  1167. my1 = min(my1, map[m].ys - 1);
  1168. if (type&~BL_MOB) {
  1169. for (by = my0 / BLOCK_SIZE; by <= my1 / BLOCK_SIZE; by++) {
  1170. for (bx = mx0 / BLOCK_SIZE; bx <= mx1 / BLOCK_SIZE; bx++) {
  1171. for (bl = map[m].block[bx + by * map[m].bxs]; bl != NULL; bl = bl->next) {
  1172. if (bl->prev && bl->type&type && bl_list_count < BL_LIST_MAX) {
  1173. //Check if inside search area
  1174. if (bl->x < mx0 || bl->x > mx1 || bl->y < my0 || bl->y > my1)
  1175. continue;
  1176. //What matters now is the relative x and y from the start point
  1177. rx = (bl->x - x0);
  1178. ry = (bl->y - y0);
  1179. //Do not hit source cell
  1180. if (rx == 0 && ry == 0)
  1181. continue;
  1182. //This turns it so that the area that is hit is always with positive rx and ry
  1183. rx *= dx;
  1184. ry *= dy;
  1185. //These checks only need to be done for diagonal paths
  1186. if (dir % 2) {
  1187. //Check for length
  1188. if ((rx + ry < offset) || (rx + ry > 2 * (length + (offset/2) - 1)))
  1189. continue;
  1190. //Check for width
  1191. if (abs(rx - ry) > 2 * range)
  1192. continue;
  1193. }
  1194. //Everything else ok, check for line of sight from source
  1195. if (!path_search_long(NULL, m, x0, y0, bl->x, bl->y, CELL_CHKWALL))
  1196. continue;
  1197. //All checks passed, add to list
  1198. bl_list[bl_list_count++] = bl;
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. if (type&BL_MOB) {
  1205. for (by = my0 / BLOCK_SIZE; by <= my1 / BLOCK_SIZE; by++) {
  1206. for (bx = mx0 / BLOCK_SIZE; bx <= mx1 / BLOCK_SIZE; bx++) {
  1207. for (bl = map[m].block_mob[bx + by * map[m].bxs]; bl != NULL; bl = bl->next) {
  1208. if (bl->prev && bl_list_count < BL_LIST_MAX) {
  1209. //Check if inside search area
  1210. if (bl->x < mx0 || bl->x > mx1 || bl->y < my0 || bl->y > my1)
  1211. continue;
  1212. //What matters now is the relative x and y from the start point
  1213. rx = (bl->x - x0);
  1214. ry = (bl->y - y0);
  1215. //Do not hit source cell
  1216. if (rx == 0 && ry == 0)
  1217. continue;
  1218. //This turns it so that the area that is hit is always with positive rx and ry
  1219. rx *= dx;
  1220. ry *= dy;
  1221. //These checks only need to be done for diagonal paths
  1222. if (dir % 2) {
  1223. //Check for length
  1224. if ((rx + ry < offset) || (rx + ry > 2 * (length + (offset / 2) - 1)))
  1225. continue;
  1226. //Check for width
  1227. if (abs(rx - ry) > 2 * range)
  1228. continue;
  1229. }
  1230. //Everything else ok, check for line of sight from source
  1231. if (!path_search_long(NULL, m, x0, y0, bl->x, bl->y, CELL_CHKWALL))
  1232. continue;
  1233. //All checks passed, add to list
  1234. bl_list[bl_list_count++] = bl;
  1235. }
  1236. }
  1237. }
  1238. }
  1239. }
  1240. if( bl_list_count >= BL_LIST_MAX )
  1241. ShowWarning("map_foreachindir: block count too many!\n");
  1242. map_freeblock_lock();
  1243. for( i = blockcount; i < bl_list_count; i++ )
  1244. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  1245. va_start(ap, type);
  1246. returnCount += func(bl_list[ i ], ap);
  1247. va_end(ap);
  1248. }
  1249. map_freeblock_unlock();
  1250. bl_list_count = blockcount;
  1251. return returnCount;
  1252. }
  1253. // Copy of map_foreachincell, but applied to the whole map. [Skotlex]
  1254. int map_foreachinmap(int (*func)(struct block_list*,va_list), int16 m, int type,...)
  1255. {
  1256. int b, bsize;
  1257. int returnCount = 0; //total sum of returned values of func() [Skotlex]
  1258. struct block_list *bl;
  1259. int blockcount = bl_list_count, i;
  1260. va_list ap;
  1261. bsize = map[ m ].bxs * map[ m ].bys;
  1262. if( type&~BL_MOB )
  1263. for( b = 0; b < bsize; b++ )
  1264. for( bl = map[ m ].block[ b ]; bl != NULL; bl = bl->next )
  1265. if( bl->type&type && bl_list_count < BL_LIST_MAX )
  1266. bl_list[ bl_list_count++ ] = bl;
  1267. if( type&BL_MOB )
  1268. for( b = 0; b < bsize; b++ )
  1269. for( bl = map[ m ].block_mob[ b ]; bl != NULL; bl = bl->next )
  1270. if( bl_list_count < BL_LIST_MAX )
  1271. bl_list[ bl_list_count++ ] = bl;
  1272. if( bl_list_count >= BL_LIST_MAX )
  1273. ShowWarning("map_foreachinmap: block count too many!\n");
  1274. map_freeblock_lock();
  1275. for( i = blockcount; i < bl_list_count ; i++ )
  1276. if( bl_list[ i ]->prev ) { //func() may delete this bl_list[] slot, checking for prev ensures it wasn't queued for deletion.
  1277. va_start(ap, type);
  1278. returnCount += func(bl_list[ i ], ap);
  1279. va_end(ap);
  1280. }
  1281. map_freeblock_unlock();
  1282. bl_list_count = blockcount;
  1283. return returnCount;
  1284. }
  1285. /// Generates a new flooritem object id from the interval [MIN_FLOORITEM, MAX_FLOORITEM).
  1286. /// Used for floor items, skill units and chatroom objects.
  1287. /// @return The new object id
  1288. int map_get_new_object_id(void)
  1289. {
  1290. static int last_object_id = MIN_FLOORITEM - 1;
  1291. int i;
  1292. // find a free id
  1293. i = last_object_id + 1;
  1294. while( i != last_object_id ) {
  1295. if( i == MAX_FLOORITEM )
  1296. i = MIN_FLOORITEM;
  1297. if( !idb_exists(id_db, i) )
  1298. break;
  1299. ++i;
  1300. }
  1301. if( i == last_object_id ) {
  1302. ShowError("map_addobject: no free object id!\n");
  1303. return 0;
  1304. }
  1305. // update cursor
  1306. last_object_id = i;
  1307. return i;
  1308. }
  1309. /*==========================================
  1310. * Timered function to clear the floor (remove remaining item)
  1311. * Called each flooritem_lifetime ms
  1312. *------------------------------------------*/
  1313. int map_clearflooritem_timer(int tid, unsigned int tick, int id, intptr_t data)
  1314. {
  1315. struct flooritem_data* fitem = (struct flooritem_data*)idb_get(id_db, id);
  1316. if (fitem == NULL || fitem->bl.type != BL_ITEM || (fitem->cleartimer != tid)) {
  1317. ShowError("map_clearflooritem_timer : error\n");
  1318. return 1;
  1319. }
  1320. if (search_petDB_index(fitem->item.nameid, PET_EGG) >= 0)
  1321. intif_delete_petdata(MakeDWord(fitem->item.card[1], fitem->item.card[2]));
  1322. clif_clearflooritem(fitem, 0);
  1323. map_deliddb(&fitem->bl);
  1324. map_delblock(&fitem->bl);
  1325. map_freeblock(&fitem->bl);
  1326. return 0;
  1327. }
  1328. /*
  1329. * clears a single bl item out of the map.
  1330. */
  1331. void map_clearflooritem(struct block_list *bl) {
  1332. struct flooritem_data* fitem = (struct flooritem_data*)bl;
  1333. if( fitem->cleartimer != INVALID_TIMER )
  1334. delete_timer(fitem->cleartimer,map_clearflooritem_timer);
  1335. clif_clearflooritem(fitem, 0);
  1336. map_deliddb(&fitem->bl);
  1337. map_delblock(&fitem->bl);
  1338. map_freeblock(&fitem->bl);
  1339. }
  1340. /*==========================================
  1341. * (m,x,y) locates a random available free cell around the given coordinates
  1342. * to place an BL_ITEM object. Scan area is 9x9, returns 1 on success.
  1343. * x and y are modified with the target cell when successful.
  1344. *------------------------------------------*/
  1345. int map_searchrandfreecell(int16 m,int16 *x,int16 *y,int stack) {
  1346. int free_cell,i,j;
  1347. int free_cells[9][2];
  1348. for(free_cell=0,i=-1;i<=1;i++){
  1349. if(i+*y<0 || i+*y>=map[m].ys)
  1350. continue;
  1351. for(j=-1;j<=1;j++){
  1352. if(j+*x<0 || j+*x>=map[m].xs)
  1353. continue;
  1354. if(map_getcell(m,j+*x,i+*y,CELL_CHKNOPASS) && !map_getcell(m,j+*x,i+*y,CELL_CHKICEWALL))
  1355. continue;
  1356. //Avoid item stacking to prevent against exploits. [Skotlex]
  1357. if(stack && map_count_oncell(m,j+*x,i+*y, BL_ITEM, 0) > stack)
  1358. continue;
  1359. free_cells[free_cell][0] = j+*x;
  1360. free_cells[free_cell++][1] = i+*y;
  1361. }
  1362. }
  1363. if(free_cell==0)
  1364. return 0;
  1365. free_cell = rnd()%free_cell;
  1366. *x = free_cells[free_cell][0];
  1367. *y = free_cells[free_cell][1];
  1368. return 1;
  1369. }
  1370. static int map_count_sub(struct block_list *bl,va_list ap)
  1371. {
  1372. return 1;
  1373. }
  1374. /*==========================================
  1375. * Locates a random spare cell around the object given, using range as max
  1376. * distance from that spot. Used for warping functions. Use range < 0 for
  1377. * whole map range.
  1378. * Returns 1 on success. when it fails and src is available, x/y are set to src's
  1379. * src can be null as long as flag&1
  1380. * when ~flag&1, m is not needed.
  1381. * Flag values:
  1382. * &1 = random cell must be around given m,x,y, not around src
  1383. * &2 = the target should be able to walk to the target tile.
  1384. * &4 = there shouldn't be any players around the target tile (use the no_spawn_on_player setting)
  1385. *------------------------------------------*/
  1386. int map_search_freecell(struct block_list *src, int16 m, int16 *x,int16 *y, int16 rx, int16 ry, int flag)
  1387. {
  1388. int tries, spawn=0;
  1389. int bx, by;
  1390. int rx2 = 2*rx+1;
  1391. int ry2 = 2*ry+1;
  1392. if( !src && (!(flag&1) || flag&2) )
  1393. {
  1394. ShowDebug("map_search_freecell: Incorrect usage! When src is NULL, flag has to be &1 and can't have &2\n");
  1395. return 0;
  1396. }
  1397. if (flag&1) {
  1398. bx = *x;
  1399. by = *y;
  1400. } else {
  1401. bx = src->x;
  1402. by = src->y;
  1403. m = src->m;
  1404. }
  1405. if (!rx && !ry) {
  1406. //No range? Return the target cell then....
  1407. *x = bx;
  1408. *y = by;
  1409. return map_getcell(m,*x,*y,CELL_CHKREACH);
  1410. }
  1411. if (rx >= 0 && ry >= 0) {
  1412. tries = rx2*ry2;
  1413. if (tries > 100) tries = 100;
  1414. } else {
  1415. tries = map[m].xs*map[m].ys;
  1416. if (tries > 500) tries = 500;
  1417. }
  1418. while(tries--) {
  1419. *x = (rx >= 0)?(rnd()%rx2-rx+bx):(rnd()%(map[m].xs-2)+1);
  1420. *y = (ry >= 0)?(rnd()%ry2-ry+by):(rnd()%(map[m].ys-2)+1);
  1421. if (*x == bx && *y == by)
  1422. continue; //Avoid picking the same target tile.
  1423. if (map_getcell(m,*x,*y,CELL_CHKREACH))
  1424. {
  1425. if(flag&2 && !unit_can_reach_pos(src, *x, *y, 1))
  1426. continue;
  1427. if(flag&4) {
  1428. if (spawn >= 100) return 0; //Limit of retries reached.
  1429. if (spawn++ < battle_config.no_spawn_on_player &&
  1430. map_foreachinarea(map_count_sub, m,
  1431. *x-AREA_SIZE, *y-AREA_SIZE,
  1432. *x+AREA_SIZE, *y+AREA_SIZE, BL_PC)
  1433. )
  1434. continue;
  1435. }
  1436. return 1;
  1437. }
  1438. }
  1439. *x = bx;
  1440. *y = by;
  1441. return 0;
  1442. }
  1443. /*==========================================
  1444. * Locates the closest, walkable cell with no blocks of a certain type on it
  1445. * Returns true on success and sets x and y to cell found.
  1446. * Otherwise returns false and x and y are not changed.
  1447. * type: Types of block to count
  1448. * flag:
  1449. * 0x1 - only count standing units
  1450. *------------------------------------------*/
  1451. bool map_closest_freecell(int16 m, int16 *x, int16 *y, int type, int flag)
  1452. {
  1453. uint8 dir = 6;
  1454. int16 tx = *x;
  1455. int16 ty = *y;
  1456. int costrange = 10;
  1457. if(!map_count_oncell(m, tx, ty, type, flag))
  1458. return true; //Current cell is free
  1459. //Algorithm only works up to costrange of 34
  1460. while(costrange <= 34) {
  1461. short dx = dirx[dir];
  1462. short dy = diry[dir];
  1463. //Linear search
  1464. if(dir%2 == 0 && costrange%MOVE_COST == 0) {
  1465. tx = *x+dx*(costrange/MOVE_COST);
  1466. ty = *y+dy*(costrange/MOVE_COST);
  1467. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1468. *x = tx;
  1469. *y = ty;
  1470. return true;
  1471. }
  1472. }
  1473. //Full diagonal search
  1474. else if(dir%2 == 1 && costrange%MOVE_DIAGONAL_COST == 0) {
  1475. tx = *x+dx*(costrange/MOVE_DIAGONAL_COST);
  1476. ty = *y+dy*(costrange/MOVE_DIAGONAL_COST);
  1477. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1478. *x = tx;
  1479. *y = ty;
  1480. return true;
  1481. }
  1482. }
  1483. //One cell diagonal, rest linear (TODO: Find a better algorithm for this)
  1484. else if(dir%2 == 1 && costrange%MOVE_COST == 4) {
  1485. tx = *x+dx*((dir%4==3)?(costrange/MOVE_COST):1);
  1486. ty = *y+dy*((dir%4==1)?(costrange/MOVE_COST):1);
  1487. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1488. *x = tx;
  1489. *y = ty;
  1490. return true;
  1491. }
  1492. tx = *x+dx*((dir%4==1)?(costrange/MOVE_COST):1);
  1493. ty = *y+dy*((dir%4==3)?(costrange/MOVE_COST):1);
  1494. if(!map_count_oncell(m, tx, ty, type, flag) && map_getcell(m,tx,ty,CELL_CHKPASS)) {
  1495. *x = tx;
  1496. *y = ty;
  1497. return true;
  1498. }
  1499. }
  1500. //Get next direction
  1501. if (dir == 5) {
  1502. //Diagonal search complete, repeat with higher cost range
  1503. if(costrange == 14) costrange += 6;
  1504. else if(costrange == 28 || costrange >= 38) costrange += 2;
  1505. else costrange += 4;
  1506. dir = 6;
  1507. } else if (dir == 4) {
  1508. //Linear search complete, switch to diagonal directions
  1509. dir = 7;
  1510. } else {
  1511. dir = (dir+2)%8;
  1512. }
  1513. }
  1514. return false;
  1515. }
  1516. /*==========================================
  1517. * Add an item in floor to location (m,x,y) and add restriction for those who could pickup later
  1518. * NB : If charids are null their no restriction for pickup
  1519. * @param item_data : item attributes
  1520. * @param amount : items quantity
  1521. * @param m : mapid
  1522. * @param x : x coordinates
  1523. * @param y : y coordinates
  1524. * @param first_charid : 1st player that could loot the item (only charid that could loot for first_get_tick duration)
  1525. * @param second_charid : 2nd player that could loot the item (2nd charid that could loot for second_get_charid duration)
  1526. * @param third_charid : 3rd player that could loot the item (3rd charid that could loot for third_get_charid duration)
  1527. * @param flag: &1 MVP item. &2 do stacking check. &4 bypass droppable check.
  1528. * @param mob_id: Monster ID if dropped by monster
  1529. * @return 0:failure, x:item_gid [MIN_FLOORITEM;MAX_FLOORITEM]==[2;START_ACCOUNT_NUM]
  1530. *------------------------------------------*/
  1531. int map_addflooritem(struct item *item, int amount, int16 m, int16 x, int16 y, int first_charid, int second_charid, int third_charid, int flags, unsigned short mob_id)
  1532. {
  1533. int r;
  1534. struct flooritem_data *fitem = NULL;
  1535. nullpo_ret(item);
  1536. if (!(flags&4) && battle_config.item_onfloor && (itemdb_traderight(item->nameid)&1))
  1537. return 0; //can't be dropped
  1538. if (!map_searchrandfreecell(m,&x,&y,flags&2?1:0))
  1539. return 0;
  1540. r = rnd();
  1541. CREATE(fitem, struct flooritem_data, 1);
  1542. fitem->bl.type=BL_ITEM;
  1543. fitem->bl.prev = fitem->bl.next = NULL;
  1544. fitem->bl.m=m;
  1545. fitem->bl.x=x;
  1546. fitem->bl.y=y;
  1547. fitem->bl.id = map_get_new_object_id();
  1548. if (fitem->bl.id==0) {
  1549. aFree(fitem);
  1550. return 0;
  1551. }
  1552. fitem->first_get_charid = first_charid;
  1553. fitem->first_get_tick = gettick() + (flags&1 ? battle_config.mvp_item_first_get_time : battle_config.item_first_get_time);
  1554. fitem->second_get_charid = second_charid;
  1555. fitem->second_get_tick = fitem->first_get_tick + (flags&1 ? battle_config.mvp_item_second_get_time : battle_config.item_second_get_time);
  1556. fitem->third_get_charid = third_charid;
  1557. fitem->third_get_tick = fitem->second_get_tick + (flags&1 ? battle_config.mvp_item_third_get_time : battle_config.item_third_get_time);
  1558. fitem->mob_id = mob_id;
  1559. memcpy(&fitem->item,item,sizeof(*item));
  1560. fitem->item.amount = amount;
  1561. fitem->subx = (r&3)*3+3;
  1562. fitem->suby = ((r>>2)&3)*3+3;
  1563. fitem->cleartimer = add_timer(gettick()+battle_config.flooritem_lifetime,map_clearflooritem_timer,fitem->bl.id,0);
  1564. map_addiddb(&fitem->bl);
  1565. if (map_addblock(&fitem->bl))
  1566. return 0;
  1567. clif_dropflooritem(fitem);
  1568. return fitem->bl.id;
  1569. }
  1570. /**
  1571. * @see DBCreateData
  1572. */
  1573. static DBData create_charid2nick(DBKey key, va_list args)
  1574. {
  1575. struct charid2nick *p;
  1576. CREATE(p, struct charid2nick, 1);
  1577. return db_ptr2data(p);
  1578. }
  1579. /// Adds(or replaces) the nick of charid to nick_db and fulfils pending requests.
  1580. /// Does nothing if the character is online.
  1581. void map_addnickdb(int charid, const char* nick)
  1582. {
  1583. struct charid2nick* p;
  1584. if( map_charid2sd(charid) )
  1585. return;// already online
  1586. p = (struct charid2nick*)idb_ensure(nick_db, charid, create_charid2nick);
  1587. safestrncpy(p->nick, nick, sizeof(p->nick));
  1588. while( p->requests ) {
  1589. struct map_session_data* sd;
  1590. struct charid_request* req;
  1591. req = p->requests;
  1592. p->requests = req->next;
  1593. sd = map_charid2sd(req->charid);
  1594. if( sd )
  1595. clif_solved_charname(sd->fd, charid, p->nick);
  1596. aFree(req);
  1597. }
  1598. }
  1599. /// Removes the nick of charid from nick_db.
  1600. /// Sends name to all pending requests on charid.
  1601. void map_delnickdb(int charid, const char* name)
  1602. {
  1603. struct charid2nick* p;
  1604. DBData data;
  1605. if (!nick_db->remove(nick_db, db_i2key(charid), &data) || (p = (struct charid2nick*)db_data2ptr(&data)) == NULL)
  1606. return;
  1607. while( p->requests ) {
  1608. struct charid_request* req;
  1609. struct map_session_data* sd;
  1610. req = p->requests;
  1611. p->requests = req->next;
  1612. sd = map_charid2sd(req->charid);
  1613. if( sd )
  1614. clif_solved_charname(sd->fd, charid, name);
  1615. aFree(req);
  1616. }
  1617. aFree(p);
  1618. }
  1619. /// Notifies sd of the nick of charid.
  1620. /// Uses the name in the character if online.
  1621. /// Uses the name in nick_db if offline.
  1622. void map_reqnickdb(struct map_session_data * sd, int charid)
  1623. {
  1624. struct charid2nick* p;
  1625. struct charid_request* req;
  1626. struct map_session_data* tsd;
  1627. nullpo_retv(sd);
  1628. tsd = map_charid2sd(charid);
  1629. if( tsd )
  1630. {
  1631. clif_solved_charname(sd->fd, charid, tsd->status.name);
  1632. return;
  1633. }
  1634. p = (struct charid2nick*)idb_ensure(nick_db, charid, create_charid2nick);
  1635. if( *p->nick )
  1636. {
  1637. clif_solved_charname(sd->fd, charid, p->nick);
  1638. return;
  1639. }
  1640. // not in cache, request it
  1641. CREATE(req, struct charid_request, 1);
  1642. req->next = p->requests;
  1643. p->requests = req;
  1644. chrif_searchcharid(charid);
  1645. }
  1646. /*==========================================
  1647. * add bl to id_db
  1648. *------------------------------------------*/
  1649. void map_addiddb(struct block_list *bl)
  1650. {
  1651. nullpo_retv(bl);
  1652. if( bl->type == BL_PC )
  1653. {
  1654. TBL_PC* sd = (TBL_PC*)bl;
  1655. idb_put(pc_db,sd->bl.id,sd);
  1656. uidb_put(charid_db,sd->status.char_id,sd);
  1657. }
  1658. else if( bl->type == BL_MOB )
  1659. {
  1660. TBL_MOB* md = (TBL_MOB*)bl;
  1661. idb_put(mobid_db,bl->id,bl);
  1662. if( md->state.boss )
  1663. idb_put(bossid_db, bl->id, bl);
  1664. }
  1665. if( bl->type & BL_REGEN )
  1666. idb_put(regen_db, bl->id, bl);
  1667. idb_put(id_db,bl->id,bl);
  1668. }
  1669. /*==========================================
  1670. * remove bl from id_db
  1671. *------------------------------------------*/
  1672. void map_deliddb(struct block_list *bl)
  1673. {
  1674. nullpo_retv(bl);
  1675. if( bl->type == BL_PC )
  1676. {
  1677. TBL_PC* sd = (TBL_PC*)bl;
  1678. idb_remove(pc_db,sd->bl.id);
  1679. uidb_remove(charid_db,sd->status.char_id);
  1680. }
  1681. else if( bl->type == BL_MOB )
  1682. {
  1683. idb_remove(mobid_db,bl->id);
  1684. idb_remove(bossid_db,bl->id);
  1685. }
  1686. if( bl->type & BL_REGEN )
  1687. idb_remove(regen_db,bl->id);
  1688. idb_remove(id_db,bl->id);
  1689. }
  1690. /*==========================================
  1691. * Standard call when a player connection is closed.
  1692. *------------------------------------------*/
  1693. int map_quit(struct map_session_data *sd) {
  1694. int i;
  1695. if (sd->state.keepshop == false) { // Close vending/buyingstore
  1696. if (sd->state.vending)
  1697. vending_closevending(sd);
  1698. else if (sd->state.buyingstore)
  1699. buyingstore_close(sd);
  1700. }
  1701. if(!sd->state.active) { //Removing a player that is not active.
  1702. struct auth_node *node = chrif_search(sd->status.account_id);
  1703. if (node && node->char_id == sd->status.char_id &&
  1704. node->state != ST_LOGOUT)
  1705. //Except when logging out, clear the auth-connect data immediately.
  1706. chrif_auth_delete(node->account_id, node->char_id, node->state);
  1707. //Non-active players should not have loaded any data yet (or it was cleared already) so no additional cleanups are needed.
  1708. return 0;
  1709. }
  1710. if (sd->expiration_tid != INVALID_TIMER)
  1711. delete_timer(sd->expiration_tid, pc_expiration_timer);
  1712. if (sd->npc_timer_id != INVALID_TIMER) //Cancel the event timer.
  1713. npc_timerevent_quit(sd);
  1714. if (sd->autotrade_tid != INVALID_TIMER)
  1715. delete_timer(sd->autotrade_tid, pc_autotrade_timer);
  1716. if (sd->npc_id)
  1717. npc_event_dequeue(sd);
  1718. if( sd->bg_id )
  1719. bg_team_leave(sd,1);
  1720. if( sd->status.clan_id )
  1721. clan_member_left(sd);
  1722. pc_itemcd_do(sd,false);
  1723. npc_script_event(sd, NPCE_LOGOUT);
  1724. //Unit_free handles clearing the player related data,
  1725. //map_quit handles extra specific data which is related to quitting normally
  1726. //(changing map-servers invokes unit_free but bypasses map_quit)
  1727. if( sd->sc.count ) {
  1728. //Status that are not saved...
  1729. status_change_end(&sd->bl, SC_BOSSMAPINFO, INVALID_TIMER);
  1730. status_change_end(&sd->bl, SC_AUTOTRADE, INVALID_TIMER);
  1731. status_change_end(&sd->bl, SC_SPURT, INVALID_TIMER);
  1732. status_change_end(&sd->bl, SC_BERSERK, INVALID_TIMER);
  1733. status_change_end(&sd->bl, SC__BLOODYLUST, INVALID_TIMER);
  1734. status_change_end(&sd->bl, SC_TRICKDEAD, INVALID_TIMER);
  1735. status_change_end(&sd->bl, SC_LEADERSHIP, INVALID_TIMER);
  1736. status_change_end(&sd->bl, SC_GLORYWOUNDS, INVALID_TIMER);
  1737. status_change_end(&sd->bl, SC_SOULCOLD, INVALID_TIMER);
  1738. status_change_end(&sd->bl, SC_HAWKEYES, INVALID_TIMER);
  1739. status_change_end(&sd->bl, SC_CHASEWALK2, INVALID_TIMER);
  1740. if(sd->sc.data[SC_ENDURE] && sd->sc.data[SC_ENDURE]->val4)
  1741. status_change_end(&sd->bl, SC_ENDURE, INVALID_TIMER); //No need to save infinite endure.
  1742. if(sd->sc.data[SC_PROVOKE] && sd->sc.data[SC_PROVOKE]->timer == INVALID_TIMER)
  1743. status_change_end(&sd->bl, SC_PROVOKE, INVALID_TIMER); //Infinite provoke ends on logout
  1744. status_change_end(&sd->bl, SC_WEIGHT50, INVALID_TIMER);
  1745. status_change_end(&sd->bl, SC_WEIGHT90, INVALID_TIMER);
  1746. status_change_end(&sd->bl, SC_SATURDAYNIGHTFEVER, INVALID_TIMER);
  1747. status_change_end(&sd->bl, SC_KYOUGAKU, INVALID_TIMER);
  1748. status_change_end(&sd->bl, SC_C_MARKER, INVALID_TIMER);
  1749. status_change_end(&sd->bl, SC_READYSTORM, INVALID_TIMER);
  1750. status_change_end(&sd->bl, SC_READYDOWN, INVALID_TIMER);
  1751. status_change_end(&sd->bl, SC_READYTURN, INVALID_TIMER);
  1752. status_change_end(&sd->bl, SC_READYCOUNTER, INVALID_TIMER);
  1753. status_change_end(&sd->bl, SC_CBC, INVALID_TIMER);
  1754. status_change_end(&sd->bl, SC_EQC, INVALID_TIMER);
  1755. status_change_end(&sd->bl, SC_SPRITEMABLE, INVALID_TIMER);
  1756. // Remove visuals effect from headgear
  1757. status_change_end(&sd->bl, SC_MOONSTAR, INVALID_TIMER);
  1758. status_change_end(&sd->bl, SC_SUPER_STAR, INVALID_TIMER);
  1759. status_change_end(&sd->bl, SC_STRANGELIGHTS, INVALID_TIMER);
  1760. status_change_end(&sd->bl, SC_DECORATION_OF_MUSIC, INVALID_TIMER);
  1761. if (battle_config.debuff_on_logout&1) { //Remove negative buffs
  1762. status_change_end(&sd->bl, SC_ORCISH, INVALID_TIMER);
  1763. status_change_end(&sd->bl, SC_STRIPWEAPON, INVALID_TIMER);
  1764. status_change_end(&sd->bl, SC_STRIPARMOR, INVALID_TIMER);
  1765. status_change_end(&sd->bl, SC_STRIPSHIELD, INVALID_TIMER);
  1766. status_change_end(&sd->bl, SC_STRIPHELM, INVALID_TIMER);
  1767. status_change_end(&sd->bl, SC_EXTREMITYFIST, INVALID_TIMER);
  1768. status_change_end(&sd->bl, SC_EXPLOSIONSPIRITS, INVALID_TIMER);
  1769. if(sd->sc.data[SC_REGENERATION] && sd->sc.data[SC_REGENERATION]->val4)
  1770. status_change_end(&sd->bl, SC_REGENERATION, INVALID_TIMER);
  1771. //TO-DO Probably there are way more NPC_type negative status that are removed
  1772. status_change_end(&sd->bl, SC_CHANGEUNDEAD, INVALID_TIMER);
  1773. // Both these statuses are removed on logout. [L0ne_W0lf]
  1774. status_change_end(&sd->bl, SC_SLOWCAST, INVALID_TIMER);
  1775. status_change_end(&sd->bl, SC_CRITICALWOUND, INVALID_TIMER);
  1776. status_change_end(&sd->bl, SC_HEAT_BARREL_AFTER, INVALID_TIMER);
  1777. status_change_end(&sd->bl, SC_H_MINE, INVALID_TIMER);
  1778. status_change_end(&sd->bl, SC_ANTI_M_BLAST, INVALID_TIMER);
  1779. status_change_end(&sd->bl, SC_B_TRAP, INVALID_TIMER);
  1780. }
  1781. if (battle_config.debuff_on_logout&2) { //Remove positive buffs
  1782. status_change_end(&sd->bl, SC_MAXIMIZEPOWER, INVALID_TIMER);
  1783. status_change_end(&sd->bl, SC_MAXOVERTHRUST, INVALID_TIMER);
  1784. status_change_end(&sd->bl, SC_STEELBODY, INVALID_TIMER);
  1785. status_change_end(&sd->bl, SC_PRESERVE, INVALID_TIMER);
  1786. status_change_end(&sd->bl, SC_KAAHI, INVALID_TIMER);
  1787. status_change_end(&sd->bl, SC_SPIRIT, INVALID_TIMER);
  1788. status_change_end(&sd->bl, SC_HEAT_BARREL, INVALID_TIMER);
  1789. status_change_end(&sd->bl, SC_P_ALTER, INVALID_TIMER);
  1790. status_change_end(&sd->bl, SC_E_CHAIN, INVALID_TIMER);
  1791. status_change_end(&sd->bl, SC_SIGHTBLASTER, INVALID_TIMER);
  1792. }
  1793. }
  1794. for (i = 0; i < EQI_MAX; i++) {
  1795. if (sd->equip_index[i] >= 0)
  1796. if (pc_isequip(sd,sd->equip_index[i]))
  1797. pc_unequipitem(sd,sd->equip_index[i],2);
  1798. }
  1799. // Return loot to owner
  1800. if( sd->pd ) pet_lootitem_drop(sd->pd, sd);
  1801. if (sd->ed) // Remove effects here rather than unit_remove_map_pc so we don't clear on Teleport/map change.
  1802. elemental_clean_effect(sd->ed);
  1803. if (sd->state.permanent_speed == 1) sd->state.permanent_speed = 0; // Remove lock so speed is set back to normal at login.
  1804. if( map[sd->bl.m].instance_id )
  1805. instance_delusers(map[sd->bl.m].instance_id);
  1806. unit_remove_map_pc(sd,CLR_RESPAWN);
  1807. if( map[sd->bl.m].instance_id ) { // Avoid map conflicts and warnings on next login
  1808. int16 m;
  1809. struct point *pt;
  1810. if( map[sd->bl.m].save.map )
  1811. pt = &map[sd->bl.m].save;
  1812. else
  1813. pt = &sd->status.save_point;
  1814. if( (m=map_mapindex2mapid(pt->map)) >= 0 )
  1815. {
  1816. sd->bl.m = m;
  1817. sd->bl.x = pt->x;
  1818. sd->bl.y = pt->y;
  1819. sd->mapindex = pt->map;
  1820. }
  1821. }
  1822. if (sd->state.vending)
  1823. idb_remove(vending_getdb(), sd->status.char_id);
  1824. if (sd->state.buyingstore)
  1825. idb_remove(buyingstore_getdb(), sd->status.char_id);
  1826. pc_damage_log_clear(sd,0);
  1827. party_booking_delete(sd); // Party Booking [Spiria]
  1828. pc_makesavestatus(sd);
  1829. pc_clean_skilltree(sd);
  1830. pc_crimson_marker_clear(sd);
  1831. chrif_save(sd, CSAVE_QUIT|CSAVE_INVENTORY|CSAVE_CART);
  1832. unit_free_pc(sd);
  1833. return 0;
  1834. }
  1835. /*==========================================
  1836. * Lookup, id to session (player,mob,npc,homon,merc..)
  1837. *------------------------------------------*/
  1838. struct map_session_data * map_id2sd(int id){
  1839. if (id <= 0) return NULL;
  1840. return (struct map_session_data*)idb_get(pc_db,id);
  1841. }
  1842. struct mob_data * map_id2md(int id){
  1843. if (id <= 0) return NULL;
  1844. return (struct mob_data*)idb_get(mobid_db,id);
  1845. }
  1846. struct npc_data * map_id2nd(int id){
  1847. struct block_list* bl = map_id2bl(id);
  1848. return BL_CAST(BL_NPC, bl);
  1849. }
  1850. struct homun_data* map_id2hd(int id){
  1851. struct block_list* bl = map_id2bl(id);
  1852. return BL_CAST(BL_HOM, bl);
  1853. }
  1854. struct mercenary_data* map_id2mc(int id){
  1855. struct block_list* bl = map_id2bl(id);
  1856. return BL_CAST(BL_MER, bl);
  1857. }
  1858. struct pet_data* map_id2pd(int id){
  1859. struct block_list* bl = map_id2bl(id);
  1860. return BL_CAST(BL_PET, bl);
  1861. }
  1862. struct elemental_data* map_id2ed(int id) {
  1863. struct block_list* bl = map_id2bl(id);
  1864. return BL_CAST(BL_ELEM, bl);
  1865. }
  1866. struct chat_data* map_id2cd(int id){
  1867. struct block_list* bl = map_id2bl(id);
  1868. return BL_CAST(BL_CHAT, bl);
  1869. }
  1870. /// Returns the nick of the target charid or NULL if unknown (requests the nick to the char server).
  1871. const char* map_charid2nick(int charid)
  1872. {
  1873. struct charid2nick *p;
  1874. struct map_session_data* sd;
  1875. sd = map_charid2sd(charid);
  1876. if( sd )
  1877. return sd->status.name;// character is online, return it's name
  1878. p = (struct charid2nick*)idb_ensure(nick_db, charid, create_charid2nick);
  1879. if( *p->nick )
  1880. return p->nick;// name in nick_db
  1881. chrif_searchcharid(charid);// request the name
  1882. return NULL;
  1883. }
  1884. /// Returns the struct map_session_data of the charid or NULL if the char is not online.
  1885. struct map_session_data* map_charid2sd(int charid)
  1886. {
  1887. return (struct map_session_data*)uidb_get(charid_db, charid);
  1888. }
  1889. /*==========================================
  1890. * Search session data from a nick name
  1891. * (without sensitive case if necessary)
  1892. * return map_session_data pointer or NULL
  1893. *------------------------------------------*/
  1894. struct map_session_data * map_nick2sd(const char *nick, bool allow_partial)
  1895. {
  1896. struct map_session_data* sd;
  1897. struct map_session_data* found_sd;
  1898. struct s_mapiterator* iter;
  1899. size_t nicklen;
  1900. int qty = 0;
  1901. if( nick == NULL )
  1902. return NULL;
  1903. nicklen = strlen(nick);
  1904. iter = mapit_getallusers();
  1905. found_sd = NULL;
  1906. for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
  1907. {
  1908. if( allow_partial && battle_config.partial_name_scan )
  1909. {// partial name search
  1910. if( strnicmp(sd->status.name, nick, nicklen) == 0 )
  1911. {
  1912. found_sd = sd;
  1913. if( strcmp(sd->status.name, nick) == 0 )
  1914. {// Perfect Match
  1915. qty = 1;
  1916. break;
  1917. }
  1918. qty++;
  1919. }
  1920. }
  1921. else if( strcasecmp(sd->status.name, nick) == 0 )
  1922. {// exact search only
  1923. found_sd = sd;
  1924. qty = 1;
  1925. break;
  1926. }
  1927. }
  1928. mapit_free(iter);
  1929. if( battle_config.partial_name_scan && qty != 1 )
  1930. found_sd = NULL;
  1931. return found_sd;
  1932. }
  1933. /*==========================================
  1934. * Looksup id_db DBMap and returns BL pointer of 'id' or NULL if not found
  1935. *------------------------------------------*/
  1936. struct block_list * map_id2bl(int id) {
  1937. return (struct block_list*)idb_get(id_db,id);
  1938. }
  1939. /**
  1940. * Same as map_id2bl except it only checks for its existence
  1941. **/
  1942. bool map_blid_exists( int id ) {
  1943. return (idb_exists(id_db,id));
  1944. }
  1945. /*==========================================
  1946. * Convex Mirror
  1947. *------------------------------------------*/
  1948. struct mob_data * map_getmob_boss(int16 m)
  1949. {
  1950. DBIterator* iter;
  1951. struct mob_data *md = NULL;
  1952. bool found = false;
  1953. iter = db_iterator(bossid_db);
  1954. for( md = (struct mob_data*)dbi_first(iter); dbi_exists(iter); md = (struct mob_data*)dbi_next(iter) )
  1955. {
  1956. if( md->bl.m == m )
  1957. {
  1958. found = true;
  1959. break;
  1960. }
  1961. }
  1962. dbi_destroy(iter);
  1963. return (found)? md : NULL;
  1964. }
  1965. struct mob_data * map_id2boss(int id)
  1966. {
  1967. if (id <= 0) return NULL;
  1968. return (struct mob_data*)idb_get(bossid_db,id);
  1969. }
  1970. /// Applies func to all the players in the db.
  1971. /// Stops iterating if func returns -1.
  1972. void map_foreachpc(int (*func)(struct map_session_data* sd, va_list args), ...)
  1973. {
  1974. DBIterator* iter;
  1975. struct map_session_data* sd;
  1976. iter = db_iterator(pc_db);
  1977. for( sd = (struct map_session_data*)dbi_first(iter); dbi_exists(iter); sd = (struct map_session_data*)dbi_next(iter) )
  1978. {
  1979. va_list args;
  1980. int ret;
  1981. va_start(args, func);
  1982. ret = func(sd, args);
  1983. va_end(args);
  1984. if( ret == -1 )
  1985. break;// stop iterating
  1986. }
  1987. dbi_destroy(iter);
  1988. }
  1989. /// Applies func to all the mobs in the db.
  1990. /// Stops iterating if func returns -1.
  1991. void map_foreachmob(int (*func)(struct mob_data* md, va_list args), ...)
  1992. {
  1993. DBIterator* iter;
  1994. struct mob_data* md;
  1995. iter = db_iterator(mobid_db);
  1996. for( md = (struct mob_data*)dbi_first(iter); dbi_exists(iter); md = (struct mob_data*)dbi_next(iter) )
  1997. {
  1998. va_list args;
  1999. int ret;
  2000. va_start(args, func);
  2001. ret = func(md, args);
  2002. va_end(args);
  2003. if( ret == -1 )
  2004. break;// stop iterating
  2005. }
  2006. dbi_destroy(iter);
  2007. }
  2008. /// Applies func to all the npcs in the db.
  2009. /// Stops iterating if func returns -1.
  2010. void map_foreachnpc(int (*func)(struct npc_data* nd, va_list args), ...)
  2011. {
  2012. DBIterator* iter;
  2013. struct block_list* bl;
  2014. iter = db_iterator(id_db);
  2015. for( bl = (struct block_list*)dbi_first(iter); dbi_exists(iter); bl = (struct block_list*)dbi_next(iter) )
  2016. {
  2017. if( bl->type == BL_NPC )
  2018. {
  2019. struct npc_data* nd = (struct npc_data*)bl;
  2020. va_list args;
  2021. int ret;
  2022. va_start(args, func);
  2023. ret = func(nd, args);
  2024. va_end(args);
  2025. if( ret == -1 )
  2026. break;// stop iterating
  2027. }
  2028. }
  2029. dbi_destroy(iter);
  2030. }
  2031. /// Applies func to everything in the db.
  2032. /// Stops iterating if func returns -1.
  2033. void map_foreachregen(int (*func)(struct block_list* bl, va_list args), ...)
  2034. {
  2035. DBIterator* iter;
  2036. struct block_list* bl;
  2037. iter = db_iterator(regen_db);
  2038. for( bl = (struct block_list*)dbi_first(iter); dbi_exists(iter); bl = (struct block_list*)dbi_next(iter) )
  2039. {
  2040. va_list args;
  2041. int ret;
  2042. va_start(args, func);
  2043. ret = func(bl, args);
  2044. va_end(args);
  2045. if( ret == -1 )
  2046. break;// stop iterating
  2047. }
  2048. dbi_destroy(iter);
  2049. }
  2050. /// Applies func to everything in the db.
  2051. /// Stops iterating if func returns -1.
  2052. void map_foreachiddb(int (*func)(struct block_list* bl, va_list args), ...)
  2053. {
  2054. DBIterator* iter;
  2055. struct block_list* bl;
  2056. iter = db_iterator(id_db);
  2057. for( bl = (struct block_list*)dbi_first(iter); dbi_exists(iter); bl = (struct block_list*)dbi_next(iter) )
  2058. {
  2059. va_list args;
  2060. int ret;
  2061. va_start(args, func);
  2062. ret = func(bl, args);
  2063. va_end(args);
  2064. if( ret == -1 )
  2065. break;// stop iterating
  2066. }
  2067. dbi_destroy(iter);
  2068. }
  2069. /// Iterator.
  2070. /// Can filter by bl type.
  2071. struct s_mapiterator
  2072. {
  2073. enum e_mapitflags flags;// flags for special behaviour
  2074. enum bl_type types;// what bl types to return
  2075. DBIterator* dbi;// database iterator
  2076. };
  2077. /// Returns true if the block_list matches the description in the iterator.
  2078. ///
  2079. /// @param _mapit_ Iterator
  2080. /// @param _bl_ block_list
  2081. /// @return true if it matches
  2082. #define MAPIT_MATCHES(_mapit_,_bl_) \
  2083. ( \
  2084. ( (_bl_)->type & (_mapit_)->types /* type matches */ ) \
  2085. )
  2086. /// Allocates a new iterator.
  2087. /// Returns the new iterator.
  2088. /// types can represent several BL's as a bit field.
  2089. /// TODO should this be expanded to allow filtering of map/guild/party/chat/cell/area/...?
  2090. ///
  2091. /// @param flags Flags of the iterator
  2092. /// @param type Target types
  2093. /// @return Iterator
  2094. struct s_mapiterator* mapit_alloc(enum e_mapitflags flags, enum bl_type types)
  2095. {
  2096. struct s_mapiterator* mapit;
  2097. CREATE(mapit, struct s_mapiterator, 1);
  2098. mapit->flags = flags;
  2099. mapit->types = types;
  2100. if( types == BL_PC ) mapit->dbi = db_iterator(pc_db);
  2101. else if( types == BL_MOB ) mapit->dbi = db_iterator(mobid_db);
  2102. else mapit->dbi = db_iterator(id_db);
  2103. return mapit;
  2104. }
  2105. /// Frees the iterator.
  2106. ///
  2107. /// @param mapit Iterator
  2108. void mapit_free(struct s_mapiterator* mapit)
  2109. {
  2110. nullpo_retv(mapit);
  2111. dbi_destroy(mapit->dbi);
  2112. aFree(mapit);
  2113. }
  2114. /// Returns the first block_list that matches the description.
  2115. /// Returns NULL if not found.
  2116. ///
  2117. /// @param mapit Iterator
  2118. /// @return first block_list or NULL
  2119. struct block_list* mapit_first(struct s_mapiterator* mapit)
  2120. {
  2121. struct block_list* bl;
  2122. nullpo_retr(NULL,mapit);
  2123. for( bl = (struct block_list*)dbi_first(mapit->dbi); bl != NULL; bl = (struct block_list*)dbi_next(mapit->dbi) )
  2124. {
  2125. if( MAPIT_MATCHES(mapit,bl) )
  2126. break;// found match
  2127. }
  2128. return bl;
  2129. }
  2130. /// Returns the last block_list that matches the description.
  2131. /// Returns NULL if not found.
  2132. ///
  2133. /// @param mapit Iterator
  2134. /// @return last block_list or NULL
  2135. struct block_list* mapit_last(struct s_mapiterator* mapit)
  2136. {
  2137. struct block_list* bl;
  2138. nullpo_retr(NULL,mapit);
  2139. for( bl = (struct block_list*)dbi_last(mapit->dbi); bl != NULL; bl = (struct block_list*)dbi_prev(mapit->dbi) )
  2140. {
  2141. if( MAPIT_MATCHES(mapit,bl) )
  2142. break;// found match
  2143. }
  2144. return bl;
  2145. }
  2146. /// Returns the next block_list that matches the description.
  2147. /// Returns NULL if not found.
  2148. ///
  2149. /// @param mapit Iterator
  2150. /// @return next block_list or NULL
  2151. struct block_list* mapit_next(struct s_mapiterator* mapit)
  2152. {
  2153. struct block_list* bl;
  2154. nullpo_retr(NULL,mapit);
  2155. for( ; ; )
  2156. {
  2157. bl = (struct block_list*)dbi_next(mapit->dbi);
  2158. if( bl == NULL )
  2159. break;// end
  2160. if( MAPIT_MATCHES(mapit,bl) )
  2161. break;// found a match
  2162. // try next
  2163. }
  2164. return bl;
  2165. }
  2166. /// Returns the previous block_list that matches the description.
  2167. /// Returns NULL if not found.
  2168. ///
  2169. /// @param mapit Iterator
  2170. /// @return previous block_list or NULL
  2171. struct block_list* mapit_prev(struct s_mapiterator* mapit)
  2172. {
  2173. struct block_list* bl;
  2174. nullpo_retr(NULL,mapit);
  2175. for( ; ; )
  2176. {
  2177. bl = (struct block_list*)dbi_prev(mapit->dbi);
  2178. if( bl == NULL )
  2179. break;// end
  2180. if( MAPIT_MATCHES(mapit,bl) )
  2181. break;// found a match
  2182. // try prev
  2183. }
  2184. return bl;
  2185. }
  2186. /// Returns true if the current block_list exists in the database.
  2187. ///
  2188. /// @param mapit Iterator
  2189. /// @return true if it exists
  2190. bool mapit_exists(struct s_mapiterator* mapit)
  2191. {
  2192. nullpo_retr(false,mapit);
  2193. return dbi_exists(mapit->dbi);
  2194. }
  2195. /*==========================================
  2196. * Add npc-bl to id_db, basically register npc to map
  2197. *------------------------------------------*/
  2198. bool map_addnpc(int16 m,struct npc_data *nd)
  2199. {
  2200. nullpo_ret(nd);
  2201. if( m < 0 || m >= map_num )
  2202. return false;
  2203. if( map[m].npc_num == MAX_NPC_PER_MAP )
  2204. {
  2205. ShowWarning("too many NPCs in one map %s\n",map[m].name);
  2206. return false;
  2207. }
  2208. map[m].npc[map[m].npc_num]=nd;
  2209. map[m].npc_num++;
  2210. idb_put(id_db,nd->bl.id,nd);
  2211. return true;
  2212. }
  2213. /*==========================================
  2214. * Add an instance map
  2215. *------------------------------------------*/
  2216. int map_addinstancemap(const char *name, unsigned short instance_id)
  2217. {
  2218. int src_m = map_mapname2mapid(name);
  2219. int dst_m = -1, i;
  2220. char iname[MAP_NAME_LENGTH];
  2221. size_t num_cell, size;
  2222. if(src_m < 0)
  2223. return -1;
  2224. if(strlen(name) > 20) {
  2225. // against buffer overflow
  2226. ShowError("map_addisntancemap: can't add long map name \"%s\"\n", name);
  2227. return -2;
  2228. }
  2229. for(i = instance_start; i < MAX_MAP_PER_SERVER; i++) {
  2230. if(!map[i].name[0])
  2231. break;
  2232. }
  2233. if(i < map_num) // Destination map value overwrites another
  2234. dst_m = i;
  2235. else if(i < MAX_MAP_PER_SERVER) // Destination map value increments to new map
  2236. dst_m = map_num++;
  2237. else {
  2238. // Out of bounds
  2239. ShowError("map_addinstancemap failed. map_num(%d) > map_max(%d)\n",map_num, MAX_MAP_PER_SERVER);
  2240. return -3;
  2241. }
  2242. // Copy the map
  2243. memcpy(&map[dst_m], &map[src_m], sizeof(struct map_data));
  2244. strcpy(iname,name);
  2245. // Alter the name
  2246. // Due to this being custom we only worry about preserving as many characters as necessary for accurate map distinguishing
  2247. // This also allows us to maintain complete independence with main map functions
  2248. if((strchr(iname,'@') == NULL) && strlen(iname) > 8) {
  2249. memmove(iname, iname+(strlen(iname)-9), strlen(iname));
  2250. snprintf(map[dst_m].name, sizeof(map[dst_m].name),"%hu#%s", instance_id, iname);
  2251. } else
  2252. snprintf(map[dst_m].name, sizeof(map[dst_m].name),"%.3hu%s", instance_id, iname);
  2253. map[dst_m].name[MAP_NAME_LENGTH-1] = '\0';
  2254. // Mimic questinfo
  2255. if( map[src_m].qi_count ) {
  2256. map[dst_m].qi_count = map[src_m].qi_count;
  2257. CREATE( map[dst_m].qi_data, struct questinfo, map[dst_m].qi_count );
  2258. memcpy( map[dst_m].qi_data, map[src_m].qi_data, map[dst_m].qi_count * sizeof(struct questinfo) );
  2259. }
  2260. map[dst_m].m = dst_m;
  2261. map[dst_m].instance_id = instance_id;
  2262. map[dst_m].instance_src_map = src_m;
  2263. map[dst_m].users = 0;
  2264. memset(map[dst_m].npc, 0, sizeof(map[dst_m].npc));
  2265. map[dst_m].npc_num = 0;
  2266. // Reallocate cells
  2267. num_cell = map[dst_m].xs * map[dst_m].ys;
  2268. CREATE( map[dst_m].cell, struct mapcell, num_cell );
  2269. memcpy( map[dst_m].cell, map[src_m].cell, num_cell * sizeof(struct mapcell) );
  2270. size = map[dst_m].bxs * map[dst_m].bys * sizeof(struct block_list*);
  2271. map[dst_m].block = (struct block_list **)aCalloc(1,size);
  2272. map[dst_m].block_mob = (struct block_list **)aCalloc(1,size);
  2273. map[dst_m].index = mapindex_addmap(-1, map[dst_m].name);
  2274. map[dst_m].channel = NULL;
  2275. map[dst_m].mob_delete_timer = INVALID_TIMER;
  2276. map_addmap2db(&map[dst_m]);
  2277. return dst_m;
  2278. }
  2279. /*==========================================
  2280. * Set player to save point when they leave
  2281. *------------------------------------------*/
  2282. static int map_instancemap_leave(struct block_list *bl, va_list ap)
  2283. {
  2284. struct map_session_data* sd;
  2285. nullpo_retr(0, bl);
  2286. nullpo_retr(0, sd = (struct map_session_data *)bl);
  2287. pc_setpos(sd, sd->status.save_point.map, sd->status.save_point.x, sd->status.save_point.y, CLR_TELEPORT);
  2288. return 1;
  2289. }
  2290. /*==========================================
  2291. * Remove all units from instance
  2292. *------------------------------------------*/
  2293. static int map_instancemap_clean(struct block_list *bl, va_list ap)
  2294. {
  2295. nullpo_retr(0, bl);
  2296. switch(bl->type) {
  2297. /*case BL_PC:
  2298. // BL_PET, BL_HOM, BL_MER, and BL_ELEM are moved when BL_PC warped out in map_instancemap_leave
  2299. map_quit((struct map_session_data *) bl);
  2300. break;*/
  2301. case BL_NPC:
  2302. npc_unload((struct npc_data *)bl,true);
  2303. break;
  2304. case BL_MOB:
  2305. unit_free(bl,CLR_OUTSIGHT);
  2306. break;
  2307. case BL_ITEM:
  2308. map_clearflooritem(bl);
  2309. break;
  2310. case BL_SKILL:
  2311. skill_delunit((struct skill_unit *) bl);
  2312. break;
  2313. }
  2314. return 1;
  2315. }
  2316. static void map_free_questinfo(int m);
  2317. /*==========================================
  2318. * Deleting an instance map
  2319. *------------------------------------------*/
  2320. int map_delinstancemap(int m)
  2321. {
  2322. if(m < 0 || !map[m].instance_id)
  2323. return 0;
  2324. // Kick everyone out
  2325. map_foreachinmap(map_instancemap_leave, m, BL_PC);
  2326. // Do the unit cleanup
  2327. map_foreachinmap(map_instancemap_clean, m, BL_ALL);
  2328. if( map[m].mob_delete_timer != INVALID_TIMER )
  2329. delete_timer(map[m].mob_delete_timer, map_removemobs_timer);
  2330. // Free memory
  2331. aFree(map[m].cell);
  2332. aFree(map[m].block);
  2333. aFree(map[m].block_mob);
  2334. map_free_questinfo(m);
  2335. mapindex_removemap( map[m].index );
  2336. map_removemapdb(&map[m]);
  2337. memset(&map[m], 0x00, sizeof(map[0]));
  2338. map[m].mob_delete_timer = INVALID_TIMER;
  2339. return 1;
  2340. }
  2341. /*=========================================
  2342. * Dynamic Mobs [Wizputer]
  2343. *-----------------------------------------*/
  2344. // Stores the spawn data entry in the mob list.
  2345. // Returns the index of successful, or -1 if the list was full.
  2346. int map_addmobtolist(unsigned short m, struct spawn_data *spawn)
  2347. {
  2348. size_t i;
  2349. ARR_FIND( 0, MAX_MOB_LIST_PER_MAP, i, map[m].moblist[i] == NULL );
  2350. if( i < MAX_MOB_LIST_PER_MAP )
  2351. {
  2352. map[m].moblist[i] = spawn;
  2353. return i;
  2354. }
  2355. return -1;
  2356. }
  2357. void map_spawnmobs(int16 m)
  2358. {
  2359. int i, k=0;
  2360. if (map[m].mob_delete_timer != INVALID_TIMER)
  2361. { //Mobs have not been removed yet [Skotlex]
  2362. delete_timer(map[m].mob_delete_timer, map_removemobs_timer);
  2363. map[m].mob_delete_timer = INVALID_TIMER;
  2364. return;
  2365. }
  2366. for(i=0; i<MAX_MOB_LIST_PER_MAP; i++)
  2367. if(map[m].moblist[i]!=NULL)
  2368. {
  2369. k+=map[m].moblist[i]->num;
  2370. npc_parse_mob2(map[m].moblist[i]);
  2371. }
  2372. if (battle_config.etc_log && k > 0)
  2373. {
  2374. ShowStatus("Map %s: Spawned '"CL_WHITE"%d"CL_RESET"' mobs.\n",map[m].name, k);
  2375. }
  2376. }
  2377. int map_removemobs_sub(struct block_list *bl, va_list ap)
  2378. {
  2379. struct mob_data *md = (struct mob_data *)bl;
  2380. nullpo_ret(md);
  2381. //When not to remove mob:
  2382. // doesn't respawn and is not a slave
  2383. if( !md->spawn && !md->master_id )
  2384. return 0;
  2385. // respawn data is not in cache
  2386. if( md->spawn && !md->spawn->state.dynamic )
  2387. return 0;
  2388. // hasn't spawned yet
  2389. if( md->spawn_timer != INVALID_TIMER )
  2390. return 0;
  2391. // is damaged and mob_remove_damaged is off
  2392. if( !battle_config.mob_remove_damaged && md->status.hp < md->status.max_hp )
  2393. return 0;
  2394. // is a mvp
  2395. if( md->db->mexp > 0 )
  2396. return 0;
  2397. unit_free(&md->bl,CLR_OUTSIGHT);
  2398. return 1;
  2399. }
  2400. int map_removemobs_timer(int tid, unsigned int tick, int id, intptr_t data)
  2401. {
  2402. int count;
  2403. const int16 m = id;
  2404. if (m < 0 || m >= MAX_MAP_PER_SERVER)
  2405. { //Incorrect map id!
  2406. ShowError("map_removemobs_timer error: timer %d points to invalid map %d\n",tid, m);
  2407. return 0;
  2408. }
  2409. if (map[m].mob_delete_timer != tid)
  2410. { //Incorrect timer call!
  2411. ShowError("map_removemobs_timer mismatch: %d != %d (map %s)\n",map[m].mob_delete_timer, tid, map[m].name);
  2412. return 0;
  2413. }
  2414. map[m].mob_delete_timer = INVALID_TIMER;
  2415. if (map[m].users > 0) //Map not empty!
  2416. return 1;
  2417. count = map_foreachinmap(map_removemobs_sub, m, BL_MOB);
  2418. if (battle_config.etc_log && count > 0)
  2419. ShowStatus("Map %s: Removed '"CL_WHITE"%d"CL_RESET"' mobs.\n",map[m].name, count);
  2420. return 1;
  2421. }
  2422. void map_removemobs(int16 m)
  2423. {
  2424. if (map[m].mob_delete_timer != INVALID_TIMER) // should never happen
  2425. return; //Mobs are already scheduled for removal
  2426. // Don't remove mobs on instance map
  2427. if (map[m].instance_id)
  2428. return;
  2429. map[m].mob_delete_timer = add_timer(gettick()+battle_config.mob_remove_delay, map_removemobs_timer, m, 0);
  2430. }
  2431. /*==========================================
  2432. * Check for map_name from map_id
  2433. *------------------------------------------*/
  2434. const char* map_mapid2mapname(int m)
  2435. {
  2436. if (map[m].instance_id) { // Instance map check
  2437. struct instance_data *im = &instance_data[map[m].instance_id];
  2438. if (!im) // This shouldn't happen but if it does give them the map we intended to give
  2439. return map[m].name;
  2440. else {
  2441. uint8 i;
  2442. for (i = 0; i < im->cnt_map; i++) { // Loop to find the src map we want
  2443. if (im->map[i]->m == m)
  2444. return map[im->map[i]->src_m].name;
  2445. }
  2446. }
  2447. }
  2448. return map[m].name;
  2449. }
  2450. /*==========================================
  2451. * Hookup, get map_id from map_name
  2452. *------------------------------------------*/
  2453. int16 map_mapname2mapid(const char* name)
  2454. {
  2455. unsigned short map_index;
  2456. map_index = mapindex_name2id(name);
  2457. if (!map_index)
  2458. return -1;
  2459. return map_mapindex2mapid(map_index);
  2460. }
  2461. /*==========================================
  2462. * Returns the map of the given mapindex. [Skotlex]
  2463. *------------------------------------------*/
  2464. int16 map_mapindex2mapid(unsigned short mapindex)
  2465. {
  2466. struct map_data *md=NULL;
  2467. if (!mapindex)
  2468. return -1;
  2469. md = (struct map_data*)uidb_get(map_db,(unsigned int)mapindex);
  2470. if(md==NULL || md->cell==NULL)
  2471. return -1;
  2472. return md->m;
  2473. }
  2474. /*==========================================
  2475. * Switching Ip, port ? (like changing map_server) get ip/port from map_name
  2476. *------------------------------------------*/
  2477. int map_mapname2ipport(unsigned short name, uint32* ip, uint16* port)
  2478. {
  2479. struct map_data_other_server *mdos;
  2480. mdos = (struct map_data_other_server*)uidb_get(map_db,(unsigned int)name);
  2481. if(mdos==NULL || mdos->cell) //If gat isn't null, this is a local map.
  2482. return -1;
  2483. *ip=mdos->ip;
  2484. *port=mdos->port;
  2485. return 0;
  2486. }
  2487. /*==========================================
  2488. * Checks if both dirs point in the same direction.
  2489. *------------------------------------------*/
  2490. int map_check_dir(int s_dir,int t_dir)
  2491. {
  2492. if(s_dir == t_dir)
  2493. return 0;
  2494. switch(s_dir) {
  2495. case 0: if(t_dir == 7 || t_dir == 1 || t_dir == 0) return 0; break;
  2496. case 1: if(t_dir == 0 || t_dir == 2 || t_dir == 1) return 0; break;
  2497. case 2: if(t_dir == 1 || t_dir == 3 || t_dir == 2) return 0; break;
  2498. case 3: if(t_dir == 2 || t_dir == 4 || t_dir == 3) return 0; break;
  2499. case 4: if(t_dir == 3 || t_dir == 5 || t_dir == 4) return 0; break;
  2500. case 5: if(t_dir == 4 || t_dir == 6 || t_dir == 5) return 0; break;
  2501. case 6: if(t_dir == 5 || t_dir == 7 || t_dir == 6) return 0; break;
  2502. case 7: if(t_dir == 6 || t_dir == 0 || t_dir == 7) return 0; break;
  2503. }
  2504. return 1;
  2505. }
  2506. /*==========================================
  2507. * Returns the direction of the given cell, relative to 'src'
  2508. *------------------------------------------*/
  2509. uint8 map_calc_dir(struct block_list* src, int16 x, int16 y)
  2510. {
  2511. uint8 dir = 0;
  2512. nullpo_ret(src);
  2513. dir = map_calc_dir_xy(src->x, src->y, x, y, unit_getdir(src));
  2514. return dir;
  2515. }
  2516. /*==========================================
  2517. * Returns the direction of the given cell, relative to source cell
  2518. * Use this if you don't have a block list available to check against
  2519. *------------------------------------------*/
  2520. uint8 map_calc_dir_xy(int16 srcx, int16 srcy, int16 x, int16 y, uint8 srcdir) {
  2521. uint8 dir = 0;
  2522. int dx, dy;
  2523. dx = x-srcx;
  2524. dy = y-srcy;
  2525. if( dx == 0 && dy == 0 )
  2526. { // both are standing on the same spot
  2527. // aegis-style, makes knockback default to the left
  2528. // athena-style, makes knockback default to behind 'src'
  2529. dir = (battle_config.knockback_left ? 6 : srcdir);
  2530. }
  2531. else if( dx >= 0 && dy >=0 )
  2532. { // upper-right
  2533. if( dx >= dy*3 ) dir = 6; // right
  2534. else if( dx*3 < dy ) dir = 0; // up
  2535. else dir = 7; // up-right
  2536. }
  2537. else if( dx >= 0 && dy <= 0 )
  2538. { // lower-right
  2539. if( dx >= -dy*3 ) dir = 6; // right
  2540. else if( dx*3 < -dy ) dir = 4; // down
  2541. else dir = 5; // down-right
  2542. }
  2543. else if( dx <= 0 && dy <= 0 )
  2544. { // lower-left
  2545. if( dx*3 >= dy ) dir = 4; // down
  2546. else if( dx < dy*3 ) dir = 2; // left
  2547. else dir = 3; // down-left
  2548. }
  2549. else
  2550. { // upper-left
  2551. if( -dx*3 <= dy ) dir = 0; // up
  2552. else if( -dx > dy*3 ) dir = 2; // left
  2553. else dir = 1; // up-left
  2554. }
  2555. return dir;
  2556. }
  2557. /*==========================================
  2558. * Randomizes target cell x,y to a random walkable cell that
  2559. * has the same distance from object as given coordinates do. [Skotlex]
  2560. *------------------------------------------*/
  2561. int map_random_dir(struct block_list *bl, int16 *x, int16 *y)
  2562. {
  2563. short xi = *x-bl->x;
  2564. short yi = *y-bl->y;
  2565. short i=0;
  2566. int dist2 = xi*xi + yi*yi;
  2567. short dist = (short)sqrt((float)dist2);
  2568. if (dist < 1) dist =1;
  2569. do {
  2570. short j = 1 + 2*(rnd()%4); //Pick a random diagonal direction
  2571. short segment = 1+(rnd()%dist); //Pick a random interval from the whole vector in that direction
  2572. xi = bl->x + segment*dirx[j];
  2573. segment = (short)sqrt((float)(dist2 - segment*segment)); //The complement of the previously picked segment
  2574. yi = bl->y + segment*diry[j];
  2575. } while (
  2576. (map_getcell(bl->m,xi,yi,CELL_CHKNOPASS) || !path_search(NULL,bl->m,bl->x,bl->y,xi,yi,1,CELL_CHKNOREACH))
  2577. && (++i)<100 );
  2578. if (i < 100) {
  2579. *x = xi;
  2580. *y = yi;
  2581. return 1;
  2582. }
  2583. return 0;
  2584. }
  2585. // gat system
  2586. inline static struct mapcell map_gat2cell(int gat) {
  2587. struct mapcell cell;
  2588. memset(&cell,0,sizeof(struct mapcell));
  2589. switch( gat ) {
  2590. case 0: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // walkable ground
  2591. case 1: cell.walkable = 0; cell.shootable = 0; cell.water = 0; break; // non-walkable ground
  2592. case 2: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // ???
  2593. case 3: cell.walkable = 1; cell.shootable = 1; cell.water = 1; break; // walkable water
  2594. case 4: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // ???
  2595. case 5: cell.walkable = 0; cell.shootable = 1; cell.water = 0; break; // gap (snipable)
  2596. case 6: cell.walkable = 1; cell.shootable = 1; cell.water = 0; break; // ???
  2597. default:
  2598. ShowWarning("map_gat2cell: unrecognized gat type '%d'\n", gat);
  2599. break;
  2600. }
  2601. return cell;
  2602. }
  2603. static int map_cell2gat(struct mapcell cell)
  2604. {
  2605. if( cell.walkable == 1 && cell.shootable == 1 && cell.water == 0 ) return 0;
  2606. if( cell.walkable == 0 && cell.shootable == 0 && cell.water == 0 ) return 1;
  2607. if( cell.walkable == 1 && cell.shootable == 1 && cell.water == 1 ) return 3;
  2608. if( cell.walkable == 0 && cell.shootable == 1 && cell.water == 0 ) return 5;
  2609. ShowWarning("map_cell2gat: cell has no matching gat type\n");
  2610. return 1; // default to 'wall'
  2611. }
  2612. /*==========================================
  2613. * Confirm if celltype in (m,x,y) match the one given in cellchk
  2614. *------------------------------------------*/
  2615. int map_getcell(int16 m,int16 x,int16 y,cell_chk cellchk)
  2616. {
  2617. return (m < 0 || m >= MAX_MAP_PER_SERVER) ? 0 : map_getcellp(&map[m],x,y,cellchk);
  2618. }
  2619. int map_getcellp(struct map_data* m,int16 x,int16 y,cell_chk cellchk)
  2620. {
  2621. struct mapcell cell;
  2622. nullpo_ret(m);
  2623. //NOTE: this intentionally overrides the last row and column
  2624. if(x<0 || x>=m->xs-1 || y<0 || y>=m->ys-1)
  2625. return( cellchk == CELL_CHKNOPASS );
  2626. cell = m->cell[x + y*m->xs];
  2627. switch(cellchk)
  2628. {
  2629. // gat type retrieval
  2630. case CELL_GETTYPE:
  2631. return map_cell2gat(cell);
  2632. // base gat type checks
  2633. case CELL_CHKWALL:
  2634. return (!cell.walkable && !cell.shootable);
  2635. case CELL_CHKWATER:
  2636. return (cell.water);
  2637. case CELL_CHKCLIFF:
  2638. return (!cell.walkable && cell.shootable);
  2639. // base cell type checks
  2640. case CELL_CHKNPC:
  2641. return (cell.npc);
  2642. case CELL_CHKBASILICA:
  2643. return (cell.basilica);
  2644. case CELL_CHKLANDPROTECTOR:
  2645. return (cell.landprotector);
  2646. case CELL_CHKNOVENDING:
  2647. return (cell.novending);
  2648. case CELL_CHKNOCHAT:
  2649. return (cell.nochat);
  2650. case CELL_CHKMAELSTROM:
  2651. return (cell.maelstrom);
  2652. case CELL_CHKICEWALL:
  2653. return (cell.icewall);
  2654. // special checks
  2655. case CELL_CHKPASS:
  2656. #ifdef CELL_NOSTACK
  2657. if (cell.cell_bl >= battle_config.custom_cell_stack_limit) return 0;
  2658. #endif
  2659. case CELL_CHKREACH:
  2660. return (cell.walkable);
  2661. case CELL_CHKNOPASS:
  2662. #ifdef CELL_NOSTACK
  2663. if (cell.cell_bl >= battle_config.custom_cell_stack_limit) return 1;
  2664. #endif
  2665. case CELL_CHKNOREACH:
  2666. return (!cell.walkable);
  2667. case CELL_CHKSTACK:
  2668. #ifdef CELL_NOSTACK
  2669. return (cell.cell_bl >= battle_config.custom_cell_stack_limit);
  2670. #else
  2671. return 0;
  2672. #endif
  2673. default:
  2674. return 0;
  2675. }
  2676. }
  2677. /*==========================================
  2678. * Change the type/flags of a map cell
  2679. * 'cell' - which flag to modify
  2680. * 'flag' - true = on, false = off
  2681. *------------------------------------------*/
  2682. void map_setcell(int16 m, int16 x, int16 y, cell_t cell, bool flag)
  2683. {
  2684. int j;
  2685. if( m < 0 || m >= map_num || x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys )
  2686. return;
  2687. j = x + y*map[m].xs;
  2688. switch( cell ) {
  2689. case CELL_WALKABLE: map[m].cell[j].walkable = flag; break;
  2690. case CELL_SHOOTABLE: map[m].cell[j].shootable = flag; break;
  2691. case CELL_WATER: map[m].cell[j].water = flag; break;
  2692. case CELL_NPC: map[m].cell[j].npc = flag; break;
  2693. case CELL_BASILICA: map[m].cell[j].basilica = flag; break;
  2694. case CELL_LANDPROTECTOR: map[m].cell[j].landprotector = flag; break;
  2695. case CELL_NOVENDING: map[m].cell[j].novending = flag; break;
  2696. case CELL_NOCHAT: map[m].cell[j].nochat = flag; break;
  2697. case CELL_MAELSTROM: map[m].cell[j].maelstrom = flag; break;
  2698. case CELL_ICEWALL: map[m].cell[j].icewall = flag; break;
  2699. default:
  2700. ShowWarning("map_setcell: invalid cell type '%d'\n", (int)cell);
  2701. break;
  2702. }
  2703. }
  2704. void map_setgatcell(int16 m, int16 x, int16 y, int gat)
  2705. {
  2706. int j;
  2707. struct mapcell cell;
  2708. if( m < 0 || m >= map_num || x < 0 || x >= map[m].xs || y < 0 || y >= map[m].ys )
  2709. return;
  2710. j = x + y*map[m].xs;
  2711. cell = map_gat2cell(gat);
  2712. map[m].cell[j].walkable = cell.walkable;
  2713. map[m].cell[j].shootable = cell.shootable;
  2714. map[m].cell[j].water = cell.water;
  2715. }
  2716. /*==========================================
  2717. * Invisible Walls
  2718. *------------------------------------------*/
  2719. static DBMap* iwall_db;
  2720. void map_iwall_nextxy(int16 x, int16 y, int8 dir, int pos, int16 *x1, int16 *y1)
  2721. {
  2722. if( dir == 0 || dir == 4 )
  2723. *x1 = x; // Keep X
  2724. else if( dir > 0 && dir < 4 )
  2725. *x1 = x - pos; // Going left
  2726. else
  2727. *x1 = x + pos; // Going right
  2728. if( dir == 2 || dir == 6 )
  2729. *y1 = y;
  2730. else if( dir > 2 && dir < 6 )
  2731. *y1 = y - pos;
  2732. else
  2733. *y1 = y + pos;
  2734. }
  2735. bool map_iwall_set(int16 m, int16 x, int16 y, int size, int8 dir, bool shootable, const char* wall_name)
  2736. {
  2737. struct iwall_data *iwall;
  2738. int i;
  2739. int16 x1 = 0, y1 = 0;
  2740. if( size < 1 || !wall_name )
  2741. return false;
  2742. if( (iwall = (struct iwall_data *)strdb_get(iwall_db, wall_name)) != NULL )
  2743. return false; // Already Exists
  2744. if( map_getcell(m, x, y, CELL_CHKNOREACH) )
  2745. return false; // Starting cell problem
  2746. CREATE(iwall, struct iwall_data, 1);
  2747. iwall->m = m;
  2748. iwall->x = x;
  2749. iwall->y = y;
  2750. iwall->size = size;
  2751. iwall->dir = dir;
  2752. iwall->shootable = shootable;
  2753. safestrncpy(iwall->wall_name, wall_name, sizeof(iwall->wall_name));
  2754. for( i = 0; i < size; i++ )
  2755. {
  2756. map_iwall_nextxy(x, y, dir, i, &x1, &y1);
  2757. if( map_getcell(m, x1, y1, CELL_CHKNOREACH) )
  2758. break; // Collision
  2759. map_setcell(m, x1, y1, CELL_WALKABLE, false);
  2760. map_setcell(m, x1, y1, CELL_SHOOTABLE, shootable);
  2761. clif_changemapcell(0, m, x1, y1, map_getcell(m, x1, y1, CELL_GETTYPE), ALL_SAMEMAP);
  2762. }
  2763. iwall->size = i;
  2764. strdb_put(iwall_db, iwall->wall_name, iwall);
  2765. map[m].iwall_num++;
  2766. return true;
  2767. }
  2768. void map_iwall_get(struct map_session_data *sd) {
  2769. struct iwall_data *iwall;
  2770. DBIterator* iter;
  2771. int16 x1, y1;
  2772. int i;
  2773. if( map[sd->bl.m].iwall_num < 1 )
  2774. return;
  2775. iter = db_iterator(iwall_db);
  2776. for( iwall = (struct iwall_data *)dbi_first(iter); dbi_exists(iter); iwall = (struct iwall_data *)dbi_next(iter) ) {
  2777. if( iwall->m != sd->bl.m )
  2778. continue;
  2779. for( i = 0; i < iwall->size; i++ ) {
  2780. map_iwall_nextxy(iwall->x, iwall->y, iwall->dir, i, &x1, &y1);
  2781. clif_changemapcell(sd->fd, iwall->m, x1, y1, map_getcell(iwall->m, x1, y1, CELL_GETTYPE), SELF);
  2782. }
  2783. }
  2784. dbi_destroy(iter);
  2785. }
  2786. void map_iwall_remove(const char *wall_name)
  2787. {
  2788. struct iwall_data *iwall;
  2789. int16 i, x1, y1;
  2790. if( (iwall = (struct iwall_data *)strdb_get(iwall_db, wall_name)) == NULL )
  2791. return; // Nothing to do
  2792. for( i = 0; i < iwall->size; i++ ) {
  2793. map_iwall_nextxy(iwall->x, iwall->y, iwall->dir, i, &x1, &y1);
  2794. map_setcell(iwall->m, x1, y1, CELL_SHOOTABLE, true);
  2795. map_setcell(iwall->m, x1, y1, CELL_WALKABLE, true);
  2796. clif_changemapcell(0, iwall->m, x1, y1, map_getcell(iwall->m, x1, y1, CELL_GETTYPE), ALL_SAMEMAP);
  2797. }
  2798. map[iwall->m].iwall_num--;
  2799. strdb_remove(iwall_db, iwall->wall_name);
  2800. }
  2801. /**
  2802. * @see DBCreateData
  2803. */
  2804. static DBData create_map_data_other_server(DBKey key, va_list args)
  2805. {
  2806. struct map_data_other_server *mdos;
  2807. unsigned short mapindex = (unsigned short)key.ui;
  2808. mdos=(struct map_data_other_server *)aCalloc(1,sizeof(struct map_data_other_server));
  2809. mdos->index = mapindex;
  2810. memcpy(mdos->name, mapindex_id2name(mapindex), MAP_NAME_LENGTH);
  2811. return db_ptr2data(mdos);
  2812. }
  2813. /*==========================================
  2814. * Add mapindex to db of another map server
  2815. *------------------------------------------*/
  2816. int map_setipport(unsigned short mapindex, uint32 ip, uint16 port)
  2817. {
  2818. struct map_data_other_server *mdos;
  2819. mdos= (struct map_data_other_server *)uidb_ensure(map_db,(unsigned int)mapindex, create_map_data_other_server);
  2820. if(mdos->cell) //Local map,Do nothing. Give priority to our own local maps over ones from another server. [Skotlex]
  2821. return 0;
  2822. if(ip == clif_getip() && port == clif_getport()) {
  2823. //That's odd, we received info that we are the ones with this map, but... we don't have it.
  2824. ShowFatalError("map_setipport : received info that this map-server SHOULD have map '%s', but it is not loaded.\n",mapindex_id2name(mapindex));
  2825. exit(EXIT_FAILURE);
  2826. }
  2827. mdos->ip = ip;
  2828. mdos->port = port;
  2829. return 1;
  2830. }
  2831. /**
  2832. * Delete all the other maps server management
  2833. * @see DBApply
  2834. */
  2835. int map_eraseallipport_sub(DBKey key, DBData *data, va_list va)
  2836. {
  2837. struct map_data_other_server *mdos = (struct map_data_other_server *)db_data2ptr(data);
  2838. if(mdos->cell == NULL) {
  2839. db_remove(map_db,key);
  2840. aFree(mdos);
  2841. }
  2842. return 0;
  2843. }
  2844. int map_eraseallipport(void)
  2845. {
  2846. map_db->foreach(map_db,map_eraseallipport_sub);
  2847. return 1;
  2848. }
  2849. /*==========================================
  2850. * Delete mapindex from db of another map server
  2851. *------------------------------------------*/
  2852. int map_eraseipport(unsigned short mapindex, uint32 ip, uint16 port)
  2853. {
  2854. struct map_data_other_server *mdos;
  2855. mdos = (struct map_data_other_server*)uidb_get(map_db,(unsigned int)mapindex);
  2856. if(!mdos || mdos->cell) //Map either does not exists or is a local map.
  2857. return 0;
  2858. if(mdos->ip==ip && mdos->port == port) {
  2859. uidb_remove(map_db,(unsigned int)mapindex);
  2860. aFree(mdos);
  2861. return 1;
  2862. }
  2863. return 0;
  2864. }
  2865. /*==========================================
  2866. * [Shinryo]: Init the mapcache
  2867. *------------------------------------------*/
  2868. static char *map_init_mapcache(FILE *fp)
  2869. {
  2870. size_t size = 0;
  2871. char *buffer;
  2872. // No file open? Return..
  2873. nullpo_ret(fp);
  2874. // Get file size
  2875. fseek(fp, 0, SEEK_END);
  2876. size = ftell(fp);
  2877. fseek(fp, 0, SEEK_SET);
  2878. // Allocate enough space
  2879. CREATE(buffer, char, size);
  2880. // No memory? Return..
  2881. nullpo_ret(buffer);
  2882. // Read file into buffer..
  2883. if(fread(buffer, 1, size, fp) != size) {
  2884. ShowError("map_init_mapcache: Could not read entire mapcache file\n");
  2885. return NULL;
  2886. }
  2887. return buffer;
  2888. }
  2889. /*==========================================
  2890. * Map cache reading
  2891. * [Shinryo]: Optimized some behaviour to speed this up
  2892. *==========================================*/
  2893. int map_readfromcache(struct map_data *m, char *buffer, char *decode_buffer)
  2894. {
  2895. int i;
  2896. struct map_cache_main_header *header = (struct map_cache_main_header *)buffer;
  2897. struct map_cache_map_info *info = NULL;
  2898. char *p = buffer + sizeof(struct map_cache_main_header);
  2899. for(i = 0; i < header->map_count; i++) {
  2900. info = (struct map_cache_map_info *)p;
  2901. if( strcmp(m->name, info->name) == 0 )
  2902. break; // Map found
  2903. // Jump to next entry..
  2904. p += sizeof(struct map_cache_map_info) + info->len;
  2905. }
  2906. if( info && i < header->map_count ) {
  2907. unsigned long size, xy;
  2908. if( info->xs <= 0 || info->ys <= 0 )
  2909. return 0;// Invalid
  2910. m->xs = info->xs;
  2911. m->ys = info->ys;
  2912. size = (unsigned long)info->xs*(unsigned long)info->ys;
  2913. if(size > MAX_MAP_SIZE) {
  2914. ShowWarning("map_readfromcache: %s exceeded MAX_MAP_SIZE of %d\n", info->name, MAX_MAP_SIZE);
  2915. return 0; // Say not found to remove it from list.. [Shinryo]
  2916. }
  2917. // TO-DO: Maybe handle the scenario, if the decoded buffer isn't the same size as expected? [Shinryo]
  2918. decode_zip(decode_buffer, &size, p+sizeof(struct map_cache_map_info), info->len);
  2919. CREATE(m->cell, struct mapcell, size);
  2920. for( xy = 0; xy < size; ++xy )
  2921. m->cell[xy] = map_gat2cell(decode_buffer[xy]);
  2922. return 1;
  2923. }
  2924. return 0; // Not found
  2925. }
  2926. int map_addmap(char* mapname)
  2927. {
  2928. if( strcmpi(mapname,"clear")==0 )
  2929. {
  2930. map_num = 0;
  2931. instance_start = 0;
  2932. return 0;
  2933. }
  2934. if( map_num >= MAX_MAP_PER_SERVER - 1 )
  2935. {
  2936. ShowError("Could not add map '"CL_WHITE"%s"CL_RESET"', the limit of maps has been reached.\n",mapname);
  2937. return 1;
  2938. }
  2939. mapindex_getmapname(mapname, map[map_num].name);
  2940. map_num++;
  2941. return 0;
  2942. }
  2943. static void map_delmapid(int id)
  2944. {
  2945. ShowNotice("Removing map [ %s ] from maplist"CL_CLL"\n",map[id].name);
  2946. memmove(map+id, map+id+1, sizeof(map[0])*(map_num-id-1));
  2947. map_num--;
  2948. }
  2949. int map_delmap(char* mapname)
  2950. {
  2951. int i;
  2952. char map_name[MAP_NAME_LENGTH];
  2953. if (strcmpi(mapname, "all") == 0) {
  2954. map_num = 0;
  2955. return 0;
  2956. }
  2957. mapindex_getmapname(mapname, map_name);
  2958. for(i = 0; i < map_num; i++) {
  2959. if (strcmp(map[i].name, map_name) == 0) {
  2960. map_delmapid(i);
  2961. return 1;
  2962. }
  2963. }
  2964. return 0;
  2965. }
  2966. /// Initializes map flags and adjusts them depending on configuration.
  2967. void map_flags_init(void)
  2968. {
  2969. int i;
  2970. for( i = 0; i < map_num; i++ )
  2971. {
  2972. // mapflags
  2973. memset(&map[i].flag, 0, sizeof(map[i].flag));
  2974. // additional mapflag data
  2975. map[i].zone = 0; // restricted mapflag zone
  2976. map[i].nocommand = 0; // nocommand mapflag level
  2977. map[i].adjust.bexp = 100; // per map base exp multiplicator
  2978. map[i].adjust.jexp = 100; // per map job exp multiplicator
  2979. memset(map[i].drop_list, 0, sizeof(map[i].drop_list)); // pvp nightmare drop list
  2980. // skill damage
  2981. #ifdef ADJUST_SKILL_DAMAGE
  2982. memset(&map[i].adjust.damage, 0, sizeof(map[i].adjust.damage));
  2983. if (map[i].skill_damage.count)
  2984. map_skill_damage_free(&map[i]);
  2985. #endif
  2986. // adjustments
  2987. if( battle_config.pk_mode )
  2988. map[i].flag.pvp = 1; // make all maps pvp for pk_mode [Valaris]
  2989. map_free_questinfo(i);
  2990. }
  2991. }
  2992. #define NO_WATER 1000000
  2993. /*
  2994. * Reads from the .rsw for each map
  2995. * Returns water height (or NO_WATER if file doesn't exist) or other error is encountered.
  2996. * Assumed path for file is data/mapname.rsw
  2997. * Credits to LittleWolf
  2998. */
  2999. int map_waterheight(char* mapname)
  3000. {
  3001. char fn[256];
  3002. char *rsw, *found;
  3003. //Look up for the rsw
  3004. sprintf(fn, "data\\%s.rsw", mapname);
  3005. found = grfio_find_file(fn);
  3006. if (found) strcpy(fn, found); // replace with real name
  3007. // read & convert fn
  3008. rsw = (char *) grfio_read (fn);
  3009. if (rsw)
  3010. { //Load water height from file
  3011. int wh = (int) *(float*)(rsw+166); //FIXME Casting between integer* and float* which have an incompatible binary data representation.
  3012. aFree(rsw);
  3013. return wh;
  3014. }
  3015. ShowWarning("Failed to find water level for (%s)\n", mapname, fn);
  3016. return NO_WATER;
  3017. }
  3018. /*==================================
  3019. * .GAT format
  3020. *----------------------------------*/
  3021. int map_readgat (struct map_data* m)
  3022. {
  3023. char filename[256];
  3024. uint8* gat;
  3025. int water_height;
  3026. size_t xy, off, num_cells;
  3027. sprintf(filename, "data\\%s.gat", m->name);
  3028. gat = (uint8 *) grfio_read(filename);
  3029. if (gat == NULL)
  3030. return 0;
  3031. m->xs = *(int32*)(gat+6);
  3032. m->ys = *(int32*)(gat+10);
  3033. num_cells = m->xs * m->ys;
  3034. CREATE(m->cell, struct mapcell, num_cells);
  3035. water_height = map_waterheight(m->name);
  3036. // Set cell properties
  3037. off = 14;
  3038. for( xy = 0; xy < num_cells; ++xy )
  3039. {
  3040. // read cell data
  3041. float height = *(float*)( gat + off );
  3042. uint32 type = *(uint32*)( gat + off + 16 );
  3043. off += 20;
  3044. if( type == 0 && water_height != NO_WATER && height > water_height )
  3045. type = 3; // Cell is 0 (walkable) but under water level, set to 3 (walkable water)
  3046. m->cell[xy] = map_gat2cell(type);
  3047. }
  3048. aFree(gat);
  3049. return 1;
  3050. }
  3051. /*======================================
  3052. * Add/Remove map to the map_db
  3053. *--------------------------------------*/
  3054. void map_addmap2db(struct map_data *m)
  3055. {
  3056. uidb_put(map_db, (unsigned int)m->index, m);
  3057. }
  3058. void map_removemapdb(struct map_data *m)
  3059. {
  3060. uidb_remove(map_db, (unsigned int)m->index);
  3061. }
  3062. /*======================================
  3063. * Initiate maps loading stage
  3064. *--------------------------------------*/
  3065. int map_readallmaps (void)
  3066. {
  3067. int i;
  3068. FILE* fp=NULL;
  3069. int maps_removed = 0;
  3070. // Has the uncompressed gat data of all maps, so just one allocation has to be made
  3071. char *map_cache_buffer[2] = {
  3072. NULL,
  3073. NULL
  3074. };
  3075. char map_cache_decode_buffer[MAX_MAP_SIZE];
  3076. if( enable_grf )
  3077. ShowStatus("Loading maps (using GRF files)...\n");
  3078. else {
  3079. char* mapcachefilepath[] = {
  3080. "db/"DBPATH"map_cache.dat",
  3081. "db/import/map_cache.dat"
  3082. };
  3083. for( i = 0; i < 2; i++ ){
  3084. ShowStatus( "Loading maps (using %s as map cache)...\n", mapcachefilepath[i] );
  3085. if( ( fp = fopen(mapcachefilepath[i], "rb") ) == NULL ){
  3086. if( i == 0 ){
  3087. ShowFatalError( "Unable to open map cache file "CL_WHITE"%s"CL_RESET"\n", mapcachefilepath[i] );
  3088. exit(EXIT_FAILURE); //No use launching server if maps can't be read.
  3089. }else{
  3090. ShowWarning( "Unable to open map cache file "CL_WHITE"%s"CL_RESET"\n", mapcachefilepath[i] );
  3091. break;
  3092. }
  3093. }
  3094. // Init mapcache data. [Shinryo]
  3095. map_cache_buffer[i] = map_init_mapcache(fp);
  3096. if( !map_cache_buffer[i] ) {
  3097. ShowFatalError( "Failed to initialize mapcache data (%s)..\n", mapcachefilepath );
  3098. exit(EXIT_FAILURE);
  3099. }
  3100. fclose(fp);
  3101. }
  3102. }
  3103. for(i = 0; i < map_num; i++) {
  3104. size_t size;
  3105. bool success = false;
  3106. unsigned short idx = 0;
  3107. if( enable_grf ){
  3108. // show progress
  3109. ShowStatus("Loading maps [%i/%i]: %s"CL_CLL"\r", i, map_num, map[i].name);
  3110. // try to load the map
  3111. success = map_readgat(&map[i]) != 0;
  3112. }else{
  3113. // try to load the map
  3114. // Read from import first, in case of override
  3115. if( map_cache_buffer[1] != NULL ){
  3116. success = map_readfromcache( &map[i], map_cache_buffer[1], map_cache_decode_buffer ) != 0;
  3117. }
  3118. // Nothing was found in import - try to find it in the main file
  3119. if( !success ){
  3120. success = map_readfromcache( &map[i], map_cache_buffer[0], map_cache_decode_buffer ) != 0;
  3121. }
  3122. }
  3123. // The map was not found - remove it
  3124. if( !(idx = mapindex_name2id(map[i].name)) || !success ){
  3125. map_delmapid(i);
  3126. maps_removed++;
  3127. i--;
  3128. continue;
  3129. }
  3130. map[i].index = idx;
  3131. if (uidb_get(map_db,(unsigned int)map[i].index) != NULL)
  3132. {
  3133. ShowWarning("Map %s already loaded!"CL_CLL"\n", map[i].name);
  3134. if (map[i].cell) {
  3135. aFree(map[i].cell);
  3136. map[i].cell = NULL;
  3137. }
  3138. map_delmapid(i);
  3139. maps_removed++;
  3140. i--;
  3141. continue;
  3142. }
  3143. map_addmap2db(&map[i]);
  3144. map[i].m = i;
  3145. memset(map[i].moblist, 0, sizeof(map[i].moblist)); //Initialize moblist [Skotlex]
  3146. map[i].mob_delete_timer = INVALID_TIMER; //Initialize timer [Skotlex]
  3147. map[i].bxs = (map[i].xs + BLOCK_SIZE - 1) / BLOCK_SIZE;
  3148. map[i].bys = (map[i].ys + BLOCK_SIZE - 1) / BLOCK_SIZE;
  3149. size = map[i].bxs * map[i].bys * sizeof(struct block_list*);
  3150. map[i].block = (struct block_list**)aCalloc(size, 1);
  3151. map[i].block_mob = (struct block_list**)aCalloc(size, 1);
  3152. }
  3153. // intialization and configuration-dependent adjustments of mapflags
  3154. map_flags_init();
  3155. if( !enable_grf ) {
  3156. // The cache isn't needed anymore, so free it. [Shinryo]
  3157. if( map_cache_buffer[1] != NULL ){
  3158. aFree(map_cache_buffer[1]);
  3159. }
  3160. aFree(map_cache_buffer[0]);
  3161. }
  3162. // finished map loading
  3163. ShowInfo("Successfully loaded '"CL_WHITE"%d"CL_RESET"' maps."CL_CLL"\n",map_num);
  3164. instance_start = map_num; // Next Map Index will be instances
  3165. if (maps_removed)
  3166. ShowNotice("Maps removed: '"CL_WHITE"%d"CL_RESET"'\n",maps_removed);
  3167. return 0;
  3168. }
  3169. ////////////////////////////////////////////////////////////////////////
  3170. static int map_ip_set = 0;
  3171. static int char_ip_set = 0;
  3172. /*==========================================
  3173. * Console Command Parser [Wizputer]
  3174. *------------------------------------------*/
  3175. int parse_console(const char* buf){
  3176. char type[64];
  3177. char command[64];
  3178. char mapname[64];
  3179. int16 x = 0;
  3180. int16 y = 0;
  3181. int n;
  3182. struct map_session_data sd;
  3183. memset(&sd, 0, sizeof(struct map_session_data));
  3184. strcpy(sd.status.name, "console");
  3185. if( ( n = sscanf(buf, "%63[^:]:%63[^:]:%63s %6hd %6hd[^\n]", type, command, mapname, &x, &y) ) < 5 ){
  3186. if( ( n = sscanf(buf, "%63[^:]:%63[^\n]", type, command) ) < 2 ) {
  3187. if((n = sscanf(buf, "%63[^\n]", type))<1) return -1; //nothing to do no arg
  3188. }
  3189. }
  3190. if( n != 5 ){ //end string and display
  3191. if( n < 2 ) {
  3192. ShowNotice("Type of command: '%s'\n", type);
  3193. command[0] = '\0';
  3194. mapname[0] = '\0';
  3195. }
  3196. else {
  3197. ShowNotice("Type of command: '%s' || Command: '%s'\n", type, command);
  3198. mapname[0] = '\0';
  3199. }
  3200. }
  3201. else
  3202. ShowNotice("Type of command: '%s' || Command: '%s' || Map: '%s' Coords: %d %d\n", type, command, mapname, x, y);
  3203. if(strcmpi("admin",type) == 0 ) {
  3204. if(strcmpi("map",command) == 0){
  3205. int16 m = map_mapname2mapid(mapname);
  3206. if( m < 0 ){
  3207. ShowWarning("Console: Unknown map.\n");
  3208. return 0;
  3209. }
  3210. sd.bl.m = m;
  3211. map_search_freecell(&sd.bl, m, &sd.bl.x, &sd.bl.y, -1, -1, 0);
  3212. if( x > 0 )
  3213. sd.bl.x = x;
  3214. if( y > 0 )
  3215. sd.bl.y = y;
  3216. ShowNotice("Now at: '%s' Coords: %d %d\n", mapname, x, y);
  3217. }
  3218. else if( !is_atcommand(sd.fd, &sd, command, 2) )
  3219. ShowInfo("Console: Invalid atcommand.\n");
  3220. }
  3221. else if( n == 2 && strcmpi("server", type) == 0 ){
  3222. if( strcmpi("shutdown", command) == 0 || strcmpi("exit", command) == 0 || strcmpi("quit", command) == 0 ){
  3223. runflag = 0;
  3224. }
  3225. }
  3226. else if( strcmpi("ers_report", type) == 0 ){
  3227. ers_report();
  3228. }
  3229. else if( strcmpi("help", type) == 0 ) {
  3230. ShowInfo("Available commands:\n");
  3231. ShowInfo("\t admin:@<atcommand> => Uses an atcommand. Do NOT use commands requiring an attached player.\n");
  3232. ShowInfo("\t admin:map:<map> <x> <y> => Changes the map from which console commands are executed.\n");
  3233. ShowInfo("\t server:shutdown => Stops the server.\n");
  3234. ShowInfo("\t ers_report => Displays database usage.\n");
  3235. }
  3236. return 0;
  3237. }
  3238. /*==========================================
  3239. * Read map server configuration files (conf/map_athena.conf...)
  3240. *------------------------------------------*/
  3241. int map_config_read(char *cfgName)
  3242. {
  3243. char line[1024], w1[32], w2[1024];
  3244. FILE *fp;
  3245. fp = fopen(cfgName,"r");
  3246. if( fp == NULL )
  3247. {
  3248. ShowError("Map configuration file not found at: %s\n", cfgName);
  3249. return 1;
  3250. }
  3251. while( fgets(line, sizeof(line), fp) )
  3252. {
  3253. char* ptr;
  3254. if( line[0] == '/' && line[1] == '/' )
  3255. continue;
  3256. if( (ptr = strstr(line, "//")) != NULL )
  3257. *ptr = '\n'; //Strip comments
  3258. if( sscanf(line, "%31[^:]: %1023[^\t\r\n]", w1, w2) < 2 )
  3259. continue;
  3260. //Strip trailing spaces
  3261. ptr = w2 + strlen(w2);
  3262. while (--ptr >= w2 && *ptr == ' ');
  3263. ptr++;
  3264. *ptr = '\0';
  3265. if(strcmpi(w1,"timestamp_format")==0)
  3266. safestrncpy(timestamp_format, w2, 20);
  3267. else if(strcmpi(w1,"stdout_with_ansisequence")==0)
  3268. stdout_with_ansisequence = config_switch(w2);
  3269. else if(strcmpi(w1,"console_silent")==0) {
  3270. msg_silent = atoi(w2);
  3271. if( msg_silent ) // only bother if its actually enabled
  3272. ShowInfo("Console Silent Setting: %d\n", atoi(w2));
  3273. } else if (strcmpi(w1, "userid")==0)
  3274. chrif_setuserid(w2);
  3275. else if (strcmpi(w1, "passwd") == 0)
  3276. chrif_setpasswd(w2);
  3277. else if (strcmpi(w1, "char_ip") == 0)
  3278. char_ip_set = chrif_setip(w2);
  3279. else if (strcmpi(w1, "char_port") == 0)
  3280. chrif_setport(atoi(w2));
  3281. else if (strcmpi(w1, "map_ip") == 0)
  3282. map_ip_set = clif_setip(w2);
  3283. else if (strcmpi(w1, "bind_ip") == 0)
  3284. clif_setbindip(w2);
  3285. else if (strcmpi(w1, "map_port") == 0) {
  3286. clif_setport(atoi(w2));
  3287. map_port = (atoi(w2));
  3288. } else if (strcmpi(w1, "map") == 0)
  3289. map_addmap(w2);
  3290. else if (strcmpi(w1, "delmap") == 0)
  3291. map_delmap(w2);
  3292. else if (strcmpi(w1, "npc") == 0)
  3293. npc_addsrcfile(w2, false);
  3294. else if (strcmpi(w1, "delnpc") == 0)
  3295. npc_delsrcfile(w2);
  3296. else if (strcmpi(w1, "autosave_time") == 0) {
  3297. autosave_interval = atoi(w2);
  3298. if (autosave_interval < 1) //Revert to default saving.
  3299. autosave_interval = DEFAULT_AUTOSAVE_INTERVAL;
  3300. else
  3301. autosave_interval *= 1000; //Pass from sec to ms
  3302. } else if (strcmpi(w1, "minsave_time") == 0) {
  3303. minsave_interval= atoi(w2);
  3304. if (minsave_interval < 1)
  3305. minsave_interval = 1;
  3306. } else if (strcmpi(w1, "save_settings") == 0)
  3307. save_settings = cap_value(atoi(w2),CHARSAVE_NONE,CHARSAVE_ALL);
  3308. else if (strcmpi(w1, "motd_txt") == 0)
  3309. strcpy(motd_txt, w2);
  3310. else if (strcmpi(w1, "help_txt") == 0)
  3311. strcpy(help_txt, w2);
  3312. else if (strcmpi(w1, "help2_txt") == 0)
  3313. strcpy(help2_txt, w2);
  3314. else if (strcmpi(w1, "charhelp_txt") == 0)
  3315. strcpy(charhelp_txt, w2);
  3316. else if(strcmpi(w1,"db_path") == 0)
  3317. safestrncpy(db_path,w2,ARRAYLENGTH(db_path));
  3318. else if (strcmpi(w1, "console") == 0) {
  3319. console = config_switch(w2);
  3320. if (console)
  3321. ShowNotice("Console Commands are enabled.\n");
  3322. } else if (strcmpi(w1, "enable_spy") == 0)
  3323. enable_spy = config_switch(w2);
  3324. else if (strcmpi(w1, "use_grf") == 0)
  3325. enable_grf = config_switch(w2);
  3326. else if (strcmpi(w1, "console_msg_log") == 0)
  3327. console_msg_log = atoi(w2);//[Ind]
  3328. else if (strcmpi(w1, "console_log_filepath") == 0)
  3329. safestrncpy(console_log_filepath, w2, sizeof(console_log_filepath));
  3330. else if (strcmpi(w1, "import") == 0)
  3331. map_config_read(w2);
  3332. else
  3333. ShowWarning("Unknown setting '%s' in file %s\n", w1, cfgName);
  3334. }
  3335. fclose(fp);
  3336. return 0;
  3337. }
  3338. void map_reloadnpc_sub(char *cfgName)
  3339. {
  3340. char line[1024], w1[1024], w2[1024];
  3341. FILE *fp;
  3342. fp = fopen(cfgName,"r");
  3343. if( fp == NULL )
  3344. {
  3345. ShowError("Map configuration file not found at: %s\n", cfgName);
  3346. return;
  3347. }
  3348. while( fgets(line, sizeof(line), fp) )
  3349. {
  3350. char* ptr;
  3351. if( line[0] == '/' && line[1] == '/' )
  3352. continue;
  3353. if( (ptr = strstr(line, "//")) != NULL )
  3354. *ptr = '\n'; //Strip comments
  3355. if( sscanf(line, "%1023[^:]: %1023[^\t\r\n]", w1, w2) < 2 )
  3356. continue;
  3357. //Strip trailing spaces
  3358. ptr = w2 + strlen(w2);
  3359. while (--ptr >= w2 && *ptr == ' ');
  3360. ptr++;
  3361. *ptr = '\0';
  3362. if (strcmpi(w1, "npc") == 0)
  3363. npc_addsrcfile(w2, false);
  3364. else if (strcmpi(w1, "delnpc") == 0)
  3365. npc_delsrcfile(w2);
  3366. else if (strcmpi(w1, "import") == 0)
  3367. map_reloadnpc_sub(w2);
  3368. else
  3369. ShowWarning("Unknown setting '%s' in file %s\n", w1, cfgName);
  3370. }
  3371. fclose(fp);
  3372. }
  3373. void map_reloadnpc(bool clear)
  3374. {
  3375. if (clear)
  3376. npc_addsrcfile("clear", false); // this will clear the current script list
  3377. #ifdef RENEWAL
  3378. map_reloadnpc_sub("npc/re/scripts_main.conf");
  3379. #else
  3380. map_reloadnpc_sub("npc/pre-re/scripts_main.conf");
  3381. #endif
  3382. }
  3383. int inter_config_read(char *cfgName)
  3384. {
  3385. char line[1024],w1[1024],w2[1024];
  3386. FILE *fp;
  3387. fp=fopen(cfgName,"r");
  3388. if(fp==NULL){
  3389. ShowError("File not found: %s\n",cfgName);
  3390. return 1;
  3391. }
  3392. while(fgets(line, sizeof(line), fp))
  3393. {
  3394. if(line[0] == '/' && line[1] == '/')
  3395. continue;
  3396. if( sscanf(line,"%1023[^:]: %1023[^\r\n]",w1,w2) < 2 )
  3397. continue;
  3398. #define RENEWALPREFIX "renewal-"
  3399. if (!strncmpi(w1, RENEWALPREFIX, strlen(RENEWALPREFIX))) {
  3400. #ifdef RENEWAL
  3401. // Copy the original name
  3402. safestrncpy(w1, w1 + strlen(RENEWALPREFIX), strlen(w1) - strlen(RENEWALPREFIX));
  3403. #else
  3404. // In Pre-Renewal the Renewal specific configurations can safely be ignored
  3405. continue;
  3406. #endif
  3407. }
  3408. #undef RENEWALPREFIX
  3409. if( strcmpi( w1, "buyingstore_db" ) == 0 )
  3410. strcpy( buyingstores_table, w2 );
  3411. else if( strcmpi( w1, "buyingstore_items_table" ) == 0 )
  3412. strcpy( buyingstore_items_table, w2 );
  3413. else if(strcmpi(w1,"item_table")==0)
  3414. strcpy(item_table,w2);
  3415. else if(strcmpi(w1,"item2_table")==0)
  3416. strcpy(item2_table,w2);
  3417. else if(strcmpi(w1,"mob_table")==0)
  3418. strcpy(mob_table,w2);
  3419. else if(strcmpi(w1,"mob2_table")==0)
  3420. strcpy(mob2_table,w2);
  3421. else if(strcmpi(w1,"mob_skill_table")==0)
  3422. strcpy(mob_skill_table,w2);
  3423. else if(strcmpi(w1,"mob_skill2_table")==0)
  3424. strcpy(mob_skill2_table,w2);
  3425. else if( strcmpi( w1, "item_cash_table" ) == 0 )
  3426. strcpy( item_cash_table, w2 );
  3427. else if( strcmpi( w1, "item_cash2_table" ) == 0 )
  3428. strcpy( item_cash2_table, w2 );
  3429. else if( strcmpi( w1, "vending_db" ) == 0 )
  3430. strcpy( vendings_table, w2 );
  3431. else if( strcmpi( w1, "vending_items_table" ) == 0 )
  3432. strcpy(vending_items_table, w2);
  3433. else if( strcmpi(w1, "roulette_table") == 0)
  3434. strcpy(roulette_table, w2);
  3435. else if (strcmpi(w1, "market_table") == 0)
  3436. strcpy(market_table, w2);
  3437. else if (strcmpi(w1, "sales_table") == 0)
  3438. strcpy(sales_table, w2);
  3439. else
  3440. //Map Server SQL DB
  3441. if(strcmpi(w1,"map_server_ip")==0)
  3442. strcpy(map_server_ip, w2);
  3443. else
  3444. if(strcmpi(w1,"map_server_port")==0)
  3445. map_server_port=atoi(w2);
  3446. else
  3447. if(strcmpi(w1,"map_server_id")==0)
  3448. strcpy(map_server_id, w2);
  3449. else
  3450. if(strcmpi(w1,"map_server_pw")==0)
  3451. strcpy(map_server_pw, w2);
  3452. else
  3453. if(strcmpi(w1,"map_server_db")==0)
  3454. strcpy(map_server_db, w2);
  3455. else
  3456. if(strcmpi(w1,"default_codepage")==0)
  3457. strcpy(default_codepage, w2);
  3458. else
  3459. if(strcmpi(w1,"use_sql_db")==0) {
  3460. db_use_sqldbs = config_switch(w2);
  3461. ShowStatus ("Using SQL dbs: %s\n",w2);
  3462. } else
  3463. if(strcmpi(w1,"log_db_ip")==0)
  3464. strcpy(log_db_ip, w2);
  3465. else
  3466. if(strcmpi(w1,"log_db_id")==0)
  3467. strcpy(log_db_id, w2);
  3468. else
  3469. if(strcmpi(w1,"log_db_pw")==0)
  3470. strcpy(log_db_pw, w2);
  3471. else
  3472. if(strcmpi(w1,"log_db_port")==0)
  3473. log_db_port = atoi(w2);
  3474. else
  3475. if(strcmpi(w1,"log_db_db")==0)
  3476. strcpy(log_db_db, w2);
  3477. else
  3478. if( mapreg_config_read(w1,w2) )
  3479. continue;
  3480. //support the import command, just like any other config
  3481. else
  3482. if(strcmpi(w1,"import")==0)
  3483. inter_config_read(w2);
  3484. }
  3485. fclose(fp);
  3486. return 0;
  3487. }
  3488. /*=======================================
  3489. * MySQL Init
  3490. *---------------------------------------*/
  3491. int map_sql_init(void)
  3492. {
  3493. // main db connection
  3494. mmysql_handle = Sql_Malloc();
  3495. qsmysql_handle = Sql_Malloc();
  3496. ShowInfo("Connecting to the Map DB Server....\n");
  3497. if( SQL_ERROR == Sql_Connect(mmysql_handle, map_server_id, map_server_pw, map_server_ip, map_server_port, map_server_db) ||
  3498. SQL_ERROR == Sql_Connect(qsmysql_handle, map_server_id, map_server_pw, map_server_ip, map_server_port, map_server_db) )
  3499. {
  3500. ShowError("Couldn't connect with uname='%s',passwd='%s',host='%s',port='%d',database='%s'\n",
  3501. map_server_id, map_server_pw, map_server_ip, map_server_port, map_server_db);
  3502. Sql_ShowDebug(mmysql_handle);
  3503. Sql_Free(mmysql_handle);
  3504. Sql_ShowDebug(qsmysql_handle);
  3505. Sql_Free(qsmysql_handle);
  3506. exit(EXIT_FAILURE);
  3507. }
  3508. ShowStatus("Connect success! (Map Server Connection)\n");
  3509. if( strlen(default_codepage) > 0 ) {
  3510. if ( SQL_ERROR == Sql_SetEncoding(mmysql_handle, default_codepage) )
  3511. Sql_ShowDebug(mmysql_handle);
  3512. if ( SQL_ERROR == Sql_SetEncoding(qsmysql_handle, default_codepage) )
  3513. Sql_ShowDebug(qsmysql_handle);
  3514. }
  3515. return 0;
  3516. }
  3517. int map_sql_close(void)
  3518. {
  3519. ShowStatus("Close Map DB Connection....\n");
  3520. Sql_Free(mmysql_handle);
  3521. Sql_Free(qsmysql_handle);
  3522. mmysql_handle = NULL;
  3523. qsmysql_handle = NULL;
  3524. #ifndef BETA_THREAD_TEST
  3525. if (log_config.sql_logs)
  3526. {
  3527. ShowStatus("Close Log DB Connection....\n");
  3528. Sql_Free(logmysql_handle);
  3529. logmysql_handle = NULL;
  3530. }
  3531. #endif
  3532. return 0;
  3533. }
  3534. int log_sql_init(void)
  3535. {
  3536. #ifndef BETA_THREAD_TEST
  3537. // log db connection
  3538. logmysql_handle = Sql_Malloc();
  3539. ShowInfo(""CL_WHITE"[SQL]"CL_RESET": Connecting to the Log Database "CL_WHITE"%s"CL_RESET" At "CL_WHITE"%s"CL_RESET"...\n",log_db_db,log_db_ip);
  3540. if ( SQL_ERROR == Sql_Connect(logmysql_handle, log_db_id, log_db_pw, log_db_ip, log_db_port, log_db_db) ){
  3541. ShowError("Couldn't connect with uname='%s',passwd='%s',host='%s',port='%d',database='%s'\n",
  3542. log_db_id, log_db_pw, log_db_ip, log_db_port, log_db_db);
  3543. Sql_ShowDebug(logmysql_handle);
  3544. Sql_Free(logmysql_handle);
  3545. exit(EXIT_FAILURE);
  3546. }
  3547. ShowStatus(""CL_WHITE"[SQL]"CL_RESET": Successfully '"CL_GREEN"connected"CL_RESET"' to Database '"CL_WHITE"%s"CL_RESET"'.\n", log_db_db);
  3548. if( strlen(default_codepage) > 0 )
  3549. if ( SQL_ERROR == Sql_SetEncoding(logmysql_handle, default_codepage) )
  3550. Sql_ShowDebug(logmysql_handle);
  3551. #endif
  3552. return 0;
  3553. }
  3554. struct questinfo *map_add_questinfo(int m, struct questinfo *qi) {
  3555. unsigned short i;
  3556. /* duplicate, override */
  3557. for(i = 0; i < map[m].qi_count; i++) {
  3558. if( &map[m].qi_data[i] && map[m].qi_data[i].nd == qi->nd && map[m].qi_data[i].quest_id == qi->quest_id)
  3559. break;
  3560. }
  3561. if( i == map[m].qi_count )
  3562. RECREATE(map[m].qi_data, struct questinfo, ++map[m].qi_count);
  3563. else { // clear previous criteria on override
  3564. if (map[m].qi_data[i].jobid)
  3565. aFree(map[m].qi_data[i].jobid);
  3566. map[m].qi_data[i].jobid = NULL;
  3567. map[m].qi_data[i].jobid_count = 0;
  3568. if (map[m].qi_data[i].req)
  3569. aFree(map[m].qi_data[i].req);
  3570. map[m].qi_data[i].req = NULL;
  3571. map[m].qi_data[i].req_count = 0;
  3572. }
  3573. memcpy(&map[m].qi_data[i], qi, sizeof(struct questinfo));
  3574. return &map[m].qi_data[i];
  3575. }
  3576. bool map_remove_questinfo(int m, struct npc_data *nd) {
  3577. unsigned short i, c;
  3578. for(i = 0; i < map[m].qi_count; i++) {
  3579. struct questinfo *qi = &map[m].qi_data[i];
  3580. if( qi->nd == nd ) {
  3581. if (qi->jobid)
  3582. aFree(qi->jobid);
  3583. qi->jobid = NULL;
  3584. qi->jobid_count = 0;
  3585. if (qi->req)
  3586. aFree(qi->req);
  3587. qi->req = NULL;
  3588. qi->req_count = 0;
  3589. memset(&map[m].qi_data[i], 0, sizeof(map[m].qi_data[i]));
  3590. }
  3591. }
  3592. // Move next data to empty slot
  3593. for(i = 0, c = 0; i < map[m].qi_count; i++) {
  3594. struct questinfo *qi = &map[m].qi_data[i];
  3595. if (!qi || !qi->nd)
  3596. continue;
  3597. if (i != c) {
  3598. map[m].qi_data[c] = map[m].qi_data[i];
  3599. memset(&map[m].qi_data[i], 0, sizeof(map[m].qi_data[i]));
  3600. }
  3601. c++;
  3602. }
  3603. if (!(map[m].qi_count = c)) {
  3604. aFree(map[m].qi_data);
  3605. map[m].qi_data = NULL;
  3606. }
  3607. else
  3608. RECREATE(map[m].qi_data, struct questinfo, map[m].qi_count);
  3609. return true;
  3610. }
  3611. static void map_free_questinfo(int m) {
  3612. unsigned short i;
  3613. for(i = 0; i < map[m].qi_count; i++) {
  3614. if (map[m].qi_data[i].jobid)
  3615. aFree(map[m].qi_data[i].jobid);
  3616. map[m].qi_data[i].jobid = NULL;
  3617. map[m].qi_data[i].jobid_count = 0;
  3618. if (map[m].qi_data[i].req)
  3619. aFree(map[m].qi_data[i].req);
  3620. map[m].qi_data[i].req = NULL;
  3621. map[m].qi_data[i].req_count = 0;
  3622. }
  3623. aFree(map[m].qi_data);
  3624. map[m].qi_data = NULL;
  3625. map[m].qi_count = 0;
  3626. }
  3627. struct questinfo *map_has_questinfo(int m, struct npc_data *nd, int quest_id) {
  3628. unsigned short i;
  3629. for (i = 0; i < map[m].qi_count; i++) {
  3630. struct questinfo *qi = &map[m].qi_data[i];
  3631. if (qi->nd == nd && qi->quest_id == quest_id) {
  3632. return qi;
  3633. }
  3634. }
  3635. return NULL;
  3636. }
  3637. /**
  3638. * @see DBApply
  3639. */
  3640. int map_db_final(DBKey key, DBData *data, va_list ap)
  3641. {
  3642. struct map_data_other_server *mdos = (struct map_data_other_server *)db_data2ptr(data);
  3643. if(mdos && mdos->cell == NULL)
  3644. aFree(mdos);
  3645. return 0;
  3646. }
  3647. /**
  3648. * @see DBApply
  3649. */
  3650. int nick_db_final(DBKey key, DBData *data, va_list args)
  3651. {
  3652. struct charid2nick* p = (struct charid2nick*)db_data2ptr(data);
  3653. struct charid_request* req;
  3654. if( p == NULL )
  3655. return 0;
  3656. while( p->requests )
  3657. {
  3658. req = p->requests;
  3659. p->requests = req->next;
  3660. aFree(req);
  3661. }
  3662. aFree(p);
  3663. return 0;
  3664. }
  3665. int cleanup_sub(struct block_list *bl, va_list ap)
  3666. {
  3667. nullpo_ret(bl);
  3668. switch(bl->type) {
  3669. case BL_PC:
  3670. map_quit((struct map_session_data *) bl);
  3671. break;
  3672. case BL_NPC:
  3673. npc_unload((struct npc_data *)bl,false);
  3674. break;
  3675. case BL_MOB:
  3676. unit_free(bl,CLR_OUTSIGHT);
  3677. break;
  3678. case BL_PET:
  3679. //There is no need for this, the pet is removed together with the player. [Skotlex]
  3680. break;
  3681. case BL_ITEM:
  3682. map_clearflooritem(bl);
  3683. break;
  3684. case BL_SKILL:
  3685. skill_delunit((struct skill_unit *) bl);
  3686. break;
  3687. }
  3688. return 1;
  3689. }
  3690. #ifdef ADJUST_SKILL_DAMAGE
  3691. /**
  3692. * Free all skill damage entries for a map
  3693. * @param m Map data
  3694. **/
  3695. void map_skill_damage_free(struct map_data *m) {
  3696. uint8 i;
  3697. for (i = 0; i < m->skill_damage.count; i++) {
  3698. ers_free(map_skill_damage_ers, m->skill_damage.entries[i]);
  3699. m->skill_damage.entries[i] = NULL;
  3700. }
  3701. aFree(m->skill_damage.entries);
  3702. m->skill_damage.entries = NULL;
  3703. m->skill_damage.count = 0;
  3704. }
  3705. /**
  3706. * Add new skill damage adjustment entry for a map
  3707. * @param m Map data
  3708. * @param skill_id Skill
  3709. * @param pc Rate to PC
  3710. * @param mobs Rate to Monster
  3711. * @param boss Rate to Boss-monster
  3712. * @param other Rate to Other target
  3713. * @param caster Caster type
  3714. **/
  3715. void map_skill_damage_add(struct map_data *m, uint16 skill_id, int pc, int mob, int boss, int other, uint8 caster) {
  3716. struct s_skill_damage *entry;
  3717. int i = 0;
  3718. if (m->skill_damage.count >= UINT8_MAX)
  3719. return;
  3720. for (i = 0; i < m->skill_damage.count; i++) {
  3721. if (m->skill_damage.entries[i]->skill_id == skill_id) {
  3722. m->skill_damage.entries[i]->pc = pc;
  3723. m->skill_damage.entries[i]->mob = mob;
  3724. m->skill_damage.entries[i]->boss = boss;
  3725. m->skill_damage.entries[i]->other = other;
  3726. m->skill_damage.entries[i]->caster = caster;
  3727. return;
  3728. }
  3729. }
  3730. entry = ers_alloc(map_skill_damage_ers, struct s_skill_damage);
  3731. entry->skill_id = skill_id;
  3732. entry->pc = pc;
  3733. entry->mob = mob;
  3734. entry->boss = boss;
  3735. entry->other = other;
  3736. entry->caster = caster;
  3737. RECREATE(m->skill_damage.entries, struct s_skill_damage *, m->skill_damage.count+1);
  3738. m->skill_damage.entries[m->skill_damage.count++] = entry;
  3739. }
  3740. #endif
  3741. /**
  3742. * @see DBApply
  3743. */
  3744. static int cleanup_db_sub(DBKey key, DBData *data, va_list va)
  3745. {
  3746. return cleanup_sub((struct block_list *)db_data2ptr(data), va);
  3747. }
  3748. /*==========================================
  3749. * map destructor
  3750. *------------------------------------------*/
  3751. void do_final(void)
  3752. {
  3753. int i, j;
  3754. struct map_session_data* sd;
  3755. struct s_mapiterator* iter;
  3756. ShowStatus("Terminating...\n");
  3757. channel_config.closing = true;
  3758. //Ladies and babies first.
  3759. iter = mapit_getallusers();
  3760. for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
  3761. map_quit(sd);
  3762. mapit_free(iter);
  3763. /* prepares npcs for a faster shutdown process */
  3764. do_clear_npc();
  3765. // remove all objects on maps
  3766. for (i = 0; i < map_num; i++) {
  3767. ShowStatus("Cleaning up maps [%d/%d]: %s..."CL_CLL"\r", i+1, map_num, map[i].name);
  3768. if (map[i].m >= 0) {
  3769. map_foreachinmap(cleanup_sub, i, BL_ALL);
  3770. channel_delete(map[i].channel);
  3771. }
  3772. }
  3773. ShowStatus("Cleaned up %d maps."CL_CLL"\n", map_num);
  3774. id_db->foreach(id_db,cleanup_db_sub);
  3775. chrif_char_reset_offline();
  3776. chrif_flush_fifo();
  3777. do_final_atcommand();
  3778. do_final_battle();
  3779. do_final_chrif();
  3780. do_final_clan();
  3781. do_final_clif();
  3782. do_final_npc();
  3783. do_final_quest();
  3784. do_final_script();
  3785. do_final_instance();
  3786. do_final_itemdb();
  3787. do_final_storage();
  3788. do_final_guild();
  3789. do_final_party();
  3790. do_final_pc();
  3791. do_final_pet();
  3792. do_final_homunculus();
  3793. do_final_mercenary();
  3794. do_final_mob();
  3795. do_final_msg();
  3796. do_final_skill();
  3797. do_final_status();
  3798. do_final_unit();
  3799. do_final_battleground();
  3800. do_final_duel();
  3801. do_final_elemental();
  3802. do_final_cashshop();
  3803. do_final_channel(); //should be called after final guild
  3804. do_final_vending();
  3805. do_final_buyingstore();
  3806. do_final_path();
  3807. map_db->destroy(map_db, map_db_final);
  3808. for (i=0; i<map_num; i++) {
  3809. if(map[i].cell) aFree(map[i].cell);
  3810. if(map[i].block) aFree(map[i].block);
  3811. if(map[i].block_mob) aFree(map[i].block_mob);
  3812. if(battle_config.dynamic_mobs) { //Dynamic mobs flag by [random]
  3813. if(map[i].mob_delete_timer != INVALID_TIMER)
  3814. delete_timer(map[i].mob_delete_timer, map_removemobs_timer);
  3815. for (j=0; j<MAX_MOB_LIST_PER_MAP; j++)
  3816. if (map[i].moblist[j]) aFree(map[i].moblist[j]);
  3817. }
  3818. map_free_questinfo(i);
  3819. #ifdef ADJUST_SKILL_DAMAGE
  3820. if (map[i].skill_damage.count)
  3821. map_skill_damage_free(&map[i]);
  3822. #endif
  3823. }
  3824. mapindex_final();
  3825. if(enable_grf)
  3826. grfio_final();
  3827. id_db->destroy(id_db, NULL);
  3828. pc_db->destroy(pc_db, NULL);
  3829. mobid_db->destroy(mobid_db, NULL);
  3830. bossid_db->destroy(bossid_db, NULL);
  3831. nick_db->destroy(nick_db, nick_db_final);
  3832. charid_db->destroy(charid_db, NULL);
  3833. iwall_db->destroy(iwall_db, NULL);
  3834. regen_db->destroy(regen_db, NULL);
  3835. #ifdef ADJUST_SKILL_DAMAGE
  3836. ers_destroy(map_skill_damage_ers);
  3837. #endif
  3838. map_sql_close();
  3839. ShowStatus("Finished.\n");
  3840. }
  3841. static int map_abort_sub(struct map_session_data* sd, va_list ap)
  3842. {
  3843. chrif_save(sd, CSAVE_QUIT|CSAVE_INVENTORY|CSAVE_CART);
  3844. return 1;
  3845. }
  3846. //------------------------------
  3847. // Function called when the server
  3848. // has received a crash signal.
  3849. //------------------------------
  3850. void do_abort(void)
  3851. {
  3852. static int run = 0;
  3853. //Save all characters and then flush the inter-connection.
  3854. if (run) {
  3855. ShowFatalError("Server has crashed while trying to save characters. Character data can't be saved!\n");
  3856. return;
  3857. }
  3858. run = 1;
  3859. if (!chrif_isconnected())
  3860. {
  3861. if (pc_db->size(pc_db))
  3862. ShowFatalError("Server has crashed without a connection to the char-server, %u characters can't be saved!\n", pc_db->size(pc_db));
  3863. return;
  3864. }
  3865. ShowError("Server received crash signal! Attempting to save all online characters!\n");
  3866. map_foreachpc(map_abort_sub);
  3867. chrif_flush_fifo();
  3868. }
  3869. /*======================================================
  3870. * Map-Server help options screen
  3871. *------------------------------------------------------*/
  3872. void display_helpscreen(bool do_exit)
  3873. {
  3874. ShowInfo("Usage: %s [options]\n", SERVER_NAME);
  3875. ShowInfo("\n");
  3876. ShowInfo("Options:\n");
  3877. ShowInfo(" -?, -h [--help]\t\tDisplays this help screen.\n");
  3878. ShowInfo(" -v [--version]\t\tDisplays the server's version.\n");
  3879. ShowInfo(" --run-once\t\t\tCloses server after loading (testing).\n");
  3880. ShowInfo(" --map-config <file>\t\tAlternative map-server configuration.\n");
  3881. ShowInfo(" --battle-config <file>\tAlternative battle configuration.\n");
  3882. ShowInfo(" --atcommand-config <file>\tAlternative atcommand configuration.\n");
  3883. ShowInfo(" --script-config <file>\tAlternative script configuration.\n");
  3884. ShowInfo(" --msg-config <file>\t\tAlternative message configuration.\n");
  3885. ShowInfo(" --grf-path <file>\t\tAlternative GRF path configuration.\n");
  3886. ShowInfo(" --inter-config <file>\t\tAlternative inter-server configuration.\n");
  3887. ShowInfo(" --log-config <file>\t\tAlternative logging configuration.\n");
  3888. if( do_exit )
  3889. exit(EXIT_SUCCESS);
  3890. }
  3891. /*======================================================
  3892. * Map-Server Init and Command-line Arguments [Valaris]
  3893. *------------------------------------------------------*/
  3894. void set_server_type(void)
  3895. {
  3896. SERVER_TYPE = ATHENA_SERVER_MAP;
  3897. }
  3898. /*======================================================
  3899. * Message System
  3900. *------------------------------------------------------*/
  3901. struct msg_data {
  3902. char* msg[MAP_MAX_MSG];
  3903. };
  3904. struct msg_data *map_lang2msgdb(uint8 lang){
  3905. return (struct msg_data*)idb_get(map_msg_db, lang);
  3906. }
  3907. void map_do_init_msg(void){
  3908. int test=0, i=0, size;
  3909. char * listelang[] = {
  3910. MSG_CONF_NAME_EN, //default
  3911. MSG_CONF_NAME_RUS,
  3912. MSG_CONF_NAME_SPN,
  3913. MSG_CONF_NAME_GRM,
  3914. MSG_CONF_NAME_CHN,
  3915. MSG_CONF_NAME_MAL,
  3916. MSG_CONF_NAME_IDN,
  3917. MSG_CONF_NAME_FRN,
  3918. MSG_CONF_NAME_POR,
  3919. MSG_CONF_NAME_THA
  3920. };
  3921. map_msg_db = idb_alloc(DB_OPT_BASE);
  3922. size = ARRAYLENGTH(listelang); //avoid recalc
  3923. while(test!=-1 && size>i){ //for all enable lang +(English default)
  3924. test = msg_checklangtype(i,false);
  3925. if(test == 1) msg_config_read(listelang[i],i); //if enabled read it and assign i to langtype
  3926. i++;
  3927. }
  3928. }
  3929. void map_do_final_msg(void){
  3930. DBIterator *iter = db_iterator(map_msg_db);
  3931. struct msg_data *mdb;
  3932. for (mdb = (struct msg_data *)dbi_first(iter); dbi_exists(iter); mdb = (struct msg_data *)dbi_next(iter)) {
  3933. _do_final_msg(MAP_MAX_MSG,mdb->msg);
  3934. aFree(mdb);
  3935. }
  3936. dbi_destroy(iter);
  3937. map_msg_db->destroy(map_msg_db, NULL);
  3938. }
  3939. void map_msg_reload(void){
  3940. map_do_final_msg(); //clear data
  3941. map_do_init_msg();
  3942. }
  3943. int map_msg_config_read(char *cfgName, int lang){
  3944. struct msg_data *mdb;
  3945. if( (mdb = map_lang2msgdb(lang)) == NULL )
  3946. CREATE(mdb, struct msg_data, 1);
  3947. else
  3948. idb_remove(map_msg_db, lang);
  3949. idb_put(map_msg_db, lang, mdb);
  3950. if(_msg_config_read(cfgName,MAP_MAX_MSG,mdb->msg)!=0){ //an error occur
  3951. idb_remove(map_msg_db, lang); //@TRYME
  3952. aFree(mdb);
  3953. }
  3954. return 0;
  3955. }
  3956. const char* map_msg_txt(struct map_session_data *sd, int msg_number){
  3957. struct msg_data *mdb;
  3958. uint8 lang = 0; //default
  3959. if(sd && sd->langtype) lang = sd->langtype;
  3960. if( (mdb = map_lang2msgdb(lang)) != NULL){
  3961. const char *tmp = _msg_txt(msg_number,MAP_MAX_MSG,mdb->msg);
  3962. if(strcmp(tmp,"??")) //to verify result
  3963. return tmp;
  3964. ShowDebug("Message #%d not found for langtype %d.\n",msg_number,lang);
  3965. }
  3966. ShowDebug("Selected langtype %d not loaded, trying fallback...\n",lang);
  3967. if(lang != 0 && (mdb = map_lang2msgdb(0)) != NULL) //fallback
  3968. return _msg_txt(msg_number,MAP_MAX_MSG,mdb->msg);
  3969. return "??";
  3970. }
  3971. /// Called when a terminate signal is received.
  3972. void do_shutdown(void)
  3973. {
  3974. if( runflag != MAPSERVER_ST_SHUTDOWN )
  3975. {
  3976. runflag = MAPSERVER_ST_SHUTDOWN;
  3977. ShowStatus("Shutting down...\n");
  3978. {
  3979. struct map_session_data* sd;
  3980. struct s_mapiterator* iter = mapit_getallusers();
  3981. for( sd = (TBL_PC*)mapit_first(iter); mapit_exists(iter); sd = (TBL_PC*)mapit_next(iter) )
  3982. clif_GM_kick(NULL, sd);
  3983. mapit_free(iter);
  3984. flush_fifos();
  3985. }
  3986. chrif_check_shutdown();
  3987. }
  3988. }
  3989. int do_init(int argc, char *argv[])
  3990. {
  3991. runflag = MAPSERVER_ST_STARTING;
  3992. #ifdef GCOLLECT
  3993. GC_enable_incremental();
  3994. #endif
  3995. INTER_CONF_NAME="conf/inter_athena.conf";
  3996. LOG_CONF_NAME="conf/log_athena.conf";
  3997. MAP_CONF_NAME = "conf/map_athena.conf";
  3998. BATTLE_CONF_FILENAME = "conf/battle_athena.conf";
  3999. ATCOMMAND_CONF_FILENAME = "conf/atcommand_athena.conf";
  4000. SCRIPT_CONF_NAME = "conf/script_athena.conf";
  4001. GRF_PATH_FILENAME = "conf/grf-files.txt";
  4002. safestrncpy(console_log_filepath, "./log/map-msg_log.log", sizeof(console_log_filepath));
  4003. /* Multilanguage */
  4004. MSG_CONF_NAME_EN = "conf/msg_conf/map_msg.conf"; // English (default)
  4005. MSG_CONF_NAME_RUS = "conf/msg_conf/map_msg_rus.conf"; // Russian
  4006. MSG_CONF_NAME_SPN = "conf/msg_conf/map_msg_spn.conf"; // Spanish
  4007. MSG_CONF_NAME_GRM = "conf/msg_conf/map_msg_grm.conf"; // German
  4008. MSG_CONF_NAME_CHN = "conf/msg_conf/map_msg_chn.conf"; // Chinese
  4009. MSG_CONF_NAME_MAL = "conf/msg_conf/map_msg_mal.conf"; // Malaysian
  4010. MSG_CONF_NAME_IDN = "conf/msg_conf/map_msg_idn.conf"; // Indonesian
  4011. MSG_CONF_NAME_FRN = "conf/msg_conf/map_msg_frn.conf"; // French
  4012. MSG_CONF_NAME_POR = "conf/msg_conf/map_msg_por.conf"; // Brazilian Portuguese
  4013. MSG_CONF_NAME_THA = "conf/msg_conf/map_msg_tha.conf"; // Thai
  4014. /* Multilanguage */
  4015. // Default map
  4016. safestrncpy(map_default.mapname, "prontera", MAP_NAME_LENGTH);
  4017. map_default.x = 156;
  4018. map_default.y = 191;
  4019. cli_get_options(argc,argv);
  4020. rnd_init();
  4021. map_config_read(MAP_CONF_NAME);
  4022. if (save_settings == CHARSAVE_NONE)
  4023. ShowWarning("Value of 'save_settings' is not set, player's data only will be saved every 'autosave_time' (%d seconds).\n", autosave_interval/1000);
  4024. // loads npcs
  4025. map_reloadnpc(false);
  4026. chrif_checkdefaultlogin();
  4027. if (!map_ip_set || !char_ip_set) {
  4028. char ip_str[16];
  4029. ip2str(addr_[0], ip_str);
  4030. // Skip this warning if the server is run with run-once flag
  4031. if( runflag != CORE_ST_STOP ){
  4032. ShowWarning("Not all IP addresses in map_athena.conf configured, autodetecting...\n");
  4033. }
  4034. if (naddr_ == 0)
  4035. ShowError("Unable to determine your IP address...\n");
  4036. else if (naddr_ > 1)
  4037. ShowNotice("Multiple interfaces detected...\n");
  4038. ShowInfo("Defaulting to %s as our IP address\n", ip_str);
  4039. if (!map_ip_set)
  4040. clif_setip(ip_str);
  4041. if (!char_ip_set)
  4042. chrif_setip(ip_str);
  4043. }
  4044. battle_config_read(BATTLE_CONF_FILENAME);
  4045. script_config_read(SCRIPT_CONF_NAME);
  4046. inter_config_read(INTER_CONF_NAME);
  4047. log_config_read(LOG_CONF_NAME);
  4048. id_db = idb_alloc(DB_OPT_BASE);
  4049. pc_db = idb_alloc(DB_OPT_BASE); //Added for reliable map_id2sd() use. [Skotlex]
  4050. mobid_db = idb_alloc(DB_OPT_BASE); //Added to lower the load of the lazy mob ai. [Skotlex]
  4051. bossid_db = idb_alloc(DB_OPT_BASE); // Used for Convex Mirror quick MVP search
  4052. map_db = uidb_alloc(DB_OPT_BASE);
  4053. nick_db = idb_alloc(DB_OPT_BASE);
  4054. charid_db = uidb_alloc(DB_OPT_BASE);
  4055. regen_db = idb_alloc(DB_OPT_BASE); // efficient status_natural_heal processing
  4056. iwall_db = strdb_alloc(DB_OPT_RELEASE_DATA,2*NAME_LENGTH+2+1); // [Zephyrus] Invisible Walls
  4057. #ifdef ADJUST_SKILL_DAMAGE
  4058. map_skill_damage_ers = ers_new(sizeof(struct s_skill_damage), "map.c:map_skill_damage_ers", ERS_OPT_NONE);
  4059. #endif
  4060. map_sql_init();
  4061. if (log_config.sql_logs)
  4062. log_sql_init();
  4063. mapindex_init();
  4064. if(enable_grf)
  4065. grfio_init(GRF_PATH_FILENAME);
  4066. map_readallmaps();
  4067. add_timer_func_list(map_freeblock_timer, "map_freeblock_timer");
  4068. add_timer_func_list(map_clearflooritem_timer, "map_clearflooritem_timer");
  4069. add_timer_func_list(map_removemobs_timer, "map_removemobs_timer");
  4070. add_timer_interval(gettick()+1000, map_freeblock_timer, 0, 0, 60*1000);
  4071. map_do_init_msg();
  4072. do_init_path();
  4073. do_init_atcommand();
  4074. do_init_battle();
  4075. do_init_instance();
  4076. do_init_channel();
  4077. do_init_chrif();
  4078. do_init_clan();
  4079. do_init_clif();
  4080. do_init_script();
  4081. do_init_itemdb();
  4082. do_init_cashshop();
  4083. do_init_skill();
  4084. do_init_mob();
  4085. do_init_pc();
  4086. do_init_status();
  4087. do_init_party();
  4088. do_init_guild();
  4089. do_init_storage();
  4090. do_init_pet();
  4091. do_init_homunculus();
  4092. do_init_mercenary();
  4093. do_init_elemental();
  4094. do_init_quest();
  4095. do_init_npc();
  4096. do_init_unit();
  4097. do_init_battleground();
  4098. do_init_duel();
  4099. do_init_vending();
  4100. do_init_buyingstore();
  4101. npc_event_do_oninit(); // Init npcs (OnInit)
  4102. if (battle_config.pk_mode)
  4103. ShowNotice("Server is running on '"CL_WHITE"PK Mode"CL_RESET"'.\n");
  4104. ShowStatus("Server is '"CL_GREEN"ready"CL_RESET"' and listening on port '"CL_WHITE"%d"CL_RESET"'.\n\n", map_port);
  4105. if( runflag != CORE_ST_STOP )
  4106. {
  4107. shutdown_callback = do_shutdown;
  4108. runflag = MAPSERVER_ST_RUNNING;
  4109. }
  4110. #if defined(BUILDBOT)
  4111. if( buildbotflag )
  4112. exit(EXIT_FAILURE);
  4113. #endif
  4114. if( console ){ //start listening
  4115. add_timer_func_list(parse_console_timer, "parse_console_timer");
  4116. add_timer_interval(gettick()+1000, parse_console_timer, 0, 0, 1000); //start in 1s each 1sec
  4117. }
  4118. return 0;
  4119. }