updates for 0.9.3
[debian/openrocket] / src / net / sf / openrocket / gui / plot / PlotDialog.java
1 package net.sf.openrocket.gui.plot;
2
3 import java.awt.AlphaComposite;
4 import java.awt.Color;
5 import java.awt.Composite;
6 import java.awt.Font;
7 import java.awt.Graphics2D;
8 import java.awt.Image;
9 import java.awt.Window;
10 import java.awt.event.ActionEvent;
11 import java.awt.event.ActionListener;
12 import java.awt.geom.Line2D;
13 import java.awt.geom.Point2D;
14 import java.awt.geom.Rectangle2D;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
22 import java.util.Map;
23
24 import javax.imageio.ImageIO;
25 import javax.swing.BorderFactory;
26 import javax.swing.JButton;
27 import javax.swing.JCheckBox;
28 import javax.swing.JDialog;
29 import javax.swing.JPanel;
30
31 import net.miginfocom.swing.MigLayout;
32 import net.sf.openrocket.document.Simulation;
33 import net.sf.openrocket.simulation.FlightDataBranch;
34 import net.sf.openrocket.simulation.FlightEvent;
35 import net.sf.openrocket.unit.Unit;
36 import net.sf.openrocket.unit.UnitGroup;
37 import net.sf.openrocket.util.GUIUtil;
38 import net.sf.openrocket.util.MathUtil;
39 import net.sf.openrocket.util.Pair;
40 import net.sf.openrocket.util.Prefs;
41
42 import org.jfree.chart.ChartFactory;
43 import org.jfree.chart.ChartPanel;
44 import org.jfree.chart.JFreeChart;
45 import org.jfree.chart.annotations.XYImageAnnotation;
46 import org.jfree.chart.axis.NumberAxis;
47 import org.jfree.chart.axis.ValueAxis;
48 import org.jfree.chart.plot.Marker;
49 import org.jfree.chart.plot.PlotOrientation;
50 import org.jfree.chart.plot.ValueMarker;
51 import org.jfree.chart.plot.XYPlot;
52 import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
53 import org.jfree.chart.title.TextTitle;
54 import org.jfree.data.Range;
55 import org.jfree.data.xy.XYSeries;
56 import org.jfree.data.xy.XYSeriesCollection;
57 import org.jfree.text.TextUtilities;
58 import org.jfree.ui.LengthAdjustmentType;
59 import org.jfree.ui.RectangleAnchor;
60 import org.jfree.ui.TextAnchor;
61
62 public class PlotDialog extends JDialog {
63         
64         private static final Color DEFAULT_EVENT_COLOR = new Color(0,0,0);
65         private static final Map<FlightEvent.Type, Color> EVENT_COLORS =
66                 new HashMap<FlightEvent.Type, Color>();
67         static {
68                 EVENT_COLORS.put(FlightEvent.Type.LAUNCH, new Color(255,0,0));
69                 EVENT_COLORS.put(FlightEvent.Type.LIFTOFF, new Color(0,80,196));
70                 EVENT_COLORS.put(FlightEvent.Type.LAUNCHROD, new Color(0,100,80));
71                 EVENT_COLORS.put(FlightEvent.Type.IGNITION, new Color(230,130,15));
72                 EVENT_COLORS.put(FlightEvent.Type.BURNOUT, new Color(80,55,40));
73                 EVENT_COLORS.put(FlightEvent.Type.EJECTION_CHARGE, new Color(80,55,40));
74                 EVENT_COLORS.put(FlightEvent.Type.STAGE_SEPARATION, new Color(80,55,40));
75                 EVENT_COLORS.put(FlightEvent.Type.APOGEE, new Color(15,120,15));
76                 EVENT_COLORS.put(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, new Color(0,0,128));
77                 EVENT_COLORS.put(FlightEvent.Type.GROUND_HIT, new Color(0,0,0));
78                 EVENT_COLORS.put(FlightEvent.Type.SIMULATION_END, new Color(128,0,0));
79         }
80
81         private static final Map<FlightEvent.Type, Image> EVENT_IMAGES =
82                 new HashMap<FlightEvent.Type, Image>();
83         static {
84                 loadImage(FlightEvent.Type.LAUNCH, "pix/eventicons/event-launch.png");
85                 loadImage(FlightEvent.Type.LIFTOFF, "pix/eventicons/event-liftoff.png");
86                 loadImage(FlightEvent.Type.LAUNCHROD, "pix/eventicons/event-launchrod.png");
87                 loadImage(FlightEvent.Type.IGNITION, "pix/eventicons/event-ignition.png");
88                 loadImage(FlightEvent.Type.BURNOUT, "pix/eventicons/event-burnout.png");
89                 loadImage(FlightEvent.Type.EJECTION_CHARGE,"pix/eventicons/event-ejection-charge.png");
90                 loadImage(FlightEvent.Type.STAGE_SEPARATION, 
91                                 "pix/eventicons/event-stage-separation.png");
92                 loadImage(FlightEvent.Type.APOGEE, "pix/eventicons/event-apogee.png");
93                 loadImage(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, 
94                                 "pix/eventicons/event-recovery-device-deployment.png");
95                 loadImage(FlightEvent.Type.GROUND_HIT, "pix/eventicons/event-ground-hit.png");
96                 loadImage(FlightEvent.Type.SIMULATION_END, "pix/eventicons/event-simulation-end.png");
97         }
98
99     private static void loadImage(FlightEvent.Type type, String file) {
100         InputStream is;
101  
102         is = ClassLoader.getSystemResourceAsStream(file);
103         if (is == null) {
104                 System.out.println("ERROR: File " + file + " not found!");
105                 return;
106         }
107         
108         try {
109                 Image image = ImageIO.read(is);
110                 EVENT_IMAGES.put(type, image);
111         } catch (IOException ignore) {
112                 ignore.printStackTrace();
113         }
114     }
115     
116     
117     
118     
119     private final List<ModifiedXYItemRenderer> renderers =
120         new ArrayList<ModifiedXYItemRenderer>();
121         
122         private PlotDialog(Window parent, Simulation simulation, PlotConfiguration config) {
123                 super(parent, "Flight data plot");
124                 this.setModalityType(ModalityType.DOCUMENT_MODAL);
125                 
126                 final boolean initialShowPoints = Prefs.getBoolean(Prefs.PLOT_SHOW_POINTS, false);
127                 
128                 
129                 // Fill the auto-selections
130                 FlightDataBranch branch = simulation.getSimulatedData().getBranch(0);
131                 PlotConfiguration filled = config.fillAutoAxes(branch);
132                 List<Axis> axes = filled.getAllAxes();
133
134
135                 // Create the data series for both axes
136                 XYSeriesCollection[] data = new XYSeriesCollection[2];
137                 data[0] = new XYSeriesCollection();
138                 data[1] = new XYSeriesCollection();
139                 
140                 
141                 // Get the domain axis type
142                 final FlightDataBranch.Type domainType = filled.getDomainAxisType();
143                 final Unit domainUnit = filled.getDomainAxisUnit();
144                 if (domainType == null) {
145                         throw new IllegalArgumentException("Domain axis type not specified.");
146                 }
147                 List<Double> x = branch.get(domainType);
148                 
149                 
150                 // Get plot length (ignore trailing NaN's)
151                 int typeCount = filled.getTypeCount();
152                 int dataLength = 0;
153                 for (int i=0; i<typeCount; i++) {
154                         FlightDataBranch.Type type = filled.getType(i);
155                         List<Double> y = branch.get(type);
156                         
157                         for (int j = dataLength; j < y.size(); j++) {
158                                 if (!Double.isNaN(y.get(j)) && !Double.isInfinite(y.get(j)))
159                                         dataLength = j;
160                         }
161                 }
162                 dataLength = Math.min(dataLength, x.size());
163                 
164                 
165                 // Create the XYSeries objects from the flight data and store into the collections
166                 String[] axisLabel = new String[2];
167                 for (int i = 0; i < typeCount; i++) {
168                         // Get info
169                         FlightDataBranch.Type type = filled.getType(i);
170                         Unit unit = filled.getUnit(i);
171                         int axis = filled.getAxis(i);
172                         String name = getLabel(type, unit);
173                         
174                         // Store data in provided units
175                         List<Double> y = branch.get(type);
176                         XYSeries series = new XYSeries(name, false, true);
177                         for (int j=0; j < dataLength; j++) {
178                                 series.add(domainUnit.toUnit(x.get(j)), unit.toUnit(y.get(j)));
179                         }
180                         data[axis].addSeries(series);
181
182                         // Update axis label
183                         if (axisLabel[axis] == null)
184                                 axisLabel[axis] = type.getName();
185                         else
186                                 axisLabel[axis] += "; " + type.getName();
187                 }
188                 
189                 
190                 // Create the chart using the factory to get all default settings
191         JFreeChart chart = ChartFactory.createXYLineChart(
192             "Simulated flight",
193             null, 
194             null, 
195             null,
196             PlotOrientation.VERTICAL,
197             true,
198             true,
199             false
200         );
201                 
202         chart.addSubtitle(new TextTitle(config.getName()));
203         
204                 // Add the data and formatting to the plot
205                 XYPlot plot = chart.getXYPlot();
206                 int axisno = 0;
207                 for (int i=0; i<2; i++) {
208                         // Check whether axis has any data
209                         if (data[i].getSeriesCount() > 0) {
210                                 // Create and set axis
211                                 double min = axes.get(i).getMinValue();
212                                 double max = axes.get(i).getMaxValue();
213                                 NumberAxis axis = new PresetNumberAxis(min, max);
214                                 axis.setLabel(axisLabel[i]);
215 //                              axis.setRange(axes.get(i).getMinValue(), axes.get(i).getMaxValue());
216                                 plot.setRangeAxis(axisno, axis);
217                                 
218                                 // Add data and map to the axis
219                                 plot.setDataset(axisno, data[i]);
220                                 ModifiedXYItemRenderer r = new ModifiedXYItemRenderer();
221                                 r.setBaseShapesVisible(initialShowPoints);
222                                 r.setBaseShapesFilled(true);
223                                 renderers.add(r);
224                                 plot.setRenderer(axisno, r);
225                                 plot.mapDatasetToRangeAxis(axisno, axisno);
226                                 axisno++;
227                         }
228                 }
229                 
230                 plot.getDomainAxis().setLabel(getLabel(domainType,domainUnit));
231                 plot.addDomainMarker(new ValueMarker(0));
232                 plot.addRangeMarker(new ValueMarker(0));
233                 
234                 
235                 
236                 // Create list of events to show (combine event too close to each other)
237                 ArrayList<Double> timeList = new ArrayList<Double>();
238                 ArrayList<String> eventList = new ArrayList<String>();
239                 ArrayList<Color> colorList = new ArrayList<Color>();
240                 ArrayList<Image> imageList = new ArrayList<Image>();
241                 
242                 HashSet<FlightEvent.Type> typeSet = new HashSet<FlightEvent.Type>();
243                 
244                 double prevTime = -100;
245                 String text = null;
246                 Color color = null;
247                 Image image = null;
248                 
249                 List<Pair<Double, FlightEvent>> events = branch.getEvents();
250                 for (int i=0; i < events.size(); i++) {
251                         Pair<Double, FlightEvent> event = events.get(i);
252                         double t = event.getU();
253                         FlightEvent.Type type = event.getV().getType();
254                         
255                         if (type != FlightEvent.Type.ALTITUDE && config.isEventActive(type)) {
256                                 if (Math.abs(t - prevTime) <= 0.01) {
257                                         
258                                         if (!typeSet.contains(type)) {
259                                                 text = text + ", " + event.getV().getType().toString();
260                                                 color = getEventColor(type);
261                                                 image = EVENT_IMAGES.get(type);
262                                                 typeSet.add(type);
263                                         }
264                                         
265                                 } else {
266                                         
267                                         if (text != null) {
268                                                 timeList.add(prevTime);
269                                                 eventList.add(text);
270                                                 colorList.add(color);
271                                                 imageList.add(image);
272                                         }
273                                         prevTime = t;
274                                         text = type.toString();
275                                         color = getEventColor(type);
276                                         image = EVENT_IMAGES.get(type);
277                                         typeSet.clear();
278                                         typeSet.add(type);
279                                         
280                                 }
281                         }
282                 }
283                 if (text != null) {
284                         timeList.add(prevTime);
285                         eventList.add(text);
286                         colorList.add(color);
287                         imageList.add(image);
288                 }
289                 
290                 
291                 // Create the event markers
292                 
293                 if (config.getDomainAxisType() == FlightDataBranch.TYPE_TIME) {
294                         
295                         // Domain time is plotted as vertical markers
296                         for (int i=0; i < eventList.size(); i++) {
297                                 double t = timeList.get(i);
298                                 String event = eventList.get(i);
299                                 color = colorList.get(i);
300                                 
301                                 ValueMarker m = new ValueMarker(t);
302                                 m.setLabel(event);
303                                 m.setPaint(color);
304                                 m.setLabelPaint(color);
305                                 m.setAlpha(0.7f);
306                                 plot.addDomainMarker(m);
307                         }
308                         
309                 } else {
310                         
311                         // Other domains are plotted as image annotations
312                         List<Double> time = branch.get(FlightDataBranch.TYPE_TIME);
313                         List<Double> domain = branch.get(config.getDomainAxisType());
314                         
315                         for (int i=0; i < eventList.size(); i++) {
316                                 final double t = timeList.get(i);
317                                 String event = eventList.get(i);
318                                 image = imageList.get(i);
319                                 
320                                 if (image == null)
321                                         continue;
322                                 
323                                 // Calculate index and interpolation position a
324                                 final double a;
325                                 int tindex = Collections.binarySearch(time, t);
326                                 if (tindex < 0) {
327                                         tindex = -tindex -1;
328                                 }
329                                 if (tindex >= time.size()) {
330                                         // index greater than largest value in time list
331                                         tindex = time.size()-1;
332                                         a = 0;
333                                 } else if (tindex <= 0) {
334                                         // index smaller than smallest value in time list
335                                         tindex = 0;
336                                         a = 0;
337                                 } else {
338                                         assert(tindex > 0);
339                                         tindex--;
340                                         double t1 = time.get(tindex);
341                                         double t2 = time.get(tindex+1);
342                                         
343                                         if ((t1 > t) || (t2 < t)) {
344                                                 throw new RuntimeException("BUG: t1="+t1+" t2="+t2+" t="+t);
345                                         }
346                                         
347                                         if (MathUtil.equals(t1, t2)) {
348                                                 a = 0;
349                                         } else {
350                                                 a = 1 - (t-t1) / (t2-t1);
351                                         }
352                                 }
353                                 
354                                 final double xcoord;
355                                 if (a == 0) {
356                                         xcoord = domain.get(tindex);
357                                 } else {
358                                         xcoord = a * domain.get(tindex) + (1-a) * domain.get(tindex+1);
359                                 }
360                                 
361                                 for (int index = 0; index < config.getTypeCount(); index++) {
362                                         FlightDataBranch.Type type = config.getType(index);
363                                         List<Double> range = branch.get(type);
364                                         
365                                         final double ycoord;
366                                         if (a == 0) {
367                                                 ycoord = range.get(tindex);
368                                         } else {
369                                                 ycoord = a * range.get(tindex) + (1-a) * range.get(tindex+1);
370                                         }
371                                         
372                                         XYImageAnnotation annotation = 
373                                                 new XYImageAnnotation(xcoord, ycoord, image, RectangleAnchor.CENTER);
374                                         annotation.setToolTipText(event);
375                                         plot.addAnnotation(annotation);
376                                 }
377                         }
378                 }
379                 
380                 
381                 // Create the dialog
382                 
383                 JPanel panel = new JPanel(new MigLayout("fill"));
384                 this.add(panel);
385                 
386                 ChartPanel chartPanel = new ChartPanel(chart,
387                                 false, // properties
388                                 true,  // save
389                                 false, // print
390                                 true,  // zoom
391                                 true); // tooltips
392                 chartPanel.setMouseWheelEnabled(true);
393                 chartPanel.setEnforceFileExtensions(true);
394                 chartPanel.setInitialDelay(500);
395                 
396                 chartPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
397                 
398                 panel.add(chartPanel, "grow, wrap 20lp");
399                 
400                 final JCheckBox check = new JCheckBox("Show points");
401                 check.setSelected(initialShowPoints);
402                 check.addActionListener(new ActionListener() {
403                         @Override
404                         public void actionPerformed(ActionEvent e) {
405                                 boolean show = check.isSelected();
406                                 Prefs.putBoolean(Prefs.PLOT_SHOW_POINTS, show);
407                                 for (ModifiedXYItemRenderer r: renderers) {
408                                         r.setBaseShapesVisible(show);
409                                 }
410                         }
411                 });
412                 panel.add(check, "split, left");
413                 
414                 panel.add(new JPanel(), "growx");
415
416                 JButton button = new JButton("Close");
417                 button.addActionListener(new ActionListener() {
418                         @Override
419                         public void actionPerformed(ActionEvent e) {
420                                 PlotDialog.this.dispose();
421                         }
422                 });
423                 panel.add(button, "right");
424
425                 this.setLocationByPlatform(true);
426                 this.pack();
427                 GUIUtil.installEscapeCloseOperation(this);
428                 GUIUtil.setDefaultButton(button);
429         }
430         
431         
432         private String getLabel(FlightDataBranch.Type type, Unit unit) {
433                 String name = type.getName();
434                 if (unit != null  &&  !UnitGroup.UNITS_NONE.contains(unit)  &&
435                                 !UnitGroup.UNITS_COEFFICIENT.contains(unit) && unit.getUnit().length() > 0)
436                         name += " ("+unit.getUnit() + ")";
437                 return name;
438         }
439         
440
441         
442         private class PresetNumberAxis extends NumberAxis {
443                 private final double min;
444                 private final double max;
445                 
446                 public PresetNumberAxis(double min, double max) {
447                         this.min = min;
448                         this.max = max;
449                         autoAdjustRange();
450                 }
451                 
452                 @Override
453                 protected void autoAdjustRange() {
454                         this.setRange(min, max);
455                 }
456         }
457         
458         
459         /**
460          * Static method that shows a plot with the specified parameters.
461          * 
462          * @param parent                the parent window, which will be blocked.
463          * @param simulation    the simulation to plot.
464          * @param config                the configuration of the plot.
465          */
466         public static void showPlot(Window parent, Simulation simulation, PlotConfiguration config) {
467                 new PlotDialog(parent, simulation, config).setVisible(true);
468         }
469         
470         
471         
472         private static Color getEventColor(FlightEvent.Type type) {
473                 Color c = EVENT_COLORS.get(type);
474                 if (c != null)
475                         return c;
476                 return DEFAULT_EVENT_COLOR;
477         }
478         
479         
480
481         
482         
483         /**
484          * A modification to the standard renderer that renders the domain marker
485          * labels vertically instead of horizontally.
486          */
487         private static class ModifiedXYItemRenderer extends StandardXYItemRenderer {
488
489                 @Override
490                 public void drawDomainMarker(Graphics2D g2, XYPlot plot, ValueAxis domainAxis,
491                                 Marker marker, Rectangle2D dataArea) {
492
493                         if (!(marker instanceof ValueMarker)) {
494                                 // Use parent for all others
495                                 super.drawDomainMarker(g2, plot, domainAxis, marker, dataArea);
496                                 return;
497                         }
498
499                         /*
500                          * Draw the normal marker, but with rotated text.
501                          * Copied from the overridden method.
502                          */
503                         ValueMarker vm = (ValueMarker) marker;
504                         double value = vm.getValue();
505                         Range range = domainAxis.getRange();
506                         if (!range.contains(value)) {
507                                 return;
508                         }
509
510                         double v = domainAxis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge());
511
512                         PlotOrientation orientation = plot.getOrientation();
513                         Line2D line = null;
514                         if (orientation == PlotOrientation.HORIZONTAL) {
515                                 line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v);
516                         } else {
517                                 line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY());
518                         }
519
520                         final Composite originalComposite = g2.getComposite();
521                         g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, marker
522                                         .getAlpha()));
523                         g2.setPaint(marker.getPaint());
524                         g2.setStroke(marker.getStroke());
525                         g2.draw(line);
526
527                         String label = marker.getLabel();
528                         RectangleAnchor anchor = marker.getLabelAnchor();
529                         if (label != null) {
530                                 Font labelFont = marker.getLabelFont();
531                                 g2.setFont(labelFont);
532                                 g2.setPaint(marker.getLabelPaint());
533                                 Point2D coordinates = calculateDomainMarkerTextAnchorPoint(g2,
534                                                 orientation, dataArea, line.getBounds2D(), marker
535                                                                 .getLabelOffset(), LengthAdjustmentType.EXPAND, anchor);
536                                 
537                                 // Changed:
538                                 TextAnchor textAnchor = TextAnchor.TOP_RIGHT;
539                                 TextUtilities.drawRotatedString(label, g2, (float) coordinates.getX()+2,
540                                                 (float) coordinates.getY(), textAnchor,
541                                                 -Math.PI/2, textAnchor);
542                         }
543                         g2.setComposite(originalComposite);
544                 }
545
546         }
547
548 }