Merge pull request #952 from SiboVG/issue-927

[fixes #927 & #771] Fix auto-run simulation NA values
This commit is contained in:
Joe Pfeiffer 2021-09-28 14:40:13 -06:00 committed by GitHub
commit a513c676de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 325 additions and 107 deletions

View File

@ -810,7 +810,7 @@ public class OpenRocketDocument implements ComponentChangeListener {
listeners.remove(listener);
}
protected void fireDocumentChangeEvent(DocumentChangeEvent event) {
public void fireDocumentChangeEvent(DocumentChangeEvent event) {
DocumentChangeListener[] array = listeners.toArray(new DocumentChangeListener[0]);
for (DocumentChangeListener l : array) {
l.documentChanged(event);

View File

@ -18,10 +18,20 @@ public abstract class InterpolatingAtmosphericModel implements AtmosphericModel
if (levels == null)
computeLayers();
if (altitude <= 0)
if (altitude <= 0) {
// TODO: LOW: levels[0] returned null in some cases, see GitHub issue #952 for more information
if (levels[0] == null) {
computeLayers();
}
return levels[0];
if (altitude >= DELTA * (levels.length - 1))
}
if (altitude >= DELTA * (levels.length - 1)) {
// TODO: LOW: levels[levels.length - 1] returned null in some cases, see GitHub issue #952 for more information
if (levels[levels.length - 1] == null) {
computeLayers();
}
return levels[levels.length - 1];
}
int n = (int) (altitude / DELTA);
double d = (altitude - n * DELTA) / DELTA;

View File

@ -115,6 +115,8 @@ public class MotorConfiguration implements FlightConfigurableParameter<MotorConf
public void useDefaultIgnition() {
this.ignitionOveride = false;
setIgnitionDelay(0);
setIgnitionEvent(IgnitionEvent.AUTOMATIC);
}
public double getIgnitionDelay() {

View File

@ -8,6 +8,8 @@ import net.sf.openrocket.unit.UnitGroup;
import net.sf.openrocket.util.MathUtil;
import net.sf.openrocket.util.Pair;
import java.util.Objects;
public class DeploymentConfiguration implements FlightConfigurableParameter<DeploymentConfiguration> {
@ -154,5 +156,17 @@ public class DeploymentConfiguration implements FlightConfigurableParameter<Depl
@Override
public void update(){
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeploymentConfiguration that = (DeploymentConfiguration) o;
return Double.compare(that.deployAltitude, deployAltitude) == 0 && Double.compare(that.deployDelay, deployDelay) == 0 && deployEvent == that.deployEvent;
}
@Override
public int hashCode() {
return Objects.hash(deployEvent, deployAltitude, deployDelay);
}
}

View File

@ -5,6 +5,8 @@ import net.sf.openrocket.simulation.FlightEvent;
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.util.MathUtil;
import java.util.Objects;
public class StageSeparationConfiguration implements FlightConfigurableParameter<StageSeparationConfiguration> {
public static enum SeparationEvent {
@ -144,8 +146,20 @@ public class StageSeparationConfiguration implements FlightConfigurableParameter
clone.separationDelay = this.separationDelay;
return clone;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
StageSeparationConfiguration that = (StageSeparationConfiguration) o;
return Double.compare(that.separationDelay, separationDelay) == 0 && separationEvent == that.separationEvent;
}
@Override
public int hashCode() {
return Objects.hash(separationEvent, separationDelay);
}
private void fireChangeEvent() {
}

View File

@ -259,7 +259,7 @@ public class BasicEventSimulationEngine implements SimulationEngine {
private boolean handleEvents() throws SimulationException {
boolean ret = true;
FlightEvent event;
log.trace("HandleEvents: current branch = " + currentStatus.getFlightData().getBranchName());
for (event = nextEvent(); event != null; event = nextEvent()) {
log.trace("Obtained event from queue: " + event.toString());
@ -300,7 +300,7 @@ public class BasicEventSimulationEngine implements SimulationEngine {
// Ignore events for components that are no longer attached to the rocket
if (event.getSource() != null && event.getSource().getParent() != null &&
!currentStatus.getConfiguration().isComponentActive(event.getSource())) {
log.trace("Ignoring event from unattached componenent");
log.trace("Ignoring event from unattached component");
continue;
}
@ -332,6 +332,7 @@ public class BasicEventSimulationEngine implements SimulationEngine {
// Check for recovery device deployment, add events to queue
// TODO: LOW: check if deprecated function getActiveComponents needs to be replaced
for (RocketComponent c : currentStatus.getConfiguration().getActiveComponents()) {
if (!(c instanceof RecoveryDevice))
continue;
@ -532,7 +533,8 @@ public class BasicEventSimulationEngine implements SimulationEngine {
}
}
// TODO : FUTURE : do not hard code the 1200 (maybe even make it configurable by the user)
if( 1200 < currentStatus.getSimulationTime() ){
ret = false;
log.error("Simulation hit max time (1200s): aborting.");

View File

@ -220,7 +220,7 @@ public class FlightData {
timeToApogee = Double.NaN;
// Launch rod velocity
// Launch rod velocity + deployment velocity + ground hit velocity
for (FlightEvent event : branch.getEvents()) {
if (event.getType() == FlightEvent.Type.LAUNCHROD) {
double t = event.getTime();

View File

@ -0,0 +1,29 @@
package net.sf.openrocket.simulation.listeners.system;
import net.sf.openrocket.simulation.FlightEvent;
import net.sf.openrocket.simulation.SimulationStatus;
import net.sf.openrocket.simulation.listeners.AbstractSimulationListener;
/**
* A simulation listeners that ends the simulation when the ground is hit.
*
* @author Sibo Van Gool <sibo.vangool@hotmail.com>
*/
public class GroundHitListener extends AbstractSimulationListener {
public static final GroundHitListener INSTANCE = new GroundHitListener();
@Override
public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) {
if (event.getType() == FlightEvent.Type.GROUND_HIT) {
status.getEventQueue().add(new FlightEvent(FlightEvent.Type.SIMULATION_END, status.getSimulationTime()));
}
return true;
}
@Override
public boolean isSystemListener() {
return true;
}
}

View File

@ -221,7 +221,7 @@ public class BasicFrame extends JFrame {
// Bottom segment, rocket figure
rocketpanel = new RocketPanel(document);
rocketpanel = new RocketPanel(document, this);
vertical.setBottomComponent(rocketpanel);
rocketpanel.setSelectionModel(tree.getSelectionModel());
@ -1099,6 +1099,9 @@ public class BasicFrame extends JFrame {
tabbedPane.setSelectedIndex(tab);
}
public int getSelectedTab() {
return tabbedPane.getSelectedIndex();
}
private void openAction() {

View File

@ -576,7 +576,7 @@ public class SimulationPanel extends JPanel {
public void documentChanged(DocumentChangeEvent event) {
if (!(event instanceof SimulationChangeEvent))
return;
simulationTableModel.fireTableDataChanged();
fireMaintainSelection();
}
});

View File

@ -54,10 +54,14 @@ public abstract class FlightConfigurablePanel<T extends FlightConfigurableCompon
synchronizeConfigurationSelection();
}
public void fireTableDataChanged() {
/**
* Update the data in the table, with component change event type {cce}
* @param cce index of the ComponentChangeEvent to use (e.g. ComponentChangeEvent.NONFUNCTIONAL_CHANGE)
*/
public void fireTableDataChanged(int cce) {
int selectedRow = table.getSelectedRow();
int selectedColumn = table.getSelectedColumn();
this.rocket.fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
this.rocket.fireComponentChangeEvent(cce);
((AbstractTableModel)table.getModel()).fireTableDataChanged();
restoreSelection(selectedRow,selectedColumn);
updateButtonState();

View File

@ -15,6 +15,7 @@ import net.sf.openrocket.document.Simulation;
import net.sf.openrocket.gui.dialogs.flightconfiguration.RenameConfigDialog;
import net.sf.openrocket.gui.main.BasicFrame;
import net.sf.openrocket.l10n.Translator;
import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
import net.sf.openrocket.rocketcomponent.FlightConfigurableComponent;
import net.sf.openrocket.rocketcomponent.FlightConfiguration;
import net.sf.openrocket.rocketcomponent.FlightConfigurationId;
@ -79,7 +80,7 @@ public class FlightConfigurationPanel extends JPanel implements StateChangeListe
int lastCol = motorConfigurationPanel.table.getColumnCount() - 1;
motorConfigurationPanel.table.setRowSelectionInterval(lastRow, lastRow);
motorConfigurationPanel.table.setColumnSelectionInterval(lastCol, lastCol);
configurationChanged();
configurationChanged(ComponentChangeEvent.MOTOR_CHANGE);
}
});
@ -91,7 +92,7 @@ public class FlightConfigurationPanel extends JPanel implements StateChangeListe
@Override
public void actionPerformed(ActionEvent e) {
renameConfiguration();
configurationChanged();
configurationChanged(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
}
});
this.add(renameConfButton,"gapright para");
@ -101,7 +102,7 @@ public class FlightConfigurationPanel extends JPanel implements StateChangeListe
@Override
public void actionPerformed(ActionEvent e) {
removeConfiguration();
configurationChanged();
configurationChanged(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
}
});
this.add(removeConfButton,"gapright para");
@ -111,7 +112,7 @@ public class FlightConfigurationPanel extends JPanel implements StateChangeListe
@Override
public void actionPerformed(ActionEvent e) {
addOrCopyConfiguration(true);
configurationChanged();
configurationChanged(ComponentChangeEvent.MOTOR_CHANGE);
}
});
this.add(copyConfButton, "wrap");
@ -172,13 +173,13 @@ public class FlightConfigurationPanel extends JPanel implements StateChangeListe
if (currentId == null)
return;
document.removeFlightConfigurationAndSimulations(currentId);
configurationChanged();
configurationChanged(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
}
private void configurationChanged() {
motorConfigurationPanel.fireTableDataChanged();
recoveryConfigurationPanel.fireTableDataChanged();
separationConfigurationPanel.fireTableDataChanged();
private void configurationChanged(int cce) {
motorConfigurationPanel.fireTableDataChanged(cce);
recoveryConfigurationPanel.fireTableDataChanged(cce);
separationConfigurationPanel.fireTableDataChanged(cce);
}
private void updateButtonState() {

View File

@ -29,10 +29,12 @@ import net.sf.openrocket.gui.widgets.SelectColorButton;
import net.sf.openrocket.motor.IgnitionEvent;
import net.sf.openrocket.motor.Motor;
import net.sf.openrocket.motor.MotorConfiguration;
import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
import net.sf.openrocket.rocketcomponent.FlightConfiguration;
import net.sf.openrocket.rocketcomponent.FlightConfigurationId;
import net.sf.openrocket.rocketcomponent.MotorMount;
import net.sf.openrocket.rocketcomponent.Rocket;
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.unit.UnitGroup;
import net.sf.openrocket.util.Chars;
@ -201,20 +203,25 @@ public class MotorConfigurationPanel extends FlightConfigurablePanel<MotorMount>
throw new IllegalStateException("Attempting to set a motor on the default FCID.");
}
double initDelay = curMount.getMotorConfig(fcid).getEjectionDelay();
motorChooserDialog.setMotorMountAndConfig( fcid, curMount );
motorChooserDialog.setVisible(true);
Motor mtr = motorChooserDialog.getSelectedMotor();
double d = motorChooserDialog.getSelectedDelay();
if (mtr != null) {
if (mtr == curMount.getMotorConfig(fcid).getMotor() && d == initDelay) {
return;
}
final MotorConfiguration templateConfig = curMount.getMotorConfig(fcid);
final MotorConfiguration newConfig = new MotorConfiguration( curMount, fcid, templateConfig);
newConfig.setMotor(mtr);
newConfig.setEjectionDelay(d);
curMount.setMotorConfig( newConfig, fcid);
}
fireTableDataChanged();
fireTableDataChanged(ComponentChangeEvent.MOTOR_CHANGE);
}
}
private void removeMotor() {
@ -226,24 +233,30 @@ public class MotorConfigurationPanel extends FlightConfigurablePanel<MotorMount>
curMount.setMotorConfig( null, fcid);
fireTableDataChanged();
fireTableDataChanged(ComponentChangeEvent.MOTOR_CHANGE);
}
private void selectIgnition() {
MotorMount curMount = getSelectedComponent();
FlightConfigurationId fcid= getSelectedConfigurationId();
if ( (null == fcid )||( null == curMount )){
return;
}
MotorMount curMount = getSelectedComponent();
FlightConfigurationId fcid = getSelectedConfigurationId();
if ((null == fcid) || (null == curMount)) {
return;
}
MotorConfiguration curInstance = curMount.getMotorConfig(fcid);
IgnitionEvent initialIgnitionEvent = curInstance.getIgnitionEvent();
double initialIgnitionDelay = curInstance.getIgnitionDelay();
// this call also performs the update changes
IgnitionSelectionDialog ignitionDialog = new IgnitionSelectionDialog(
SwingUtilities.getWindowAncestor(this.flightConfigurationPanel),
fcid,
curMount);
ignitionDialog.setVisible(true);
fireTableDataChanged();
if (!initialIgnitionEvent.equals(curInstance.getIgnitionEvent()) || (initialIgnitionDelay != curInstance.getIgnitionDelay())) {
fireTableDataChanged(ComponentChangeEvent.MOTOR_CHANGE);
}
}
@ -254,10 +267,14 @@ public class MotorConfigurationPanel extends FlightConfigurablePanel<MotorMount>
return;
}
MotorConfiguration curInstance = curMount.getMotorConfig(fcid);
IgnitionEvent initialIgnitionEvent = curInstance.getIgnitionEvent();
double initialIgnitionDelay = curInstance.getIgnitionDelay();
curInstance.useDefaultIgnition();
fireTableDataChanged();
if (!initialIgnitionEvent.equals(curInstance.getIgnitionEvent()) || (initialIgnitionDelay != curInstance.getIgnitionDelay())) {
fireTableDataChanged(ComponentChangeEvent.MOTOR_CHANGE);
}
}

View File

@ -99,22 +99,31 @@ public class RecoveryConfigurationPanel extends FlightConfigurablePanel<Recovery
private void selectDeployment() {
RecoveryDevice c = getSelectedComponent();
if (c == null) {
FlightConfigurationId fcid = getSelectedConfigurationId();
if ((c == null) || (fcid == null)) {
return;
}
DeploymentConfiguration initialConfig = c.getDeploymentConfigurations().get(fcid).copy(fcid);
JDialog d = new DeploymentSelectionDialog(SwingUtilities.getWindowAncestor(this), rocket, c);
d.setVisible(true);
fireTableDataChanged();
if (!initialConfig.equals(c.getDeploymentConfigurations().get(fcid))) {
fireTableDataChanged(ComponentChangeEvent.AERODYNAMIC_CHANGE);
}
}
private void resetDeployment() {
RecoveryDevice c = getSelectedComponent();
if (c == null) {
FlightConfigurationId fcid = getSelectedConfigurationId();
if ((c == null) || (fcid == null)) {
return;
}
DeploymentConfiguration initialConfig = c.getDeploymentConfigurations().get(fcid).copy(fcid);
FlightConfigurationId id = rocket.getSelectedConfiguration().getFlightConfigurationID();
c.getDeploymentConfigurations().reset(id);
fireTableDataChanged();
if (!initialConfig.equals(c.getDeploymentConfigurations().get(fcid))) {
fireTableDataChanged(ComponentChangeEvent.AERODYNAMIC_CHANGE);
}
}
public void updateButtonState() {

View File

@ -17,6 +17,7 @@ import net.sf.openrocket.formatting.RocketDescriptor;
import net.sf.openrocket.gui.dialogs.flightconfiguration.SeparationSelectionDialog;
import net.sf.openrocket.l10n.Translator;
import net.sf.openrocket.rocketcomponent.AxialStage;
import net.sf.openrocket.rocketcomponent.ComponentChangeEvent;
import net.sf.openrocket.rocketcomponent.FlightConfigurationId;
import net.sf.openrocket.rocketcomponent.Rocket;
import net.sf.openrocket.rocketcomponent.StageSeparationConfiguration;
@ -46,7 +47,7 @@ public class SeparationConfigurationPanel extends FlightConfigurablePanel<AxialS
selectSeparationButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectDeployment();
selectSeparation();
}
});
this.add(selectSeparationButton, "split, align right, sizegroup button");
@ -57,7 +58,7 @@ public class SeparationConfigurationPanel extends FlightConfigurablePanel<AxialS
resetDeploymentButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resetDeployment();
resetSeparation();
}
});
this.add(resetDeploymentButton, "sizegroup button, wrap");
@ -86,7 +87,7 @@ public class SeparationConfigurationPanel extends FlightConfigurablePanel<AxialS
updateButtonState();
if (e.getClickCount() == 2) {
// Double-click edits
selectDeployment();
selectSeparation();
}
}
});
@ -95,27 +96,35 @@ public class SeparationConfigurationPanel extends FlightConfigurablePanel<AxialS
return separationTable;
}
private void selectDeployment() {
private void selectSeparation() {
AxialStage stage = getSelectedComponent();
if (stage == null) {
FlightConfigurationId fcid = getSelectedConfigurationId();
if ((stage == null) || (fcid == null)) {
return;
}
StageSeparationConfiguration initialConfig = stage.getSeparationConfigurations().get(fcid).copy(fcid);
JDialog d = new SeparationSelectionDialog(SwingUtilities.getWindowAncestor(this), rocket, stage);
d.setVisible(true);
fireTableDataChanged();
if (!initialConfig.equals(stage.getSeparationConfigurations().get(fcid))) {
fireTableDataChanged(ComponentChangeEvent.AEROMASS_CHANGE);
}
}
private void resetDeployment() {
private void resetSeparation() {
AxialStage stage = getSelectedComponent();
if (stage == null) {
FlightConfigurationId fcid = getSelectedConfigurationId();
if ((stage == null) || (fcid == null)) {
return;
}
StageSeparationConfiguration initialConfig = stage.getSeparationConfigurations().get(fcid).copy(fcid);
// why?
FlightConfigurationId id = rocket.getSelectedConfiguration().getFlightConfigurationID();
stage.getSeparationConfigurations().reset(id);
fireTableDataChanged();
if (!initialConfig.equals(stage.getSeparationConfigurations().get(fcid))) {
fireTableDataChanged(ComponentChangeEvent.AEROMASS_CHANGE);
}
}
public void updateButtonState() {
boolean componentSelected = getSelectedComponent() != null;

View File

@ -8,22 +8,15 @@ import java.awt.Point;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EventListener;
import java.util.EventObject;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TreeSelectionEvent;
@ -38,6 +31,7 @@ import net.sf.openrocket.aerodynamics.FlightConditions;
import net.sf.openrocket.aerodynamics.WarningSet;
import net.sf.openrocket.document.OpenRocketDocument;
import net.sf.openrocket.document.Simulation;
import net.sf.openrocket.document.events.SimulationChangeEvent;
import net.sf.openrocket.gui.adaptors.DoubleModel;
import net.sf.openrocket.gui.components.BasicSlider;
import net.sf.openrocket.gui.components.ConfigurationComboBox;
@ -49,6 +43,7 @@ import net.sf.openrocket.gui.figureelements.CGCaret;
import net.sf.openrocket.gui.figureelements.CPCaret;
import net.sf.openrocket.gui.figureelements.Caret;
import net.sf.openrocket.gui.figureelements.RocketInfo;
import net.sf.openrocket.gui.main.BasicFrame;
import net.sf.openrocket.gui.main.componenttree.ComponentTreeModel;
import net.sf.openrocket.gui.simulation.SimulationWorker;
import net.sf.openrocket.gui.util.SwingPreferences;
@ -63,10 +58,12 @@ import net.sf.openrocket.rocketcomponent.Rocket;
import net.sf.openrocket.rocketcomponent.RocketComponent;
import net.sf.openrocket.rocketcomponent.SymmetricComponent;
import net.sf.openrocket.simulation.FlightData;
import net.sf.openrocket.simulation.SimulationStatus;
import net.sf.openrocket.simulation.customexpression.CustomExpression;
import net.sf.openrocket.simulation.customexpression.CustomExpressionSimulationListener;
import net.sf.openrocket.simulation.exception.SimulationException;
import net.sf.openrocket.simulation.listeners.SimulationListener;
import net.sf.openrocket.simulation.listeners.system.ApogeeEndListener;
import net.sf.openrocket.simulation.listeners.system.GroundHitListener;
import net.sf.openrocket.simulation.listeners.system.InterruptListener;
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.unit.UnitGroup;
@ -75,11 +72,13 @@ import net.sf.openrocket.util.Chars;
import net.sf.openrocket.util.Coordinate;
import net.sf.openrocket.util.MathUtil;
import net.sf.openrocket.util.StateChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A JPanel that contains a RocketFigure and buttons to manipulate the figure.
*
* A JPanel that contains a RocketFigure and buttons to manipulate the figure.
*
* @author Sampo Niskanen <sampo.niskanen@iki.fi>
* @author Bill Kuker <bkuker@billkuker.com>
*/
@ -87,6 +86,7 @@ import net.sf.openrocket.util.StateChangeListener;
public class RocketPanel extends JPanel implements TreeSelectionListener, ChangeSource {
private static final Translator trans = Application.getTranslator();
private static final Logger log = LoggerFactory.getLogger(RocketPanel.class);
public enum VIEW_TYPE {
SideView(false, RocketFigure.VIEW_SIDE),
@ -128,7 +128,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
/* Calculation of CP and CG */
private AerodynamicCalculator aerodynamicCalculator;
private final OpenRocketDocument document;
private Caret extraCP = null;
@ -148,13 +148,16 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
private List<EventListener> listeners = new ArrayList<EventListener>();
// Store the basic frame to know which tab is selected (Rocket design, Motors & Configuration, Flight simulations)
private final BasicFrame basicFrame;
/**
* The executor service used for running the background simulations.
* This uses a fixed-sized thread pool for all background simulations
* with all threads in daemon mode and with minimum priority.
*/
private static final Executor backgroundSimulationExecutor;
private static final ExecutorService backgroundSimulationExecutor;
static {
backgroundSimulationExecutor = Executors.newFixedThreadPool(SwingPreferences.getMaxThreadCount(),
new ThreadFactory() {
@ -170,13 +173,17 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
});
}
public OpenRocketDocument getDocument(){
return this.document;
}
public RocketPanel(OpenRocketDocument document) {
this(document, null);
}
public RocketPanel(OpenRocketDocument document, BasicFrame basicFrame) {
this.document = document;
this.basicFrame = basicFrame;
Rocket rkt = document.getRocket();
@ -216,6 +223,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
rkt.addComponentChangeListener(new ComponentChangeListener() {
@Override
public void componentChanged(ComponentChangeEvent e) {
updateExtras();
if (is3d) {
if (e.isTextureChange()) {
figure3d.flushTextureCaches();
@ -367,7 +375,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
/**
* Get the center of pressure figure element.
*
*
* @return center of pressure info
*/
public Caret getExtraCP() {
@ -376,7 +384,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
/**
* Get the center of gravity figure element.
*
*
* @return center of gravity info
*/
public Caret getExtraCG() {
@ -385,7 +393,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
/**
* Get the extra text figure element.
*
*
* @return extra text that contains info about the rocket design
*/
public RocketInfo getExtraText() {
@ -490,12 +498,12 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
/**
* Handle clicking on figure shapes. The functioning is the following:
*
*
* Get the components clicked.
* If no component is clicked, do nothing.
* If the currently selected component is in the set, keep it,
* unless the selector specified is pressed. If it is pressed, cycle to
* the next component. Otherwise select the first component in the list.
* If the currently selected component is in the set, keep it,
* unless the selector specified is pressed. If it is pressed, cycle to
* the next component. Otherwise select the first component in the list.
*/
public static final int CYCLE_SELECTION_MODIFIER = InputEvent.SHIFT_DOWN_MASK;
@ -557,7 +565,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
/**
* Updates the extra data included in the figure. Currently this includes
* the CP and CG carets.
* the CP and CG carets. Also start the background simulator.
*/
private WarningSet warnings = new WarningSet();
@ -645,7 +653,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
figure3d.setCG(new Coordinate(Double.NaN, Double.NaN));
figure3d.setCP(new Coordinate(Double.NaN, Double.NaN));
}
if (figure.getType() == RocketPanel.VIEW_TYPE.SideView && length > 0) {
extraCP.setPosition(cpx, cpy);
extraCG.setPosition(cgx, cgy);
@ -683,35 +691,120 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
return;
}
// Start calculation process
if(((SwingPreferences) Application.getPreferences()).computeFlightInBackground()){
extraText.setCalculatingData(true);
// Update simulations
if (Application.getPreferences().getAutoRunSimulations()) {
// Update only current flight config simulation when you are not in the simulations tab
updateSims(this.basicFrame != null && this.basicFrame.getSelectedTab() == BasicFrame.SIMULATION_TAB);
}
else {
// Always update the simulation of the current configuration
updateSims(false);
}
Rocket duplicate = (Rocket) document.getRocket().copy();
// Update flight data and add flight data update trigger upon simulation changes
for (Simulation sim : document.getSimulations()) {
sim.addChangeListener(new StateChangeListener() {
@Override
public void stateChanged(EventObject e) {
if (updateFlightData(sim)) {
updateFigures();
}
}
});
if (updateFlightData(sim)) {
break;
}
}
}
// find a Simulation based on the current flight configuration
FlightConfigurationId curID = curConfig.getFlightConfigurationID();
Simulation simulation = null;
for (Simulation sim : document.getSimulations()) {
/**
* Updates the simulations. If *currentConfig* is false, only update the simulation of the current flight
* configuration. If it is true, update all the simulations.
*
* @param updateAllSims flag to check whether to update all the simulations (true) or only the current
* flight config sim (false)
*/
private void updateSims(boolean updateAllSims) {
// Stop previous computation (if any)
stopBackgroundSimulation();
FlightConfigurationId curID = document.getSelectedConfiguration().getFlightConfigurationID();
extraText.setCalculatingData(true);
Rocket duplicate = (Rocket)document.getRocket().copy();
// Re-run the present simulation(s)
List<Simulation> sims = new LinkedList<>();
for (Simulation sim : document.getSimulations()) {
if (sim.getStatus() == Simulation.Status.UPTODATE || sim.getStatus() == Simulation.Status.LOADED
|| !document.getRocket().getFlightConfiguration(sim.getFlightConfigurationId()).hasMotors())
continue;
// Find a Simulation based on the current flight configuration
if (!updateAllSims) {
if (sim.getFlightConfigurationId().compareTo(curID) == 0) {
simulation = sim;
sims.add(sim);
break;
}
}
// I *think* every FlightConfiguration has at least one associated simulation; just in case I'm wrong,
// if there isn't one we'll create a new simulation to update the statistics in the panel using the
// default simulation conditions
if (simulation == null) {
System.out.println("creating new simulation");
simulation = ((SwingPreferences) Application.getPreferences()).getBackgroundSimulation(duplicate);
simulation.setFlightConfigurationId( document.getSelectedConfiguration().getId());
} else
System.out.println("using pre-existing simulation");
backgroundSimulationWorker = new BackgroundSimulationWorker(document, simulation);
backgroundSimulationExecutor.execute(backgroundSimulationWorker);
else {
sims.add(sim);
}
}
runBackgroundSimulations(sims, duplicate);
}
/**
* Update the flight data text with the data of {sim}. Only update if sim is the simulation of the current flight
* configuration.
* @param sim: simulation from which the flight data is taken
* @return true if the flight data was updated, false if not
*/
private boolean updateFlightData(Simulation sim) {
FlightConfigurationId curID = document.getSelectedConfiguration().getFlightConfigurationID();
if (sim.getFlightConfigurationId().compareTo(curID) == 0) {
if (sim.hasSimulationData()) {
extraText.setFlightData(sim.getSimulatedData());
} else {
extraText.setFlightData(FlightData.NaN_DATA);
}
return true;
}
return false;
}
/**
* Runs a new background simulation for simulations *sims*. It will run all the simulations in sims sequentially
* in the background.
*
* @param sims simulations which should be run
* @param rkt rocket for which the simulations are run
*/
private void runBackgroundSimulations(List<Simulation> sims, Rocket rkt) {
if (sims.size() == 0) {
extraText.setCalculatingData(false);
for (Simulation sim : document.getSimulations()) {
if (updateFlightData(sim)) {
return;
}
}
extraText.setFlightData(FlightData.NaN_DATA);
return;
}
// I *think* every FlightConfiguration has at least one associated simulation; just in case I'm wrong,
// if there isn't one we'll create a new simulation to update the statistics in the panel using the
// default simulation conditions
for (Simulation sim : sims) {
if (sim == null) {
log.info("creating new simulation");
sim = ((SwingPreferences) Application.getPreferences()).getBackgroundSimulation(rkt);
sim.setFlightConfigurationId(document.getSelectedConfiguration().getId());
} else
log.info("using pre-existing simulation");
}
backgroundSimulationWorker = new BackgroundSimulationWorker(document, sims);
backgroundSimulationExecutor.execute(backgroundSimulationWorker);
}
/**
@ -732,16 +825,20 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
private class BackgroundSimulationWorker extends SimulationWorker {
private final CustomExpressionSimulationListener exprListener;
private final OpenRocketDocument doc;
private List<Simulation> sims;
public BackgroundSimulationWorker(OpenRocketDocument doc, Simulation sim) {
super(sim);
public BackgroundSimulationWorker(OpenRocketDocument doc, List<Simulation> sims) {
super(sims.get(0));
this.sims = sims;
this.doc = doc;
List<CustomExpression> exprs = doc.getCustomExpressions();
exprListener = new CustomExpressionSimulationListener(exprs);
}
@Override
protected FlightData doInBackground() {
extraText.setCalculatingData(true);
// Pause a little while to allow faster UI reaction
try {
Thread.sleep(300);
@ -749,7 +846,6 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
}
if (isCancelled() || backgroundSimulationWorker != this)
return null;
return super.doInBackground();
}
@ -758,19 +854,27 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
// Do nothing if cancelled
if (isCancelled() || backgroundSimulationWorker != this)
return;
backgroundSimulationWorker = null;
extraText.setFlightData(simulation.getSimulatedData());
// Only set the flight data information of the current flight configuration
extraText.setCalculatingData(false);
figure.repaint();
figure3d.repaint();
document.fireDocumentChangeEvent(new SimulationChangeEvent(simulation));
// Run the new simulation after this one has ended
this.sims.remove(0);
if (this.sims.size() > 0) {
backgroundSimulationWorker = new BackgroundSimulationWorker(this.doc, this.sims);
backgroundSimulationExecutor.execute(backgroundSimulationWorker);
}
}
@Override
protected SimulationListener[] getExtraListeners() {
return new SimulationListener[] {
InterruptListener.INSTANCE,
ApogeeEndListener.INSTANCE,
GroundHitListener.INSTANCE,
exprListener };
}
@ -813,7 +917,7 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
}
/**
* Updates the selection in the FigureParameters and repaints the figure.
* Updates the selection in the FigureParameters and repaints the figure.
* Ignores the event itself.
*/
@Override
@ -868,5 +972,5 @@ public class RocketPanel extends JPanel implements TreeSelectionListener, Change
// putValue(Action.SELECTED_KEY, figure.getType() == type && !is3d);
// }
// }
}