map.cpp 153 KB

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