Util.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. /*
  2. * Copyright (C) 2004-2013 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.gameserver.util;
  20. import java.io.File;
  21. import java.text.DateFormat;
  22. import java.text.NumberFormat;
  23. import java.text.SimpleDateFormat;
  24. import java.util.Collection;
  25. import java.util.Date;
  26. import java.util.List;
  27. import java.util.Locale;
  28. import javolution.text.TextBuilder;
  29. import javolution.util.FastList;
  30. import com.l2jserver.Config;
  31. import com.l2jserver.gameserver.GeoData;
  32. import com.l2jserver.gameserver.ThreadPoolManager;
  33. import com.l2jserver.gameserver.model.L2Object;
  34. import com.l2jserver.gameserver.model.actor.L2Character;
  35. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  36. import com.l2jserver.gameserver.network.serverpackets.NpcHtmlMessage;
  37. import com.l2jserver.gameserver.network.serverpackets.ShowBoard;
  38. import com.l2jserver.util.file.filter.ExtFilter;
  39. /**
  40. * General Utility functions related to game server.
  41. */
  42. public final class Util
  43. {
  44. private static final NumberFormat ADENA_FORMATTER = NumberFormat.getIntegerInstance(Locale.ENGLISH);
  45. public static void handleIllegalPlayerAction(L2PcInstance actor, String message, int punishment)
  46. {
  47. ThreadPoolManager.getInstance().scheduleGeneral(new IllegalPlayerAction(actor, message, punishment), 5000);
  48. }
  49. public static String getRelativePath(File base, File file)
  50. {
  51. return file.toURI().getPath().substring(base.toURI().getPath().length());
  52. }
  53. /**
  54. * @param obj1
  55. * @param obj2
  56. * @return degree value of object 2 to the horizontal line with object 1 being the origin.
  57. */
  58. public static double calculateAngleFrom(L2Object obj1, L2Object obj2)
  59. {
  60. return calculateAngleFrom(obj1.getX(), obj1.getY(), obj2.getX(), obj2.getY());
  61. }
  62. /**
  63. * @param obj1X
  64. * @param obj1Y
  65. * @param obj2X
  66. * @param obj2Y
  67. * @return degree value of object 2 to the horizontal line with object 1 being the origin
  68. */
  69. public static final double calculateAngleFrom(int obj1X, int obj1Y, int obj2X, int obj2Y)
  70. {
  71. double angleTarget = Math.toDegrees(Math.atan2(obj2Y - obj1Y, obj2X - obj1X));
  72. if (angleTarget < 0)
  73. {
  74. angleTarget = 360 + angleTarget;
  75. }
  76. return angleTarget;
  77. }
  78. public static final double convertHeadingToDegree(int clientHeading)
  79. {
  80. double degree = clientHeading / 182.044444444;
  81. return degree;
  82. }
  83. public static final int convertDegreeToClientHeading(double degree)
  84. {
  85. if (degree < 0)
  86. {
  87. degree = 360 + degree;
  88. }
  89. return (int) (degree * 182.044444444);
  90. }
  91. public static final int calculateHeadingFrom(L2Object obj1, L2Object obj2)
  92. {
  93. return calculateHeadingFrom(obj1.getX(), obj1.getY(), obj2.getX(), obj2.getY());
  94. }
  95. public static final int calculateHeadingFrom(int obj1X, int obj1Y, int obj2X, int obj2Y)
  96. {
  97. double angleTarget = Math.toDegrees(Math.atan2(obj2Y - obj1Y, obj2X - obj1X));
  98. if (angleTarget < 0)
  99. {
  100. angleTarget = 360 + angleTarget;
  101. }
  102. return (int) (angleTarget * 182.044444444);
  103. }
  104. public static final int calculateHeadingFrom(double dx, double dy)
  105. {
  106. double angleTarget = Math.toDegrees(Math.atan2(dy, dx));
  107. if (angleTarget < 0)
  108. {
  109. angleTarget = 360 + angleTarget;
  110. }
  111. return (int) (angleTarget * 182.044444444);
  112. }
  113. /**
  114. * @param x1
  115. * @param y1
  116. * @param x2
  117. * @param y2
  118. * @return the distance between the two coordinates in 2D plane
  119. */
  120. public static double calculateDistance(int x1, int y1, int x2, int y2)
  121. {
  122. return calculateDistance(x1, y1, 0, x2, y2, 0, false);
  123. }
  124. /**
  125. * @param x1
  126. * @param y1
  127. * @param z1
  128. * @param x2
  129. * @param y2
  130. * @param z2
  131. * @param includeZAxis - if true, includes also the Z axis in the calculation
  132. * @return the distance between the two coordinates
  133. */
  134. public static double calculateDistance(int x1, int y1, int z1, int x2, int y2, int z2, boolean includeZAxis)
  135. {
  136. double dx = (double) x1 - x2;
  137. double dy = (double) y1 - y2;
  138. if (includeZAxis)
  139. {
  140. double dz = z1 - z2;
  141. return Math.sqrt((dx * dx) + (dy * dy) + (dz * dz));
  142. }
  143. return Math.sqrt((dx * dx) + (dy * dy));
  144. }
  145. /**
  146. * @param obj1
  147. * @param obj2
  148. * @param includeZAxis - if true, includes also the Z axis in the calculation
  149. * @return the distance between the two objects
  150. */
  151. public static double calculateDistance(L2Object obj1, L2Object obj2, boolean includeZAxis)
  152. {
  153. if ((obj1 == null) || (obj2 == null))
  154. {
  155. return 1000000;
  156. }
  157. return calculateDistance(obj1.getPosition().getX(), obj1.getPosition().getY(), obj1.getPosition().getZ(), obj2.getPosition().getX(), obj2.getPosition().getY(), obj2.getPosition().getZ(), includeZAxis);
  158. }
  159. /**
  160. * @param str - the string whose first letter to capitalize
  161. * @return a string with the first letter of the {@code str} capitalized
  162. */
  163. public static String capitalizeFirst(String str)
  164. {
  165. if ((str == null) || str.isEmpty())
  166. {
  167. return str;
  168. }
  169. final char[] arr = str.toCharArray();
  170. final char c = arr[0];
  171. if (Character.isLetter(c))
  172. {
  173. arr[0] = Character.toUpperCase(c);
  174. }
  175. return new String(arr);
  176. }
  177. /**
  178. * (Based on ucwords() function of PHP)<br>
  179. * DrHouse: still functional but must be rewritten to avoid += to concat strings
  180. * @param str - the string to capitalize
  181. * @return a string with the first letter of every word in {@code str} capitalized
  182. */
  183. @Deprecated
  184. public static String capitalizeWords(String str)
  185. {
  186. if ((str == null) || str.isEmpty())
  187. {
  188. return str;
  189. }
  190. char[] charArray = str.toCharArray();
  191. StringBuilder result = new StringBuilder();
  192. // Capitalize the first letter in the given string!
  193. charArray[0] = Character.toUpperCase(charArray[0]);
  194. for (int i = 0; i < charArray.length; i++)
  195. {
  196. if (Character.isWhitespace(charArray[i]))
  197. {
  198. charArray[i + 1] = Character.toUpperCase(charArray[i + 1]);
  199. }
  200. result.append(charArray[i]);
  201. }
  202. return result.toString();
  203. }
  204. /**
  205. * @param range
  206. * @param obj1
  207. * @param obj2
  208. * @param includeZAxis
  209. * @return {@code true} if the two objects are within specified range between each other, {@code false} otherwise
  210. */
  211. public static boolean checkIfInRange(int range, L2Object obj1, L2Object obj2, boolean includeZAxis)
  212. {
  213. if ((obj1 == null) || (obj2 == null))
  214. {
  215. return false;
  216. }
  217. if (obj1.getInstanceId() != obj2.getInstanceId())
  218. {
  219. return false;
  220. }
  221. if (range == -1)
  222. {
  223. return true; // not limited
  224. }
  225. int rad = 0;
  226. if (obj1 instanceof L2Character)
  227. {
  228. rad += ((L2Character) obj1).getTemplate().getCollisionRadius();
  229. }
  230. if (obj2 instanceof L2Character)
  231. {
  232. rad += ((L2Character) obj2).getTemplate().getCollisionRadius();
  233. }
  234. double dx = obj1.getX() - obj2.getX();
  235. double dy = obj1.getY() - obj2.getY();
  236. double d = (dx * dx) + (dy * dy);
  237. if (includeZAxis)
  238. {
  239. double dz = obj1.getZ() - obj2.getZ();
  240. d += (dz * dz);
  241. }
  242. return d <= ((range * range) + (2 * range * rad) + (rad * rad));
  243. }
  244. /**
  245. * Checks if object is within short (sqrt(int.max_value)) radius, not using collisionRadius. Faster calculation than checkIfInRange if distance is short and collisionRadius isn't needed. Not for long distance checks (potential teleports, far away castles etc).
  246. * @param radius
  247. * @param obj1
  248. * @param obj2
  249. * @param includeZAxis if true, check also Z axis (3-dimensional check), otherwise only 2D
  250. * @return {@code true} if objects are within specified range between each other, {@code false} otherwise
  251. */
  252. public static boolean checkIfInShortRadius(int radius, L2Object obj1, L2Object obj2, boolean includeZAxis)
  253. {
  254. if ((obj1 == null) || (obj2 == null))
  255. {
  256. return false;
  257. }
  258. if (radius == -1)
  259. {
  260. return true; // not limited
  261. }
  262. int dx = obj1.getX() - obj2.getX();
  263. int dy = obj1.getY() - obj2.getY();
  264. if (includeZAxis)
  265. {
  266. int dz = obj1.getZ() - obj2.getZ();
  267. return ((dx * dx) + (dy * dy) + (dz * dz)) <= (radius * radius);
  268. }
  269. return ((dx * dx) + (dy * dy)) <= (radius * radius);
  270. }
  271. /**
  272. * @param str - the String to count
  273. * @return the number of "words" in a given string.
  274. */
  275. public static int countWords(String str)
  276. {
  277. return str.trim().split("\\s+").length;
  278. }
  279. /**
  280. * (Based on implode() in PHP)
  281. * @param strArray - an array of strings to concatenate
  282. * @param strDelim - the delimiter to put between the strings
  283. * @return a delimited string for a given array of string elements.
  284. */
  285. public static String implodeString(Iterable<String> strArray, String strDelim)
  286. {
  287. final TextBuilder sbString = TextBuilder.newInstance();
  288. for (String strValue : strArray)
  289. {
  290. sbString.append(strValue);
  291. sbString.append(strDelim);
  292. }
  293. String result = sbString.toString();
  294. TextBuilder.recycle(sbString);
  295. return result;
  296. }
  297. /**
  298. * Based on implode() in PHP
  299. * @param <T>
  300. * @param array
  301. * @param delim
  302. * @return a delimited string for a given array of string elements.
  303. */
  304. public static <T> String implode(T[] array, String delim)
  305. {
  306. String result = "";
  307. for (T val : array)
  308. {
  309. result += val.toString() + delim;
  310. }
  311. if (!result.isEmpty())
  312. {
  313. result = result.substring(0, result.length() - 1);
  314. }
  315. return result;
  316. }
  317. /**
  318. * (Based on round() in PHP)
  319. * @param number - the number to round
  320. * @param numPlaces - how many digits after decimal point to leave intact
  321. * @return the value of {@code number} rounded to specified number of digits after the decimal point.
  322. */
  323. public static float roundTo(float number, int numPlaces)
  324. {
  325. if (numPlaces <= 1)
  326. {
  327. return Math.round(number);
  328. }
  329. float exponent = (float) Math.pow(10, numPlaces);
  330. return Math.round(number * exponent) / exponent;
  331. }
  332. /**
  333. * @param text - the text to check
  334. * @return {@code true} if {@code text} contains only numbers, {@code false} otherwise
  335. */
  336. public static boolean isDigit(String text)
  337. {
  338. if ((text == null) || text.isEmpty())
  339. {
  340. return false;
  341. }
  342. for (char c : text.toCharArray())
  343. {
  344. if (!Character.isDigit(c))
  345. {
  346. return false;
  347. }
  348. }
  349. return true;
  350. }
  351. /**
  352. * @param text - the text to check
  353. * @return {@code true} if {@code text} contains only letters and/or numbers, {@code false} otherwise
  354. */
  355. public static boolean isAlphaNumeric(String text)
  356. {
  357. if ((text == null) || text.isEmpty())
  358. {
  359. return false;
  360. }
  361. for (char c : text.toCharArray())
  362. {
  363. if (!Character.isLetterOrDigit(c))
  364. {
  365. return false;
  366. }
  367. }
  368. return true;
  369. }
  370. /**
  371. * Format the specified digit using the digit grouping symbol "," (comma).<br>
  372. * For example, 123456789 becomes 123,456,789.
  373. * @param amount - the amount of adena
  374. * @return the formatted adena amount
  375. */
  376. public static String formatAdena(long amount)
  377. {
  378. synchronized (ADENA_FORMATTER)
  379. {
  380. return ADENA_FORMATTER.format(amount);
  381. }
  382. }
  383. /**
  384. * Format the given date on the given format
  385. * @param date : the date to format.
  386. * @param format : the format to correct by.
  387. * @return a string representation of the formatted date.
  388. */
  389. public static String formatDate(Date date, String format)
  390. {
  391. if (date == null)
  392. {
  393. return null;
  394. }
  395. final DateFormat dateFormat = new SimpleDateFormat(format);
  396. return dateFormat.format(date);
  397. }
  398. /**
  399. * @param <T>
  400. * @param array - the array to look into
  401. * @param obj - the object to search for
  402. * @return {@code true} if the {@code array} contains the {@code obj}, {@code false} otherwise.
  403. */
  404. public static <T> boolean contains(T[] array, T obj)
  405. {
  406. for (T element : array)
  407. {
  408. if (element == obj)
  409. {
  410. return true;
  411. }
  412. }
  413. return false;
  414. }
  415. /**
  416. * @param array - the array to look into
  417. * @param obj - the integer to search for
  418. * @return {@code true} if the {@code array} contains the {@code obj}, {@code false} otherwise
  419. */
  420. public static boolean contains(int[] array, int obj)
  421. {
  422. for (int element : array)
  423. {
  424. if (element == obj)
  425. {
  426. return true;
  427. }
  428. }
  429. return false;
  430. }
  431. public static File[] getDatapackFiles(String dirname, String extention)
  432. {
  433. File dir = new File(Config.DATAPACK_ROOT, "data/" + dirname);
  434. if (!dir.exists())
  435. {
  436. return null;
  437. }
  438. return dir.listFiles(new ExtFilter(extention));
  439. }
  440. public static String getDateString(Date date)
  441. {
  442. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  443. return dateFormat.format(date.getTime());
  444. }
  445. /**
  446. * Sends the given html to the player.
  447. * @param activeChar
  448. * @param html
  449. */
  450. public static void sendHtml(L2PcInstance activeChar, String html)
  451. {
  452. NpcHtmlMessage npcHtml = new NpcHtmlMessage(0);
  453. npcHtml.setHtml(html);
  454. activeChar.sendPacket(npcHtml);
  455. }
  456. /**
  457. * Sends the html using the community board window.
  458. * @param activeChar
  459. * @param html
  460. */
  461. public static void sendCBHtml(L2PcInstance activeChar, String html)
  462. {
  463. sendCBHtml(activeChar, html, "");
  464. }
  465. /**
  466. * Sends the html using the community board window.
  467. * @param activeChar
  468. * @param html
  469. * @param fillMultiEdit fills the multiedit window (if any) inside the community board.
  470. */
  471. public static void sendCBHtml(L2PcInstance activeChar, String html, String fillMultiEdit)
  472. {
  473. if (activeChar == null)
  474. {
  475. return;
  476. }
  477. if (html != null)
  478. {
  479. activeChar.clearBypass();
  480. int len = html.length();
  481. for (int i = 0; i < len; i++)
  482. {
  483. int start = html.indexOf("\"bypass ", i);
  484. int finish = html.indexOf("\"", start + 1);
  485. if ((start < 0) || (finish < 0))
  486. {
  487. break;
  488. }
  489. if (html.substring(start + 8, start + 10).equals("-h"))
  490. {
  491. start += 11;
  492. }
  493. else
  494. {
  495. start += 8;
  496. }
  497. i = finish;
  498. int finish2 = html.indexOf("$", start);
  499. if ((finish2 < finish) && (finish2 > 0))
  500. {
  501. activeChar.addBypass2(html.substring(start, finish2).trim());
  502. }
  503. else
  504. {
  505. activeChar.addBypass(html.substring(start, finish).trim());
  506. }
  507. }
  508. }
  509. if (fillMultiEdit != null)
  510. {
  511. activeChar.sendPacket(new ShowBoard(html, "1001"));
  512. fillMultiEditContent(activeChar, fillMultiEdit);
  513. }
  514. else
  515. {
  516. activeChar.sendPacket(new ShowBoard(null, "101"));
  517. activeChar.sendPacket(new ShowBoard(html, "101"));
  518. activeChar.sendPacket(new ShowBoard(null, "102"));
  519. activeChar.sendPacket(new ShowBoard(null, "103"));
  520. }
  521. }
  522. /**
  523. * Fills the community board's multiedit window with text. Must send after sendCBHtml
  524. * @param activeChar
  525. * @param text
  526. */
  527. public static void fillMultiEditContent(L2PcInstance activeChar, String text)
  528. {
  529. text = text.replaceAll("<br>", Config.EOL);
  530. List<String> arg = new FastList<>();
  531. arg.add("0");
  532. arg.add("0");
  533. arg.add("0");
  534. arg.add("0");
  535. arg.add("0");
  536. arg.add("0");
  537. arg.add(activeChar.getName());
  538. arg.add(Integer.toString(activeChar.getObjectId()));
  539. arg.add(activeChar.getAccountName());
  540. arg.add("9");
  541. arg.add(" ");
  542. arg.add(" ");
  543. arg.add(text);
  544. arg.add("0");
  545. arg.add("0");
  546. arg.add("0");
  547. arg.add("0");
  548. activeChar.sendPacket(new ShowBoard(arg));
  549. }
  550. /**
  551. * Return the number of playable characters in a defined radius around the specified object.
  552. * @param range : the radius in which to look for players
  553. * @param npc : the object whose knownlist to check
  554. * @param playable : if {@code true}, count summons and pets aswell
  555. * @param invisible : if {@code true}, count invisible characters aswell
  556. * @return the number of targets found
  557. */
  558. public static int getPlayersCountInRadius(int range, L2Object npc, boolean playable, boolean invisible)
  559. {
  560. int count = 0;
  561. final Collection<L2Object> objs = npc.getKnownList().getKnownObjects().values();
  562. for (L2Object obj : objs)
  563. {
  564. if ((obj != null) && ((obj.isPlayable() && playable) || obj.isPet()))
  565. {
  566. if (obj.isPlayer() && !invisible && obj.getActingPlayer().getAppearance().getInvisible())
  567. {
  568. continue;
  569. }
  570. final L2Character cha = (L2Character) obj;
  571. if (((cha.getZ() < (npc.getZ() - 100)) && (cha.getZ() > (npc.getZ() + 100))) || !(GeoData.getInstance().canSeeTarget(cha.getX(), cha.getY(), cha.getZ(), npc.getX(), npc.getY(), npc.getZ())))
  572. {
  573. continue;
  574. }
  575. if (Util.checkIfInRange(range, npc, obj, true) && !cha.isDead())
  576. {
  577. count++;
  578. }
  579. }
  580. }
  581. return count;
  582. }
  583. }