5b0743e144cfcfae13694acd60e7f4d915842b62
[debian/openrocket] / core / src / net / sf / openrocket / file / motor / RockSimMotorLoader.java
1 package net.sf.openrocket.file.motor;
2
3 import java.io.IOException;
4 import java.io.Reader;
5 import java.nio.charset.Charset;
6 import java.util.ArrayList;
7 import java.util.HashMap;
8 import java.util.List;
9
10 import net.sf.openrocket.aerodynamics.WarningSet;
11 import net.sf.openrocket.file.simplesax.ElementHandler;
12 import net.sf.openrocket.file.simplesax.NullElementHandler;
13 import net.sf.openrocket.file.simplesax.PlainTextHandler;
14 import net.sf.openrocket.file.simplesax.SimpleSAX;
15 import net.sf.openrocket.logging.LogHelper;
16 import net.sf.openrocket.motor.Manufacturer;
17 import net.sf.openrocket.motor.Motor;
18 import net.sf.openrocket.motor.MotorDigest;
19 import net.sf.openrocket.motor.MotorDigest.DataType;
20 import net.sf.openrocket.motor.ThrustCurveMotor;
21 import net.sf.openrocket.startup.Application;
22 import net.sf.openrocket.util.Coordinate;
23
24 import org.xml.sax.InputSource;
25 import org.xml.sax.SAXException;
26
27 public class RockSimMotorLoader extends AbstractMotorLoader {
28         
29         private static final LogHelper log = Application.getLogger();
30         
31         public static final String CHARSET_NAME = "UTF-8";
32         
33         public static final Charset CHARSET = Charset.forName(CHARSET_NAME);
34         
35
36         /** Any delay longer than this will be interpreted as a plugged motor. */
37         private static final int DELAY_LIMIT = 90;
38         
39         
40
41         @Override
42         protected Charset getDefaultCharset() {
43                 return CHARSET;
44         }
45         
46         
47
48         /**
49          * Load a <code>Motor</code> from a RockSim motor definition file specified by the 
50          * <code>Reader</code>. The <code>Reader</code> is responsible for using the correct 
51          * charset.
52          * <p>
53          * If automatic CG/mass calculation is used, then the CG is assumed to be located at 
54          * the center of the motor casing and the mass is calculated from the thrust curve 
55          * by assuming a constant exhaust velocity.
56          * 
57          * @param reader  the source of the file.
58          * @return                a list of the {@link Motor} objects defined in the file.
59          * @throws IOException  if an I/O error occurs or if the file format is invalid.
60          */
61         @Override
62         public List<Motor> load(Reader reader, String filename) throws IOException {
63                 InputSource source = new InputSource(reader);
64                 RSEHandler handler = new RSEHandler();
65                 WarningSet warnings = new WarningSet();
66                 
67                 try {
68                         SimpleSAX.readXML(source, handler, warnings);
69                         return handler.getMotors();
70                 } catch (SAXException e) {
71                         throw new IOException(e.getMessage(), e);
72                 }
73         }
74         
75         
76
77         /**
78          * Initial handler for the RockSim engine files.
79          */
80         private static class RSEHandler extends ElementHandler {
81                 private final List<Motor> motors = new ArrayList<Motor>();
82                 
83                 private RSEMotorHandler motorHandler;
84                 
85                 public List<Motor> getMotors() {
86                         return motors;
87                 }
88                 
89                 @Override
90                 public ElementHandler openElement(String element,
91                                 HashMap<String, String> attributes, WarningSet warnings) throws SAXException {
92                         
93                         if (element.equals("engine-database") ||
94                                         element.equals("engine-list")) {
95                                 // Ignore <engine-database> and <engine-list> elements
96                                 return this;
97                         }
98                         
99                         if (element.equals("version")) {
100                                 // Ignore <version> elements completely
101                                 return null;
102                         }
103                         
104                         if (element.equals("engine")) {
105                                 motorHandler = new RSEMotorHandler(attributes);
106                                 return motorHandler;
107                         }
108                         
109                         return null;
110                 }
111                 
112                 @Override
113                 public void closeElement(String element, HashMap<String, String> attributes,
114                                 String content, WarningSet warnings) throws SAXException {
115                         
116                         if (element.equals("engine")) {
117                                 Motor motor = motorHandler.getMotor();
118                                 motors.add(motor);
119                         }
120                 }
121         }
122         
123         
124         /**
125          * Handler for a RockSim engine file <motor> element.
126          */
127         private static class RSEMotorHandler extends ElementHandler {
128                 
129                 private final String manufacturer;
130                 private final String designation;
131                 private final double[] delays;
132                 private final double diameter;
133                 private final double length;
134                 private final double initMass;
135                 private final double propMass;
136                 private final Motor.Type type;
137                 private boolean calculateMass;
138                 private boolean calculateCG;
139                 
140                 private String description = "";
141                 
142                 private List<Double> time;
143                 private List<Double> force;
144                 private List<Double> mass;
145                 private List<Double> cg;
146                 
147                 private RSEMotorDataHandler dataHandler = null;
148                 
149                 
150                 public RSEMotorHandler(HashMap<String, String> attributes) throws SAXException {
151                         String str;
152                         
153                         // Manufacturer
154                         str = attributes.get("mfg");
155                         if (str == null)
156                                 throw new SAXException("Manufacturer missing");
157                         manufacturer = str;
158                         
159                         // Designation
160                         str = attributes.get("code");
161                         if (str == null)
162                                 throw new SAXException("Designation missing");
163                         designation = removeDelay(str);
164                         
165                         // Delays
166                         ArrayList<Double> delayList = new ArrayList<Double>();
167                         str = attributes.get("delays");
168                         if (str != null) {
169                                 String[] split = str.split(",");
170                                 for (String delay : split) {
171                                         try {
172                                                 
173                                                 double d = Double.parseDouble(delay);
174                                                 if (d >= DELAY_LIMIT)
175                                                         d = Motor.PLUGGED;
176                                                 delayList.add(d);
177                                                 
178                                         } catch (NumberFormatException e) {
179                                                 if (str.equalsIgnoreCase("P") || str.equalsIgnoreCase("plugged")) {
180                                                         delayList.add(Motor.PLUGGED);
181                                                 }
182                                         }
183                                 }
184                         }
185                         delays = new double[delayList.size()];
186                         for (int i = 0; i < delayList.size(); i++) {
187                                 delays[i] = delayList.get(i);
188                         }
189                         
190                         // Diameter
191                         str = attributes.get("dia");
192                         if (str == null)
193                                 throw new SAXException("Diameter missing");
194                         try {
195                                 diameter = Double.parseDouble(str) / 1000.0;
196                         } catch (NumberFormatException e) {
197                                 throw new SAXException("Invalid diameter " + str);
198                         }
199                         
200                         // Length
201                         str = attributes.get("len");
202                         if (str == null)
203                                 throw new SAXException("Length missing");
204                         try {
205                                 length = Double.parseDouble(str) / 1000.0;
206                         } catch (NumberFormatException e) {
207                                 throw new SAXException("Invalid length " + str);
208                         }
209                         
210                         // Initial mass
211                         str = attributes.get("initWt");
212                         if (str == null)
213                                 throw new SAXException("Initial mass missing");
214                         try {
215                                 initMass = Double.parseDouble(str) / 1000.0;
216                         } catch (NumberFormatException e) {
217                                 throw new SAXException("Invalid initial mass " + str);
218                         }
219                         
220                         // Propellant mass
221                         str = attributes.get("propWt");
222                         if (str == null)
223                                 throw new SAXException("Propellant mass missing");
224                         try {
225                                 propMass = Double.parseDouble(str) / 1000.0;
226                         } catch (NumberFormatException e) {
227                                 throw new SAXException("Invalid propellant mass " + str);
228                         }
229                         
230                         if (propMass > initMass) {
231                                 throw new SAXException("Propellant weight exceeds total weight in " +
232                                                 "RockSim engine format");
233                         }
234                         
235                         // Motor type
236                         str = attributes.get("Type");
237                         type = Motor.Type.fromName(str);
238                         
239                         // Calculate mass
240                         str = attributes.get("auto-calc-mass");
241                         if ("0".equals(str) || "false".equalsIgnoreCase(str)) {
242                                 calculateMass = false;
243                         } else {
244                                 calculateMass = true;
245                         }
246                         
247                         // Calculate CG
248                         str = attributes.get("auto-calc-cg");
249                         if ("0".equals(str) || "false".equalsIgnoreCase(str)) {
250                                 calculateCG = false;
251                         } else {
252                                 calculateCG = true;
253                         }
254                 }
255                 
256                 @Override
257                 public ElementHandler openElement(String element,
258                                 HashMap<String, String> attributes, WarningSet warnings) throws SAXException {
259                         
260                         if (element.equals("comments")) {
261                                 return PlainTextHandler.INSTANCE;
262                         }
263                         
264                         if (element.equals("data")) {
265                                 if (dataHandler != null) {
266                                         throw new SAXException("Multiple data elements encountered in motor " +
267                                                         "definition");
268                                 }
269                                 dataHandler = new RSEMotorDataHandler();
270                                 return dataHandler;
271                         }
272                         
273                         warnings.add("Unknown element '" + element + "' encountered, ignoring.");
274                         return null;
275                 }
276                 
277                 @Override
278                 public void closeElement(String element, HashMap<String, String> attributes,
279                                 String content, WarningSet warnings) {
280                         
281                         if (element.equals("comments")) {
282                                 if (description.length() > 0) {
283                                         description = description + "\n\n" + content.trim();
284                                 } else {
285                                         description = content.trim();
286                                 }
287                                 return;
288                         }
289                         
290                         if (element.equals("data")) {
291                                 time = dataHandler.getTime();
292                                 force = dataHandler.getForce();
293                                 mass = dataHandler.getMass();
294                                 cg = dataHandler.getCG();
295                                 
296                                 sortLists(time, force, mass, cg);
297                                 
298                                 for (double d : mass) {
299                                         if (Double.isNaN(d)) {
300                                                 calculateMass = true;
301                                                 break;
302                                         }
303                                 }
304                                 for (double d : cg) {
305                                         if (Double.isNaN(d)) {
306                                                 calculateCG = true;
307                                                 break;
308                                         }
309                                 }
310                                 return;
311                         }
312                 }
313                 
314                 public Motor getMotor() throws SAXException {
315                         if (time == null || time.size() == 0)
316                                 throw new SAXException("Illegal motor data");
317                         
318
319                         finalizeThrustCurve(time, force, mass, cg);
320                         final int n = time.size();
321                         
322                         if (hasIllegalValue(mass))
323                                 calculateMass = true;
324                         if (hasIllegalValue(cg))
325                                 calculateCG = true;
326                         
327                         if (calculateMass) {
328                                 mass = calculateMass(time, force, initMass, propMass);
329                         }
330                         if (calculateCG) {
331                                 for (int i = 0; i < n; i++) {
332                                         cg.set(i, length / 2);
333                                 }
334                         }
335                         
336                         double[] timeArray = toArray(time);
337                         double[] thrustArray = toArray(force);
338                         Coordinate[] cgArray = new Coordinate[n];
339                         for (int i = 0; i < n; i++) {
340                                 cgArray[i] = new Coordinate(cg.get(i), 0, 0, mass.get(i));
341                         }
342                         
343
344                         // Create the motor digest from all data available in the file
345                         MotorDigest motorDigest = new MotorDigest();
346                         motorDigest.update(DataType.TIME_ARRAY, timeArray);
347                         if (!calculateMass) {
348                                 motorDigest.update(DataType.MASS_PER_TIME, toArray(mass));
349                         } else {
350                                 motorDigest.update(DataType.MASS_SPECIFIC, initMass, initMass - propMass);
351                         }
352                         if (!calculateCG) {
353                                 motorDigest.update(DataType.CG_PER_TIME, toArray(cg));
354                         }
355                         motorDigest.update(DataType.FORCE_PER_TIME, thrustArray);
356                         // TODO: HIGH: Motor digest?
357                         //                      final String digest = motorDigest.getDigest();
358                         
359
360                         try {
361                                 Manufacturer m = Manufacturer.getManufacturer(manufacturer);
362                                 Motor.Type t = type;
363                                 if (t == Motor.Type.UNKNOWN) {
364                                         t = m.getMotorType();
365                                 } else {
366                                         if (m.getMotorType() != Motor.Type.UNKNOWN && m.getMotorType() != t) {
367                                                 log.warn("Loaded motor type inconsistent with manufacturer," +
368                                                                 " loaded type=" + t + " manufacturer=" + m +
369                                                                 " manufacturer type=" + m.getMotorType() +
370                                                                 " designation=" + designation);
371                                         }
372                                 }
373                                 
374                                 return new ThrustCurveMotor(m, designation, description, t,
375                                                 delays, diameter, length, timeArray, thrustArray, cgArray);
376                         } catch (IllegalArgumentException e) {
377                                 throw new SAXException("Illegal motor data", e);
378                         }
379                 }
380         }
381         
382         
383         /**
384          * Handler for the <data> element in a RockSim engine file motor definition.
385          */
386         private static class RSEMotorDataHandler extends ElementHandler {
387                 
388                 private final List<Double> time = new ArrayList<Double>();
389                 private final List<Double> force = new ArrayList<Double>();
390                 private final List<Double> mass = new ArrayList<Double>();
391                 private final List<Double> cg = new ArrayList<Double>();
392                 
393                 
394                 public List<Double> getTime() {
395                         return time;
396                 }
397                 
398                 public List<Double> getForce() {
399                         return force;
400                 }
401                 
402                 public List<Double> getMass() {
403                         return mass;
404                 }
405                 
406                 public List<Double> getCG() {
407                         return cg;
408                 }
409                 
410                 
411                 @Override
412                 public ElementHandler openElement(String element,
413                                 HashMap<String, String> attributes, WarningSet warnings) {
414                         
415                         if (element.equals("eng-data")) {
416                                 return NullElementHandler.INSTANCE;
417                         }
418                         
419                         warnings.add("Unknown element '" + element + "' encountered, ignoring.");
420                         return null;
421                 }
422                 
423                 @Override
424                 public void closeElement(String element, HashMap<String, String> attributes,
425                                 String content, WarningSet warnings) throws SAXException {
426                         
427                         double t = parseDouble(attributes.get("t"));
428                         double f = parseDouble(attributes.get("f"));
429                         double m = parseDouble(attributes.get("m")) / 1000.0;
430                         double g = parseDouble(attributes.get("cg")) / 1000.0;
431                         
432                         if (Double.isNaN(t) || Double.isNaN(f)) {
433                                 throw new SAXException("Illegal motor data point encountered");
434                         }
435                         
436                         time.add(t);
437                         force.add(f);
438                         mass.add(m);
439                         cg.add(g);
440                 }
441                 
442                 
443                 private double parseDouble(String str) {
444                         if (str == null)
445                                 return Double.NaN;
446                         try {
447                                 return Double.parseDouble(str);
448                         } catch (NumberFormatException e) {
449                                 return Double.NaN;
450                         }
451                 }
452         }
453         
454         
455
456         private static boolean hasIllegalValue(List<Double> list) {
457                 for (Double d : list) {
458                         if (d == null || d.isNaN() || d.isInfinite()) {
459                                 return true;
460                         }
461                 }
462                 return false;
463         }
464         
465         private static double[] toArray(List<Double> list) {
466                 final int n = list.size();
467                 double[] array = new double[n];
468                 for (int i = 0; i < n; i++) {
469                         array[i] = list.get(i);
470                 }
471                 return array;
472         }
473 }