63d739500d125c2edf9c4525ffcc2f0db26dbb88
[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                 else
94                         return events.peek().timing;
95         }
96
97         public void reset()
98         {
99                 events.clear();
100                 currentTime = 0;
101         }
102
103         public void addEventAddedListener(Consumer<TimelineEvent> listener)
104         {
105                 eventAddedListener.add(listener);
106         }
107
108         public void removeEventAddedListener(Consumer<TimelineEvent> listener)
109         {
110                 eventAddedListener.remove(listener);
111         }
112
113         /**
114          * Adds an Event to the {@link Timeline}
115          * 
116          * @param function       The {@link TimelineEventHandler} that will be executed, when the {@link InnerEvent} occurs on the timeline.
117          * @param relativeTiming The amount of MI ticks in which the {@link InnerEvent} is called, starting from the current time.
118          */
119         public void addEvent(TimelineEventHandler function, int relativeTiming)
120         {
121                 long timing = currentTime + relativeTiming;
122                 TimelineEvent event = new TimelineEvent(timing);
123                 events.add(new InnerEvent(function, event, timing));
124                 eventAddedListener.forEach(l -> l.accept(event));
125         }
126
127         private class InnerEvent
128         {
129
130                 private final long timing;
131                 private final TimelineEventHandler function;
132                 private final TimelineEvent event;
133
134                 /**
135                  * Creates an {@link InnerEvent}
136                  * 
137                  * @param function {@link TimelineEventHandler} to be executed when the {@link InnerEvent} occurs
138                  * @param timing   Point in the MI simulation {@link Timeline}, at which the {@link InnerEvent} is executed;
139                  */
140                 InnerEvent(TimelineEventHandler function, TimelineEvent event, long timing)
141                 {
142                         this.function = function;
143                         this.event = event;
144                         this.timing = timing;
145                 }
146
147                 public long getTiming()
148                 {
149                         return timing;
150                 }
151
152                 public void run()
153                 {
154                         function.handle(event);
155                 }
156
157                 @Override
158                 public String toString()
159                 {
160                         return event.toString();
161                 }
162         }
163
164         @Override
165         public String toString()
166         {
167                 return "simulation time: " + currentTime + ", " + events.toString();
168         }
169
170         public static long toNanoseconds(long ticks)
171         {
172                 return ticks; // TODO: Alter this when it has been determined how ticks should relate to real time.
173         }
174
175         public enum ExecutionResult
176         {
177                 NOTHING_DONE, DONE_IN_TIME, RAN_OUT_OF_TIME
178         }
179 }