Difference between revisions of "Simulation Extensions"

From OpenRocket wiki
Jump to navigation Jump to search
m (fix path to AbstractSimulationListener.java)
 
(43 intermediate revisions by the same user not shown)
Line 7: Line 7:
 
Extensions are added to a simulation through a menu in the "Simulation Options" tab.
 
Extensions are added to a simulation through a menu in the "Simulation Options" tab.
 
# Open a .ork file and go to the '''Flight Simulations''' tab
 
# Open a .ork file and go to the '''Flight Simulations''' tab
# Click the ''Edit simulation'' button to open the '''Edit simulation''' dialog.
+
# Click the '''Edit simulation''' button to open the '''Edit simulation''' dialog.
 
# Go to the '''Simulation options''' tab.
 
# Go to the '''Simulation options''' tab.
 
# Click the '''Add extension''' button
 
# Click the '''Add extension''' button
Line 22: Line 22:
 
[[File:Air-start-pane.png]]
 
[[File:Air-start-pane.png]]
  
== Some Preliminary Concepts ==
+
== Creating a New OpenRocket Extension ==
  
 +
The remainder of this page will describe how a new simulation extension is created.
 +
 +
===Preliminary Concepts===
 
Before we can discuss writing an extension, we need to briefly discuss some of the internals of OpenRocket.  In particular,
 
Before we can discuss writing an extension, we need to briefly discuss some of the internals of OpenRocket.  In particular,
 
we need to talk about the simulation status, flight data, and simulation listeners.
 
we need to talk about the simulation status, flight data, and simulation listeners.
  
===Simulation Status and Flight Data===
+
====Simulation Status====
 +
As a simulation proceeds, it maintains its state in a <code>SimulationStatus</code>.  The <code>SimulationStatus</code> object contains information about the rocket's current position, orientation, velocity and simulation state.  It also contains a reference to a copy of the rocket design and its configuration.  Any simulation listener method may modify the state of the rocket by changing the properties of the <code>SimulationStatus</code> object.
 +
 
 +
You can obtain current information regarding the state of the simulation by calling <code>get*()</code> methods.  For instance, the rocket's current position is returned by calling <code>getRocketPosition()</code>; the rocket's position can be changed by calling <code>setRocketPosition<Coordinate position></code>.  All of the <code>get*()</code> and <code>set*()</code> methods can be found in <code>code/src/net/sf/openrocket/simulation/SimulationStatus.java</code>.  Note that while some information can be obtained in this way, it is not as complete as that found in <code>FlightData</code> and <code>FlightDataBranch</code> objects.
  
As a simulation proceeds, it maintains its state in a <code>SimulationStatus</code>.  The <code>SimulationStatus</code> object contains information about the rocket's current position, orientation, velocity and simulation state. It also contains a reference to a copy of the rocket design and its configuration. Any simulation listener method may modify the state of the rocket by changing the properties of the state object.
+
====Flight Data====
 +
OpenRocket refers to simulation variables as <code>FlightDataType</code>s, which are <code>List&lt;Double&gt;</code> objects with one list for each simulation variable and one element in the list for each time stepTo obtain a <code>FlightDataType</code>, for example the current motor mass, from <code>flightData</code>, we call <code>flightData.get(FlightDataType.TYPE_MOTOR_MASS))</code>. The standard <code>FlightDataType</code> lists are all created in <code>core/src/net/sf/openrocket/simulation/FlightDataType.java</code>; the mechanism for creating a new <code>FlightDataType</code> if needed for your extension will be described later.
  
Assuming the simulation status is stored in <code>status</code>, we obtain the flight data for the currently executing simulation branch by calling <code>status.getFlightData()</code>.
+
Data from the current simulation step can be obtained with e.g. <code>flightData.getLast(FlightDataType.TYPE_MOTOR_MASS)</code>.
  
OpenRocket refers to simulation variables as <code>FlightDataType</code>s, which are <code>List&lt;Double&gt;</code>s, with one list for each simulation variable.  To obtain a <code>FlightDataType</code>, for example the current motor mass, from <code>flightData</code>, we call <code>flightData.get(FlightDataType.TYPE_MOTOR_MASS))</code>. The standard <code>FlightDataType</code>s are all created in <code>core/src/net/sf/openrocket/simulation/FlightDataType.java</code>; the mechanism for creating a new <code>FlightDataType</code> for your extension will be described later.
+
The simulation data for each stage of the rocket's flight is referred to as a <code>FlightDataBranch</code>. Every simulation has at least one <code>FlightDataBranch</code> for its sustainer, and will have additional branches for its boosters.
  
Data from the current simulation step can be obtained with e.g. <code>flightData.getLast(FlightDataType.TYPE_MOTOR_MASS</code>.
+
Finally, the collection of all of the <code>FlightDataBranch</code>es and some summary data for the simulation is stored in a <code>FlightData</code> object.
  
===Simulation Listeners===
+
====Flight Conditions====
 +
Current data regarding the aerodynamics of the flight itself are stored in a <code>FlightConditions</code> object.  This includes things like the velocity, angle of attack, and roll and pitch angle and rates. It also contains a reference to the current <code>AtmosphericConditions</code>
  
 +
====Simulation Listeners====
 
Simulation listeners are methods that OpenRocket calls at specified points in the computation to either record information or modify the simulation state.  These are divided into three interface classes, named <code>SimulationListener</code>, <code>SimulationComputationListener</code>, and <code>SimulationEventListener</code>.
 
Simulation listeners are methods that OpenRocket calls at specified points in the computation to either record information or modify the simulation state.  These are divided into three interface classes, named <code>SimulationListener</code>, <code>SimulationComputationListener</code>, and <code>SimulationEventListener</code>.
  
Line 50: Line 59:
 
</pre>
 
</pre>
  
This method is called when the simulation is first started.  It obtains the desired launch altitude and velocity from its configuration, configuration, and inserts them into the simulation status.
+
This method is called when the simulation is first started.  It obtains the desired launch altitude and velocity from its configuration, and inserts them into the simulation status to simulate an air-start.
  
The full set of listener methods, with documentation regarding when they are called, can be found in <code>core/src/net/sf/openrocket/AbstractSimulationListener.java</code>.
+
The full set of listener methods, with documentation regarding when they are called, can be found in <code>core/src/net/sf/openrocket/simulation/listeners/AbstractSimulationListener.java</code>.
  
 
The listener methods can have three return value types:
 
The listener methods can have three return value types:
  
* The <code>startSimulation</code>, <code>endSimulation</code>, and <code>postStep</code> are called at a specific point of the simulation.  They are void methods and do not return any value.
+
* The <code>startSimulation()</code>, <code>endSimulation()</code>, and <code>postStep()</code> are called at a specific point of the simulation.  They are void methods and do not return any value.
  
* The <code>preStep</code> and event-related hooks return a boolean value indicating whether the action should be taken or not.  A return value of <code>true</code> indicates that the action should be taken as normally would be (default), <code>false</code> will inhibit the action.
+
* The <code>preStep()</code> and event-related hook methods return a boolean value indicating whether the associated action should be taken or not.  A return value of <code>true</code> indicates that the action should be taken as normally would be (default), <code>false</code> will inhibit the action.
  
 
* The pre- and post-computation methods may return the computed value, either as an object or a double value.  The pre-computation methods allow pre-empting the entire computation, while the post-computation methods allow augmenting the computed values.  These methods may return <code>null</code> or <code>Double.NaN</code> to use the original values (default), or return an overriding value.
 
* The pre- and post-computation methods may return the computed value, either as an object or a double value.  The pre-computation methods allow pre-empting the entire computation, while the post-computation methods allow augmenting the computed values.  These methods may return <code>null</code> or <code>Double.NaN</code> to use the original values (default), or return an overriding value.
  
Every method receives a <code>SimulationStatus</code> (see above) object as the first argument, and may have additional arguments.
+
Every listener receives a <code>SimulationStatus</code> (see above) object as the first argument, and may also have additional arguments.
 
    
 
    
Each listener method may also throw a <code>SimulationException</code>.  This is considered an error during simulation, and an error dialog is displayed to the user with the exception message.  The simulation data thus far is not stored in the simulation.  Throwing a <code>RuntimeException</code> is considered a bug in the software and will result in a bug report dialog.
+
Each listener method may also throw a <code>SimulationException</code>.  This is considered an error during simulation (not a bug), and an error dialog is displayed to the user with the exception message.  The simulation data produced thus far is not stored in the simulation.  Throwing a <code>RuntimeException</code> is considered a bug in the software and will result in a bug report dialog.
  
 
If a simulation listener wants to stop a simulation prematurely without an error condition, it needs to add a flight event of type <code>FlightEvent.SIMULATION_END</code> to the simulation event queue:
 
If a simulation listener wants to stop a simulation prematurely without an error condition, it needs to add a flight event of type <code>FlightEvent.SIMULATION_END</code> to the simulation event queue:
Line 72: Line 81:
 
This will cause the simulation to be terminated normally.
 
This will cause the simulation to be terminated normally.
  
=== Creating a Simulation Extension ===
+
=== Creating a New Simulation Extension ===
  
 
Creating an extension for OpenRocket requires writing three classes:
 
Creating an extension for OpenRocket requires writing three classes:
  
* A listener, which extends <code>AbstractSimulationListener</code>. This will be the bulk of your extension, and performs all the real work.
+
* A listener, which extends <code>AbstractSimulationListener</code>. This will be the bulk of your extension, and performs all the real work.
  
* An extension, which extends <code>AbstractSimulationExtension</code>. This inserts your listener into the simulation when it is called. Your listener can (and probably will) be private within your extension.
+
* An extension, which extends <code>AbstractSimulationExtension</code>. This inserts your listener into the simulation. Your listener can (and ordinarily will) be private to your extension.
  
* A provider, which extends <code>AbstractSimulationExtensionProvider</code>/ This puts your extension into the menu described above and calls the simulation.
+
* A provider, which extends <code>AbstractSimulationExtensionProvider</code> This puts your extension into the menu described above.
  
 
In addition, if your extension will have a configuration GUI, you will need to write:
 
In addition, if your extension will have a configuration GUI, you will need to write:
Line 86: Line 95:
 
* A configurator, which extends <code>AbstractSwingSimulationExtensionConfigurator&lt;E&gt;</code>
 
* A configurator, which extends <code>AbstractSwingSimulationExtensionConfigurator&lt;E&gt;</code>
  
You can either create your extension outside the source tree and insert it in OpenRocket's .jar file when compiled, or you can insert it in the source tree and compile it with OpenRocket.  Since all of OpenRocket's code is freely available, and reading the code for the existing extensions will be very helpful in writing your's, the easiest approach is to simply insert it in the source tree.  If you select this option, a very logical place to put your extension is in
+
You can either create your extension outside the source tree and make sure it is in a directory that is in your Java classpath when OpenRocket is executed, or you can insert it in the source tree and compile it along with OpenRocket.  Since all of OpenRocket's code is freely available, and reading the code for the existing extensions will be very helpful in writing your own, the easiest approach is to simply insert it in the source tree.  If you select this option, a very logical place to put your extension is in
  
 
<code>core/src/net/sf/openrocket/simulation/extension/example/</code>
 
<code>core/src/net/sf/openrocket/simulation/extension/example/</code>
  
This is where the extensions provided with OpenRocket are defined.  Your configurator, if any, will logically go in
+
This is where the extension examples provided with OpenRocket are located.  Your configurator, if any, will logically go in
  
 
<code>swing/src/net/sf/openrocket/simulation/extension/example/</code>
 
<code>swing/src/net/sf/openrocket/simulation/extension/example/</code>
  
===A Simple Example===
+
====Extension Example====
 +
 
 +
To make things concrete, we'll start by creating a simple example extension, to air-start a rocket from a hard-coded altitude.  Later, we'll add a configurator to the extension so we can set the launch altitude through a GUI at run time. This is a simplified version of the <code>AirStart</code> extension located in the OpenRocket source code tree; that class also sets a start velocity.
 +
 
 +
{| align="top"
 +
| <pre>
 +
1
 +
2
 +
3
 +
4
 +
5
 +
6
 +
7
 +
8
 +
9
 +
10
 +
11
 +
12
 +
13
 +
14
 +
15
 +
16
 +
17
 +
18
 +
19
 +
20
 +
21
 +
22
 +
23
 +
24
 +
25
 +
26
 +
27
 +
28
 +
29
 +
30
 +
31
 +
32
 +
33
 +
34
 +
35
 +
</pre>
 +
| <pre>
 +
package net.sf.openrocket.simulation.extension.example;
 +
 
 +
import net.sf.openrocket.simulation.SimulationStatus;
 +
import net.sf.openrocket.simulation.exception.SimulationException;
 +
import net.sf.openrocket.simulation.extension.AbstractSimulationExtension;
 +
import net.sf.openrocket.simulation.listeners.AbstractSimulationListener;
 +
import net.sf.openrocket.util.Coordinate;
 +
 
 +
/**
 +
* Simulation extension that launches a rocket from a specific altitude.
 +
*/
 +
public class AirStartExample extends AbstractSimulationExtension {
 +
 
 +
    public void initialize(SimulationConditions conditions) throws SimulationException {
 +
        conditions.getSimulationListenerList().add(new AirStartListener());
 +
    }
 +
 
 +
    @Override
 +
    public String getName() {
 +
        return "Air-Start Example";
 +
    }
 +
 
 +
    @Override
 +
    public String getDescription() {
 +
        return "Simple extension example for air-start";
 +
    }
 +
 
 +
    private class AirStartListener extends AbstractSimulationListener {
 +
 
 +
        @Override
 +
        public void startSimulation(SimulationStatus status) throws SimulationException {
 +
            status.setRocketPosition(new Coordinate(0, 0, 1000.0));
 +
        }
 +
    }
 +
}
 +
</pre>
 +
|}
 +
 
 +
There are several important features in this example:
 +
* The <code>initialize()</code> method in lines 14-16, which adds the listener to the simulations <code>List</code> of listeners.  This is the only method that is required to be defined in your extension.
 +
* The <code>getName()</code> method in lines 19-21, which provides the extension's name.  A default <code>getName()</code> is provided by <code>AbstractSimulationExtension</code>, which simply uses the classname (so for this example, <code>getName()</code> would have returned <code>"AirStartExample"</code> if this method hadn't overridden it).
 +
* The <code>getDescription()</code> method in lines 24-26, which provides a brief description of the purpose of the extension. This is the method that provides the text for the <code>Info</code> button dialog shown in the first section of this page.
 +
* The listener itself in lines 28-34, which provides a single <code>startSimulation()</code> method.  When the simulation for starts executing, this listener is called and the rocket is set to an altitude of 1000 meters.
 +
 
 +
This will create the extension when it's compiled, but it won't put it in the simulation extension menu.  To be able to actually use it, we need a provider, like this:
 +
 
 +
{| align="top"
 +
| <pre>
 +
1
 +
2
 +
3
 +
4
 +
5
 +
6
 +
7
 +
8
 +
9
 +
10
 +
11
 +
</pre>
 +
| <pre>
 +
package net.sf.openrocket.simulation.extension.example;
 +
 
 +
import net.sf.openrocket.plugin.Plugin;
 +
import net.sf.openrocket.simulation.extension.AbstractSimulationExtensionProvider;
 +
 
 +
@Plugin
 +
public class AirStartExampleProvider extends AbstractSimulationExtensionProvider {
 +
    public AirStartExampleProvider() {
 +
        super(AirStartExample.class, "Launch conditions", "Air-start example");
 +
    }
 +
}
 +
</pre>
 +
|}
 +
 
 +
This class adds your extension to the extension menu.  The first <code>String</code> (<code>"Launch Conditions"</code>) is the first menu level, while the second (<code>"Air-start example"</code>) is the actual menu entry.  These strings can be anything you want; using a first level entry that didn't previously exist will add it to the first level menu.
 +
 
 +
Try it! Putting the extension in a file named <code>core/src/net/sf/openrocket/simulation/extensions/example/AirStartExample.java</code> and the provider in <code>core/src/net/sf/openrocket/simulation/extensions/example/AirStartExampleProvider.java</code>, compiling, and running will give you a new entry in the extensions menu; adding it to the simulation will cause your simulation to start at an altitude of 1000 meters.
 +
 
 +
====Adding a Configurator====
 +
To be able to configure the extension at run time, we need to write a configurator and provide it with a way to communicate with the extension First, we'll modify the extension as follows:
 +
 
 +
{| align="top"
 +
| <pre>
 +
1
 +
2
 +
3
 +
4
 +
5
 +
6
 +
7
 +
8
 +
9
 +
10
 +
11
 +
12
 +
13
 +
14
 +
15
 +
16
 +
17
 +
18
 +
19
 +
20
 +
21
 +
22
 +
23
 +
24
 +
25
 +
26
 +
27
 +
28
 +
29
 +
30
 +
31
 +
32
 +
33
 +
34
 +
35
 +
36
 +
37
 +
38
 +
39
 +
40
 +
41
 +
42
 +
43
 +
44
 +
45
 +
</pre>
 +
| <pre>
 +
package net.sf.openrocket.simulation.extension.example;
 +
 
 +
import net.sf.openrocket.simulation.SimulationStatus;
 +
import net.sf.openrocket.simulation.exception.SimulationException;
 +
import net.sf.openrocket.simulation.extension.AbstractSimulationExtension;
 +
import net.sf.openrocket.simulation.listeners.AbstractSimulationListener;
 +
import net.sf.openrocket.util.Coordinate;
 +
 
 +
/**
 +
* Simulation extension that launches a rocket from a specific altitude.
 +
*/
 +
public class AirStartExample extends AbstractSimulationExtension {
 +
 
 +
    public void initialize(SimulationConditions conditions) throws SimulationException {
 +
        conditions.getSimulationListenerList().add(new AirStartListener());
 +
    }
 +
 
 +
    @Override
 +
    public String getName() {
 +
        return "Air-Start Example";
 +
    }
 +
 
 +
    @Override
 +
    public String getDescription() {
 +
        return "Simple extension example for air-start";
 +
    }
 +
 
 +
    public double getLaunchAltitude() {
 +
        return config.getDouble("launchAltitude", 1000.0);
 +
    }
 +
 
 +
    public void setLaunchAltitude(double launchAltitude) {
 +
        config.put("launchAltitude", launchAltitude);
 +
        fireChangeEvent();
 +
    }
 +
       
 +
    private class AirStartListener extends AbstractSimulationListener {
 +
 
 +
        @Override
 +
        public void startSimulation(SimulationStatus status) throws SimulationException {
 +
 
 +
            status.setRocketPosition(new Coordinate(0, 0, getLaunchAltitude()));
 +
        }
 +
    }
 +
}
 +
</pre>
 +
|}
 +
 
 +
This adds two methods to the extension (<code>getLaunchAltitude()</code> and <code>setLaunchAltitude()</code>), and calls <code>getLaunchAltitude()</code> from within the listener to obtain the configured launch altitude. <code>config</code> is a <code>Config</code> object, provided by <code>AbstractSimulationExtension</code> (so it isn't necessary to call a constructor yourself). <code>core/src/net/sf/openrocket/util/Config.java</code> includes methods to interact with a configurator, allowing the extension to obtain <code>double</code>, <code>string</code>, and other configuration values.
 +
 
 +
In this case, we'll only be defining a single configuration field in our configurator, <code>"launchAltitude"</code>.
 +
 
 +
The <code>getLaunchAltitude()</code> method obtains the air-start altitude for the simulation from the configuration, and sets a default air-start altitude of 1000 meters. Our <code>startSimulation()</code> method has been modified to make use of this to obtain the user's requested air-start altitude from the configurator, in place of the original hard-coded value.
 +
 
 +
The <code>setLaunchAltitude()</code> method places a new launch altitude in the configuration.  While our extension doesn't make use of this method directly, it will be necessary for our configurator. The call to <code>fireChangeEvent()</code> in this method assures that the changes we make to the air-start altitude are propagated throughout the simulation.
 +
 
 +
The configurator itself looks like this
 +
{| align="top"
 +
| <pre>
 +
1
 +
2
 +
3
 +
4
 +
5
 +
6
 +
7
 +
8
 +
9
 +
10
 +
11
 +
12
 +
13
 +
14
 +
15
 +
16
 +
17
 +
18
 +
19
 +
20
 +
21
 +
22
 +
23
 +
24
 +
25
 +
26
 +
27
 +
28
 +
29
 +
30
 +
31
 +
32
 +
33
 +
34
 +
35
 +
36
 +
37
 +
38
 +
39
 +
30
 +
31
 +
42
 +
43
 +
</pre>
 +
| <pre>
 +
package net.sf.openrocket.simulation.extension.example;
 +
 
 +
import javax.swing.JComponent;
 +
import javax.swing.JLabel;
 +
import javax.swing.JPanel;
 +
import javax.swing.JSpinner;
 +
 
 +
import net.sf.openrocket.document.Simulation;
 +
import net.sf.openrocket.gui.SpinnerEditor;
 +
import net.sf.openrocket.gui.adaptors.DoubleModel;
 +
import net.sf.openrocket.gui.components.BasicSlider;
 +
import net.sf.openrocket.gui.components.UnitSelector;
 +
import net.sf.openrocket.plugin.Plugin;
 +
import net.sf.openrocket.simulation.extension.AbstractSwingSimulationExtensionConfigurator;
 +
import net.sf.openrocket.unit.UnitGroup;
 +
 
 +
@Plugin
 +
public class AirStartConfigurator extends AbstractSwingSimulationExtensionConfigurator<AirStart> {
 +
 +
    public AirStartConfigurator() {
 +
        super(AirStart.class);
 +
    }
 +
 +
    @Override
 +
    protected JComponent getConfigurationComponent(AirStart extension, Simulation simulation, JPanel panel) {
 +
        panel.add(new JLabel("Launch altitude:"));
 +
 
 +
        DoubleModel m = new DoubleModel(extension, "LaunchAltitude", UnitGroup.UNITS_DISTANCE, 0);
 +
 
 +
        JSpinner spin = new JSpinner(m.getSpinnerModel());
 +
        spin.setEditor(new SpinnerEditor(spin));
 +
        panel.add(spin, "w 65lp!");
  
To explore the process of writing an extension, we'll begin with a simple example: an extension that writes <code>Hello World</code> to the standard output after every simulation step.  The extension is as follows:
+
        UnitSelector unit = new UnitSelector(m);
<pre>
+
        panel.add(unit, "w 25");
  
 +
        BasicSlider slider = new BasicSlider(m.getSliderModel(0, 5000));
 +
        panel.add(slider, "w 75lp, wrap");
 +
 +
        return panel;
 +
    }
 +
}
 
</pre>
 
</pre>
 +
|}
 +
 +
After some boilerplate, this class creates a new <code>DoubleModel</code> to manage the airstart altitude.  The most important things to notice about the <code>DoubleModel</code> constructor are the parameters <code>"LaunchAltitude"</code> and <code>UnitGroup.UNITS_DISTANCE</code>.
 +
* <code>"LaunchAltitude"</code>  is used by the system to synthesize calls to the <code>getLaunchAltitude()</code> and <code>setLaunchAltitude()</code> methods mentioned earlier. The name of the <code>DoubleModel</code>, <code>"LaunchAltitude"</code>, '''''MUST''''' match the names of the corresponding <code>set</code> and <code>get</code> methods exactly.  If they don't, there will be an exception at run time when the user attempts to change the value.
 +
* <code>UnitGroup.UNITS_DISTANCE</code> specifies the unit group to be used by this <code>DoubleModel</code>. OpenRocket uses SI (MKS) units internally, but allows users to select the units they wish to use for their interface.  Specifying a <code>UnitGroup</code> provides the conversions and unit displays for the interface.  The available <code>UnitGroup</code>s are defined in <code>core/src/net/sf/openrocket/unit/UnitGroup.java</code>
 +
 +
The remaining code in this method creates a <code>JSpinner</code>, a <code>UnitSelector</code>, and a <code>BasicSlider</code> all referring to this <code>DoubleModel</code>.  When the resulting configurator is displayed, it looks like this:
 +
 +
[[File:Example_Configurator.png]]
 +
 +
The surrounding Dialog window and the '''Close''' button are provided by the system.
 +
====Example User Extensions Provided With OpenRocket====
 +
Several examples of user extensions are provided in the OpenRocket source tree.  As mentioned previously, the extensions are all located in <code>core/src/net/sf/openrocket/simulation/extension/example</code> and their configurators are all located in <code>swing/src/net/sf/openrocket/simulation/extension/example</code>.  Also recall that every extension has a corresponding provider.
 +
 +
{| class="wikitable" style="margin:auto"
 +
!Purpose!!Extension!!Configurator
 +
|-
 +
| Set air-start altitude and velocity||<code>AirStart.java</code>||<code>AirStartConfigurator.java</code>
 +
|-
 +
| Save some simulation values as a CSV file||<code>CSVSave.java</code>||''(none)''
 +
|-
 +
| Calculate damping moment coefficient after every simulation step||<code>DampingMoment.java</code>||''(none)''
 +
|-
 +
| Print summary of simulation progress after each step||<code>PrintSimulation.java</code>||''(none)''
 +
|-
 +
| Active roll control||<code>RollControl.java</code>||<code>RollControlConfigurator.java</code>
 +
|-
 +
| Stop simulation at specified time or number of steps||<code>StopSimulation</code>||<code>StopSimulationConfigurator</code>
 +
|}
 +
''Note:  documentation for adding user-created simulation listeners, without making use of the full extension mechanism, is also available at [[Simulation Listeners]]''

Latest revision as of 18:53, 11 September 2023

By using OpenRocket's extension and listener mechanism, it's possible to modify the program itself to add features that are not supported by the program as distributed; some extensions that have been created already provide the ability to air-start a rocket, to add active roll control, and to calculate and save extra flight data.

This page will discuss extensions and simulations. We'll start by showing how a simulation is executed (so you can get a taste of what's possible), and then document the process of creating the extension. WARNING: writing an extension inserts new code into the program. It is entirely possible to disrupt a simulation in a way that invalidates simulation results, or can even crash the program. Be careful!

Adding an Existing Extension to a Simulation[edit]

Extensions are added to a simulation through a menu in the "Simulation Options" tab.

  1. Open a .ork file and go to the Flight Simulations tab
  2. Click the Edit simulation button to open the Edit simulation dialog.
  3. Go to the Simulation options tab.
  4. Click the Add extension button

This will open a menu similar to the one in the following screenshot:

Extension-menu.png

Clicking on the name of an extension will add it to the simulation; if it has a configuration dialog the dialog will be opened:

Air-start-configuration.png

In the case of the air-start extension, the configuration dialog allows you to set the altitude and velocity at which your simulation will begin. After you close the configuration dialog (if any), a new panel will be added to the Simulation options pane, showing the new extension with buttons to reconfigure it, obtain information about it, or remove it from the simulation:

Air-start-pane.png

Creating a New OpenRocket Extension[edit]

The remainder of this page will describe how a new simulation extension is created.

Preliminary Concepts[edit]

Before we can discuss writing an extension, we need to briefly discuss some of the internals of OpenRocket. In particular, we need to talk about the simulation status, flight data, and simulation listeners.

Simulation Status[edit]

As a simulation proceeds, it maintains its state in a SimulationStatus. The SimulationStatus object contains information about the rocket's current position, orientation, velocity and simulation state. It also contains a reference to a copy of the rocket design and its configuration. Any simulation listener method may modify the state of the rocket by changing the properties of the SimulationStatus object.

You can obtain current information regarding the state of the simulation by calling get*() methods. For instance, the rocket's current position is returned by calling getRocketPosition(); the rocket's position can be changed by calling setRocketPosition<Coordinate position>. All of the get*() and set*() methods can be found in code/src/net/sf/openrocket/simulation/SimulationStatus.java. Note that while some information can be obtained in this way, it is not as complete as that found in FlightData and FlightDataBranch objects.

Flight Data[edit]

OpenRocket refers to simulation variables as FlightDataTypes, which are List<Double> objects with one list for each simulation variable and one element in the list for each time step. To obtain a FlightDataType, for example the current motor mass, from flightData, we call flightData.get(FlightDataType.TYPE_MOTOR_MASS)). The standard FlightDataType lists are all created in core/src/net/sf/openrocket/simulation/FlightDataType.java; the mechanism for creating a new FlightDataType if needed for your extension will be described later.

Data from the current simulation step can be obtained with e.g. flightData.getLast(FlightDataType.TYPE_MOTOR_MASS).

The simulation data for each stage of the rocket's flight is referred to as a FlightDataBranch. Every simulation has at least one FlightDataBranch for its sustainer, and will have additional branches for its boosters.

Finally, the collection of all of the FlightDataBranches and some summary data for the simulation is stored in a FlightData object.

Flight Conditions[edit]

Current data regarding the aerodynamics of the flight itself are stored in a FlightConditions object. This includes things like the velocity, angle of attack, and roll and pitch angle and rates. It also contains a reference to the current AtmosphericConditions

Simulation Listeners[edit]

Simulation listeners are methods that OpenRocket calls at specified points in the computation to either record information or modify the simulation state. These are divided into three interface classes, named SimulationListener, SimulationComputationListener, and SimulationEventListener.

All of these interfaces are implemented by the abstract class AbstractSimulationListener. This class provides empty methods for all of the methods defined in the three interfaces, which are overridden as needed when writing a listener. A typical listener method (which is actually in the Air-start listener), would be

public void startSimulation(SimulationStatus status) throws SimulationException {
    status.setRocketPosition(new Coordinate(0, 0, getLaunchAltitude()));
    status.setRocketVelocity(status.getRocketOrientationQuaternion().rotate(new Coordinate(0, 0, getLaunchVelocity())));
}

This method is called when the simulation is first started. It obtains the desired launch altitude and velocity from its configuration, and inserts them into the simulation status to simulate an air-start.

The full set of listener methods, with documentation regarding when they are called, can be found in core/src/net/sf/openrocket/simulation/listeners/AbstractSimulationListener.java.

The listener methods can have three return value types:

  • The startSimulation(), endSimulation(), and postStep() are called at a specific point of the simulation. They are void methods and do not return any value.
  • The preStep() and event-related hook methods return a boolean value indicating whether the associated action should be taken or not. A return value of true indicates that the action should be taken as normally would be (default), false will inhibit the action.
  • The pre- and post-computation methods may return the computed value, either as an object or a double value. The pre-computation methods allow pre-empting the entire computation, while the post-computation methods allow augmenting the computed values. These methods may return null or Double.NaN to use the original values (default), or return an overriding value.

Every listener receives a SimulationStatus (see above) object as the first argument, and may also have additional arguments.

Each listener method may also throw a SimulationException. This is considered an error during simulation (not a bug), and an error dialog is displayed to the user with the exception message. The simulation data produced thus far is not stored in the simulation. Throwing a RuntimeException is considered a bug in the software and will result in a bug report dialog.

If a simulation listener wants to stop a simulation prematurely without an error condition, it needs to add a flight event of type FlightEvent.SIMULATION_END to the simulation event queue:

 status.getEventQueue().add(new FlightEvent(FlightEvent.Type.SIMULATION_END, status.getSimulationTime(), null));

This will cause the simulation to be terminated normally.

Creating a New Simulation Extension[edit]

Creating an extension for OpenRocket requires writing three classes:

  • A listener, which extends AbstractSimulationListener. This will be the bulk of your extension, and performs all the real work.
  • An extension, which extends AbstractSimulationExtension. This inserts your listener into the simulation. Your listener can (and ordinarily will) be private to your extension.
  • A provider, which extends AbstractSimulationExtensionProvider This puts your extension into the menu described above.

In addition, if your extension will have a configuration GUI, you will need to write:

  • A configurator, which extends AbstractSwingSimulationExtensionConfigurator<E>

You can either create your extension outside the source tree and make sure it is in a directory that is in your Java classpath when OpenRocket is executed, or you can insert it in the source tree and compile it along with OpenRocket. Since all of OpenRocket's code is freely available, and reading the code for the existing extensions will be very helpful in writing your own, the easiest approach is to simply insert it in the source tree. If you select this option, a very logical place to put your extension is in

core/src/net/sf/openrocket/simulation/extension/example/

This is where the extension examples provided with OpenRocket are located. Your configurator, if any, will logically go in

swing/src/net/sf/openrocket/simulation/extension/example/

Extension Example[edit]

To make things concrete, we'll start by creating a simple example extension, to air-start a rocket from a hard-coded altitude. Later, we'll add a configurator to the extension so we can set the launch altitude through a GUI at run time. This is a simplified version of the AirStart extension located in the OpenRocket source code tree; that class also sets a start velocity.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package net.sf.openrocket.simulation.extension.example;

import net.sf.openrocket.simulation.SimulationStatus;
import net.sf.openrocket.simulation.exception.SimulationException;
import net.sf.openrocket.simulation.extension.AbstractSimulationExtension;
import net.sf.openrocket.simulation.listeners.AbstractSimulationListener;
import net.sf.openrocket.util.Coordinate;

/**
 * Simulation extension that launches a rocket from a specific altitude.
 */
public class AirStartExample extends AbstractSimulationExtension {

    public void initialize(SimulationConditions conditions) throws SimulationException {
        conditions.getSimulationListenerList().add(new AirStartListener());
    }

    @Override
    public String getName() {
        return "Air-Start Example";
    }

    @Override
    public String getDescription() {
        return "Simple extension example for air-start";
    }

    private class AirStartListener extends AbstractSimulationListener {

        @Override
        public void startSimulation(SimulationStatus status) throws SimulationException {
            status.setRocketPosition(new Coordinate(0, 0, 1000.0));
        }
    }
}

There are several important features in this example:

  • The initialize() method in lines 14-16, which adds the listener to the simulations List of listeners. This is the only method that is required to be defined in your extension.
  • The getName() method in lines 19-21, which provides the extension's name. A default getName() is provided by AbstractSimulationExtension, which simply uses the classname (so for this example, getName() would have returned "AirStartExample" if this method hadn't overridden it).
  • The getDescription() method in lines 24-26, which provides a brief description of the purpose of the extension. This is the method that provides the text for the Info button dialog shown in the first section of this page.
  • The listener itself in lines 28-34, which provides a single startSimulation() method. When the simulation for starts executing, this listener is called and the rocket is set to an altitude of 1000 meters.

This will create the extension when it's compiled, but it won't put it in the simulation extension menu. To be able to actually use it, we need a provider, like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package net.sf.openrocket.simulation.extension.example;

import net.sf.openrocket.plugin.Plugin;
import net.sf.openrocket.simulation.extension.AbstractSimulationExtensionProvider;

@Plugin
public class AirStartExampleProvider extends AbstractSimulationExtensionProvider {
    public AirStartExampleProvider() {
        super(AirStartExample.class, "Launch conditions", "Air-start example");
    }
}

This class adds your extension to the extension menu. The first String ("Launch Conditions") is the first menu level, while the second ("Air-start example") is the actual menu entry. These strings can be anything you want; using a first level entry that didn't previously exist will add it to the first level menu.

Try it! Putting the extension in a file named core/src/net/sf/openrocket/simulation/extensions/example/AirStartExample.java and the provider in core/src/net/sf/openrocket/simulation/extensions/example/AirStartExampleProvider.java, compiling, and running will give you a new entry in the extensions menu; adding it to the simulation will cause your simulation to start at an altitude of 1000 meters.

Adding a Configurator[edit]

To be able to configure the extension at run time, we need to write a configurator and provide it with a way to communicate with the extension First, we'll modify the extension as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package net.sf.openrocket.simulation.extension.example;

import net.sf.openrocket.simulation.SimulationStatus;
import net.sf.openrocket.simulation.exception.SimulationException;
import net.sf.openrocket.simulation.extension.AbstractSimulationExtension;
import net.sf.openrocket.simulation.listeners.AbstractSimulationListener;
import net.sf.openrocket.util.Coordinate;

/**
 * Simulation extension that launches a rocket from a specific altitude.
 */
public class AirStartExample extends AbstractSimulationExtension {

    public void initialize(SimulationConditions conditions) throws SimulationException {
        conditions.getSimulationListenerList().add(new AirStartListener());
    }

    @Override
    public String getName() {
        return "Air-Start Example";
    }

    @Override
    public String getDescription() {
        return "Simple extension example for air-start";
    }

    public double getLaunchAltitude() {
        return config.getDouble("launchAltitude", 1000.0);
    }

    public void setLaunchAltitude(double launchAltitude) {
        config.put("launchAltitude", launchAltitude);
        fireChangeEvent();
    }
        
    private class AirStartListener extends AbstractSimulationListener {

        @Override
        public void startSimulation(SimulationStatus status) throws SimulationException {

            status.setRocketPosition(new Coordinate(0, 0, getLaunchAltitude()));
        }
    }
}

This adds two methods to the extension (getLaunchAltitude() and setLaunchAltitude()), and calls getLaunchAltitude() from within the listener to obtain the configured launch altitude. config is a Config object, provided by AbstractSimulationExtension (so it isn't necessary to call a constructor yourself). core/src/net/sf/openrocket/util/Config.java includes methods to interact with a configurator, allowing the extension to obtain double, string, and other configuration values.

In this case, we'll only be defining a single configuration field in our configurator, "launchAltitude".

The getLaunchAltitude() method obtains the air-start altitude for the simulation from the configuration, and sets a default air-start altitude of 1000 meters. Our startSimulation() method has been modified to make use of this to obtain the user's requested air-start altitude from the configurator, in place of the original hard-coded value.

The setLaunchAltitude() method places a new launch altitude in the configuration. While our extension doesn't make use of this method directly, it will be necessary for our configurator. The call to fireChangeEvent() in this method assures that the changes we make to the air-start altitude are propagated throughout the simulation.

The configurator itself looks like this

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
30
31
42
43
package net.sf.openrocket.simulation.extension.example;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;

import net.sf.openrocket.document.Simulation;
import net.sf.openrocket.gui.SpinnerEditor;
import net.sf.openrocket.gui.adaptors.DoubleModel;
import net.sf.openrocket.gui.components.BasicSlider;
import net.sf.openrocket.gui.components.UnitSelector;
import net.sf.openrocket.plugin.Plugin;
import net.sf.openrocket.simulation.extension.AbstractSwingSimulationExtensionConfigurator;
import net.sf.openrocket.unit.UnitGroup;

@Plugin
public class AirStartConfigurator extends AbstractSwingSimulationExtensionConfigurator<AirStart> {
	
    public AirStartConfigurator() {
        super(AirStart.class);
    }
	
    @Override
    protected JComponent getConfigurationComponent(AirStart extension, Simulation simulation, JPanel panel) {
        panel.add(new JLabel("Launch altitude:"));

        DoubleModel m = new DoubleModel(extension, "LaunchAltitude", UnitGroup.UNITS_DISTANCE, 0);

        JSpinner spin = new JSpinner(m.getSpinnerModel());
        spin.setEditor(new SpinnerEditor(spin));
        panel.add(spin, "w 65lp!");

        UnitSelector unit = new UnitSelector(m);
        panel.add(unit, "w 25");

        BasicSlider slider = new BasicSlider(m.getSliderModel(0, 5000));
        panel.add(slider, "w 75lp, wrap");
		
        return panel;
    }
}

After some boilerplate, this class creates a new DoubleModel to manage the airstart altitude. The most important things to notice about the DoubleModel constructor are the parameters "LaunchAltitude" and UnitGroup.UNITS_DISTANCE.

  • "LaunchAltitude" is used by the system to synthesize calls to the getLaunchAltitude() and setLaunchAltitude() methods mentioned earlier. The name of the DoubleModel, "LaunchAltitude", MUST match the names of the corresponding set and get methods exactly. If they don't, there will be an exception at run time when the user attempts to change the value.
  • UnitGroup.UNITS_DISTANCE specifies the unit group to be used by this DoubleModel. OpenRocket uses SI (MKS) units internally, but allows users to select the units they wish to use for their interface. Specifying a UnitGroup provides the conversions and unit displays for the interface. The available UnitGroups are defined in core/src/net/sf/openrocket/unit/UnitGroup.java

The remaining code in this method creates a JSpinner, a UnitSelector, and a BasicSlider all referring to this DoubleModel. When the resulting configurator is displayed, it looks like this:

Example Configurator.png

The surrounding Dialog window and the Close button are provided by the system.

Example User Extensions Provided With OpenRocket[edit]

Several examples of user extensions are provided in the OpenRocket source tree. As mentioned previously, the extensions are all located in core/src/net/sf/openrocket/simulation/extension/example and their configurators are all located in swing/src/net/sf/openrocket/simulation/extension/example. Also recall that every extension has a corresponding provider.

Purpose Extension Configurator
Set air-start altitude and velocity AirStart.java AirStartConfigurator.java
Save some simulation values as a CSV file CSVSave.java (none)
Calculate damping moment coefficient after every simulation step DampingMoment.java (none)
Print summary of simulation progress after each step PrintSimulation.java (none)
Active roll control RollControl.java RollControlConfigurator.java
Stop simulation at specified time or number of steps StopSimulation StopSimulationConfigurator

Note: documentation for adding user-created simulation listeners, without making use of the full extension mechanism, is also available at Simulation Listeners