1 package era.mi.logic.timeline;
3 import java.util.PriorityQueue;
6 * Orders Events by the time they are due to be executed. Can execute Events individually.
7 * @author Fabian Stemmler
12 private PriorityQueue<InnerEvent> events;
13 private long currentTime = 0;
15 public Timeline(int initCapacity)
17 events = new PriorityQueue<InnerEvent>(initCapacity, (a, b) -> {
18 //Is this really necessary? If only ints are allowed as relative timing, the difference should always be an int
19 long difference = a.getTiming() - b.getTiming();
22 return difference < 0 ? -1 : 1;
26 public boolean hasNext()
28 return !events.isEmpty();
31 public void executeNext()
33 InnerEvent first = events.poll();
34 currentTime = first.getTiming();
38 public long getSimulationTime()
50 * Adds an Event to the {@link Timeline}
51 * @param function The {@link TimelineEventHandler} that will be executed, when the {@link InnerEvent} occurs on the timeline.
52 * @param relativeTiming The amount of MI ticks in which the {@link InnerEvent} is called, starting from the current time.
54 public void addEvent(TimelineEventHandler function, int relativeTiming)
56 long timing = currentTime + relativeTiming;
57 events.add(new InnerEvent(function, new TimelineEvent(timing), timing));
60 private class InnerEvent
63 private final long timing;
64 private final TimelineEventHandler function;
65 private final TimelineEvent event;
68 * Creates an {@link InnerEvent}
69 * @param function {@link TimelineEventHandler} to be executed when the {@link InnerEvent} occurs
70 * @param timing Point in the MI simulation {@link Timeline}, at which the {@link InnerEvent} is executed;
72 InnerEvent(TimelineEventHandler function, TimelineEvent event, long timing)
74 this.function = function;
79 public long getTiming()
86 function.handle(event);