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 InnerEvent first = events.peek();
98 while (hasNext() && !condition.getAsBoolean())
101 lastTimeUpdated = first.getTiming();
103 // Don't check after every run
104 checkStop = (checkStop + 1) % 10;
105 if (checkStop == 0 && System.currentTimeMillis() >= stopMillis)
106 return ExecutionResult.EXEC_OUT_OF_TIME;
107 first = events.peek();
109 lastTimeUpdated = getSimulationTime();
110 return hasNext() ? ExecutionResult.EXEC_UNTIL_EMPTY : ExecutionResult.EXEC_UNTIL_CONDITION;
114 * Sets the function, which defines the current simulation time at any time.
116 * @param time The return value of calling this function is the current simulation time.
118 public void setTimeFunction(LongSupplier time)
124 * Calculates the current simulation time.
126 * @return The simulation time as defined by the time function.
128 public long getSimulationTime()
130 return time.getAsLong();
134 * Retrieves the timestamp of the next event.
136 * @return The timestamp of the next enqueued event, if the {@link Timeline} is not empty, -1 otherwise.
138 public long nextEventTime()
142 return events.peek().getTiming();
146 * Clears the {@link Timeline} of enqueued events.
155 * Adds a listener, that is called when a {@link TimelineEvent} is added.
157 public void addEventAddedListener(Consumer<TimelineEvent> listener)
159 eventAddedListener.add(listener);
163 * Removes the listener, if possible. It will no longer be called when a {@link TimelineEvent} is added.
165 public void removeEventAddedListener(Consumer<TimelineEvent> listener)
167 eventAddedListener.remove(listener);
171 * Adds an Event to the {@link Timeline}
173 * @param function The {@link TimelineEventHandler} that will be executed, when the {@link InnerEvent} occurs on the timeline.
174 * @param relativeTiming The amount of MI ticks in which the {@link InnerEvent} is called, starting from the current time.
176 public void addEvent(TimelineEventHandler function, int relativeTiming)
178 long timing = getSimulationTime() + relativeTiming;
179 TimelineEvent event = new TimelineEvent(timing);
180 events.add(new InnerEvent(function, event, eventCounter++));
181 eventAddedListener.forEach(l -> l.accept(event));
184 private class InnerEvent implements Runnable, Comparable<InnerEvent>
186 private final TimelineEventHandler function;
187 private final TimelineEvent event;
188 private final long id;
191 * Creates an {@link InnerEvent}
193 * @param function {@link TimelineEventHandler} to be executed when the {@link InnerEvent} occurs
194 * @param timing Point in the MI simulation {@link Timeline}, at which the {@link InnerEvent} is executed;
196 InnerEvent(TimelineEventHandler function, TimelineEvent event, long id)
198 this.function = function;
203 public long getTiming()
205 return event.getTiming();
211 function.handle(event);
215 public String toString()
217 return event.toString();
221 public int compareTo(InnerEvent o)
224 return (c1 = timeCmp(getTiming(), o.getTiming())) == 0 ? timeCmp(id, o.id) : c1;
228 public static int timeCmp(long a, long b)
230 return Long.signum(a - b);
234 public String toString()
236 return String.format("Simulation time: %s, Last update: %d, Events: %s", getSimulationTime(), lastTimeUpdated, events.toString());
239 public enum ExecutionResult
241 NOTHING_DONE, EXEC_UNTIL_EMPTY, EXEC_UNTIL_CONDITION, EXEC_OUT_OF_TIME