Quest.java 105 KB

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