1 package net.sf.openrocket.gui.scalefigure;
4 import java.awt.Dimension;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.InputEvent;
9 import java.awt.event.MouseEvent;
10 import java.util.ArrayList;
11 import java.util.Collection;
12 import java.util.List;
13 import java.util.concurrent.Executor;
14 import java.util.concurrent.Executors;
15 import java.util.concurrent.ThreadFactory;
17 import javax.swing.AbstractAction;
18 import javax.swing.Action;
19 import javax.swing.JComboBox;
20 import javax.swing.JLabel;
21 import javax.swing.JPanel;
22 import javax.swing.JSlider;
23 import javax.swing.JToggleButton;
24 import javax.swing.JViewport;
25 import javax.swing.SwingUtilities;
26 import javax.swing.event.ChangeEvent;
27 import javax.swing.event.ChangeListener;
28 import javax.swing.event.TreeSelectionEvent;
29 import javax.swing.event.TreeSelectionListener;
30 import javax.swing.tree.TreePath;
31 import javax.swing.tree.TreeSelectionModel;
33 import net.miginfocom.swing.MigLayout;
34 import net.sf.openrocket.aerodynamics.AerodynamicCalculator;
35 import net.sf.openrocket.aerodynamics.BarrowmanCalculator;
36 import net.sf.openrocket.aerodynamics.FlightConditions;
37 import net.sf.openrocket.aerodynamics.WarningSet;
38 import net.sf.openrocket.document.OpenRocketDocument;
39 import net.sf.openrocket.document.Simulation;
40 import net.sf.openrocket.gui.adaptors.DoubleModel;
41 import net.sf.openrocket.gui.adaptors.MotorConfigurationModel;
42 import net.sf.openrocket.gui.components.BasicSlider;
43 import net.sf.openrocket.gui.components.StageSelector;
44 import net.sf.openrocket.gui.components.UnitSelector;
45 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
46 import net.sf.openrocket.gui.figureelements.CGCaret;
47 import net.sf.openrocket.gui.figureelements.CPCaret;
48 import net.sf.openrocket.gui.figureelements.Caret;
49 import net.sf.openrocket.gui.figureelements.RocketInfo;
50 import net.sf.openrocket.gui.main.SimulationWorker;
51 import net.sf.openrocket.gui.main.componenttree.ComponentTreeModel;
52 import net.sf.openrocket.l10n.Translator;
53 import net.sf.openrocket.masscalc.BasicMassCalculator;
54 import net.sf.openrocket.masscalc.MassCalculator;
55 import net.sf.openrocket.masscalc.MassCalculator.MassCalcType;
56 import net.sf.openrocket.rocketcomponent.Configuration;
57 import net.sf.openrocket.rocketcomponent.Rocket;
58 import net.sf.openrocket.rocketcomponent.RocketComponent;
59 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
60 import net.sf.openrocket.simulation.FlightData;
61 import net.sf.openrocket.simulation.listeners.SimulationListener;
62 import net.sf.openrocket.simulation.listeners.system.ApogeeEndListener;
63 import net.sf.openrocket.simulation.listeners.system.InterruptListener;
64 import net.sf.openrocket.startup.Application;
65 import net.sf.openrocket.unit.UnitGroup;
66 import net.sf.openrocket.util.ChangeSource;
67 import net.sf.openrocket.util.Chars;
68 import net.sf.openrocket.util.Coordinate;
69 import net.sf.openrocket.util.MathUtil;
70 import net.sf.openrocket.util.Prefs;
73 * A JPanel that contains a RocketFigure and buttons to manipulate the figure.
75 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
77 public class RocketPanel extends JPanel implements TreeSelectionListener, ChangeSource {
79 private static final Translator trans = Application.getTranslator();
80 private final RocketFigure figure;
81 private final ScaleScrollPane scrollPane;
83 private JLabel infoMessage;
85 private TreeSelectionModel selectionModel = null;
88 /* Calculation of CP and CG */
89 private AerodynamicCalculator aerodynamicCalculator;
90 private MassCalculator massCalculator;
93 private final OpenRocketDocument document;
94 private final Configuration configuration;
96 private Caret extraCP = null;
97 private Caret extraCG = null;
98 private RocketInfo extraText = null;
101 private double cpAOA = Double.NaN;
102 private double cpTheta = Double.NaN;
103 private double cpMach = Double.NaN;
104 private double cpRoll = Double.NaN;
106 // The functional ID of the rocket that was simulated
107 private int flightDataFunctionalID = -1;
108 private String flightDataMotorID = null;
111 private SimulationWorker backgroundSimulationWorker = null;
112 private boolean dirty = false;
114 private List<ChangeListener> listeners = new ArrayList<ChangeListener>();
118 * The executor service used for running the background simulations.
119 * This uses a fixed-sized thread pool for all background simulations
120 * with all threads in daemon mode and with minimum priority.
122 private static final Executor backgroundSimulationExecutor;
124 backgroundSimulationExecutor = Executors.newFixedThreadPool(Prefs.getMaxThreadCount(),
125 new ThreadFactory() {
126 private ThreadFactory factory = Executors.defaultThreadFactory();
129 public Thread newThread(Runnable r) {
130 Thread t = factory.newThread(r);
132 t.setPriority(Thread.MIN_PRIORITY);
139 public RocketPanel(OpenRocketDocument document) {
141 this.document = document;
142 configuration = document.getDefaultConfiguration();
144 // TODO: FUTURE: calculator selection
145 aerodynamicCalculator = new BarrowmanCalculator();
146 massCalculator = new BasicMassCalculator();
148 // Create figure and custom scroll pane
149 figure = new RocketFigure(configuration);
151 scrollPane = new ScaleScrollPane(figure) {
153 public void mouseClicked(MouseEvent event) {
154 handleMouseClick(event);
157 scrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
158 scrollPane.setFitting(true);
162 configuration.addChangeListener(new ChangeListener() {
164 public void stateChanged(ChangeEvent e) {
165 System.out.println("Configuration changed, calling updateFigure");
167 figure.updateFigure();
174 * Creates the layout and components of the panel.
176 private void createPanel() {
177 setLayout(new MigLayout("", "[shrink][grow]", "[shrink][shrink][grow][shrink]"));
179 setPreferredSize(new Dimension(800, 300));
185 FigureTypeAction action = new FigureTypeAction(RocketFigure.TYPE_SIDE);
187 action.putValue(Action.NAME, trans.get("RocketPanel.FigTypeAct.Sideview"));
189 action.putValue(Action.SHORT_DESCRIPTION, trans.get("RocketPanel.FigTypeAct.ttip.Sideview"));
190 JToggleButton toggle = new JToggleButton(action);
191 add(toggle, "spanx, split");
193 action = new FigureTypeAction(RocketFigure.TYPE_BACK);
195 action.putValue(Action.NAME, trans.get("RocketPanel.FigTypeAct.Backview"));
197 action.putValue(Action.SHORT_DESCRIPTION, trans.get("RocketPanel.FigTypeAct.ttip.Backview"));
198 toggle = new JToggleButton(action);
199 add(toggle, "gap rel");
202 // Zoom level selector
203 ScaleSelector scaleSelector = new ScaleSelector(scrollPane);
209 StageSelector stageSelector = new StageSelector(configuration);
210 add(stageSelector, "");
214 // Motor configuration selector
215 //// Motor configuration:
216 JLabel label = new JLabel(trans.get("RocketPanel.lbl.Motorcfg"));
217 label.setHorizontalAlignment(JLabel.RIGHT);
218 add(label, "growx, right");
219 add(new JComboBox(new MotorConfigurationModel(configuration)), "wrap");
225 // Create slider and scroll pane
227 DoubleModel theta = new DoubleModel(figure, "Rotation",
228 UnitGroup.UNITS_ANGLE, 0, 2 * Math.PI);
229 UnitSelector us = new UnitSelector(theta, true);
230 us.setHorizontalAlignment(JLabel.CENTER);
231 add(us, "alignx 50%, growx");
233 // Add the rocket figure
234 add(scrollPane, "grow, spany 2, wmin 300lp, hmin 100lp, wrap");
237 // Add rotation slider
238 // Minimum size to fit "360deg"
239 JLabel l = new JLabel("360" + Chars.DEGREE);
240 Dimension d = l.getPreferredSize();
242 add(new BasicSlider(theta.getSliderModel(0, 2 * Math.PI), JSlider.VERTICAL, true),
243 "ax 50%, wrap, width " + (d.width + 6) + "px:null:null, growy");
246 //// <html>Click to select Shift+click to select other Double-click to edit Click+drag to move
247 infoMessage = new JLabel(trans.get("RocketPanel.lbl.infoMessage"));
248 infoMessage.setFont(new Font("Sans Serif", Font.PLAIN, 9));
249 add(infoMessage, "skip, span, gapleft 25, wrap");
257 public RocketFigure getFigure() {
261 public AerodynamicCalculator getAerodynamicCalculator() {
262 return aerodynamicCalculator;
265 public Configuration getConfiguration() {
266 return configuration;
270 * Get the center of pressure figure element.
272 * @return center of pressure info
274 public Caret getExtraCP() {
279 * Get the center of gravity figure element.
281 * @return center of gravity info
283 public Caret getExtraCG() {
288 * Get the extra text figure element.
290 * @return extra text that contains info about the rocket design
292 public RocketInfo getExtraText() {
296 public void setSelectionModel(TreeSelectionModel m) {
297 if (selectionModel != null) {
298 selectionModel.removeTreeSelectionListener(this);
301 selectionModel.addTreeSelectionListener(this);
302 valueChanged((TreeSelectionEvent) null); // updates FigureParameters
308 * Return the angle of attack used in CP calculation. NaN signifies the default value
310 * @return the angle of attack used, or NaN.
312 public double getCPAOA() {
317 * Set the angle of attack to be used in CP calculation. A value of NaN signifies that
318 * the default AOA (zero) should be used.
319 * @param aoa the angle of attack to use, or NaN
321 public void setCPAOA(double aoa) {
322 if (MathUtil.equals(aoa, cpAOA) ||
323 (Double.isNaN(aoa) && Double.isNaN(cpAOA)))
327 figure.updateFigure();
331 public double getCPTheta() {
335 public void setCPTheta(double theta) {
336 if (MathUtil.equals(theta, cpTheta) ||
337 (Double.isNaN(theta) && Double.isNaN(cpTheta)))
340 if (!Double.isNaN(theta))
341 figure.setRotation(theta);
343 figure.updateFigure();
347 public double getCPMach() {
351 public void setCPMach(double mach) {
352 if (MathUtil.equals(mach, cpMach) ||
353 (Double.isNaN(mach) && Double.isNaN(cpMach)))
357 figure.updateFigure();
361 public double getCPRoll() {
365 public void setCPRoll(double roll) {
366 if (MathUtil.equals(roll, cpRoll) ||
367 (Double.isNaN(roll) && Double.isNaN(cpRoll)))
371 figure.updateFigure();
378 public void addChangeListener(ChangeListener listener) {
379 listeners.add(0, listener);
383 public void removeChangeListener(ChangeListener listener) {
384 listeners.remove(listener);
387 protected void fireChangeEvent() {
388 ChangeEvent e = new ChangeEvent(this);
389 ChangeListener[] list = listeners.toArray(new ChangeListener[0]);
390 for (ChangeListener l : list) {
399 * Handle clicking on figure shapes. The functioning is the following:
401 * Get the components clicked.
402 * If no component is clicked, do nothing.
403 * If the currently selected component is in the set, keep it,
404 * unless the selector specified is pressed. If it is pressed, cycle to
405 * the next component. Otherwise select the first component in the list.
407 public static final int CYCLE_SELECTION_MODIFIER = InputEvent.SHIFT_DOWN_MASK;
409 private void handleMouseClick(MouseEvent event) {
410 if (event.getButton() != MouseEvent.BUTTON1)
412 Point p0 = event.getPoint();
413 Point p1 = scrollPane.getViewport().getViewPosition();
417 RocketComponent[] clicked = figure.getComponentsByPoint(x, y);
419 // If no component is clicked, do nothing
420 if (clicked.length == 0)
423 // Check whether the currently selected component is in the clicked components.
424 TreePath path = selectionModel.getSelectionPath();
426 RocketComponent current = (RocketComponent) path.getLastPathComponent();
428 for (int i = 0; i < clicked.length; i++) {
429 if (clicked[i] == current) {
430 if (event.isShiftDown() && (event.getClickCount() == 1)) {
431 path = ComponentTreeModel.makeTreePath(clicked[(i + 1) % clicked.length]);
433 path = ComponentTreeModel.makeTreePath(clicked[i]);
440 // Currently selected component not clicked
442 if (event.isShiftDown() && event.getClickCount() == 1 && clicked.length > 1) {
443 path = ComponentTreeModel.makeTreePath(clicked[1]);
445 path = ComponentTreeModel.makeTreePath(clicked[0]);
449 // Set selection and check for double-click
450 selectionModel.setSelectionPath(path);
451 if (event.getClickCount() == 2) {
452 RocketComponent component = (RocketComponent) path.getLastPathComponent();
454 ComponentConfigDialog.showDialog(SwingUtilities.getWindowAncestor(this),
455 document, component);
463 * Updates the extra data included in the figure. Currently this includes
464 * the CP and CG carets.
466 private WarningSet warnings = new WarningSet();
468 private void updateExtras() {
472 // TODO: MEDIUM: User-definable conditions
473 FlightConditions conditions = new FlightConditions(configuration);
476 if (!Double.isNaN(cpMach)) {
477 conditions.setMach(cpMach);
478 extraText.setMach(cpMach);
480 conditions.setMach(Prefs.getDefaultMach());
481 extraText.setMach(Prefs.getDefaultMach());
484 if (!Double.isNaN(cpAOA)) {
485 conditions.setAOA(cpAOA);
487 conditions.setAOA(0);
489 extraText.setAOA(cpAOA);
491 if (!Double.isNaN(cpRoll)) {
492 conditions.setRollRate(cpRoll);
494 conditions.setRollRate(0);
497 if (!Double.isNaN(cpTheta)) {
498 conditions.setTheta(cpTheta);
499 cp = aerodynamicCalculator.getCP(configuration, conditions, warnings);
501 cp = aerodynamicCalculator.getWorstCP(configuration, conditions, warnings);
503 extraText.setTheta(cpTheta);
506 cg = massCalculator.getCG(configuration, MassCalcType.LAUNCH_MASS);
507 // System.out.println("CG computed as "+cg+ " CP as "+cp);
509 if (cp.weight > 0.000001)
514 if (cg.weight > 0.000001)
519 // Length bound is assumed to be tight
520 double length = 0, diameter = 0;
521 Collection<Coordinate> bounds = configuration.getBounds();
522 if (!bounds.isEmpty()) {
523 double minX = Double.POSITIVE_INFINITY, maxX = Double.NEGATIVE_INFINITY;
524 for (Coordinate c : bounds) {
530 length = maxX - minX;
533 for (RocketComponent c : configuration) {
534 if (c instanceof SymmetricComponent) {
535 double d1 = ((SymmetricComponent) c).getForeRadius() * 2;
536 double d2 = ((SymmetricComponent) c).getAftRadius() * 2;
537 diameter = MathUtil.max(diameter, d1, d2);
541 extraText.setCG(cgx);
542 extraText.setCP(cpx);
543 extraText.setLength(length);
544 extraText.setDiameter(diameter);
545 extraText.setMass(cg.weight);
546 extraText.setWarnings(warnings);
549 if (figure.getType() == RocketFigure.TYPE_SIDE && length > 0) {
551 // TODO: LOW: Y-coordinate and rotation
552 extraCP.setPosition(cpx * RocketFigure.EXTRA_SCALE, 0);
553 extraCG.setPosition(cgx * RocketFigure.EXTRA_SCALE, 0);
557 extraCP.setPosition(Double.NaN, Double.NaN);
558 extraCG.setPosition(Double.NaN, Double.NaN);
563 //////// Flight simulation in background
565 // Check whether to compute or not
566 if (!Prefs.computeFlightInBackground()) {
567 extraText.setFlightData(null);
568 extraText.setCalculatingData(false);
569 stopBackgroundSimulation();
573 // Check whether data is already up to date
574 if (flightDataFunctionalID == configuration.getRocket().getFunctionalModID() &&
575 flightDataMotorID == configuration.getMotorConfigurationID()) {
579 flightDataFunctionalID = configuration.getRocket().getFunctionalModID();
580 flightDataMotorID = configuration.getMotorConfigurationID();
582 // Stop previous computation (if any)
583 stopBackgroundSimulation();
585 // Check that configuration has motors
586 if (!configuration.hasMotors()) {
587 extraText.setFlightData(FlightData.NaN_DATA);
588 extraText.setCalculatingData(false);
592 // Start calculation process
593 extraText.setCalculatingData(true);
595 Rocket duplicate = (Rocket) configuration.getRocket().copy();
596 Simulation simulation = Prefs.getBackgroundSimulation(duplicate);
597 simulation.getOptions().setMotorConfigurationID(
598 configuration.getMotorConfigurationID());
600 backgroundSimulationWorker = new BackgroundSimulationWorker(simulation);
601 backgroundSimulationExecutor.execute(backgroundSimulationWorker);
605 * Cancels the current background simulation worker, if any.
607 private void stopBackgroundSimulation() {
608 if (backgroundSimulationWorker != null) {
609 backgroundSimulationWorker.cancel(true);
610 backgroundSimulationWorker = null;
616 * A SimulationWorker that simulates the rocket flight in the background and
617 * sets the results to the extra text when finished. The worker can be cancelled
620 private class BackgroundSimulationWorker extends SimulationWorker {
622 public BackgroundSimulationWorker(Simulation sim) {
627 protected FlightData doInBackground() {
629 // Pause a little while to allow faster UI reaction
632 } catch (InterruptedException ignore) {
634 if (isCancelled() || backgroundSimulationWorker != this)
637 return super.doInBackground();
641 protected void simulationDone() {
642 // Do nothing if cancelled
643 if (isCancelled() || backgroundSimulationWorker != this)
646 backgroundSimulationWorker = null;
647 extraText.setFlightData(simulation.getSimulatedData());
648 extraText.setCalculatingData(false);
653 protected SimulationListener[] getExtraListeners() {
654 return new SimulationListener[] {
655 InterruptListener.INSTANCE,
656 ApogeeEndListener.INSTANCE };
660 protected void simulationInterrupted(Throwable t) {
661 // Do nothing on cancel, set N/A data otherwise
662 if (isCancelled() || backgroundSimulationWorker != this) // Double-check
665 backgroundSimulationWorker = null;
666 extraText.setFlightData(FlightData.NaN_DATA);
667 extraText.setCalculatingData(false);
675 * Adds the extra data to the figure. Currently this includes the CP and CG carets.
677 private void addExtras() {
678 figure.clearRelativeExtra();
679 extraCG = new CGCaret(0, 0);
680 extraCP = new CPCaret(0, 0);
681 extraText = new RocketInfo(configuration);
683 figure.addRelativeExtra(extraCP);
684 figure.addRelativeExtra(extraCG);
685 figure.addAbsoluteExtra(extraText);
690 * Updates the selection in the FigureParameters and repaints the figure.
691 * Ignores the event itself.
694 public void valueChanged(TreeSelectionEvent e) {
695 TreePath[] paths = selectionModel.getSelectionPaths();
697 figure.setSelection(null);
701 RocketComponent[] components = new RocketComponent[paths.length];
702 for (int i = 0; i < paths.length; i++)
703 components[i] = (RocketComponent) paths[i].getLastPathComponent();
704 figure.setSelection(components);
710 * An <code>Action</code> that shows whether the figure type is the type
711 * given in the constructor.
713 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
715 private class FigureTypeAction extends AbstractAction implements ChangeListener {
716 private final int type;
718 public FigureTypeAction(int type) {
721 figure.addChangeListener(this);
725 public void actionPerformed(ActionEvent e) {
726 boolean state = (Boolean) getValue(Action.SELECTED_KEY);
728 // This view has been selected
729 figure.setType(type);
736 public void stateChanged(ChangeEvent e) {
737 putValue(Action.SELECTED_KEY, figure.getType() == type);