map.cpp 151 KB

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