I18 changes
[debian/openrocket] / src / net / sf / openrocket / gui / main / SimulationEditDialog.java
1 package net.sf.openrocket.gui.main;
2
3
4 import java.awt.Color;
5 import java.awt.Component;
6 import java.awt.Window;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
9 import java.util.Arrays;
10 import java.util.List;
11
12 import javax.swing.AbstractListModel;
13 import javax.swing.BorderFactory;
14 import javax.swing.JButton;
15 import javax.swing.JCheckBox;
16 import javax.swing.JComboBox;
17 import javax.swing.JDialog;
18 import javax.swing.JLabel;
19 import javax.swing.JList;
20 import javax.swing.JOptionPane;
21 import javax.swing.JPanel;
22 import javax.swing.JScrollPane;
23 import javax.swing.JSpinner;
24 import javax.swing.JTabbedPane;
25 import javax.swing.JTextField;
26 import javax.swing.ListCellRenderer;
27 import javax.swing.event.ChangeEvent;
28 import javax.swing.event.ChangeListener;
29 import javax.swing.event.DocumentEvent;
30 import javax.swing.event.DocumentListener;
31
32 import net.miginfocom.swing.MigLayout;
33 import net.sf.openrocket.document.Simulation;
34 import net.sf.openrocket.gui.SpinnerEditor;
35 import net.sf.openrocket.gui.adaptors.BooleanModel;
36 import net.sf.openrocket.gui.adaptors.DoubleModel;
37 import net.sf.openrocket.gui.adaptors.MotorConfigurationModel;
38 import net.sf.openrocket.gui.components.BasicSlider;
39 import net.sf.openrocket.gui.components.DescriptionArea;
40 import net.sf.openrocket.gui.components.SimulationExportPanel;
41 import net.sf.openrocket.gui.components.UnitSelector;
42 import net.sf.openrocket.gui.plot.Axis;
43 import net.sf.openrocket.gui.plot.PlotConfiguration;
44 import net.sf.openrocket.gui.plot.SimulationPlotPanel;
45 import net.sf.openrocket.l10n.Translator;
46 import net.sf.openrocket.models.atmosphere.ExtendedISAModel;
47 import net.sf.openrocket.rocketcomponent.Configuration;
48 import net.sf.openrocket.simulation.FlightData;
49 import net.sf.openrocket.simulation.FlightDataBranch;
50 import net.sf.openrocket.simulation.RK4SimulationStepper;
51 import net.sf.openrocket.simulation.GUISimulationConditions;
52 import net.sf.openrocket.simulation.FlightDataType;
53 import net.sf.openrocket.simulation.listeners.SimulationListener;
54 import net.sf.openrocket.simulation.listeners.example.CSVSaveListener;
55 import net.sf.openrocket.startup.Application;
56 import net.sf.openrocket.unit.Unit;
57 import net.sf.openrocket.unit.UnitGroup;
58 import net.sf.openrocket.util.Chars;
59 import net.sf.openrocket.util.GUIUtil;
60 import net.sf.openrocket.util.Icons;
61 import net.sf.openrocket.util.Prefs;
62
63 import org.jfree.chart.ChartFactory;
64 import org.jfree.chart.ChartPanel;
65 import org.jfree.chart.JFreeChart;
66 import org.jfree.chart.axis.NumberAxis;
67 import org.jfree.chart.plot.PlotOrientation;
68 import org.jfree.chart.plot.ValueMarker;
69 import org.jfree.chart.plot.XYPlot;
70 import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
71 import org.jfree.data.xy.XYSeries;
72 import org.jfree.data.xy.XYSeriesCollection;
73
74
75 public class SimulationEditDialog extends JDialog {
76
77         public static final int DEFAULT = -1;
78         public static final int EDIT = 1;
79         public static final int PLOT = 2;
80         
81         
82         private final Window parentWindow;
83         private final Simulation simulation;
84         private final GUISimulationConditions conditions;
85         private final Configuration configuration;
86         private static final Translator trans = Application.getTranslator();
87
88         
89         public SimulationEditDialog(Window parent, Simulation s) {
90                 this(parent, s, 0);
91         }       
92         
93         public SimulationEditDialog(Window parent, Simulation s, int tab) {
94                 //// Edit simulation
95                 super(parent, trans.get("simedtdlg.title.Editsim"), JDialog.ModalityType.DOCUMENT_MODAL);
96                 
97                 this.parentWindow = parent;
98                 this.simulation = s;
99                 this.conditions = simulation.getConditions();
100                 configuration = simulation.getConfiguration();
101                 
102                 JPanel mainPanel = new JPanel(new MigLayout("fill","[grow, fill]"));
103                 
104                 //// Simulation name:
105                 mainPanel.add(new JLabel(trans.get("simedtdlg.lbl.Simname") + " "), "span, split 2, shrink");
106                 final JTextField field = new JTextField(simulation.getName());
107                 field.getDocument().addDocumentListener(new DocumentListener() {
108                         @Override
109                         public void changedUpdate(DocumentEvent e) {
110                                 setText();
111                         }
112                         @Override
113                         public void insertUpdate(DocumentEvent e) {
114                                 setText();
115                         }
116                         @Override
117                         public void removeUpdate(DocumentEvent e) {
118                                 setText();
119                         }
120                         private void setText() {
121                                 String name = field.getText();
122                                 if (name == null || name.equals(""))
123                                         return;
124                                 System.out.println("Setting name:"+name);
125                                 simulation.setName(name);
126                                 
127                         }
128                 });
129                 mainPanel.add(field, "shrinky, growx, wrap");
130                 
131                 JTabbedPane tabbedPane = new JTabbedPane();
132                 
133                 //// Launch conditions
134                 tabbedPane.addTab(trans.get("simedtdlg.tab.Launchcond"), flightConditionsTab());
135                 //// Simulation options
136                 tabbedPane.addTab(trans.get("simedtdlg.tab.Simopt"), simulationOptionsTab());
137                 //// Plot data
138                 tabbedPane.addTab(trans.get("simedtdlg.tab.Plotdata"), plotTab());
139                 //// Export data
140                 tabbedPane.addTab(trans.get("simedtdlg.tab.Exportdata"), exportTab());
141                 
142                 // Select the initial tab
143                 if (tab == EDIT) {
144                         tabbedPane.setSelectedIndex(0);
145                 } else if (tab == PLOT) {
146                         tabbedPane.setSelectedIndex(2);
147                 } else {
148                         FlightData data = s.getSimulatedData();
149                         if (data == null || data.getBranchCount() == 0)
150                                 tabbedPane.setSelectedIndex(0);
151                         else
152                                 tabbedPane.setSelectedIndex(2);
153                 }
154                 
155                 mainPanel.add(tabbedPane, "spanx, grow, wrap");
156
157                 
158                 // Buttons
159                 mainPanel.add(new JPanel(), "spanx, split, growx");
160
161                 JButton button;
162                 //// Run simulation button
163                 button = new JButton(trans.get("simedtdlg.but.runsimulation"));
164                 button.addActionListener(new ActionListener() {
165                         @Override
166                         public void actionPerformed(ActionEvent e) {
167                                 SimulationEditDialog.this.dispose();
168                                 SimulationRunDialog.runSimulations(parentWindow, simulation);
169                         }
170                 });
171                 mainPanel.add(button, "gapright para");
172                 
173                 //// Close button 
174                 JButton close = new JButton(trans.get("dlg.but.close"));
175                 close.addActionListener(new ActionListener() {
176                         @Override
177                         public void actionPerformed(ActionEvent e) {
178                                 SimulationEditDialog.this.dispose();
179                         }
180                 });
181                 mainPanel.add(close, "");
182                 
183                 
184                 this.add(mainPanel);
185                 this.validate();
186                 this.pack();
187                 this.setLocationByPlatform(true);
188                 
189                 GUIUtil.setDisposableDialogOptions(this, button);
190         }
191         
192         
193         
194         
195         
196         private JPanel flightConditionsTab() {
197                 JPanel panel = new JPanel(new MigLayout("fill"));
198                 JPanel sub;
199                 String tip;
200                 UnitSelector unit;
201                 BasicSlider slider;
202                 DoubleModel m;
203                 JSpinner spin;
204                 
205                 //// Motor selector
206                 //// Motor configuration:
207                 JLabel label = new JLabel(trans.get("simedtdlg.lbl.Motorcfg"));
208                 //// Select the motor configuration to use.
209                 label.setToolTipText(trans.get("simedtdlg.lbl.ttip.Motorcfg"));
210                 panel.add(label, "shrinkx, spanx, split 2");
211                 
212                 JComboBox combo = new JComboBox(new MotorConfigurationModel(configuration));
213                 //// Select the motor configuration to use.
214                 combo.setToolTipText(trans.get("simedtdlg.combo.ttip.motorconf"));
215                 combo.addActionListener(new ActionListener() {
216                         @Override
217                         public void actionPerformed(ActionEvent e) {
218                                 conditions.setMotorConfigurationID(configuration.getMotorConfigurationID());
219                         }
220                 });
221                 panel.add(combo, "growx, wrap para");
222                 
223                 
224                 //// Wind settings:  Average wind speed, turbulence intensity, std. deviation
225                 sub = new JPanel(new MigLayout("fill, gap rel unrel",
226                                 "[grow][65lp!][30lp!][75lp!]",""));
227                 //// Wind
228                 sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.lbl.Wind")));
229                 panel.add(sub, "growx, split 2, aligny 0, flowy, gapright para");
230
231
232                 // Wind average
233                 //// Average windspeed:
234                 label = new JLabel(trans.get("simedtdlg.lbl.Averwindspeed"));
235                 //// The average windspeed relative to the ground.
236                 tip = trans.get("simedtdlg.lbl.ttip.Averwindspeed");
237                 label.setToolTipText(tip);
238                 sub.add(label);
239                 
240                 m = new DoubleModel(conditions,"WindSpeedAverage", UnitGroup.UNITS_VELOCITY,0);
241                 
242                 spin = new JSpinner(m.getSpinnerModel());
243                 spin.setEditor(new SpinnerEditor(spin));
244                 spin.setToolTipText(tip);
245                 sub.add(spin,"w 65lp!");
246                 
247                 unit = new UnitSelector(m);
248                 unit.setToolTipText(tip);
249                 sub.add(unit,"growx");
250                 slider = new BasicSlider(m.getSliderModel(0, 10.0));
251                 slider.setToolTipText(tip);
252                 sub.add(slider,"w 75lp, wrap");
253                 
254
255
256                 // Wind std. deviation
257                 //// Standard deviation:
258                 label = new JLabel(trans.get("simedtdlg.lbl.Stddeviation"));
259                 //// <html>The standard deviation of the windspeed.<br>
260                 //// The windspeed is within twice the standard deviation from the average for 95% of the time.
261                 tip = trans.get("simedtdlg.lbl.ttip.Stddeviation");
262                 label.setToolTipText(tip);
263                 sub.add(label);
264                 
265                 m = new DoubleModel(conditions,"WindSpeedDeviation", UnitGroup.UNITS_VELOCITY,0);
266                 DoubleModel m2 = new DoubleModel(conditions,"WindSpeedAverage", 0.25, 
267                                 UnitGroup.UNITS_COEFFICIENT,0);
268                 
269                 spin = new JSpinner(m.getSpinnerModel());
270                 spin.setEditor(new SpinnerEditor(spin));
271                 spin.setToolTipText(tip);
272                 sub.add(spin,"w 65lp!");
273                 
274                 unit = new UnitSelector(m);
275                 unit.setToolTipText(tip);
276                 sub.add(unit,"growx");
277                 slider = new BasicSlider(m.getSliderModel(new DoubleModel(0), m2));
278                 slider.setToolTipText(tip);
279                 sub.add(slider,"w 75lp, wrap");
280                                 
281
282                 // Wind turbulence intensity
283                 //// Turbulence intensity:
284                 label = new JLabel(trans.get("simedtdlg.lbl.Turbulenceintensity"));
285                 //// <html>The turbulence intensity is the standard deviation divided by the average windspeed.<br>
286                 //// Typical values range from 
287                 //// to
288                 tip = trans.get("simedtdlg.lbl.ttip.Turbulenceintensity1") +
289                         trans.get("simedtdlg.lbl.ttip.Turbulenceintensity2") + " "+
290                         UnitGroup.UNITS_RELATIVE.getDefaultUnit().toStringUnit(0.05) +
291                         " " + trans.get("simedtdlg.lbl.ttip.Turbulenceintensity3") +" " +
292                         UnitGroup.UNITS_RELATIVE.getDefaultUnit().toStringUnit(0.20) + ".";
293                 label.setToolTipText(tip);
294                 sub.add(label);
295                 
296                 m = new DoubleModel(conditions,"WindTurbulenceIntensity", UnitGroup.UNITS_RELATIVE,0);
297                 
298                 spin = new JSpinner(m.getSpinnerModel());
299                 spin.setEditor(new SpinnerEditor(spin));
300                 spin.setToolTipText(tip);
301                 sub.add(spin,"w 65lp!");
302                 
303                 unit = new UnitSelector(m);
304                 unit.setToolTipText(tip);
305                 sub.add(unit,"growx");
306                 
307                 final JLabel intensityLabel = new JLabel(
308                                 getIntensityDescription(conditions.getWindTurbulenceIntensity()));
309                 intensityLabel.setToolTipText(tip);
310                 sub.add(intensityLabel,"w 75lp, wrap");
311                 m.addChangeListener(new ChangeListener() {
312                         @Override
313                         public void stateChanged(ChangeEvent e) {
314                                 intensityLabel.setText(
315                                                 getIntensityDescription(conditions.getWindTurbulenceIntensity()));
316                         }
317                 });
318                 
319
320                 
321                 
322                 
323                 //// Temperature and pressure
324                 sub = new JPanel(new MigLayout("fill, gap rel unrel",
325                                 "[grow][65lp!][30lp!][75lp!]",""));
326                 //// Atmospheric conditions
327                 sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.border.Atmoscond")));
328                 panel.add(sub, "growx, aligny 0, gapright para");
329
330                 
331                 BooleanModel isa = new BooleanModel(conditions, "ISAAtmosphere");
332                 JCheckBox check = new JCheckBox(isa);
333                 //// Use International Standard Atmosphere
334                 check.setText(trans.get("simedtdlg.checkbox.InterStdAtmosphere"));
335                 //// <html>Select to use the International Standard Atmosphere model.
336                 //// <br>This model has a temperature of
337                 //// and a pressure of
338                 //// at sea level.
339                 check.setToolTipText(trans.get("simedtdlg.checkbox.ttip.InterStdAtmosphere1") +" " + 
340                                 UnitGroup.UNITS_TEMPERATURE.toStringUnit(ExtendedISAModel.STANDARD_TEMPERATURE)+
341                                 " " + trans.get("simedtdlg.checkbox.ttip.InterStdAtmosphere2") + " " +
342                                 UnitGroup.UNITS_PRESSURE.toStringUnit(ExtendedISAModel.STANDARD_PRESSURE) +
343                                 " " + trans.get("simedtdlg.checkbox.ttip.InterStdAtmosphere3"));
344                 sub.add(check, "spanx, wrap unrel");
345                 
346                 // Temperature:
347                 label = new JLabel(trans.get("simedtdlg.lbl.Temperature"));
348                 //// The temperature at the launch site.
349                 tip = trans.get("simedtdlg.lbl.ttip.Temperature");
350                 label.setToolTipText(tip);
351                 isa.addEnableComponent(label, false);
352                 sub.add(label);
353                 
354                 m = new DoubleModel(conditions,"LaunchTemperature", UnitGroup.UNITS_TEMPERATURE,0);
355                 
356                 spin = new JSpinner(m.getSpinnerModel());
357                 spin.setEditor(new SpinnerEditor(spin));
358                 spin.setToolTipText(tip);
359                 isa.addEnableComponent(spin, false);
360                 sub.add(spin,"w 65lp!");
361                 
362                 unit = new UnitSelector(m);
363                 unit.setToolTipText(tip);
364                 isa.addEnableComponent(unit, false);
365                 sub.add(unit,"growx");
366                 slider = new BasicSlider(m.getSliderModel(253.15, 308.15));  // -20 ... 35
367                 slider.setToolTipText(tip);
368                 isa.addEnableComponent(slider, false);
369                 sub.add(slider,"w 75lp, wrap");
370                 
371
372                 
373                 // Pressure:
374                 label = new JLabel(trans.get("simedtdlg.lbl.Pressure"));
375                 //// The atmospheric pressure at the launch site.
376                 tip = trans.get("simedtdlg.lbl.ttip.Pressure");
377                 label.setToolTipText(tip);
378                 isa.addEnableComponent(label, false);
379                 sub.add(label);
380                 
381                 m = new DoubleModel(conditions,"LaunchPressure", UnitGroup.UNITS_PRESSURE,0);
382                 
383                 spin = new JSpinner(m.getSpinnerModel());
384                 spin.setEditor(new SpinnerEditor(spin));
385                 spin.setToolTipText(tip);
386                 isa.addEnableComponent(spin, false);
387                 sub.add(spin,"w 65lp!");
388                 
389                 unit = new UnitSelector(m);
390                 unit.setToolTipText(tip);
391                 isa.addEnableComponent(unit, false);
392                 sub.add(unit,"growx");
393                 slider = new BasicSlider(m.getSliderModel(0.950e5, 1.050e5));
394                 slider.setToolTipText(tip);
395                 isa.addEnableComponent(slider, false);
396                 sub.add(slider,"w 75lp, wrap");
397                 
398
399                 
400                 
401                 
402                 //// Launch site conditions
403                 sub = new JPanel(new MigLayout("fill, gap rel unrel",
404                                 "[grow][65lp!][30lp!][75lp!]",""));
405                 //// Launch site
406                 sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.lbl.Launchsite")));
407                 panel.add(sub, "growx, split 2, aligny 0, flowy");
408
409                 
410                 // Latitude:
411                 label = new JLabel(trans.get("simedtdlg.lbl.Latitude"));
412                 //// <html>The launch site latitude affects the gravitational pull of Earth.<br>
413                 //// Positive values are on the Northern hemisphere, negative values on the Southern hemisphere.
414                 tip = trans.get("simedtdlg.lbl.ttip.Latitude");
415                 label.setToolTipText(tip);
416                 sub.add(label);
417                 
418                 m = new DoubleModel(conditions,"LaunchLatitude", UnitGroup.UNITS_NONE, -90, 90);
419                 
420                 spin = new JSpinner(m.getSpinnerModel());
421                 spin.setEditor(new SpinnerEditor(spin));
422                 spin.setToolTipText(tip);
423                 sub.add(spin,"w 65lp!");
424                 
425                 label = new JLabel(Chars.DEGREE + " N");
426                 label.setToolTipText(tip);
427                 sub.add(label,"growx");
428                 slider = new BasicSlider(m.getSliderModel(-90, 90));
429                 slider.setToolTipText(tip);
430                 sub.add(slider,"w 75lp, wrap");
431                 
432
433                 
434                 // Altitude:
435                 label = new JLabel(trans.get("simedtdlg.lbl.Altitude"));
436                 //// <html>The launch altitude above mean sea level.<br> 
437                 //// This affects the position of the rocket in the atmospheric model.
438                 tip = trans.get("simedtdlg.lbl.ttip.Altitude");
439                 label.setToolTipText(tip);
440                 sub.add(label);
441                 
442                 m = new DoubleModel(conditions,"LaunchAltitude", UnitGroup.UNITS_DISTANCE,0);
443                 
444                 spin = new JSpinner(m.getSpinnerModel());
445                 spin.setEditor(new SpinnerEditor(spin));
446                 spin.setToolTipText(tip);
447                 sub.add(spin,"w 65lp!");
448                 
449                 unit = new UnitSelector(m);
450                 unit.setToolTipText(tip);
451                 sub.add(unit,"growx");
452                 slider = new BasicSlider(m.getSliderModel(0, 250, 1000));
453                 slider.setToolTipText(tip);
454                 sub.add(slider,"w 75lp, wrap");
455                 
456
457                 
458
459                 
460                 //// Launch rod
461                 sub = new JPanel(new MigLayout("fill, gap rel unrel",
462                                 "[grow][65lp!][30lp!][75lp!]",""));
463                 //// Launch rod
464                 sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.border.Launchrod")));
465                 panel.add(sub, "growx, aligny 0, wrap");
466
467                 
468                 // Length:
469                 label = new JLabel(trans.get("simedtdlg.lbl.Length"));
470                 //// The length of the launch rod.
471                 tip = trans.get("simedtdlg.lbl.ttip.Length");
472                 label.setToolTipText(tip);
473                 sub.add(label);
474                 
475                 m = new DoubleModel(conditions,"LaunchRodLength", UnitGroup.UNITS_LENGTH, 0);
476                 
477                 spin = new JSpinner(m.getSpinnerModel());
478                 spin.setEditor(new SpinnerEditor(spin));
479                 spin.setToolTipText(tip);
480                 sub.add(spin,"w 65lp!");
481                 
482                 unit = new UnitSelector(m);
483                 unit.setToolTipText(tip);
484                 sub.add(unit,"growx");
485                 slider = new BasicSlider(m.getSliderModel(0, 1, 5));
486                 slider.setToolTipText(tip);
487                 sub.add(slider,"w 75lp, wrap");
488                 
489
490                 
491                 // Angle:
492                 label = new JLabel(trans.get("simedtdlg.lbl.Angle"));
493                 //// The angle of the launch rod from vertical.
494                 tip = trans.get("simedtdlg.lbl.ttip.Angle");
495                 label.setToolTipText(tip);
496                 sub.add(label);
497                 
498                 m = new DoubleModel(conditions,"LaunchRodAngle", UnitGroup.UNITS_ANGLE,
499                                 0, GUISimulationConditions.MAX_LAUNCH_ROD_ANGLE);
500                 
501                 spin = new JSpinner(m.getSpinnerModel());
502                 spin.setEditor(new SpinnerEditor(spin));
503                 spin.setToolTipText(tip);
504                 sub.add(spin,"w 65lp!");
505                 
506                 unit = new UnitSelector(m);
507                 unit.setToolTipText(tip);
508                 sub.add(unit,"growx");
509                 slider = new BasicSlider(m.getSliderModel(0, Math.PI/9, 
510                                 GUISimulationConditions.MAX_LAUNCH_ROD_ANGLE));
511                 slider.setToolTipText(tip);
512                 sub.add(slider,"w 75lp, wrap");
513                 
514
515                 
516                 // Direction:
517                 label = new JLabel(trans.get("simedtdlg.lbl.Direction"));
518                 //// <html>Direction of the launch rod relative to the wind.<br>
519                 ////  = towards the wind, 
520                 ////  = downwind.
521                 tip = trans.get("simedtdlg.lbl.ttip.Direction1") +
522                                 UnitGroup.UNITS_ANGLE.toStringUnit(0) +
523                                 " " + trans.get("simedtdlg.lbl.ttip.Direction2") + " "+
524                                 UnitGroup.UNITS_ANGLE.toStringUnit(Math.PI) +
525                                 " " + trans.get("simedtdlg.lbl.ttip.Direction3");
526                 label.setToolTipText(tip);
527                 sub.add(label);
528                 
529                 m = new DoubleModel(conditions,"LaunchRodDirection", UnitGroup.UNITS_ANGLE,
530                                 -Math.PI, Math.PI);
531                 
532                 spin = new JSpinner(m.getSpinnerModel());
533                 spin.setEditor(new SpinnerEditor(spin));
534                 spin.setToolTipText(tip);
535                 sub.add(spin,"w 65lp!");
536                 
537                 unit = new UnitSelector(m);
538                 unit.setToolTipText(tip);
539                 sub.add(unit,"growx");
540                 slider = new BasicSlider(m.getSliderModel(-Math.PI, Math.PI));
541                 slider.setToolTipText(tip);
542                 sub.add(slider,"w 75lp, wrap");
543                 
544                 return panel;
545         }
546
547         
548         private String getIntensityDescription(double i) {
549                 if (i < 0.001)
550                         return "None";
551                 if (i < 0.05)
552                         return "Very low";
553                 if (i < 0.10)
554                         return "Low";
555                 if (i < 0.15)
556                         return "Medium";
557                 if (i < 0.20)
558                         return "High";
559                 if (i < 0.25)
560                         return "Very high";
561                 return "Extreme";
562         }
563
564         
565         
566         private JPanel simulationOptionsTab() {
567                 JPanel panel = new JPanel(new MigLayout("fill"));
568                 JPanel sub;
569                 String tip;
570                 JLabel label;
571                 DoubleModel m;
572                 JSpinner spin;
573                 UnitSelector unit;
574                 BasicSlider slider;
575
576                 
577                 //// Simulation options
578                 sub = new JPanel(new MigLayout("fill, gap rel unrel",
579                                 "[grow][65lp!][30lp!][75lp!]",""));
580                 //// Simulator options
581                 sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.border.Simopt")));
582                 panel.add(sub, "w 330lp!, growy, aligny 0");
583
584                 
585                 //  Calculation method
586                 //// <html>The Extended Barrowman method calculates aerodynamic forces according <br>
587                 //// to the Barrowman equations extended to accommodate more components.
588                 tip = trans.get("simedtdlg.lbl.ttip.Calcmethod");
589
590                 //// Calculation method:
591                 label = new JLabel(trans.get("simedtdlg.lbl.Calcmethod"));
592                 label.setToolTipText(tip);
593                 sub.add(label, "gaptop unrel, gapright para, spanx, split 2, w 150lp!");
594                 
595                 //// Extended Barrowman
596                 label = new JLabel(trans.get("simedtdlg.lbl.ExtBarrowman"));
597                 label.setToolTipText(tip);
598                 sub.add(label, "growx, wrap para");
599                 
600                 
601                 //  Simulation method
602                 //// <html>The six degree-of-freedom simulator allows the rocket total freedom during flight.<br>
603                 //// Integration is performed using a 4<sup>th</sup> order Runge-Kutta 4 numerical integration.
604                 tip = trans.get("simedtdlg.lbl.ttip.Simmethod1") +
605                 trans.get("simedtdlg.lbl.ttip.Simmethod2");
606
607                 //// Simulation method:
608                 label = new JLabel(trans.get("simedtdlg.lbl.Simmethod"));
609                 label.setToolTipText(tip);
610                 sub.add(label, "gaptop unrel, gapright para, spanx, split 2, w 150lp!");
611                 
612                 label = new JLabel("6-DOF Runge-Kutta 4");
613                 label.setToolTipText(tip);
614                 sub.add(label, "growx, wrap 35lp");
615                 
616                 
617                 // Wind average
618                 //// Time step:
619                 label = new JLabel(trans.get("simedtdlg.lbl.Timestep"));
620                 //// <html>The time between simulation steps.<br>
621                 //// A smaller time step results in a more accurate but slower simulation.<br>
622                 //// The 4<sup>th</sup> order simulation method is quite accurate with a time step of 
623                 tip = trans.get("simedtdlg.lbl.ttip.Timestep1") +
624                 trans.get("simedtdlg.lbl.ttip.Timestep2") + " " +
625                                 UnitGroup.UNITS_TIME_STEP.toStringUnit(RK4SimulationStepper.RECOMMENDED_TIME_STEP) +
626                                 ".";
627                 label.setToolTipText(tip);
628                 sub.add(label);
629                 
630                 m = new DoubleModel(conditions,"TimeStep", UnitGroup.UNITS_TIME_STEP, 0, 1);
631                 
632                 spin = new JSpinner(m.getSpinnerModel());
633                 spin.setEditor(new SpinnerEditor(spin));
634                 spin.setToolTipText(tip);
635                 sub.add(spin,"w 65lp!");
636                 
637                 unit = new UnitSelector(m);
638                 unit.setToolTipText(tip);
639                 sub.add(unit,"growx");
640                 slider = new BasicSlider(m.getSliderModel(0, 0.2));
641                 slider.setToolTipText(tip);
642                 sub.add(slider,"w 75lp, wrap");
643                 
644
645
646                 // Maximum angle step
647                 /*
648                 label = new JLabel("Max. angle step:");
649                 tip = "<html>" +
650                                 "This defines the maximum angle the rocket will turn during one time step.<br>"+
651                                 "Smaller values result in a more accurate but possibly slower simulation.<br>"+
652                                 "A recommended value is " +
653                                 UnitGroup.UNITS_ANGLE.toStringUnit(RK4Simulator.RECOMMENDED_ANGLE_STEP) + ".";
654                 label.setToolTipText(tip);
655                 sub.add(label);
656                 
657                 m = new DoubleModel(conditions,"MaximumStepAngle", UnitGroup.UNITS_ANGLE, 
658                                 1*Math.PI/180, Math.PI/9);
659                 
660                 spin = new JSpinner(m.getSpinnerModel());
661                 spin.setEditor(new SpinnerEditor(spin));
662                 spin.setToolTipText(tip);
663                 sub.add(spin,"w 65lp!");
664                 
665                 unit = new UnitSelector(m);
666                 unit.setToolTipText(tip);
667                 sub.add(unit,"growx");
668                 slider = new BasicSlider(m.getSliderModel(0, Math.toRadians(10)));
669                 slider.setToolTipText(tip);
670                 sub.add(slider,"w 75lp, wrap para");
671                 */
672
673                 //// Reset to default button
674                 JButton button = new JButton(trans.get("simedtdlg.but.resettodefault"));
675                 //// Reset the time step to its default value (
676                 button.setToolTipText(trans.get("simedtdlg.but.ttip.resettodefault") +
677                                 UnitGroup.UNITS_SHORT_TIME.toStringUnit(RK4SimulationStepper.RECOMMENDED_TIME_STEP) +
678                                 ").");
679                 button.addActionListener(new ActionListener() {
680                         @Override
681                         public void actionPerformed(ActionEvent e) {
682                                 conditions.setTimeStep(RK4SimulationStepper.RECOMMENDED_TIME_STEP);
683                         }
684                 });
685                                 
686 //              button.setToolTipText("<html>Reset the step value to its default:<br>" +
687 //                              "Time step " +
688 //                              UnitGroup.UNITS_SHORT_TIME.toStringUnit(RK4Simulator.RECOMMENDED_TIME_STEP) +
689 //                              "; maximum angle step " +
690 //                              UnitGroup.UNITS_ANGLE.toStringUnit(RK4Simulator.RECOMMENDED_ANGLE_STEP) + ".");
691                 sub.add(button, "spanx, tag right, wrap para");
692                 
693                 
694                 
695                 
696                 //// Simulation listeners
697                 sub = new JPanel(new MigLayout("fill, gap 0 0"));
698                 //// Simulator listeners
699                 sub.setBorder(BorderFactory.createTitledBorder(trans.get("simedtdlg.border.Simlist")));
700                 panel.add(sub, "growx, growy");
701                 
702                 
703                 DescriptionArea desc = new DescriptionArea(5);
704                 //// <html><i>Simulation listeners</i> is an advanced feature that allows user-written code to listen to and interact with the simulation.  
705                 //// For details on writing simulation listeners, see the OpenRocket technical documentation.
706                 desc.setText(trans.get("simedtdlg.txt.longA1") +
707                                 trans.get("simedtdlg.txt.longA2"));
708                 sub.add(desc, "aligny 0, growx, wrap para");
709                 
710                 //// Current listeners:
711                 label = new JLabel(trans.get("simedtdlg.lbl.Curlist"));
712                 sub.add(label, "spanx, wrap rel");
713
714                 final ListenerListModel listenerModel = new ListenerListModel();
715                 final JList list = new JList(listenerModel);
716                 list.setCellRenderer(new ListenerCellRenderer());
717                 JScrollPane scroll = new JScrollPane(list);
718 //              scroll.setPreferredSize(new Dimension(1,1));
719                 sub.add(scroll, "height 1px, grow, wrap rel");
720                 
721                 //// Add button
722                 button = new JButton(trans.get("simedtdlg.but.add"));
723                 button.addActionListener(new ActionListener() {
724                         @Override
725                         public void actionPerformed(ActionEvent e) {
726                                 String previous = Prefs.NODE.get("previousListenerName", "");
727                                 String input = (String)JOptionPane.showInputDialog(SimulationEditDialog.this,
728                                                 new Object[] {
729                                                 //// Type the full Java class name of the simulation listener, for example:
730                                                 "Type the full Java class name of the simulation listener, for example:",
731                                                 "<html><tt>" + CSVSaveListener.class.getName() + "</tt>" },
732                                                 //// Add simulation listener
733                                                 trans.get("simedtdlg.lbl.Addsimlist"),
734                                                 JOptionPane.QUESTION_MESSAGE,
735                                                 null, null,
736                                                 previous
737                                 );
738                                 if (input == null || input.equals(""))
739                                         return;
740
741                                 Prefs.NODE.put("previousListenerName", input);
742                                 simulation.getSimulationListeners().add(input);
743                                 listenerModel.fireContentsChanged();
744                         }
745                 });
746                 sub.add(button, "split 2, sizegroup buttons, alignx 50%, gapright para");
747                 
748                 //// Remove button
749                 button = new JButton(trans.get("simedtdlg.but.remove"));
750                 button.addActionListener(new ActionListener() {
751                         @Override
752                         public void actionPerformed(ActionEvent e) {
753                                 int[] selected = list.getSelectedIndices();
754                                 Arrays.sort(selected);
755                                 for (int i=selected.length-1; i>=0; i--) {
756                                         simulation.getSimulationListeners().remove(selected[i]);
757                                 }
758                                 listenerModel.fireContentsChanged();
759                         }
760                 });
761                 sub.add(button, "sizegroup buttons, alignx 50%");
762                 
763
764                 return panel;
765         }
766
767
768         private class ListenerListModel extends AbstractListModel {
769                 @Override
770                 public String getElementAt(int index) {
771                         if (index < 0 || index >= getSize())
772                                 return null;
773                         return simulation.getSimulationListeners().get(index);
774                 }
775                 @Override
776                 public int getSize() {
777                         return simulation.getSimulationListeners().size();
778                 }
779                 public void fireContentsChanged() {
780                         super.fireContentsChanged(this, 0, getSize());
781                 }
782         }
783         
784         
785         
786         
787         /**
788          * A panel for plotting the previously calculated data.
789          */
790         private JPanel plotTab() {
791
792                 // Check that data exists
793                 if (simulation.getSimulatedData() == null  ||
794                                 simulation.getSimulatedData().getBranchCount() == 0) {
795                         return noDataPanel();
796                 }
797                 
798                 return new SimulationPlotPanel(simulation);
799         }
800         
801         
802         
803         /**
804          * A panel for exporting the data.
805          */
806         private JPanel exportTab() {
807                 FlightData data = simulation.getSimulatedData();
808
809                 // Check that data exists
810                 if (data == null  || data.getBranchCount() == 0 ||
811                                 data.getBranch(0).getTypes().length == 0) {
812                         return noDataPanel();
813                 }
814                 
815                 return new SimulationExportPanel(simulation);
816         }
817         
818         
819         
820         
821
822         /**
823          * Return a panel stating that there is no data available, and that the user
824          * should run the simulation first.
825          */
826         public static JPanel noDataPanel() {
827                 JPanel panel = new JPanel(new MigLayout("fill"));
828                 
829                 // No data available
830                 //// No flight data available.
831                 panel.add(new JLabel(trans.get("simedtdlg.lbl.Noflightdata")),
832                 "alignx 50%, aligny 100%, wrap para");
833                 //// Please run the simulation first.
834                 panel.add(new JLabel(trans.get("simedtdlg.lbl.runsimfirst")),
835                 "alignx 50%, aligny 0%, wrap");
836                 return panel;
837         }
838         
839
840         private void performPlot(PlotConfiguration config) {
841
842                 // Fill the auto-selections
843                 FlightDataBranch branch = simulation.getSimulatedData().getBranch(0);
844                 PlotConfiguration filled = config.fillAutoAxes(branch);
845                 List<Axis> axes = filled.getAllAxes();
846
847
848                 // Create the data series for both axes
849                 XYSeriesCollection[] data = new XYSeriesCollection[2];
850                 data[0] = new XYSeriesCollection();
851                 data[1] = new XYSeriesCollection();
852                 
853                 
854                 // Get the domain axis type
855                 final FlightDataType domainType = filled.getDomainAxisType();
856                 final Unit domainUnit = filled.getDomainAxisUnit();
857                 if (domainType == null) {
858                         throw new IllegalArgumentException("Domain axis type not specified.");
859                 }
860                 List<Double> x = branch.get(domainType);
861
862                 
863                 // Create the XYSeries objects from the flight data and store into the collections
864                 int length = filled.getTypeCount();
865                 String[] axisLabel = new String[2];
866                 for (int i = 0; i < length; i++) {
867                         // Get info
868                         FlightDataType type = filled.getType(i);
869                         Unit unit = filled.getUnit(i);
870                         int axis = filled.getAxis(i);
871                         String name = getLabel(type, unit);
872                         
873                         // Store data in provided units
874                         List<Double> y = branch.get(type);
875                         XYSeries series = new XYSeries(name, false, true);
876                         for (int j=0; j<x.size(); j++) {
877                                 series.add(domainUnit.toUnit(x.get(j)), unit.toUnit(y.get(j)));
878                         }
879                         data[axis].addSeries(series);
880
881                         // Update axis label
882                         if (axisLabel[axis] == null)
883                                 axisLabel[axis] = type.getName();
884                         else
885                                 axisLabel[axis] += "; " + type.getName();
886                 }
887                 
888                 
889                 // Create the chart using the factory to get all default settings
890         JFreeChart chart = ChartFactory.createXYLineChart(
891             //// Simulated flight
892                 trans.get("simedtdlg.chart.Simflight"),
893             null, 
894             null, 
895             null,
896             PlotOrientation.VERTICAL,
897             true,
898             true,
899             false
900         );
901                 
902         
903                 // Add the data and formatting to the plot
904                 XYPlot plot = chart.getXYPlot();
905                 int axisno = 0;
906                 for (int i=0; i<2; i++) {
907                         // Check whether axis has any data
908                         if (data[i].getSeriesCount() > 0) {
909                                 // Create and set axis
910                                 double min = axes.get(i).getMinValue();
911                                 double max = axes.get(i).getMaxValue();
912                                 NumberAxis axis = new PresetNumberAxis(min, max);
913                                 axis.setLabel(axisLabel[i]);
914 //                              axis.setRange(axes.get(i).getMinValue(), axes.get(i).getMaxValue());
915                                 plot.setRangeAxis(axisno, axis);
916                                 
917                                 // Add data and map to the axis
918                                 plot.setDataset(axisno, data[i]);
919                                 plot.setRenderer(axisno, new StandardXYItemRenderer());
920                                 plot.mapDatasetToRangeAxis(axisno, axisno);
921                                 axisno++;
922                         }
923                 }
924                 
925                 plot.getDomainAxis().setLabel(getLabel(domainType,domainUnit));
926                 plot.addDomainMarker(new ValueMarker(0));
927                 plot.addRangeMarker(new ValueMarker(0));
928                 
929                 
930                 // Create the dialog
931                 //// Simulation results
932                 final JDialog dialog = new JDialog(this, trans.get("simedtdlg.dlg.Simres"));
933                 dialog.setModalityType(ModalityType.DOCUMENT_MODAL);
934                 
935                 JPanel panel = new JPanel(new MigLayout("fill"));
936                 dialog.add(panel);
937                 
938                 ChartPanel chartPanel = new ChartPanel(chart,
939                                 false, // properties
940                                 true,  // save
941                                 false, // print
942                                 true,  // zoom
943                                 true); // tooltips
944                 chartPanel.setMouseWheelEnabled(true);
945                 chartPanel.setEnforceFileExtensions(true);
946                 chartPanel.setInitialDelay(500);
947                 
948                 chartPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
949                 
950                 panel.add(chartPanel, "grow, wrap 20lp");
951
952                 //// Close button
953                 JButton button = new JButton(trans.get("dlg.but.close"));
954                 button.addActionListener(new ActionListener() {
955                         @Override
956                         public void actionPerformed(ActionEvent e) {
957                                 dialog.setVisible(false);
958                         }
959                 });
960                 panel.add(button, "right");
961
962                 dialog.setLocationByPlatform(true);
963                 dialog.pack();
964                 
965                 GUIUtil.setDisposableDialogOptions(dialog, button);
966
967                 dialog.setVisible(true);
968         }
969
970         
971         private class PresetNumberAxis extends NumberAxis {
972                 private final double min;
973                 private final double max;
974                 
975                 public PresetNumberAxis(double min, double max) {
976                         this.min = min;
977                         this.max = max;
978                         autoAdjustRange();
979                 }
980                 
981                 @Override
982                 protected void autoAdjustRange() {
983                         this.setRange(min, max);
984                 }
985         }
986         
987         
988         private String getLabel(FlightDataType type, Unit unit) {
989                 String name = type.getName();
990                 if (unit != null  &&  !UnitGroup.UNITS_NONE.contains(unit)  &&
991                                 !UnitGroup.UNITS_COEFFICIENT.contains(unit) && unit.getUnit().length() > 0)
992                         name += " ("+unit.getUnit() + ")";
993                 return name;
994         }
995         
996
997
998         private class ListenerCellRenderer extends JLabel implements ListCellRenderer {
999
1000                 public Component getListCellRendererComponent(JList list, Object value,
1001                                 int index, boolean isSelected, boolean cellHasFocus) {
1002                         String s = value.toString();
1003                         setText(s);
1004
1005                         // Attempt instantiating, catch any exceptions
1006                         Exception ex = null;
1007                         try {
1008                                 Class<?> c = Class.forName(s);
1009                                 @SuppressWarnings("unused")
1010                                 SimulationListener l = (SimulationListener)c.newInstance();
1011                         } catch (Exception e) {
1012                                 ex = e;
1013                         }
1014
1015                         if (ex == null) {
1016                                 setIcon(Icons.SIMULATION_LISTENER_OK);
1017                                 //// Listener instantiated successfully.
1018                                 setToolTipText("Listener instantiated successfully.");
1019                         } else {
1020                                 setIcon(Icons.SIMULATION_LISTENER_ERROR);
1021                                 //// <html>Unable to instantiate listener due to exception:<br>
1022                                 setToolTipText("<html>Unable to instantiate listener due to exception:<br>" +
1023                                                 ex.toString());
1024                         }
1025
1026                         if (isSelected) {
1027                                 setBackground(list.getSelectionBackground());
1028                                 setForeground(list.getSelectionForeground());
1029                         } else {
1030                                 setBackground(list.getBackground());
1031                                 setForeground(list.getForeground());
1032                         }
1033                         setOpaque(true);
1034                         return this;
1035                 }
1036         }
1037 }