Quest.java 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504
  1. /*
  2. * Copyright (C) 2004-2013 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.gameserver.model.quest;
  20. import java.sql.Connection;
  21. import java.sql.PreparedStatement;
  22. import java.sql.ResultSet;
  23. import java.util.ArrayList;
  24. import java.util.Collection;
  25. import java.util.HashMap;
  26. import java.util.HashSet;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Set;
  30. import java.util.concurrent.locks.ReentrantReadWriteLock;
  31. import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
  32. import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
  33. import java.util.logging.Level;
  34. import java.util.logging.Logger;
  35. import com.l2jserver.Config;
  36. import com.l2jserver.L2DatabaseFactory;
  37. import com.l2jserver.gameserver.GameTimeController;
  38. import com.l2jserver.gameserver.ThreadPoolManager;
  39. import com.l2jserver.gameserver.cache.HtmCache;
  40. import com.l2jserver.gameserver.datatables.DoorTable;
  41. import com.l2jserver.gameserver.datatables.ItemTable;
  42. import com.l2jserver.gameserver.datatables.NpcTable;
  43. import com.l2jserver.gameserver.idfactory.IdFactory;
  44. import com.l2jserver.gameserver.instancemanager.InstanceManager;
  45. import com.l2jserver.gameserver.instancemanager.QuestManager;
  46. import com.l2jserver.gameserver.instancemanager.ZoneManager;
  47. import com.l2jserver.gameserver.model.L2DropData;
  48. import com.l2jserver.gameserver.model.L2Object;
  49. import com.l2jserver.gameserver.model.L2Party;
  50. import com.l2jserver.gameserver.model.L2Spawn;
  51. import com.l2jserver.gameserver.model.Location;
  52. import com.l2jserver.gameserver.model.actor.L2Character;
  53. import com.l2jserver.gameserver.model.actor.L2Npc;
  54. import com.l2jserver.gameserver.model.actor.L2Trap;
  55. import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
  56. import com.l2jserver.gameserver.model.actor.instance.L2MonsterInstance;
  57. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  58. import com.l2jserver.gameserver.model.actor.instance.L2TrapInstance;
  59. import com.l2jserver.gameserver.model.actor.templates.L2NpcTemplate;
  60. import com.l2jserver.gameserver.model.entity.Instance;
  61. import com.l2jserver.gameserver.model.holders.ItemHolder;
  62. import com.l2jserver.gameserver.model.interfaces.IL2Procedure;
  63. import com.l2jserver.gameserver.model.itemcontainer.PcInventory;
  64. import com.l2jserver.gameserver.model.items.L2Item;
  65. import com.l2jserver.gameserver.model.items.instance.L2ItemInstance;
  66. import com.l2jserver.gameserver.model.olympiad.CompetitionType;
  67. import com.l2jserver.gameserver.model.quest.AITasks.AggroRangeEnter;
  68. import com.l2jserver.gameserver.model.quest.AITasks.SeeCreature;
  69. import com.l2jserver.gameserver.model.quest.AITasks.SkillSee;
  70. import com.l2jserver.gameserver.model.skills.L2Skill;
  71. import com.l2jserver.gameserver.model.stats.Stats;
  72. import com.l2jserver.gameserver.model.zone.L2ZoneType;
  73. import com.l2jserver.gameserver.network.NpcStringId;
  74. import com.l2jserver.gameserver.network.SystemMessageId;
  75. import com.l2jserver.gameserver.network.serverpackets.ActionFailed;
  76. import com.l2jserver.gameserver.network.serverpackets.ExShowScreenMessage;
  77. import com.l2jserver.gameserver.network.serverpackets.InventoryUpdate;
  78. import com.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;
  79. import com.l2jserver.gameserver.network.serverpackets.NpcQuestHtmlMessage;
  80. import com.l2jserver.gameserver.network.serverpackets.PlaySound;
  81. import com.l2jserver.gameserver.network.serverpackets.StatusUpdate;
  82. import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
  83. import com.l2jserver.gameserver.scripting.ManagedScript;
  84. import com.l2jserver.gameserver.scripting.ScriptManager;
  85. import com.l2jserver.gameserver.util.MinionList;
  86. import com.l2jserver.util.L2FastMap;
  87. import com.l2jserver.util.Rnd;
  88. import com.l2jserver.util.Util;
  89. /**
  90. * Quest main class.
  91. * @author Luis Arias
  92. */
  93. public class Quest extends ManagedScript
  94. {
  95. public static final Logger _log = Logger.getLogger(Quest.class.getName());
  96. /** Map containing events from String value of the event. */
  97. private static Map<String, Quest> _allEventsS = new HashMap<>();
  98. /** Map containing lists of timers from the name of the timer. */
  99. private final Map<String, List<QuestTimer>> _allEventTimers = new L2FastMap<>(true);
  100. private final Set<Integer> _questInvolvedNpcs = new HashSet<>();
  101. private final ReentrantReadWriteLock _rwLock = new ReentrantReadWriteLock();
  102. private final WriteLock _writeLock = _rwLock.writeLock();
  103. private final ReadLock _readLock = _rwLock.readLock();
  104. private final int _questId;
  105. private final String _name;
  106. private final String _descr;
  107. private final byte _initialState = State.CREATED;
  108. protected boolean _onEnterWorld = false;
  109. private boolean _isCustom = false;
  110. private boolean _isOlympiadUse = false;
  111. public int[] questItemIds = null;
  112. private static final String DEFAULT_NO_QUEST_MSG = "<html><body>You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.</body></html>";
  113. private static final String DEFAULT_ALREADY_COMPLETED_MSG = "<html><body>This quest has already been completed.</body></html>";
  114. private static final String QUEST_DELETE_FROM_CHAR_QUERY = "DELETE FROM character_quests WHERE charId=? AND name=?";
  115. private static final String QUEST_DELETE_FROM_CHAR_QUERY_NON_REPEATABLE_QUERY = "DELETE FROM character_quests WHERE charId=? AND name=? AND var!=?";
  116. private static final int RESET_HOUR = 6;
  117. private static final int RESET_MINUTES = 30;
  118. /**
  119. * This enum contains known sound effects used by quests.<br>
  120. * The idea is to have only a single object of each quest sound instead of constructing a new one every time a script calls the playSound method.<br>
  121. * This is pretty much just a memory and CPU cycle optimization; avoids constructing/deconstructing objects all the time if they're all the same.<br>
  122. * For datapack scripts written in Java and extending the Quest class, this does not need an extra import.
  123. * @author jurchiks
  124. */
  125. public static enum QuestSound
  126. {
  127. ITEMSOUND_QUEST_ACCEPT(new PlaySound("ItemSound.quest_accept")),
  128. ITEMSOUND_QUEST_MIDDLE(new PlaySound("ItemSound.quest_middle")),
  129. ITEMSOUND_QUEST_FINISH(new PlaySound("ItemSound.quest_finish")),
  130. ITEMSOUND_QUEST_ITEMGET(new PlaySound("ItemSound.quest_itemget")),
  131. // Newbie Guide tutorial (incl. some quests), Mutated Kaneus quests, Quest 192
  132. ITEMSOUND_QUEST_TUTORIAL(new PlaySound("ItemSound.quest_tutorial")),
  133. // Quests 107, 363, 364
  134. ITEMSOUND_QUEST_GIVEUP(new PlaySound("ItemSound.quest_giveup")),
  135. // Quests 212, 217, 224, 226, 416
  136. ITEMSOUND_QUEST_BEFORE_BATTLE(new PlaySound("ItemSound.quest_before_battle")),
  137. // Quests 211, 258, 266, 330
  138. ITEMSOUND_QUEST_JACKPOT(new PlaySound("ItemSound.quest_jackpot")),
  139. // Quests 508, 509 and 510
  140. ITEMSOUND_QUEST_FANFARE_1(new PlaySound("ItemSound.quest_fanfare_1")),
  141. // Played only after class transfer via Test Server Helpers (Id 31756 and 31757)
  142. ITEMSOUND_QUEST_FANFARE_2(new PlaySound("ItemSound.quest_fanfare_2")),
  143. // Quests 336
  144. ITEMSOUND_QUEST_FANFARE_MIDDLE(new PlaySound("ItemSound.quest_fanfare_middle")),
  145. // Quest 114
  146. ITEMSOUND_ARMOR_WOOD(new PlaySound("ItemSound.armor_wood_3")),
  147. // Quest 21
  148. ITEMSOUND_ARMOR_CLOTH(new PlaySound("ItemSound.item_drop_equip_armor_cloth")),
  149. ITEMSOUND_ED_CHIMES(new PlaySound("AmdSound.ed_chimes_05")),
  150. // Quest 22
  151. ITEMSOUND_D_HORROR_03(new PlaySound("AmbSound.d_horror_03")),
  152. ITEMSOUND_D_HORROR_15(new PlaySound("AmbSound.d_horror_15")),
  153. ITEMSOUND_DD_HORROR_01(new PlaySound("AmbSound.dd_horror_01")),
  154. // Quest 120
  155. ITEMSOUND_ED_DRONE_02(new PlaySound("AmbSound.ed_drone_02")),
  156. // Quest 23
  157. ITEMSOUND_ARMOR_LEATHER(new PlaySound("ItemSound.itemdrop_armor_leather")),
  158. ITEMSOUND_WEAPON_SPEAR(new PlaySound("ItemSound.itemdrop_weapon_spear")),
  159. // Quest 24
  160. AMDSOUND_D_WIND_LOOT_02(new PlaySound("AmdSound.d_wind_loot_02")),
  161. INTERFACESOUND_CHARSTAT_OPEN_01(new PlaySound("InterfaceSound.charstat_open_01")),
  162. // Quest 648 and treasure chests
  163. ITEMSOUND_BROKEN_KEY(new PlaySound("ItemSound2.broken_key")),
  164. // Quest 184
  165. ITEMSOUND_SIREN(new PlaySound("ItemSound3.sys_siren")),
  166. // Quest 648
  167. ITEMSOUND_ENCHANT_SUCCESS(new PlaySound("ItemSound3.sys_enchant_success")),
  168. ITEMSOUND_ENCHANT_FAILED(new PlaySound("ItemSound3.sys_enchant_failed")),
  169. // Best farm mobs
  170. ITEMSOUND_SOW_SUCCESS(new PlaySound("ItemSound3.sys_sow_success")),
  171. // Quest 25
  172. SKILLSOUND_HORROR_1(new PlaySound("SkillSound5.horror_01")),
  173. // Quests 21 and 23
  174. SKILLSOUND_HORROR_2(new PlaySound("SkillSound5.horror_02")),
  175. // Quest 22
  176. SKILLSOUND_ANTARAS_FEAR(new PlaySound("SkillSound3.antaras_fear")),
  177. // Quest 505
  178. SKILLSOUND_JEWEL_CELEBRATE(new PlaySound("SkillSound2.jewel.celebrate")),
  179. // Quest 373
  180. SKILLSOUND_LIQUID_MIX(new PlaySound("SkillSound5.liquid_mix_01")),
  181. SKILLSOUND_LIQUID_SUCCESS(new PlaySound("SkillSound5.liquid_success_01")),
  182. SKILLSOUND_LIQUID_FAIL(new PlaySound("SkillSound5.liquid_fail_01")),
  183. // Elroki sounds - Quest 111
  184. ETCSOUND_ELROKI_SOUND_FULL(new PlaySound("EtcSound.elcroki_song_full")),
  185. ETCSOUND_ELROKI_SOUND_1ST(new PlaySound("EtcSound.elcroki_song_1st")),
  186. ETCSOUND_ELROKI_SOUND_2ND(new PlaySound("EtcSound.elcroki_song_2nd")),
  187. ETCSOUND_ELROKI_SOUND_3RD(new PlaySound("EtcSound.elcroki_song_3rd")),
  188. // PailakaInjuredDragon
  189. BS08_A(new PlaySound("BS08_A")),
  190. // Quest 115
  191. AMBSOUND_T_WINGFLAP_04(new PlaySound("AmbSound.t_wingflap_04")),
  192. AMBSOUND_THUNDER_02(new PlaySound("AmbSound.thunder_02"));
  193. private final PlaySound _playSound;
  194. private static Map<String, PlaySound> soundPackets = new HashMap<>();
  195. private QuestSound(PlaySound playSound)
  196. {
  197. _playSound = playSound;
  198. }
  199. /**
  200. * Get a {@link PlaySound} packet by its name.
  201. * @param soundName : the name of the sound to look for
  202. * @return the {@link PlaySound} packet with the specified sound or {@code null} if one was not found
  203. */
  204. public static PlaySound getSound(String soundName)
  205. {
  206. if (soundPackets.containsKey(soundName))
  207. {
  208. return soundPackets.get(soundName);
  209. }
  210. for (QuestSound qs : QuestSound.values())
  211. {
  212. if (qs._playSound.getSoundName().equals(soundName))
  213. {
  214. soundPackets.put(soundName, qs._playSound); // cache in map to avoid looping repeatedly
  215. return qs._playSound;
  216. }
  217. }
  218. _log.info("Missing QuestSound enum for sound: " + soundName);
  219. soundPackets.put(soundName, new PlaySound(soundName));
  220. return soundPackets.get(soundName);
  221. }
  222. /**
  223. * @return the name of the sound of this QuestSound object
  224. */
  225. public String getSoundName()
  226. {
  227. return _playSound.getSoundName();
  228. }
  229. /**
  230. * @return the {@link PlaySound} packet of this QuestSound object
  231. */
  232. public PlaySound getPacket()
  233. {
  234. return _playSound;
  235. }
  236. }
  237. /**
  238. * @return the reset hour for a daily quest, could be overridden on a script.
  239. */
  240. public int getResetHour()
  241. {
  242. return RESET_HOUR;
  243. }
  244. /**
  245. * @return the reset minutes for a daily quest, could be overridden on a script.
  246. */
  247. public int getResetMinutes()
  248. {
  249. return RESET_MINUTES;
  250. }
  251. /**
  252. * @return a collection of the values contained in the _allEventsS map.
  253. */
  254. public static Collection<Quest> findAllEvents()
  255. {
  256. return _allEventsS.values();
  257. }
  258. /**
  259. * The Quest object constructor.<br>
  260. * Constructing a quest also calls the {@code init_LoadGlobalData} convenience method.
  261. * @param questId int pointing out the Id of the quest.
  262. * @param name String corresponding to the name of the quest.
  263. * @param descr String for the description of the quest.
  264. */
  265. public Quest(int questId, String name, String descr)
  266. {
  267. _questId = questId;
  268. _name = name;
  269. _descr = descr;
  270. if (questId != 0)
  271. {
  272. QuestManager.getInstance().addQuest(this);
  273. }
  274. else
  275. {
  276. _allEventsS.put(name, this);
  277. }
  278. init_LoadGlobalData();
  279. }
  280. /**
  281. * The function init_LoadGlobalData is, by default, called by the constructor of all quests.<br>
  282. * Children of this class can implement this function in order to define what variables to load and what structures to save them in.<br>
  283. * By default, nothing is loaded.
  284. */
  285. protected void init_LoadGlobalData()
  286. {
  287. }
  288. /**
  289. * The function saveGlobalData is, by default, called at shutdown, for all quests, by the QuestManager.<br>
  290. * Children of this class can implement this function in order to convert their structures<br>
  291. * into <var, value> tuples and make calls to save them to the database, if needed.<br>
  292. * By default, nothing is saved.
  293. */
  294. public void saveGlobalData()
  295. {
  296. }
  297. /**
  298. * Trap actions:<br>
  299. * <ul>
  300. * <li>Triggered</li>
  301. * <li>Detected</li>
  302. * <li>Disarmed</li>
  303. * </ul>
  304. */
  305. public static enum TrapAction
  306. {
  307. TRAP_TRIGGERED,
  308. TRAP_DETECTED,
  309. TRAP_DISARMED
  310. }
  311. public static enum QuestEventType
  312. {
  313. ON_FIRST_TALK(false), // control the first dialog shown by NPCs when they are clicked (some quests must override the default npc action)
  314. QUEST_START(true), // onTalk action from start npcs
  315. ON_TALK(true), // onTalk action from npcs participating in a quest
  316. ON_ATTACK(true), // onAttack action triggered when a mob gets attacked by someone
  317. ON_KILL(true), // onKill action triggered when a mob gets killed.
  318. ON_SPAWN(true), // onSpawn action triggered when an NPC is spawned or respawned.
  319. ON_SKILL_SEE(true), // NPC or Mob saw a person casting a skill (regardless what the target is).
  320. ON_FACTION_CALL(true), // NPC or Mob saw a person casting a skill (regardless what the target is).
  321. ON_AGGRO_RANGE_ENTER(true), // a person came within the Npc/Mob's range
  322. ON_SPELL_FINISHED(true), // on spell finished action when npc finish casting skill
  323. ON_SKILL_LEARN(false), // control the AcquireSkill dialog from quest script
  324. ON_ENTER_ZONE(true), // on zone enter
  325. ON_EXIT_ZONE(true), // on zone exit
  326. ON_TRAP_ACTION(true), // on zone exit
  327. ON_ITEM_USE(true),
  328. ON_EVENT_RECEIVED(true), // onEventReceived action, triggered when NPC receiving an event, sent by other NPC
  329. ON_MOVE_FINISHED(true), // onMoveFinished action, triggered when NPC stops after moving
  330. ON_NODE_ARRIVED(true), // onNodeArrived action, triggered when NPC, controlled by Walking Manager, arrives to next node
  331. ON_SEE_CREATURE(true), // onSeeCreature action, triggered when NPC's known list include the character
  332. ON_ROUTE_FINISHED(true); // onRouteFinished action, triggered when NPC, controlled by Walking Manager, arrives to last node
  333. // control whether this event type is allowed for the same npc template in multiple quests
  334. // or if the npc must be registered in at most one quest for the specified event
  335. private boolean _allowMultipleRegistration;
  336. private QuestEventType(boolean allowMultipleRegistration)
  337. {
  338. _allowMultipleRegistration = allowMultipleRegistration;
  339. }
  340. public boolean isMultipleRegistrationAllowed()
  341. {
  342. return _allowMultipleRegistration;
  343. }
  344. }
  345. /**
  346. * @return the Id of the quest
  347. */
  348. public int getQuestIntId()
  349. {
  350. return _questId;
  351. }
  352. /**
  353. * Add a new quest state of this quest to the database.
  354. * @param player the owner of the newly created quest state
  355. * @return the newly created {@link QuestState} object
  356. */
  357. public QuestState newQuestState(L2PcInstance player)
  358. {
  359. return new QuestState(this, player, getInitialState());
  360. }
  361. /**
  362. * @return the initial state of the quest
  363. */
  364. public byte getInitialState()
  365. {
  366. return _initialState;
  367. }
  368. /**
  369. * @return the name of the quest
  370. */
  371. public String getName()
  372. {
  373. return _name;
  374. }
  375. /**
  376. * @return the description of the quest
  377. */
  378. public String getDescr()
  379. {
  380. return _descr;
  381. }
  382. /**
  383. * Add a timer to the quest (if it doesn't exist already) and start it.
  384. * @param name the name of the timer (also passed back as "event" in {@link #onAdvEvent(String, L2Npc, L2PcInstance)})
  385. * @param time time in ms for when to fire the timer
  386. * @param npc the npc associated with this timer (can be null)
  387. * @param player the player associated with this timer (can be null)
  388. * @see #startQuestTimer(String, long, L2Npc, L2PcInstance, boolean)
  389. */
  390. public void startQuestTimer(String name, long time, L2Npc npc, L2PcInstance player)
  391. {
  392. startQuestTimer(name, time, npc, player, false);
  393. }
  394. /**
  395. * Add a timer to the quest (if it doesn't exist already) and start it.
  396. * @param name the name of the timer (also passed back as "event" in {@link #onAdvEvent(String, L2Npc, L2PcInstance)})
  397. * @param time time in ms for when to fire the timer
  398. * @param npc the npc associated with this timer (can be null)
  399. * @param player the player associated with this timer (can be null)
  400. * @param repeating indicates whether the timer is repeatable or one-time.<br>
  401. * If {@code true}, the task is repeated every {@code time} milliseconds until explicitly stopped.
  402. */
  403. public void startQuestTimer(String name, long time, L2Npc npc, L2PcInstance player, boolean repeating)
  404. {
  405. List<QuestTimer> timers = _allEventTimers.get(name);
  406. // Add quest timer if timer doesn't already exist
  407. if (timers == null)
  408. {
  409. timers = new ArrayList<>();
  410. timers.add(new QuestTimer(this, name, time, npc, player, repeating));
  411. _allEventTimers.put(name, timers);
  412. }
  413. // a timer with this name exists, but may not be for the same set of npc and player
  414. else
  415. {
  416. // if there exists a timer with this name, allow the timer only if the [npc, player] set is unique
  417. // nulls act as wildcards
  418. if (getQuestTimer(name, npc, player) == null)
  419. {
  420. _writeLock.lock();
  421. try
  422. {
  423. timers.add(new QuestTimer(this, name, time, npc, player, repeating));
  424. }
  425. finally
  426. {
  427. _writeLock.unlock();
  428. }
  429. }
  430. }
  431. }
  432. /**
  433. * Get a quest timer that matches the provided name and parameters.
  434. * @param name the name of the quest timer to get
  435. * @param npc the NPC associated with the quest timer to get
  436. * @param player the player associated with the quest timer to get
  437. * @return the quest timer that matches the parameters of this function or {@code null} if nothing was found
  438. */
  439. public QuestTimer getQuestTimer(String name, L2Npc npc, L2PcInstance player)
  440. {
  441. final List<QuestTimer> timers = _allEventTimers.get(name);
  442. if (timers != null)
  443. {
  444. _readLock.lock();
  445. try
  446. {
  447. for (QuestTimer timer : timers)
  448. {
  449. if (timer != null)
  450. {
  451. if (timer.isMatch(this, name, npc, player))
  452. {
  453. return timer;
  454. }
  455. }
  456. }
  457. }
  458. finally
  459. {
  460. _readLock.unlock();
  461. }
  462. }
  463. return null;
  464. }
  465. /**
  466. * Cancel all quest timers with the specified name.
  467. * @param name the name of the quest timers to cancel
  468. */
  469. public void cancelQuestTimers(String name)
  470. {
  471. final List<QuestTimer> timers = _allEventTimers.get(name);
  472. if (timers != null)
  473. {
  474. _writeLock.lock();
  475. try
  476. {
  477. for (QuestTimer timer : timers)
  478. {
  479. if (timer != null)
  480. {
  481. timer.cancel();
  482. }
  483. }
  484. timers.clear();
  485. }
  486. finally
  487. {
  488. _writeLock.unlock();
  489. }
  490. }
  491. }
  492. /**
  493. * Cancel the quest timer that matches the specified name and parameters.
  494. * @param name the name of the quest timer to cancel
  495. * @param npc the NPC associated with the quest timer to cancel
  496. * @param player the player associated with the quest timer to cancel
  497. */
  498. public void cancelQuestTimer(String name, L2Npc npc, L2PcInstance player)
  499. {
  500. final QuestTimer timer = getQuestTimer(name, npc, player);
  501. if (timer != null)
  502. {
  503. timer.cancelAndRemove();
  504. }
  505. }
  506. /**
  507. * Remove a quest timer from the list of all timers.<br>
  508. * Note: does not stop the timer itself!
  509. * @param timer the {@link QuestState} object to remove
  510. */
  511. public void removeQuestTimer(QuestTimer timer)
  512. {
  513. if (timer != null)
  514. {
  515. final List<QuestTimer> timers = _allEventTimers.get(timer.getName());
  516. if (timers != null)
  517. {
  518. _writeLock.lock();
  519. try
  520. {
  521. timers.remove(timer);
  522. }
  523. finally
  524. {
  525. _writeLock.unlock();
  526. }
  527. }
  528. }
  529. }
  530. public Map<String, List<QuestTimer>> getQuestTimers()
  531. {
  532. return _allEventTimers;
  533. }
  534. // These are methods to call within the core to call the quest events.
  535. /**
  536. * @param npc the NPC that was attacked
  537. * @param attacker the attacking player
  538. * @param damage the damage dealt to the NPC by the player
  539. * @param isSummon if {@code true}, the attack was actually made by the player's summon
  540. * @param skill the skill used to attack the NPC (can be null)
  541. */
  542. public final void notifyAttack(L2Npc npc, L2PcInstance attacker, int damage, boolean isSummon, L2Skill skill)
  543. {
  544. String res = null;
  545. try
  546. {
  547. res = onAttack(npc, attacker, damage, isSummon, skill);
  548. }
  549. catch (Exception e)
  550. {
  551. showError(attacker, e);
  552. return;
  553. }
  554. showResult(attacker, res);
  555. }
  556. /**
  557. * @param killer the character that killed the {@code victim}
  558. * @param victim the character that was killed by the {@code killer}
  559. * @param qs the quest state object of the player to be notified of this event
  560. */
  561. public final void notifyDeath(L2Character killer, L2Character victim, QuestState qs)
  562. {
  563. String res = null;
  564. try
  565. {
  566. res = onDeath(killer, victim, qs);
  567. }
  568. catch (Exception e)
  569. {
  570. showError(qs.getPlayer(), e);
  571. }
  572. showResult(qs.getPlayer(), res);
  573. }
  574. /**
  575. * @param item
  576. * @param player
  577. */
  578. public final void notifyItemUse(L2Item item, L2PcInstance player)
  579. {
  580. String res = null;
  581. try
  582. {
  583. res = onItemUse(item, player);
  584. }
  585. catch (Exception e)
  586. {
  587. showError(player, e);
  588. }
  589. showResult(player, res);
  590. }
  591. /**
  592. * @param instance
  593. * @param player
  594. * @param skill
  595. */
  596. public final void notifySpellFinished(L2Npc instance, L2PcInstance player, L2Skill skill)
  597. {
  598. String res = null;
  599. try
  600. {
  601. res = onSpellFinished(instance, player, skill);
  602. }
  603. catch (Exception e)
  604. {
  605. showError(player, e);
  606. }
  607. showResult(player, res);
  608. }
  609. /**
  610. * Notify quest script when something happens with a trap.
  611. * @param trap the trap instance which triggers the notification
  612. * @param trigger the character which makes effect on the trap
  613. * @param action 0: trap casting its skill. 1: trigger detects the trap. 2: trigger removes the trap
  614. */
  615. public final void notifyTrapAction(L2Trap trap, L2Character trigger, TrapAction action)
  616. {
  617. String res = null;
  618. try
  619. {
  620. res = onTrapAction(trap, trigger, action);
  621. }
  622. catch (Exception e)
  623. {
  624. if (trigger.getActingPlayer() != null)
  625. {
  626. showError(trigger.getActingPlayer(), e);
  627. }
  628. _log.log(Level.WARNING, "Exception on onTrapAction() in notifyTrapAction(): " + e.getMessage(), e);
  629. return;
  630. }
  631. if (trigger.getActingPlayer() != null)
  632. {
  633. showResult(trigger.getActingPlayer(), res);
  634. }
  635. }
  636. /**
  637. * @param npc the spawned NPC
  638. */
  639. public final void notifySpawn(L2Npc npc)
  640. {
  641. try
  642. {
  643. onSpawn(npc);
  644. }
  645. catch (Exception e)
  646. {
  647. _log.log(Level.WARNING, "Exception on onSpawn() in notifySpawn(): " + e.getMessage(), e);
  648. }
  649. }
  650. /**
  651. * @param event
  652. * @param npc
  653. * @param player
  654. * @return {@code false} if there was an error or the message was sent, {@code true} otherwise
  655. */
  656. public final boolean notifyEvent(String event, L2Npc npc, L2PcInstance player)
  657. {
  658. String res = null;
  659. try
  660. {
  661. res = onAdvEvent(event, npc, player);
  662. }
  663. catch (Exception e)
  664. {
  665. return showError(player, e);
  666. }
  667. return showResult(player, res);
  668. }
  669. /**
  670. * @param player the player entering the world
  671. */
  672. public final void notifyEnterWorld(L2PcInstance player)
  673. {
  674. String res = null;
  675. try
  676. {
  677. res = onEnterWorld(player);
  678. }
  679. catch (Exception e)
  680. {
  681. showError(player, e);
  682. }
  683. showResult(player, res);
  684. }
  685. /**
  686. * @param npc
  687. * @param killer
  688. * @param isSummon
  689. */
  690. public final void notifyKill(L2Npc npc, L2PcInstance killer, boolean isSummon)
  691. {
  692. String res = null;
  693. try
  694. {
  695. res = onKill(npc, killer, isSummon);
  696. }
  697. catch (Exception e)
  698. {
  699. showError(killer, e);
  700. }
  701. showResult(killer, res);
  702. }
  703. /**
  704. * @param npc
  705. * @param qs
  706. * @return {@code false} if there was an error or the message was sent, {@code true} otherwise
  707. */
  708. public final boolean notifyTalk(L2Npc npc, QuestState qs)
  709. {
  710. String res = null;
  711. try
  712. {
  713. res = onTalk(npc, qs.getPlayer());
  714. }
  715. catch (Exception e)
  716. {
  717. return showError(qs.getPlayer(), e);
  718. }
  719. qs.getPlayer().setLastQuestNpcObject(npc.getObjectId());
  720. return showResult(qs.getPlayer(), res);
  721. }
  722. /**
  723. * Override the default NPC dialogs when a quest defines this for the given NPC.<br>
  724. * Note: If the default html for this npc needs to be shown, onFirstTalk should call npc.showChatWindow(player) and then return null.
  725. * @param npc the NPC whose dialogs to override
  726. * @param player the player talking to the NPC
  727. */
  728. public final void notifyFirstTalk(L2Npc npc, L2PcInstance player)
  729. {
  730. String res = null;
  731. try
  732. {
  733. res = onFirstTalk(npc, player);
  734. }
  735. catch (Exception e)
  736. {
  737. showError(player, e);
  738. }
  739. showResult(player, res);
  740. }
  741. /**
  742. * @param npc
  743. * @param player
  744. */
  745. public final void notifyAcquireSkillList(L2Npc npc, L2PcInstance player)
  746. {
  747. String res = null;
  748. try
  749. {
  750. res = onAcquireSkillList(npc, player);
  751. }
  752. catch (Exception e)
  753. {
  754. showError(player, e);
  755. }
  756. showResult(player, res);
  757. }
  758. /**
  759. * @param npc
  760. * @param player
  761. * @param skill
  762. */
  763. public final void notifyAcquireSkillInfo(L2Npc npc, L2PcInstance player, L2Skill skill)
  764. {
  765. String res = null;
  766. try
  767. {
  768. res = onAcquireSkillInfo(npc, player, skill);
  769. }
  770. catch (Exception e)
  771. {
  772. showError(player, e);
  773. }
  774. showResult(player, res);
  775. }
  776. /**
  777. * @param npc
  778. * @param player
  779. * @param skill
  780. */
  781. public final void notifyAcquireSkill(L2Npc npc, L2PcInstance player, L2Skill skill)
  782. {
  783. String res = null;
  784. try
  785. {
  786. res = onAcquireSkill(npc, player, skill);
  787. }
  788. catch (Exception e)
  789. {
  790. showError(player, e);
  791. }
  792. showResult(player, res);
  793. }
  794. /**
  795. * @param item
  796. * @param player
  797. * @return
  798. */
  799. public final boolean notifyItemTalk(L2ItemInstance item, L2PcInstance player)
  800. {
  801. String res = null;
  802. try
  803. {
  804. res = onItemTalk(item, player);
  805. if (res != null)
  806. {
  807. if (res.equalsIgnoreCase("true"))
  808. {
  809. return true;
  810. }
  811. else if (res.equalsIgnoreCase("false"))
  812. {
  813. return false;
  814. }
  815. }
  816. }
  817. catch (Exception e)
  818. {
  819. return showError(player, e);
  820. }
  821. return showResult(player, res);
  822. }
  823. /**
  824. * @param item
  825. * @param player
  826. * @return
  827. */
  828. public String onItemTalk(L2ItemInstance item, L2PcInstance player)
  829. {
  830. return null;
  831. }
  832. /**
  833. * @param item
  834. * @param player
  835. * @param event
  836. * @return
  837. */
  838. public final boolean notifyItemEvent(L2ItemInstance item, L2PcInstance player, String event)
  839. {
  840. String res = null;
  841. try
  842. {
  843. res = onItemEvent(item, player, event);
  844. if (res != null)
  845. {
  846. if (res.equalsIgnoreCase("true"))
  847. {
  848. return true;
  849. }
  850. else if (res.equalsIgnoreCase("false"))
  851. {
  852. return false;
  853. }
  854. }
  855. }
  856. catch (Exception e)
  857. {
  858. return showError(player, e);
  859. }
  860. return showResult(player, res);
  861. }
  862. /**
  863. * @param npc
  864. * @param caster
  865. * @param skill
  866. * @param targets
  867. * @param isSummon
  868. */
  869. public final void notifySkillSee(L2Npc npc, L2PcInstance caster, L2Skill skill, L2Object[] targets, boolean isSummon)
  870. {
  871. ThreadPoolManager.getInstance().executeAi(new SkillSee(this, npc, caster, skill, targets, isSummon));
  872. }
  873. /**
  874. * @param npc
  875. * @param caller
  876. * @param attacker
  877. * @param isSummon
  878. */
  879. public final void notifyFactionCall(L2Npc npc, L2Npc caller, L2PcInstance attacker, boolean isSummon)
  880. {
  881. String res = null;
  882. try
  883. {
  884. res = onFactionCall(npc, caller, attacker, isSummon);
  885. }
  886. catch (Exception e)
  887. {
  888. showError(attacker, e);
  889. }
  890. showResult(attacker, res);
  891. }
  892. /**
  893. * @param npc
  894. * @param player
  895. * @param isSummon
  896. */
  897. public final void notifyAggroRangeEnter(L2Npc npc, L2PcInstance player, boolean isSummon)
  898. {
  899. ThreadPoolManager.getInstance().executeAi(new AggroRangeEnter(this, npc, player, isSummon));
  900. }
  901. /**
  902. * @param npc the NPC that sees the creature
  903. * @param creature the creature seen by the NPC
  904. * @param isSummon
  905. */
  906. public final void notifySeeCreature(L2Npc npc, L2Character creature, boolean isSummon)
  907. {
  908. ThreadPoolManager.getInstance().executeAi(new SeeCreature(this, npc, creature, isSummon));
  909. }
  910. /**
  911. * @param eventName - name of event
  912. * @param sender - NPC, who sent event
  913. * @param receiver - NPC, who received event
  914. * @param reference - L2Object to pass, if needed
  915. */
  916. public final void notifyEventReceived(String eventName, L2Npc sender, L2Npc receiver, L2Object reference)
  917. {
  918. try
  919. {
  920. onEventReceived(eventName, sender, receiver, reference);
  921. }
  922. catch (Exception e)
  923. {
  924. _log.log(Level.WARNING, "Exception on onEventReceived() in notifyEventReceived(): " + e.getMessage(), e);
  925. }
  926. }
  927. /**
  928. * @param character
  929. * @param zone
  930. */
  931. public final void notifyEnterZone(L2Character character, L2ZoneType zone)
  932. {
  933. L2PcInstance player = character.getActingPlayer();
  934. String res = null;
  935. try
  936. {
  937. res = onEnterZone(character, zone);
  938. }
  939. catch (Exception e)
  940. {
  941. if (player != null)
  942. {
  943. showError(player, e);
  944. }
  945. }
  946. if (player != null)
  947. {
  948. showResult(player, res);
  949. }
  950. }
  951. /**
  952. * @param character
  953. * @param zone
  954. */
  955. public final void notifyExitZone(L2Character character, L2ZoneType zone)
  956. {
  957. L2PcInstance player = character.getActingPlayer();
  958. String res = null;
  959. try
  960. {
  961. res = onExitZone(character, zone);
  962. }
  963. catch (Exception e)
  964. {
  965. if (player != null)
  966. {
  967. showError(player, e);
  968. }
  969. }
  970. if (player != null)
  971. {
  972. showResult(player, res);
  973. }
  974. }
  975. /**
  976. * @param winner
  977. * @param type {@code false} if there was an error, {@code true} otherwise
  978. */
  979. public final void notifyOlympiadWin(L2PcInstance winner, CompetitionType type)
  980. {
  981. try
  982. {
  983. onOlympiadWin(winner, type);
  984. }
  985. catch (Exception e)
  986. {
  987. showError(winner, e);
  988. }
  989. }
  990. /**
  991. * @param loser
  992. * @param type {@code false} if there was an error, {@code true} otherwise
  993. */
  994. public final void notifyOlympiadLose(L2PcInstance loser, CompetitionType type)
  995. {
  996. try
  997. {
  998. onOlympiadLose(loser, type);
  999. }
  1000. catch (Exception e)
  1001. {
  1002. showError(loser, e);
  1003. }
  1004. }
  1005. /**
  1006. * @param npc
  1007. */
  1008. public final void notifyMoveFinished(L2Npc npc)
  1009. {
  1010. try
  1011. {
  1012. onMoveFinished(npc);
  1013. }
  1014. catch (Exception e)
  1015. {
  1016. _log.log(Level.WARNING, "Exception on onMoveFinished() in notifyMoveFinished(): " + e.getMessage(), e);
  1017. }
  1018. }
  1019. /**
  1020. * @param npc
  1021. */
  1022. public final void notifyNodeArrived(L2Npc npc)
  1023. {
  1024. try
  1025. {
  1026. onNodeArrived(npc);
  1027. }
  1028. catch (Exception e)
  1029. {
  1030. _log.log(Level.WARNING, "Exception on onNodeArrived() in notifyNodeArrived(): " + e.getMessage(), e);
  1031. }
  1032. }
  1033. /**
  1034. * @param npc
  1035. */
  1036. public final void notifyRouteFinished(L2Npc npc)
  1037. {
  1038. try
  1039. {
  1040. onRouteFinished(npc);
  1041. }
  1042. catch (Exception e)
  1043. {
  1044. _log.log(Level.WARNING, "Exception on onRouteFinished() in notifyRouteFinished(): " + e.getMessage(), e);
  1045. }
  1046. }
  1047. // These are methods that java calls to invoke scripts.
  1048. /**
  1049. * This function is called in place of {@link #onAttack(L2Npc, L2PcInstance, int, boolean, L2Skill)} if the former is not implemented.<br>
  1050. * If a script contains both onAttack(..) implementations, then this method will never be called unless the script's {@link #onAttack(L2Npc, L2PcInstance, int, boolean, L2Skill)} explicitly calls this method.
  1051. * @param npc this parameter contains a reference to the exact instance of the NPC that got attacked the NPC.
  1052. * @param attacker this parameter contains a reference to the exact instance of the player who attacked.
  1053. * @param damage this parameter represents the total damage that this attack has inflicted to the NPC.
  1054. * @param isSummon this parameter if it's {@code false} it denotes that the attacker was indeed the player, else it specifies that the damage was actually dealt by the player's pet.
  1055. * @return
  1056. */
  1057. public String onAttack(L2Npc npc, L2PcInstance attacker, int damage, boolean isSummon)
  1058. {
  1059. return null;
  1060. }
  1061. /**
  1062. * This function is called whenever a player attacks an NPC that is registered for the quest.<br>
  1063. * If is not overridden by a subclass, then default to the returned value of the simpler (and older) {@link #onAttack(L2Npc, L2PcInstance, int, boolean)} override.<br>
  1064. * @param npc this parameter contains a reference to the exact instance of the NPC that got attacked.
  1065. * @param attacker this parameter contains a reference to the exact instance of the player who attacked the NPC.
  1066. * @param damage this parameter represents the total damage that this attack has inflicted to the NPC.
  1067. * @param isSummon this parameter if it's {@code false} it denotes that the attacker was indeed the player, else it specifies that the damage was actually dealt by the player's summon
  1068. * @param skill parameter is the skill that player used to attack NPC.
  1069. * @return
  1070. */
  1071. public String onAttack(L2Npc npc, L2PcInstance attacker, int damage, boolean isSummon, L2Skill skill)
  1072. {
  1073. return onAttack(npc, attacker, damage, isSummon);
  1074. }
  1075. /**
  1076. * This function is called whenever an <b>exact instance</b> of a character who was previously registered for this event dies.<br>
  1077. * The registration for {@link #onDeath(L2Character, L2Character, QuestState)} events <b>is not</b> done via the quest itself, but it is instead handled by the QuestState of a particular player.
  1078. * @param killer this parameter contains a reference to the exact instance of the NPC that <b>killed</b> the character.
  1079. * @param victim this parameter contains a reference to the exact instance of the character that got killed.
  1080. * @param qs this parameter contains a reference to the QuestState of whomever was interested (waiting) for this kill.
  1081. * @return
  1082. */
  1083. public String onDeath(L2Character killer, L2Character victim, QuestState qs)
  1084. {
  1085. return onAdvEvent("", ((killer instanceof L2Npc) ? ((L2Npc) killer) : null), qs.getPlayer());
  1086. }
  1087. /**
  1088. * This function is called whenever a player clicks on a link in a quest dialog and whenever a timer fires.<br>
  1089. * If is not overridden by a subclass, then default to the returned value of the simpler (and older) {@link #onEvent(String, QuestState)} override.<br>
  1090. * If the player has a quest state, use it as parameter in the next call, otherwise return null.
  1091. * @param event this parameter contains a string identifier for the event.<br>
  1092. * Generally, this string is passed directly via the link.<br>
  1093. * For example:<br>
  1094. * <code>
  1095. * &lt;a action="bypass -h Quest 626_ADarkTwilight 31517-01.htm"&gt;hello&lt;/a&gt;
  1096. * </code><br>
  1097. * The above link sets the event variable to "31517-01.htm" for the quest 626_ADarkTwilight.<br>
  1098. * In the case of timers, this will be the name of the timer.<br>
  1099. * This parameter serves as a sort of identifier.
  1100. * @param npc this parameter contains a reference to the instance of NPC associated with this event.<br>
  1101. * This may be the NPC registered in a timer, or the NPC with whom a player is speaking, etc.<br>
  1102. * This parameter may be {@code null} in certain circumstances.
  1103. * @param player this parameter contains a reference to the player participating in this function.<br>
  1104. * It may be the player speaking to the NPC, or the player who caused a timer to start (and owns that timer).<br>
  1105. * This parameter may be {@code null} in certain circumstances.
  1106. * @return the text returned by the event (may be {@code null}, a filename or just text)
  1107. */
  1108. public String onAdvEvent(String event, L2Npc npc, L2PcInstance player)
  1109. {
  1110. if (player != null)
  1111. {
  1112. final QuestState qs = player.getQuestState(getName());
  1113. if (qs != null)
  1114. {
  1115. return onEvent(event, qs);
  1116. }
  1117. }
  1118. return null;
  1119. }
  1120. /**
  1121. * This function is called in place of {@link #onAdvEvent(String, L2Npc, L2PcInstance)} if the former is not implemented.<br>
  1122. * If a script contains both {@link #onAdvEvent(String, L2Npc, L2PcInstance)} and this implementation, then this method will never be called unless the script's {@link #onAdvEvent(String, L2Npc, L2PcInstance)} explicitly calls this method.
  1123. * @param event this parameter contains a string identifier for the event.<br>
  1124. * Generally, this string is passed directly via the link.<br>
  1125. * For example:<br>
  1126. * <code>
  1127. * &lt;a action="bypass -h Quest 626_ADarkTwilight 31517-01.htm"&gt;hello&lt;/a&gt;
  1128. * </code><br>
  1129. * The above link sets the event variable to "31517-01.htm" for the quest 626_ADarkTwilight.<br>
  1130. * In the case of timers, this will be the name of the timer.<br>
  1131. * This parameter serves as a sort of identifier.
  1132. * @param qs this parameter contains a reference to the quest state of the player who used the link or started the timer.
  1133. * @return the text returned by the event (may be {@code null}, a filename or just text)
  1134. */
  1135. public String onEvent(String event, QuestState qs)
  1136. {
  1137. return null;
  1138. }
  1139. /**
  1140. * This function is called whenever a player kills a NPC that is registered for the quest.
  1141. * @param npc this parameter contains a reference to the exact instance of the NPC that got killed.
  1142. * @param killer this parameter contains a reference to the exact instance of the player who killed the NPC.
  1143. * @param isSummon this parameter if it's {@code false} it denotes that the attacker was indeed the player, else it specifies that the killer was the player's pet.
  1144. * @return the text returned by the event (may be {@code null}, a filename or just text)
  1145. */
  1146. public String onKill(L2Npc npc, L2PcInstance killer, boolean isSummon)
  1147. {
  1148. return null;
  1149. }
  1150. /**
  1151. * This function is called whenever a player clicks to the "Quest" link of an NPC that is registered for the quest.
  1152. * @param npc this parameter contains a reference to the exact instance of the NPC that the player is talking with.
  1153. * @param talker this parameter contains a reference to the exact instance of the player who is talking to the NPC.
  1154. * @return the text returned by the event (may be {@code null}, a filename or just text)
  1155. */
  1156. public String onTalk(L2Npc npc, L2PcInstance talker)
  1157. {
  1158. return null;
  1159. }
  1160. /**
  1161. * This function is called whenever a player talks to an NPC that is registered for the quest.<br>
  1162. * That is, it is triggered from the very first click on the NPC, not via another dialog.<br>
  1163. * <b>Note 1:</b><br>
  1164. * Each NPC can be registered to at most one quest for triggering this function.<br>
  1165. * In other words, the same one NPC cannot respond to an "onFirstTalk" request from two different quests.<br>
  1166. * Attempting to register an NPC in two different quests for this function will result in one of the two registration being ignored.<br>
  1167. * <b>Note 2:</b><br>
  1168. * Since a Quest link isn't clicked in order to reach this, a quest state can be invalid within this function.<br>
  1169. * The coder of the script may need to create a new quest state (if necessary).<br>
  1170. * <b>Note 3:</b><br>
  1171. * The returned value of onFirstTalk replaces the default HTML that would have otherwise been loaded from a sub-folder of DatapackRoot/game/data/html/.<br>
  1172. * If you wish to show the default HTML, within onFirstTalk do npc.showChatWindow(player) and then return ""<br>
  1173. * @param npc this parameter contains a reference to the exact instance of the NPC that the player is talking with.
  1174. * @param player this parameter contains a reference to the exact instance of the player who is talking to the NPC.
  1175. * @return the text returned by the event (may be {@code null}, a filename or just text)
  1176. * @since <a href="http://trac.l2jserver.com/changeset/771">Jython AI support for "onFirstTalk"</a>
  1177. */
  1178. public String onFirstTalk(L2Npc npc, L2PcInstance player)
  1179. {
  1180. return null;
  1181. }
  1182. /**
  1183. * @param item
  1184. * @param player
  1185. * @param event
  1186. * @return
  1187. */
  1188. public String onItemEvent(L2ItemInstance item, L2PcInstance player, String event)
  1189. {
  1190. return null;
  1191. }
  1192. /**
  1193. * This function is called whenever a player request a skill list.<br>
  1194. * TODO: Re-implement, since Skill Trees rework it's support was removed.
  1195. * @param npc this parameter contains a reference to the exact instance of the NPC that the player requested the skill list.
  1196. * @param player this parameter contains a reference to the exact instance of the player who requested the skill list.
  1197. * @return
  1198. */
  1199. public String onAcquireSkillList(L2Npc npc, L2PcInstance player)
  1200. {
  1201. return null;
  1202. }
  1203. /**
  1204. * This function is called whenever a player request a skill info.<br>
  1205. * TODO: Re-implement, since Skill Trees rework it's support was removed.
  1206. * @param npc this parameter contains a reference to the exact instance of the NPC that the player requested the skill info.
  1207. * @param player this parameter contains a reference to the exact instance of the player who requested the skill info.
  1208. * @param skill this parameter contains a reference to the skill that the player requested its info.
  1209. * @return
  1210. */
  1211. public String onAcquireSkillInfo(L2Npc npc, L2PcInstance player, L2Skill skill)
  1212. {
  1213. return null;
  1214. }
  1215. /**
  1216. * This function is called whenever a player acquire a skill.<br>
  1217. * TODO: Re-implement, since Skill Trees rework it's support was removed.
  1218. * @param npc this parameter contains a reference to the exact instance of the NPC that the player requested the skill.
  1219. * @param player this parameter contains a reference to the exact instance of the player who requested the skill.
  1220. * @param skill this parameter contains a reference to the skill that the player requested.
  1221. * @return
  1222. */
  1223. public String onAcquireSkill(L2Npc npc, L2PcInstance player, L2Skill skill)
  1224. {
  1225. return null;
  1226. }
  1227. /**
  1228. * This function is called whenever a player uses a quest item that has a quest events list.<br>
  1229. * TODO: complete this documentation and unhardcode it to work with all item uses not with those listed.
  1230. * @param item the quest item that the player used
  1231. * @param player the player who used the item
  1232. * @return
  1233. */
  1234. public String onItemUse(L2Item item, L2PcInstance player)
  1235. {
  1236. return null;
  1237. }
  1238. /**
  1239. * This function is called whenever a player casts a skill near a registered NPC (1000 distance).<br>
  1240. * <b>Note:</b><br>
  1241. * If a skill does damage, both onSkillSee(..) and onAttack(..) will be triggered for the damaged NPC!<br>
  1242. * However, only onSkillSee(..) will be triggered if the skill does no damage,<br>
  1243. * or if it damages an NPC who has no onAttack(..) registration while near another NPC who has an onSkillSee registration.<br>
  1244. * TODO: confirm if the distance is 1000 and unhardcode.
  1245. * @param npc the NPC that saw the skill
  1246. * @param caster the player who cast the skill
  1247. * @param skill the actual skill that was used
  1248. * @param targets an array of all objects (can be any type of object, including mobs and players) that were affected by the skill
  1249. * @param isSummon if {@code true}, the skill was actually cast by the player's summon, not the player himself
  1250. * @return
  1251. */
  1252. public String onSkillSee(L2Npc npc, L2PcInstance caster, L2Skill skill, L2Object[] targets, boolean isSummon)
  1253. {
  1254. return null;
  1255. }
  1256. /**
  1257. * This function is called whenever an NPC finishes casting a skill.
  1258. * @param npc the NPC that casted the skill.
  1259. * @param player the player who is the target of the skill. Can be {@code null}.
  1260. * @param skill the actual skill that was used by the NPC.
  1261. * @return
  1262. */
  1263. public String onSpellFinished(L2Npc npc, L2PcInstance player, L2Skill skill)
  1264. {
  1265. return null;
  1266. }
  1267. /**
  1268. * This function is called whenever a trap action is performed.
  1269. * @param trap this parameter contains a reference to the exact instance of the trap that was activated.
  1270. * @param trigger this parameter contains a reference to the exact instance of the character that triggered the action.
  1271. * @param action this parameter contains a reference to the action that was triggered.
  1272. * @return
  1273. */
  1274. public String onTrapAction(L2Trap trap, L2Character trigger, TrapAction action)
  1275. {
  1276. return null;
  1277. }
  1278. /**
  1279. * This function is called whenever an NPC spawns or re-spawns and passes a reference to the newly (re)spawned NPC.<br>
  1280. * Currently the only function that has no reference to a player.<br>
  1281. * It is useful for initializations, starting quest timers, displaying chat (NpcSay), and more.
  1282. * @param npc this parameter contains a reference to the exact instance of the NPC who just (re)spawned.
  1283. * @return
  1284. */
  1285. public String onSpawn(L2Npc npc)
  1286. {
  1287. return null;
  1288. }
  1289. /**
  1290. * This function is called whenever an NPC is called by another NPC in the same faction.
  1291. * @param npc this parameter contains a reference to the exact instance of the NPC who is being asked for help.
  1292. * @param caller this parameter contains a reference to the exact instance of the NPC who is asking for help.<br>
  1293. * @param attacker this parameter contains a reference to the exact instance of the player who attacked.
  1294. * @param isSummon this parameter if it's {@code false} it denotes that the attacker was indeed the player, else it specifies that the attacker was the player's summon.
  1295. * @return
  1296. */
  1297. public String onFactionCall(L2Npc npc, L2Npc caller, L2PcInstance attacker, boolean isSummon)
  1298. {
  1299. return null;
  1300. }
  1301. /**
  1302. * This function is called whenever a player enters an NPC aggression range.
  1303. * @param npc this parameter contains a reference to the exact instance of the NPC whose aggression range is being transgressed.
  1304. * @param player this parameter contains a reference to the exact instance of the player who is entering the NPC's aggression range.
  1305. * @param isSummon this parameter if it's {@code false} it denotes that the character that entered the aggression range was indeed the player, else it specifies that the character was the player's summon.
  1306. * @return
  1307. */
  1308. public String onAggroRangeEnter(L2Npc npc, L2PcInstance player, boolean isSummon)
  1309. {
  1310. return null;
  1311. }
  1312. /**
  1313. * This function is called whenever a NPC "sees" a creature.
  1314. * @param npc the NPC who sees the creature
  1315. * @param creature the creature seen by the NPC
  1316. * @param isSummon this parameter if it's {@code false} it denotes that the character seen by the NPC was indeed the player, else it specifies that the character was the player's summon
  1317. * @return
  1318. */
  1319. public String onSeeCreature(L2Npc npc, L2Character creature, boolean isSummon)
  1320. {
  1321. return null;
  1322. }
  1323. /**
  1324. * This function is called whenever a player enters the game.
  1325. * @param player this parameter contains a reference to the exact instance of the player who is entering to the world.
  1326. * @return
  1327. */
  1328. public String onEnterWorld(L2PcInstance player)
  1329. {
  1330. return null;
  1331. }
  1332. /**
  1333. * This function is called whenever a character enters a registered zone.
  1334. * @param character this parameter contains a reference to the exact instance of the character who is entering the zone.
  1335. * @param zone this parameter contains a reference to the zone.
  1336. * @return
  1337. */
  1338. public String onEnterZone(L2Character character, L2ZoneType zone)
  1339. {
  1340. return null;
  1341. }
  1342. /**
  1343. * This function is called whenever a character exits a registered zone.
  1344. * @param character this parameter contains a reference to the exact instance of the character who is exiting the zone.
  1345. * @param zone this parameter contains a reference to the zone.
  1346. * @return
  1347. */
  1348. public String onExitZone(L2Character character, L2ZoneType zone)
  1349. {
  1350. return null;
  1351. }
  1352. /**
  1353. * @param eventName - name of event
  1354. * @param sender - NPC, who sent event
  1355. * @param receiver - NPC, who received event
  1356. * @param reference - L2Object to pass, if needed
  1357. * @return
  1358. */
  1359. public String onEventReceived(String eventName, L2Npc sender, L2Npc receiver, L2Object reference)
  1360. {
  1361. return null;
  1362. }
  1363. /**
  1364. * This function is called whenever a player wins an Olympiad Game.
  1365. * @param winner this parameter contains a reference to the exact instance of the player who won the competition.
  1366. * @param type this parameter contains a reference to the competition type.
  1367. */
  1368. public void onOlympiadWin(L2PcInstance winner, CompetitionType type)
  1369. {
  1370. }
  1371. /**
  1372. * This function is called whenever a player looses an Olympiad Game.
  1373. * @param loser this parameter contains a reference to the exact instance of the player who lose the competition.
  1374. * @param type this parameter contains a reference to the competition type.
  1375. */
  1376. public void onOlympiadLose(L2PcInstance loser, CompetitionType type)
  1377. {
  1378. }
  1379. /**
  1380. * This function is called whenever a NPC finishes moving
  1381. * @param npc registered NPC
  1382. */
  1383. public void onMoveFinished(L2Npc npc)
  1384. {
  1385. }
  1386. /**
  1387. * This function is called whenever a walker NPC (controlled by WalkingManager) arrive a walking node
  1388. * @param npc registered NPC
  1389. */
  1390. public void onNodeArrived(L2Npc npc)
  1391. {
  1392. }
  1393. /**
  1394. * This function is called whenever a walker NPC (controlled by WalkingManager) arrive to last node
  1395. * @param npc registered NPC
  1396. */
  1397. public void onRouteFinished(L2Npc npc)
  1398. {
  1399. }
  1400. /**
  1401. * Show an error message to the specified player.
  1402. * @param player the player to whom to send the error (must be a GM)
  1403. * @param t the {@link Throwable} to get the message/stacktrace from
  1404. * @return {@code false}
  1405. */
  1406. public boolean showError(L2PcInstance player, Throwable t)
  1407. {
  1408. _log.log(Level.WARNING, getScriptFile().getAbsolutePath(), t);
  1409. if (t.getMessage() == null)
  1410. {
  1411. _log.warning(getClass().getSimpleName() + ": " + t.getMessage());
  1412. }
  1413. if ((player != null) && player.getAccessLevel().isGm())
  1414. {
  1415. String res = "<html><body><title>Script error</title>" + Util.getStackTrace(t) + "</body></html>";
  1416. return showResult(player, res);
  1417. }
  1418. return false;
  1419. }
  1420. /**
  1421. * Show a message to the specified player.<br>
  1422. * <u><i>Concept:</i></u><br>
  1423. * Three cases are managed according to the value of the {@code res} parameter:<br>
  1424. * <ul>
  1425. * <li><u>{@code res} ends with ".htm" or ".html":</u> the contents of the specified HTML file are shown in a dialog window</li>
  1426. * <li><u>{@code res} starts with "&lt;html&gt;":</u> the contents of the parameter are shown in a dialog window</li>
  1427. * <li><u>all other cases :</u> the text contained in the parameter is shown in chat</li>
  1428. * </ul>
  1429. * @param player the player to whom to show the result
  1430. * @param res the message to show to the player
  1431. * @return {@code false} if the message was sent, {@code true} otherwise
  1432. */
  1433. public boolean showResult(L2PcInstance player, String res)
  1434. {
  1435. if ((res == null) || res.isEmpty() || (player == null))
  1436. {
  1437. return true;
  1438. }
  1439. if (res.endsWith(".htm") || res.endsWith(".html"))
  1440. {
  1441. showHtmlFile(player, res);
  1442. }
  1443. else if (res.startsWith("<html>"))
  1444. {
  1445. NpcHtmlMessage npcReply = new NpcHtmlMessage(5);
  1446. npcReply.setHtml(res);
  1447. npcReply.replace("%playername%", player.getName());
  1448. player.sendPacket(npcReply);
  1449. player.sendPacket(ActionFailed.STATIC_PACKET);
  1450. }
  1451. else
  1452. {
  1453. player.sendMessage(res);
  1454. }
  1455. return false;
  1456. }
  1457. /**
  1458. * Loads all quest states and variables for the specified player.
  1459. * @param player the player who is entering the world
  1460. */
  1461. public static final void playerEnter(L2PcInstance player)
  1462. {
  1463. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1464. PreparedStatement invalidQuestData = con.prepareStatement("DELETE FROM character_quests WHERE charId = ? AND name = ?");
  1465. PreparedStatement invalidQuestDataVar = con.prepareStatement("DELETE FROM character_quests WHERE charId = ? AND name = ? AND var = ?");
  1466. PreparedStatement ps1 = con.prepareStatement("SELECT name, value FROM character_quests WHERE charId = ? AND var = ?"))
  1467. {
  1468. // Get list of quests owned by the player from database
  1469. ps1.setInt(1, player.getObjectId());
  1470. ps1.setString(2, "<state>");
  1471. try (ResultSet rs = ps1.executeQuery())
  1472. {
  1473. while (rs.next())
  1474. {
  1475. // Get Id of the quest and Id of its state
  1476. String questId = rs.getString("name");
  1477. String statename = rs.getString("value");
  1478. // Search quest associated with the Id
  1479. Quest q = QuestManager.getInstance().getQuest(questId);
  1480. if (q == null)
  1481. {
  1482. _log.finer("Unknown quest " + questId + " for player " + player.getName());
  1483. if (Config.AUTODELETE_INVALID_QUEST_DATA)
  1484. {
  1485. invalidQuestData.setInt(1, player.getObjectId());
  1486. invalidQuestData.setString(2, questId);
  1487. invalidQuestData.executeUpdate();
  1488. }
  1489. continue;
  1490. }
  1491. // Create a new QuestState for the player that will be added to the player's list of quests
  1492. new QuestState(q, player, State.getStateId(statename));
  1493. }
  1494. }
  1495. // Get list of quests owned by the player from the DB in order to add variables used in the quest.
  1496. try (PreparedStatement ps2 = con.prepareStatement("SELECT name, var, value FROM character_quests WHERE charId = ? AND var <> ?"))
  1497. {
  1498. ps2.setInt(1, player.getObjectId());
  1499. ps2.setString(2, "<state>");
  1500. try (ResultSet rs = ps2.executeQuery())
  1501. {
  1502. while (rs.next())
  1503. {
  1504. String questId = rs.getString("name");
  1505. String var = rs.getString("var");
  1506. String value = rs.getString("value");
  1507. // Get the QuestState saved in the loop before
  1508. QuestState qs = player.getQuestState(questId);
  1509. if (qs == null)
  1510. {
  1511. _log.finer("Lost variable " + var + " in quest " + questId + " for player " + player.getName());
  1512. if (Config.AUTODELETE_INVALID_QUEST_DATA)
  1513. {
  1514. invalidQuestDataVar.setInt(1, player.getObjectId());
  1515. invalidQuestDataVar.setString(2, questId);
  1516. invalidQuestDataVar.setString(3, var);
  1517. invalidQuestDataVar.executeUpdate();
  1518. }
  1519. continue;
  1520. }
  1521. // Add parameter to the quest
  1522. qs.setInternal(var, value);
  1523. }
  1524. }
  1525. }
  1526. }
  1527. catch (Exception e)
  1528. {
  1529. _log.log(Level.WARNING, "could not insert char quest:", e);
  1530. }
  1531. // events
  1532. for (String name : _allEventsS.keySet())
  1533. {
  1534. player.processQuestEvent(name, "enter");
  1535. }
  1536. }
  1537. /**
  1538. * Insert (or update) in the database variables that need to stay persistent for this quest after a reboot.<br>
  1539. * This function is for storage of values that do not related to a specific player but are global for all characters.<br>
  1540. * For example, if we need to disable a quest-gatekeeper until a certain time (as is done with some grand-boss gatekeepers), we can save that time in the DB.
  1541. * @param var the name of the variable to save
  1542. * @param value the value of the variable
  1543. */
  1544. public final void saveGlobalQuestVar(String var, String value)
  1545. {
  1546. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1547. PreparedStatement statement = con.prepareStatement("REPLACE INTO quest_global_data (quest_name,var,value) VALUES (?,?,?)"))
  1548. {
  1549. statement.setString(1, getName());
  1550. statement.setString(2, var);
  1551. statement.setString(3, value);
  1552. statement.executeUpdate();
  1553. }
  1554. catch (Exception e)
  1555. {
  1556. _log.log(Level.WARNING, "could not insert global quest variable:", e);
  1557. }
  1558. }
  1559. /**
  1560. * Read from the database a previously saved variable for this quest.<br>
  1561. * Due to performance considerations, this function should best be used only when the quest is first loaded.<br>
  1562. * Subclasses of this class can define structures into which these loaded values can be saved.<br>
  1563. * However, on-demand usage of this function throughout the script is not prohibited, only not recommended.<br>
  1564. * Values read from this function were entered by calls to "saveGlobalQuestVar".
  1565. * @param var the name of the variable to load
  1566. * @return the current value of the specified variable, or an empty string if the variable does not exist
  1567. */
  1568. public final String loadGlobalQuestVar(String var)
  1569. {
  1570. String result = "";
  1571. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1572. PreparedStatement statement = con.prepareStatement("SELECT value FROM quest_global_data WHERE quest_name = ? AND var = ?"))
  1573. {
  1574. statement.setString(1, getName());
  1575. statement.setString(2, var);
  1576. try (ResultSet rs = statement.executeQuery())
  1577. {
  1578. if (rs.first())
  1579. {
  1580. result = rs.getString(1);
  1581. }
  1582. }
  1583. }
  1584. catch (Exception e)
  1585. {
  1586. _log.log(Level.WARNING, "could not load global quest variable:", e);
  1587. }
  1588. return result;
  1589. }
  1590. /**
  1591. * Permanently delete from the database a global quest variable that was previously saved for this quest.
  1592. * @param var the name of the variable to delete
  1593. */
  1594. public final void deleteGlobalQuestVar(String var)
  1595. {
  1596. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1597. PreparedStatement statement = con.prepareStatement("DELETE FROM quest_global_data WHERE quest_name = ? AND var = ?"))
  1598. {
  1599. statement.setString(1, getName());
  1600. statement.setString(2, var);
  1601. statement.executeUpdate();
  1602. }
  1603. catch (Exception e)
  1604. {
  1605. _log.log(Level.WARNING, "could not delete global quest variable:", e);
  1606. }
  1607. }
  1608. /**
  1609. * Permanently delete from the database all global quest variables that were previously saved for this quest.
  1610. */
  1611. public final void deleteAllGlobalQuestVars()
  1612. {
  1613. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1614. PreparedStatement statement = con.prepareStatement("DELETE FROM quest_global_data WHERE quest_name = ?"))
  1615. {
  1616. statement.setString(1, getName());
  1617. statement.executeUpdate();
  1618. }
  1619. catch (Exception e)
  1620. {
  1621. _log.log(Level.WARNING, "could not delete global quest variables:", e);
  1622. }
  1623. }
  1624. /**
  1625. * Insert in the database the quest for the player.
  1626. * @param qs the {@link QuestState} object whose variable to insert
  1627. * @param var the name of the variable
  1628. * @param value the value of the variable
  1629. */
  1630. public static void createQuestVarInDb(QuestState qs, String var, String value)
  1631. {
  1632. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1633. PreparedStatement statement = con.prepareStatement("INSERT INTO character_quests (charId,name,var,value) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE value=?"))
  1634. {
  1635. statement.setInt(1, qs.getPlayer().getObjectId());
  1636. statement.setString(2, qs.getQuestName());
  1637. statement.setString(3, var);
  1638. statement.setString(4, value);
  1639. statement.setString(5, value);
  1640. statement.executeUpdate();
  1641. }
  1642. catch (Exception e)
  1643. {
  1644. _log.log(Level.WARNING, "could not insert char quest:", e);
  1645. }
  1646. }
  1647. /**
  1648. * Update the value of the variable "var" for the specified quest in database
  1649. * @param qs the {@link QuestState} object whose variable to update
  1650. * @param var the name of the variable
  1651. * @param value the value of the variable
  1652. */
  1653. public static void updateQuestVarInDb(QuestState qs, String var, String value)
  1654. {
  1655. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1656. PreparedStatement statement = con.prepareStatement("UPDATE character_quests SET value=? WHERE charId=? AND name=? AND var = ?"))
  1657. {
  1658. statement.setString(1, value);
  1659. statement.setInt(2, qs.getPlayer().getObjectId());
  1660. statement.setString(3, qs.getQuestName());
  1661. statement.setString(4, var);
  1662. statement.executeUpdate();
  1663. }
  1664. catch (Exception e)
  1665. {
  1666. _log.log(Level.WARNING, "could not update char quest:", e);
  1667. }
  1668. }
  1669. /**
  1670. * Delete a variable of player's quest from the database.
  1671. * @param qs the {@link QuestState} object whose variable to delete
  1672. * @param var the name of the variable to delete
  1673. */
  1674. public static void deleteQuestVarInDb(QuestState qs, String var)
  1675. {
  1676. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1677. PreparedStatement statement = con.prepareStatement("DELETE FROM character_quests WHERE charId=? AND name=? AND var=?"))
  1678. {
  1679. statement.setInt(1, qs.getPlayer().getObjectId());
  1680. statement.setString(2, qs.getQuestName());
  1681. statement.setString(3, var);
  1682. statement.executeUpdate();
  1683. }
  1684. catch (Exception e)
  1685. {
  1686. _log.log(Level.WARNING, "could not delete char quest:", e);
  1687. }
  1688. }
  1689. /**
  1690. * Delete from the database all variables and states of the specified quest state.
  1691. * @param qs the {@link QuestState} object whose variables to delete
  1692. * @param repeatable if {@code false}, the state variable will be preserved, otherwise it will be deleted as well
  1693. */
  1694. public static void deleteQuestInDb(QuestState qs, boolean repeatable)
  1695. {
  1696. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  1697. PreparedStatement ps = con.prepareStatement(repeatable ? QUEST_DELETE_FROM_CHAR_QUERY : QUEST_DELETE_FROM_CHAR_QUERY_NON_REPEATABLE_QUERY))
  1698. {
  1699. ps.setInt(1, qs.getPlayer().getObjectId());
  1700. ps.setString(2, qs.getQuestName());
  1701. if (!repeatable)
  1702. {
  1703. ps.setString(3, "<state>");
  1704. }
  1705. ps.executeUpdate();
  1706. }
  1707. catch (Exception e)
  1708. {
  1709. _log.log(Level.WARNING, "could not delete char quest:", e);
  1710. }
  1711. }
  1712. /**
  1713. * Create a database record for the specified quest state.
  1714. * @param qs the {@link QuestState} object whose data to write in the database
  1715. */
  1716. public static void createQuestInDb(QuestState qs)
  1717. {
  1718. createQuestVarInDb(qs, "<state>", State.getStateName(qs.getState()));
  1719. }
  1720. /**
  1721. * Update informations regarding quest in database.<br>
  1722. * Actions:<br>
  1723. * <ul>
  1724. * <li>Get Id state of the quest recorded in object qs</li>
  1725. * <li>Test if quest is completed. If true, add a star (*) before the Id state</li>
  1726. * <li>Save in database the Id state (with or without the star) for the variable called "&lt;state&gt;" of the quest</li>
  1727. * </ul>
  1728. * @param qs the quest state
  1729. */
  1730. public static void updateQuestInDb(QuestState qs)
  1731. {
  1732. updateQuestVarInDb(qs, "<state>", State.getStateName(qs.getState()));
  1733. }
  1734. /**
  1735. * @param player the player whose language settings to use in finding the html of the right language
  1736. * @return the default html for when no quest is available: "You are either not on a quest that involves this NPC.."
  1737. */
  1738. public static String getNoQuestMsg(L2PcInstance player)
  1739. {
  1740. final String result = HtmCache.getInstance().getHtm(player.getHtmlPrefix(), "data/html/noquest.htm");
  1741. if ((result != null) && (result.length() > 0))
  1742. {
  1743. return result;
  1744. }
  1745. return DEFAULT_NO_QUEST_MSG;
  1746. }
  1747. /**
  1748. * @param player the player whose language settings to use in finding the html of the right language
  1749. * @return the default html for when no quest is already completed: "This quest has already been completed."
  1750. */
  1751. public static String getAlreadyCompletedMsg(L2PcInstance player)
  1752. {
  1753. final String result = HtmCache.getInstance().getHtm(player.getHtmlPrefix(), "data/html/alreadycompleted.htm");
  1754. if ((result != null) && (result.length() > 0))
  1755. {
  1756. return result;
  1757. }
  1758. return DEFAULT_ALREADY_COMPLETED_MSG;
  1759. }
  1760. /**
  1761. * Add this quest to the list of quests that the passed mob will respond to for the specified Event type.
  1762. * @param eventType type of event being registered
  1763. * @param npcIds NPC Ids to register
  1764. */
  1765. public void addEventId(QuestEventType eventType, int... npcIds)
  1766. {
  1767. try
  1768. {
  1769. for (int npcId : npcIds)
  1770. {
  1771. final L2NpcTemplate t = NpcTable.getInstance().getTemplate(npcId);
  1772. if (t != null)
  1773. {
  1774. t.addQuestEvent(eventType, this);
  1775. _questInvolvedNpcs.add(npcId);
  1776. }
  1777. }
  1778. }
  1779. catch (Exception e)
  1780. {
  1781. _log.log(Level.WARNING, "Exception on addEventId(): " + e.getMessage(), e);
  1782. }
  1783. }
  1784. // TODO: Remove after all Jython scripts are replaced with Java versions.
  1785. public void addStartNpc(int npcId)
  1786. {
  1787. addEventId(QuestEventType.QUEST_START, npcId);
  1788. }
  1789. public void addFirstTalkId(int npcId)
  1790. {
  1791. addEventId(QuestEventType.ON_FIRST_TALK, npcId);
  1792. }
  1793. public void addTalkId(int npcId)
  1794. {
  1795. addEventId(QuestEventType.ON_TALK, npcId);
  1796. }
  1797. public void addKillId(int killId)
  1798. {
  1799. addEventId(QuestEventType.ON_KILL, killId);
  1800. }
  1801. public void addAttackId(int npcId)
  1802. {
  1803. addEventId(QuestEventType.ON_ATTACK, npcId);
  1804. }
  1805. /**
  1806. * Add the quest to the NPC's startQuest
  1807. * @param npcIds
  1808. */
  1809. public void addStartNpc(int... npcIds)
  1810. {
  1811. addEventId(QuestEventType.QUEST_START, npcIds);
  1812. }
  1813. /**
  1814. * Add the quest to the NPC's first-talk (default action dialog)
  1815. * @param npcIds
  1816. */
  1817. public void addFirstTalkId(int... npcIds)
  1818. {
  1819. addEventId(QuestEventType.ON_FIRST_TALK, npcIds);
  1820. }
  1821. /**
  1822. * Add the NPC to the AcquireSkill dialog
  1823. * @param npcIds
  1824. */
  1825. public void addAcquireSkillId(int... npcIds)
  1826. {
  1827. addEventId(QuestEventType.ON_SKILL_LEARN, npcIds);
  1828. }
  1829. /**
  1830. * Add this quest to the list of quests that the passed mob will respond to for Attack Events.
  1831. * @param npcIds
  1832. */
  1833. public void addAttackId(int... npcIds)
  1834. {
  1835. addEventId(QuestEventType.ON_ATTACK, npcIds);
  1836. }
  1837. /**
  1838. * Add this quest to the list of quests that the passed mob will respond to for Kill Events.
  1839. * @param killIds
  1840. */
  1841. public void addKillId(int... killIds)
  1842. {
  1843. addEventId(QuestEventType.ON_KILL, killIds);
  1844. }
  1845. /**
  1846. * Add this quest event to the collection of NPC Ids that will respond to for on kill events.
  1847. * @param killIds the collection of NPC Ids
  1848. */
  1849. public void addKillId(Collection<Integer> killIds)
  1850. {
  1851. for (int killId : killIds)
  1852. {
  1853. addEventId(QuestEventType.ON_KILL, killId);
  1854. }
  1855. }
  1856. /**
  1857. * Add this quest to the list of quests that the passed npc will respond to for Talk Events.
  1858. * @param npcIds Id of the NPC
  1859. */
  1860. public void addTalkId(int... npcIds)
  1861. {
  1862. addEventId(QuestEventType.ON_TALK, npcIds);
  1863. }
  1864. /**
  1865. * Add this quest to the list of quests that the passed npc will respond to for Spawn Events.
  1866. * @param npcIds Id of the NPC
  1867. */
  1868. public void addSpawnId(int... npcIds)
  1869. {
  1870. addEventId(QuestEventType.ON_SPAWN, npcIds);
  1871. }
  1872. /**
  1873. * Add this quest to the list of quests that the passed npc will respond to for Skill-See Events.
  1874. * @param npcIds Id of the NPC
  1875. */
  1876. public void addSkillSeeId(int... npcIds)
  1877. {
  1878. addEventId(QuestEventType.ON_SKILL_SEE, npcIds);
  1879. }
  1880. /**
  1881. * @param npcIds
  1882. */
  1883. public void addSpellFinishedId(int... npcIds)
  1884. {
  1885. addEventId(QuestEventType.ON_SPELL_FINISHED, npcIds);
  1886. }
  1887. /**
  1888. * @param npcIds
  1889. */
  1890. public void addTrapActionId(int... npcIds)
  1891. {
  1892. addEventId(QuestEventType.ON_TRAP_ACTION, npcIds);
  1893. }
  1894. /**
  1895. * Add this quest to the list of quests that the passed npc will respond to for Faction Call Events.
  1896. * @param npcIds Id of the NPC
  1897. */
  1898. public void addFactionCallId(int... npcIds)
  1899. {
  1900. addEventId(QuestEventType.ON_FACTION_CALL, npcIds);
  1901. }
  1902. /**
  1903. * Add this quest to the list of quests that the passed npc will respond to for Character See Events.
  1904. * @param npcIds Id of the NPC
  1905. */
  1906. public void addAggroRangeEnterId(int... npcIds)
  1907. {
  1908. addEventId(QuestEventType.ON_AGGRO_RANGE_ENTER, npcIds);
  1909. }
  1910. /**
  1911. * @param npcIds NPC Ids to register to on see creature event
  1912. */
  1913. public void addSeeCreatureId(int... npcIds)
  1914. {
  1915. addEventId(QuestEventType.ON_SEE_CREATURE, npcIds);
  1916. }
  1917. /**
  1918. * @param zoneIds
  1919. * @return
  1920. */
  1921. public L2ZoneType[] addEnterZoneId(int... zoneIds)
  1922. {
  1923. L2ZoneType[] value = new L2ZoneType[zoneIds.length];
  1924. int i = 0;
  1925. for (int zoneId : zoneIds)
  1926. {
  1927. try
  1928. {
  1929. L2ZoneType zone = ZoneManager.getInstance().getZoneById(zoneId);
  1930. if (zone != null)
  1931. {
  1932. zone.addQuestEvent(QuestEventType.ON_ENTER_ZONE, this);
  1933. }
  1934. value[i++] = zone;
  1935. }
  1936. catch (Exception e)
  1937. {
  1938. _log.log(Level.WARNING, "Exception on addEnterZoneId(): " + e.getMessage(), e);
  1939. continue;
  1940. }
  1941. }
  1942. return value;
  1943. }
  1944. /**
  1945. * @param zoneIds
  1946. * @return
  1947. */
  1948. public L2ZoneType[] addExitZoneId(int... zoneIds)
  1949. {
  1950. L2ZoneType[] value = new L2ZoneType[zoneIds.length];
  1951. int i = 0;
  1952. for (int zoneId : zoneIds)
  1953. {
  1954. try
  1955. {
  1956. L2ZoneType zone = ZoneManager.getInstance().getZoneById(zoneId);
  1957. if (zone != null)
  1958. {
  1959. zone.addQuestEvent(QuestEventType.ON_EXIT_ZONE, this);
  1960. }
  1961. value[i++] = zone;
  1962. }
  1963. catch (Exception e)
  1964. {
  1965. _log.log(Level.WARNING, "Exception on addEnterZoneId(): " + e.getMessage(), e);
  1966. continue;
  1967. }
  1968. }
  1969. return value;
  1970. }
  1971. /**
  1972. * @param zoneId
  1973. * @return
  1974. */
  1975. public L2ZoneType addExitZoneId(int zoneId)
  1976. {
  1977. try
  1978. {
  1979. L2ZoneType zone = ZoneManager.getInstance().getZoneById(zoneId);
  1980. if (zone != null)
  1981. {
  1982. zone.addQuestEvent(QuestEventType.ON_EXIT_ZONE, this);
  1983. }
  1984. return zone;
  1985. }
  1986. catch (Exception e)
  1987. {
  1988. _log.log(Level.WARNING, "Exception on addExitZoneId(): " + e.getMessage(), e);
  1989. return null;
  1990. }
  1991. }
  1992. /**
  1993. * Register onEventReceived trigger for NPC
  1994. * @param npcIds
  1995. */
  1996. public void addEventReceivedId(int... npcIds)
  1997. {
  1998. addEventId(QuestEventType.ON_EVENT_RECEIVED, npcIds);
  1999. }
  2000. /**
  2001. * Register onMoveFinished trigger for NPC
  2002. * @param npcIds
  2003. */
  2004. public void addMoveFinishedId(int... npcIds)
  2005. {
  2006. addEventId(QuestEventType.ON_MOVE_FINISHED, npcIds);
  2007. }
  2008. /**
  2009. * Register onNodeArrived trigger for NPC
  2010. * @param npcIds id of NPC to register
  2011. */
  2012. public void addNodeArrivedId(int... npcIds)
  2013. {
  2014. addEventId(QuestEventType.ON_NODE_ARRIVED, npcIds);
  2015. }
  2016. /**
  2017. * Register onRouteFinished trigger for NPC
  2018. * @param npcIds id of NPC to register
  2019. */
  2020. public void addRouteFinishedId(int... npcIds)
  2021. {
  2022. addEventId(QuestEventType.ON_ROUTE_FINISHED, npcIds);
  2023. }
  2024. /**
  2025. * Use this method to get a random party member from a player's party.<br>
  2026. * Useful when distributing rewards after killing an NPC.
  2027. * @param player this parameter represents the player whom the party will taken.
  2028. * @return {@code null} if {@code player} is {@code null}, {@code player} itself if the player does not have a party, and a random party member in all other cases
  2029. */
  2030. public L2PcInstance getRandomPartyMember(L2PcInstance player)
  2031. {
  2032. if (player == null)
  2033. {
  2034. return null;
  2035. }
  2036. final L2Party party = player.getParty();
  2037. if ((party == null) || (party.getMembers().isEmpty()))
  2038. {
  2039. return player;
  2040. }
  2041. return party.getMembers().get(Rnd.get(party.getMembers().size()));
  2042. }
  2043. /**
  2044. * Get a random party member with required cond value.
  2045. * @param player the instance of a player whose party is to be searched
  2046. * @param cond the value of the "cond" variable that must be matched
  2047. * @return a random party member that matches the specified condition, or {@code null} if no match was found
  2048. */
  2049. public L2PcInstance getRandomPartyMember(L2PcInstance player, int cond)
  2050. {
  2051. return getRandomPartyMember(player, "cond", String.valueOf(cond));
  2052. }
  2053. /**
  2054. * Auxiliary function for party quests.<br>
  2055. * Note: This function is only here because of how commonly it may be used by quest developers.<br>
  2056. * For any variations on this function, the quest script can always handle things on its own.
  2057. * @param player the instance of a player whose party is to be searched
  2058. * @param var the quest variable to look for in party members. If {@code null}, it simply unconditionally returns a random party member
  2059. * @param value the value of the specified quest variable the random party member must have
  2060. * @return a random party member that matches the specified conditions or {@code null} if no match was found.<br>
  2061. * If the {@code var} parameter is {@code null}, a random party member is selected without any conditions.<br>
  2062. * The party member must be within a range of 1500 ingame units of the target of the reference player, or, if no target exists, within the same range of the player itself
  2063. */
  2064. public L2PcInstance getRandomPartyMember(L2PcInstance player, String var, String value)
  2065. {
  2066. // if no valid player instance is passed, there is nothing to check...
  2067. if (player == null)
  2068. {
  2069. return null;
  2070. }
  2071. // for null var condition, return any random party member.
  2072. if (var == null)
  2073. {
  2074. return getRandomPartyMember(player);
  2075. }
  2076. // normal cases...if the player is not in a party, check the player's state
  2077. QuestState temp = null;
  2078. L2Party party = player.getParty();
  2079. // if this player is not in a party, just check if this player instance matches the conditions itself
  2080. if ((party == null) || (party.getMembers().isEmpty()))
  2081. {
  2082. temp = player.getQuestState(getName());
  2083. if ((temp != null) && temp.isSet(var) && temp.get(var).equalsIgnoreCase(value))
  2084. {
  2085. return player; // match
  2086. }
  2087. return null; // no match
  2088. }
  2089. // if the player is in a party, gather a list of all matching party members (possibly including this player)
  2090. List<L2PcInstance> candidates = new ArrayList<>();
  2091. // get the target for enforcing distance limitations.
  2092. L2Object target = player.getTarget();
  2093. if (target == null)
  2094. {
  2095. target = player;
  2096. }
  2097. for (L2PcInstance partyMember : party.getMembers())
  2098. {
  2099. if (partyMember == null)
  2100. {
  2101. continue;
  2102. }
  2103. temp = partyMember.getQuestState(getName());
  2104. if ((temp != null) && (temp.get(var) != null) && (temp.get(var)).equalsIgnoreCase(value) && partyMember.isInsideRadius(target, 1500, true, false))
  2105. {
  2106. candidates.add(partyMember);
  2107. }
  2108. }
  2109. // if there was no match, return null...
  2110. if (candidates.isEmpty())
  2111. {
  2112. return null;
  2113. }
  2114. // if a match was found from the party, return one of them at random.
  2115. return candidates.get(Rnd.get(candidates.size()));
  2116. }
  2117. /**
  2118. * Auxiliary function for party quests.<br>
  2119. * Note: This function is only here because of how commonly it may be used by quest developers.<br>
  2120. * For any variations on this function, the quest script can always handle things on its own.
  2121. * @param player the player whose random party member is to be selected
  2122. * @param state the quest state required of the random party member
  2123. * @return {@code null} if nothing was selected or a random party member that has the specified quest state
  2124. */
  2125. public L2PcInstance getRandomPartyMemberState(L2PcInstance player, byte state)
  2126. {
  2127. // if no valid player instance is passed, there is nothing to check...
  2128. if (player == null)
  2129. {
  2130. return null;
  2131. }
  2132. // normal cases...if the player is not in a partym check the player's state
  2133. QuestState temp = null;
  2134. L2Party party = player.getParty();
  2135. // if this player is not in a party, just check if this player instance matches the conditions itself
  2136. if ((party == null) || (party.getMembers().isEmpty()))
  2137. {
  2138. temp = player.getQuestState(getName());
  2139. if ((temp != null) && (temp.getState() == state))
  2140. {
  2141. return player; // match
  2142. }
  2143. return null; // no match
  2144. }
  2145. // if the player is in a party, gather a list of all matching party members (possibly
  2146. // including this player)
  2147. List<L2PcInstance> candidates = new ArrayList<>();
  2148. // get the target for enforcing distance limitations.
  2149. L2Object target = player.getTarget();
  2150. if (target == null)
  2151. {
  2152. target = player;
  2153. }
  2154. for (L2PcInstance partyMember : party.getMembers())
  2155. {
  2156. if (partyMember == null)
  2157. {
  2158. continue;
  2159. }
  2160. temp = partyMember.getQuestState(getName());
  2161. if ((temp != null) && (temp.getState() == state) && partyMember.isInsideRadius(target, 1500, true, false))
  2162. {
  2163. candidates.add(partyMember);
  2164. }
  2165. }
  2166. // if there was no match, return null...
  2167. if (candidates.isEmpty())
  2168. {
  2169. return null;
  2170. }
  2171. // if a match was found from the party, return one of them at random.
  2172. return candidates.get(Rnd.get(candidates.size()));
  2173. }
  2174. /**
  2175. * Show an on screen message to the player.
  2176. * @param player the player to display the message
  2177. * @param text the message
  2178. * @param time the display time
  2179. */
  2180. public static void showOnScreenMsg(L2PcInstance player, String text, int time)
  2181. {
  2182. player.sendPacket(new ExShowScreenMessage(text, time));
  2183. }
  2184. /**
  2185. * Show an on screen message to the player.
  2186. * @param player the player to display the message
  2187. * @param npcString the NPC String to display
  2188. * @param position the position in the screen
  2189. * @param time the display time
  2190. * @param params parameters values to replace in the NPC String
  2191. */
  2192. public static void showOnScreenMsg(L2PcInstance player, NpcStringId npcString, int position, int time, String... params)
  2193. {
  2194. player.sendPacket(new ExShowScreenMessage(npcString, position, time, params));
  2195. }
  2196. /**
  2197. * Show an on screen message to the player.
  2198. * @param player the player to display the message
  2199. * @param systemMsg the System Message to display
  2200. * @param position the position in the screen
  2201. * @param time the display time
  2202. * @param params parameters values to replace in the System Message
  2203. */
  2204. public static void showOnScreenMsg(L2PcInstance player, SystemMessageId systemMsg, int position, int time, String... params)
  2205. {
  2206. player.sendPacket(new ExShowScreenMessage(systemMsg, position, time, params));
  2207. }
  2208. /**
  2209. * Show HTML file to client
  2210. * @param player
  2211. * @param fileName
  2212. * @return String message sent to client
  2213. */
  2214. public String showHtmlFile(L2PcInstance player, String fileName)
  2215. {
  2216. boolean questwindow = !fileName.endsWith(".html");
  2217. int questId = getQuestIntId();
  2218. // Create handler to file linked to the quest
  2219. String content = getHtm(player.getHtmlPrefix(), fileName);
  2220. // Send message to client if message not empty
  2221. if (content != null)
  2222. {
  2223. if (player.getTarget() != null)
  2224. {
  2225. content = content.replaceAll("%objectId%", Integer.toString(player.getTargetId()));
  2226. }
  2227. if (questwindow && (questId > 0) && (questId < 20000) && (questId != 999))
  2228. {
  2229. NpcQuestHtmlMessage npcReply = new NpcQuestHtmlMessage(player.getTargetId(), questId);
  2230. npcReply.setHtml(content);
  2231. npcReply.replace("%playername%", player.getName());
  2232. player.sendPacket(npcReply);
  2233. }
  2234. else
  2235. {
  2236. NpcHtmlMessage npcReply = new NpcHtmlMessage(player.getTargetId());
  2237. npcReply.setHtml(content);
  2238. npcReply.replace("%playername%", player.getName());
  2239. player.sendPacket(npcReply);
  2240. }
  2241. player.sendPacket(ActionFailed.STATIC_PACKET);
  2242. }
  2243. return content;
  2244. }
  2245. /**
  2246. * @param prefix player's language prefix.
  2247. * @param fileName the html file to be get.
  2248. * @return the HTML file contents
  2249. */
  2250. public String getHtm(String prefix, String fileName)
  2251. {
  2252. final HtmCache hc = HtmCache.getInstance();
  2253. String content = hc.getHtm(prefix, fileName.startsWith("data/") ? fileName : "data/scripts/" + getDescr().toLowerCase() + "/" + getName() + "/" + fileName);
  2254. if (content == null)
  2255. {
  2256. content = hc.getHtm(prefix, "data/scripts/" + getDescr() + "/" + getName() + "/" + fileName);
  2257. if (content == null)
  2258. {
  2259. content = hc.getHtmForce(prefix, "data/scripts/quests/" + getName() + "/" + fileName);
  2260. }
  2261. }
  2262. return content;
  2263. }
  2264. /**
  2265. * Add a temporary (quest) spawn
  2266. * @param npcId
  2267. * @param cha
  2268. * @return instance of newly spawned npc
  2269. */
  2270. public L2Npc addSpawn(int npcId, L2Character cha)
  2271. {
  2272. return addSpawn(npcId, cha.getX(), cha.getY(), cha.getZ(), cha.getHeading(), false, 0, false, 0);
  2273. }
  2274. /**
  2275. * Add a temporary (quest) spawn
  2276. * @param npcId
  2277. * @param cha
  2278. * @param isSummonSpawn
  2279. * @return instance of newly spawned npc with summon animation
  2280. */
  2281. public L2Npc addSpawn(int npcId, L2Character cha, boolean isSummonSpawn)
  2282. {
  2283. return addSpawn(npcId, cha.getX(), cha.getY(), cha.getZ(), cha.getHeading(), false, 0, isSummonSpawn, 0);
  2284. }
  2285. /**
  2286. * @param npcId
  2287. * @param x
  2288. * @param y
  2289. * @param z
  2290. * @param heading
  2291. * @param randomOffSet
  2292. * @param despawnDelay
  2293. * @return
  2294. */
  2295. public L2Npc addSpawn(int npcId, int x, int y, int z, int heading, boolean randomOffSet, long despawnDelay)
  2296. {
  2297. return addSpawn(npcId, x, y, z, heading, randomOffSet, despawnDelay, false, 0);
  2298. }
  2299. /**
  2300. * @param npcId
  2301. * @param loc
  2302. * @param randomOffSet
  2303. * @param despawnDelay
  2304. * @return
  2305. */
  2306. public L2Npc addSpawn(int npcId, Location loc, boolean randomOffSet, long despawnDelay)
  2307. {
  2308. return addSpawn(npcId, loc.getX(), loc.getY(), loc.getZ(), loc.getHeading(), randomOffSet, despawnDelay, false, 0);
  2309. }
  2310. /**
  2311. * @param npcId
  2312. * @param x
  2313. * @param y
  2314. * @param z
  2315. * @param heading
  2316. * @param randomOffset
  2317. * @param despawnDelay
  2318. * @param isSummonSpawn
  2319. * @return
  2320. */
  2321. public L2Npc addSpawn(int npcId, int x, int y, int z, int heading, boolean randomOffset, long despawnDelay, boolean isSummonSpawn)
  2322. {
  2323. return addSpawn(npcId, x, y, z, heading, randomOffset, despawnDelay, isSummonSpawn, 0);
  2324. }
  2325. /**
  2326. * @param npcId
  2327. * @param loc
  2328. * @param randomOffset
  2329. * @param despawnDelay
  2330. * @param isSummonSpawn
  2331. * @return
  2332. */
  2333. public L2Npc addSpawn(int npcId, Location loc, boolean randomOffset, long despawnDelay, boolean isSummonSpawn)
  2334. {
  2335. return addSpawn(npcId, loc.getX(), loc.getY(), loc.getZ(), loc.getHeading(), randomOffset, despawnDelay, isSummonSpawn, 0);
  2336. }
  2337. /**
  2338. * @param npcId
  2339. * @param loc
  2340. * @param randomOffset
  2341. * @param despawnDelay
  2342. * @param isSummonSpawn
  2343. * @param instanceId
  2344. * @return
  2345. */
  2346. public L2Npc addSpawn(int npcId, Location loc, boolean randomOffset, long despawnDelay, boolean isSummonSpawn, int instanceId)
  2347. {
  2348. return addSpawn(npcId, loc.getX(), loc.getY(), loc.getZ(), loc.getHeading(), randomOffset, despawnDelay, isSummonSpawn, instanceId);
  2349. }
  2350. /**
  2351. * @param npcId
  2352. * @param x
  2353. * @param y
  2354. * @param z
  2355. * @param heading
  2356. * @param randomOffset
  2357. * @param despawnDelay
  2358. * @param isSummonSpawn
  2359. * @param instanceId
  2360. * @return
  2361. */
  2362. public L2Npc addSpawn(int npcId, int x, int y, int z, int heading, boolean randomOffset, long despawnDelay, boolean isSummonSpawn, int instanceId)
  2363. {
  2364. L2Npc result = null;
  2365. try
  2366. {
  2367. L2NpcTemplate template = NpcTable.getInstance().getTemplate(npcId);
  2368. if (template != null)
  2369. {
  2370. // Sometimes, even if the quest script specifies some xyz (for example npc.getX() etc) by the time the code
  2371. // reaches here, xyz have become 0! Also, a questdev might have purposely set xy to 0,0...however,
  2372. // the spawn code is coded such that if x=y=0, it looks into location for the spawn loc! This will NOT work
  2373. // with quest spawns! For both of the above cases, we need a fail-safe spawn. For this, we use the
  2374. // default spawn location, which is at the player's loc.
  2375. if ((x == 0) && (y == 0))
  2376. {
  2377. _log.log(Level.SEVERE, "Failed to adjust bad locks for quest spawn! Spawn aborted!");
  2378. return null;
  2379. }
  2380. if (randomOffset)
  2381. {
  2382. int offset;
  2383. offset = Rnd.get(2); // Get the direction of the offset
  2384. if (offset == 0)
  2385. {
  2386. // make offset negative
  2387. offset = -1;
  2388. }
  2389. offset *= Rnd.get(50, 100);
  2390. x += offset;
  2391. offset = Rnd.get(2); // Get the direction of the offset
  2392. if (offset == 0)
  2393. {
  2394. // make offset negative
  2395. offset = -1;
  2396. }
  2397. offset *= Rnd.get(50, 100);
  2398. y += offset;
  2399. }
  2400. L2Spawn spawn = new L2Spawn(template);
  2401. spawn.setInstanceId(instanceId);
  2402. spawn.setHeading(heading);
  2403. spawn.setLocx(x);
  2404. spawn.setLocy(y);
  2405. spawn.setLocz(z);
  2406. spawn.stopRespawn();
  2407. result = spawn.spawnOne(isSummonSpawn);
  2408. if (despawnDelay > 0)
  2409. {
  2410. result.scheduleDespawn(despawnDelay);
  2411. }
  2412. return result;
  2413. }
  2414. }
  2415. catch (Exception e1)
  2416. {
  2417. _log.warning("Could not spawn Npc " + npcId + " Error: " + e1.getMessage());
  2418. }
  2419. return null;
  2420. }
  2421. /**
  2422. * @param trapId
  2423. * @param x
  2424. * @param y
  2425. * @param z
  2426. * @param heading
  2427. * @param skill
  2428. * @param instanceId
  2429. * @return
  2430. */
  2431. public L2Trap addTrap(int trapId, int x, int y, int z, int heading, L2Skill skill, int instanceId)
  2432. {
  2433. L2NpcTemplate TrapTemplate = NpcTable.getInstance().getTemplate(trapId);
  2434. L2Trap trap = new L2TrapInstance(IdFactory.getInstance().getNextId(), TrapTemplate, instanceId, -1, skill);
  2435. trap.setCurrentHp(trap.getMaxHp());
  2436. trap.setCurrentMp(trap.getMaxMp());
  2437. trap.setIsInvul(true);
  2438. trap.setHeading(heading);
  2439. // L2World.getInstance().storeObject(trap);
  2440. trap.spawnMe(x, y, z);
  2441. return trap;
  2442. }
  2443. /**
  2444. * @param master
  2445. * @param minionId
  2446. * @return
  2447. */
  2448. public L2Npc addMinion(L2MonsterInstance master, int minionId)
  2449. {
  2450. return MinionList.spawnMinion(master, minionId);
  2451. }
  2452. /**
  2453. * @return the registered quest items Ids.
  2454. */
  2455. public int[] getRegisteredItemIds()
  2456. {
  2457. return questItemIds;
  2458. }
  2459. /**
  2460. * Registers all items that have to be destroyed in case player abort the quest or finish it.
  2461. * @param items
  2462. */
  2463. public void registerQuestItems(int... items)
  2464. {
  2465. questItemIds = items;
  2466. }
  2467. @Override
  2468. public String getScriptName()
  2469. {
  2470. return getName();
  2471. }
  2472. @Override
  2473. public void setActive(boolean status)
  2474. {
  2475. // TODO implement me
  2476. }
  2477. @Override
  2478. public boolean reload()
  2479. {
  2480. unload();
  2481. return super.reload();
  2482. }
  2483. @Override
  2484. public boolean unload()
  2485. {
  2486. return unload(true);
  2487. }
  2488. /**
  2489. * @param removeFromList
  2490. * @return
  2491. */
  2492. public boolean unload(boolean removeFromList)
  2493. {
  2494. saveGlobalData();
  2495. // cancel all pending timers before reloading.
  2496. // if timers ought to be restarted, the quest can take care of it
  2497. // with its code (example: save global data indicating what timer must be restarted).
  2498. for (List<QuestTimer> timers : _allEventTimers.values())
  2499. {
  2500. _readLock.lock();
  2501. try
  2502. {
  2503. for (QuestTimer timer : timers)
  2504. {
  2505. timer.cancel();
  2506. }
  2507. }
  2508. finally
  2509. {
  2510. _readLock.unlock();
  2511. }
  2512. timers.clear();
  2513. }
  2514. _allEventTimers.clear();
  2515. for (Integer npcId : _questInvolvedNpcs)
  2516. {
  2517. L2NpcTemplate template = NpcTable.getInstance().getTemplate(npcId.intValue());
  2518. if (template != null)
  2519. {
  2520. template.removeQuest(this);
  2521. }
  2522. }
  2523. _questInvolvedNpcs.clear();
  2524. if (removeFromList)
  2525. {
  2526. return QuestManager.getInstance().removeQuest(this);
  2527. }
  2528. return true;
  2529. }
  2530. public Set<Integer> getQuestInvolvedNpcs()
  2531. {
  2532. return _questInvolvedNpcs;
  2533. }
  2534. @Override
  2535. public ScriptManager<?> getScriptManager()
  2536. {
  2537. return QuestManager.getInstance();
  2538. }
  2539. /**
  2540. * @param val
  2541. */
  2542. public void setOnEnterWorld(boolean val)
  2543. {
  2544. _onEnterWorld = val;
  2545. }
  2546. /**
  2547. * @return
  2548. */
  2549. public boolean getOnEnterWorld()
  2550. {
  2551. return _onEnterWorld;
  2552. }
  2553. /**
  2554. * If a quest is set as custom, it will display it's name in the NPC Quest List.<br>
  2555. * Retail quests are unhardcoded to display the name using a client string.
  2556. * @param val if {@code true} the quest script will be set as custom quest.
  2557. */
  2558. public void setIsCustom(boolean val)
  2559. {
  2560. _isCustom = val;
  2561. }
  2562. /**
  2563. * @return {@code true} if the quest script is a custom quest, {@code false} otherwise.
  2564. */
  2565. public boolean isCustomQuest()
  2566. {
  2567. return _isCustom;
  2568. }
  2569. /**
  2570. * @param val
  2571. */
  2572. public void setOlympiadUse(boolean val)
  2573. {
  2574. _isOlympiadUse = val;
  2575. }
  2576. /**
  2577. * @return {@code true} if the quest script is used for Olympiad quests, {@code false} otherwise.
  2578. */
  2579. public boolean isOlympiadUse()
  2580. {
  2581. return _isOlympiadUse;
  2582. }
  2583. /**
  2584. * Get the amount of an item in player's inventory.
  2585. * @param player the player whose inventory to check
  2586. * @param itemId the Id of the item whose amount to get
  2587. * @return the amount of the specified item in player's inventory
  2588. */
  2589. public long getQuestItemsCount(L2PcInstance player, int itemId)
  2590. {
  2591. return player.getInventory().getInventoryItemCount(itemId, -1);
  2592. }
  2593. /**
  2594. * Get the total amount of all specified items in player's inventory.
  2595. * @param player the player whose inventory to check
  2596. * @param itemIds a list of Ids of items whose amount to get
  2597. * @return the summary amount of all listed items in player's inventory
  2598. */
  2599. public long getQuestItemsCount(L2PcInstance player, int... itemIds)
  2600. {
  2601. long count = 0;
  2602. for (L2ItemInstance item : player.getInventory().getItems())
  2603. {
  2604. if (item == null)
  2605. {
  2606. continue;
  2607. }
  2608. for (int itemId : itemIds)
  2609. {
  2610. if (item.getItemId() == itemId)
  2611. {
  2612. if ((count + item.getCount()) > Long.MAX_VALUE)
  2613. {
  2614. return Long.MAX_VALUE;
  2615. }
  2616. count += item.getCount();
  2617. }
  2618. }
  2619. }
  2620. return count;
  2621. }
  2622. /**
  2623. * Check for an item in player's inventory.
  2624. * @param player the player whose inventory to check for quest items
  2625. * @param itemId the Id of the item to check for
  2626. * @return {@code true} if the item exists in player's inventory, {@code false} otherwise
  2627. */
  2628. public boolean hasQuestItems(L2PcInstance player, int itemId)
  2629. {
  2630. return player.getInventory().getItemByItemId(itemId) != null;
  2631. }
  2632. /**
  2633. * Check for multiple items in player's inventory.
  2634. * @param player the player whose inventory to check for quest items
  2635. * @param itemIds a list of item Ids to check for
  2636. * @return {@code true} if all items exist in player's inventory, {@code false} otherwise
  2637. */
  2638. public boolean hasQuestItems(L2PcInstance player, int... itemIds)
  2639. {
  2640. final PcInventory inv = player.getInventory();
  2641. for (int itemId : itemIds)
  2642. {
  2643. if (inv.getItemByItemId(itemId) == null)
  2644. {
  2645. return false;
  2646. }
  2647. }
  2648. return true;
  2649. }
  2650. /**
  2651. * Check for multiple items in player's inventory.
  2652. * @param player the player whose inventory to check for quest items
  2653. * @param itemIds a list of item Ids to check for
  2654. * @return {@code true} if at least one items exist in player's inventory, {@code false} otherwise
  2655. */
  2656. public boolean hasAtLeastOneQuestItem(L2PcInstance player, int... itemIds)
  2657. {
  2658. final PcInventory inv = player.getInventory();
  2659. for (int itemId : itemIds)
  2660. {
  2661. if (inv.getItemByItemId(itemId) != null)
  2662. {
  2663. return true;
  2664. }
  2665. }
  2666. return false;
  2667. }
  2668. /**
  2669. * Get the enchantment level of an item in player's inventory.
  2670. * @param player the player whose item to check
  2671. * @param itemId the Id of the item whose enchantment level to get
  2672. * @return the enchantment level of the item or 0 if the item was not found
  2673. */
  2674. public int getEnchantLevel(L2PcInstance player, int itemId)
  2675. {
  2676. L2ItemInstance enchantedItem = player.getInventory().getItemByItemId(itemId);
  2677. if (enchantedItem == null)
  2678. {
  2679. return 0;
  2680. }
  2681. return enchantedItem.getEnchantLevel();
  2682. }
  2683. /**
  2684. * Give Adena to the player.
  2685. * @param player the player to whom to give the Adena
  2686. * @param count the amount of Adena to give
  2687. * @param applyRates if {@code true} quest rates will be applied to the amount
  2688. */
  2689. public void giveAdena(L2PcInstance player, long count, boolean applyRates)
  2690. {
  2691. if (applyRates)
  2692. {
  2693. rewardItems(player, PcInventory.ADENA_ID, count);
  2694. }
  2695. else
  2696. {
  2697. giveItems(player, PcInventory.ADENA_ID, count);
  2698. }
  2699. }
  2700. /**
  2701. * Give a reward to player using multipliers.
  2702. * @param player the player to whom to give the item
  2703. * @param itemId the Id of the item to give
  2704. * @param count the amount of items to give
  2705. */
  2706. public void rewardItems(L2PcInstance player, int itemId, long count)
  2707. {
  2708. if (count <= 0)
  2709. {
  2710. return;
  2711. }
  2712. L2ItemInstance _tmpItem = ItemTable.getInstance().createDummyItem(itemId);
  2713. if (_tmpItem == null)
  2714. {
  2715. return;
  2716. }
  2717. try
  2718. {
  2719. if (itemId == PcInventory.ADENA_ID)
  2720. {
  2721. count *= Config.RATE_QUEST_REWARD_ADENA;
  2722. }
  2723. else if (Config.RATE_QUEST_REWARD_USE_MULTIPLIERS)
  2724. {
  2725. if (_tmpItem.isEtcItem())
  2726. {
  2727. switch (_tmpItem.getEtcItem().getItemType())
  2728. {
  2729. case POTION:
  2730. count *= Config.RATE_QUEST_REWARD_POTION;
  2731. break;
  2732. case SCRL_ENCHANT_WP:
  2733. case SCRL_ENCHANT_AM:
  2734. case SCROLL:
  2735. count *= Config.RATE_QUEST_REWARD_SCROLL;
  2736. break;
  2737. case RECIPE:
  2738. count *= Config.RATE_QUEST_REWARD_RECIPE;
  2739. break;
  2740. case MATERIAL:
  2741. count *= Config.RATE_QUEST_REWARD_MATERIAL;
  2742. break;
  2743. default:
  2744. count *= Config.RATE_QUEST_REWARD;
  2745. }
  2746. }
  2747. }
  2748. else
  2749. {
  2750. count *= Config.RATE_QUEST_REWARD;
  2751. }
  2752. }
  2753. catch (Exception e)
  2754. {
  2755. count = Long.MAX_VALUE;
  2756. }
  2757. // Add items to player's inventory
  2758. L2ItemInstance item = player.getInventory().addItem("Quest", itemId, count, player, player.getTarget());
  2759. if (item == null)
  2760. {
  2761. return;
  2762. }
  2763. sendItemGetMessage(player, item, count);
  2764. }
  2765. /**
  2766. * Send the system message and the status update packets to the player.
  2767. * @param player the player that has got the item
  2768. * @param item the item obtain by the player
  2769. * @param count the item count
  2770. */
  2771. private void sendItemGetMessage(L2PcInstance player, L2ItemInstance item, long count)
  2772. {
  2773. // If item for reward is gold, send message of gold reward to client
  2774. if (item.getItemId() == PcInventory.ADENA_ID)
  2775. {
  2776. SystemMessage smsg = SystemMessage.getSystemMessage(SystemMessageId.EARNED_S1_ADENA);
  2777. smsg.addItemNumber(count);
  2778. player.sendPacket(smsg);
  2779. }
  2780. // Otherwise, send message of object reward to client
  2781. else
  2782. {
  2783. if (count > 1)
  2784. {
  2785. SystemMessage smsg = SystemMessage.getSystemMessage(SystemMessageId.EARNED_S2_S1_S);
  2786. smsg.addItemName(item);
  2787. smsg.addItemNumber(count);
  2788. player.sendPacket(smsg);
  2789. }
  2790. else
  2791. {
  2792. SystemMessage smsg = SystemMessage.getSystemMessage(SystemMessageId.EARNED_ITEM_S1);
  2793. smsg.addItemName(item);
  2794. player.sendPacket(smsg);
  2795. }
  2796. }
  2797. // send packets
  2798. StatusUpdate su = new StatusUpdate(player);
  2799. su.addAttribute(StatusUpdate.CUR_LOAD, player.getCurrentLoad());
  2800. player.sendPacket(su);
  2801. }
  2802. /**
  2803. * Give item/reward to the player
  2804. * @param player
  2805. * @param itemId
  2806. * @param count
  2807. */
  2808. public void giveItems(L2PcInstance player, int itemId, long count)
  2809. {
  2810. giveItems(player, itemId, count, 0);
  2811. }
  2812. /**
  2813. * Give item/reward to the player
  2814. * @param player
  2815. * @param holder
  2816. */
  2817. protected void giveItems(L2PcInstance player, ItemHolder holder)
  2818. {
  2819. giveItems(player, holder.getId(), holder.getCount());
  2820. }
  2821. /**
  2822. * @param player
  2823. * @param itemId
  2824. * @param count
  2825. * @param enchantlevel
  2826. */
  2827. public void giveItems(L2PcInstance player, int itemId, long count, int enchantlevel)
  2828. {
  2829. if (count <= 0)
  2830. {
  2831. return;
  2832. }
  2833. // If item for reward is adena (Id=57), modify count with rate for quest reward if rates available
  2834. if ((itemId == PcInventory.ADENA_ID) && (enchantlevel == 0))
  2835. {
  2836. count = (long) (count * Config.RATE_QUEST_REWARD_ADENA);
  2837. }
  2838. // Add items to player's inventory
  2839. L2ItemInstance item = player.getInventory().addItem("Quest", itemId, count, player, player.getTarget());
  2840. if (item == null)
  2841. {
  2842. return;
  2843. }
  2844. // set enchant level for item if that item is not adena
  2845. if ((enchantlevel > 0) && (itemId != PcInventory.ADENA_ID))
  2846. {
  2847. item.setEnchantLevel(enchantlevel);
  2848. }
  2849. sendItemGetMessage(player, item, count);
  2850. }
  2851. /**
  2852. * @param player
  2853. * @param itemId
  2854. * @param count
  2855. * @param attributeId
  2856. * @param attributeLevel
  2857. */
  2858. public void giveItems(L2PcInstance player, int itemId, long count, byte attributeId, int attributeLevel)
  2859. {
  2860. if (count <= 0)
  2861. {
  2862. return;
  2863. }
  2864. // Add items to player's inventory
  2865. L2ItemInstance item = player.getInventory().addItem("Quest", itemId, count, player, player.getTarget());
  2866. if (item == null)
  2867. {
  2868. return;
  2869. }
  2870. // set enchant level for item if that item is not adena
  2871. if ((attributeId >= 0) && (attributeLevel > 0))
  2872. {
  2873. item.setElementAttr(attributeId, attributeLevel);
  2874. if (item.isEquipped())
  2875. {
  2876. item.updateElementAttrBonus(player);
  2877. }
  2878. InventoryUpdate iu = new InventoryUpdate();
  2879. iu.addModifiedItem(item);
  2880. player.sendPacket(iu);
  2881. }
  2882. sendItemGetMessage(player, item, count);
  2883. }
  2884. /**
  2885. * Drop Quest item using Config.RATE_QUEST_DROP
  2886. * @param player
  2887. * @param itemId int Item Identifier of the item to be dropped
  2888. * @param count (minCount, maxCount) long Quantity of items to be dropped
  2889. * @param neededCount Quantity of items needed for quest
  2890. * @param dropChance int Base chance of drop, same as in droplist
  2891. * @param sound boolean indicating whether to play sound
  2892. * @return boolean indicating whether player has requested number of items
  2893. */
  2894. public boolean dropQuestItems(L2PcInstance player, int itemId, int count, long neededCount, int dropChance, boolean sound)
  2895. {
  2896. return dropQuestItems(player, itemId, count, count, neededCount, dropChance, sound);
  2897. }
  2898. /**
  2899. * @param player
  2900. * @param itemId
  2901. * @param minCount
  2902. * @param maxCount
  2903. * @param neededCount
  2904. * @param dropChance
  2905. * @param sound
  2906. * @return
  2907. */
  2908. public boolean dropQuestItems(L2PcInstance player, int itemId, int minCount, int maxCount, long neededCount, int dropChance, boolean sound)
  2909. {
  2910. dropChance *= Config.RATE_QUEST_DROP / ((player.getParty() != null) ? player.getParty().getMemberCount() : 1);
  2911. long currentCount = getQuestItemsCount(player, itemId);
  2912. if ((neededCount > 0) && (currentCount >= neededCount))
  2913. {
  2914. return true;
  2915. }
  2916. if (currentCount >= neededCount)
  2917. {
  2918. return true;
  2919. }
  2920. long itemCount = 0;
  2921. int random = Rnd.get(L2DropData.MAX_CHANCE);
  2922. while (random < dropChance)
  2923. {
  2924. // Get the item quantity dropped
  2925. if (minCount < maxCount)
  2926. {
  2927. itemCount += Rnd.get(minCount, maxCount);
  2928. }
  2929. else if (minCount == maxCount)
  2930. {
  2931. itemCount += minCount;
  2932. }
  2933. else
  2934. {
  2935. itemCount++;
  2936. }
  2937. // Prepare for next iteration if dropChance > L2DropData.MAX_CHANCE
  2938. dropChance -= L2DropData.MAX_CHANCE;
  2939. }
  2940. if (itemCount > 0)
  2941. {
  2942. // if over neededCount, just fill the gap
  2943. if ((neededCount > 0) && ((currentCount + itemCount) > neededCount))
  2944. {
  2945. itemCount = neededCount - currentCount;
  2946. }
  2947. // Inventory slot check
  2948. if (!player.getInventory().validateCapacityByItemId(itemId))
  2949. {
  2950. return false;
  2951. }
  2952. // Give the item to Player
  2953. player.addItem("Quest", itemId, itemCount, player.getTarget(), true);
  2954. if (sound)
  2955. {
  2956. playSound(player, ((currentCount + itemCount) < neededCount) ? QuestSound.ITEMSOUND_QUEST_ITEMGET : QuestSound.ITEMSOUND_QUEST_MIDDLE);
  2957. }
  2958. }
  2959. return ((neededCount > 0) && ((currentCount + itemCount) >= neededCount));
  2960. }
  2961. /**
  2962. * Take an amount of a specified item from player's inventory.
  2963. * @param player the player whose item to take
  2964. * @param itemId the Id of the item to take
  2965. * @param amount the amount to take
  2966. * @return {@code true} if any items were taken, {@code false} otherwise
  2967. */
  2968. public boolean takeItems(L2PcInstance player, int itemId, long amount)
  2969. {
  2970. // Get object item from player's inventory list
  2971. L2ItemInstance item = player.getInventory().getItemByItemId(itemId);
  2972. if (item == null)
  2973. {
  2974. return false;
  2975. }
  2976. // Tests on count value in order not to have negative value
  2977. if ((amount < 0) || (amount > item.getCount()))
  2978. {
  2979. amount = item.getCount();
  2980. }
  2981. // Destroy the quantity of items wanted
  2982. if (item.isEquipped())
  2983. {
  2984. L2ItemInstance[] unequiped = player.getInventory().unEquipItemInBodySlotAndRecord(item.getItem().getBodyPart());
  2985. InventoryUpdate iu = new InventoryUpdate();
  2986. for (L2ItemInstance itm : unequiped)
  2987. {
  2988. iu.addModifiedItem(itm);
  2989. }
  2990. player.sendPacket(iu);
  2991. player.broadcastUserInfo();
  2992. }
  2993. return player.destroyItemByItemId("Quest", itemId, amount, player, true);
  2994. }
  2995. /**
  2996. * Take an amount of a specified item from player's inventory.
  2997. * @param player
  2998. * @param holder
  2999. * @return {@code true} if any items were taken, {@code false} otherwise
  3000. */
  3001. protected boolean takeItems(L2PcInstance player, ItemHolder holder)
  3002. {
  3003. return takeItems(player, holder.getId(), holder.getCount());
  3004. }
  3005. /**
  3006. * Take an amount of all specified items from player's inventory.
  3007. * @param player the player whose items to take
  3008. * @param amount the amount to take of each item
  3009. * @param itemIds a list or an array of Ids of the items to take
  3010. * @return {@code true} if all items were taken, {@code false} otherwise
  3011. */
  3012. public boolean takeItems(L2PcInstance player, int amount, int... itemIds)
  3013. {
  3014. boolean check = true;
  3015. if (itemIds != null)
  3016. {
  3017. for (int item : itemIds)
  3018. {
  3019. check &= takeItems(player, item, amount);
  3020. }
  3021. }
  3022. return check;
  3023. }
  3024. /**
  3025. * Remove all quest items associated with this quest from the specified player's inventory.
  3026. * @param player the player whose quest items to remove
  3027. */
  3028. public void removeRegisteredQuestItems(L2PcInstance player)
  3029. {
  3030. takeItems(player, -1, questItemIds);
  3031. }
  3032. /**
  3033. * Send a packet in order to play a sound to the player.
  3034. * @param player the player whom to send the packet
  3035. * @param sound the name of the sound to play
  3036. */
  3037. public void playSound(L2PcInstance player, String sound)
  3038. {
  3039. player.sendPacket(QuestSound.getSound(sound));
  3040. }
  3041. /**
  3042. * Send a packet in order to play a sound to the player.
  3043. * @param player the player whom to send the packet
  3044. * @param sound the {@link QuestSound} object of the sound to play
  3045. */
  3046. public void playSound(L2PcInstance player, QuestSound sound)
  3047. {
  3048. player.sendPacket(sound.getPacket());
  3049. }
  3050. /**
  3051. * Add EXP and SP as quest reward.
  3052. * @param player the player whom to reward with the EXP/SP
  3053. * @param exp the amount of EXP to give to the player
  3054. * @param sp the amount of SP to give to the player
  3055. */
  3056. public void addExpAndSp(L2PcInstance player, long exp, int sp)
  3057. {
  3058. player.addExpAndSp((long) player.calcStat(Stats.EXPSP_RATE, exp * Config.RATE_QUEST_REWARD_XP, null, null), (int) player.calcStat(Stats.EXPSP_RATE, sp * Config.RATE_QUEST_REWARD_SP, null, null));
  3059. }
  3060. /**
  3061. * Get a random integer from 0 (inclusive) to {@code max} (exclusive).<br>
  3062. * Use this method instead of importing {@link com.l2jserver.util.Rnd} utility.
  3063. * @param max the maximum value for randomization
  3064. * @return a random integer number from 0 to {@code max - 1}
  3065. */
  3066. public static int getRandom(int max)
  3067. {
  3068. return Rnd.get(max);
  3069. }
  3070. /**
  3071. * Get a random integer from {@code min} (inclusive) to {@code max} (inclusive).<br>
  3072. * Use this method instead of importing {@link com.l2jserver.util.Rnd} utility.
  3073. * @param min the minimum value for randomization
  3074. * @param max the maximum value for randomization
  3075. * @return a random integer number from {@code min} to {@code max}
  3076. */
  3077. public static int getRandom(int min, int max)
  3078. {
  3079. return Rnd.get(min, max);
  3080. }
  3081. /**
  3082. * Get the Id of the item equipped in the specified inventory slot of the player.
  3083. * @param player the player whose inventory to check
  3084. * @param slot the location in the player's inventory to check
  3085. * @return the Id of the item equipped in the specified inventory slot or 0 if the slot is empty or item is {@code null}.
  3086. */
  3087. public int getItemEquipped(L2PcInstance player, int slot)
  3088. {
  3089. return player.getInventory().getPaperdollItemId(slot);
  3090. }
  3091. /**
  3092. * @return the number of ticks from the {@link com.l2jserver.gameserver.GameTimeController}.
  3093. */
  3094. public int getGameTicks()
  3095. {
  3096. return GameTimeController.getInstance().getGameTicks();
  3097. }
  3098. /**
  3099. * Executes a procedure for each player, depending on the parameters.
  3100. * @param player the player were the procedure will be executed
  3101. * @param npc the related Npc
  3102. * @param isSummon {@code true} if the event that call this method was originated by the player's summon
  3103. * @param includeParty if {@code true} #actionForEachPlayer(L2PcInstance, L2Npc, boolean) will be called with the player's party members
  3104. * @param includeCommandChannel if {@code true} {@link #actionForEachPlayer(L2PcInstance, L2Npc, boolean)} will be called with the player's command channel members
  3105. * @see #actionForEachPlayer(L2PcInstance, L2Npc, boolean)
  3106. */
  3107. public final void executeForEachPlayer(L2PcInstance player, final L2Npc npc, final boolean isSummon, boolean includeParty, boolean includeCommandChannel)
  3108. {
  3109. if ((includeParty || includeCommandChannel) && player.isInParty())
  3110. {
  3111. if (includeCommandChannel && player.getParty().isInCommandChannel())
  3112. {
  3113. player.getParty().getCommandChannel().forEachMember(new IL2Procedure<L2PcInstance>()
  3114. {
  3115. @Override
  3116. public boolean execute(L2PcInstance member)
  3117. {
  3118. actionForEachPlayer(member, npc, isSummon);
  3119. return true;
  3120. }
  3121. });
  3122. }
  3123. else if (includeParty)
  3124. {
  3125. player.getParty().forEachMember(new IL2Procedure<L2PcInstance>()
  3126. {
  3127. @Override
  3128. public boolean execute(L2PcInstance member)
  3129. {
  3130. actionForEachPlayer(member, npc, isSummon);
  3131. return true;
  3132. }
  3133. });
  3134. }
  3135. }
  3136. else
  3137. {
  3138. actionForEachPlayer(player, npc, isSummon);
  3139. }
  3140. }
  3141. /**
  3142. * Overridable method called from {@link #executeForEachPlayer(L2PcInstance, L2Npc, boolean, boolean, boolean)}
  3143. * @param player the player where the action will be run
  3144. * @param npc the Npc related to this action
  3145. * @param isSummon {@code true} if the event that call this method was originated by the player's summon
  3146. */
  3147. public void actionForEachPlayer(L2PcInstance player, L2Npc npc, boolean isSummon)
  3148. {
  3149. // To be overridden in quest scripts.
  3150. }
  3151. /**
  3152. * Opens the door if presents on the instance and its not open.
  3153. * @param doorId
  3154. * @param instanceId
  3155. */
  3156. public void openDoor(int doorId, int instanceId)
  3157. {
  3158. final L2DoorInstance door = getDoor(doorId, instanceId);
  3159. if (door == null)
  3160. {
  3161. _log.log(Level.WARNING, getClass().getSimpleName() + ": called openDoor(" + doorId + ", " + instanceId + "); but door wasnt found!", new NullPointerException());
  3162. }
  3163. else if (!door.getOpen())
  3164. {
  3165. door.openMe();
  3166. }
  3167. }
  3168. /**
  3169. * Closes the door if presents on the instance and its open
  3170. * @param doorId
  3171. * @param instanceId
  3172. */
  3173. public void closeDoor(int doorId, int instanceId)
  3174. {
  3175. final L2DoorInstance door = getDoor(doorId, instanceId);
  3176. if (door == null)
  3177. {
  3178. _log.log(Level.WARNING, getClass().getSimpleName() + ": called closeDoor(" + doorId + ", " + instanceId + "); but door wasnt found!", new NullPointerException());
  3179. }
  3180. else if (door.getOpen())
  3181. {
  3182. door.closeMe();
  3183. }
  3184. }
  3185. /**
  3186. * Retriving Door from instances or from the real world.
  3187. * @param doorId
  3188. * @param instanceId
  3189. * @return {@link L2DoorInstance}
  3190. */
  3191. public L2DoorInstance getDoor(int doorId, int instanceId)
  3192. {
  3193. L2DoorInstance door = null;
  3194. if (instanceId <= 0)
  3195. {
  3196. door = DoorTable.getInstance().getDoor(doorId);
  3197. }
  3198. else
  3199. {
  3200. final Instance inst = InstanceManager.getInstance().getInstance(instanceId);
  3201. if (inst != null)
  3202. {
  3203. door = inst.getDoor(doorId);
  3204. }
  3205. }
  3206. return door;
  3207. }
  3208. /**
  3209. * Teleport player to/from instance
  3210. * @param player
  3211. * @param loc
  3212. * @param instanceId
  3213. */
  3214. public void teleportPlayer(L2PcInstance player, Location loc, int instanceId)
  3215. {
  3216. teleportPlayer(player, loc, instanceId, true);
  3217. }
  3218. /**
  3219. * Teleport player to/from instance
  3220. * @param player
  3221. * @param loc
  3222. * @param instanceId
  3223. * @param allowRandomOffset
  3224. */
  3225. public void teleportPlayer(L2PcInstance player, Location loc, int instanceId, boolean allowRandomOffset)
  3226. {
  3227. loc.setInstanceId(instanceId);
  3228. player.teleToLocation(loc, allowRandomOffset);
  3229. }
  3230. }