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.l10n.Translator;
29 import net.sf.openrocket.logging.LogHelper;
30 import net.sf.openrocket.rocketcomponent.Configuration;
31 import net.sf.openrocket.rocketcomponent.MotorMount;
32 import net.sf.openrocket.rocketcomponent.MotorMount.IgnitionEvent;
33 import net.sf.openrocket.simulation.FlightEvent;
34 import net.sf.openrocket.simulation.SimulationStatus;
35 import net.sf.openrocket.simulation.exception.SimulationCancelledException;
36 import net.sf.openrocket.simulation.exception.SimulationException;
37 import net.sf.openrocket.simulation.exception.SimulationLaunchException;
38 import net.sf.openrocket.simulation.listeners.AbstractSimulationListener;
39 import net.sf.openrocket.simulation.listeners.SimulationListener;
40 import net.sf.openrocket.startup.Application;
41 import net.sf.openrocket.unit.Unit;
42 import net.sf.openrocket.unit.UnitGroup;
43 import net.sf.openrocket.util.GUIUtil;
44 import net.sf.openrocket.util.MathUtil;
45 import net.sf.openrocket.util.Prefs;
48 public class SimulationRunDialog extends JDialog {
49 private static final LogHelper log = Application.getLogger();
50 private static final Translator trans = Application.getTranslator();
53 /** Update the dialog status every this many ms */
54 private static final long UPDATE_MS = 200;
56 /** Flight progress at motor burnout */
57 private static final double BURNOUT_PROGRESS = 0.4;
59 /** Flight progress at apogee */
60 private static final double APOGEE_PROGRESS = 0.7;
64 * The executor service is not static since we want concurrent simulation
65 * dialogs to run in parallel, ie. they both have their own executor service.
67 private final ExecutorService executor = Executors.newFixedThreadPool(
68 Prefs.getMaxThreadCount());
71 private final JLabel simLabel, timeLabel, altLabel, velLabel;
72 private final JProgressBar progressBar;
76 * NOTE: Care must be used when accessing the simulation parameters, since they
77 * are being run in another thread. Mutexes are used to avoid concurrent usage, which
78 * will result in an exception being thrown!
80 private final Simulation[] simulations;
81 private final String[] simulationNames;
82 private final SimulationWorker[] simulationWorkers;
83 private final SimulationStatus[] simulationStatuses;
84 private final double[] simulationMaxAltitude;
85 private final double[] simulationMaxVelocity;
86 private final boolean[] simulationDone;
88 public SimulationRunDialog(Window window, Simulation... simulations) {
89 //// Running simulations...
90 super(window, trans.get("SimuRunDlg.title.RunSim"), Dialog.ModalityType.DOCUMENT_MODAL);
92 if (simulations.length == 0) {
93 throw new IllegalArgumentException("Called with no simulations to run");
96 this.simulations = simulations;
98 // Initialize the simulations
99 int n = simulations.length;
100 simulationNames = new String[n];
101 simulationWorkers = new SimulationWorker[n];
102 simulationStatuses = new SimulationStatus[n];
103 simulationMaxAltitude = new double[n];
104 simulationMaxVelocity = new double[n];
105 simulationDone = new boolean[n];
107 for (int i = 0; i < n; i++) {
108 simulationNames[i] = simulations[i].getName();
109 simulationWorkers[i] = new InteractiveSimulationWorker(simulations[i], i);
110 executor.execute(simulationWorkers[i]);
114 JPanel panel = new JPanel(new MigLayout("fill", "[][grow]"));
117 simLabel = new JLabel(trans.get("SimuRunDlg.lbl.Running"));
118 panel.add(simLabel, "spanx, wrap para");
119 //// Simulation time:
120 panel.add(new JLabel(trans.get("SimuRunDlg.lbl.Simutime") + " "), "gapright para");
121 timeLabel = new JLabel("");
122 panel.add(timeLabel, "growx, wrap rel");
125 panel.add(new JLabel(trans.get("SimuRunDlg.lbl.Altitude") + " "));
126 altLabel = new JLabel("");
127 panel.add(altLabel, "growx, wrap rel");
130 panel.add(new JLabel(trans.get("SimuRunDlg.lbl.Velocity") +" "));
131 velLabel = new JLabel("");
132 panel.add(velLabel, "growx, wrap para");
134 progressBar = new JProgressBar();
135 panel.add(progressBar, "spanx, growx, wrap para");
139 JButton cancel = new JButton(trans.get("dlg.but.cancel"));
140 cancel.addActionListener(new ActionListener() {
142 public void actionPerformed(ActionEvent e) {
146 panel.add(cancel, "spanx, tag cancel");
149 // Cancel simulations when user closes the window
150 this.addWindowListener(new WindowAdapter() {
152 public void windowClosing(WindowEvent e) {
159 this.setMinimumSize(new Dimension(300, 0));
160 this.setLocationByPlatform(true);
164 GUIUtil.setDisposableDialogOptions(this, null);
171 * Cancel the currently running simulations. This is equivalent to clicking
172 * the Cancel button on the dialog.
174 public void cancelSimulations() {
175 executor.shutdownNow();
176 for (SimulationWorker w : simulationWorkers) {
183 * Static helper method to run simulations.
185 * @param parent the parent Window of the dialog to use.
186 * @param simulations the simulations to run.
188 public static void runSimulations(Window parent, Simulation... simulations) {
189 new SimulationRunDialog(parent, simulations).setVisible(true);
195 private void updateProgress() {
197 for (index = 0; index < simulations.length; index++) {
198 if (!simulationDone[index])
202 if (index >= simulations.length) {
203 // Everything is done, close the dialog
204 log.debug("Everything done.");
209 // Update the progress bar status
211 for (SimulationWorker s : simulationWorkers) {
212 progress += s.getProgress();
214 progress /= simulationWorkers.length;
215 progressBar.setValue(progress);
216 log.debug("Progressbar value " + progress);
218 // Update the simulation fields
219 simLabel.setText("Running " + simulationNames[index]);
220 if (simulationStatuses[index] == null) {
221 log.debug("No simulation status data available, setting empty labels");
222 timeLabel.setText("");
223 altLabel.setText("");
224 velLabel.setText("");
228 Unit u = UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit();
229 timeLabel.setText(u.toStringUnit(simulationStatuses[index].getSimulationTime()));
231 u = UnitGroup.UNITS_DISTANCE.getDefaultUnit();
232 altLabel.setText(u.toStringUnit(simulationStatuses[index].getRocketPosition().z) + " (max. " +
233 u.toStringUnit(simulationMaxAltitude[index]) + ")");
235 u = UnitGroup.UNITS_VELOCITY.getDefaultUnit();
236 velLabel.setText(u.toStringUnit(simulationStatuses[index].getRocketVelocity().z) + " (max. " +
237 u.toStringUnit(simulationMaxVelocity[index]) + ")");
243 * A SwingWorker that performs a flight simulation. It periodically updates the
244 * simulation statuses of the parent class and calls updateProgress().
245 * The progress of the simulation is stored in the progress property of the
248 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
250 private class InteractiveSimulationWorker extends SimulationWorker {
252 private final int index;
253 private final double burnoutTimeEstimate;
254 private volatile double burnoutVelocity;
255 private volatile double apogeeAltitude;
258 * -2 = time from 0 ... burnoutTimeEstimate
259 * -1 = velocity from v(burnoutTimeEstimate) ... 0
260 * 0 ... n = stages from alt(max) ... 0
262 private volatile int simulationStage = -2;
264 private int progress = 0;
267 public InteractiveSimulationWorker(Simulation sim, int index) {
271 // Calculate estimate of motor burn time
272 double launchBurn = 0;
273 double otherBurn = 0;
274 Configuration config = simulation.getConfiguration();
275 String id = simulation.getConditions().getMotorConfigurationID();
276 Iterator<MotorMount> iterator = config.motorIterator();
277 while (iterator.hasNext()) {
278 MotorMount m = iterator.next();
279 if (m.getIgnitionEvent() == IgnitionEvent.LAUNCH)
280 launchBurn = MathUtil.max(launchBurn, m.getMotor(id).getBurnTimeEstimate());
282 otherBurn = otherBurn + m.getMotor(id).getBurnTimeEstimate();
284 burnoutTimeEstimate = Math.max(launchBurn + otherBurn, 0.1);
290 * Return the extra listeners to use, a progress listener and cancel listener.
293 protected SimulationListener[] getExtraListeners() {
294 return new SimulationListener[] { new SimulationProgressListener() };
299 * Processes simulation statuses published by the simulation listener.
300 * The statuses of the parent class and the progress property are updated.
303 protected void process(List<SimulationStatus> chunks) {
305 // Update max. altitude and velocity
306 for (SimulationStatus s : chunks) {
307 simulationMaxAltitude[index] = Math.max(simulationMaxAltitude[index],
308 s.getRocketPosition().z);
309 simulationMaxVelocity[index] = Math.max(simulationMaxVelocity[index],
310 s.getRocketVelocity().length());
313 // Calculate the progress
314 SimulationStatus status = chunks.get(chunks.size() - 1);
315 simulationStatuses[index] = status;
317 // 1. time = 0 ... burnoutTimeEstimate
318 if (simulationStage == -2 && status.getSimulationTime() < burnoutTimeEstimate) {
319 log.debug("Method 1: t=" + status.getSimulationTime() + " est=" + burnoutTimeEstimate);
320 setSimulationProgress(MathUtil.map(status.getSimulationTime(), 0, burnoutTimeEstimate,
321 0.0, BURNOUT_PROGRESS));
326 if (simulationStage == -2) {
328 burnoutVelocity = MathUtil.max(status.getRocketVelocity().z, 0.1);
329 log.debug("CHANGING to Method 2, vel=" + burnoutVelocity);
332 // 2. z-velocity from burnout velocity to zero
333 if (simulationStage == -1 && status.getRocketVelocity().z >= 0) {
334 log.debug("Method 2: vel=" + status.getRocketVelocity().z + " burnout=" + burnoutVelocity);
335 setSimulationProgress(MathUtil.map(status.getRocketVelocity().z, burnoutVelocity, 0,
336 BURNOUT_PROGRESS, APOGEE_PROGRESS));
341 if (simulationStage == -1 && status.getRocketVelocity().z < 0) {
343 apogeeAltitude = MathUtil.max(status.getRocketPosition().z, 1);
344 log.debug("CHANGING to Method 3, apogee=" + apogeeAltitude);
347 // 3. z-position from apogee to zero
348 // TODO: MEDIUM: several stages
349 log.debug("Method 3: alt=" + status.getRocketPosition().z + " apogee=" + apogeeAltitude);
350 setSimulationProgress(MathUtil.map(status.getRocketPosition().z,
351 apogeeAltitude, 0, APOGEE_PROGRESS, 1.0));
356 * Marks this simulation as done and calls the progress update.
359 protected void simulationDone() {
360 simulationDone[index] = true;
361 log.debug("Simulation done");
362 setSimulationProgress(1.0);
368 * Marks the simulation as done and shows a dialog presenting
369 * the error, unless the simulation was cancelled.
372 protected void simulationInterrupted(Throwable t) {
374 if (t instanceof SimulationCancelledException) {
376 return; // Ignore cancellations
379 // Retrieve the stack trace in a textual form
380 CharArrayWriter arrayWriter = new CharArrayWriter();
381 arrayWriter.append(t.toString() + "\n" + "\n");
382 t.printStackTrace(new PrintWriter(arrayWriter));
383 String stackTrace = arrayWriter.toString();
385 // Analyze the exception type
386 if (t instanceof SimulationLaunchException) {
388 DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this,
390 //// Unable to simulate:
391 trans.get("SimuRunDlg.msg.Unabletosim"),
394 null, simulation.getName(), JOptionPane.ERROR_MESSAGE);
396 } else if (t instanceof SimulationException) {
398 DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this,
400 //// A error occurred during the simulation:
401 trans.get("SimuRunDlg.msg.errorOccurred"),
404 stackTrace, simulation.getName(), JOptionPane.ERROR_MESSAGE);
406 } else if (t instanceof Exception) {
408 // TODO: MEDIUM: Check the exception handling here...
410 DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this,
412 //// An exception occurred during the simulation:
413 trans.get("SimuRunDlg.msg.AnException1"),
415 simulation.getSimulationListeners().isEmpty() ?
416 trans.get("SimuRunDlg.msg.AnException2") : ""
418 stackTrace, simulation.getName(), JOptionPane.ERROR_MESSAGE);
420 } else if (t instanceof AssertionError) {
423 DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this,
425 //// A computation error occurred during the simulation.
426 trans.get("SimuRunDlg.msg.AssertionError1"),
427 //// Please report this as a bug along with the details below.
428 trans.get("SimuRunDlg.msg.AssertionError2")
430 stackTrace, simulation.getName(), JOptionPane.ERROR_MESSAGE);
435 DetailDialog.showDetailedMessageDialog(SimulationRunDialog.this,
437 //// An unknown error was encountered during the simulation.
438 trans.get("SimuRunDlg.msg.unknownerror1"),
439 //// The program may be unstable, you should save all your designs and restart OpenRocket now!
440 trans.get("SimuRunDlg.msg.unknownerror2")
442 stackTrace, simulation.getName(), JOptionPane.ERROR_MESSAGE);
450 private void setSimulationProgress(double p) {
451 int exact = Math.max(progress, (int) (100 * p + 0.5));
452 progress = MathUtil.clamp(exact, 0, 100);
453 log.debug("Setting progress to " + progress + " (real " + exact + ")");
454 super.setProgress(progress);
459 * A simulation listener that regularly updates the progress property of the
460 * SimulationWorker and publishes the simulation status for the run dialog to process.
462 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
464 private class SimulationProgressListener extends AbstractSimulationListener {
465 private long time = 0;
468 public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) {
469 switch (event.getType()) {
472 apogeeAltitude = status.getRocketPosition().z;
473 log.debug("APOGEE, setting progress");
474 setSimulationProgress(APOGEE_PROGRESS);
483 log.debug("END, setting progress");
484 setSimulationProgress(1.0);
491 public void postStep(SimulationStatus status) {
492 if (System.currentTimeMillis() >= time + UPDATE_MS) {
493 time = System.currentTimeMillis();