CellPathFinding.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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.pathfinding.cellnodes;
  16. import java.util.ArrayList;
  17. import java.util.List;
  18. import java.util.ListIterator;
  19. import java.util.logging.Level;
  20. import java.util.logging.Logger;
  21. import javolution.util.FastList;
  22. import com.l2jserver.Config;
  23. import com.l2jserver.gameserver.GeoData;
  24. import com.l2jserver.gameserver.idfactory.IdFactory;
  25. import com.l2jserver.gameserver.model.L2ItemInstance;
  26. import com.l2jserver.gameserver.model.L2World;
  27. import com.l2jserver.gameserver.model.itemcontainer.PcInventory;
  28. import com.l2jserver.gameserver.pathfinding.AbstractNode;
  29. import com.l2jserver.gameserver.pathfinding.AbstractNodeLoc;
  30. import com.l2jserver.gameserver.pathfinding.PathFinding;
  31. import com.l2jserver.util.StringUtil;
  32. /**
  33. *
  34. * @author Sami, DS
  35. * Credits to Diamond
  36. */
  37. public class CellPathFinding extends PathFinding
  38. {
  39. private static final Logger _log = Logger.getLogger(CellPathFinding.class.getName());
  40. private BufferInfo[] _allBuffers;
  41. private int _findSuccess = 0;
  42. private int _findFails = 0;
  43. private int _postFilterUses = 0;
  44. private int _postFilterPlayableUses = 0;
  45. private int _postFilterPasses = 0;
  46. private long _postFilterElapsed = 0;
  47. private FastList<L2ItemInstance> _debugItems = null;
  48. public static CellPathFinding getInstance()
  49. {
  50. return SingletonHolder._instance;
  51. }
  52. private CellPathFinding()
  53. {
  54. try
  55. {
  56. String[] array = Config.PATHFIND_BUFFERS.split(";");
  57. _allBuffers = new BufferInfo[array.length];
  58. String buf;
  59. String[] args;
  60. for (int i = 0; i < array.length; i++)
  61. {
  62. buf = array[i];
  63. args = buf.split("x");
  64. if (args.length != 2)
  65. throw new Exception("Invalid buffer definition: " + buf);
  66. _allBuffers[i] = new BufferInfo(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
  67. }
  68. }
  69. catch (Exception e)
  70. {
  71. _log.log(Level.WARNING, "CellPathFinding: Problem during buffer init: " + e.getMessage(), e);
  72. throw new Error("CellPathFinding: load aborted");
  73. }
  74. }
  75. /**
  76. * @see com.l2jserver.gameserver.pathfinding.PathFinding#pathNodesExist(short)
  77. */
  78. @Override
  79. public boolean pathNodesExist(short regionoffset)
  80. {
  81. return false;
  82. }
  83. /**
  84. * @see com.l2jserver.gameserver.pathfinding.PathFinding#findPath(int, int, int, int, int, int, int, boolean)
  85. */
  86. @Override
  87. public List<AbstractNodeLoc> findPath(int x, int y, int z, int tx, int ty, int tz, int instanceId, boolean playable)
  88. {
  89. int gx = (x - L2World.MAP_MIN_X) >> 4;
  90. int gy = (y - L2World.MAP_MIN_Y) >> 4;
  91. if (!GeoData.getInstance().hasGeo(x, y))
  92. return null;
  93. short gz = GeoData.getInstance().getHeight(x, y, z);
  94. int gtx = (tx - L2World.MAP_MIN_X) >> 4;
  95. int gty = (ty - L2World.MAP_MIN_Y) >> 4;
  96. if (!GeoData.getInstance().hasGeo(tx, ty))
  97. return null;
  98. short gtz = GeoData.getInstance().getHeight(tx, ty, tz);
  99. CellNodeBuffer buffer = alloc(64 + 2 * Math.max(Math.abs(gx - gtx), Math.abs(gy - gty)), playable);
  100. if (buffer == null)
  101. return null;
  102. boolean debug = playable && Config.DEBUG_PATH;
  103. if (debug)
  104. {
  105. if (_debugItems == null)
  106. _debugItems = new FastList<L2ItemInstance>();
  107. else
  108. {
  109. for (L2ItemInstance item : _debugItems)
  110. {
  111. if (item == null)
  112. continue;
  113. item.decayMe();
  114. }
  115. _debugItems.clear();
  116. }
  117. }
  118. FastList<AbstractNodeLoc> path = null;
  119. try
  120. {
  121. CellNode result = buffer.findPath(gx, gy, gz, gtx, gty, gtz);
  122. if (debug)
  123. {
  124. for (CellNode n : buffer.debugPath())
  125. {
  126. if (n.getCost() < 0) // calculated path
  127. dropDebugItem(1831, (int) (-n.getCost() * 10), n.getLoc());
  128. else
  129. // known nodes
  130. dropDebugItem(PcInventory.ADENA_ID, (int) (n.getCost() * 10), n.getLoc());
  131. }
  132. }
  133. if (result == null)
  134. {
  135. _findFails++;
  136. return null;
  137. }
  138. path = constructPath(result);
  139. }
  140. catch (Exception e)
  141. {
  142. _log.log(Level.WARNING, "", e);
  143. return null;
  144. }
  145. finally
  146. {
  147. buffer.free();
  148. }
  149. if (path.size() < 3 || Config.MAX_POSTFILTER_PASSES <= 0)
  150. {
  151. _findSuccess++;
  152. return path;
  153. }
  154. long timeStamp = System.currentTimeMillis();
  155. _postFilterUses++;
  156. if (playable)
  157. _postFilterPlayableUses++;
  158. int currentX, currentY, currentZ;
  159. ListIterator<AbstractNodeLoc> middlePoint, endPoint;
  160. AbstractNodeLoc locMiddle, locEnd;
  161. boolean remove;
  162. int pass = 0;
  163. do
  164. {
  165. pass++;
  166. _postFilterPasses++;
  167. remove = false;
  168. middlePoint = path.listIterator();
  169. endPoint = path.listIterator(1);
  170. locEnd = null;
  171. currentX = x;
  172. currentY = y;
  173. currentZ = z;
  174. while (endPoint.hasNext())
  175. {
  176. locEnd = endPoint.next();
  177. locMiddle = middlePoint.next();
  178. if (GeoData.getInstance().canMoveFromToTarget(currentX, currentY, currentZ, locEnd.getX(), locEnd.getY(), locEnd.getZ(), instanceId))
  179. {
  180. middlePoint.remove();
  181. remove = true;
  182. if (debug)
  183. dropDebugItem(735, 1, locMiddle);
  184. }
  185. else
  186. {
  187. currentX = locMiddle.getX();
  188. currentY = locMiddle.getY();
  189. currentZ = locMiddle.getZ();
  190. }
  191. }
  192. }
  193. // only one postfilter pass for AI
  194. while (playable && remove && path.size() > 2 && pass < Config.MAX_POSTFILTER_PASSES);
  195. if (debug)
  196. {
  197. middlePoint = path.listIterator();
  198. while (middlePoint.hasNext())
  199. {
  200. locMiddle = middlePoint.next();
  201. dropDebugItem(65, 1, locMiddle);
  202. }
  203. }
  204. _findSuccess++;
  205. _postFilterElapsed += System.currentTimeMillis() - timeStamp;
  206. return path;
  207. }
  208. private FastList<AbstractNodeLoc> constructPath(AbstractNode node)
  209. {
  210. FastList<AbstractNodeLoc> path = new FastList<AbstractNodeLoc>();
  211. int previousDirectionX = Integer.MIN_VALUE;
  212. int previousDirectionY = Integer.MIN_VALUE;
  213. int directionX, directionY;
  214. while (node.getParent() != null)
  215. {
  216. if (!Config.ADVANCED_DIAGONAL_STRATEGY && node.getParent().getParent() != null)
  217. {
  218. int tmpX = node.getLoc().getNodeX() - node.getParent().getParent().getLoc().getNodeX();
  219. int tmpY = node.getLoc().getNodeY() - node.getParent().getParent().getLoc().getNodeY();
  220. if (Math.abs(tmpX) == Math.abs(tmpY))
  221. {
  222. directionX = tmpX;
  223. directionY = tmpY;
  224. }
  225. else
  226. {
  227. directionX = node.getLoc().getNodeX() - node.getParent().getLoc().getNodeX();
  228. directionY = node.getLoc().getNodeY() - node.getParent().getLoc().getNodeY();
  229. }
  230. }
  231. else
  232. {
  233. directionX = node.getLoc().getNodeX() - node.getParent().getLoc().getNodeX();
  234. directionY = node.getLoc().getNodeY() - node.getParent().getLoc().getNodeY();
  235. }
  236. // only add a new route point if moving direction changes
  237. if (directionX != previousDirectionX || directionY != previousDirectionY)
  238. {
  239. previousDirectionX = directionX;
  240. previousDirectionY = directionY;
  241. path.addFirst(node.getLoc());
  242. node.setLoc(null);
  243. }
  244. node = node.getParent();
  245. }
  246. return path;
  247. }
  248. private final CellNodeBuffer alloc(int size, boolean playable)
  249. {
  250. CellNodeBuffer current = null;
  251. for (BufferInfo i : _allBuffers)
  252. {
  253. if (i.mapSize >= size)
  254. {
  255. for (CellNodeBuffer buf : i.bufs)
  256. {
  257. if (buf.lock())
  258. {
  259. i.uses++;
  260. if (playable)
  261. i.playableUses++;
  262. i.elapsed += buf.getElapsedTime();
  263. current = buf;
  264. break;
  265. }
  266. }
  267. if (current != null)
  268. break;
  269. // not found, allocate temporary buffer
  270. current = new CellNodeBuffer(i.mapSize);
  271. current.lock();
  272. if (i.bufs.size() < i.count)
  273. {
  274. i.bufs.add(current);
  275. i.uses++;
  276. if (playable)
  277. i.playableUses++;
  278. break;
  279. }
  280. i.overflows++;
  281. if (playable)
  282. i.playableOverflows++;
  283. //System.err.println("Overflow, size requested: " + size + " playable:"+playable);
  284. }
  285. }
  286. return current;
  287. }
  288. private final void dropDebugItem(int itemId, int num, AbstractNodeLoc loc)
  289. {
  290. final L2ItemInstance item = new L2ItemInstance(IdFactory.getInstance().getNextId(), itemId);
  291. item.setCount(num);
  292. item.spawnMe(loc.getX(), loc.getY(), loc.getZ());
  293. _debugItems.add(item);
  294. }
  295. private static final class BufferInfo
  296. {
  297. final int mapSize;
  298. final int count;
  299. ArrayList<CellNodeBuffer> bufs;
  300. int uses = 0;
  301. int playableUses = 0;
  302. int overflows = 0;
  303. int playableOverflows = 0;
  304. long elapsed = 0;
  305. public BufferInfo(int size, int cnt)
  306. {
  307. mapSize = size;
  308. count = cnt;
  309. bufs = new ArrayList<CellNodeBuffer>(count);
  310. }
  311. @Override
  312. public String toString()
  313. {
  314. final StringBuilder stat = new StringBuilder(100);
  315. StringUtil.append(stat,
  316. String.valueOf(mapSize), "x", String.valueOf(mapSize),
  317. " num:", String.valueOf(bufs.size()), "/" ,String.valueOf(count),
  318. " uses:", String.valueOf(uses), "/", String.valueOf(playableUses));
  319. if (uses > 0)
  320. StringUtil.append(stat, " total/avg(ms):",
  321. String.valueOf(elapsed), "/", String.format("%1.2f", (double)elapsed/uses));
  322. StringUtil.append(stat, " ovf:", String.valueOf(overflows), "/",
  323. String.valueOf(playableOverflows));
  324. return stat.toString();
  325. }
  326. }
  327. @Override
  328. public String[] getStat()
  329. {
  330. final String[] result = new String[_allBuffers.length + 1];
  331. for (int i = 0; i < _allBuffers.length; i++)
  332. result[i] = _allBuffers[i].toString();
  333. final StringBuilder stat = new StringBuilder(100);
  334. StringUtil.append(stat,
  335. "LOS postfilter uses:", String.valueOf(_postFilterUses),
  336. "/", String.valueOf(_postFilterPlayableUses));
  337. if (_postFilterUses > 0)
  338. StringUtil.append(stat, " total/avg(ms):",
  339. String.valueOf(_postFilterElapsed), "/",
  340. String.format("%1.2f", (double)_postFilterElapsed/_postFilterUses),
  341. " passes total/avg:", String.valueOf(_postFilterPasses), "/",
  342. String.format("%1.1f", (double)_postFilterPasses/_postFilterUses),"\r\n");
  343. StringUtil.append(stat, "Pathfind success/fail:", String.valueOf(_findSuccess),
  344. "/", String.valueOf(_findFails));
  345. result[result.length - 1] = stat.toString();
  346. return result;
  347. }
  348. @SuppressWarnings("synthetic-access")
  349. private static class SingletonHolder
  350. {
  351. protected static final CellPathFinding _instance = new CellPathFinding();
  352. }
  353. }