map.cpp 153 KB

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