7b4e0f251fc02541f57a2dd4c56e58fafce8da89
[debian/openrocket] / src / net / sf / openrocket / document / Simulation.java
1 package net.sf.openrocket.document;
2
3 import java.util.List;
4
5 import javax.swing.event.ChangeEvent;
6 import javax.swing.event.ChangeListener;
7
8 import net.sf.openrocket.aerodynamics.AerodynamicCalculator;
9 import net.sf.openrocket.aerodynamics.BarrowmanCalculator;
10 import net.sf.openrocket.aerodynamics.WarningSet;
11 import net.sf.openrocket.logging.LogHelper;
12 import net.sf.openrocket.masscalc.BasicMassCalculator;
13 import net.sf.openrocket.masscalc.MassCalculator;
14 import net.sf.openrocket.rocketcomponent.Configuration;
15 import net.sf.openrocket.rocketcomponent.Rocket;
16 import net.sf.openrocket.simulation.BasicEventSimulationEngine;
17 import net.sf.openrocket.simulation.FlightData;
18 import net.sf.openrocket.simulation.GUISimulationConditions;
19 import net.sf.openrocket.simulation.RK4SimulationStepper;
20 import net.sf.openrocket.simulation.SimulationConditions;
21 import net.sf.openrocket.simulation.SimulationEngine;
22 import net.sf.openrocket.simulation.SimulationStepper;
23 import net.sf.openrocket.simulation.exception.SimulationException;
24 import net.sf.openrocket.simulation.exception.SimulationListenerException;
25 import net.sf.openrocket.simulation.listeners.SimulationListener;
26 import net.sf.openrocket.startup.Application;
27 import net.sf.openrocket.util.ArrayList;
28 import net.sf.openrocket.util.BugException;
29 import net.sf.openrocket.util.ChangeSource;
30 import net.sf.openrocket.util.SafetyMutex;
31
32 /**
33  * A class defining a simulation, its conditions and simulated data.
34  * <p>
35  * This class is not thread-safe and enforces single-threaded access with a
36  * SafetyMutex.
37  * 
38  * @author Sampo Niskanen <sampo.niskanen@iki.fi>
39  */
40 public class Simulation implements ChangeSource, Cloneable {
41         private static final LogHelper log = Application.getLogger();
42         
43         public static enum Status {
44                 /** Up-to-date */
45                 UPTODATE,
46
47                 /** Loaded from file, status probably up-to-date */
48                 LOADED,
49
50                 /** Data outdated */
51                 OUTDATED,
52
53                 /** Imported external data */
54                 EXTERNAL,
55
56                 /** Not yet simulated */
57                 NOT_SIMULATED
58         }
59         
60         private SafetyMutex mutex = SafetyMutex.newInstance();
61         
62         private final Rocket rocket;
63         
64         private String name = "";
65         
66         private Status status = Status.NOT_SIMULATED;
67         
68         /** The conditions to use */
69         // TODO: HIGH: Change to use actual conditions class??
70         private GUISimulationConditions conditions;
71         
72         private ArrayList<String> simulationListeners = new ArrayList<String>();
73         
74         private final Class<? extends SimulationEngine> simulationEngineClass = BasicEventSimulationEngine.class;
75         private Class<? extends SimulationStepper> simulationStepperClass = RK4SimulationStepper.class;
76         private Class<? extends AerodynamicCalculator> aerodynamicCalculatorClass = BarrowmanCalculator.class;
77         private Class<? extends MassCalculator> massCalculatorClass = BasicMassCalculator.class;
78         
79
80
81         /** Listeners for this object */
82         private List<ChangeListener> listeners = new ArrayList<ChangeListener>();
83         
84
85         /** The conditions actually used in the previous simulation, or null */
86         private GUISimulationConditions simulatedConditions = null;
87         private String simulatedMotors = null;
88         private FlightData simulatedData = null;
89         private int simulatedRocketID = -1;
90         
91         
92         /**
93          * Create a new simulation for the rocket.  The initial motor configuration is
94          * taken from the default rocket configuration.
95          * 
96          * @param rocket        the rocket associated with the simulation.
97          */
98         public Simulation(Rocket rocket) {
99                 this.rocket = rocket;
100                 this.status = Status.NOT_SIMULATED;
101                 
102                 conditions = new GUISimulationConditions(rocket);
103                 conditions.setMotorConfigurationID(
104                                 rocket.getDefaultConfiguration().getMotorConfigurationID());
105                 conditions.addChangeListener(new ConditionListener());
106         }
107         
108         
109         public Simulation(Rocket rocket, Status status, String name, GUISimulationConditions conditions,
110                         List<String> listeners, FlightData data) {
111                 
112                 if (rocket == null)
113                         throw new IllegalArgumentException("rocket cannot be null");
114                 if (status == null)
115                         throw new IllegalArgumentException("status cannot be null");
116                 if (name == null)
117                         throw new IllegalArgumentException("name cannot be null");
118                 if (conditions == null)
119                         throw new IllegalArgumentException("conditions cannot be null");
120                 
121                 this.rocket = rocket;
122                 
123                 if (status == Status.UPTODATE) {
124                         this.status = Status.LOADED;
125                 } else if (data == null) {
126                         this.status = Status.NOT_SIMULATED;
127                 } else {
128                         this.status = status;
129                 }
130                 
131                 this.name = name;
132                 
133                 this.conditions = conditions;
134                 conditions.addChangeListener(new ConditionListener());
135                 
136                 if (listeners != null) {
137                         this.simulationListeners.addAll(listeners);
138                 }
139                 
140
141                 if (data != null && this.status != Status.NOT_SIMULATED) {
142                         simulatedData = data;
143                         if (this.status == Status.LOADED) {
144                                 simulatedConditions = conditions.clone();
145                                 simulatedRocketID = rocket.getModID();
146                         }
147                 }
148                 
149         }
150         
151         
152         /**
153          * Return the rocket associated with this simulation.
154          * 
155          * @return      the rocket.
156          */
157         public Rocket getRocket() {
158                 mutex.verify();
159                 return rocket;
160         }
161         
162         
163         /**
164          * Return a newly created Configuration for this simulation.  The configuration
165          * has the motor ID set and all stages active.
166          * 
167          * @return      a newly created Configuration of the launch conditions.
168          */
169         public Configuration getConfiguration() {
170                 mutex.verify();
171                 Configuration c = new Configuration(rocket);
172                 c.setMotorConfigurationID(conditions.getMotorConfigurationID());
173                 c.setAllStages();
174                 return c;
175         }
176         
177         /**
178          * Returns the simulation conditions attached to this simulation.  The conditions
179          * may be modified freely, and the status of the simulation will change to reflect
180          * the changes.
181          * 
182          * @return the simulation conditions.
183          */
184         public GUISimulationConditions getConditions() {
185                 mutex.verify();
186                 return conditions;
187         }
188         
189         
190         /**
191          * Get the list of simulation listeners.  The returned list is the one used by
192          * this object; changes to it will reflect changes in the simulation.
193          * 
194          * @return      the actual list of simulation listeners.
195          */
196         public List<String> getSimulationListeners() {
197                 mutex.verify();
198                 return simulationListeners;
199         }
200         
201         
202         /**
203          * Return the user-defined name of the simulation.
204          * 
205          * @return      the name for the simulation.
206          */
207         public String getName() {
208                 mutex.verify();
209                 return name;
210         }
211         
212         /**
213          * Set the user-defined name of the simulation.  Setting the name to
214          * null yields an empty name.
215          * 
216          * @param name  the name of the simulation.
217          */
218         public void setName(String name) {
219                 mutex.lock("setName");
220                 try {
221                         if (this.name.equals(name))
222                                 return;
223                         
224                         if (name == null)
225                                 this.name = "";
226                         else
227                                 this.name = name;
228                         
229                         fireChangeEvent();
230                 } finally {
231                         mutex.unlock("setName");
232                 }
233         }
234         
235         
236         /**
237          * Returns the status of this simulation.  This method examines whether the
238          * simulation has been outdated and returns {@link Status#OUTDATED} accordingly.
239          * 
240          * @return the status
241          * @see Status
242          */
243         public Status getStatus() {
244                 mutex.verify();
245                 
246                 if (status == Status.UPTODATE || status == Status.LOADED) {
247                         if (rocket.getFunctionalModID() != simulatedRocketID ||
248                                         !conditions.equals(simulatedConditions))
249                                 return Status.OUTDATED;
250                 }
251                 
252                 return status;
253         }
254         
255         
256
257
258         public void simulate(SimulationListener... additionalListeners)
259                                                 throws SimulationException {
260                 mutex.lock("simulate");
261                 try {
262                         
263                         if (this.status == Status.EXTERNAL) {
264                                 throw new SimulationException("Cannot simulate imported simulation.");
265                         }
266                         
267                         SimulationEngine simulator;
268                         
269                         try {
270                                 simulator = simulationEngineClass.newInstance();
271                         } catch (InstantiationException e) {
272                                 throw new IllegalStateException("Cannot instantiate simulator.", e);
273                         } catch (IllegalAccessException e) {
274                                 throw new IllegalStateException("Cannot access simulator instance?! BUG!", e);
275                         } catch (NullPointerException e) {
276                                 throw new IllegalStateException("Simulator null", e);
277                         }
278                         
279                         SimulationConditions simulationConditions = conditions.toSimulationConditions();
280                         for (SimulationListener l : additionalListeners) {
281                                 simulationConditions.getSimulationListenerList().add(l);
282                         }
283                         
284                         for (String className : simulationListeners) {
285                                 SimulationListener l = null;
286                                 try {
287                                         Class<?> c = Class.forName(className);
288                                         l = (SimulationListener) c.newInstance();
289                                 } catch (Exception e) {
290                                         throw new SimulationListenerException("Could not instantiate listener of " +
291                                                         "class: " + className, e);
292                                 }
293                                 simulationConditions.getSimulationListenerList().add(l);
294                         }
295                         
296                         long t1, t2;
297                         log.debug("Simulation: calling simulator");
298                         t1 = System.currentTimeMillis();
299                         simulatedData = simulator.simulate(simulationConditions);
300                         t2 = System.currentTimeMillis();
301                         log.debug("Simulation: returning from simulator, simulation took " + (t2 - t1) + "ms");
302                         
303                         // Set simulated info after simulation, will not be set in case of exception
304                         simulatedConditions = conditions.clone();
305                         simulatedMotors = getConfiguration().getMotorConfigurationDescription();
306                         simulatedRocketID = rocket.getFunctionalModID();
307                         
308                         status = Status.UPTODATE;
309                         fireChangeEvent();
310                 } finally {
311                         mutex.unlock("simulate");
312                 }
313         }
314         
315         
316         /**
317          * Return the conditions used in the previous simulation, or <code>null</code>
318          * if this simulation has not been run.
319          * 
320          * @return      the conditions used in the previous simulation, or <code>null</code>.
321          */
322         public GUISimulationConditions getSimulatedConditions() {
323                 mutex.verify();
324                 return simulatedConditions;
325         }
326         
327         /**
328          * Return the warnings generated in the previous simulation, or
329          * <code>null</code> if this simulation has not been run.  This is the same
330          * warning set as contained in the <code>FlightData</code> object.
331          * 
332          * @return      the warnings during the previous simulation, or <code>null</code>.
333          * @see         FlightData#getWarningSet()
334          */
335         public WarningSet getSimulatedWarnings() {
336                 mutex.verify();
337                 if (simulatedData == null)
338                         return null;
339                 return simulatedData.getWarningSet();
340         }
341         
342         
343         /**
344          * Return a string describing the motor configuration of the previous simulation,
345          * or <code>null</code> if this simulation has not been run.
346          * 
347          * @return      a description of the motor configuration of the previous simulation, or
348          *                      <code>null</code>.
349          * @see         Rocket#getMotorConfigurationNameOrDescription(String)
350          */
351         public String getSimulatedMotorDescription() {
352                 mutex.verify();
353                 return simulatedMotors;
354         }
355         
356         /**
357          * Return the flight data of the previous simulation, or <code>null</code> if
358          * this simulation has not been run.
359          * 
360          * @return      the flight data of the previous simulation, or <code>null</code>.
361          */
362         public FlightData getSimulatedData() {
363                 mutex.verify();
364                 return simulatedData;
365         }
366         
367         
368
369         /**
370          * Returns a copy of this simulation suitable for cut/copy/paste operations.  
371          * This excludes any simulated data.
372          *  
373          * @return      a copy of this simulation and its conditions.
374          */
375         public Simulation copy() {
376                 mutex.lock("copy");
377                 try {
378                         
379                         Simulation copy = (Simulation) super.clone();
380                         
381                         copy.mutex = SafetyMutex.newInstance();
382                         copy.status = Status.NOT_SIMULATED;
383                         copy.conditions = this.conditions.clone();
384                         copy.simulationListeners = this.simulationListeners.clone();
385                         copy.listeners = new ArrayList<ChangeListener>();
386                         copy.simulatedConditions = null;
387                         copy.simulatedMotors = null;
388                         copy.simulatedData = null;
389                         copy.simulatedRocketID = -1;
390                         
391                         return copy;
392                         
393                 } catch (CloneNotSupportedException e) {
394                         throw new BugException("Clone not supported, BUG", e);
395                 } finally {
396                         mutex.unlock("copy");
397                 }
398         }
399         
400         
401         /**
402          * Create a duplicate of this simulation with the specified rocket.  The new
403          * simulation is in non-simulated state.
404          * 
405          * @param newRocket             the rocket for the new simulation.
406          * @return                              a new simulation with the same conditions and properties.
407          */
408         public Simulation duplicateSimulation(Rocket newRocket) {
409                 mutex.lock("duplicateSimulation");
410                 try {
411                         Simulation copy = new Simulation(newRocket);
412                         
413                         copy.name = this.name;
414                         copy.conditions.copyFrom(this.conditions);
415                         copy.simulationListeners = this.simulationListeners.clone();
416                         copy.simulationStepperClass = this.simulationStepperClass;
417                         copy.aerodynamicCalculatorClass = this.aerodynamicCalculatorClass;
418                         
419                         return copy;
420                 } finally {
421                         mutex.unlock("duplicateSimulation");
422                 }
423         }
424         
425         
426
427         @Override
428         public void addChangeListener(ChangeListener listener) {
429                 mutex.verify();
430                 listeners.add(listener);
431         }
432         
433         @Override
434         public void removeChangeListener(ChangeListener listener) {
435                 mutex.verify();
436                 listeners.remove(listener);
437         }
438         
439         protected void fireChangeEvent() {
440                 ChangeListener[] ls = listeners.toArray(new ChangeListener[0]);
441                 ChangeEvent e = new ChangeEvent(this);
442                 for (ChangeListener l : ls) {
443                         l.stateChanged(e);
444                 }
445         }
446         
447         
448
449
450         private class ConditionListener implements ChangeListener {
451                 
452                 private Status oldStatus = null;
453                 
454                 @Override
455                 public void stateChanged(ChangeEvent e) {
456                         if (getStatus() != oldStatus) {
457                                 oldStatus = getStatus();
458                                 fireChangeEvent();
459                         }
460                 }
461         }
462 }