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;
12 import java.util.UUID;
14 import javax.swing.event.ChangeListener;
16 import net.sf.openrocket.util.ChangeSource;
17 import net.sf.openrocket.util.Coordinate;
18 import net.sf.openrocket.util.LineStyle;
19 import net.sf.openrocket.util.MathUtil;
22 public abstract class RocketComponent implements ChangeSource, Cloneable,
23 Iterable<RocketComponent> {
26 * Text is suitable to the form
27 * Position relative to: <title>
29 public enum Position {
30 /** Position relative to the top of the parent component. */
31 TOP("Top of the parent component"),
32 /** Position relative to the middle of the parent component. */
33 MIDDLE("Middle of the parent component"),
34 /** Position relative to the bottom of the parent component. */
35 BOTTOM("Bottom of the parent component"),
36 /** Position after the parent component (for body components). */
37 AFTER("After the parent component"),
38 /** Specify an absolute X-coordinate position. */
39 ABSOLUTE("Tip of the nose cone");
42 Position(String title) {
47 public String toString() {
52 //////// Parent/child trees
54 * Parent component of the current component, or null if none exists.
56 private RocketComponent parent = null;
59 * List of child components of this component.
61 private List<RocketComponent> children = new ArrayList<RocketComponent>();
64 //////// Parameters common to all components:
67 * Characteristic length of the component. This is used in calculating the coordinate
68 * transformations and positions of other components in reference to this component.
69 * This may and should be used as the "true" length of the component, where applicable.
70 * By default it is zero, i.e. no translation.
72 protected double length = 0;
75 * Positioning of this component relative to the parent component.
77 protected Position relativePosition;
80 * Offset of the position of this component relative to the normal position given by
81 * relativePosition. By default zero, i.e. no position change.
83 protected double position = 0;
86 // Color of the component, null means to use the default color
87 private Color color = null;
88 private LineStyle lineStyle = null;
92 private double overrideMass = 0;
93 private boolean massOverriden = false;
94 private double overrideCGX = 0;
95 private boolean cgOverriden = false;
97 private boolean overrideSubcomponents = false;
100 // User-given name of the component
101 private String name = null;
103 // User-specified comment
104 private String comment = "";
106 // Unique ID of the component
107 private String id = null;
109 //// NOTE !!! All fields must be copied in the method copyFrom()! ////
114 * Default constructor. Sets the name of the component to the component's static name
115 * and the relative position of the component.
117 public RocketComponent(Position relativePosition) {
118 // These must not fire any events, due to Rocket undo system initialization
119 this.name = getComponentName();
120 this.relativePosition = relativePosition;
121 this.id = UUID.randomUUID().toString();
128 //////////// Methods that must be implemented ////////////
132 * Static component name. The name may not vary of the parameters, it must be static.
134 public abstract String getComponentName(); // Static component type name
137 * Return the component mass (regardless of mass overriding).
139 public abstract double getComponentMass(); // Mass of non-overridden component
142 * Return the component CG and mass (regardless of CG or mass overriding).
144 public abstract Coordinate getComponentCG(); // CG of non-overridden component
148 * Return the longitudal (around the y- or z-axis) unitary moment of inertia.
149 * The unitary moment of inertia is the moment of inertia with the assumption that
150 * the mass of the component is one kilogram. The inertia is measured in
151 * respect to the non-overridden CG.
153 * @return the longitudal unitary moment of inertia of this component.
155 public abstract double getLongitudalUnitInertia();
159 * Return the rotational (around the x-axis) unitary moment of inertia.
160 * The unitary moment of inertia is the moment of inertia with the assumption that
161 * the mass of the component is one kilogram. The inertia is measured in
162 * respect to the non-overridden CG.
164 * @return the rotational unitary moment of inertia of this component.
166 public abstract double getRotationalUnitInertia();
172 * Test whether the given component type can be added to this component. This type safety
173 * is enforced by the <code>addChild()</code> methods. The return value of this method
174 * may change to reflect the current state of this component (e.g. two components of some
175 * type cannot be placed as children).
177 * @param type The RocketComponent class type to add.
178 * @return Whether such a component can be added.
180 public abstract boolean isCompatible(Class<? extends RocketComponent> type);
183 /* Non-abstract helper method */
185 * Test whether the given component can be added to this component. This is equivalent
186 * to calling <code>isCompatible(c.getClass())</code>.
188 * @param c Component to test.
189 * @return Whether the component can be added.
190 * @see #isCompatible(Class)
192 public final boolean isCompatible(RocketComponent c) {
193 return isCompatible(c.getClass());
199 * Return a collection of bounding coordinates. The coordinates must be such that
200 * the component is fully enclosed in their convex hull.
202 * @return a collection of coordinates that bound the component.
204 public abstract Collection<Coordinate> getComponentBounds();
207 * Return true if the component may have an aerodynamic effect on the rocket.
209 public abstract boolean isAerodynamic();
212 * Return true if the component may have an effect on the rocket's mass.
214 public abstract boolean isMassive();
220 //////////// Methods that may be overridden ////////////
224 * Shift the coordinates in the array corresponding to radial movement. A component
225 * that has a radial position must shift the coordinates in this array suitably.
226 * If the component is clustered, then a new array must be returned with a
227 * coordinate for each cluster.
229 * The default implementation simply returns the array, and thus produces no shift.
231 * @param c an array of coordinates to shift.
232 * @return an array of shifted coordinates. The method may modify the contents
233 * of the passed array and return the array itself.
235 public Coordinate[] shiftCoordinates(Coordinate[] c) {
241 * Called when any component in the tree fires a ComponentChangeEvent. This is by
242 * default a no-op, but subclasses may override this method to e.g. invalidate
243 * cached data. The overriding method *must* call
244 * <code>super.componentChanged(e)</code> at some point.
246 * @param e The event fired
248 protected void componentChanged(ComponentChangeEvent e) {
256 * Return a descriptive name of the component.
258 * The description may include extra information about the type of component,
259 * e.g. "Conical nose cone".
261 * @return A string describing the component.
264 public final String toString() {
266 return getComponentName();
272 public final void printStructure() {
273 System.out.println("Rocket structure from '"+this.toString()+"':");
277 private void printStructure(int level) {
280 for (int i=0; i < level; i++) {
283 s += this.toString() + " (" + this.getComponentName()+")";
284 System.out.println(s);
286 for (RocketComponent c: children) {
287 c.printStructure(level+1);
293 * Make a deep copy of the rocket component tree structure from this component
294 * downwards. This method does not fire any events.
296 * This method must be overridden by any component that refers to mutable objects,
297 * or if some fields should not be copied. This should be performed by
298 * <code>RocketComponent c = super.copy();</code> and then cloning/modifying the
299 * appropriate fields.
301 * This is not performed as serializing/deserializing for performance reasons.
303 * @return A deep copy of the structure.
305 public RocketComponent copy() {
306 RocketComponent clone;
308 clone = (RocketComponent)this.clone();
309 } catch (CloneNotSupportedException e) {
310 throw new RuntimeException("CloneNotSupportedException encountered, " +
314 // Reset all parent/child information
316 clone.children = new ArrayList<RocketComponent>();
318 // Add copied children to the structure without firing events.
319 for (RocketComponent c: this.children) {
320 RocketComponent copy = c.copy();
321 clone.children.add(copy);
329 ////////////// Methods that may not be overridden ////////////
333 ////////// Common parameter setting/getting //////////
336 * Return the color of the object to use in 2D figures, or <code>null</code>
337 * to use the default color.
339 public final Color getColor() {
344 * Set the color of the object to use in 2D figures.
346 public final void setColor(Color c) {
347 if ((color == null && c == null) ||
348 (color != null && color.equals(c)))
352 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
356 public final LineStyle getLineStyle() {
360 public final void setLineStyle(LineStyle style) {
361 if (this.lineStyle == style)
363 this.lineStyle = style;
364 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
371 * Get the current override mass. The mass is not necessarily in use
374 * @return the override mass
376 public final double getOverrideMass() {
381 * Set the current override mass. The mass is not set to use by this
384 * @param m the override mass
386 public final void setOverrideMass(double m) {
387 overrideMass = Math.max(m,0);
389 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
393 * Return whether mass override is active for this component. This does NOT
394 * take into account whether a parent component is overriding the mass.
396 * @return whether the mass is overridden
398 public final boolean isMassOverridden() {
399 return massOverriden;
403 * Set whether the mass is currently overridden.
405 * @param o whether the mass is overridden
407 public final void setMassOverridden(boolean o) {
408 if (massOverriden != o) {
410 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
419 * Return the current override CG. The CG is not necessarily overridden.
421 * @return the override CG
423 public final Coordinate getOverrideCG() {
424 return getComponentCG().setX(overrideCGX);
428 * Return the x-coordinate of the current override CG.
430 * @return the x-coordinate of the override CG.
432 public final double getOverrideCGX() {
437 * Set the current override CG to (x,0,0).
439 * @param x the x-coordinate of the override CG to set.
441 public final void setOverrideCGX(double x) {
442 if (MathUtil.equals(overrideCGX, x))
444 this.overrideCGX = x;
445 if (isCGOverridden())
446 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
448 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
452 * Return whether the CG is currently overridden.
454 * @return whether the CG is overridden
456 public final boolean isCGOverridden() {
461 * Set whether the CG is currently overridden.
463 * @param o whether the CG is overridden
465 public final void setCGOverridden(boolean o) {
466 if (cgOverriden != o) {
468 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
475 * Return whether the mass and/or CG override overrides all subcomponent values
476 * as well. The default implementation is a normal getter/setter implementation,
477 * however, subclasses are allowed to override this behavior if some subclass
478 * always or never overrides subcomponents. In this case the subclass should
479 * also override {@link #isOverrideSubcomponentsEnabled()} to return
480 * <code>false</code>.
482 * @return whether the current mass and/or CG override overrides subcomponents as well.
484 public boolean getOverrideSubcomponents() {
485 return overrideSubcomponents;
490 * Set whether the mass and/or CG override overrides all subcomponent values
491 * as well. See {@link #getOverrideSubcomponents()} for details.
493 * @param override whether the mass and/or CG override overrides all subcomponent.
495 public void setOverrideSubcomponents(boolean override) {
496 if (overrideSubcomponents != override) {
497 overrideSubcomponents = override;
498 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
503 * Return whether the option to override all subcomponents is enabled or not.
504 * The default implementation returns <code>false</code> if neither mass nor
505 * CG is overridden, <code>true</code> otherwise.
507 * This method may be overridden if the setting of overriding subcomponents
510 * @return whether the option to override subcomponents is currently enabled.
512 public boolean isOverrideSubcomponentsEnabled() {
513 return isCGOverridden() || isMassOverridden();
520 * Get the user-defined name of the component.
522 public final String getName() {
527 * Set the user-defined name of the component. If name==null, sets the name to
528 * the default name, currently the component name.
530 public final void setName(String name) {
531 // System.out.println("Set name called:"+name+" orig:"+this.name);
532 if (name==null || name.matches("^\\s*$"))
533 this.name = getComponentName();
536 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
541 * Return the comment of the component. The component may contain multiple lines
542 * using \n as a newline separator.
544 * @return the comment of the component.
546 public final String getComment() {
551 * Set the comment of the component.
553 * @param comment the comment of the component.
555 public final void setComment(String comment) {
556 if (this.comment.equals(comment))
561 this.comment = comment;
562 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
568 * Returns the unique ID of the component.
570 * @return the ID of the component.
572 public final String getID() {
578 * Set the unique ID of the component. If <code>id</code> in <code>null</code> then
579 * this method generates a new unique ID for the component.
581 * This method should be used only in special cases, such as when creating database
582 * entries with empty IDs.
584 * @param id the ID to set.
586 public final void setID(String id) {
588 this.id = UUID.randomUUID().toString();
592 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
599 * Get the characteristic length of the component, for example the length of a body tube
600 * of the length of the root chord of a fin. This is used in positioning the component
601 * relative to its parent.
603 * If the length of a component is settable, the class must define the setter method
606 public final double getLength() {
611 * Get the positioning of the component relative to its parent component.
612 * This is one of the enums of {@link Position}. A setter method is not provided,
613 * but can be provided by a subclass.
615 public final Position getRelativePosition() {
616 return relativePosition;
621 * Set the positioning of the component relative to its parent component.
622 * The actual position of the component is maintained to the best ability.
624 * The default implementation is of protected visibility, since many components
625 * do not support setting the relative position. A component that does support
626 * it should override this with a public method that simply calls this
627 * supermethod AND fire a suitable ComponentChangeEvent.
629 * @param position the relative positioning.
631 protected void setRelativePosition(RocketComponent.Position position) {
632 if (this.relativePosition == position)
635 // Update position so as not to move the component
636 if (this.parent != null) {
637 double thisPos = this.toRelative(Coordinate.NUL,this.parent)[0].x;
641 this.position = this.toAbsolute(Coordinate.NUL)[0].x;
645 this.position = thisPos;
649 this.position = thisPos - (this.parent.length - this.length)/2;
653 this.position = thisPos - (this.parent.length - this.length);
657 assert(false): "Should not occur";
661 this.relativePosition = position;
662 fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE);
669 * Get the position value of the component. The exact meaning of the value is
670 * dependent on the current relative positioning.
672 * @return the positional value.
674 public final double getPositionValue() {
680 * Set the position value of the component. The exact meaning of the value
681 * depends on the current relative positioning.
683 * The default implementation is of protected visibility, since many components
684 * do not support setting the relative position. A component that does support
685 * it should override this with a public method that simply calls this
686 * supermethod AND fire a suitable ComponentChangeEvent.
688 * @param value the position value of the component.
690 public void setPositionValue(double value) {
691 if (MathUtil.equals(this.position, value))
693 this.position = value;
698 /////////// Coordinate changes ///////////
701 * Returns coordinate c in absolute coordinates. Equivalent to toComponent(c,null).
703 public Coordinate[] toAbsolute(Coordinate c) {
704 return toRelative(c,null);
709 * Return coordinate <code>c</code> described in the coordinate system of
710 * <code>dest</code>. If <code>dest</code> is <code>null</code> returns
711 * absolute coordinates.
713 * This method returns an array of coordinates, each of which represents a
714 * position of the coordinate in clustered cases. The array is guaranteed
715 * to contain at least one element.
717 * The current implementation does not support rotating components.
719 * @param c Coordinate in the component's coordinate system.
720 * @param dest Destination component coordinate system.
721 * @return an array of coordinates describing <code>c</code> in coordinates
722 * relative to <code>dest</code>.
724 public final Coordinate[] toRelative(Coordinate c, RocketComponent dest) {
725 double absoluteX = Double.NaN;
726 RocketComponent search = dest;
727 Coordinate[] array = new Coordinate[1];
730 RocketComponent component = this;
731 while ((component != search) && (component.parent != null)) {
733 array = component.shiftCoordinates(array);
735 switch (component.relativePosition) {
737 for (int i=0; i < array.length; i++) {
738 array[i] = array[i].add(component.position,0,0);
743 for (int i=0; i < array.length; i++) {
744 array[i] = array[i].add(component.position +
745 (component.parent.length-component.length)/2,0,0);
750 for (int i=0; i < array.length; i++) {
751 array[i] = array[i].add(component.position +
752 (component.parent.length-component.length),0,0);
757 // Add length of all previous brother-components with POSITION_RELATIVE_AFTER
758 int index = component.parent.children.indexOf(component);
760 for (index--; index >= 0; index--) {
761 RocketComponent comp = component.parent.children.get(index);
762 double length = comp.getTotalLength();
763 for (int i=0; i < array.length; i++) {
764 array[i] = array[i].add(length,0,0);
767 for (int i=0; i < array.length; i++) {
768 array[i] = array[i].add(component.position + component.parent.length,0,0);
773 search = null; // Requires back-search if dest!=null
774 if (Double.isNaN(absoluteX)) {
775 absoluteX = component.position;
780 throw new RuntimeException("Unknown relative positioning type of component"+
781 component+": "+component.relativePosition);
784 component = component.parent; // parent != null
787 if (!Double.isNaN(absoluteX)) {
788 for (int i=0; i < array.length; i++) {
789 array[i] = array[i].setX(absoluteX + c.x);
793 // Check whether destination has been found or whether to backtrack
794 // TODO: LOW: Backtracking into clustered components uses only one component
795 if ((dest != null) && (component != dest)) {
796 Coordinate[] origin = dest.toAbsolute(Coordinate.NUL);
797 for (int i=0; i < array.length; i++) {
798 array[i] = array[i].sub(origin[0]);
807 * Recursively sum the lengths of all subcomponents that have position
810 * @return Sum of the lengths.
812 private final double getTotalLength() {
814 if (relativePosition == Position.AFTER)
816 for (int i=0; i<children.size(); i++)
817 l += children.get(i).getTotalLength();
823 /////////// Total mass and CG calculation ////////////
826 * Return the (possibly overridden) mass of component.
828 * @return The mass of the component or the given override mass.
830 public final double getMass() {
833 return getComponentMass();
837 * Return the (possibly overridden) center of gravity and mass.
839 * Returns the CG with the weight of the coordinate set to the weight of the component.
840 * Both CG and mass may be separately overridden.
842 * @return The CG of the component or the given override CG.
844 public final Coordinate getCG() {
846 return getOverrideCG().setWeight(getMass());
849 return getComponentCG().setWeight(getMass());
851 return getComponentCG();
856 * Return the longitudal (around the y- or z-axis) moment of inertia of this component.
857 * The moment of inertia is scaled in reference to the (possibly overridden) mass
858 * and is relative to the non-overridden CG.
860 * @return the longitudal moment of inertia of this component.
862 public final double getLongitudalInertia() {
863 return getLongitudalUnitInertia() * getMass();
867 * Return the rotational (around the y- or z-axis) moment of inertia of this component.
868 * The moment of inertia is scaled in reference to the (possibly overridden) mass
869 * and is relative to the non-overridden CG.
871 * @return the rotational moment of inertia of this component.
873 public final double getRotationalInertia() {
874 return getRotationalUnitInertia() * getMass();
879 /////////// Children handling ///////////
883 * Adds a child to the rocket component tree. The component is added to the end
884 * of the component's child list. This is a helper method that calls
885 * {@link #addChild(RocketComponent,int)}.
887 * @param component The component to add.
888 * @throws IllegalArgumentException if the component is already part of some
890 * @see #addChild(RocketComponent,int)
892 public final void addChild(RocketComponent component) {
893 addChild(component,children.size());
898 * Adds a child to the rocket component tree. The component is added to
899 * the given position of the component's child list.
901 * This method may be overridden to enforce more strict component addition rules.
902 * The tests should be performed first and then this method called.
904 * @param component The component to add.
905 * @param position Position to add component to.
906 * @throws IllegalArgumentException If the component is already part of
907 * some component tree.
909 public void addChild(RocketComponent component, int position) {
910 if (component.parent != null) {
911 throw new IllegalArgumentException("component "+component.getComponentName()+
912 " is already in a tree");
914 if (!isCompatible(component)) {
915 throw new IllegalStateException("Component "+component.getComponentName()+
916 " not currently compatible with component "+getComponentName());
919 children.add(position,component);
920 component.parent = this;
922 fireAddRemoveEvent(component);
927 * Removes a child from the rocket component tree.
929 * @param n remove the n'th child.
930 * @throws IndexOutOfBoundsException if n is out of bounds
932 public final void removeChild(int n) {
933 RocketComponent component = children.remove(n);
934 component.parent = null;
935 fireAddRemoveEvent(component);
939 * Removes a child from the rocket component tree. Does nothing if the component
940 * is not present as a child.
942 * @param component the component to remove
944 public final void removeChild(RocketComponent component) {
945 if (children.remove(component)) {
946 component.parent = null;
948 fireAddRemoveEvent(component);
956 * Move a child to another position.
958 * @param component the component to move
959 * @param position the component's new position
960 * @throws IllegalArgumentException If an illegal placement was attempted.
962 public final void moveChild(RocketComponent component, int position) {
963 if (children.remove(component)) {
964 children.add(position, component);
965 fireAddRemoveEvent(component);
971 * Fires an AERODYNAMIC_CHANGE, MASS_CHANGE or OTHER_CHANGE event depending on the
972 * type of component removed.
974 private void fireAddRemoveEvent(RocketComponent component) {
975 Iterator<RocketComponent> iter = component.deepIterator(true);
976 int type = ComponentChangeEvent.TREE_CHANGE;
977 while (iter.hasNext()) {
978 RocketComponent c = iter.next();
979 if (c.isAerodynamic())
980 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
982 type |= ComponentChangeEvent.MASS_CHANGE;
985 fireComponentChangeEvent(type);
989 public final int getChildCount() {
990 return children.size();
993 public final RocketComponent getChild(int n) {
994 return children.get(n);
997 public final RocketComponent[] getChildren() {
998 return children.toArray(new RocketComponent[0]);
1003 * Returns the position of the child in this components child list, or -1 if the
1004 * component is not a child of this component.
1006 * @param child The child to search for.
1007 * @return Position in the list or -1 if not found.
1009 public final int getChildPosition(RocketComponent child) {
1010 return children.indexOf(child);
1014 * Get the parent component of this component. Returns <code>null</code> if the component
1017 * @return The parent of this component or <code>null</code>.
1019 public final RocketComponent getParent() {
1024 * Get the root component of the component tree.
1026 * @return The root component of the component tree.
1028 public final RocketComponent getRoot() {
1029 RocketComponent gp = this;
1030 while (gp.parent != null)
1036 * Returns the root Rocket component of this component tree. Throws an
1037 * IllegalStateException if the root component is not a Rocket.
1039 * @return The root Rocket component of the component tree.
1040 * @throws IllegalStateException If the root component is not a Rocket.
1042 public final Rocket getRocket() {
1043 RocketComponent r = getRoot();
1044 if (r instanceof Rocket)
1046 throw new IllegalStateException("getRocket() called with root component "
1047 +r.getComponentName());
1052 * Return the Stage component that this component belongs to. Throws an
1053 * IllegalStateException if a Stage is not in the parentage of this component.
1055 * @return The Stage component this component belongs to.
1056 * @throws IllegalStateException if a Stage component is not in the parentage.
1058 public final Stage getStage() {
1059 RocketComponent c = this;
1061 if (c instanceof Stage)
1065 throw new IllegalStateException("getStage() called without Stage as a parent.");
1069 * Return the stage number of the stage this component belongs to. The stages
1070 * are numbered from zero upwards.
1072 * @return the stage number this component belongs to.
1074 public final int getStageNumber() {
1075 if (parent == null) {
1076 throw new IllegalArgumentException("getStageNumber() called for root component");
1079 RocketComponent stage = this;
1080 while (!(stage instanceof Stage)) {
1081 stage = stage.parent;
1083 return stage.parent.getChildPosition(stage);
1088 * Find a component with the given ID. The component tree is searched from this component
1089 * down (including this component) for the ID and the corresponding component is returned,
1090 * or null if not found.
1092 * @param id ID to search for.
1093 * @return The component with the ID, or null if not found.
1095 public final RocketComponent findComponent(String id) {
1096 Iterator<RocketComponent> iter = this.deepIterator(true);
1097 while (iter.hasNext()) {
1098 RocketComponent c = iter.next();
1099 if (c.id.equals(id))
1106 public final RocketComponent getPreviousComponent() {
1109 int pos = parent.getChildPosition(this);
1113 RocketComponent c = parent.getChild(pos-1);
1114 while (c.getChildCount() > 0)
1115 c = c.getChild(c.getChildCount()-1);
1119 public final RocketComponent getNextComponent() {
1120 if (getChildCount() > 0)
1123 RocketComponent current = this;
1124 RocketComponent parent = this.parent;
1126 while (parent != null) {
1127 int pos = parent.getChildPosition(current);
1128 if (pos < parent.getChildCount()-1)
1129 return parent.getChild(pos+1);
1132 parent = current.parent;
1138 /////////// Event handling //////////
1140 // Listener lists are provided by the root Rocket component,
1141 // a single listener list for the whole rocket.
1145 * Adds a ComponentChangeListener to the rocket tree. The listener is added to the root
1146 * component, which must be of type Rocket (which overrides this method). Events of all
1147 * subcomponents are sent to all listeners.
1149 * @throws IllegalStateException - if the root component is not a Rocket
1151 public void addComponentChangeListener(ComponentChangeListener l) {
1152 getRocket().addComponentChangeListener(l);
1156 * Removes a ComponentChangeListener from the rocket tree. The listener is removed from
1157 * the root component, which must be of type Rocket (which overrides this method).
1159 * @param l Listener to remove
1160 * @throws IllegalStateException - if the root component is not a Rocket
1162 public void removeComponentChangeListener(ComponentChangeListener l) {
1163 getRocket().removeComponentChangeListener(l);
1168 * Adds a <code>ChangeListener</code> to the rocket tree. This is identical to
1169 * <code>addComponentChangeListener()</code> except that it uses a
1170 * <code>ChangeListener</code>. The same events are dispatched to the
1171 * <code>ChangeListener</code>, as <code>ComponentChangeEvent</code> is a subclass
1172 * of <code>ChangeEvent</code>.
1174 * @throws IllegalStateException - if the root component is not a <code>Rocket</code>
1176 public void addChangeListener(ChangeListener l) {
1177 getRocket().addChangeListener(l);
1181 * Removes a ChangeListener from the rocket tree. This is identical to
1182 * removeComponentChangeListener() except it uses a ChangeListener.
1184 * @param l Listener to remove
1185 * @throws IllegalStateException - if the root component is not a Rocket
1187 public void removeChangeListener(ChangeListener l) {
1188 getRocket().removeChangeListener(l);
1193 * Fires a ComponentChangeEvent on the rocket structure. The call is passed to the
1194 * root component, which must be of type Rocket (which overrides this method).
1195 * Events of all subcomponents are sent to all listeners.
1197 * If the component tree root is not a Rocket, the event is ignored. This is the
1198 * case when constructing components not in any Rocket tree. In this case it
1199 * would be impossible for the component to have listeners in any case.
1201 * @param e Event to send
1203 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
1205 /* Ignore if root invalid. */
1208 getRoot().fireComponentChangeEvent(e);
1213 * Fires a ComponentChangeEvent of the given type. The source of the event is set to
1216 * @param type Type of event
1217 * @see #fireComponentChangeEvent(ComponentChangeEvent)
1219 protected void fireComponentChangeEvent(int type) {
1220 fireComponentChangeEvent(new ComponentChangeEvent(this,type));
1225 /////////// Iterator implementation //////////
1228 * Private inner class to implement the Iterator.
1230 * This iterator is fail-fast if the root of the structure is a Rocket.
1232 private class RocketComponentIterator implements Iterator<RocketComponent> {
1233 // Stack holds iterators which still have some components left.
1234 private final Stack<Iterator<RocketComponent>> iteratorstack =
1235 new Stack<Iterator<RocketComponent>>();
1237 private final Rocket root;
1238 private final int treeModID;
1240 private final RocketComponent original;
1241 private boolean returnSelf=false;
1243 // Construct iterator with component's child's iterator, if it has elements
1244 public RocketComponentIterator(RocketComponent c, boolean returnSelf) {
1246 RocketComponent gp = c.getRoot();
1247 if (gp instanceof Rocket) {
1249 treeModID = root.getTreeModID();
1255 Iterator<RocketComponent> i = c.children.iterator();
1257 iteratorstack.push(i);
1260 this.returnSelf = returnSelf;
1263 public boolean hasNext() {
1267 return !iteratorstack.empty(); // Elements remain if stack is not empty
1270 public RocketComponent next() {
1271 Iterator<RocketComponent> i;
1275 // Return original component first
1281 // Peek first iterator from stack, throw exception if empty
1283 i = iteratorstack.peek();
1284 } catch (EmptyStackException e) {
1285 throw new NoSuchElementException("No further elements in " +
1286 "RocketComponent iterator");
1289 // Retrieve next component of the iterator, remove iterator from stack if empty
1290 RocketComponent c = i.next();
1292 iteratorstack.pop();
1294 // Add iterator of component children to stack if it has children
1295 i = c.children.iterator();
1297 iteratorstack.push(i);
1302 private void checkID() {
1304 if (root.getTreeModID() != treeModID) {
1305 throw new IllegalStateException("Rocket modified while being iterated");
1310 public void remove() {
1311 throw new UnsupportedOperationException("remove() not supported by " +
1312 "RocketComponent iterator");
1317 * Returns an iterator that iterates over all children and sub-children.
1319 * The iterator iterates through all children below this object, including itself if
1320 * returnSelf is true. The order of the iteration is not specified
1321 * (it may be specified in the future).
1323 * If an iterator iterating over only the direct children of the component is required,
1324 * use component.getChildren().iterator()
1326 * @param returnSelf boolean value specifying whether the component itself should be
1328 * @return An iterator for the children and sub-children.
1330 public final Iterator<RocketComponent> deepIterator(boolean returnSelf) {
1331 return new RocketComponentIterator(this,returnSelf);
1335 * Returns an iterator that iterates over all children and sub-children.
1337 * The iterator does NOT return the component itself. It is thus equivalent to
1338 * deepIterator(false).
1341 * @return An iterator for the children and sub-children.
1343 public final Iterator<RocketComponent> deepIterator() {
1344 return new RocketComponentIterator(this,false);
1349 * Return an iterator that iterates of the children of the component. The iterator
1350 * does NOT recurse to sub-children nor return itself.
1352 * @return An iterator for the children.
1354 public final Iterator<RocketComponent> iterator() {
1355 return Collections.unmodifiableList(children).iterator();
1358 //////////// Helper methods for subclasses
1361 * Helper method to add rotationally symmetric bounds at the specified coordinates.
1362 * The X-axis value is <code>x</code> and the radius at the specified position is
1365 protected static final void addBound(Collection<Coordinate> bounds, double x, double r) {
1366 bounds.add(new Coordinate(x,-r,-r));
1367 bounds.add(new Coordinate(x, r,-r));
1368 bounds.add(new Coordinate(x, r, r));
1369 bounds.add(new Coordinate(x,-r, r));
1373 protected static final Coordinate ringCG(double outerRadius, double innerRadius,
1374 double x1, double x2, double density) {
1375 return new Coordinate((x1+x2)/2, 0, 0,
1376 ringMass(outerRadius, innerRadius, x2-x1, density));
1379 protected static final double ringMass(double outerRadius, double innerRadius,
1380 double length, double density) {
1381 return Math.PI*(MathUtil.pow2(outerRadius) - MathUtil.pow2(innerRadius)) *
1385 protected static final double ringLongitudalUnitInertia(double outerRadius,
1386 double innerRadius, double length) {
1387 // 1/12 * (3 * (r1^2 + r2^2) + h^2)
1388 return (3 * (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) +
1389 MathUtil.pow2(length)) / 12;
1392 protected static final double ringRotationalUnitInertia(double outerRadius,
1393 double innerRadius) {
1394 // 1/2 * (r1^2 + r2^2)
1395 return (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius))/2;
1404 * Loads the RocketComponent fields from the given component. This method is meant
1405 * for use with the undo/redo mechanism.
1407 * The fields are copied by reference, and the supplied component must not be used
1408 * after the call, as it is in an undefined state.
1410 * TODO: MEDIUM: Make general to copy all private/protected fields...
1412 protected void copyFrom(RocketComponent src) {
1413 // Set parents and children
1415 this.children = src.children;
1416 src.children = new ArrayList<RocketComponent>();
1418 for (RocketComponent c: this.children) {
1422 // Set all parameters
1423 this.length = src.length;
1424 this.relativePosition = src.relativePosition;
1425 this.position = src.position;
1426 this.color = src.color;
1427 this.lineStyle = src.lineStyle;
1428 this.overrideMass = src.overrideMass;
1429 this.massOverriden = src.massOverriden;
1430 this.overrideCGX = src.overrideCGX;
1431 this.cgOverriden = src.cgOverriden;
1432 this.overrideSubcomponents = src.overrideSubcomponents;
1433 this.name = src.name;
1434 this.comment = src.comment;