1 package net.sf.openrocket.rocketcomponent;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.Collections;
7 import java.util.EmptyStackException;
8 import java.util.Iterator;
10 import java.util.NoSuchElementException;
11 import java.util.Stack;
13 import javax.swing.event.ChangeListener;
15 import net.sf.openrocket.logging.TraceException;
16 import net.sf.openrocket.util.BugException;
17 import net.sf.openrocket.util.ChangeSource;
18 import net.sf.openrocket.util.Coordinate;
19 import net.sf.openrocket.util.LineStyle;
20 import net.sf.openrocket.util.MathUtil;
21 import net.sf.openrocket.util.UniqueID;
24 public abstract class RocketComponent implements ChangeSource, Cloneable,
25 Iterable<RocketComponent> {
28 * Text is suitable to the form
29 * Position relative to: <title>
31 public enum Position {
32 /** Position relative to the top of the parent component. */
33 TOP("Top of the parent component"),
34 /** Position relative to the middle of the parent component. */
35 MIDDLE("Middle of the parent component"),
36 /** Position relative to the bottom of the parent component. */
37 BOTTOM("Bottom of the parent component"),
38 /** Position after the parent component (for body components). */
39 AFTER("After the parent component"),
40 /** Specify an absolute X-coordinate position. */
41 ABSOLUTE("Tip of the nose cone");
45 Position(String title) {
50 public String toString() {
55 //////// Parent/child trees
57 * Parent component of the current component, or null if none exists.
59 private RocketComponent parent = null;
62 * List of child components of this component.
64 private List<RocketComponent> children = new ArrayList<RocketComponent>();
67 //////// Parameters common to all components:
70 * Characteristic length of the component. This is used in calculating the coordinate
71 * transformations and positions of other components in reference to this component.
72 * This may and should be used as the "true" length of the component, where applicable.
73 * By default it is zero, i.e. no translation.
75 protected double length = 0;
78 * Positioning of this component relative to the parent component.
80 protected Position relativePosition;
83 * Offset of the position of this component relative to the normal position given by
84 * relativePosition. By default zero, i.e. no position change.
86 protected double position = 0;
89 // Color of the component, null means to use the default color
90 private Color color = null;
91 private LineStyle lineStyle = null;
95 private double overrideMass = 0;
96 private boolean massOverriden = false;
97 private double overrideCGX = 0;
98 private boolean cgOverriden = false;
100 private boolean overrideSubcomponents = false;
103 // User-given name of the component
104 private String name = null;
106 // User-specified comment
107 private String comment = "";
109 // Unique ID of the component
110 // TODO: CRITICAL: Sort out usage of ID and undo defect
111 private String id = null;
114 * When invalidated is non-null this component cannot be used anymore.
115 * This is a safety mechanism to prevent accidental use after calling {@link #copyFrom(RocketComponent)}.
117 private TraceException invalidated = null;
119 //// NOTE !!! All fields must be copied in the method copyFrom()! ////
124 * Default constructor. Sets the name of the component to the component's static name
125 * and the relative position of the component.
127 public RocketComponent(Position relativePosition) {
128 // These must not fire any events, due to Rocket undo system initialization
129 this.name = getComponentName();
130 this.relativePosition = relativePosition;
138 //////////// Methods that must be implemented ////////////
142 * Static component name. The name may not vary of the parameters, it must be static.
144 public abstract String getComponentName(); // Static component type name
147 * Return the component mass (regardless of mass overriding).
149 public abstract double getComponentMass(); // Mass of non-overridden component
152 * Return the component CG and mass (regardless of CG or mass overriding).
154 public abstract Coordinate getComponentCG(); // CG of non-overridden component
158 * Return the longitudal (around the y- or z-axis) unitary moment of inertia.
159 * The unitary moment of inertia is the moment of inertia with the assumption that
160 * the mass of the component is one kilogram. The inertia is measured in
161 * respect to the non-overridden CG.
163 * @return the longitudal unitary moment of inertia of this component.
165 public abstract double getLongitudalUnitInertia();
169 * Return the rotational (around the x-axis) unitary moment of inertia.
170 * The unitary moment of inertia is the moment of inertia with the assumption that
171 * the mass of the component is one kilogram. The inertia is measured in
172 * respect to the non-overridden CG.
174 * @return the rotational unitary moment of inertia of this component.
176 public abstract double getRotationalUnitInertia();
180 * Test whether this component allows any children components. This method must
181 * return true if and only if {@link #isCompatible(Class)} returns true for any
182 * rocket component class.
184 * @return <code>true</code> if children can be attached to this component, <code>false</code> otherwise.
186 public abstract boolean allowsChildren();
189 * Test whether the given component type can be added to this component. This type safety
190 * is enforced by the <code>addChild()</code> methods. The return value of this method
191 * may change to reflect the current state of this component (e.g. two components of some
192 * type cannot be placed as children).
194 * @param type The RocketComponent class type to add.
195 * @return Whether such a component can be added.
197 public abstract boolean isCompatible(Class<? extends RocketComponent> type);
200 /* Non-abstract helper method */
202 * Test whether the given component can be added to this component. This is equivalent
203 * to calling <code>isCompatible(c.getClass())</code>.
205 * @param c Component to test.
206 * @return Whether the component can be added.
207 * @see #isCompatible(Class)
209 public final boolean isCompatible(RocketComponent c) {
211 return isCompatible(c.getClass());
217 * Return a collection of bounding coordinates. The coordinates must be such that
218 * the component is fully enclosed in their convex hull.
220 * @return a collection of coordinates that bound the component.
222 public abstract Collection<Coordinate> getComponentBounds();
225 * Return true if the component may have an aerodynamic effect on the rocket.
227 public abstract boolean isAerodynamic();
230 * Return true if the component may have an effect on the rocket's mass.
232 public abstract boolean isMassive();
238 //////////// Methods that may be overridden ////////////
242 * Shift the coordinates in the array corresponding to radial movement. A component
243 * that has a radial position must shift the coordinates in this array suitably.
244 * If the component is clustered, then a new array must be returned with a
245 * coordinate for each cluster.
247 * The default implementation simply returns the array, and thus produces no shift.
249 * @param c an array of coordinates to shift.
250 * @return an array of shifted coordinates. The method may modify the contents
251 * of the passed array and return the array itself.
253 public Coordinate[] shiftCoordinates(Coordinate[] c) {
260 * Called when any component in the tree fires a ComponentChangeEvent. This is by
261 * default a no-op, but subclasses may override this method to e.g. invalidate
262 * cached data. The overriding method *must* call
263 * <code>super.componentChanged(e)</code> at some point.
265 * @param e The event fired
267 protected void componentChanged(ComponentChangeEvent e) {
276 * Return a descriptive name of the component.
278 * The description may include extra information about the type of component,
279 * e.g. "Conical nose cone".
281 * @return A string describing the component.
284 public final String toString() {
286 return getComponentName();
292 public final void printStructure() {
293 System.out.println("Rocket structure from '" + this.toString() + "':");
297 private void printStructure(int level) {
300 for (int i = 0; i < level; i++) {
303 s += this.toString() + " (" + this.getComponentName() + ")";
304 System.out.println(s);
306 for (RocketComponent c : children) {
307 c.printStructure(level + 1);
313 * Make a deep copy of the rocket component tree structure from this component
314 * downwards for copying purposes. Each component in the copy will be assigned
315 * a new component ID, making it a safe copy. This method does not fire any events.
317 * @return A deep copy of the structure.
319 public final RocketComponent copy() {
320 RocketComponent clone = copyWithOriginalID();
322 Iterator<RocketComponent> iterator = clone.deepIterator(true);
323 while (iterator.hasNext()) {
324 iterator.next().newID();
332 * Make a deep copy of the rocket component tree structure from this component
333 * downwards while maintaining the component ID's. The purpose of this method is
334 * to allow copies to be created with the original ID's for the purpose of the
335 * undo/redo mechanism. This method should not be used for other purposes,
336 * such as copy/paste. This method does not fire any events.
338 * This method must be overridden by any component that refers to mutable objects,
339 * or if some fields should not be copied. This should be performed by
340 * <code>RocketComponent c = super.copyWithOriginalID();</code> and then cloning/modifying
341 * the appropriate fields.
343 * This is not performed as serializing/deserializing for performance reasons.
345 * @return A deep copy of the structure.
347 protected RocketComponent copyWithOriginalID() {
349 RocketComponent clone;
351 clone = (RocketComponent) this.clone();
352 } catch (CloneNotSupportedException e) {
353 throw new BugException("CloneNotSupportedException encountered, " +
357 // Reset all parent/child information
359 clone.children = new ArrayList<RocketComponent>();
361 // Add copied children to the structure without firing events.
362 for (RocketComponent child : this.children) {
363 RocketComponent childCopy = child.copyWithOriginalID();
364 // Don't use add method since it fires events
365 clone.children.add(childCopy);
366 childCopy.parent = clone;
373 ////////////// Methods that may not be overridden ////////////
377 ////////// Common parameter setting/getting //////////
380 * Return the color of the object to use in 2D figures, or <code>null</code>
381 * to use the default color.
383 public final Color getColor() {
389 * Set the color of the object to use in 2D figures.
391 public final void setColor(Color c) {
393 if ((color == null && c == null) ||
394 (color != null && color.equals(c)))
398 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
402 public final LineStyle getLineStyle() {
407 public final void setLineStyle(LineStyle style) {
409 if (this.lineStyle == style)
411 this.lineStyle = style;
412 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
419 * Get the current override mass. The mass is not necessarily in use
422 * @return the override mass
424 public final double getOverrideMass() {
430 * Set the current override mass. The mass is not set to use by this
433 * @param m the override mass
435 public final void setOverrideMass(double m) {
437 overrideMass = Math.max(m, 0);
439 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
443 * Return whether mass override is active for this component. This does NOT
444 * take into account whether a parent component is overriding the mass.
446 * @return whether the mass is overridden
448 public final boolean isMassOverridden() {
450 return massOverriden;
454 * Set whether the mass is currently overridden.
456 * @param o whether the mass is overridden
458 public final void setMassOverridden(boolean o) {
460 if (massOverriden != o) {
462 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
471 * Return the current override CG. The CG is not necessarily overridden.
473 * @return the override CG
475 public final Coordinate getOverrideCG() {
477 return getComponentCG().setX(overrideCGX);
481 * Return the x-coordinate of the current override CG.
483 * @return the x-coordinate of the override CG.
485 public final double getOverrideCGX() {
491 * Set the current override CG to (x,0,0).
493 * @param x the x-coordinate of the override CG to set.
495 public final void setOverrideCGX(double x) {
497 if (MathUtil.equals(overrideCGX, x))
499 this.overrideCGX = x;
500 if (isCGOverridden())
501 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
503 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
507 * Return whether the CG is currently overridden.
509 * @return whether the CG is overridden
511 public final boolean isCGOverridden() {
517 * Set whether the CG is currently overridden.
519 * @param o whether the CG is overridden
521 public final void setCGOverridden(boolean o) {
523 if (cgOverriden != o) {
525 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
532 * Return whether the mass and/or CG override overrides all subcomponent values
533 * as well. The default implementation is a normal getter/setter implementation,
534 * however, subclasses are allowed to override this behavior if some subclass
535 * always or never overrides subcomponents. In this case the subclass should
536 * also override {@link #isOverrideSubcomponentsEnabled()} to return
537 * <code>false</code>.
539 * @return whether the current mass and/or CG override overrides subcomponents as well.
541 public boolean getOverrideSubcomponents() {
543 return overrideSubcomponents;
548 * Set whether the mass and/or CG override overrides all subcomponent values
549 * as well. See {@link #getOverrideSubcomponents()} for details.
551 * @param override whether the mass and/or CG override overrides all subcomponent.
553 public void setOverrideSubcomponents(boolean override) {
555 if (overrideSubcomponents != override) {
556 overrideSubcomponents = override;
557 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
562 * Return whether the option to override all subcomponents is enabled or not.
563 * The default implementation returns <code>false</code> if neither mass nor
564 * CG is overridden, <code>true</code> otherwise.
566 * This method may be overridden if the setting of overriding subcomponents
569 * @return whether the option to override subcomponents is currently enabled.
571 public boolean isOverrideSubcomponentsEnabled() {
573 return isCGOverridden() || isMassOverridden();
580 * Get the user-defined name of the component.
582 public final String getName() {
587 * Set the user-defined name of the component. If name==null, sets the name to
588 * the default name, currently the component name.
590 public final void setName(String name) {
592 if (name == null || name.matches("^\\s*$"))
593 this.name = getComponentName();
596 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
601 * Return the comment of the component. The component may contain multiple lines
602 * using \n as a newline separator.
604 * @return the comment of the component.
606 public final String getComment() {
612 * Set the comment of the component.
614 * @param comment the comment of the component.
616 public final void setComment(String comment) {
618 if (this.comment.equals(comment))
623 this.comment = comment;
624 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
630 * Returns the unique ID of the component.
632 * @return the ID of the component.
634 public final String getID() {
639 * Generate a new ID for this component.
641 private final void newID() {
642 this.id = UniqueID.uuid();
649 * Get the characteristic length of the component, for example the length of a body tube
650 * of the length of the root chord of a fin. This is used in positioning the component
651 * relative to its parent.
653 * If the length of a component is settable, the class must define the setter method
656 public final double getLength() {
662 * Get the positioning of the component relative to its parent component.
663 * This is one of the enums of {@link Position}. A setter method is not provided,
664 * but can be provided by a subclass.
666 public final Position getRelativePosition() {
668 return relativePosition;
673 * Set the positioning of the component relative to its parent component.
674 * The actual position of the component is maintained to the best ability.
676 * The default implementation is of protected visibility, since many components
677 * do not support setting the relative position. A component that does support
678 * it should override this with a public method that simply calls this
679 * supermethod AND fire a suitable ComponentChangeEvent.
681 * @param position the relative positioning.
683 protected void setRelativePosition(RocketComponent.Position position) {
685 if (this.relativePosition == position)
688 // Update position so as not to move the component
689 if (this.parent != null) {
690 double thisPos = this.toRelative(Coordinate.NUL, this.parent)[0].x;
694 this.position = this.toAbsolute(Coordinate.NUL)[0].x;
698 this.position = thisPos;
702 this.position = thisPos - (this.parent.length - this.length) / 2;
706 this.position = thisPos - (this.parent.length - this.length);
710 throw new BugException("Unknown position type: " + position);
714 this.relativePosition = position;
715 fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE);
722 * Get the position value of the component. The exact meaning of the value is
723 * dependent on the current relative positioning.
725 * @return the positional value.
727 public final double getPositionValue() {
734 * Set the position value of the component. The exact meaning of the value
735 * depends on the current relative positioning.
737 * The default implementation is of protected visibility, since many components
738 * do not support setting the relative position. A component that does support
739 * it should override this with a public method that simply calls this
740 * supermethod AND fire a suitable ComponentChangeEvent.
742 * @param value the position value of the component.
744 public void setPositionValue(double value) {
746 if (MathUtil.equals(this.position, value))
748 this.position = value;
753 /////////// Coordinate changes ///////////
756 * Returns coordinate c in absolute coordinates. Equivalent to toComponent(c,null).
758 public Coordinate[] toAbsolute(Coordinate c) {
760 return toRelative(c, null);
765 * Return coordinate <code>c</code> described in the coordinate system of
766 * <code>dest</code>. If <code>dest</code> is <code>null</code> returns
767 * absolute coordinates.
769 * This method returns an array of coordinates, each of which represents a
770 * position of the coordinate in clustered cases. The array is guaranteed
771 * to contain at least one element.
773 * The current implementation does not support rotating components.
775 * @param c Coordinate in the component's coordinate system.
776 * @param dest Destination component coordinate system.
777 * @return an array of coordinates describing <code>c</code> in coordinates
778 * relative to <code>dest</code>.
780 public final Coordinate[] toRelative(Coordinate c, RocketComponent dest) {
782 double absoluteX = Double.NaN;
783 RocketComponent search = dest;
784 Coordinate[] array = new Coordinate[1];
787 RocketComponent component = this;
788 while ((component != search) && (component.parent != null)) {
790 array = component.shiftCoordinates(array);
792 switch (component.relativePosition) {
794 for (int i = 0; i < array.length; i++) {
795 array[i] = array[i].add(component.position, 0, 0);
800 for (int i = 0; i < array.length; i++) {
801 array[i] = array[i].add(component.position +
802 (component.parent.length - component.length) / 2, 0, 0);
807 for (int i = 0; i < array.length; i++) {
808 array[i] = array[i].add(component.position +
809 (component.parent.length - component.length), 0, 0);
814 // Add length of all previous brother-components with POSITION_RELATIVE_AFTER
815 int index = component.parent.children.indexOf(component);
817 for (index--; index >= 0; index--) {
818 RocketComponent comp = component.parent.children.get(index);
819 double length = comp.getTotalLength();
820 for (int i = 0; i < array.length; i++) {
821 array[i] = array[i].add(length, 0, 0);
824 for (int i = 0; i < array.length; i++) {
825 array[i] = array[i].add(component.position + component.parent.length, 0, 0);
830 search = null; // Requires back-search if dest!=null
831 if (Double.isNaN(absoluteX)) {
832 absoluteX = component.position;
837 throw new BugException("Unknown relative positioning type of component" +
838 component + ": " + component.relativePosition);
841 component = component.parent; // parent != null
844 if (!Double.isNaN(absoluteX)) {
845 for (int i = 0; i < array.length; i++) {
846 array[i] = array[i].setX(absoluteX + c.x);
850 // Check whether destination has been found or whether to backtrack
851 // TODO: LOW: Backtracking into clustered components uses only one component
852 if ((dest != null) && (component != dest)) {
853 Coordinate[] origin = dest.toAbsolute(Coordinate.NUL);
854 for (int i = 0; i < array.length; i++) {
855 array[i] = array[i].sub(origin[0]);
864 * Recursively sum the lengths of all subcomponents that have position
867 * @return Sum of the lengths.
869 private final double getTotalLength() {
872 if (relativePosition == Position.AFTER)
874 for (int i = 0; i < children.size(); i++)
875 l += children.get(i).getTotalLength();
881 /////////// Total mass and CG calculation ////////////
884 * Return the (possibly overridden) mass of component.
886 * @return The mass of the component or the given override mass.
888 public final double getMass() {
892 return getComponentMass();
896 * Return the (possibly overridden) center of gravity and mass.
898 * Returns the CG with the weight of the coordinate set to the weight of the component.
899 * Both CG and mass may be separately overridden.
901 * @return The CG of the component or the given override CG.
903 public final Coordinate getCG() {
906 return getOverrideCG().setWeight(getMass());
909 return getComponentCG().setWeight(getMass());
911 return getComponentCG();
916 * Return the longitudal (around the y- or z-axis) moment of inertia of this component.
917 * The moment of inertia is scaled in reference to the (possibly overridden) mass
918 * and is relative to the non-overridden CG.
920 * @return the longitudal moment of inertia of this component.
922 public final double getLongitudalInertia() {
924 return getLongitudalUnitInertia() * getMass();
928 * Return the rotational (around the y- or z-axis) moment of inertia of this component.
929 * The moment of inertia is scaled in reference to the (possibly overridden) mass
930 * and is relative to the non-overridden CG.
932 * @return the rotational moment of inertia of this component.
934 public final double getRotationalInertia() {
936 return getRotationalUnitInertia() * getMass();
941 /////////// Children handling ///////////
945 * Adds a child to the rocket component tree. The component is added to the end
946 * of the component's child list. This is a helper method that calls
947 * {@link #addChild(RocketComponent,int)}.
949 * @param component The component to add.
950 * @throws IllegalArgumentException if the component is already part of some
952 * @see #addChild(RocketComponent,int)
954 public final void addChild(RocketComponent component) {
956 addChild(component, children.size());
961 * Adds a child to the rocket component tree. The component is added to
962 * the given position of the component's child list.
964 * This method may be overridden to enforce more strict component addition rules.
965 * The tests should be performed first and then this method called.
967 * @param component The component to add.
968 * @param position Position to add component to.
969 * @throws IllegalArgumentException If the component is already part of
970 * some component tree.
972 public void addChild(RocketComponent component, int position) {
974 if (component.parent != null) {
975 throw new IllegalArgumentException("component " + component.getComponentName() +
976 " is already in a tree");
978 if (!isCompatible(component)) {
979 throw new IllegalStateException("Component " + component.getComponentName() +
980 " not currently compatible with component " + getComponentName());
983 children.add(position, component);
984 component.parent = this;
986 fireAddRemoveEvent(component);
991 * Removes a child from the rocket component tree.
993 * @param n remove the n'th child.
994 * @throws IndexOutOfBoundsException if n is out of bounds
996 public final void removeChild(int n) {
998 RocketComponent component = children.remove(n);
999 component.parent = null;
1000 fireAddRemoveEvent(component);
1004 * Removes a child from the rocket component tree. Does nothing if the component
1005 * is not present as a child.
1007 * @param component the component to remove
1008 * @return whether the component was a child
1010 public final boolean removeChild(RocketComponent component) {
1012 if (children.remove(component)) {
1013 component.parent = null;
1014 fireAddRemoveEvent(component);
1024 * Move a child to another position.
1026 * @param component the component to move
1027 * @param position the component's new position
1028 * @throws IllegalArgumentException If an illegal placement was attempted.
1030 public final void moveChild(RocketComponent component, int position) {
1032 if (children.remove(component)) {
1033 children.add(position, component);
1034 fireAddRemoveEvent(component);
1040 * Fires an AERODYNAMIC_CHANGE, MASS_CHANGE or OTHER_CHANGE event depending on the
1041 * type of component removed.
1043 private void fireAddRemoveEvent(RocketComponent component) {
1044 Iterator<RocketComponent> iter = component.deepIterator(true);
1045 int type = ComponentChangeEvent.TREE_CHANGE;
1046 while (iter.hasNext()) {
1047 RocketComponent c = iter.next();
1048 if (c.isAerodynamic())
1049 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
1051 type |= ComponentChangeEvent.MASS_CHANGE;
1054 fireComponentChangeEvent(type);
1058 public final int getChildCount() {
1060 return children.size();
1063 public final RocketComponent getChild(int n) {
1065 return children.get(n);
1068 public final RocketComponent[] getChildren() {
1070 return children.toArray(new RocketComponent[0]);
1075 * Returns the position of the child in this components child list, or -1 if the
1076 * component is not a child of this component.
1078 * @param child The child to search for.
1079 * @return Position in the list or -1 if not found.
1081 public final int getChildPosition(RocketComponent child) {
1083 return children.indexOf(child);
1087 * Get the parent component of this component. Returns <code>null</code> if the component
1090 * @return The parent of this component or <code>null</code>.
1092 public final RocketComponent getParent() {
1098 * Get the root component of the component tree.
1100 * @return The root component of the component tree.
1102 public final RocketComponent getRoot() {
1104 RocketComponent gp = this;
1105 while (gp.parent != null)
1111 * Returns the root Rocket component of this component tree. Throws an
1112 * IllegalStateException if the root component is not a Rocket.
1114 * @return The root Rocket component of the component tree.
1115 * @throws IllegalStateException If the root component is not a Rocket.
1117 public final Rocket getRocket() {
1119 RocketComponent r = getRoot();
1120 if (r instanceof Rocket)
1122 throw new IllegalStateException("getRocket() called with root component "
1123 + r.getComponentName());
1128 * Return the Stage component that this component belongs to. Throws an
1129 * IllegalStateException if a Stage is not in the parentage of this component.
1131 * @return The Stage component this component belongs to.
1132 * @throws IllegalStateException if a Stage component is not in the parentage.
1134 public final Stage getStage() {
1136 RocketComponent c = this;
1138 if (c instanceof Stage)
1142 throw new IllegalStateException("getStage() called without Stage as a parent.");
1146 * Return the stage number of the stage this component belongs to. The stages
1147 * are numbered from zero upwards.
1149 * @return the stage number this component belongs to.
1151 public final int getStageNumber() {
1153 if (parent == null) {
1154 throw new IllegalArgumentException("getStageNumber() called for root component");
1157 RocketComponent stage = this;
1158 while (!(stage instanceof Stage)) {
1159 stage = stage.parent;
1160 if (stage == null || stage.parent == null) {
1161 throw new IllegalStateException("getStageNumber() could not find parent " +
1165 return stage.parent.getChildPosition(stage);
1170 * Find a component with the given ID. The component tree is searched from this component
1171 * down (including this component) for the ID and the corresponding component is returned,
1172 * or null if not found.
1174 * @param idToFind ID to search for.
1175 * @return The component with the ID, or null if not found.
1177 public final RocketComponent findComponent(String idToFind) {
1179 Iterator<RocketComponent> iter = this.deepIterator(true);
1180 while (iter.hasNext()) {
1181 RocketComponent c = iter.next();
1182 if (c.getID().equals(idToFind))
1189 public final RocketComponent getPreviousComponent() {
1193 int pos = parent.getChildPosition(this);
1195 StringBuffer sb = new StringBuffer();
1196 sb.append("Inconsistent internal state: ");
1197 sb.append("this=").append(this).append('[')
1198 .append(System.identityHashCode(this)).append(']');
1199 sb.append(" parent.children=[");
1200 for (int i = 0; i < parent.children.size(); i++) {
1201 RocketComponent c = parent.children.get(i);
1202 sb.append(c).append('[').append(System.identityHashCode(c)).append(']');
1203 if (i < parent.children.size() - 1)
1207 throw new IllegalStateException(sb.toString());
1212 RocketComponent c = parent.getChild(pos - 1);
1213 while (c.getChildCount() > 0)
1214 c = c.getChild(c.getChildCount() - 1);
1218 public final RocketComponent getNextComponent() {
1220 if (getChildCount() > 0)
1223 RocketComponent current = this;
1224 RocketComponent parent = this.parent;
1226 while (parent != null) {
1227 int pos = parent.getChildPosition(current);
1228 if (pos < parent.getChildCount() - 1)
1229 return parent.getChild(pos + 1);
1232 parent = current.parent;
1238 /////////// Event handling //////////
1240 // Listener lists are provided by the root Rocket component,
1241 // a single listener list for the whole rocket.
1245 * Adds a ComponentChangeListener to the rocket tree. The listener is added to the root
1246 * component, which must be of type Rocket (which overrides this method). Events of all
1247 * subcomponents are sent to all listeners.
1249 * @throws IllegalStateException - if the root component is not a Rocket
1251 public void addComponentChangeListener(ComponentChangeListener l) {
1253 getRocket().addComponentChangeListener(l);
1257 * Removes a ComponentChangeListener from the rocket tree. The listener is removed from
1258 * the root component, which must be of type Rocket (which overrides this method).
1259 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1260 * that listeners can always be removed just in case.)
1262 * @param l Listener to remove
1264 public void removeComponentChangeListener(ComponentChangeListener l) {
1265 if (parent != null) {
1266 getRoot().removeComponentChangeListener(l);
1272 * Adds a <code>ChangeListener</code> to the rocket tree. This is identical to
1273 * <code>addComponentChangeListener()</code> except that it uses a
1274 * <code>ChangeListener</code>. The same events are dispatched to the
1275 * <code>ChangeListener</code>, as <code>ComponentChangeEvent</code> is a subclass
1276 * of <code>ChangeEvent</code>.
1278 * @throws IllegalStateException - if the root component is not a <code>Rocket</code>
1280 public void addChangeListener(ChangeListener l) {
1282 getRocket().addChangeListener(l);
1286 * Removes a ChangeListener from the rocket tree. This is identical to
1287 * removeComponentChangeListener() except it uses a ChangeListener.
1288 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1289 * that listeners can always be removed just in case.)
1291 * @param l Listener to remove
1293 public void removeChangeListener(ChangeListener l) {
1294 if (this.parent != null) {
1295 getRoot().removeChangeListener(l);
1301 * Fires a ComponentChangeEvent on the rocket structure. The call is passed to the
1302 * root component, which must be of type Rocket (which overrides this method).
1303 * Events of all subcomponents are sent to all listeners.
1305 * If the component tree root is not a Rocket, the event is ignored. This is the
1306 * case when constructing components not in any Rocket tree. In this case it
1307 * would be impossible for the component to have listeners in any case.
1309 * @param e Event to send
1311 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
1313 if (parent == null) {
1314 /* Ignore if root invalid. */
1317 getRoot().fireComponentChangeEvent(e);
1322 * Fires a ComponentChangeEvent of the given type. The source of the event is set to
1325 * @param type Type of event
1326 * @see #fireComponentChangeEvent(ComponentChangeEvent)
1328 protected void fireComponentChangeEvent(int type) {
1329 fireComponentChangeEvent(new ComponentChangeEvent(this, type));
1334 * Checks whether this component has been invalidated and should no longer be used.
1335 * This is a safety check that in-place replaced components are no longer used.
1336 * All non-trivial methods should call this method as the first thing, unless the
1337 * method may be used in debugging cases.
1339 * @throws BugException if this component has been invalidated by {@link #copyFrom(RocketComponent)}.
1341 protected void checkState() {
1342 if (invalidated != null) {
1343 throw new BugException("This component has been invalidated. Cause is the point of invalidation.",
1349 /////////// Iterator implementation //////////
1352 * Private inner class to implement the Iterator.
1354 * This iterator is fail-fast if the root of the structure is a Rocket.
1356 private class RocketComponentIterator implements Iterator<RocketComponent> {
1357 // Stack holds iterators which still have some components left.
1358 private final Stack<Iterator<RocketComponent>> iteratorstack =
1359 new Stack<Iterator<RocketComponent>>();
1361 private final Rocket root;
1362 private final int treeModID;
1364 private final RocketComponent original;
1365 private boolean returnSelf = false;
1367 // Construct iterator with component's child's iterator, if it has elements
1368 public RocketComponentIterator(RocketComponent c, boolean returnSelf) {
1370 RocketComponent gp = c.getRoot();
1371 if (gp instanceof Rocket) {
1373 treeModID = root.getTreeModID();
1379 Iterator<RocketComponent> i = c.children.iterator();
1381 iteratorstack.push(i);
1384 this.returnSelf = returnSelf;
1387 public boolean hasNext() {
1392 return !iteratorstack.empty(); // Elements remain if stack is not empty
1395 public RocketComponent next() {
1396 Iterator<RocketComponent> i;
1401 // Return original component first
1407 // Peek first iterator from stack, throw exception if empty
1409 i = iteratorstack.peek();
1410 } catch (EmptyStackException e) {
1411 throw new NoSuchElementException("No further elements in " +
1412 "RocketComponent iterator");
1415 // Retrieve next component of the iterator, remove iterator from stack if empty
1416 RocketComponent c = i.next();
1418 iteratorstack.pop();
1420 // Add iterator of component children to stack if it has children
1421 i = c.children.iterator();
1423 iteratorstack.push(i);
1428 private void checkID() {
1430 if (root.getTreeModID() != treeModID) {
1431 throw new IllegalStateException("Rocket modified while being iterated");
1436 public void remove() {
1437 throw new UnsupportedOperationException("remove() not supported by " +
1438 "RocketComponent iterator");
1443 * Returns an iterator that iterates over all children and sub-children.
1445 * The iterator iterates through all children below this object, including itself if
1446 * returnSelf is true. The order of the iteration is not specified
1447 * (it may be specified in the future).
1449 * If an iterator iterating over only the direct children of the component is required,
1450 * use component.getChildren().iterator()
1452 * @param returnSelf boolean value specifying whether the component itself should be
1454 * @return An iterator for the children and sub-children.
1456 public final Iterator<RocketComponent> deepIterator(boolean returnSelf) {
1458 return new RocketComponentIterator(this, returnSelf);
1462 * Returns an iterator that iterates over all children and sub-children.
1464 * The iterator does NOT return the component itself. It is thus equivalent to
1465 * deepIterator(false).
1468 * @return An iterator for the children and sub-children.
1470 public final Iterator<RocketComponent> deepIterator() {
1472 return new RocketComponentIterator(this, false);
1477 * Return an iterator that iterates of the children of the component. The iterator
1478 * does NOT recurse to sub-children nor return itself.
1480 * @return An iterator for the children.
1482 public final Iterator<RocketComponent> iterator() {
1484 return Collections.unmodifiableList(children).iterator();
1491 * Compare component equality based on the ID of this component. Only the
1492 * ID and class type is used for a basis of comparison.
1495 public boolean equals(Object obj) {
1500 if (this.getClass() != obj.getClass())
1502 RocketComponent other = (RocketComponent) obj;
1503 return this.id.equals(other.id);
1509 public int hashCode() {
1510 return id.hashCode();
1515 //////////// Helper methods for subclasses
1521 * Helper method to add rotationally symmetric bounds at the specified coordinates.
1522 * The X-axis value is <code>x</code> and the radius at the specified position is
1525 protected static final void addBound(Collection<Coordinate> bounds, double x, double r) {
1526 bounds.add(new Coordinate(x, -r, -r));
1527 bounds.add(new Coordinate(x, r, -r));
1528 bounds.add(new Coordinate(x, r, r));
1529 bounds.add(new Coordinate(x, -r, r));
1533 protected static final Coordinate ringCG(double outerRadius, double innerRadius,
1534 double x1, double x2, double density) {
1535 return new Coordinate((x1 + x2) / 2, 0, 0,
1536 ringMass(outerRadius, innerRadius, x2 - x1, density));
1539 protected static final double ringMass(double outerRadius, double innerRadius,
1540 double length, double density) {
1541 return Math.PI * (MathUtil.pow2(outerRadius) - MathUtil.pow2(innerRadius)) *
1545 protected static final double ringLongitudalUnitInertia(double outerRadius,
1546 double innerRadius, double length) {
1547 // 1/12 * (3 * (r1^2 + r2^2) + h^2)
1548 return (3 * (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) + MathUtil.pow2(length)) / 12;
1551 protected static final double ringRotationalUnitInertia(double outerRadius,
1552 double innerRadius) {
1553 // 1/2 * (r1^2 + r2^2)
1554 return (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) / 2;
1563 * Loads the RocketComponent fields from the given component. This method is meant
1564 * for in-place replacement of a component. It is used with the undo/redo
1565 * mechanism and when converting a finset into a freeform fin set.
1566 * This component must not have a parent, otherwise this method will fail.
1568 * The fields are copied by reference, and the supplied component must not be used
1569 * after the call, as it is in an undefined state. This is enforced by invalidating
1570 * the source component.
1572 * TODO: MEDIUM: Make general to copy all private/protected fields...
1574 protected void copyFrom(RocketComponent src) {
1577 if (this.parent != null) {
1578 throw new UnsupportedOperationException("copyFrom called for non-root component "
1582 // Set parents and children
1583 this.children = src.children;
1584 src.children = new ArrayList<RocketComponent>();
1586 for (RocketComponent c : this.children) {
1590 // Set all parameters
1591 this.length = src.length;
1592 this.relativePosition = src.relativePosition;
1593 this.position = src.position;
1594 this.color = src.color;
1595 this.lineStyle = src.lineStyle;
1596 this.overrideMass = src.overrideMass;
1597 this.massOverriden = src.massOverriden;
1598 this.overrideCGX = src.overrideCGX;
1599 this.cgOverriden = src.cgOverriden;
1600 this.overrideSubcomponents = src.overrideSubcomponents;
1601 this.name = src.name;
1602 this.comment = src.comment;
1605 src.invalidated = new TraceException();