map.cpp 150 KB

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