GameTimeController.java 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. /*
  2. * This program is free software; you can redistribute it and/or modify
  3. * it under the terms of the GNU General Public License as published by
  4. * the Free Software Foundation; either version 2, or (at your option)
  5. * any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program; if not, write to the Free Software
  14. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  15. * 02111-1307, USA.
  16. *
  17. * http://www.gnu.org/copyleft/gpl.html
  18. */
  19. package net.sf.l2j.gameserver;
  20. import java.text.SimpleDateFormat;
  21. import java.util.Date;
  22. import java.util.List;
  23. import java.util.concurrent.ScheduledFuture;
  24. import java.util.logging.Logger;
  25. import javolution.util.FastList;
  26. import net.sf.l2j.gameserver.ai.CtrlEvent;
  27. import net.sf.l2j.gameserver.instancemanager.DayNightSpawnManager;
  28. import net.sf.l2j.gameserver.model.L2Character;
  29. /**
  30. * This class ...
  31. *
  32. * @version $Revision: 1.1.4.8 $ $Date: 2005/04/06 16:13:24 $
  33. */
  34. public class GameTimeController
  35. {
  36. static final Logger _log = Logger.getLogger(GameTimeController.class.getName());
  37. public static final int TICKS_PER_SECOND = 10;
  38. public static final int MILLIS_IN_TICK = 1000 / TICKS_PER_SECOND;
  39. private static GameTimeController _instance = new GameTimeController();
  40. protected static int _gameTicks;
  41. protected static long _gameStartTime;
  42. protected static boolean _isNight = false;
  43. private static List<L2Character> _movingObjects = new FastList<L2Character>();
  44. protected static TimerThread _timer;
  45. private ScheduledFuture<?> _timerWatcher;
  46. /**
  47. * one ingame day is 240 real minutes
  48. */
  49. public static GameTimeController getInstance()
  50. {
  51. return _instance;
  52. }
  53. private GameTimeController()
  54. {
  55. _gameStartTime = System.currentTimeMillis() - 3600000; // offset so that the server starts a day begin
  56. _gameTicks = 3600000 / MILLIS_IN_TICK; // offset so that the server starts a day begin
  57. _timer = new TimerThread();
  58. _timer.start();
  59. _timerWatcher = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new TimerWatcher(), 0, 1000);
  60. ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new BroadcastSunState(), 0, 600000);
  61. }
  62. public boolean isNowNight()
  63. {
  64. return _isNight;
  65. }
  66. public int getGameTime()
  67. {
  68. return (_gameTicks / (TICKS_PER_SECOND * 10));
  69. }
  70. public static int getGameTicks()
  71. {
  72. return _gameTicks;
  73. }
  74. /**
  75. * Add a L2Character to movingObjects of GameTimeController.<BR><BR>
  76. *
  77. * <B><U> Concept</U> :</B><BR><BR>
  78. * All L2Character in movement are identified in <B>movingObjects</B> of GameTimeController.<BR><BR>
  79. *
  80. * @param cha The L2Character to add to movingObjects of GameTimeController
  81. *
  82. */
  83. public synchronized void registerMovingObject(L2Character cha)
  84. {
  85. if(cha == null) return;
  86. if (!_movingObjects.contains(cha)) _movingObjects.add(cha);
  87. }
  88. /**
  89. * Move all L2Characters contained in movingObjects of GameTimeController.<BR><BR>
  90. *
  91. * <B><U> Concept</U> :</B><BR><BR>
  92. * All L2Character in movement are identified in <B>movingObjects</B> of GameTimeController.<BR><BR>
  93. *
  94. * <B><U> Actions</U> :</B><BR><BR>
  95. * <li>Update the position of each L2Character </li>
  96. * <li>If movement is finished, the L2Character is removed from movingObjects </li>
  97. * <li>Create a task to update the _knownObject and _knowPlayers of each L2Character that finished its movement and of their already known L2Object then notify AI with EVT_ARRIVED </li><BR><BR>
  98. *
  99. */
  100. protected synchronized void moveObjects()
  101. {
  102. // Get all L2Character from the ArrayList movingObjects and put them into a table
  103. L2Character[] chars = _movingObjects.toArray(new L2Character[_movingObjects.size()]);
  104. // Create an ArrayList to contain all L2Character that are arrived to destination
  105. List<L2Character> ended = null;
  106. // Go throw the table containing L2Character in movement
  107. for (int i = 0; i < chars.length; i++)
  108. {
  109. L2Character cha = chars[i];
  110. // Update the position of the L2Character and return True if the movement is finished
  111. boolean end = cha.updatePosition(_gameTicks);
  112. // If movement is finished, the L2Character is removed from movingObjects and added to the ArrayList ended
  113. if (end)
  114. {
  115. _movingObjects.remove(cha);
  116. if (ended == null) ended = new FastList<L2Character>();
  117. ended.add(cha);
  118. }
  119. }
  120. // Create a task to update the _knownObject and _knowPlayers of each L2Character that finished its movement and of their already known L2Object
  121. // then notify AI with EVT_ARRIVED
  122. // TODO: maybe a general TP is needed for that kinda stuff (all knownlist updates should be done in a TP anyway).
  123. if (ended != null)
  124. ThreadPoolManager.getInstance().executeTask(new MovingObjectArrived(ended));
  125. }
  126. public void stopTimer()
  127. {
  128. _timerWatcher.cancel(true);
  129. _timer.interrupt();
  130. }
  131. class TimerThread extends Thread
  132. {
  133. protected Exception _error;
  134. public TimerThread()
  135. {
  136. super("GameTimeController");
  137. setDaemon(true);
  138. setPriority(MAX_PRIORITY);
  139. _error = null;
  140. }
  141. @Override
  142. public void run()
  143. {
  144. try
  145. {
  146. for (;;)
  147. {
  148. int _oldTicks=_gameTicks; // save old ticks value to avoid moving objects 2x in same tick
  149. long runtime = System.currentTimeMillis() - _gameStartTime; // from server boot to now
  150. _gameTicks = (int) (runtime / MILLIS_IN_TICK); // new ticks value (ticks now)
  151. if (_oldTicks != _gameTicks) moveObjects(); // XXX: if this makes objects go slower, remove it
  152. // but I think it can't make that effect. is it better to call moveObjects() twice in same
  153. // tick to make-up for missed tick ? or is it better to ignore missed tick ?
  154. // (will happen very rarely but it will happen ... on garbage collection definitely)
  155. runtime = (System.currentTimeMillis() - _gameStartTime) - runtime;
  156. // calculate sleep time... time needed to next tick minus time it takes to call moveObjects()
  157. int sleepTime = 1 + MILLIS_IN_TICK - ((int) runtime) % MILLIS_IN_TICK;
  158. //_log.finest("TICK: "+_gameTicks);
  159. sleep(sleepTime); // hope other threads will have much more cpu time available now
  160. // SelectorThread most of all
  161. }
  162. }
  163. catch (Exception e)
  164. {
  165. _error = e;
  166. }
  167. }
  168. }
  169. class TimerWatcher implements Runnable
  170. {
  171. public void run()
  172. {
  173. if (!_timer.isAlive())
  174. {
  175. String time = (new SimpleDateFormat("HH:mm:ss")).format(new Date());
  176. _log.warning(time + " TimerThread stop with following error. restart it.");
  177. if (_timer._error != null) _timer._error.printStackTrace();
  178. _timer = new TimerThread();
  179. _timer.start();
  180. }
  181. }
  182. }
  183. /**
  184. * Update the _knownObject and _knowPlayers of each L2Character that finished its movement and of their already known L2Object then notify AI with EVT_ARRIVED.<BR><BR>
  185. */
  186. class MovingObjectArrived implements Runnable
  187. {
  188. private final List<L2Character> _ended;
  189. MovingObjectArrived(List<L2Character> ended)
  190. {
  191. _ended = ended;
  192. }
  193. public void run()
  194. {
  195. for (L2Character cha : _ended)
  196. {
  197. try {
  198. cha.getKnownList().updateKnownObjects();
  199. cha.getAI().notifyEvent(CtrlEvent.EVT_ARRIVED);
  200. } catch (NullPointerException e) {}
  201. }
  202. }
  203. }
  204. /**
  205. * @param rise
  206. */
  207. class BroadcastSunState implements Runnable
  208. {
  209. public void run()
  210. {
  211. int h = (getGameTime() / 60) % 24; // Time in hour
  212. boolean tempIsNight = (h < 6);
  213. if (tempIsNight != _isNight) { // If diff day/night state
  214. _isNight = tempIsNight; // Set current day/night varible to value of temp varible
  215. DayNightSpawnManager.getInstance().notifyChangeMode();
  216. }
  217. }
  218. }
  219. }