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.zip.GZIPOutputStream;
13 import net.sf.openrocket.aerodynamics.Warning;
14 import net.sf.openrocket.document.OpenRocketDocument;
15 import net.sf.openrocket.document.Simulation;
16 import net.sf.openrocket.document.StorageOptions;
17 import net.sf.openrocket.file.RocketSaver;
18 import net.sf.openrocket.logging.LogHelper;
19 import net.sf.openrocket.rocketcomponent.FinSet;
20 import net.sf.openrocket.rocketcomponent.MotorMount;
21 import net.sf.openrocket.rocketcomponent.Rocket;
22 import net.sf.openrocket.rocketcomponent.RocketComponent;
23 import net.sf.openrocket.rocketcomponent.TubeCoupler;
24 import net.sf.openrocket.simulation.FlightData;
25 import net.sf.openrocket.simulation.FlightDataBranch;
26 import net.sf.openrocket.simulation.FlightDataType;
27 import net.sf.openrocket.simulation.FlightEvent;
28 import net.sf.openrocket.simulation.GUISimulationConditions;
29 import net.sf.openrocket.startup.Application;
30 import net.sf.openrocket.util.BugException;
31 import net.sf.openrocket.util.MathUtil;
32 import net.sf.openrocket.util.Prefs;
33 import net.sf.openrocket.util.Reflection;
34 import net.sf.openrocket.util.TextUtil;
36 public class OpenRocketSaver extends RocketSaver {
37 private static final LogHelper log = Application.getLogger();
41 * Divisor used in converting an integer version to the point-represented version.
42 * The integer version divided by this value is the major version and the remainder is
43 * the minor version. For example 101 corresponds to file version "1.1".
45 public static final int FILE_VERSION_DIVISOR = 100;
48 private static final String OPENROCKET_CHARSET = "UTF-8";
50 private static final String METHOD_PACKAGE = "net.sf.openrocket.file.openrocket.savers";
51 private static final String METHOD_SUFFIX = "Saver";
54 // Estimated storage used by different portions
55 // These have been hand-estimated from saved files
56 private static final int BYTES_PER_COMPONENT_UNCOMPRESSED = 590;
57 private static final int BYTES_PER_COMPONENT_COMPRESSED = 80;
58 private static final int BYTES_PER_SIMULATION_UNCOMPRESSED = 1000;
59 private static final int BYTES_PER_SIMULATION_COMPRESSED = 100;
60 private static final int BYTES_PER_DATAPOINT_UNCOMPRESSED = 350;
61 private static final int BYTES_PER_DATAPOINT_COMPRESSED = 100;
68 public void save(OutputStream output, OpenRocketDocument document, StorageOptions options)
71 log.info("Saving .ork file");
73 if (options.isCompressionEnabled()) {
74 log.debug("Enabling compression");
75 output = new GZIPOutputStream(output);
78 dest = new BufferedWriter(new OutputStreamWriter(output, OPENROCKET_CHARSET));
80 // Select file version number
81 final int fileVersion = calculateNecessaryFileVersion(document, options);
82 final String fileVersionString =
83 (fileVersion / FILE_VERSION_DIVISOR) + "." + (fileVersion % FILE_VERSION_DIVISOR);
84 log.debug("Storing file version " + fileVersionString);
90 writeln("<?xml version='1.0' encoding='utf-8'?>");
91 writeln("<openrocket version=\"" + fileVersionString + "\" creator=\"OpenRocket "
92 + Prefs.getVersion() + "\">");
95 // Recursively save the rocket structure
96 saveComponent(document.getRocket());
100 // Save all simulations
101 writeln("<simulations>");
103 boolean first = true;
104 for (Simulation s : document.getSimulations()) {
108 saveSimulation(s, options.getSimulationTimeSkip());
111 writeln("</simulations>");
114 writeln("</openrocket>");
116 log.debug("Writing complete, flushing buffers");
118 if (options.isCompressionEnabled()) {
119 ((GZIPOutputStream) output).finish();
126 public long estimateFileSize(OpenRocketDocument doc, StorageOptions options) {
130 // Size per component
131 int componentCount = 0;
132 Rocket rocket = doc.getRocket();
133 Iterator<RocketComponent> iterator = rocket.deepIterator(true);
134 while (iterator.hasNext()) {
139 if (options.isCompressionEnabled())
140 size += componentCount * BYTES_PER_COMPONENT_COMPRESSED;
142 size += componentCount * BYTES_PER_COMPONENT_UNCOMPRESSED;
145 // Size per simulation
146 if (options.isCompressionEnabled())
147 size += doc.getSimulationCount() * BYTES_PER_SIMULATION_COMPRESSED;
149 size += doc.getSimulationCount() * BYTES_PER_SIMULATION_UNCOMPRESSED;
152 // Size per flight data point
154 double timeSkip = options.getSimulationTimeSkip();
155 if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) {
156 for (Simulation s : doc.getSimulations()) {
157 FlightData data = s.getSimulatedData();
159 for (int i = 0; i < data.getBranchCount(); i++) {
160 pointCount += countFlightDataBranchPoints(data.getBranch(i), timeSkip);
166 if (options.isCompressionEnabled())
167 size += pointCount * BYTES_PER_DATAPOINT_COMPRESSED;
169 size += pointCount * BYTES_PER_DATAPOINT_UNCOMPRESSED;
176 * Determine which file version is required in order to store all the features of the
177 * current design. By default the oldest version that supports all the necessary features
180 * @param document the document to output.
181 * @param opts the storage options.
182 * @return the integer file version to use.
184 private int calculateNecessaryFileVersion(OpenRocketDocument document, StorageOptions opts) {
186 * File version 1.2 is required for:
187 * - saving motor data
189 * File version 1.1 is required for:
191 * - components attached to tube coupler
193 * Otherwise use version 1.0.
196 // Check for motor definitions (version 1.2)
197 Iterator<RocketComponent> iterator = document.getRocket().deepIterator();
198 while (iterator.hasNext()) {
199 RocketComponent c = iterator.next();
200 if (!(c instanceof MotorMount))
203 MotorMount mount = (MotorMount) c;
204 for (String id : document.getRocket().getMotorConfigurationIDs()) {
205 if (mount.getMotor(id) != null) {
206 return FILE_VERSION_DIVISOR + 2;
211 // Check for fin tabs (version 1.1)
212 iterator = document.getRocket().deepIterator();
213 while (iterator.hasNext()) {
214 RocketComponent c = iterator.next();
216 // Check for fin tabs
217 if (c instanceof FinSet) {
218 FinSet fin = (FinSet) c;
219 if (!MathUtil.equals(fin.getTabHeight(), 0) &&
220 !MathUtil.equals(fin.getTabLength(), 0)) {
221 return FILE_VERSION_DIVISOR + 1;
225 // Check for components attached to tube coupler
226 if (c instanceof TubeCoupler) {
227 if (c.getChildCount() > 0) {
228 return FILE_VERSION_DIVISOR + 1;
233 // Default (version 1.0)
234 return FILE_VERSION_DIVISOR + 0;
239 @SuppressWarnings("unchecked")
240 private void saveComponent(RocketComponent component) throws IOException {
242 log.debug("Saving component " + component.getComponentName());
244 Reflection.Method m = Reflection.findMethod(METHOD_PACKAGE, component, METHOD_SUFFIX,
245 "getElements", RocketComponent.class);
247 throw new BugException("Unable to find saving class for component " +
248 component.getComponentName());
251 // Get the strings to save
252 List<String> list = (List<String>) m.invokeStatic(component);
253 int length = list.size();
255 if (length == 0) // Nothing to do
259 throw new RuntimeException("BUG, component data length less than two lines.");
263 writeln(list.get(0));
267 for (int i = 1; i < length - 1; i++) {
268 writeln(list.get(i));
271 // Recursively write subcomponents
272 if (component.getChildCount() > 0) {
274 writeln("<subcomponents>");
276 boolean emptyline = false;
277 for (RocketComponent subcomponent : component) {
281 saveComponent(subcomponent);
284 writeln("</subcomponents>");
289 writeln(list.get(length - 1));
294 private void saveSimulation(Simulation simulation, double timeSkip) throws IOException {
295 GUISimulationConditions cond = simulation.getConditions();
297 writeln("<simulation status=\"" + enumToXMLName(simulation.getStatus()) + "\">");
300 writeln("<name>" + escapeXML(simulation.getName()) + "</name>");
301 // TODO: MEDIUM: Other simulators/calculators
302 writeln("<simulator>RK4Simulator</simulator>");
303 writeln("<calculator>BarrowmanCalculator</calculator>");
304 writeln("<conditions>");
307 writeElement("configid", cond.getMotorConfigurationID());
308 writeElement("launchrodlength", cond.getLaunchRodLength());
309 writeElement("launchrodangle", cond.getLaunchRodAngle() * 180.0 / Math.PI);
310 writeElement("launchroddirection", cond.getLaunchRodDirection() * 180.0 / Math.PI);
311 writeElement("windaverage", cond.getWindSpeedAverage());
312 writeElement("windturbulence", cond.getWindTurbulenceIntensity());
313 writeElement("launchaltitude", cond.getLaunchAltitude());
314 writeElement("launchlatitude", cond.getLaunchLatitude());
316 if (cond.isISAAtmosphere()) {
317 writeln("<atmosphere model=\"isa\"/>");
319 writeln("<atmosphere model=\"extendedisa\">");
321 writeElement("basetemperature", cond.getLaunchTemperature());
322 writeElement("basepressure", cond.getLaunchPressure());
324 writeln("</atmosphere>");
327 writeElement("timestep", cond.getTimeStep());
330 writeln("</conditions>");
333 for (String s : simulation.getSimulationListeners()) {
334 writeElement("listener", escapeXML(s));
338 // Write basic simulation data
340 FlightData data = simulation.getSimulatedData();
342 String str = "<flightdata";
343 if (!Double.isNaN(data.getMaxAltitude()))
344 str += " maxaltitude=\"" + TextUtil.doubleToString(data.getMaxAltitude()) + "\"";
345 if (!Double.isNaN(data.getMaxVelocity()))
346 str += " maxvelocity=\"" + TextUtil.doubleToString(data.getMaxVelocity()) + "\"";
347 if (!Double.isNaN(data.getMaxAcceleration()))
348 str += " maxacceleration=\"" + TextUtil.doubleToString(data.getMaxAcceleration()) + "\"";
349 if (!Double.isNaN(data.getMaxMachNumber()))
350 str += " maxmach=\"" + TextUtil.doubleToString(data.getMaxMachNumber()) + "\"";
351 if (!Double.isNaN(data.getTimeToApogee()))
352 str += " timetoapogee=\"" + TextUtil.doubleToString(data.getTimeToApogee()) + "\"";
353 if (!Double.isNaN(data.getFlightTime()))
354 str += " flighttime=\"" + TextUtil.doubleToString(data.getFlightTime()) + "\"";
355 if (!Double.isNaN(data.getGroundHitVelocity()))
356 str += " groundhitvelocity=\"" + TextUtil.doubleToString(data.getGroundHitVelocity()) + "\"";
361 for (Warning w : data.getWarningSet()) {
362 writeElement("warning", escapeXML(w.toString()));
365 // Check whether to store data
366 if (simulation.getStatus() == Simulation.Status.EXTERNAL) // Always store external data
369 if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) {
370 for (int i = 0; i < data.getBranchCount(); i++) {
371 FlightDataBranch branch = data.getBranch(i);
372 saveFlightDataBranch(branch, timeSkip);
377 writeln("</flightdata>");
381 writeln("</simulation>");
387 private void saveFlightDataBranch(FlightDataBranch branch, double timeSkip)
389 double previousTime = -100000;
394 // Retrieve the types from the branch
395 FlightDataType[] types = branch.getTypes();
397 if (types.length == 0)
400 // Retrieve the data from the branch
401 List<List<Double>> data = new ArrayList<List<Double>>(types.length);
402 for (int i = 0; i < types.length; i++) {
403 data.add(branch.get(types[i]));
405 List<Double> timeData = branch.get(FlightDataType.TYPE_TIME);
406 if (timeData == null) {
407 // TODO: MEDIUM: External data may not have time data
408 throw new IllegalArgumentException("Data did not contain time data");
411 // Build the <databranch> tag
412 StringBuilder sb = new StringBuilder();
413 sb.append("<databranch name=\"");
414 sb.append(escapeXML(branch.getBranchName()));
415 sb.append("\" types=\"");
416 for (int i = 0; i < types.length; i++) {
419 sb.append(escapeXML(types[i].getName()));
422 writeln(sb.toString());
426 for (FlightEvent event : branch.getEvents()) {
427 writeln("<event time=\"" + TextUtil.doubleToString(event.getTime())
428 + "\" type=\"" + enumToXMLName(event.getType()) + "\"/>");
432 int length = branch.getLength();
434 writeDataPointString(data, 0, sb);
435 previousTime = timeData.get(0);
438 for (int i = 1; i < length - 1; i++) {
439 if (Math.abs(timeData.get(i) - previousTime - timeSkip) < Math.abs(timeData.get(i + 1) - previousTime - timeSkip)) {
440 writeDataPointString(data, i, sb);
441 previousTime = timeData.get(i);
446 writeDataPointString(data, length - 1, sb);
450 writeln("</databranch>");
455 /* TODO: LOW: This is largely duplicated from above! */
456 private int countFlightDataBranchPoints(FlightDataBranch branch, double timeSkip) {
459 double previousTime = -100000;
464 // Retrieve the types from the branch
465 FlightDataType[] types = branch.getTypes();
467 if (types.length == 0)
470 List<Double> timeData = branch.get(FlightDataType.TYPE_TIME);
471 if (timeData == null) {
472 // TODO: MEDIUM: External data may not have time data
473 throw new IllegalArgumentException("Data did not contain time data");
477 int length = branch.getLength();
480 previousTime = timeData.get(0);
483 for (int i = 1; i < length - 1; i++) {
484 if (Math.abs(timeData.get(i) - previousTime - timeSkip) < Math.abs(timeData.get(i + 1) - previousTime - timeSkip)) {
486 previousTime = timeData.get(i);
499 private void writeDataPointString(List<List<Double>> data, int index, StringBuilder sb)
502 sb.append("<datapoint>");
503 for (int j = 0; j < data.size(); j++) {
506 sb.append(TextUtil.doubleToString(data.get(j).get(index)));
508 sb.append("</datapoint>");
509 writeln(sb.toString());
514 private void writeElement(String element, Object content) throws IOException {
517 writeln("<" + element + ">" + content + "</" + element + ">");
522 private void writeln(String str) throws IOException {
523 if (str.length() == 0) {
528 for (int i = 0; i < indent; i++)
538 * Return the XML equivalent of an enum name.
540 * @param e the enum to save.
541 * @return the corresponding XML name.
543 public static String enumToXMLName(Enum<?> e) {
544 return e.name().toLowerCase().replace("_", "");