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.rocketcomponent.FinSet;
19 import net.sf.openrocket.rocketcomponent.Rocket;
20 import net.sf.openrocket.rocketcomponent.RocketComponent;
21 import net.sf.openrocket.rocketcomponent.TubeCoupler;
22 import net.sf.openrocket.simulation.FlightData;
23 import net.sf.openrocket.simulation.FlightDataBranch;
24 import net.sf.openrocket.simulation.FlightEvent;
25 import net.sf.openrocket.simulation.SimulationConditions;
26 import net.sf.openrocket.util.MathUtil;
27 import net.sf.openrocket.util.Pair;
28 import net.sf.openrocket.util.Prefs;
29 import net.sf.openrocket.util.Reflection;
30 import net.sf.openrocket.util.TextUtil;
32 public class OpenRocketSaver extends RocketSaver {
35 * Divisor used in converting an integer version to the point-represented version.
36 * The integer version divided by this value is the major version and the remainder is
37 * the minor version. For example 101 corresponds to file version "1.1".
39 public static final int FILE_VERSION_DIVISOR = 100;
42 private static final String OPENROCKET_CHARSET = "UTF-8";
44 private static final String METHOD_PACKAGE = "net.sf.openrocket.file.openrocket.savers";
45 private static final String METHOD_SUFFIX = "Saver";
48 // Estimated storage used by different portions
49 // These have been hand-estimated from saved files
50 private static final int BYTES_PER_COMPONENT_UNCOMPRESSED = 590;
51 private static final int BYTES_PER_COMPONENT_COMPRESSED = 80;
52 private static final int BYTES_PER_SIMULATION_UNCOMPRESSED = 1000;
53 private static final int BYTES_PER_SIMULATION_COMPRESSED = 100;
54 private static final int BYTES_PER_DATAPOINT_UNCOMPRESSED = 350;
55 private static final int BYTES_PER_DATAPOINT_COMPRESSED = 100;
62 public void save(OutputStream output, OpenRocketDocument document, StorageOptions options)
65 if (options.isCompressionEnabled()) {
66 output = new GZIPOutputStream(output);
69 dest = new BufferedWriter(new OutputStreamWriter(output, OPENROCKET_CHARSET));
71 final int fileVersion = calculateNecessaryFileVersion(document, options);
72 final String fileVersionString =
73 (fileVersion / FILE_VERSION_DIVISOR) + "." + (fileVersion % FILE_VERSION_DIVISOR);
78 System.out.println("Writing...");
80 writeln("<?xml version='1.0' encoding='utf-8'?>");
81 writeln("<openrocket version=\"" + fileVersionString + "\" creator=\"OpenRocket "
82 + Prefs.getVersion() + "\">");
85 // Recursively save the rocket structure
86 saveComponent(document.getRocket());
90 // Save all simulations
91 writeln("<simulations>");
94 for (Simulation s: document.getSimulations()) {
98 saveSimulation(s, options.getSimulationTimeSkip());
101 writeln("</simulations>");
104 writeln("</openrocket>");
107 if (options.isCompressionEnabled()) {
108 ((GZIPOutputStream)output).finish();
115 public long estimateFileSize(OpenRocketDocument doc, StorageOptions options) {
119 // Size per component
120 int componentCount = 0;
121 Rocket rocket = doc.getRocket();
122 Iterator<RocketComponent> iterator = rocket.deepIterator(true);
123 while (iterator.hasNext()) {
128 if (options.isCompressionEnabled())
129 size += componentCount * BYTES_PER_COMPONENT_COMPRESSED;
131 size += componentCount * BYTES_PER_COMPONENT_UNCOMPRESSED;
134 // Size per simulation
135 if (options.isCompressionEnabled())
136 size += doc.getSimulationCount() * BYTES_PER_SIMULATION_COMPRESSED;
138 size += doc.getSimulationCount() * BYTES_PER_SIMULATION_UNCOMPRESSED;
141 // Size per flight data point
143 double timeSkip = options.getSimulationTimeSkip();
144 if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) {
145 for (Simulation s: doc.getSimulations()) {
146 FlightData data = s.getSimulatedData();
148 for (int i=0; i < data.getBranchCount(); i++) {
149 pointCount += countFlightDataBranchPoints(data.getBranch(i), timeSkip);
155 if (options.isCompressionEnabled())
156 size += pointCount * BYTES_PER_DATAPOINT_COMPRESSED;
158 size += pointCount * BYTES_PER_DATAPOINT_UNCOMPRESSED;
165 * Determine which file version is required in order to store all the features of the
166 * current design. By default the oldest version that supports all the necessary features
169 * @param document the document to output.
170 * @param opts the storage options.
171 * @return the integer file version to use.
173 private int calculateNecessaryFileVersion(OpenRocketDocument document, StorageOptions opts) {
175 * File version 1.1 is required for:
177 * - components attached to tube coupler
179 * Otherwise use version 1.0.
182 // Check for fin tabs (version 1.1)
183 Iterator<RocketComponent> iterator = document.getRocket().deepIterator();
184 while (iterator.hasNext()) {
185 RocketComponent c = iterator.next();
187 // Check for fin tabs
188 if (c instanceof FinSet) {
189 FinSet fin = (FinSet)c;
190 if (!MathUtil.equals(fin.getTabHeight(),0) &&
191 !MathUtil.equals(fin.getTabLength(), 0)) {
192 return FILE_VERSION_DIVISOR + 1;
196 // Check for components attached to tube coupler
197 if (c instanceof TubeCoupler) {
198 if (c.getChildCount() > 0) {
199 return FILE_VERSION_DIVISOR + 1;
204 // Default (version 1.0)
205 return FILE_VERSION_DIVISOR + 0;
210 @SuppressWarnings("unchecked")
211 private void saveComponent(RocketComponent component) throws IOException {
213 Reflection.Method m = Reflection.findMethod(METHOD_PACKAGE, component, METHOD_SUFFIX,
214 "getElements", RocketComponent.class);
216 throw new RuntimeException("Unable to find saving class for component "+
217 component.getComponentName());
220 // Get the strings to save
221 List<String> list = (List<String>) m.invokeStatic(component);
222 int length = list.size();
224 if (length == 0) // Nothing to do
228 throw new RuntimeException("BUG, component data length less than two lines.");
232 writeln(list.get(0));
236 for (int i=1; i<length-1; i++) {
237 writeln(list.get(i));
240 // Recursively write subcomponents
241 if (component.getChildCount() > 0) {
243 writeln("<subcomponents>");
245 boolean emptyline = false;
246 for (RocketComponent subcomponent: component) {
250 saveComponent(subcomponent);
253 writeln("</subcomponents>");
258 writeln(list.get(length-1));
263 private void saveSimulation(Simulation simulation, double timeSkip) throws IOException {
264 SimulationConditions cond = simulation.getConditions();
266 writeln("<simulation status=\"" + enumToXMLName(simulation.getStatus()) +"\">");
269 writeln("<name>" + escapeXML(simulation.getName()) + "</name>");
270 // TODO: MEDIUM: Other simulators/calculators
271 writeln("<simulator>RK4Simulator</simulator>");
272 writeln("<calculator>BarrowmanCalculator</calculator>");
273 writeln("<conditions>");
276 writeElement("configid", cond.getMotorConfigurationID());
277 writeElement("launchrodlength", cond.getLaunchRodLength());
278 writeElement("launchrodangle", cond.getLaunchRodAngle() * 180.0/Math.PI);
279 writeElement("launchroddirection", cond.getLaunchRodDirection() * 180.0/Math.PI);
280 writeElement("windaverage", cond.getWindSpeedAverage());
281 writeElement("windturbulence", cond.getWindTurbulenceIntensity());
282 writeElement("launchaltitude", cond.getLaunchAltitude());
283 writeElement("launchlatitude", cond.getLaunchLatitude());
285 if (cond.isISAAtmosphere()) {
286 writeln("<atmosphere model=\"isa\"/>");
288 writeln("<atmosphere model=\"extendedisa\">");
290 writeElement("basetemperature", cond.getLaunchTemperature());
291 writeElement("basepressure", cond.getLaunchPressure());
293 writeln("</atmosphere>");
296 writeElement("timestep", cond.getTimeStep());
299 writeln("</conditions>");
302 for (String s: simulation.getSimulationListeners()) {
303 writeElement("listener", escapeXML(s));
307 // Write basic simulation data
309 FlightData data = simulation.getSimulatedData();
311 String str = "<flightdata";
312 if (!Double.isNaN(data.getMaxAltitude()))
313 str += " maxaltitude=\"" + TextUtil.doubleToString(data.getMaxAltitude()) + "\"";
314 if (!Double.isNaN(data.getMaxVelocity()))
315 str += " maxvelocity=\"" + TextUtil.doubleToString(data.getMaxVelocity()) + "\"";
316 if (!Double.isNaN(data.getMaxAcceleration()))
317 str += " maxacceleration=\"" + TextUtil.doubleToString(data.getMaxAcceleration()) + "\"";
318 if (!Double.isNaN(data.getMaxMachNumber()))
319 str += " maxmach=\"" + TextUtil.doubleToString(data.getMaxMachNumber()) + "\"";
320 if (!Double.isNaN(data.getTimeToApogee()))
321 str += " timetoapogee=\"" + TextUtil.doubleToString(data.getTimeToApogee()) + "\"";
322 if (!Double.isNaN(data.getFlightTime()))
323 str += " flighttime=\"" + TextUtil.doubleToString(data.getFlightTime()) + "\"";
324 if (!Double.isNaN(data.getGroundHitVelocity()))
325 str += " groundhitvelocity=\"" + TextUtil.doubleToString(data.getGroundHitVelocity()) + "\"";
330 for (Warning w: data.getWarningSet()) {
331 writeElement("warning", escapeXML(w.toString()));
334 // Check whether to store data
335 if (simulation.getStatus() == Simulation.Status.EXTERNAL) // Always store external data
338 if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) {
339 for (int i=0; i<data.getBranchCount(); i++) {
340 FlightDataBranch branch = data.getBranch(i);
341 saveFlightDataBranch(branch, timeSkip);
346 writeln("</flightdata>");
350 writeln("</simulation>");
356 private void saveFlightDataBranch(FlightDataBranch branch, double timeSkip)
358 double previousTime = -100000;
363 // Retrieve the types from the branch
364 FlightDataBranch.Type[] types = branch.getTypes();
366 if (types.length == 0)
369 // Retrieve the data from the branch
370 List<List<Double>> data = new ArrayList<List<Double>>(types.length);
371 for (int i=0; i<types.length; i++) {
372 data.add(branch.get(types[i]));
374 List<Double> timeData = branch.get(FlightDataBranch.TYPE_TIME);
375 if (timeData == null) {
376 // TODO: MEDIUM: External data may not have time data
377 throw new IllegalArgumentException("Data did not contain time data");
380 // Build the <databranch> tag
381 StringBuilder sb = new StringBuilder();
382 sb.append("<databranch name=\"");
383 sb.append(escapeXML(branch.getBranchName()));
384 sb.append("\" types=\"");
385 for (int i=0; i<types.length; i++) {
388 sb.append(escapeXML(types[i].getName()));
391 writeln(sb.toString());
395 for (Pair<Double,FlightEvent> p: branch.getEvents()) {
396 writeln("<event time=\"" + TextUtil.doubleToString(p.getU())
397 + "\" type=\"" + enumToXMLName(p.getV().getType()) + "\"/>");
401 int length = branch.getLength();
403 writeDataPointString(data, 0, sb);
404 previousTime = timeData.get(0);
407 for (int i=1; i < length-1; i++) {
408 if (Math.abs(timeData.get(i) - previousTime - timeSkip) <
409 Math.abs(timeData.get(i+1) - previousTime - timeSkip)) {
410 writeDataPointString(data, i, sb);
411 previousTime = timeData.get(i);
416 writeDataPointString(data, length-1, sb);
420 writeln("</databranch>");
425 /* TODO: LOW: This is largely duplicated from above! */
426 private int countFlightDataBranchPoints(FlightDataBranch branch, double timeSkip) {
429 double previousTime = -100000;
434 // Retrieve the types from the branch
435 FlightDataBranch.Type[] types = branch.getTypes();
437 if (types.length == 0)
440 List<Double> timeData = branch.get(FlightDataBranch.TYPE_TIME);
441 if (timeData == null) {
442 // TODO: MEDIUM: External data may not have time data
443 throw new IllegalArgumentException("Data did not contain time data");
447 int length = branch.getLength();
450 previousTime = timeData.get(0);
453 for (int i=1; i < length-1; i++) {
454 if (Math.abs(timeData.get(i) - previousTime - timeSkip) <
455 Math.abs(timeData.get(i+1) - previousTime - timeSkip)) {
457 previousTime = timeData.get(i);
470 private void writeDataPointString(List<List<Double>> data, int index, StringBuilder sb)
473 sb.append("<datapoint>");
474 for (int j=0; j < data.size(); j++) {
477 sb.append(TextUtil.doubleToString(data.get(j).get(index)));
479 sb.append("</datapoint>");
480 writeln(sb.toString());
485 private void writeElement(String element, Object content) throws IOException {
488 writeln("<"+element+">"+content+"</"+element+">");
493 private void writeln(String str) throws IOException {
494 if (str.length() == 0) {
499 for (int i=0; i<indent; i++)
506 public static void main(String[] arg) {
507 double d = -0.000000123456789123;
510 for (int i=0; i< 20; i++) {
511 String str = TextUtil.doubleToString(d);
512 System.out.println(str + " -> " + Double.parseDouble(str));
517 System.out.println("Value: "+ Double.parseDouble("1.2345e9"));
523 * Return the XML equivalent of an enum name.
525 * @param e the enum to save.
526 * @return the corresponding XML name.
528 public static String enumToXMLName(Enum<?> e) {
529 return e.name().toLowerCase().replace("_", "");