1 package net.sf.openrocket.rocketcomponent;
3 import net.sf.openrocket.gui.main.ExceptionHandler;
4 import net.sf.openrocket.logging.LogHelper;
5 import net.sf.openrocket.motor.Motor;
6 import net.sf.openrocket.startup.Application;
7 import net.sf.openrocket.util.ArrayList;
8 import net.sf.openrocket.util.*;
10 import javax.swing.event.ChangeListener;
11 import javax.swing.event.EventListenerList;
16 * Base for all rocket components. This is the "starting point" for all rocket trees.
17 * It provides the actual implementations of several methods defined in RocketComponent
18 * (eg. the rocket listener lists) and the methods defined in RocketComponent call these.
19 * It also defines some other methods that concern the whole rocket, and helper methods
20 * that keep information about the program state.
22 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
25 public class Rocket extends RocketComponent {
26 private static final LogHelper log = Application.getLogger();
28 public static final double DEFAULT_REFERENCE_LENGTH = 0.01;
32 * List of component change listeners.
34 private EventListenerList listenerList = new EventListenerList();
37 * When freezeList != null, events are not dispatched but stored in the list.
38 * When the structure is thawed, a single combined event will be fired.
40 private List<ComponentChangeEvent> freezeList = null;
44 private int massModID;
45 private int aeroModID;
46 private int treeModID;
47 private int functionalModID;
50 private ReferenceType refType = ReferenceType.MAXIMUM; // Set in constructor
51 private double customReferenceLength = DEFAULT_REFERENCE_LENGTH;
54 // The default configuration used in dialogs
55 private final Configuration defaultConfiguration;
58 private String designer = "";
59 private String revision = "";
62 // Motor configuration list
63 private ArrayList<String> motorConfigurationIDs = new ArrayList<String>();
64 private HashMap<String, String> motorConfigurationNames = new HashMap<String, String>();
66 motorConfigurationIDs.add(null);
70 // Does the rocket have a perfect finish (a notable amount of laminar flow)
71 private boolean perfectFinish = false;
75 ///////////// Constructor /////////////
78 super(RocketComponent.Position.AFTER);
79 modID = UniqueID.next();
83 functionalModID = modID;
84 defaultConfiguration = new Configuration(this);
89 public String getDesigner() {
94 public void setDesigner(String s) {
98 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
102 public String getRevision() {
107 public void setRevision(String s) {
111 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
118 * Return the number of stages in this rocket.
120 * @return the number of stages in this rocket.
122 public int getStageCount() {
124 return this.getChildCount();
129 * Return the non-negative modification ID of this rocket. The ID is changed
130 * every time any change occurs in the rocket. This can be used to check
131 * whether it is necessary to void cached data in cases where listeners can not
132 * or should not be used.
134 * Three other modification IDs are also available, {@link #getMassModID()},
135 * {@link #getAerodynamicModID()} {@link #getTreeModID()}, which change every time
136 * a mass change, aerodynamic change, or tree change occur. Even though the values
137 * of the different modification ID's may be equal, they should be treated totally
140 * Note that undo events restore the modification IDs that were in use at the
141 * corresponding undo level. Subsequent modifications, however, produce modIDs
142 * distinct from those already used.
144 * @return a unique ID number for this modification state.
146 public int getModID() {
151 * Return the non-negative mass modification ID of this rocket. See
152 * {@link #getModID()} for details.
154 * @return a unique ID number for this mass-modification state.
156 public int getMassModID() {
161 * Return the non-negative aerodynamic modification ID of this rocket. See
162 * {@link #getModID()} for details.
164 * @return a unique ID number for this aerodynamic-modification state.
166 public int getAerodynamicModID() {
171 * Return the non-negative tree modification ID of this rocket. See
172 * {@link #getModID()} for details.
174 * @return a unique ID number for this tree-modification state.
176 public int getTreeModID() {
181 * Return the non-negative functional modificationID of this rocket.
182 * This changes every time a functional change occurs.
184 * @return a unique ID number for this functional modification state.
186 public int getFunctionalModID() {
187 return functionalModID;
193 public ReferenceType getReferenceType() {
198 public void setReferenceType(ReferenceType type) {
202 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
206 public double getCustomReferenceLength() {
208 return customReferenceLength;
211 public void setCustomReferenceLength(double length) {
212 if (MathUtil.equals(customReferenceLength, length))
215 this.customReferenceLength = Math.max(length, 0.001);
217 if (refType == ReferenceType.CUSTOM) {
218 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
227 * Set whether the rocket has a perfect finish. This will affect whether the
228 * boundary layer is assumed to be fully turbulent or not.
230 * @param perfectFinish whether the finish is perfect.
232 public void setPerfectFinish(boolean perfectFinish) {
233 if (this.perfectFinish == perfectFinish)
235 this.perfectFinish = perfectFinish;
236 fireComponentChangeEvent(ComponentChangeEvent.AERODYNAMIC_CHANGE);
242 * Get whether the rocket has a perfect finish.
244 * @return the perfectFinish
246 public boolean isPerfectFinish() {
247 return perfectFinish;
255 * Make a deep copy of the Rocket structure. This method is exposed as public to allow
256 * for undo/redo system functionality.
258 @SuppressWarnings("unchecked")
260 public Rocket copyWithOriginalID() {
261 Rocket copy = (Rocket) super.copyWithOriginalID();
262 copy.motorConfigurationIDs = this.motorConfigurationIDs.clone();
263 copy.motorConfigurationNames =
264 (HashMap<String, String>) this.motorConfigurationNames.clone();
265 copy.resetListeners();
271 * Load the rocket structure from the source. The method loads the fields of this
272 * Rocket object and copies the references to siblings from the <code>source</code>.
273 * The object <code>source</code> should not be used after this call, as it is in
276 * This method is meant to be used in conjunction with undo/redo functionality,
277 * and therefore fires an UNDO_EVENT, masked with all applicable mass/aerodynamic/tree
280 @SuppressWarnings("unchecked")
281 public void loadFrom(Rocket r) {
283 // Store list of components to invalidate after event has been fired
284 List<RocketComponent> toInvalidate = this.copyFrom(r);
286 int type = ComponentChangeEvent.UNDO_CHANGE | ComponentChangeEvent.NONFUNCTIONAL_CHANGE;
287 if (this.massModID != r.massModID)
288 type |= ComponentChangeEvent.MASS_CHANGE;
289 if (this.aeroModID != r.aeroModID)
290 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
291 // Loading a rocket is always a tree change since the component objects change
292 type |= ComponentChangeEvent.TREE_CHANGE;
294 this.modID = r.modID;
295 this.massModID = r.massModID;
296 this.aeroModID = r.aeroModID;
297 this.treeModID = r.treeModID;
298 this.functionalModID = r.functionalModID;
299 this.refType = r.refType;
300 this.customReferenceLength = r.customReferenceLength;
302 this.motorConfigurationIDs = r.motorConfigurationIDs.clone();
303 this.motorConfigurationNames =
304 (HashMap<String, String>) r.motorConfigurationNames.clone();
305 this.perfectFinish = r.perfectFinish;
307 String id = defaultConfiguration.getMotorConfigurationID();
308 if (!this.motorConfigurationIDs.contains(id))
309 defaultConfiguration.setMotorConfigurationID(null);
311 this.checkComponentStructure();
313 fireComponentChangeEvent(type);
315 // Invalidate obsolete components after event
316 for (RocketComponent c : toInvalidate) {
324 /////// Implement the ComponentChangeListener lists
327 * Creates a new EventListenerList for this component. This is necessary when cloning
330 public void resetListeners() {
331 // System.out.println("RESETTING LISTENER LIST of Rocket "+this);
332 listenerList = new EventListenerList();
336 public void printListeners() {
337 System.out.println("" + this + " has " + listenerList.getListenerCount() + " listeners:");
338 Object[] list = listenerList.getListenerList();
339 for (int i = 1; i < list.length; i += 2)
340 System.out.println(" " + ((i + 1) / 2) + ": " + list[i]);
344 public void addComponentChangeListener(ComponentChangeListener l) {
346 listenerList.add(ComponentChangeListener.class, l);
347 log.verbose("Added ComponentChangeListener " + l + ", current number of listeners is " +
348 listenerList.getListenerCount());
352 public void removeComponentChangeListener(ComponentChangeListener l) {
353 listenerList.remove(ComponentChangeListener.class, l);
354 log.verbose("Removed ComponentChangeListener " + l + ", current number of listeners is " +
355 listenerList.getListenerCount());
360 public void addChangeListener(ChangeListener l) {
362 listenerList.add(ChangeListener.class, l);
363 log.verbose("Added ChangeListener " + l + ", current number of listeners is " +
364 listenerList.getListenerCount());
368 public void removeChangeListener(ChangeListener l) {
369 listenerList.remove(ChangeListener.class, l);
370 log.verbose("Removed ChangeListener " + l + ", current number of listeners is " +
371 listenerList.getListenerCount());
376 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
377 mutex.lock("fireComponentChangeEvent");
381 // Update modification ID's only for normal (not undo/redo) events
382 if (!e.isUndoChange()) {
383 modID = UniqueID.next();
384 if (e.isMassChange())
386 if (e.isAerodynamicChange())
388 if (e.isTreeChange())
390 if (e.getType() != ComponentChangeEvent.NONFUNCTIONAL_CHANGE)
391 functionalModID = modID;
394 // Check whether frozen
395 if (freezeList != null) {
396 log.debug("Rocket is in frozen state, adding event " + e + " info freeze list");
401 log.debug("Firing rocket change event " + e);
403 // Notify all components first
404 Iterator<RocketComponent> iterator = this.iterator(true);
405 while (iterator.hasNext()) {
406 iterator.next().componentChanged(e);
409 // Notify all listeners
410 Object[] listeners = listenerList.getListenerList();
411 for (int i = listeners.length - 2; i >= 0; i -= 2) {
412 if (listeners[i] == ComponentChangeListener.class) {
413 ((ComponentChangeListener) listeners[i + 1]).componentChanged(e);
414 } else if (listeners[i] == ChangeListener.class) {
415 ((ChangeListener) listeners[i + 1]).stateChanged(e);
419 mutex.unlock("fireComponentChangeEvent");
425 * Freezes the rocket structure from firing any events. This may be performed to
426 * combine several actions on the structure into a single large action.
427 * <code>thaw()</code> must always be called afterwards.
429 * NOTE: Always use a try/finally to ensure <code>thaw()</code> is called:
431 * Rocket r = c.getRocket();
442 public void freeze() {
444 if (freezeList == null) {
445 freezeList = new LinkedList<ComponentChangeEvent>();
446 log.debug("Freezing Rocket");
448 ExceptionHandler.handleErrorCondition("Attempting to freeze Rocket when it is already frozen, " +
449 "freezeList=" + freezeList);
454 * Thaws a frozen rocket structure and fires a combination of the events fired during
455 * the freeze. The event type is a combination of those fired and the source is the
456 * last component to have been an event source.
462 if (freezeList == null) {
463 ExceptionHandler.handleErrorCondition("Attempting to thaw Rocket when it is not frozen");
466 if (freezeList.size() == 0) {
467 log.warn("Thawing rocket with no changes made");
472 log.debug("Thawing rocket, freezeList=" + freezeList);
476 for (ComponentChangeEvent e : freezeList) {
477 type = type | e.getType();
482 fireComponentChangeEvent(new ComponentChangeEvent((RocketComponent) c, type));
488 //////// Motor configurations ////////
492 * Return the default configuration. This should be used in the user interface
493 * to ensure a consistent rocket configuration between dialogs. It should NOT
494 * be used in simulations not relating to the UI.
496 * @return the default {@link Configuration}.
498 public Configuration getDefaultConfiguration() {
500 return defaultConfiguration;
505 * Return an array of the motor configuration IDs. This array is guaranteed
506 * to contain the <code>null</code> ID as the first element.
508 * @return an array of the motor configuration IDs.
510 public String[] getMotorConfigurationIDs() {
512 return motorConfigurationIDs.toArray(new String[0]);
516 * Add a new motor configuration ID to the motor configurations. The new ID
519 * @return the new motor configuration ID.
521 public String newMotorConfigurationID() {
523 String id = UUID.randomUUID().toString();
524 motorConfigurationIDs.add(id);
525 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
530 * Add a specified motor configuration ID to the motor configurations.
532 * @param id the motor configuration ID.
533 * @return true if successful, false if the ID was already used.
535 public boolean addMotorConfigurationID(String id) {
537 if (id == null || motorConfigurationIDs.contains(id))
539 motorConfigurationIDs.add(id);
540 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
545 * Remove a motor configuration ID from the configuration IDs. The <code>null</code>
546 * ID cannot be removed, and an attempt to remove it will be silently ignored.
548 * @param id the motor configuration ID to remove
550 public void removeMotorConfigurationID(String id) {
554 motorConfigurationIDs.remove(id);
555 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
560 * Check whether <code>id</code> is a valid motor configuration ID.
562 * @param id the configuration ID.
563 * @return whether a motor configuration with that ID exists.
565 public boolean isMotorConfigurationID(String id) {
567 return motorConfigurationIDs.contains(id);
573 * Check whether the given motor configuration ID has motors defined for it.
575 * @param id the motor configuration ID (may be invalid).
576 * @return whether any motors are defined for it.
578 public boolean hasMotors(String id) {
583 Iterator<RocketComponent> iterator = this.iterator();
584 while (iterator.hasNext()) {
585 RocketComponent c = iterator.next();
587 if (c instanceof MotorMount) {
588 MotorMount mount = (MotorMount) c;
589 if (!mount.isMotorMount())
591 if (mount.getMotor(id) != null) {
601 * Return the user-set name of the motor configuration. If no name has been set,
602 * returns an empty string (not null).
604 * @param id the motor configuration id
605 * @return the configuration name
607 public String getMotorConfigurationName(String id) {
609 if (!isMotorConfigurationID(id))
611 String s = motorConfigurationNames.get(id);
619 * Set the name of the motor configuration. A name can be unset by passing
620 * <code>null</code> or an empty string.
622 * @param id the motor configuration id
623 * @param name the name for the motor configuration
625 public void setMotorConfigurationName(String id, String name) {
627 motorConfigurationNames.put(id, name);
628 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
633 * Return either the motor configuration name (if set) or its description.
635 * @param id the motor configuration ID.
636 * @return a textual representation of the configuration
638 public String getMotorConfigurationNameOrDescription(String id) {
642 name = getMotorConfigurationName(id);
643 if (name != null && !name.equals(""))
646 return getMotorConfigurationDescription(id);
650 * Return a description for the motor configuration, generated from the motor
651 * designations of the components.
653 * @param id the motor configuration ID.
654 * @return a textual representation of the configuration
656 @SuppressWarnings("null")
657 public String getMotorConfigurationDescription(String id) {
662 // Generate the description
664 // First iterate over each stage and store the designations of each motor
665 List<List<String>> list = new ArrayList<List<String>>();
666 List<String> currentList = null;
668 Iterator<RocketComponent> iterator = this.iterator();
669 while (iterator.hasNext()) {
670 RocketComponent c = iterator.next();
672 if (c instanceof Stage) {
674 currentList = new ArrayList<String>();
675 list.add(currentList);
677 } else if (c instanceof MotorMount) {
679 MotorMount mount = (MotorMount) c;
680 Motor motor = mount.getMotor(id);
682 if (mount.isMotorMount() && motor != null) {
683 String designation = motor.getDesignation(mount.getMotorDelay(id));
685 for (int i = 0; i < mount.getMotorCount(); i++) {
686 currentList.add(designation);
694 if (motorCount == 0) {
695 return "[No motors]";
698 // Change multiple occurrences of a motor to n x motor
699 List<String> stages = new ArrayList<String>();
701 for (List<String> stage : list) {
702 String stageName = "";
703 String previous = null;
706 Collections.sort(stage);
707 for (String current : stage) {
708 if (current.equals(previous)) {
714 if (previous != null) {
717 s = "" + count + Chars.TIMES + previous;
722 if (stageName.equals(""))
725 stageName = stageName + "," + s;
733 if (previous != null) {
736 s = "" + count + Chars.TIMES + previous;
741 if (stageName.equals(""))
744 stageName = stageName + "," + s;
747 stages.add(stageName);
751 for (int i = 0; i < stages.size(); i++) {
752 String s = stages.get(i);
758 name = name + "; " + s;
766 //////// Obligatory component information
770 public String getComponentName() {
775 public Coordinate getComponentCG() {
776 return new Coordinate(0, 0, 0, 0);
780 public double getComponentMass() {
785 public double getLongitudinalUnitInertia() {
790 public double getRotationalUnitInertia() {
795 public Collection<Coordinate> getComponentBounds() {
796 return Collections.emptyList();
800 public boolean isAerodynamic() {
805 public boolean isMassive() {
810 public boolean allowsChildren() {
815 * Allows only <code>Stage</code> components to be added to the type Rocket.
818 public boolean isCompatible(Class<? extends RocketComponent> type) {
819 return (Stage.class.isAssignableFrom(type));