1 package net.sf.openrocket.gui.main;
4 import java.awt.Dialog;
5 import java.awt.Dimension;
6 import java.awt.Window;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
9 import java.awt.event.WindowAdapter;
10 import java.awt.event.WindowEvent;
11 import java.io.CharArrayWriter;
12 import java.io.PrintWriter;
13 import java.util.Iterator;
14 import java.util.List;
15 import java.util.concurrent.ExecutorService;
16 import java.util.concurrent.Executors;
18 import javax.swing.JButton;
19 import javax.swing.JDialog;
20 import javax.swing.JLabel;
21 import javax.swing.JOptionPane;
22 import javax.swing.JPanel;
23 import javax.swing.JProgressBar;
25 import net.miginfocom.swing.MigLayout;
26 import net.sf.openrocket.document.Simulation;
27 import net.sf.openrocket.gui.dialogs.DetailDialog;
28 import net.sf.openrocket.rocketcomponent.Configuration;
29 import net.sf.openrocket.rocketcomponent.MotorMount;
30 import net.sf.openrocket.rocketcomponent.MotorMount.IgnitionEvent;
31 import net.sf.openrocket.simulation.FlightEvent;
32 import net.sf.openrocket.simulation.SimulationStatus;
33 import net.sf.openrocket.simulation.exception.SimulationCancelledException;
34 import net.sf.openrocket.simulation.exception.SimulationException;
35 import net.sf.openrocket.simulation.exception.SimulationLaunchException;
36 import net.sf.openrocket.simulation.listeners.AbstractSimulationListener;
37 import net.sf.openrocket.simulation.listeners.SimulationListener;
38 import net.sf.openrocket.unit.Unit;
39 import net.sf.openrocket.unit.UnitGroup;
40 import net.sf.openrocket.util.GUIUtil;
41 import net.sf.openrocket.util.MathUtil;
42 import net.sf.openrocket.util.Prefs;
45 public class SimulationRunDialog extends JDialog {
46 /** Update the dialog status every this many ms */
47 private static final long UPDATE_MS = 200;
49 /** Flight progress at motor burnout */
50 private static final double BURNOUT_PROGRESS = 0.4;
52 /** Flight progress at apogee */
53 private static final double APOGEE_PROGRESS = 0.7;
57 * The executor service is not static since we want concurrent simulation
58 * dialogs to run in parallel, ie. they both have their own executor service.
60 private final ExecutorService executor = Executors.newFixedThreadPool(
61 Prefs.getMaxThreadCount());
64 private final JLabel simLabel, timeLabel, altLabel, velLabel;
65 private final JProgressBar progressBar;
68 private final Simulation[] simulations;
69 private final SimulationWorker[] simulationWorkers;
70 private final SimulationStatus[] simulationStatuses;
71 private final double[] simulationMaxAltitude;
72 private final double[] simulationMaxVelocity;
73 private final boolean[] simulationDone;
75 public SimulationRunDialog(Window window, Simulation... simulations) {
76 super(window, "Running simulations...", Dialog.ModalityType.DOCUMENT_MODAL);
78 if (simulations.length == 0) {
79 throw new IllegalArgumentException("Called with no simulations to run");
82 this.simulations = simulations;
84 // Initialize the simulations
85 int n = simulations.length;
86 simulationWorkers = new SimulationWorker[n];
87 simulationStatuses = new SimulationStatus[n];
88 simulationMaxAltitude = new double[n];
89 simulationMaxVelocity = new double[n];
90 simulationDone = new boolean[n];
92 for (int i = 0; i < n; i++) {
93 simulationWorkers[i] = new InteractiveSimulationWorker(simulations[i], i);
94 executor.execute(simulationWorkers[i]);
98 JPanel panel = new JPanel(new MigLayout("fill", "[][grow]"));
100 simLabel = new JLabel("Running ...");
101 panel.add(simLabel, "spanx, wrap para");
103 panel.add(new JLabel("Simulation time: "), "gapright para");
104 timeLabel = new JLabel("");
105 panel.add(timeLabel, "growx, wrap rel");
107 panel.add(new JLabel("Altitude: "));
108 altLabel = new JLabel("");
109 panel.add(altLabel, "growx, wrap rel");
111 panel.add(new JLabel("Velocity: "));
112 velLabel = new JLabel("");
113 panel.add(velLabel, "growx, wrap para");
115 progressBar = new JProgressBar();
116 panel.add(progressBar, "spanx, growx, wrap para");
120 JButton cancel = new JButton("Cancel");
121 cancel.addActionListener(new ActionListener() {
123 public void actionPerformed(ActionEvent e) {
127 panel.add(cancel, "spanx, tag cancel");
130 // Cancel simulations when user closes the window
131 this.addWindowListener(new WindowAdapter() {
133 public void windowClosing(WindowEvent e) {
140 this.setMinimumSize(new Dimension(300, 0));
141 this.setLocationByPlatform(true);
145 GUIUtil.setDisposableDialogOptions(this, null);
152 * Cancel the currently running simulations. This is equivalent to clicking
153 * the Cancel button on the dialog.
155 public void cancelSimulations() {
156 executor.shutdownNow();
157 for (SimulationWorker w : simulationWorkers) {
164 * Static helper method to run simulations.
166 * @param parent the parent Window of the dialog to use.
167 * @param simulations the simulations to run.
169 public static void runSimulations(Window parent, Simulation... simulations) {
170 new SimulationRunDialog(parent, simulations).setVisible(true);
176 private void updateProgress() {
177 System.out.println("updateProgress() called");
179 for (index = 0; index < simulations.length; index++) {
180 if (!simulationDone[index])
184 if (index >= simulations.length) {
185 // Everything is done, close the dialog
186 System.out.println("Everything done.");
191 // Update the progress bar status
193 for (SimulationWorker s : simulationWorkers) {
194 progress += s.getProgress();
196 progress /= simulationWorkers.length;
197 progressBar.setValue(progress);
198 System.out.println("Progressbar value " + progress);
200 // Update the simulation fields
201 simLabel.setText("Running " + simulations[index].getName());
202 if (simulationStatuses[index] == null) {
203 timeLabel.setText("");
204 altLabel.setText("");
205 velLabel.setText("");
206 System.out.println("Empty labels, how sad.");
210 Unit u = UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit();
211 timeLabel.setText(u.toStringUnit(simulationStatuses[index].getSimulationTime()));
213 u = UnitGroup.UNITS_DISTANCE.getDefaultUnit();
214 altLabel.setText(u.toStringUnit(simulationStatuses[index].getRocketPosition().z) + " (max. " +
215 u.toStringUnit(simulationMaxAltitude[index]) + ")");
217 u = UnitGroup.UNITS_VELOCITY.getDefaultUnit();
218 velLabel.setText(u.toStringUnit(simulationStatuses[index].getRocketVelocity().z) + " (max. " +
219 u.toStringUnit(simulationMaxVelocity[index]) + ")");
220 System.out.println("Set interesting labels.");
226 * A SwingWorker that performs a flight simulation. It periodically updates the
227 * simulation statuses of the parent class and calls updateProgress().
228 * The progress of the simulation is stored in the progress property of the
231 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
233 private class InteractiveSimulationWorker extends SimulationWorker {
235 private final int index;
236 private final double burnoutTimeEstimate;
237 private volatile double burnoutVelocity;
238 private volatile double apogeeAltitude;
241 * -2 = time from 0 ... burnoutTimeEstimate
242 * -1 = velocity from v(burnoutTimeEstimate) ... 0
243 * 0 ... n = stages from alt(max) ... 0
245 private volatile int simulationStage = -2;
247 private int progress = 0;
250 public InteractiveSimulationWorker(Simulation sim, int index) {
254 // Calculate estimate of motor burn time
255 double launchBurn = 0;
256 double otherBurn = 0;
257 Configuration config = simulation.getConfiguration();
258 String id = simulation.getConditions().getMotorConfigurationID();
259 Iterator<MotorMount> iterator = config.motorIterator();
260 while (iterator.hasNext()) {
261 MotorMount m = iterator.next();
262 if (m.getIgnitionEvent() == IgnitionEvent.LAUNCH)
263 launchBurn = MathUtil.max(launchBurn, m.getMotor(id).getBurnTimeEstimate());
265 otherBurn = otherBurn + m.getMotor(id).getBurnTimeEstimate();
267 burnoutTimeEstimate = Math.max(launchBurn + otherBurn, 0.1);
273 * Return the extra listeners to use, a progress listener and cancel listener.
276 protected SimulationListener[] getExtraListeners() {
277 return new SimulationListener[] { new SimulationProgressListener() };
282 * Processes simulation statuses published by the simulation listener.
283 * The statuses of the parent class and the progress property are updated.
286 protected void process(List<SimulationStatus> chunks) {
288 // Update max. altitude and velocity
289 for (SimulationStatus s : chunks) {
290 simulationMaxAltitude[index] = Math.max(simulationMaxAltitude[index],
291 s.getRocketPosition().z);
292 simulationMaxVelocity[index] = Math.max(simulationMaxVelocity[index],
293 s.getRocketVelocity().length());
296 // Calculate the progress
297 SimulationStatus status = chunks.get(chunks.size() - 1);
298 simulationStatuses[index] = status;
300 // 1. time = 0 ... burnoutTimeEstimate
301 if (simulationStage == -2 && status.getSimulationTime() < burnoutTimeEstimate) {
302 System.out.println("Method 1: t=" + status.getSimulationTime() + " est=" + burnoutTimeEstimate);
303 setSimulationProgress(MathUtil.map(status.getSimulationTime(), 0, burnoutTimeEstimate,
304 0.0, BURNOUT_PROGRESS));
309 if (simulationStage == -2) {
311 burnoutVelocity = MathUtil.max(status.getRocketVelocity().z, 0.1);
312 System.out.println("CHANGING to Method 2, vel=" + burnoutVelocity);
315 // 2. z-velocity from burnout velocity to zero
316 if (simulationStage == -1 && status.getRocketVelocity().z >= 0) {
317 System.out.println("Method 2: vel=" + status.getRocketVelocity().z + " burnout=" +
319 setSimulationProgress(MathUtil.map(status.getRocketVelocity().z, burnoutVelocity, 0,
320 BURNOUT_PROGRESS, APOGEE_PROGRESS));
325 if (simulationStage == -1 && status.getRocketVelocity().z < 0) {
327 apogeeAltitude = MathUtil.max(status.getRocketPosition().z, 1);
330 // 3. z-position from apogee to zero
331 // TODO: MEDIUM: several stages
332 System.out.println("Method 3: alt=" + status.getRocketPosition().z + " apogee=" + apogeeAltitude);
333 setSimulationProgress(MathUtil.map(status.getRocketPosition().z,
334 apogeeAltitude, 0, APOGEE_PROGRESS, 1.0));
339 * Marks this simulation as done and calls the progress update.
342 protected void simulationDone() {
343 simulationDone[index] = true;
344 System.out.println("DONE, setting progress");
345 setSimulationProgress(1.0);
351 * Marks the simulation as done and shows a dialog presenting
352 * the error, unless the simulation was cancelled.
355 protected void simulationInterrupted(Throwable t) {
357 if (t instanceof SimulationCancelledException) {
359 return; // Ignore cancellations
362 // Retrieve the stack trace in a textual form
363 CharArrayWriter arrayWriter = new CharArrayWriter();
364 arrayWriter.append(t.toString() + "\n" + "\n");
365 t.printStackTrace(new PrintWriter(arrayWriter));
366 String stackTrace = arrayWriter.toString();
368 // Analyze the exception type
369 if (t instanceof SimulationLaunchException) {
371 DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this,
373 "Unable to simulate:",
376 null, simulation.getName(), JOptionPane.ERROR_MESSAGE);
378 } else if (t instanceof SimulationException) {
380 DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this,
382 "A error occurred during the simulation:",
385 stackTrace, simulation.getName(), JOptionPane.ERROR_MESSAGE);
387 } else if (t instanceof Exception) {
389 // TODO: MEDIUM: Check the exception handling here...
391 DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this,
393 "An exception occurred during the simulation:",
395 simulation.getSimulationListeners().isEmpty() ?
396 "Please report this as a bug along with the details below." : ""
398 stackTrace, simulation.getName(), JOptionPane.ERROR_MESSAGE);
400 } else if (t instanceof AssertionError) {
403 DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this,
405 "A computation error occurred during the simulation.",
406 "Please report this as a bug along with the details below."
408 stackTrace, simulation.getName(), JOptionPane.ERROR_MESSAGE);
413 DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this,
415 "An unknown error was encountered during the simulation.",
416 "The program may be unstable, you should save all your designs " +
417 "and restart OpenRocket now!"
419 stackTrace, simulation.getName(), JOptionPane.ERROR_MESSAGE);
427 private void setSimulationProgress(double p) {
428 progress = Math.max(progress, (int) (100 * p + 0.5));
429 progress = MathUtil.clamp(progress, 0, 100);
430 System.out.println("Setting progress to " + progress + " (real " +
431 ((int) (100 * p + 0.5)) + ")");
432 super.setProgress(progress);
437 * A simulation listener that regularly updates the progress property of the
438 * SimulationWorker and publishes the simulation status for the run dialog to process.
440 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
442 private class SimulationProgressListener extends AbstractSimulationListener {
443 private long time = 0;
446 public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) {
447 switch (event.getType()) {
450 apogeeAltitude = status.getRocketPosition().z;
451 System.out.println("APOGEE, setting progress");
452 setSimulationProgress(APOGEE_PROGRESS);
461 System.out.println("END, setting progress");
462 setSimulationProgress(1.0);
469 public void postStep(SimulationStatus status) {
470 if (System.currentTimeMillis() >= time + UPDATE_MS) {
471 time = System.currentTimeMillis();