1 package net.sf.openrocket.file.openrocket;
3 import java.io.BufferedWriter;
4 import java.io.IOException;
5 import java.io.OutputStream;
6 import java.io.OutputStreamWriter;
8 import java.util.ArrayList;
9 import java.util.Iterator;
10 import java.util.List;
11 import java.util.Locale;
12 import java.util.zip.GZIPOutputStream;
14 import net.sf.openrocket.aerodynamics.Warning;
15 import net.sf.openrocket.document.OpenRocketDocument;
16 import net.sf.openrocket.document.Simulation;
17 import net.sf.openrocket.document.StorageOptions;
18 import net.sf.openrocket.file.RocketSaver;
19 import net.sf.openrocket.logging.LogHelper;
20 import net.sf.openrocket.rocketcomponent.FinSet;
21 import net.sf.openrocket.rocketcomponent.MotorMount;
22 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
23 import net.sf.openrocket.rocketcomponent.RecoveryDevice.DeployEvent;
24 import net.sf.openrocket.rocketcomponent.Rocket;
25 import net.sf.openrocket.rocketcomponent.RocketComponent;
26 import net.sf.openrocket.rocketcomponent.TubeCoupler;
27 import net.sf.openrocket.simulation.CustomExpression;
28 import net.sf.openrocket.simulation.FlightData;
29 import net.sf.openrocket.simulation.FlightDataBranch;
30 import net.sf.openrocket.simulation.FlightDataType;
31 import net.sf.openrocket.simulation.FlightEvent;
32 import net.sf.openrocket.simulation.SimulationOptions;
33 import net.sf.openrocket.startup.Application;
34 import net.sf.openrocket.util.BugException;
35 import net.sf.openrocket.util.BuildProperties;
36 import net.sf.openrocket.util.MathUtil;
37 import net.sf.openrocket.util.Reflection;
38 import net.sf.openrocket.util.TextUtil;
40 public class OpenRocketSaver extends RocketSaver {
41 private static final LogHelper log = Application.getLogger();
45 * Divisor used in converting an integer version to the point-represented version.
46 * The integer version divided by this value is the major version and the remainder is
47 * the minor version. For example 101 corresponds to file version "1.1".
49 public static final int FILE_VERSION_DIVISOR = 100;
52 private static final String OPENROCKET_CHARSET = "UTF-8";
54 private static final String METHOD_PACKAGE = "net.sf.openrocket.file.openrocket.savers";
55 private static final String METHOD_SUFFIX = "Saver";
58 // Estimated storage used by different portions
59 // These have been hand-estimated from saved files
60 private static final int BYTES_PER_COMPONENT_UNCOMPRESSED = 590;
61 private static final int BYTES_PER_COMPONENT_COMPRESSED = 80;
62 private static final int BYTES_PER_SIMULATION_UNCOMPRESSED = 1000;
63 private static final int BYTES_PER_SIMULATION_COMPRESSED = 100;
64 private static final int BYTES_PER_DATAPOINT_UNCOMPRESSED = 350;
65 private static final int BYTES_PER_DATAPOINT_COMPRESSED = 100;
72 public void save(OutputStream output, OpenRocketDocument document, StorageOptions options)
75 log.info("Saving .ork file");
77 if (options.isCompressionEnabled()) {
78 log.debug("Enabling compression");
79 output = new GZIPOutputStream(output);
82 dest = new BufferedWriter(new OutputStreamWriter(output, OPENROCKET_CHARSET));
84 // Select file version number
85 final int fileVersion = calculateNecessaryFileVersion(document, options);
86 final String fileVersionString =
87 (fileVersion / FILE_VERSION_DIVISOR) + "." + (fileVersion % FILE_VERSION_DIVISOR);
88 log.debug("Storing file version " + fileVersionString);
94 writeln("<?xml version='1.0' encoding='utf-8'?>");
95 writeln("<openrocket version=\"" + fileVersionString + "\" creator=\"OpenRocket "
96 + BuildProperties.getVersion() + "\">");
99 // Recursively save the rocket structure
100 saveComponent(document.getRocket());
104 // Save all simulations
105 writeln("<simulations>");
107 boolean first = true;
108 for (Simulation s : document.getSimulations()) {
112 saveSimulation(s, options.getSimulationTimeSkip());
115 writeln("</simulations>");
118 writeln("</openrocket>");
120 log.debug("Writing complete, flushing buffers");
122 if (options.isCompressionEnabled()) {
123 ((GZIPOutputStream) output).finish();
130 public long estimateFileSize(OpenRocketDocument doc, StorageOptions options) {
134 // Size per component
135 int componentCount = 0;
136 Rocket rocket = doc.getRocket();
137 Iterator<RocketComponent> iterator = rocket.iterator(true);
138 while (iterator.hasNext()) {
143 if (options.isCompressionEnabled())
144 size += componentCount * BYTES_PER_COMPONENT_COMPRESSED;
146 size += componentCount * BYTES_PER_COMPONENT_UNCOMPRESSED;
149 // Size per simulation
150 if (options.isCompressionEnabled())
151 size += doc.getSimulationCount() * BYTES_PER_SIMULATION_COMPRESSED;
153 size += doc.getSimulationCount() * BYTES_PER_SIMULATION_UNCOMPRESSED;
156 // Size per flight data point
158 double timeSkip = options.getSimulationTimeSkip();
159 if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) {
160 for (Simulation s : doc.getSimulations()) {
161 FlightData data = s.getSimulatedData();
163 for (int i = 0; i < data.getBranchCount(); i++) {
164 pointCount += countFlightDataBranchPoints(data.getBranch(i), timeSkip);
170 if (options.isCompressionEnabled())
171 size += pointCount * BYTES_PER_DATAPOINT_COMPRESSED;
173 size += pointCount * BYTES_PER_DATAPOINT_UNCOMPRESSED;
180 * Determine which file version is required in order to store all the features of the
181 * current design. By default the oldest version that supports all the necessary features
184 * @param document the document to output.
185 * @param opts the storage options.
186 * @return the integer file version to use.
188 private int calculateNecessaryFileVersion(OpenRocketDocument document, StorageOptions opts) {
190 * File version 1.5 is requires for:
191 * - saving designs using ComponentPrests
192 * - recovery device deployment on lower stage separation
194 * File version 1.4 is required for:
195 * - saving simulation data
196 * - saving motor data
198 * File version 1.1 is required for:
200 * - components attached to tube coupler
202 * Otherwise use version 1.0.
205 // Search the rocket for any ComponentPresets (version 1.5)
206 for (RocketComponent c : document.getRocket()) {
207 if (c.getPresetComponent() != null) {
208 return FILE_VERSION_DIVISOR + 5;
212 // Search for recovery device deployment type LOWER_STAGE_SEPARATION (version 1.5)
213 for (RocketComponent c : document.getRocket()) {
214 if (c instanceof RecoveryDevice) {
215 if (((RecoveryDevice) c).getDeployEvent() == DeployEvent.LOWER_STAGE_SEPARATION) {
216 return FILE_VERSION_DIVISOR + 5;
221 // Check if design has simulations defined (version 1.4)
222 if (document.getSimulationCount() > 0) {
223 return FILE_VERSION_DIVISOR + 4;
226 // Check for motor definitions (version 1.4)
227 for (RocketComponent c : document.getRocket()) {
228 if (!(c instanceof MotorMount))
231 MotorMount mount = (MotorMount) c;
232 for (String id : document.getRocket().getMotorConfigurationIDs()) {
233 if (mount.getMotor(id) != null) {
234 return FILE_VERSION_DIVISOR + 4;
239 // Check for fin tabs (version 1.1)
240 for (RocketComponent c : document.getRocket()) {
241 // Check for fin tabs
242 if (c instanceof FinSet) {
243 FinSet fin = (FinSet) c;
244 if (!MathUtil.equals(fin.getTabHeight(), 0) &&
245 !MathUtil.equals(fin.getTabLength(), 0)) {
246 return FILE_VERSION_DIVISOR + 1;
250 // Check for components attached to tube coupler
251 if (c instanceof TubeCoupler) {
252 if (c.getChildCount() > 0) {
253 return FILE_VERSION_DIVISOR + 1;
258 // Default (version 1.0)
259 return FILE_VERSION_DIVISOR + 0;
264 @SuppressWarnings("unchecked")
265 private void saveComponent(RocketComponent component) throws IOException {
267 log.debug("Saving component " + component.getComponentName());
269 Reflection.Method m = Reflection.findMethod(METHOD_PACKAGE, component, METHOD_SUFFIX,
270 "getElements", RocketComponent.class);
272 throw new BugException("Unable to find saving class for component " +
273 component.getComponentName());
276 // Get the strings to save
277 List<String> list = (List<String>) m.invokeStatic(component);
278 int length = list.size();
280 if (length == 0) // Nothing to do
284 throw new RuntimeException("BUG, component data length less than two lines.");
288 writeln(list.get(0));
292 for (int i = 1; i < length - 1; i++) {
293 writeln(list.get(i));
296 // Recursively write subcomponents
297 if (component.getChildCount() > 0) {
299 writeln("<subcomponents>");
301 boolean emptyline = false;
302 for (RocketComponent subcomponent : component.getChildren()) {
306 saveComponent(subcomponent);
309 writeln("</subcomponents>");
314 writeln(list.get(length - 1));
318 private void saveSimulation(Simulation simulation, double timeSkip) throws IOException {
319 SimulationOptions cond = simulation.getOptions();
321 writeln("<simulation status=\"" + enumToXMLName(simulation.getStatus()) + "\">");
324 writeln("<name>" + escapeXML(simulation.getName()) + "</name>");
325 // TODO: MEDIUM: Other simulators/calculators
327 writeln("<simulator>RK4Simulator</simulator>");
328 writeln("<calculator>BarrowmanCalculator</calculator>");
330 // Write out custom expressions
331 if (!simulation.getCustomExpressions().isEmpty()){
332 writeln("<customexpressions>"); indent++;
333 for (CustomExpression expression : simulation.getCustomExpressions()){
334 writeln("<expression>"); indent++;
335 writeElement("name", expression.getName());
336 writeElement("symbol", expression.getSymbol());
337 writeElement("unit", expression.getUnit());
338 writeElement("expressionstring", expression.getExpressionString());
339 indent--; writeln("</expression>");
341 indent--; writeln("</customexpressions>");
344 writeln("<conditions>"); indent++;
346 writeElement("configid", cond.getMotorConfigurationID());
347 writeElement("launchrodlength", cond.getLaunchRodLength());
348 writeElement("launchrodangle", cond.getLaunchRodAngle() * 180.0 / Math.PI);
349 writeElement("launchroddirection", cond.getLaunchRodDirection() * 180.0 / Math.PI);
350 writeElement("windaverage", cond.getWindSpeedAverage());
351 writeElement("windturbulence", cond.getWindTurbulenceIntensity());
352 writeElement("launchaltitude", cond.getLaunchAltitude());
353 writeElement("launchlatitude", cond.getLaunchLatitude());
354 writeElement("launchlongitude", cond.getLaunchLongitude());
355 writeElement("geodeticmethod", cond.getGeodeticComputation().name().toLowerCase(Locale.ENGLISH));
357 if (cond.isISAAtmosphere()) {
358 writeln("<atmosphere model=\"isa\"/>");
360 writeln("<atmosphere model=\"extendedisa\">");
362 writeElement("basetemperature", cond.getLaunchTemperature());
363 writeElement("basepressure", cond.getLaunchPressure());
365 writeln("</atmosphere>");
368 writeElement("timestep", cond.getTimeStep());
371 writeln("</conditions>");
374 for (String s : simulation.getSimulationListeners()) {
375 writeElement("listener", escapeXML(s));
378 // Write basic simulation data
380 FlightData data = simulation.getSimulatedData();
382 String str = "<flightdata";
383 if (!Double.isNaN(data.getMaxAltitude()))
384 str += " maxaltitude=\"" + TextUtil.doubleToString(data.getMaxAltitude()) + "\"";
385 if (!Double.isNaN(data.getMaxVelocity()))
386 str += " maxvelocity=\"" + TextUtil.doubleToString(data.getMaxVelocity()) + "\"";
387 if (!Double.isNaN(data.getMaxAcceleration()))
388 str += " maxacceleration=\"" + TextUtil.doubleToString(data.getMaxAcceleration()) + "\"";
389 if (!Double.isNaN(data.getMaxMachNumber()))
390 str += " maxmach=\"" + TextUtil.doubleToString(data.getMaxMachNumber()) + "\"";
391 if (!Double.isNaN(data.getTimeToApogee()))
392 str += " timetoapogee=\"" + TextUtil.doubleToString(data.getTimeToApogee()) + "\"";
393 if (!Double.isNaN(data.getFlightTime()))
394 str += " flighttime=\"" + TextUtil.doubleToString(data.getFlightTime()) + "\"";
395 if (!Double.isNaN(data.getGroundHitVelocity()))
396 str += " groundhitvelocity=\"" + TextUtil.doubleToString(data.getGroundHitVelocity()) + "\"";
397 if (!Double.isNaN(data.getLaunchRodVelocity()))
398 str += " launchrodvelocity=\"" + TextUtil.doubleToString(data.getLaunchRodVelocity()) + "\"";
399 if (!Double.isNaN(data.getDeploymentVelocity()))
400 str += " deploymentvelocity=\"" + TextUtil.doubleToString(data.getDeploymentVelocity()) + "\"";
405 for (Warning w : data.getWarningSet()) {
406 writeElement("warning", escapeXML(w.toString()));
409 // Check whether to store data
410 if (simulation.getStatus() == Simulation.Status.EXTERNAL) // Always store external data
413 if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) {
414 for (int i = 0; i < data.getBranchCount(); i++) {
415 FlightDataBranch branch = data.getBranch(i);
416 saveFlightDataBranch(branch, timeSkip);
421 writeln("</flightdata>");
425 writeln("</simulation>");
431 private void saveFlightDataBranch(FlightDataBranch branch, double timeSkip)
433 double previousTime = -100000;
438 // Retrieve the types from the branch
439 FlightDataType[] types = branch.getTypes();
441 if (types.length == 0)
444 // Retrieve the data from the branch
445 List<List<Double>> data = new ArrayList<List<Double>>(types.length);
446 for (int i = 0; i < types.length; i++) {
447 data.add(branch.get(types[i]));
449 List<Double> timeData = branch.get(FlightDataType.TYPE_TIME);
451 // Build the <databranch> tag
452 StringBuilder sb = new StringBuilder();
453 sb.append("<databranch name=\"");
454 sb.append(escapeXML(branch.getBranchName()));
455 sb.append("\" types=\"");
456 for (int i = 0; i < types.length; i++) {
459 sb.append(escapeXML(types[i].getName()));
462 writeln(sb.toString());
466 for (FlightEvent event : branch.getEvents()) {
467 writeln("<event time=\"" + TextUtil.doubleToString(event.getTime())
468 + "\" type=\"" + enumToXMLName(event.getType()) + "\"/>");
472 int length = branch.getLength();
474 writeDataPointString(data, 0, sb);
475 previousTime = timeData.get(0);
478 for (int i = 1; i < length - 1; i++) {
479 if (timeData != null) {
480 if (Math.abs(timeData.get(i) - previousTime - timeSkip) < Math.abs(timeData.get(i + 1) - previousTime - timeSkip)) {
481 writeDataPointString(data, i, sb);
482 previousTime = timeData.get(i);
485 // If time data is not available, write all points
486 writeDataPointString(data, i, sb);
491 writeDataPointString(data, length - 1, sb);
495 writeln("</databranch>");
500 /* TODO: LOW: This is largely duplicated from above! */
501 private int countFlightDataBranchPoints(FlightDataBranch branch, double timeSkip) {
504 double previousTime = -100000;
509 // Retrieve the types from the branch
510 FlightDataType[] types = branch.getTypes();
512 if (types.length == 0)
515 List<Double> timeData = branch.get(FlightDataType.TYPE_TIME);
516 if (timeData == null) {
517 // If time data not available, store all points
518 return branch.getLength();
522 int length = branch.getLength();
525 previousTime = timeData.get(0);
528 for (int i = 1; i < length - 1; i++) {
529 if (Math.abs(timeData.get(i) - previousTime - timeSkip) < Math.abs(timeData.get(i + 1) - previousTime - timeSkip)) {
531 previousTime = timeData.get(i);
544 private void writeDataPointString(List<List<Double>> data, int index, StringBuilder sb)
547 sb.append("<datapoint>");
548 for (int j = 0; j < data.size(); j++) {
551 sb.append(TextUtil.doubleToString(data.get(j).get(index)));
553 sb.append("</datapoint>");
554 writeln(sb.toString());
559 private void writeElement(String element, Object content) throws IOException {
562 writeln("<" + element + ">" + content + "</" + element + ">");
567 private void writeln(String str) throws IOException {
568 if (str.length() == 0) {
573 for (int i = 0; i < indent; i++)
583 * Return the XML equivalent of an enum name.
585 * @param e the enum to save.
586 * @return the corresponding XML name.
588 public static String enumToXMLName(Enum<?> e) {
589 return e.name().toLowerCase(Locale.ENGLISH).replace("_", "");