map.c 123 KB

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