8107db9627d1d70034db863a4da738a4cf647a0c
[Mograsim.git] / era.mi / src / era / mi / logic / timeline / Timeline.java
1 package era.mi.logic.timeline;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.PriorityQueue;
6 import java.util.function.Consumer;
7
8 /**
9  * Orders Events by the time they are due to be executed. Can execute Events individually.
10  * 
11  * @author Fabian Stemmler
12  *
13  */
14 public class Timeline
15 {
16         private PriorityQueue<InnerEvent> events;
17         private long currentTime = 0;
18
19         private final List<Consumer<TimelineEvent>> eventAddedListener;
20
21         public Timeline(int initCapacity)
22         {
23                 events = new PriorityQueue<InnerEvent>(initCapacity, (a, b) ->
24                 {
25                         long difference = a.getTiming() - b.getTiming();
26                         if (difference == 0)
27                                 return 0;
28                         return difference < 0 ? -1 : 1;
29                 });
30
31                 eventAddedListener = new ArrayList<>();
32         }
33
34         public boolean hasNext()
35         {
36                 return !events.isEmpty();
37         }
38
39         public void executeNext()
40         {
41                 InnerEvent first = events.poll();
42                 currentTime = first.getTiming();
43                 first.run();
44         }
45
46         public void executeAll()
47         {
48                 while (hasNext())
49                         executeNext();
50         }
51
52         /**
53          * Executes all events up to a given simulation timestamp. The simulation process can be constrained by a real world timestamp.
54          * 
55          * @param timestamp  the simulation timestamp up to which the events will be processed
56          * @param stopMillis the System.currentTimeMillis() when simulation definitely needs to stop.
57          * @return if it was possible to fulfil the goal in the given real world time.
58          * @author Christian Femers
59          */
60         public ExecutionResult executeUpTo(long timestamp, long stopMillis)
61         {
62                 if (events.isEmpty())
63                 {
64                         currentTime = timestamp;
65                         return ExecutionResult.NOTHING_DONE;
66                 }
67                 int checkStop = 0;
68                 InnerEvent first = events.peek();
69                 while (first != null && first.getTiming() <= timestamp)
70                 {
71                         events.remove();
72                         currentTime = first.getTiming();
73                         first.run();
74                         // Don't check after every run
75                         checkStop = (checkStop + 1) % 10;
76                         if (checkStop == 0 && System.currentTimeMillis() >= stopMillis)
77                                 return ExecutionResult.RAN_OUT_OF_TIME;
78                         first = events.peek();
79                 }
80                 currentTime = timestamp;
81                 return ExecutionResult.DONE_IN_TIME;
82         }
83
84         public long getSimulationTime()
85         {
86                 return currentTime;
87         }
88
89         public long nextEventTime()
90         {
91                 if (!hasNext())
92                         return -1;
93                 return events.peek().timing;
94         }
95
96         public void reset()
97         {
98                 events.clear();
99                 currentTime = 0;
100         }
101
102         public void addEventAddedListener(Consumer<TimelineEvent> listener)
103         {
104                 eventAddedListener.add(listener);
105         }
106
107         public void removeEventAddedListener(Consumer<TimelineEvent> listener)
108         {
109                 eventAddedListener.remove(listener);
110         }
111
112         /**
113          * Adds an Event to the {@link Timeline}
114          * 
115          * @param function       The {@link TimelineEventHandler} that will be executed, when the {@link InnerEvent} occurs on the timeline.
116          * @param relativeTiming The amount of MI ticks in which the {@link InnerEvent} is called, starting from the current time.
117          */
118         public void addEvent(TimelineEventHandler function, int relativeTiming)
119         {
120                 long timing = currentTime + relativeTiming;
121                 TimelineEvent event = new TimelineEvent(timing);
122                 events.add(new InnerEvent(function, event, timing));
123                 eventAddedListener.forEach(l -> l.accept(event));
124         }
125
126         private class InnerEvent
127         {
128
129                 final long timing;
130                 private final TimelineEventHandler function;
131                 private final TimelineEvent event;
132
133                 /**
134                  * Creates an {@link InnerEvent}
135                  * 
136                  * @param function {@link TimelineEventHandler} to be executed when the {@link InnerEvent} occurs
137                  * @param timing   Point in the MI simulation {@link Timeline}, at which the {@link InnerEvent} is executed;
138                  */
139                 InnerEvent(TimelineEventHandler function, TimelineEvent event, long timing)
140                 {
141                         this.function = function;
142                         this.event = event;
143                         this.timing = timing;
144                 }
145
146                 public long getTiming()
147                 {
148                         return timing;
149                 }
150
151                 public void run()
152                 {
153                         function.handle(event);
154                 }
155
156                 @Override
157                 public String toString()
158                 {
159                         return event.toString();
160                 }
161         }
162
163         @Override
164         public String toString()
165         {
166                 return "simulation time: " + currentTime + ", " + events.toString();
167         }
168
169         public static long toNanoseconds(long ticks)
170         {
171                 return ticks; // TODO: Alter this when it has been determined how ticks should relate to real time.
172         }
173
174         public enum ExecutionResult
175         {
176                 NOTHING_DONE, DONE_IN_TIME, RAN_OUT_OF_TIME
177         }
178 }