1 package net.sf.openrocket.gui.plot;
3 import java.awt.AlphaComposite;
4 import java.awt.BasicStroke;
6 import java.awt.Composite;
8 import java.awt.Graphics2D;
10 import java.awt.Window;
11 import java.awt.event.ActionEvent;
12 import java.awt.event.ActionListener;
13 import java.awt.geom.Line2D;
14 import java.awt.geom.Point2D;
15 import java.awt.geom.Rectangle2D;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
25 import javax.imageio.ImageIO;
26 import javax.swing.BorderFactory;
27 import javax.swing.JButton;
28 import javax.swing.JCheckBox;
29 import javax.swing.JDialog;
30 import javax.swing.JPanel;
32 import net.miginfocom.swing.MigLayout;
33 import net.sf.openrocket.document.Simulation;
34 import net.sf.openrocket.simulation.FlightDataBranch;
35 import net.sf.openrocket.simulation.FlightDataType;
36 import net.sf.openrocket.simulation.FlightEvent;
37 import net.sf.openrocket.unit.Unit;
38 import net.sf.openrocket.unit.UnitGroup;
39 import net.sf.openrocket.util.BugException;
40 import net.sf.openrocket.util.GUIUtil;
41 import net.sf.openrocket.util.MathUtil;
42 import net.sf.openrocket.util.Prefs;
44 import org.jfree.chart.ChartFactory;
45 import org.jfree.chart.ChartPanel;
46 import org.jfree.chart.JFreeChart;
47 import org.jfree.chart.annotations.XYImageAnnotation;
48 import org.jfree.chart.axis.NumberAxis;
49 import org.jfree.chart.axis.ValueAxis;
50 import org.jfree.chart.plot.Marker;
51 import org.jfree.chart.plot.PlotOrientation;
52 import org.jfree.chart.plot.ValueMarker;
53 import org.jfree.chart.plot.XYPlot;
54 import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
55 import org.jfree.chart.title.TextTitle;
56 import org.jfree.data.Range;
57 import org.jfree.data.xy.XYSeries;
58 import org.jfree.data.xy.XYSeriesCollection;
59 import org.jfree.text.TextUtilities;
60 import org.jfree.ui.LengthAdjustmentType;
61 import org.jfree.ui.RectangleAnchor;
62 import org.jfree.ui.TextAnchor;
64 public class PlotDialog extends JDialog {
66 private static final float PLOT_STROKE_WIDTH = 1.5f;
68 private static final Color DEFAULT_EVENT_COLOR = new Color(0, 0, 0);
69 private static final Map<FlightEvent.Type, Color> EVENT_COLORS =
70 new HashMap<FlightEvent.Type, Color>();
72 EVENT_COLORS.put(FlightEvent.Type.LAUNCH, new Color(255, 0, 0));
73 EVENT_COLORS.put(FlightEvent.Type.LIFTOFF, new Color(0, 80, 196));
74 EVENT_COLORS.put(FlightEvent.Type.LAUNCHROD, new Color(0, 100, 80));
75 EVENT_COLORS.put(FlightEvent.Type.IGNITION, new Color(230, 130, 15));
76 EVENT_COLORS.put(FlightEvent.Type.BURNOUT, new Color(80, 55, 40));
77 EVENT_COLORS.put(FlightEvent.Type.EJECTION_CHARGE, new Color(80, 55, 40));
78 EVENT_COLORS.put(FlightEvent.Type.STAGE_SEPARATION, new Color(80, 55, 40));
79 EVENT_COLORS.put(FlightEvent.Type.APOGEE, new Color(15, 120, 15));
80 EVENT_COLORS.put(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, new Color(0, 0, 128));
81 EVENT_COLORS.put(FlightEvent.Type.GROUND_HIT, new Color(0, 0, 0));
82 EVENT_COLORS.put(FlightEvent.Type.SIMULATION_END, new Color(128, 0, 0));
85 private static final Map<FlightEvent.Type, Image> EVENT_IMAGES =
86 new HashMap<FlightEvent.Type, Image>();
88 loadImage(FlightEvent.Type.LAUNCH, "pix/eventicons/event-launch.png");
89 loadImage(FlightEvent.Type.LIFTOFF, "pix/eventicons/event-liftoff.png");
90 loadImage(FlightEvent.Type.LAUNCHROD, "pix/eventicons/event-launchrod.png");
91 loadImage(FlightEvent.Type.IGNITION, "pix/eventicons/event-ignition.png");
92 loadImage(FlightEvent.Type.BURNOUT, "pix/eventicons/event-burnout.png");
93 loadImage(FlightEvent.Type.EJECTION_CHARGE, "pix/eventicons/event-ejection-charge.png");
94 loadImage(FlightEvent.Type.STAGE_SEPARATION,
95 "pix/eventicons/event-stage-separation.png");
96 loadImage(FlightEvent.Type.APOGEE, "pix/eventicons/event-apogee.png");
97 loadImage(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT,
98 "pix/eventicons/event-recovery-device-deployment.png");
99 loadImage(FlightEvent.Type.GROUND_HIT, "pix/eventicons/event-ground-hit.png");
100 loadImage(FlightEvent.Type.SIMULATION_END, "pix/eventicons/event-simulation-end.png");
103 private static void loadImage(FlightEvent.Type type, String file) {
106 is = ClassLoader.getSystemResourceAsStream(file);
108 System.out.println("ERROR: File " + file + " not found!");
113 Image image = ImageIO.read(is);
114 EVENT_IMAGES.put(type, image);
115 } catch (IOException ignore) {
116 ignore.printStackTrace();
123 private final List<ModifiedXYItemRenderer> renderers =
124 new ArrayList<ModifiedXYItemRenderer>();
126 private PlotDialog(Window parent, Simulation simulation, PlotConfiguration config) {
127 super(parent, "Flight data plot");
128 this.setModalityType(ModalityType.DOCUMENT_MODAL);
130 final boolean initialShowPoints = Prefs.getBoolean(Prefs.PLOT_SHOW_POINTS, false);
133 // Fill the auto-selections
134 FlightDataBranch branch = simulation.getSimulatedData().getBranch(0);
135 PlotConfiguration filled = config.fillAutoAxes(branch);
136 List<Axis> axes = filled.getAllAxes();
139 // Create the data series for both axes
140 XYSeriesCollection[] data = new XYSeriesCollection[2];
141 data[0] = new XYSeriesCollection();
142 data[1] = new XYSeriesCollection();
145 // Get the domain axis type
146 final FlightDataType domainType = filled.getDomainAxisType();
147 final Unit domainUnit = filled.getDomainAxisUnit();
148 if (domainType == null) {
149 throw new IllegalArgumentException("Domain axis type not specified.");
151 List<Double> x = branch.get(domainType);
154 // Get plot length (ignore trailing NaN's)
155 int typeCount = filled.getTypeCount();
157 for (int i = 0; i < typeCount; i++) {
158 FlightDataType type = filled.getType(i);
159 List<Double> y = branch.get(type);
161 for (int j = dataLength; j < y.size(); j++) {
162 if (!Double.isNaN(y.get(j)) && !Double.isInfinite(y.get(j)))
166 dataLength = Math.min(dataLength, x.size());
169 // Create the XYSeries objects from the flight data and store into the collections
170 String[] axisLabel = new String[2];
171 for (int i = 0; i < typeCount; i++) {
173 FlightDataType type = filled.getType(i);
174 Unit unit = filled.getUnit(i);
175 int axis = filled.getAxis(i);
176 String name = getLabel(type, unit);
178 // Store data in provided units
179 List<Double> y = branch.get(type);
180 XYSeries series = new XYSeries(name, false, true);
181 for (int j = 0; j < dataLength; j++) {
182 series.add(domainUnit.toUnit(x.get(j)), unit.toUnit(y.get(j)));
184 data[axis].addSeries(series);
187 if (axisLabel[axis] == null)
188 axisLabel[axis] = type.getName();
190 axisLabel[axis] += "; " + type.getName();
194 // Create the chart using the factory to get all default settings
195 JFreeChart chart = ChartFactory.createXYLineChart(
200 PlotOrientation.VERTICAL,
206 chart.addSubtitle(new TextTitle(config.getName()));
208 // Add the data and formatting to the plot
209 XYPlot plot = chart.getXYPlot();
211 for (int i = 0; i < 2; i++) {
212 // Check whether axis has any data
213 if (data[i].getSeriesCount() > 0) {
214 // Create and set axis
215 double min = axes.get(i).getMinValue();
216 double max = axes.get(i).getMaxValue();
217 NumberAxis axis = new PresetNumberAxis(min, max);
218 axis.setLabel(axisLabel[i]);
219 // axis.setRange(axes.get(i).getMinValue(), axes.get(i).getMaxValue());
220 plot.setRangeAxis(axisno, axis);
222 // Add data and map to the axis
223 plot.setDataset(axisno, data[i]);
224 ModifiedXYItemRenderer r = new ModifiedXYItemRenderer();
225 r.setBaseShapesVisible(initialShowPoints);
226 r.setBaseShapesFilled(true);
227 for (int j = 0; j < data[i].getSeriesCount(); j++) {
228 r.setSeriesStroke(j, new BasicStroke(PLOT_STROKE_WIDTH));
231 plot.setRenderer(axisno, r);
232 plot.mapDatasetToRangeAxis(axisno, axisno);
237 plot.getDomainAxis().setLabel(getLabel(domainType, domainUnit));
238 plot.addDomainMarker(new ValueMarker(0));
239 plot.addRangeMarker(new ValueMarker(0));
243 // Create list of events to show (combine event too close to each other)
244 ArrayList<Double> timeList = new ArrayList<Double>();
245 ArrayList<String> eventList = new ArrayList<String>();
246 ArrayList<Color> colorList = new ArrayList<Color>();
247 ArrayList<Image> imageList = new ArrayList<Image>();
249 HashSet<FlightEvent.Type> typeSet = new HashSet<FlightEvent.Type>();
251 double prevTime = -100;
256 List<FlightEvent> events = branch.getEvents();
257 for (int i = 0; i < events.size(); i++) {
258 FlightEvent event = events.get(i);
259 double t = event.getTime();
260 FlightEvent.Type type = event.getType();
262 if (type != FlightEvent.Type.ALTITUDE && config.isEventActive(type)) {
263 if (Math.abs(t - prevTime) <= 0.01) {
265 if (!typeSet.contains(type)) {
266 text = text + ", " + type.toString();
267 color = getEventColor(type);
268 image = EVENT_IMAGES.get(type);
275 timeList.add(prevTime);
277 colorList.add(color);
278 imageList.add(image);
281 text = type.toString();
282 color = getEventColor(type);
283 image = EVENT_IMAGES.get(type);
291 timeList.add(prevTime);
293 colorList.add(color);
294 imageList.add(image);
298 // Create the event markers
300 if (config.getDomainAxisType() == FlightDataType.TYPE_TIME) {
302 // Domain time is plotted as vertical markers
303 for (int i = 0; i < eventList.size(); i++) {
304 double t = timeList.get(i);
305 String event = eventList.get(i);
306 color = colorList.get(i);
308 ValueMarker m = new ValueMarker(t);
311 m.setLabelPaint(color);
313 plot.addDomainMarker(m);
318 // Other domains are plotted as image annotations
319 List<Double> time = branch.get(FlightDataType.TYPE_TIME);
320 List<Double> domain = branch.get(config.getDomainAxisType());
322 for (int i = 0; i < eventList.size(); i++) {
323 final double t = timeList.get(i);
324 String event = eventList.get(i);
325 image = imageList.get(i);
330 // Calculate index and interpolation position a
332 int tindex = Collections.binarySearch(time, t);
334 tindex = -tindex - 1;
336 if (tindex >= time.size()) {
337 // index greater than largest value in time list
338 tindex = time.size() - 1;
340 } else if (tindex <= 0) {
341 // index smaller than smallest value in time list
347 double t1 = time.get(tindex);
348 double t2 = time.get(tindex + 1);
350 if ((t1 > t) || (t2 < t)) {
351 throw new BugException("BUG: t1=" + t1 + " t2=" + t2 + " t=" + t);
354 if (MathUtil.equals(t1, t2)) {
357 a = 1 - (t - t1) / (t2 - t1);
363 xcoord = domain.get(tindex);
365 xcoord = a * domain.get(tindex) + (1 - a) * domain.get(tindex + 1);
368 for (int index = 0; index < config.getTypeCount(); index++) {
369 FlightDataType type = config.getType(index);
370 List<Double> range = branch.get(type);
374 ycoord = range.get(tindex);
376 ycoord = a * range.get(tindex) + (1 - a) * range.get(tindex + 1);
379 XYImageAnnotation annotation =
380 new XYImageAnnotation(xcoord, ycoord, image, RectangleAnchor.CENTER);
381 annotation.setToolTipText(event);
382 plot.addAnnotation(annotation);
390 JPanel panel = new JPanel(new MigLayout("fill"));
393 ChartPanel chartPanel = new ChartPanel(chart,
399 chartPanel.setMouseWheelEnabled(true);
400 chartPanel.setEnforceFileExtensions(true);
401 chartPanel.setInitialDelay(500);
403 chartPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
405 panel.add(chartPanel, "grow, wrap 20lp");
407 final JCheckBox check = new JCheckBox("Show data points");
408 check.setSelected(initialShowPoints);
409 check.addActionListener(new ActionListener() {
411 public void actionPerformed(ActionEvent e) {
412 boolean show = check.isSelected();
413 Prefs.putBoolean(Prefs.PLOT_SHOW_POINTS, show);
414 for (ModifiedXYItemRenderer r : renderers) {
415 r.setBaseShapesVisible(show);
419 panel.add(check, "split, left");
421 panel.add(new JPanel(), "growx");
423 JButton button = new JButton("Close");
424 button.addActionListener(new ActionListener() {
426 public void actionPerformed(ActionEvent e) {
427 PlotDialog.this.dispose();
430 panel.add(button, "right");
432 this.setLocationByPlatform(true);
435 GUIUtil.setDisposableDialogOptions(this, button);
439 private String getLabel(FlightDataType type, Unit unit) {
440 String name = type.getName();
441 if (unit != null && !UnitGroup.UNITS_NONE.contains(unit) &&
442 !UnitGroup.UNITS_COEFFICIENT.contains(unit) && unit.getUnit().length() > 0)
443 name += " (" + unit.getUnit() + ")";
449 private class PresetNumberAxis extends NumberAxis {
450 private final double min;
451 private final double max;
453 public PresetNumberAxis(double min, double max) {
460 protected void autoAdjustRange() {
461 this.setRange(min, max);
467 * Static method that shows a plot with the specified parameters.
469 * @param parent the parent window, which will be blocked.
470 * @param simulation the simulation to plot.
471 * @param config the configuration of the plot.
473 public static void showPlot(Window parent, Simulation simulation, PlotConfiguration config) {
474 new PlotDialog(parent, simulation, config).setVisible(true);
479 private static Color getEventColor(FlightEvent.Type type) {
480 Color c = EVENT_COLORS.get(type);
483 return DEFAULT_EVENT_COLOR;
491 * A modification to the standard renderer that renders the domain marker
492 * labels vertically instead of horizontally.
494 private static class ModifiedXYItemRenderer extends StandardXYItemRenderer {
497 public void drawDomainMarker(Graphics2D g2, XYPlot plot, ValueAxis domainAxis,
498 Marker marker, Rectangle2D dataArea) {
500 if (!(marker instanceof ValueMarker)) {
501 // Use parent for all others
502 super.drawDomainMarker(g2, plot, domainAxis, marker, dataArea);
507 * Draw the normal marker, but with rotated text.
508 * Copied from the overridden method.
510 ValueMarker vm = (ValueMarker) marker;
511 double value = vm.getValue();
512 Range range = domainAxis.getRange();
513 if (!range.contains(value)) {
517 double v = domainAxis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge());
519 PlotOrientation orientation = plot.getOrientation();
521 if (orientation == PlotOrientation.HORIZONTAL) {
522 line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v);
524 line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY());
527 final Composite originalComposite = g2.getComposite();
528 g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, marker
530 g2.setPaint(marker.getPaint());
531 g2.setStroke(marker.getStroke());
534 String label = marker.getLabel();
535 RectangleAnchor anchor = marker.getLabelAnchor();
537 Font labelFont = marker.getLabelFont();
538 g2.setFont(labelFont);
539 g2.setPaint(marker.getLabelPaint());
540 Point2D coordinates = calculateDomainMarkerTextAnchorPoint(g2,
541 orientation, dataArea, line.getBounds2D(), marker
542 .getLabelOffset(), LengthAdjustmentType.EXPAND, anchor);
545 TextAnchor textAnchor = TextAnchor.TOP_RIGHT;
546 TextUtilities.drawRotatedString(label, g2, (float) coordinates.getX() + 2,
547 (float) coordinates.getY(), textAnchor,
548 -Math.PI / 2, textAnchor);
550 g2.setComposite(originalComposite);