map.cpp 151 KB

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