Util.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. if (includeZAxis)
  237. {
  238. double dz = obj1.getZ() - obj2.getZ();
  239. double d = (dx * dx) + (dy * dy) + (dz * dz);
  240. return d <= ((range * range) + (2 * range * rad) + (rad * rad));
  241. }
  242. double d = (dx * dx) + (dy * dy);
  243. return d <= ((range * range) + (2 * range * rad) + (rad * rad));
  244. }
  245. /**
  246. * 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).
  247. * @param radius
  248. * @param obj1
  249. * @param obj2
  250. * @param includeZAxis if true, check also Z axis (3-dimensional check), otherwise only 2D
  251. * @return {@code true} if objects are within specified range between each other, {@code false} otherwise
  252. */
  253. public static boolean checkIfInShortRadius(int radius, L2Object obj1, L2Object obj2, boolean includeZAxis)
  254. {
  255. if ((obj1 == null) || (obj2 == null))
  256. {
  257. return false;
  258. }
  259. if (radius == -1)
  260. {
  261. return true; // not limited
  262. }
  263. int dx = obj1.getX() - obj2.getX();
  264. int dy = obj1.getY() - obj2.getY();
  265. if (includeZAxis)
  266. {
  267. int dz = obj1.getZ() - obj2.getZ();
  268. return ((dx * dx) + (dy * dy) + (dz * dz)) <= (radius * radius);
  269. }
  270. return ((dx * dx) + (dy * dy)) <= (radius * radius);
  271. }
  272. /**
  273. * @param str - the String to count
  274. * @return the number of "words" in a given string.
  275. */
  276. public static int countWords(String str)
  277. {
  278. return str.trim().split("\\s+").length;
  279. }
  280. /**
  281. * (Based on implode() in PHP)
  282. * @param strArray - an array of strings to concatenate
  283. * @param strDelim - the delimiter to put between the strings
  284. * @return a delimited string for a given array of string elements.
  285. */
  286. public static String implodeString(Iterable<String> strArray, String strDelim)
  287. {
  288. final TextBuilder sbString = TextBuilder.newInstance();
  289. for (String strValue : strArray)
  290. {
  291. sbString.append(strValue);
  292. sbString.append(strDelim);
  293. }
  294. String result = sbString.toString();
  295. TextBuilder.recycle(sbString);
  296. return result;
  297. }
  298. /**
  299. * (Based on round() in PHP)
  300. * @param number - the number to round
  301. * @param numPlaces - how many digits after decimal point to leave intact
  302. * @return the value of {@code number} rounded to specified number of digits after the decimal point.
  303. */
  304. public static float roundTo(float number, int numPlaces)
  305. {
  306. if (numPlaces <= 1)
  307. {
  308. return Math.round(number);
  309. }
  310. float exponent = (float) Math.pow(10, numPlaces);
  311. return Math.round(number * exponent) / exponent;
  312. }
  313. /**
  314. * @param text - the text to check
  315. * @return {@code true} if {@code text} contains only numbers, {@code false} otherwise
  316. */
  317. public static boolean isDigit(String text)
  318. {
  319. if ((text == null) || text.isEmpty())
  320. {
  321. return false;
  322. }
  323. for (char c : text.toCharArray())
  324. {
  325. if (!Character.isDigit(c))
  326. {
  327. return false;
  328. }
  329. }
  330. return true;
  331. }
  332. /**
  333. * @param text - the text to check
  334. * @return {@code true} if {@code text} contains only letters and/or numbers, {@code false} otherwise
  335. */
  336. public static boolean isAlphaNumeric(String text)
  337. {
  338. if ((text == null) || text.isEmpty())
  339. {
  340. return false;
  341. }
  342. for (char c : text.toCharArray())
  343. {
  344. if (!Character.isLetterOrDigit(c))
  345. {
  346. return false;
  347. }
  348. }
  349. return true;
  350. }
  351. /**
  352. * Format the specified digit using the digit grouping symbol "," (comma).<br>
  353. * For example, 123456789 becomes 123,456,789.
  354. * @param amount - the amount of adena
  355. * @return the formatted adena amount
  356. */
  357. public static String formatAdena(long amount)
  358. {
  359. synchronized (ADENA_FORMATTER)
  360. {
  361. return ADENA_FORMATTER.format(amount);
  362. }
  363. }
  364. /**
  365. * Format the given date on the given format
  366. * @param date : the date to format.
  367. * @param format : the format to correct by.
  368. * @return a string representation of the formatted date.
  369. */
  370. public static String formatDate(Date date, String format)
  371. {
  372. if (date == null)
  373. {
  374. return null;
  375. }
  376. final DateFormat dateFormat = new SimpleDateFormat(format);
  377. return dateFormat.format(date);
  378. }
  379. /**
  380. * @param <T>
  381. * @param array - the array to look into
  382. * @param obj - the object to search for
  383. * @return {@code true} if the {@code array} contains the {@code obj}, {@code false} otherwise.
  384. */
  385. public static <T> boolean contains(T[] array, T obj)
  386. {
  387. for (T element : array)
  388. {
  389. if (element == obj)
  390. {
  391. return true;
  392. }
  393. }
  394. return false;
  395. }
  396. /**
  397. * @param array - the array to look into
  398. * @param obj - the integer to search for
  399. * @return {@code true} if the {@code array} contains the {@code obj}, {@code false} otherwise
  400. */
  401. public static boolean contains(int[] array, int obj)
  402. {
  403. for (int element : array)
  404. {
  405. if (element == obj)
  406. {
  407. return true;
  408. }
  409. }
  410. return false;
  411. }
  412. public static File[] getDatapackFiles(String dirname, String extention)
  413. {
  414. File dir = new File(Config.DATAPACK_ROOT, "data/" + dirname);
  415. if (!dir.exists())
  416. {
  417. return null;
  418. }
  419. return dir.listFiles(new ExtFilter(extention));
  420. }
  421. public static String getDateString(Date date)
  422. {
  423. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  424. return dateFormat.format(date.getTime());
  425. }
  426. /**
  427. * Sends the given html to the player.
  428. * @param activeChar
  429. * @param html
  430. */
  431. public static void sendHtml(L2PcInstance activeChar, String html)
  432. {
  433. NpcHtmlMessage npcHtml = new NpcHtmlMessage(0);
  434. npcHtml.setHtml(html);
  435. activeChar.sendPacket(npcHtml);
  436. }
  437. /**
  438. * Sends the html using the community board window.
  439. * @param activeChar
  440. * @param html
  441. */
  442. public static void sendCBHtml(L2PcInstance activeChar, String html)
  443. {
  444. sendCBHtml(activeChar, html, "");
  445. }
  446. /**
  447. * Sends the html using the community board window.
  448. * @param activeChar
  449. * @param html
  450. * @param fillMultiEdit fills the multiedit window (if any) inside the community board.
  451. */
  452. public static void sendCBHtml(L2PcInstance activeChar, String html, String fillMultiEdit)
  453. {
  454. if (activeChar == null)
  455. {
  456. return;
  457. }
  458. if (html != null)
  459. {
  460. activeChar.clearBypass();
  461. int len = html.length();
  462. for (int i = 0; i < len; i++)
  463. {
  464. int start = html.indexOf("\"bypass ", i);
  465. int finish = html.indexOf("\"", start + 1);
  466. if ((start < 0) || (finish < 0))
  467. {
  468. break;
  469. }
  470. if (html.substring(start + 8, start + 10).equals("-h"))
  471. {
  472. start += 11;
  473. }
  474. else
  475. {
  476. start += 8;
  477. }
  478. i = finish;
  479. int finish2 = html.indexOf("$", start);
  480. if ((finish2 < finish) && (finish2 > 0))
  481. {
  482. activeChar.addBypass2(html.substring(start, finish2).trim());
  483. }
  484. else
  485. {
  486. activeChar.addBypass(html.substring(start, finish).trim());
  487. }
  488. }
  489. }
  490. if (fillMultiEdit != null)
  491. {
  492. activeChar.sendPacket(new ShowBoard(html, "1001"));
  493. fillMultiEditContent(activeChar, fillMultiEdit);
  494. }
  495. else
  496. {
  497. activeChar.sendPacket(new ShowBoard(null, "101"));
  498. activeChar.sendPacket(new ShowBoard(html, "101"));
  499. activeChar.sendPacket(new ShowBoard(null, "102"));
  500. activeChar.sendPacket(new ShowBoard(null, "103"));
  501. }
  502. }
  503. /**
  504. * Fills the community board's multiedit window with text. Must send after sendCBHtml
  505. * @param activeChar
  506. * @param text
  507. */
  508. public static void fillMultiEditContent(L2PcInstance activeChar, String text)
  509. {
  510. text = text.replaceAll("<br>", Config.EOL);
  511. List<String> arg = new FastList<>();
  512. arg.add("0");
  513. arg.add("0");
  514. arg.add("0");
  515. arg.add("0");
  516. arg.add("0");
  517. arg.add("0");
  518. arg.add(activeChar.getName());
  519. arg.add(Integer.toString(activeChar.getObjectId()));
  520. arg.add(activeChar.getAccountName());
  521. arg.add("9");
  522. arg.add(" ");
  523. arg.add(" ");
  524. arg.add(text);
  525. arg.add("0");
  526. arg.add("0");
  527. arg.add("0");
  528. arg.add("0");
  529. activeChar.sendPacket(new ShowBoard(arg));
  530. }
  531. /**
  532. * Return the number of players in a defined radius.<br>
  533. * @param range : the radius.
  534. * @param npc : the object to make the test on.
  535. * @param playable : true counts summons and pets.
  536. * @param invisible : true counts invisible characters.
  537. * @return the number of targets found.
  538. */
  539. public static int getPlayersCountInRadius(int range, L2Object npc, boolean playable, boolean invisible)
  540. {
  541. int count = 0;
  542. final Collection<L2Object> objs = npc.getKnownList().getKnownObjects().values();
  543. for (L2Object obj : objs)
  544. {
  545. if ((obj != null) && ((obj.isPlayable() && playable) || obj.isPet()))
  546. {
  547. if (obj.isPlayer() && !invisible)
  548. {
  549. if (obj.getActingPlayer().getAppearance().getInvisible())
  550. {
  551. continue;
  552. }
  553. }
  554. final L2Character cha = (L2Character) obj;
  555. 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())))
  556. {
  557. continue;
  558. }
  559. if (Util.checkIfInRange(range, npc, obj, true) && !cha.isDead())
  560. {
  561. count++;
  562. }
  563. }
  564. }
  565. return count;
  566. }
  567. }