map.c 134 KB

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