map.cpp 150 KB

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