1 package net.sf.openrocket.rocketcomponent;
3 import java.util.Collection;
4 import java.util.Collections;
5 import java.util.EventListener;
6 import java.util.HashMap;
7 import java.util.Iterator;
8 import java.util.LinkedList;
10 import java.util.UUID;
12 import net.sf.openrocket.l10n.Translator;
13 import net.sf.openrocket.logging.LogHelper;
14 import net.sf.openrocket.motor.Motor;
15 import net.sf.openrocket.startup.Application;
16 import net.sf.openrocket.util.ArrayList;
17 import net.sf.openrocket.util.Chars;
18 import net.sf.openrocket.util.Coordinate;
19 import net.sf.openrocket.util.MathUtil;
20 import net.sf.openrocket.util.StateChangeListener;
21 import net.sf.openrocket.util.UniqueID;
25 * Base for all rocket components. This is the "starting point" for all rocket trees.
26 * It provides the actual implementations of several methods defined in RocketComponent
27 * (eg. the rocket listener lists) and the methods defined in RocketComponent call these.
28 * It also defines some other methods that concern the whole rocket, and helper methods
29 * that keep information about the program state.
31 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
34 public class Rocket extends RocketComponent {
35 private static final LogHelper log = Application.getLogger();
36 private static final Translator trans = Application.getTranslator();
38 public static final double DEFAULT_REFERENCE_LENGTH = 0.01;
42 * List of component change listeners.
44 private List<EventListener> listenerList = new ArrayList<EventListener>();
47 * When freezeList != null, events are not dispatched but stored in the list.
48 * When the structure is thawed, a single combined event will be fired.
50 private List<ComponentChangeEvent> freezeList = null;
54 private int massModID;
55 private int aeroModID;
56 private int treeModID;
57 private int functionalModID;
60 private ReferenceType refType = ReferenceType.MAXIMUM; // Set in constructor
61 private double customReferenceLength = DEFAULT_REFERENCE_LENGTH;
64 // The default configuration used in dialogs
65 private final Configuration defaultConfiguration;
68 private String designer = "";
69 private String revision = "";
72 // Motor configuration list
73 private ArrayList<String> motorConfigurationIDs = new ArrayList<String>();
74 private HashMap<String, String> motorConfigurationNames = new HashMap<String, String>();
76 motorConfigurationIDs.add(null);
80 // Does the rocket have a perfect finish (a notable amount of laminar flow)
81 private boolean perfectFinish = false;
85 ///////////// Constructor /////////////
88 super(RocketComponent.Position.AFTER);
89 modID = UniqueID.next();
93 functionalModID = modID;
94 defaultConfiguration = new Configuration(this);
99 public String getDesigner() {
104 public void setDesigner(String s) {
108 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
112 public String getRevision() {
117 public void setRevision(String s) {
121 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
128 * Return the number of stages in this rocket.
130 * @return the number of stages in this rocket.
132 public int getStageCount() {
134 return this.getChildCount();
139 * Return the non-negative modification ID of this rocket. The ID is changed
140 * every time any change occurs in the rocket. This can be used to check
141 * whether it is necessary to void cached data in cases where listeners can not
142 * or should not be used.
144 * Three other modification IDs are also available, {@link #getMassModID()},
145 * {@link #getAerodynamicModID()} {@link #getTreeModID()}, which change every time
146 * a mass change, aerodynamic change, or tree change occur. Even though the values
147 * of the different modification ID's may be equal, they should be treated totally
150 * Note that undo events restore the modification IDs that were in use at the
151 * corresponding undo level. Subsequent modifications, however, produce modIDs
152 * distinct from those already used.
154 * @return a unique ID number for this modification state.
156 public int getModID() {
161 * Return the non-negative mass modification ID of this rocket. See
162 * {@link #getModID()} for details.
164 * @return a unique ID number for this mass-modification state.
166 public int getMassModID() {
171 * Return the non-negative aerodynamic modification ID of this rocket. See
172 * {@link #getModID()} for details.
174 * @return a unique ID number for this aerodynamic-modification state.
176 public int getAerodynamicModID() {
181 * Return the non-negative tree modification ID of this rocket. See
182 * {@link #getModID()} for details.
184 * @return a unique ID number for this tree-modification state.
186 public int getTreeModID() {
191 * Return the non-negative functional modificationID of this rocket.
192 * This changes every time a functional change occurs.
194 * @return a unique ID number for this functional modification state.
196 public int getFunctionalModID() {
197 return functionalModID;
203 public ReferenceType getReferenceType() {
208 public void setReferenceType(ReferenceType type) {
212 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
216 public double getCustomReferenceLength() {
218 return customReferenceLength;
221 public void setCustomReferenceLength(double length) {
222 if (MathUtil.equals(customReferenceLength, length))
225 this.customReferenceLength = Math.max(length, 0.001);
227 if (refType == ReferenceType.CUSTOM) {
228 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
237 * Set whether the rocket has a perfect finish. This will affect whether the
238 * boundary layer is assumed to be fully turbulent or not.
240 * @param perfectFinish whether the finish is perfect.
242 public void setPerfectFinish(boolean perfectFinish) {
243 if (this.perfectFinish == perfectFinish)
245 this.perfectFinish = perfectFinish;
246 fireComponentChangeEvent(ComponentChangeEvent.AERODYNAMIC_CHANGE);
252 * Get whether the rocket has a perfect finish.
254 * @return the perfectFinish
256 public boolean isPerfectFinish() {
257 return perfectFinish;
265 * Make a deep copy of the Rocket structure. This method is exposed as public to allow
266 * for undo/redo system functionality.
268 @SuppressWarnings("unchecked")
270 public Rocket copyWithOriginalID() {
271 Rocket copy = (Rocket) super.copyWithOriginalID();
272 copy.motorConfigurationIDs = this.motorConfigurationIDs.clone();
273 copy.motorConfigurationNames =
274 (HashMap<String, String>) this.motorConfigurationNames.clone();
275 copy.resetListeners();
281 * Load the rocket structure from the source. The method loads the fields of this
282 * Rocket object and copies the references to siblings from the <code>source</code>.
283 * The object <code>source</code> should not be used after this call, as it is in
286 * This method is meant to be used in conjunction with undo/redo functionality,
287 * and therefore fires an UNDO_EVENT, masked with all applicable mass/aerodynamic/tree
290 @SuppressWarnings("unchecked")
291 public void loadFrom(Rocket r) {
293 // Store list of components to invalidate after event has been fired
294 List<RocketComponent> toInvalidate = this.copyFrom(r);
296 int type = ComponentChangeEvent.UNDO_CHANGE | ComponentChangeEvent.NONFUNCTIONAL_CHANGE;
297 if (this.massModID != r.massModID)
298 type |= ComponentChangeEvent.MASS_CHANGE;
299 if (this.aeroModID != r.aeroModID)
300 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
301 // Loading a rocket is always a tree change since the component objects change
302 type |= ComponentChangeEvent.TREE_CHANGE;
304 this.modID = r.modID;
305 this.massModID = r.massModID;
306 this.aeroModID = r.aeroModID;
307 this.treeModID = r.treeModID;
308 this.functionalModID = r.functionalModID;
309 this.refType = r.refType;
310 this.customReferenceLength = r.customReferenceLength;
312 this.motorConfigurationIDs = r.motorConfigurationIDs.clone();
313 this.motorConfigurationNames =
314 (HashMap<String, String>) r.motorConfigurationNames.clone();
315 this.perfectFinish = r.perfectFinish;
317 String id = defaultConfiguration.getMotorConfigurationID();
318 if (!this.motorConfigurationIDs.contains(id))
319 defaultConfiguration.setMotorConfigurationID(null);
321 this.checkComponentStructure();
323 fireComponentChangeEvent(type);
325 // Invalidate obsolete components after event
326 for (RocketComponent c : toInvalidate) {
334 /////// Implement the ComponentChangeListener lists
337 * Creates a new EventListenerList for this component. This is necessary when cloning
340 public void resetListeners() {
341 // System.out.println("RESETTING LISTENER LIST of Rocket "+this);
342 listenerList = new ArrayList<EventListener>();
346 public void printListeners() {
347 System.out.println("" + this + " has " + listenerList.size() + " listeners:");
349 for( EventListener l : listenerList ) {
350 System.out.println(" " + (i) + ": " + l);
356 public void addComponentChangeListener(ComponentChangeListener l) {
359 log.verbose("Added ComponentChangeListener " + l + ", current number of listeners is " +
360 listenerList.size());
364 public void removeComponentChangeListener(ComponentChangeListener l) {
365 listenerList.remove(l);
366 log.verbose("Removed ComponentChangeListener " + l + ", current number of listeners is " +
367 listenerList.size());
372 public void addChangeListener(EventListener l) {
375 log.verbose("Added ChangeListener " + l + ", current number of listeners is " +
376 listenerList.size());
380 public void removeChangeListener(EventListener l) {
381 listenerList.remove(l);
382 log.verbose("Removed ChangeListener " + l + ", current number of listeners is " +
383 listenerList.size());
388 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
389 mutex.lock("fireComponentChangeEvent");
393 // Update modification ID's only for normal (not undo/redo) events
394 if (!e.isUndoChange()) {
395 modID = UniqueID.next();
396 if (e.isMassChange())
398 if (e.isAerodynamicChange())
400 if (e.isTreeChange())
402 if (e.getType() != ComponentChangeEvent.NONFUNCTIONAL_CHANGE)
403 functionalModID = modID;
406 // Check whether frozen
407 if (freezeList != null) {
408 log.debug("Rocket is in frozen state, adding event " + e + " info freeze list");
413 log.debug("Firing rocket change event " + e);
415 // Notify all components first
416 Iterator<RocketComponent> iterator = this.iterator(true);
417 while (iterator.hasNext()) {
418 iterator.next().componentChanged(e);
421 // Notify all listeners
422 // Copy the list before iterating to prevent concurrent modification exceptions.
423 EventListener[] list = listenerList.toArray( new EventListener[0] );
424 for ( EventListener l : list ) {
425 if ( l instanceof ComponentChangeListener ) {
426 ((ComponentChangeListener) l ).componentChanged(e);
427 } else if ( l instanceof StateChangeListener ) {
428 ((StateChangeListener) l ).stateChanged(e);
432 mutex.unlock("fireComponentChangeEvent");
438 * Freezes the rocket structure from firing any events. This may be performed to
439 * combine several actions on the structure into a single large action.
440 * <code>thaw()</code> must always be called afterwards.
442 * NOTE: Always use a try/finally to ensure <code>thaw()</code> is called:
444 * Rocket r = c.getRocket();
455 public void freeze() {
457 if (freezeList == null) {
458 freezeList = new LinkedList<ComponentChangeEvent>();
459 log.debug("Freezing Rocket");
461 Application.getExceptionHandler().handleErrorCondition("Attempting to freeze Rocket when it is already frozen, " +
462 "freezeList=" + freezeList);
467 * Thaws a frozen rocket structure and fires a combination of the events fired during
468 * the freeze. The event type is a combination of those fired and the source is the
469 * last component to have been an event source.
475 if (freezeList == null) {
476 Application.getExceptionHandler().handleErrorCondition("Attempting to thaw Rocket when it is not frozen");
479 if (freezeList.size() == 0) {
480 log.warn("Thawing rocket with no changes made");
485 log.debug("Thawing rocket, freezeList=" + freezeList);
489 for (ComponentChangeEvent e : freezeList) {
490 type = type | e.getType();
495 fireComponentChangeEvent(new ComponentChangeEvent((RocketComponent) c, type));
501 //////// Motor configurations ////////
505 * Return the default configuration. This should be used in the user interface
506 * to ensure a consistent rocket configuration between dialogs. It should NOT
507 * be used in simulations not relating to the UI.
509 * @return the default {@link Configuration}.
511 public Configuration getDefaultConfiguration() {
513 return defaultConfiguration;
518 * Return an array of the motor configuration IDs. This array is guaranteed
519 * to contain the <code>null</code> ID as the first element.
521 * @return an array of the motor configuration IDs.
523 public String[] getMotorConfigurationIDs() {
525 return motorConfigurationIDs.toArray(new String[0]);
529 * Add a new motor configuration ID to the motor configurations. The new ID
532 * @return the new motor configuration ID.
534 public String newMotorConfigurationID() {
536 String id = UUID.randomUUID().toString();
537 motorConfigurationIDs.add(id);
538 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
543 * Add a specified motor configuration ID to the motor configurations.
545 * @param id the motor configuration ID.
546 * @return true if successful, false if the ID was already used.
548 public boolean addMotorConfigurationID(String id) {
550 if (id == null || motorConfigurationIDs.contains(id))
552 motorConfigurationIDs.add(id);
553 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
558 * Remove a motor configuration ID from the configuration IDs. The <code>null</code>
559 * ID cannot be removed, and an attempt to remove it will be silently ignored.
561 * @param id the motor configuration ID to remove
563 public void removeMotorConfigurationID(String id) {
567 motorConfigurationIDs.remove(id);
568 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
573 * Check whether <code>id</code> is a valid motor configuration ID.
575 * @param id the configuration ID.
576 * @return whether a motor configuration with that ID exists.
578 public boolean isMotorConfigurationID(String id) {
580 return motorConfigurationIDs.contains(id);
586 * Check whether the given motor configuration ID has motors defined for it.
588 * @param id the motor configuration ID (may be invalid).
589 * @return whether any motors are defined for it.
591 public boolean hasMotors(String id) {
596 Iterator<RocketComponent> iterator = this.iterator();
597 while (iterator.hasNext()) {
598 RocketComponent c = iterator.next();
600 if (c instanceof MotorMount) {
601 MotorMount mount = (MotorMount) c;
602 if (!mount.isMotorMount())
604 if (mount.getMotor(id) != null) {
614 * Return the user-set name of the motor configuration. If no name has been set,
615 * returns an empty string (not null).
617 * @param id the motor configuration id
618 * @return the configuration name
620 public String getMotorConfigurationName(String id) {
622 if (!isMotorConfigurationID(id))
624 String s = motorConfigurationNames.get(id);
632 * Set the name of the motor configuration. A name can be unset by passing
633 * <code>null</code> or an empty string.
635 * @param id the motor configuration id
636 * @param name the name for the motor configuration
638 public void setMotorConfigurationName(String id, String name) {
640 motorConfigurationNames.put(id, name);
641 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
646 * Return either the motor configuration name (if set) or its description.
648 * @param id the motor configuration ID.
649 * @return a textual representation of the configuration
651 public String getMotorConfigurationNameOrDescription(String id) {
655 name = getMotorConfigurationName(id);
656 if (name != null && !name.equals(""))
659 return getMotorConfigurationDescription(id);
663 * Return a description for the motor configuration, generated from the motor
664 * designations of the components.
666 * @param id the motor configuration ID.
667 * @return a textual representation of the configuration
669 @SuppressWarnings("null")
670 public String getMotorConfigurationDescription(String id) {
675 // Generate the description
677 // First iterate over each stage and store the designations of each motor
678 List<List<String>> list = new ArrayList<List<String>>();
679 List<String> currentList = null;
681 Iterator<RocketComponent> iterator = this.iterator();
682 while (iterator.hasNext()) {
683 RocketComponent c = iterator.next();
685 if (c instanceof Stage) {
687 currentList = new ArrayList<String>();
688 list.add(currentList);
690 } else if (c instanceof MotorMount) {
692 MotorMount mount = (MotorMount) c;
693 Motor motor = mount.getMotor(id);
695 if (mount.isMotorMount() && motor != null) {
696 String designation = motor.getDesignation(mount.getMotorDelay(id));
698 for (int i = 0; i < mount.getMotorCount(); i++) {
699 currentList.add(designation);
707 if (motorCount == 0) {
709 return trans.get("Rocket.motorCount.Nomotor");
712 // Change multiple occurrences of a motor to n x motor
713 List<String> stages = new ArrayList<String>();
715 for (List<String> stage : list) {
716 String stageName = "";
717 String previous = null;
720 Collections.sort(stage);
721 for (String current : stage) {
722 if (current.equals(previous)) {
728 if (previous != null) {
731 s = "" + count + Chars.TIMES + previous;
736 if (stageName.equals(""))
739 stageName = stageName + "," + s;
747 if (previous != null) {
750 s = "" + count + Chars.TIMES + previous;
755 if (stageName.equals(""))
758 stageName = stageName + "," + s;
761 stages.add(stageName);
765 for (int i = 0; i < stages.size(); i++) {
766 String s = stages.get(i);
772 name = name + "; " + s;
780 //////// Obligatory component information
784 public String getComponentName() {
786 return trans.get("Rocket.compname.Rocket");
790 public Coordinate getComponentCG() {
791 return new Coordinate(0, 0, 0, 0);
795 public double getComponentMass() {
800 public double getLongitudinalUnitInertia() {
805 public double getRotationalUnitInertia() {
810 public Collection<Coordinate> getComponentBounds() {
811 return Collections.emptyList();
815 public boolean isAerodynamic() {
820 public boolean isMassive() {
825 public boolean allowsChildren() {
830 * Allows only <code>Stage</code> components to be added to the type Rocket.
833 public boolean isCompatible(Class<? extends RocketComponent> type) {
834 return (Stage.class.isAssignableFrom(type));