1 package net.sf.openrocket.rocketcomponent;
4 import java.util.ArrayDeque;
5 import java.util.Collection;
6 import java.util.Deque;
7 import java.util.Iterator;
9 import java.util.NoSuchElementException;
11 import javax.swing.event.ChangeListener;
13 import net.sf.openrocket.l10n.Translator;
14 import net.sf.openrocket.logging.LogHelper;
15 import net.sf.openrocket.preset.RocketComponentPreset;
16 import net.sf.openrocket.startup.Application;
17 import net.sf.openrocket.util.ArrayList;
18 import net.sf.openrocket.util.BugException;
19 import net.sf.openrocket.util.ChangeSource;
20 import net.sf.openrocket.util.Coordinate;
21 import net.sf.openrocket.util.Invalidator;
22 import net.sf.openrocket.util.LineStyle;
23 import net.sf.openrocket.util.MathUtil;
24 import net.sf.openrocket.util.SafetyMutex;
25 import net.sf.openrocket.util.UniqueID;
28 public abstract class RocketComponent implements ChangeSource, Cloneable, Iterable<RocketComponent> {
29 private static final LogHelper log = Application.getLogger();
30 private static final Translator trans = Application.getTranslator();
33 * Text is suitable to the form
34 * Position relative to: <title>
36 public enum Position {
37 /** Position relative to the top of the parent component. */
38 //// Top of the parent component
39 TOP(trans.get("RocketComponent.Position.TOP")),
40 /** Position relative to the middle of the parent component. */
41 //// Middle of the parent component
42 MIDDLE(trans.get("RocketComponent.Position.MIDDLE")),
43 /** Position relative to the bottom of the parent component. */
44 //// Bottom of the parent component
45 BOTTOM(trans.get("RocketComponent.Position.BOTTOM")),
46 /** Position after the parent component (for body components). */
47 //// After the parent component
48 AFTER(trans.get("RocketComponent.Position.AFTER")),
49 /** Specify an absolute X-coordinate position. */
50 //// Tip of the nose cone
51 ABSOLUTE(trans.get("RocketComponent.Position.ABSOLUTE"));
55 Position(String title) {
60 public String toString() {
66 * A safety mutex that can be used to prevent concurrent access to this component.
68 protected SafetyMutex mutex = SafetyMutex.newInstance();
70 //////// Parent/child trees
72 * Parent component of the current component, or null if none exists.
74 private RocketComponent parent = null;
77 * List of child components of this component.
79 private ArrayList<RocketComponent> children = new ArrayList<RocketComponent>();
82 //////// Parameters common to all components:
85 * Characteristic length of the component. This is used in calculating the coordinate
86 * transformations and positions of other components in reference to this component.
87 * This may and should be used as the "true" length of the component, where applicable.
88 * By default it is zero, i.e. no translation.
90 protected double length = 0;
93 * Positioning of this component relative to the parent component.
95 protected Position relativePosition;
98 * Offset of the position of this component relative to the normal position given by
99 * relativePosition. By default zero, i.e. no position change.
101 protected double position = 0;
104 // Color of the component, null means to use the default color
105 private Color color = null;
106 private LineStyle lineStyle = null;
110 private double overrideMass = 0;
111 private boolean massOverriden = false;
112 private double overrideCGX = 0;
113 private boolean cgOverriden = false;
115 private boolean overrideSubcomponents = false;
118 // User-given name of the component
119 private String name = null;
121 // User-specified comment
122 private String comment = "";
124 // Unique ID of the component
125 private String id = null;
127 // Preset component this component is based upon
128 private RocketComponentPreset presetComponent = null;
132 * Used to invalidate the component after calling {@link #copyFrom(RocketComponent)}.
134 private Invalidator invalidator = new Invalidator(this);
137 //// NOTE !!! All fields must be copied in the method copyFrom()! ////
142 * Default constructor. Sets the name of the component to the component's static name
143 * and the relative position of the component.
145 public RocketComponent(Position relativePosition) {
146 // These must not fire any events, due to Rocket undo system initialization
147 this.name = getComponentName();
148 this.relativePosition = relativePosition;
152 //////////// Methods that must be implemented ////////////
156 * Static component name. The name may not vary of the parameters, it must be static.
158 public abstract String getComponentName(); // Static component type name
161 * Return the component mass (regardless of mass overriding).
163 public abstract double getComponentMass(); // Mass of non-overridden component
166 * Return the component CG and mass (regardless of CG or mass overriding).
168 public abstract Coordinate getComponentCG(); // CG of non-overridden component
172 * Return the longitudinal (around the y- or z-axis) unitary moment of inertia.
173 * The unitary moment of inertia is the moment of inertia with the assumption that
174 * the mass of the component is one kilogram. The inertia is measured in
175 * respect to the non-overridden CG.
177 * @return the longitudinal unitary moment of inertia of this component.
179 public abstract double getLongitudinalUnitInertia();
183 * Return the rotational (around the x-axis) unitary moment of inertia.
184 * The unitary moment of inertia is the moment of inertia with the assumption that
185 * the mass of the component is one kilogram. The inertia is measured in
186 * respect to the non-overridden CG.
188 * @return the rotational unitary moment of inertia of this component.
190 public abstract double getRotationalUnitInertia();
194 * Test whether this component allows any children components. This method must
195 * return true if and only if {@link #isCompatible(Class)} returns true for any
196 * rocket component class.
198 * @return <code>true</code> if children can be attached to this component, <code>false</code> otherwise.
200 public abstract boolean allowsChildren();
203 * Test whether the given component type can be added to this component. This type safety
204 * is enforced by the <code>addChild()</code> methods. The return value of this method
205 * may change to reflect the current state of this component (e.g. two components of some
206 * type cannot be placed as children).
208 * @param type The RocketComponent class type to add.
209 * @return Whether such a component can be added.
211 public abstract boolean isCompatible(Class<? extends RocketComponent> type);
214 /* Non-abstract helper method */
216 * Test whether the given component can be added to this component. This is equivalent
217 * to calling <code>isCompatible(c.getClass())</code>.
219 * @param c Component to test.
220 * @return Whether the component can be added.
221 * @see #isCompatible(Class)
223 public final boolean isCompatible(RocketComponent c) {
225 return isCompatible(c.getClass());
231 * Return a collection of bounding coordinates. The coordinates must be such that
232 * the component is fully enclosed in their convex hull.
234 * @return a collection of coordinates that bound the component.
236 public abstract Collection<Coordinate> getComponentBounds();
239 * Return true if the component may have an aerodynamic effect on the rocket.
241 public abstract boolean isAerodynamic();
244 * Return true if the component may have an effect on the rocket's mass.
246 public abstract boolean isMassive();
252 //////////// Methods that may be overridden ////////////
256 * Shift the coordinates in the array corresponding to radial movement. A component
257 * that has a radial position must shift the coordinates in this array suitably.
258 * If the component is clustered, then a new array must be returned with a
259 * coordinate for each cluster.
261 * The default implementation simply returns the array, and thus produces no shift.
263 * @param c an array of coordinates to shift.
264 * @return an array of shifted coordinates. The method may modify the contents
265 * of the passed array and return the array itself.
267 public Coordinate[] shiftCoordinates(Coordinate[] c) {
274 * Called when any component in the tree fires a ComponentChangeEvent. This is by
275 * default a no-op, but subclasses may override this method to e.g. invalidate
276 * cached data. The overriding method *must* call
277 * <code>super.componentChanged(e)</code> at some point.
279 * @param e The event fired
281 protected void componentChanged(ComponentChangeEvent e) {
290 * Return the user-provided name of the component, or the component base
291 * name if the user-provided name is empty. This can be used in the UI.
293 * @return A string describing the component.
296 public final String toString() {
298 if (name.length() == 0)
299 return getComponentName();
306 * Create a string describing the basic component structure from this component downwards.
307 * @return a string containing the rocket structure
309 public final String toDebugString() {
310 mutex.lock("toDebugString");
312 StringBuilder sb = new StringBuilder();
314 return sb.toString();
316 mutex.unlock("toDebugString");
320 private void toDebugString(StringBuilder sb) {
321 sb.append(this.getClass().getSimpleName()).append('@').append(System.identityHashCode(this));
322 sb.append("[\"").append(this.getName()).append('"');
323 for (RocketComponent c : this.children) {
332 * Make a deep copy of the rocket component tree structure from this component
333 * downwards for copying purposes. Each component in the copy will be assigned
334 * a new component ID, making it a safe copy. This method does not fire any events.
336 * @return A deep copy of the structure.
338 public final RocketComponent copy() {
339 RocketComponent clone = copyWithOriginalID();
341 Iterator<RocketComponent> iterator = clone.iterator(true);
342 while (iterator.hasNext()) {
343 iterator.next().newID();
351 * Make a deep copy of the rocket component tree structure from this component
352 * downwards while maintaining the component ID's. The purpose of this method is
353 * to allow copies to be created with the original ID's for the purpose of the
354 * undo/redo mechanism. This method should not be used for other purposes,
355 * such as copy/paste. This method does not fire any events.
357 * This method must be overridden by any component that refers to mutable objects,
358 * or if some fields should not be copied. This should be performed by
359 * <code>RocketComponent c = super.copyWithOriginalID();</code> and then cloning/modifying
360 * the appropriate fields.
362 * This is not performed as serializing/deserializing for performance reasons.
364 * @return A deep copy of the structure.
366 protected RocketComponent copyWithOriginalID() {
367 mutex.lock("copyWithOriginalID");
370 RocketComponent clone;
372 clone = (RocketComponent) this.clone();
373 } catch (CloneNotSupportedException e) {
374 throw new BugException("CloneNotSupportedException encountered, report a bug!", e);
378 clone.mutex = SafetyMutex.newInstance();
380 // Reset all parent/child information
382 clone.children = new ArrayList<RocketComponent>();
384 // Add copied children to the structure without firing events.
385 for (RocketComponent child : this.children) {
386 RocketComponent childCopy = child.copyWithOriginalID();
387 // Don't use add method since it fires events
388 clone.children.add(childCopy);
389 childCopy.parent = clone;
392 this.checkComponentStructure();
393 clone.checkComponentStructure();
397 mutex.unlock("copyWithOriginalID");
402 ////////////// Methods that may not be overridden ////////////
406 ////////// Common parameter setting/getting //////////
409 * Return the color of the object to use in 2D figures, or <code>null</code>
410 * to use the default color.
412 public final Color getColor() {
418 * Set the color of the object to use in 2D figures.
420 public final void setColor(Color c) {
421 if ((color == null && c == null) ||
422 (color != null && color.equals(c)))
427 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
431 public final LineStyle getLineStyle() {
436 public final void setLineStyle(LineStyle style) {
437 if (this.lineStyle == style)
440 this.lineStyle = style;
441 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
448 * Get the current override mass. The mass is not necessarily in use
451 * @return the override mass
453 public final double getOverrideMass() {
459 * Set the current override mass. The mass is not set to use by this
462 * @param m the override mass
464 public final void setOverrideMass(double m) {
465 if (MathUtil.equals(m, overrideMass))
468 overrideMass = Math.max(m, 0);
470 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
474 * Return whether mass override is active for this component. This does NOT
475 * take into account whether a parent component is overriding the mass.
477 * @return whether the mass is overridden
479 public final boolean isMassOverridden() {
481 return massOverriden;
485 * Set whether the mass is currently overridden.
487 * @param o whether the mass is overridden
489 public final void setMassOverridden(boolean o) {
490 if (massOverriden == o) {
495 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
503 * Return the current override CG. The CG is not necessarily overridden.
505 * @return the override CG
507 public final Coordinate getOverrideCG() {
509 return getComponentCG().setX(overrideCGX);
513 * Return the x-coordinate of the current override CG.
515 * @return the x-coordinate of the override CG.
517 public final double getOverrideCGX() {
523 * Set the current override CG to (x,0,0).
525 * @param x the x-coordinate of the override CG to set.
527 public final void setOverrideCGX(double x) {
528 if (MathUtil.equals(overrideCGX, x))
531 this.overrideCGX = x;
532 if (isCGOverridden())
533 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
535 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
539 * Return whether the CG is currently overridden.
541 * @return whether the CG is overridden
543 public final boolean isCGOverridden() {
549 * Set whether the CG is currently overridden.
551 * @param o whether the CG is overridden
553 public final void setCGOverridden(boolean o) {
554 if (cgOverriden == o) {
559 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
565 * Return whether the mass and/or CG override overrides all subcomponent values
566 * as well. The default implementation is a normal getter/setter implementation,
567 * however, subclasses are allowed to override this behavior if some subclass
568 * always or never overrides subcomponents. In this case the subclass should
569 * also override {@link #isOverrideSubcomponentsEnabled()} to return
570 * <code>false</code>.
572 * @return whether the current mass and/or CG override overrides subcomponents as well.
574 public boolean getOverrideSubcomponents() {
576 return overrideSubcomponents;
581 * Set whether the mass and/or CG override overrides all subcomponent values
582 * as well. See {@link #getOverrideSubcomponents()} for details.
584 * @param override whether the mass and/or CG override overrides all subcomponent.
586 public void setOverrideSubcomponents(boolean override) {
587 if (overrideSubcomponents == override) {
591 overrideSubcomponents = override;
592 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
596 * Return whether the option to override all subcomponents is enabled or not.
597 * The default implementation returns <code>false</code> if neither mass nor
598 * CG is overridden, <code>true</code> otherwise.
600 * This method may be overridden if the setting of overriding subcomponents
603 * @return whether the option to override subcomponents is currently enabled.
605 public boolean isOverrideSubcomponentsEnabled() {
607 return isCGOverridden() || isMassOverridden();
614 * Get the user-defined name of the component.
616 public final String getName() {
622 * Set the user-defined name of the component. If name==null, sets the name to
623 * the default name, currently the component name.
625 public final void setName(String name) {
626 if (this.name.equals(name)) {
630 if (name == null || name.matches("^\\s*$"))
631 this.name = getComponentName();
634 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
639 * Return the comment of the component. The component may contain multiple lines
640 * using \n as a newline separator.
642 * @return the comment of the component.
644 public final String getComment() {
650 * Set the comment of the component.
652 * @param comment the comment of the component.
654 public final void setComment(String comment) {
655 if (this.comment.equals(comment))
661 this.comment = comment;
662 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
668 * Return the preset component that this component is based upon.
670 * @return the preset component, or <code>null</code> if this is not based on a preset.
672 public final RocketComponentPreset getPresetComponent() {
673 return presetComponent;
677 * Set the preset component this component is based upon and load all of the
680 * @param preset the preset component to load, or <code>null</code> to clear the preset.
682 public final void loadPreset(RocketComponentPreset preset) {
683 if (presetComponent == preset) {
687 if (preset == null) {
692 if (preset.getComponentClass() != this.getClass()) {
693 throw new IllegalArgumentException("Attempting to load preset of type " + preset.getComponentClass()
694 + " into component of type " + this.getClass());
697 RocketComponent root = getRoot();
699 if (root instanceof Rocket) {
700 rocket = (Rocket) root;
706 if (rocket != null) {
710 loadFromPreset(preset);
712 this.presetComponent = preset;
713 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
716 if (rocket != null) {
724 * Load component properties from the specified preset. The preset is guaranteed
725 * to be of the correct type.
727 * This method should fire the appropriate events related to the changes. The rocket
728 * is frozen by the caller, so the events will be automatically combined.
730 * @param preset the preset to load from
732 protected void loadFromPreset(RocketComponentPreset preset) {
738 * Clear the current component preset. This does not affect the component properties
741 public final void clearPreset() {
742 if (presetComponent == null)
744 presetComponent = null;
745 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
751 * Returns the unique ID of the component.
753 * @return the ID of the component.
755 public final String getID() {
760 * Generate a new ID for this component.
762 private final void newID() {
764 this.id = UniqueID.uuid();
771 * Get the characteristic length of the component, for example the length of a body tube
772 * of the length of the root chord of a fin. This is used in positioning the component
773 * relative to its parent.
775 * If the length of a component is settable, the class must define the setter method
778 public final double getLength() {
784 * Get the positioning of the component relative to its parent component.
785 * This is one of the enums of {@link Position}. A setter method is not provided,
786 * but can be provided by a subclass.
788 public final Position getRelativePosition() {
790 return relativePosition;
795 * Set the positioning of the component relative to its parent component.
796 * The actual position of the component is maintained to the best ability.
798 * The default implementation is of protected visibility, since many components
799 * do not support setting the relative position. A component that does support
800 * it should override this with a public method that simply calls this
801 * supermethod AND fire a suitable ComponentChangeEvent.
803 * @param position the relative positioning.
805 protected void setRelativePosition(RocketComponent.Position position) {
806 if (this.relativePosition == position)
810 // Update position so as not to move the component
811 if (this.parent != null) {
812 double thisPos = this.toRelative(Coordinate.NUL, this.parent)[0].x;
816 this.position = this.toAbsolute(Coordinate.NUL)[0].x;
820 this.position = thisPos;
824 this.position = thisPos - (this.parent.length - this.length) / 2;
828 this.position = thisPos - (this.parent.length - this.length);
832 throw new BugException("Unknown position type: " + position);
836 this.relativePosition = position;
837 fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE);
844 * Get the position value of the component. The exact meaning of the value is
845 * dependent on the current relative positioning.
847 * @return the positional value.
849 public final double getPositionValue() {
856 * Set the position value of the component. The exact meaning of the value
857 * depends on the current relative positioning.
859 * The default implementation is of protected visibility, since many components
860 * do not support setting the relative position. A component that does support
861 * it should override this with a public method that simply calls this
862 * supermethod AND fire a suitable ComponentChangeEvent.
864 * @param value the position value of the component.
866 public void setPositionValue(double value) {
867 if (MathUtil.equals(this.position, value))
870 this.position = value;
875 /////////// Coordinate changes ///////////
878 * Returns coordinate c in absolute coordinates. Equivalent to toComponent(c,null).
880 public Coordinate[] toAbsolute(Coordinate c) {
882 return toRelative(c, null);
887 * Return coordinate <code>c</code> described in the coordinate system of
888 * <code>dest</code>. If <code>dest</code> is <code>null</code> returns
889 * absolute coordinates.
891 * This method returns an array of coordinates, each of which represents a
892 * position of the coordinate in clustered cases. The array is guaranteed
893 * to contain at least one element.
895 * The current implementation does not support rotating components.
897 * @param c Coordinate in the component's coordinate system.
898 * @param dest Destination component coordinate system.
899 * @return an array of coordinates describing <code>c</code> in coordinates
900 * relative to <code>dest</code>.
902 public final Coordinate[] toRelative(Coordinate c, RocketComponent dest) {
904 mutex.lock("toRelative");
906 double absoluteX = Double.NaN;
907 RocketComponent search = dest;
908 Coordinate[] array = new Coordinate[1];
911 RocketComponent component = this;
912 while ((component != search) && (component.parent != null)) {
914 array = component.shiftCoordinates(array);
916 switch (component.relativePosition) {
918 for (int i = 0; i < array.length; i++) {
919 array[i] = array[i].add(component.position, 0, 0);
924 for (int i = 0; i < array.length; i++) {
925 array[i] = array[i].add(component.position +
926 (component.parent.length - component.length) / 2, 0, 0);
931 for (int i = 0; i < array.length; i++) {
932 array[i] = array[i].add(component.position +
933 (component.parent.length - component.length), 0, 0);
938 // Add length of all previous brother-components with POSITION_RELATIVE_AFTER
939 int index = component.parent.children.indexOf(component);
941 for (index--; index >= 0; index--) {
942 RocketComponent comp = component.parent.children.get(index);
943 double componentLength = comp.getTotalLength();
944 for (int i = 0; i < array.length; i++) {
945 array[i] = array[i].add(componentLength, 0, 0);
948 for (int i = 0; i < array.length; i++) {
949 array[i] = array[i].add(component.position + component.parent.length, 0, 0);
954 search = null; // Requires back-search if dest!=null
955 if (Double.isNaN(absoluteX)) {
956 absoluteX = component.position;
961 throw new BugException("Unknown relative positioning type of component" +
962 component + ": " + component.relativePosition);
965 component = component.parent; // parent != null
968 if (!Double.isNaN(absoluteX)) {
969 for (int i = 0; i < array.length; i++) {
970 array[i] = array[i].setX(absoluteX + c.x);
974 // Check whether destination has been found or whether to backtrack
975 // TODO: LOW: Backtracking into clustered components uses only one component
976 if ((dest != null) && (component != dest)) {
977 Coordinate[] origin = dest.toAbsolute(Coordinate.NUL);
978 for (int i = 0; i < array.length; i++) {
979 array[i] = array[i].sub(origin[0]);
985 mutex.unlock("toRelative");
991 * Recursively sum the lengths of all subcomponents that have position
994 * @return Sum of the lengths.
996 private final double getTotalLength() {
998 this.checkComponentStructure();
999 mutex.lock("getTotalLength");
1002 if (relativePosition == Position.AFTER)
1004 for (int i = 0; i < children.size(); i++)
1005 l += children.get(i).getTotalLength();
1008 mutex.unlock("getTotalLength");
1014 /////////// Total mass and CG calculation ////////////
1017 * Return the (possibly overridden) mass of component.
1019 * @return The mass of the component or the given override mass.
1021 public final double getMass() {
1024 return overrideMass;
1025 return getComponentMass();
1029 * Return the (possibly overridden) center of gravity and mass.
1031 * Returns the CG with the weight of the coordinate set to the weight of the component.
1032 * Both CG and mass may be separately overridden.
1034 * @return The CG of the component or the given override CG.
1036 public final Coordinate getCG() {
1039 return getOverrideCG().setWeight(getMass());
1042 return getComponentCG().setWeight(getMass());
1044 return getComponentCG();
1049 * Return the longitudinal (around the y- or z-axis) moment of inertia of this component.
1050 * The moment of inertia is scaled in reference to the (possibly overridden) mass
1051 * and is relative to the non-overridden CG.
1053 * @return the longitudinal moment of inertia of this component.
1055 public final double getLongitudinalInertia() {
1057 return getLongitudinalUnitInertia() * getMass();
1061 * Return the rotational (around the y- or z-axis) moment of inertia of this component.
1062 * The moment of inertia is scaled in reference to the (possibly overridden) mass
1063 * and is relative to the non-overridden CG.
1065 * @return the rotational moment of inertia of this component.
1067 public final double getRotationalInertia() {
1069 return getRotationalUnitInertia() * getMass();
1074 /////////// Children handling ///////////
1078 * Adds a child to the rocket component tree. The component is added to the end
1079 * of the component's child list. This is a helper method that calls
1080 * {@link #addChild(RocketComponent,int)}.
1082 * @param component The component to add.
1083 * @throws IllegalArgumentException if the component is already part of some
1085 * @see #addChild(RocketComponent,int)
1087 public final void addChild(RocketComponent component) {
1089 addChild(component, children.size());
1094 * Adds a child to the rocket component tree. The component is added to
1095 * the given position of the component's child list.
1097 * This method may be overridden to enforce more strict component addition rules.
1098 * The tests should be performed first and then this method called.
1100 * @param component The component to add.
1101 * @param index Position to add component to.
1102 * @throws IllegalArgumentException If the component is already part of
1103 * some component tree.
1105 public void addChild(RocketComponent component, int index) {
1107 if (component.parent != null) {
1108 throw new IllegalArgumentException("component " + component.getComponentName() +
1109 " is already in a tree");
1111 if (!isCompatible(component)) {
1112 throw new IllegalStateException("Component " + component.getComponentName() +
1113 " not currently compatible with component " + getComponentName());
1116 children.add(index, component);
1117 component.parent = this;
1119 this.checkComponentStructure();
1120 component.checkComponentStructure();
1122 fireAddRemoveEvent(component);
1127 * Removes a child from the rocket component tree.
1129 * @param n remove the n'th child.
1130 * @throws IndexOutOfBoundsException if n is out of bounds
1132 public final void removeChild(int n) {
1134 RocketComponent component = children.remove(n);
1135 component.parent = null;
1137 this.checkComponentStructure();
1138 component.checkComponentStructure();
1140 fireAddRemoveEvent(component);
1144 * Removes a child from the rocket component tree. Does nothing if the component
1145 * is not present as a child.
1147 * @param component the component to remove
1148 * @return whether the component was a child
1150 public final boolean removeChild(RocketComponent component) {
1153 component.checkComponentStructure();
1155 if (children.remove(component)) {
1156 component.parent = null;
1158 this.checkComponentStructure();
1159 component.checkComponentStructure();
1161 fireAddRemoveEvent(component);
1171 * Move a child to another position.
1173 * @param component the component to move
1174 * @param index the component's new position
1175 * @throws IllegalArgumentException If an illegal placement was attempted.
1177 public final void moveChild(RocketComponent component, int index) {
1179 if (children.remove(component)) {
1180 children.add(index, component);
1182 this.checkComponentStructure();
1183 component.checkComponentStructure();
1185 fireAddRemoveEvent(component);
1191 * Fires an AERODYNAMIC_CHANGE, MASS_CHANGE or OTHER_CHANGE event depending on the
1192 * type of component removed.
1194 private void fireAddRemoveEvent(RocketComponent component) {
1195 Iterator<RocketComponent> iter = component.iterator(true);
1196 int type = ComponentChangeEvent.TREE_CHANGE;
1197 while (iter.hasNext()) {
1198 RocketComponent c = iter.next();
1199 if (c.isAerodynamic())
1200 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
1202 type |= ComponentChangeEvent.MASS_CHANGE;
1205 fireComponentChangeEvent(type);
1209 public final int getChildCount() {
1211 this.checkComponentStructure();
1212 return children.size();
1215 public final RocketComponent getChild(int n) {
1217 this.checkComponentStructure();
1218 return children.get(n);
1221 public final List<RocketComponent> getChildren() {
1223 this.checkComponentStructure();
1224 return children.clone();
1229 * Returns the position of the child in this components child list, or -1 if the
1230 * component is not a child of this component.
1232 * @param child The child to search for.
1233 * @return Position in the list or -1 if not found.
1235 public final int getChildPosition(RocketComponent child) {
1237 this.checkComponentStructure();
1238 return children.indexOf(child);
1242 * Get the parent component of this component. Returns <code>null</code> if the component
1245 * @return The parent of this component or <code>null</code>.
1247 public final RocketComponent getParent() {
1253 * Get the root component of the component tree.
1255 * @return The root component of the component tree.
1257 public final RocketComponent getRoot() {
1259 RocketComponent gp = this;
1260 while (gp.parent != null)
1266 * Returns the root Rocket component of this component tree. Throws an
1267 * IllegalStateException if the root component is not a Rocket.
1269 * @return The root Rocket component of the component tree.
1270 * @throws IllegalStateException If the root component is not a Rocket.
1272 public final Rocket getRocket() {
1274 RocketComponent r = getRoot();
1275 if (r instanceof Rocket)
1277 throw new IllegalStateException("getRocket() called with root component "
1278 + r.getComponentName());
1283 * Return the Stage component that this component belongs to. Throws an
1284 * IllegalStateException if a Stage is not in the parentage of this component.
1286 * @return The Stage component this component belongs to.
1287 * @throws IllegalStateException if a Stage component is not in the parentage.
1289 public final Stage getStage() {
1291 RocketComponent c = this;
1293 if (c instanceof Stage)
1297 throw new IllegalStateException("getStage() called without Stage as a parent.");
1301 * Return the stage number of the stage this component belongs to. The stages
1302 * are numbered from zero upwards.
1304 * @return the stage number this component belongs to.
1306 public final int getStageNumber() {
1308 if (parent == null) {
1309 throw new IllegalArgumentException("getStageNumber() called for root component");
1312 RocketComponent stage = this;
1313 while (!(stage instanceof Stage)) {
1314 stage = stage.parent;
1315 if (stage == null || stage.parent == null) {
1316 throw new IllegalStateException("getStageNumber() could not find parent " +
1320 return stage.parent.getChildPosition(stage);
1325 * Find a component with the given ID. The component tree is searched from this component
1326 * down (including this component) for the ID and the corresponding component is returned,
1327 * or null if not found.
1329 * @param idToFind ID to search for.
1330 * @return The component with the ID, or null if not found.
1332 public final RocketComponent findComponent(String idToFind) {
1334 Iterator<RocketComponent> iter = this.iterator(true);
1335 while (iter.hasNext()) {
1336 RocketComponent c = iter.next();
1337 if (c.getID().equals(idToFind))
1344 // TODO: Move these methods elsewhere (used only in SymmetricComponent)
1345 public final RocketComponent getPreviousComponent() {
1347 this.checkComponentStructure();
1350 int pos = parent.getChildPosition(this);
1352 StringBuffer sb = new StringBuffer();
1353 sb.append("Inconsistent internal state: ");
1354 sb.append("this=").append(this).append('[')
1355 .append(System.identityHashCode(this)).append(']');
1356 sb.append(" parent.children=[");
1357 for (int i = 0; i < parent.children.size(); i++) {
1358 RocketComponent c = parent.children.get(i);
1359 sb.append(c).append('[').append(System.identityHashCode(c)).append(']');
1360 if (i < parent.children.size() - 1)
1364 throw new IllegalStateException(sb.toString());
1369 RocketComponent c = parent.getChild(pos - 1);
1370 while (c.getChildCount() > 0)
1371 c = c.getChild(c.getChildCount() - 1);
1375 // TODO: Move these methods elsewhere (used only in SymmetricComponent)
1376 public final RocketComponent getNextComponent() {
1378 if (getChildCount() > 0)
1381 RocketComponent current = this;
1382 RocketComponent nextParent = this.parent;
1384 while (nextParent != null) {
1385 int pos = nextParent.getChildPosition(current);
1386 if (pos < nextParent.getChildCount() - 1)
1387 return nextParent.getChild(pos + 1);
1389 current = nextParent;
1390 nextParent = current.parent;
1396 /////////// Event handling //////////
1398 // Listener lists are provided by the root Rocket component,
1399 // a single listener list for the whole rocket.
1403 * Adds a ComponentChangeListener to the rocket tree. The listener is added to the root
1404 * component, which must be of type Rocket (which overrides this method). Events of all
1405 * subcomponents are sent to all listeners.
1407 * @throws IllegalStateException - if the root component is not a Rocket
1409 public void addComponentChangeListener(ComponentChangeListener l) {
1411 getRocket().addComponentChangeListener(l);
1415 * Removes a ComponentChangeListener from the rocket tree. The listener is removed from
1416 * the root component, which must be of type Rocket (which overrides this method).
1417 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1418 * that listeners can always be removed just in case.)
1420 * @param l Listener to remove
1422 public void removeComponentChangeListener(ComponentChangeListener l) {
1423 if (parent != null) {
1424 getRoot().removeComponentChangeListener(l);
1430 * Adds a <code>ChangeListener</code> to the rocket tree. This is identical to
1431 * <code>addComponentChangeListener()</code> except that it uses a
1432 * <code>ChangeListener</code>. The same events are dispatched to the
1433 * <code>ChangeListener</code>, as <code>ComponentChangeEvent</code> is a subclass
1434 * of <code>ChangeEvent</code>.
1436 * @throws IllegalStateException - if the root component is not a <code>Rocket</code>
1439 public void addChangeListener(ChangeListener l) {
1441 getRocket().addChangeListener(l);
1445 * Removes a ChangeListener from the rocket tree. This is identical to
1446 * removeComponentChangeListener() except it uses a ChangeListener.
1447 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1448 * that listeners can always be removed just in case.)
1450 * @param l Listener to remove
1453 public void removeChangeListener(ChangeListener l) {
1454 if (this.parent != null) {
1455 getRoot().removeChangeListener(l);
1461 * Fires a ComponentChangeEvent on the rocket structure. The call is passed to the
1462 * root component, which must be of type Rocket (which overrides this method).
1463 * Events of all subcomponents are sent to all listeners.
1465 * If the component tree root is not a Rocket, the event is ignored. This is the
1466 * case when constructing components not in any Rocket tree. In this case it
1467 * would be impossible for the component to have listeners in any case.
1469 * @param e Event to send
1471 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
1473 if (parent == null) {
1474 /* Ignore if root invalid. */
1475 log.debug("Attempted firing event " + e + " with root " + this.getComponentName() + ", ignoring event");
1478 getRoot().fireComponentChangeEvent(e);
1483 * Fires a ComponentChangeEvent of the given type. The source of the event is set to
1486 * @param type Type of event
1487 * @see #fireComponentChangeEvent(ComponentChangeEvent)
1489 protected void fireComponentChangeEvent(int type) {
1490 fireComponentChangeEvent(new ComponentChangeEvent(this, type));
1495 * Checks whether this component has been invalidated and should no longer be used.
1496 * This is a safety check that in-place replaced components are no longer used.
1497 * All non-trivial methods (with the exception of methods simply getting a property)
1498 * should call this method before changing or computing anything.
1500 * @throws BugException if this component has been invalidated by {@link #copyFrom(RocketComponent)}.
1502 protected void checkState() {
1503 invalidator.check(true);
1509 * Check that the local component structure is correct. This can be called after changing
1510 * the component structure in order to verify the integrity.
1512 * TODO: Remove this after the "inconsistent internal state" bug has been corrected
1514 public void checkComponentStructure() {
1515 if (this.parent != null) {
1516 // Test that this component is found in parent's children with == operator
1517 if (!containsExact(this.parent.children, this)) {
1518 throw new BugException("Inconsistent component structure detected, parent does not contain this " +
1519 "component as a child, parent=" + parent.toDebugString() + " this=" + this.toDebugString());
1522 for (RocketComponent child : this.children) {
1523 if (child.parent != this) {
1524 throw new BugException("Inconsistent component structure detected, child does not have this component " +
1525 "as the parent, this=" + this.toDebugString() + " child=" + child.toDebugString() +
1526 " child.parent=" + (child.parent == null ? "null" : child.parent.toDebugString()));
1531 // Check whether the list contains exactly the searched-for component (with == operator)
1532 private boolean containsExact(List<RocketComponent> haystack, RocketComponent needle) {
1533 for (RocketComponent c : haystack) {
1542 /////////// Iterators //////////
1545 * Returns an iterator that iterates over all children and sub-children.
1547 * The iterator iterates through all children below this object, including itself if
1548 * <code>returnSelf</code> is true. The order of the iteration is not specified
1549 * (it may be specified in the future).
1551 * If an iterator iterating over only the direct children of the component is required,
1552 * use <code>component.getChildren().iterator()</code>.
1554 * TODO: HIGH: Remove this after merges have been done
1556 * @param returnSelf boolean value specifying whether the component itself should be
1558 * @return An iterator for the children and sub-children.
1559 * @deprecated Use {@link #iterator(boolean)} instead
1562 public final Iterator<RocketComponent> deepIterator(boolean returnSelf) {
1563 return iterator(returnSelf);
1568 * Returns an iterator that iterates over all children and sub-children, including itself.
1570 * This method is equivalent to <code>deepIterator(true)</code>.
1572 * TODO: HIGH: Remove this after merges have been done
1574 * @return An iterator for this component, its children and sub-children.
1575 * @deprecated Use {@link #iterator()} instead
1578 public final Iterator<RocketComponent> deepIterator() {
1585 * Returns an iterator that iterates over all children and sub-children.
1587 * The iterator iterates through all children below this object, including itself if
1588 * <code>returnSelf</code> is true. The order of the iteration is not specified
1589 * (it may be specified in the future).
1591 * If an iterator iterating over only the direct children of the component is required,
1592 * use <code>component.getChildren().iterator()</code>.
1594 * @param returnSelf boolean value specifying whether the component itself should be
1596 * @return An iterator for the children and sub-children.
1598 public final Iterator<RocketComponent> iterator(boolean returnSelf) {
1600 return new RocketComponentIterator(this, returnSelf);
1605 * Returns an iterator that iterates over this component, its children and sub-children.
1607 * This method is equivalent to <code>iterator(true)</code>.
1609 * @return An iterator for this component, its children and sub-children.
1612 public final Iterator<RocketComponent> iterator() {
1613 return iterator(true);
1621 * Compare component equality based on the ID of this component. Only the
1622 * ID and class type is used for a basis of comparison.
1625 public boolean equals(Object obj) {
1630 if (this.getClass() != obj.getClass())
1632 RocketComponent other = (RocketComponent) obj;
1633 return this.id.equals(other.id);
1639 public int hashCode() {
1640 return id.hashCode();
1645 //////////// Helper methods for subclasses
1651 * Helper method to add rotationally symmetric bounds at the specified coordinates.
1652 * The X-axis value is <code>x</code> and the radius at the specified position is
1655 protected static final void addBound(Collection<Coordinate> bounds, double x, double r) {
1656 bounds.add(new Coordinate(x, -r, -r));
1657 bounds.add(new Coordinate(x, r, -r));
1658 bounds.add(new Coordinate(x, r, r));
1659 bounds.add(new Coordinate(x, -r, r));
1663 protected static final Coordinate ringCG(double outerRadius, double innerRadius,
1664 double x1, double x2, double density) {
1665 return new Coordinate((x1 + x2) / 2, 0, 0,
1666 ringMass(outerRadius, innerRadius, x2 - x1, density));
1669 protected static final double ringMass(double outerRadius, double innerRadius,
1670 double length, double density) {
1671 return Math.PI * (MathUtil.pow2(outerRadius) - MathUtil.pow2(innerRadius)) *
1675 protected static final double ringLongitudinalUnitInertia(double outerRadius,
1676 double innerRadius, double length) {
1677 // 1/12 * (3 * (r1^2 + r2^2) + h^2)
1678 return (3 * (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) + MathUtil.pow2(length)) / 12;
1681 protected static final double ringRotationalUnitInertia(double outerRadius,
1682 double innerRadius) {
1683 // 1/2 * (r1^2 + r2^2)
1684 return (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) / 2;
1693 * Loads the RocketComponent fields from the given component. This method is meant
1694 * for in-place replacement of a component. It is used with the undo/redo
1695 * mechanism and when converting a finset into a freeform fin set.
1696 * This component must not have a parent, otherwise this method will fail.
1698 * The child components in the source tree are copied into the current tree, however,
1699 * the original components should not be used since they represent old copies of the
1700 * components. It is recommended to invalidate them by calling {@link #invalidate()}.
1702 * This method returns a list of components that should be invalidated after references
1703 * to them have been removed (for example by firing appropriate events). The list contains
1704 * all children and sub-children of the current component and the entire component
1705 * tree of <code>src</code>.
1707 * @return a list of components that should not be used after this call.
1709 protected List<RocketComponent> copyFrom(RocketComponent src) {
1711 List<RocketComponent> toInvalidate = new ArrayList<RocketComponent>();
1713 if (this.parent != null) {
1714 throw new UnsupportedOperationException("copyFrom called for non-root component, parent=" +
1715 this.parent.toDebugString() + ", this=" + this.toDebugString());
1718 // Add current structure to be invalidated
1719 Iterator<RocketComponent> iterator = this.iterator(false);
1720 while (iterator.hasNext()) {
1721 toInvalidate.add(iterator.next());
1724 // Remove previous components
1725 for (RocketComponent child : this.children) {
1726 child.parent = null;
1728 this.children.clear();
1730 // Copy new children to this component
1731 for (RocketComponent c : src.children) {
1732 RocketComponent copy = c.copyWithOriginalID();
1733 this.children.add(copy);
1737 this.checkComponentStructure();
1738 src.checkComponentStructure();
1740 // Set all parameters
1741 this.length = src.length;
1742 this.relativePosition = src.relativePosition;
1743 this.position = src.position;
1744 this.color = src.color;
1745 this.lineStyle = src.lineStyle;
1746 this.overrideMass = src.overrideMass;
1747 this.massOverriden = src.massOverriden;
1748 this.overrideCGX = src.overrideCGX;
1749 this.cgOverriden = src.cgOverriden;
1750 this.overrideSubcomponents = src.overrideSubcomponents;
1751 this.name = src.name;
1752 this.comment = src.comment;
1755 // Add source components to invalidation tree
1756 for (RocketComponent c : src) {
1757 toInvalidate.add(c);
1760 return toInvalidate;
1763 protected void invalidate() {
1764 invalidator.invalidate();
1768 ////////// Iterator implementation ///////////
1771 * Private inner class to implement the Iterator.
1773 * This iterator is fail-fast if the root of the structure is a Rocket.
1775 private static class RocketComponentIterator implements Iterator<RocketComponent> {
1776 // Stack holds iterators which still have some components left.
1777 private final Deque<Iterator<RocketComponent>> iteratorStack = new ArrayDeque<Iterator<RocketComponent>>();
1779 private final Rocket root;
1780 private final int treeModID;
1782 private final RocketComponent original;
1783 private boolean returnSelf = false;
1785 // Construct iterator with component's child's iterator, if it has elements
1786 public RocketComponentIterator(RocketComponent c, boolean returnSelf) {
1788 RocketComponent gp = c.getRoot();
1789 if (gp instanceof Rocket) {
1791 treeModID = root.getTreeModID();
1797 Iterator<RocketComponent> i = c.children.iterator();
1799 iteratorStack.push(i);
1802 this.returnSelf = returnSelf;
1806 public boolean hasNext() {
1810 return !iteratorStack.isEmpty(); // Elements remain if stack is not empty
1814 public RocketComponent next() {
1815 Iterator<RocketComponent> i;
1819 // Return original component first
1825 // Peek first iterator from stack, throw exception if empty
1826 i = iteratorStack.peek();
1828 throw new NoSuchElementException("No further elements in RocketComponent iterator");
1831 // Retrieve next component of the iterator, remove iterator from stack if empty
1832 RocketComponent c = i.next();
1834 iteratorStack.pop();
1836 // Add iterator of component children to stack if it has children
1837 i = c.children.iterator();
1839 iteratorStack.push(i);
1844 private void checkID() {
1846 if (root.getTreeModID() != treeModID) {
1847 throw new IllegalStateException("Rocket modified while being iterated");
1853 public void remove() {
1854 throw new UnsupportedOperationException("remove() not supported by " +
1855 "RocketComponent iterator");