1 package net.mograsim.logic.core.timeline;
3 import java.util.ArrayList;
5 import java.util.PriorityQueue;
6 import java.util.function.BooleanSupplier;
7 import java.util.function.Consumer;
8 import java.util.function.LongSupplier;
11 * Orders Events by the time they are due to be executed. Can execute Events individually.
13 * @author Fabian Stemmler
18 private PriorityQueue<InnerEvent> events;
19 private LongSupplier time;
20 private long lastTimeUpdated = 0;
21 private long eventCounter = 0;
23 private final List<Consumer<TimelineEvent>> eventAddedListener;
25 public final LongSupplier stepByStepExec = () -> lastTimeUpdated;
26 public final LongSupplier realTimeExec = () -> System.currentTimeMillis();
29 * Constructs a Timeline object. Per default the time function is set to step by step execution.
31 * @param initCapacity The initial capacity of the event queue.
33 public Timeline(int initCapacity)
35 events = new PriorityQueue<>(initCapacity);
36 eventAddedListener = new ArrayList<>();
37 time = stepByStepExec;
41 * @param timestamp exclusive
42 * @return <code>true</code> if the first event in queue is later than the given timestamp
44 public BooleanSupplier laterThan(long timestamp)
46 return () -> timeCmp(events.peek().getTiming(), timestamp) > 0;
50 * @return <code>true</code> if there is at least one event enqueued. <code>false</code> otherwise
52 public boolean hasNext()
54 return !events.isEmpty();
58 * Executes all events at the next timestamp, at which there are any
60 public void executeNext()
62 InnerEvent first = events.peek();
64 executeUntil(laterThan(first.getTiming()), -1);
68 * Executes all events enqueued in the {@link Timeline}. Use very carefully! Events may generate new events, causing an infinite loop.
70 public void executeAll()
77 * Executes all events until a given condition is met. The simulation process can be constrained by a real world timestamp.
79 * @param condition the condition until which the events are be processed
80 * @param stopMillis the System.currentTimeMillis() when simulation definitely needs to stop. A value of -1 means no timeout.
81 * @return State of the event execution
83 * <code>NOTHING_DONE</code> if the {@link Timeline} was already empty
84 * <code>EXEC_OUT_OF_TIME</code> if the given maximum time was reached
85 * <code>EXEC_UNTIL_CONDITION</code> if the condition was met
86 * <code>EXEC_UNTIL_EMPTY</code> if events were executed until the {@link Timeline} was empty
89 public ExecutionResult executeUntil(BooleanSupplier condition, long stopMillis)
93 lastTimeUpdated = getSimulationTime();
94 return ExecutionResult.NOTHING_DONE;
97 while (hasNext() && !condition.getAsBoolean())
100 synchronized (events)
102 event = events.remove();
104 lastTimeUpdated = event.getTiming();
106 // Don't check after every run
107 checkStop = (checkStop + 1) % 10;
108 if (checkStop == 0 && System.currentTimeMillis() >= stopMillis)
109 return ExecutionResult.EXEC_OUT_OF_TIME;
111 lastTimeUpdated = getSimulationTime();
112 return hasNext() ? ExecutionResult.EXEC_UNTIL_EMPTY : ExecutionResult.EXEC_UNTIL_CONDITION;
116 * Sets the function, which defines the current simulation time at any time.
118 * @param time The return value of calling this function is the current simulation time.
120 public void setTimeFunction(LongSupplier time)
126 * Calculates the current simulation time.
128 * @return The simulation time as defined by the time function.
130 public long getSimulationTime()
132 return time.getAsLong();
136 * Retrieves the timestamp of the next event.
138 * @return The timestamp of the next enqueued event, if the {@link Timeline} is not empty, -1 otherwise.
140 public long nextEventTime()
144 return events.peek().getTiming();
148 * Clears the {@link Timeline} of enqueued events.
152 synchronized (events)
160 * Adds a listener, that is called when a {@link TimelineEvent} is added.
162 public void addEventAddedListener(Consumer<TimelineEvent> listener)
164 eventAddedListener.add(listener);
168 * Removes the listener, if possible. It will no longer be called when a {@link TimelineEvent} is added.
170 public void removeEventAddedListener(Consumer<TimelineEvent> listener)
172 eventAddedListener.remove(listener);
176 * Adds an Event to the {@link Timeline}
178 * @param function The {@link TimelineEventHandler} that will be executed, when the {@link InnerEvent} occurs on the timeline.
179 * @param relativeTiming The amount of MI ticks in which the {@link InnerEvent} is called, starting from the current time.
181 public void addEvent(TimelineEventHandler function, int relativeTiming)
183 long timing = getSimulationTime() + relativeTiming;
184 TimelineEvent event = new TimelineEvent(timing);
185 synchronized (events)
187 events.add(new InnerEvent(function, event, eventCounter++));
189 eventAddedListener.forEach(l -> l.accept(event));
192 private class InnerEvent implements Runnable, Comparable<InnerEvent>
194 private final TimelineEventHandler function;
195 private final TimelineEvent event;
196 private final long id;
199 * Creates an {@link InnerEvent}
201 * @param function {@link TimelineEventHandler} to be executed when the {@link InnerEvent} occurs
202 * @param timing Point in the MI simulation {@link Timeline}, at which the {@link InnerEvent} is executed;
204 InnerEvent(TimelineEventHandler function, TimelineEvent event, long id)
206 this.function = function;
211 public long getTiming()
213 return event.getTiming();
219 function.handle(event);
223 public String toString()
225 return event.toString();
229 public int compareTo(InnerEvent o)
232 return (c1 = timeCmp(getTiming(), o.getTiming())) == 0 ? timeCmp(id, o.id) : c1;
236 public static int timeCmp(long a, long b)
238 return Long.signum(a - b);
242 public String toString()
245 synchronized (events)
247 eventsString = events.toString();
249 return String.format("Simulation time: %s, Last update: %d, Events: %s", getSimulationTime(), lastTimeUpdated, eventsString);
252 public enum ExecutionResult
254 NOTHING_DONE, EXEC_UNTIL_EMPTY, EXEC_UNTIL_CONDITION, EXEC_OUT_OF_TIME