map.cpp 151 KB

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