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.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;
23 public abstract class RocketComponent implements ChangeSource, Cloneable,
24 Iterable<RocketComponent> {
27 * Text is suitable to the form
28 * Position relative to: <title>
30 public enum Position {
31 /** Position relative to the top of the parent component. */
32 TOP("Top of the parent component"),
33 /** Position relative to the middle of the parent component. */
34 MIDDLE("Middle of the parent component"),
35 /** Position relative to the bottom of the parent component. */
36 BOTTOM("Bottom of the parent component"),
37 /** Position after the parent component (for body components). */
38 AFTER("After the parent component"),
39 /** Specify an absolute X-coordinate position. */
40 ABSOLUTE("Tip of the nose cone");
43 Position(String title) {
48 public String toString() {
53 //////// Parent/child trees
55 * Parent component of the current component, or null if none exists.
57 private RocketComponent parent = null;
60 * List of child components of this component.
62 private List<RocketComponent> children = new ArrayList<RocketComponent>();
65 //////// Parameters common to all components:
68 * Characteristic length of the component. This is used in calculating the coordinate
69 * transformations and positions of other components in reference to this component.
70 * This may and should be used as the "true" length of the component, where applicable.
71 * By default it is zero, i.e. no translation.
73 protected double length = 0;
76 * Positioning of this component relative to the parent component.
78 protected Position relativePosition;
81 * Offset of the position of this component relative to the normal position given by
82 * relativePosition. By default zero, i.e. no position change.
84 protected double position = 0;
87 // Color of the component, null means to use the default color
88 private Color color = null;
89 private LineStyle lineStyle = null;
93 private double overrideMass = 0;
94 private boolean massOverriden = false;
95 private double overrideCGX = 0;
96 private boolean cgOverriden = false;
98 private boolean overrideSubcomponents = false;
101 // User-given name of the component
102 private String name = null;
104 // User-specified comment
105 private String comment = "";
107 // Unique ID of the component
108 private String id = null;
110 //// NOTE !!! All fields must be copied in the method copyFrom()! ////
115 * Default constructor. Sets the name of the component to the component's static name
116 * and the relative position of the component.
118 public RocketComponent(Position relativePosition) {
119 // These must not fire any events, due to Rocket undo system initialization
120 this.name = getComponentName();
121 this.relativePosition = relativePosition;
122 this.id = UUID.randomUUID().toString();
129 //////////// Methods that must be implemented ////////////
133 * Static component name. The name may not vary of the parameters, it must be static.
135 public abstract String getComponentName(); // Static component type name
138 * Return the component mass (regardless of mass overriding).
140 public abstract double getComponentMass(); // Mass of non-overridden component
143 * Return the component CG and mass (regardless of CG or mass overriding).
145 public abstract Coordinate getComponentCG(); // CG of non-overridden component
149 * Return the longitudal (around the y- or z-axis) unitary moment of inertia.
150 * The unitary moment of inertia is the moment of inertia with the assumption that
151 * the mass of the component is one kilogram. The inertia is measured in
152 * respect to the non-overridden CG.
154 * @return the longitudal unitary moment of inertia of this component.
156 public abstract double getLongitudalUnitInertia();
160 * Return the rotational (around the x-axis) unitary moment of inertia.
161 * The unitary moment of inertia is the moment of inertia with the assumption that
162 * the mass of the component is one kilogram. The inertia is measured in
163 * respect to the non-overridden CG.
165 * @return the rotational unitary moment of inertia of this component.
167 public abstract double getRotationalUnitInertia();
173 * Test whether the given component type can be added to this component. This type safety
174 * is enforced by the <code>addChild()</code> methods. The return value of this method
175 * may change to reflect the current state of this component (e.g. two components of some
176 * type cannot be placed as children).
178 * @param type The RocketComponent class type to add.
179 * @return Whether such a component can be added.
181 public abstract boolean isCompatible(Class<? extends RocketComponent> type);
184 /* Non-abstract helper method */
186 * Test whether the given component can be added to this component. This is equivalent
187 * to calling <code>isCompatible(c.getClass())</code>.
189 * @param c Component to test.
190 * @return Whether the component can be added.
191 * @see #isCompatible(Class)
193 public final boolean isCompatible(RocketComponent c) {
194 return isCompatible(c.getClass());
200 * Return a collection of bounding coordinates. The coordinates must be such that
201 * the component is fully enclosed in their convex hull.
203 * @return a collection of coordinates that bound the component.
205 public abstract Collection<Coordinate> getComponentBounds();
208 * Return true if the component may have an aerodynamic effect on the rocket.
210 public abstract boolean isAerodynamic();
213 * Return true if the component may have an effect on the rocket's mass.
215 public abstract boolean isMassive();
221 //////////// Methods that may be overridden ////////////
225 * Shift the coordinates in the array corresponding to radial movement. A component
226 * that has a radial position must shift the coordinates in this array suitably.
227 * If the component is clustered, then a new array must be returned with a
228 * coordinate for each cluster.
230 * The default implementation simply returns the array, and thus produces no shift.
232 * @param c an array of coordinates to shift.
233 * @return an array of shifted coordinates. The method may modify the contents
234 * of the passed array and return the array itself.
236 public Coordinate[] shiftCoordinates(Coordinate[] c) {
242 * Called when any component in the tree fires a ComponentChangeEvent. This is by
243 * default a no-op, but subclasses may override this method to e.g. invalidate
244 * cached data. The overriding method *must* call
245 * <code>super.componentChanged(e)</code> at some point.
247 * @param e The event fired
249 protected void componentChanged(ComponentChangeEvent e) {
257 * Return a descriptive name of the component.
259 * The description may include extra information about the type of component,
260 * e.g. "Conical nose cone".
262 * @return A string describing the component.
265 public final String toString() {
267 return getComponentName();
273 public final void printStructure() {
274 System.out.println("Rocket structure from '"+this.toString()+"':");
278 private void printStructure(int level) {
281 for (int i=0; i < level; i++) {
284 s += this.toString() + " (" + this.getComponentName()+")";
285 System.out.println(s);
287 for (RocketComponent c: children) {
288 c.printStructure(level+1);
294 * Make a deep copy of the rocket component tree structure from this component
295 * downwards. This method does not fire any events.
297 * This method must be overridden by any component that refers to mutable objects,
298 * or if some fields should not be copied. This should be performed by
299 * <code>RocketComponent c = super.copy();</code> and then cloning/modifying the
300 * appropriate fields.
302 * This is not performed as serializing/deserializing for performance reasons.
304 * @return A deep copy of the structure.
306 public RocketComponent copy() {
307 RocketComponent clone;
309 clone = (RocketComponent)this.clone();
310 } catch (CloneNotSupportedException e) {
311 throw new BugException("CloneNotSupportedException encountered, " +
315 // Reset all parent/child information
317 clone.children = new ArrayList<RocketComponent>();
319 // Add copied children to the structure without firing events.
320 for (RocketComponent child: this.children) {
321 RocketComponent childCopy = child.copy();
322 // Don't use add method since it fires events
323 clone.children.add(childCopy);
324 childCopy.parent = clone;
331 ////////////// Methods that may not be overridden ////////////
335 ////////// Common parameter setting/getting //////////
338 * Return the color of the object to use in 2D figures, or <code>null</code>
339 * to use the default color.
341 public final Color getColor() {
346 * Set the color of the object to use in 2D figures.
348 public final void setColor(Color c) {
349 if ((color == null && c == null) ||
350 (color != null && color.equals(c)))
354 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
358 public final LineStyle getLineStyle() {
362 public final void setLineStyle(LineStyle style) {
363 if (this.lineStyle == style)
365 this.lineStyle = style;
366 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
373 * Get the current override mass. The mass is not necessarily in use
376 * @return the override mass
378 public final double getOverrideMass() {
383 * Set the current override mass. The mass is not set to use by this
386 * @param m the override mass
388 public final void setOverrideMass(double m) {
389 overrideMass = Math.max(m,0);
391 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
395 * Return whether mass override is active for this component. This does NOT
396 * take into account whether a parent component is overriding the mass.
398 * @return whether the mass is overridden
400 public final boolean isMassOverridden() {
401 return massOverriden;
405 * Set whether the mass is currently overridden.
407 * @param o whether the mass is overridden
409 public final void setMassOverridden(boolean o) {
410 if (massOverriden != o) {
412 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
421 * Return the current override CG. The CG is not necessarily overridden.
423 * @return the override CG
425 public final Coordinate getOverrideCG() {
426 return getComponentCG().setX(overrideCGX);
430 * Return the x-coordinate of the current override CG.
432 * @return the x-coordinate of the override CG.
434 public final double getOverrideCGX() {
439 * Set the current override CG to (x,0,0).
441 * @param x the x-coordinate of the override CG to set.
443 public final void setOverrideCGX(double x) {
444 if (MathUtil.equals(overrideCGX, x))
446 this.overrideCGX = x;
447 if (isCGOverridden())
448 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
450 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
454 * Return whether the CG is currently overridden.
456 * @return whether the CG is overridden
458 public final boolean isCGOverridden() {
463 * Set whether the CG is currently overridden.
465 * @param o whether the CG is overridden
467 public final void setCGOverridden(boolean o) {
468 if (cgOverriden != o) {
470 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
477 * Return whether the mass and/or CG override overrides all subcomponent values
478 * as well. The default implementation is a normal getter/setter implementation,
479 * however, subclasses are allowed to override this behavior if some subclass
480 * always or never overrides subcomponents. In this case the subclass should
481 * also override {@link #isOverrideSubcomponentsEnabled()} to return
482 * <code>false</code>.
484 * @return whether the current mass and/or CG override overrides subcomponents as well.
486 public boolean getOverrideSubcomponents() {
487 return overrideSubcomponents;
492 * Set whether the mass and/or CG override overrides all subcomponent values
493 * as well. See {@link #getOverrideSubcomponents()} for details.
495 * @param override whether the mass and/or CG override overrides all subcomponent.
497 public void setOverrideSubcomponents(boolean override) {
498 if (overrideSubcomponents != override) {
499 overrideSubcomponents = override;
500 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
505 * Return whether the option to override all subcomponents is enabled or not.
506 * The default implementation returns <code>false</code> if neither mass nor
507 * CG is overridden, <code>true</code> otherwise.
509 * This method may be overridden if the setting of overriding subcomponents
512 * @return whether the option to override subcomponents is currently enabled.
514 public boolean isOverrideSubcomponentsEnabled() {
515 return isCGOverridden() || isMassOverridden();
522 * Get the user-defined name of the component.
524 public final String getName() {
529 * Set the user-defined name of the component. If name==null, sets the name to
530 * the default name, currently the component name.
532 public final void setName(String name) {
533 // System.out.println("Set name called:"+name+" orig:"+this.name);
534 if (name==null || name.matches("^\\s*$"))
535 this.name = getComponentName();
538 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
543 * Return the comment of the component. The component may contain multiple lines
544 * using \n as a newline separator.
546 * @return the comment of the component.
548 public final String getComment() {
553 * Set the comment of the component.
555 * @param comment the comment of the component.
557 public final void setComment(String comment) {
558 if (this.comment.equals(comment))
563 this.comment = comment;
564 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
570 * Returns the unique ID of the component.
572 * @return the ID of the component.
574 public final String getID() {
580 * Set the unique ID of the component. If <code>id</code> in <code>null</code> then
581 * this method generates a new unique ID for the component.
583 * This method should be used only in special cases, such as when creating database
584 * entries with empty IDs.
586 * @param id the ID to set.
588 public final void setID(String id) {
590 this.id = UUID.randomUUID().toString();
594 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
601 * Get the characteristic length of the component, for example the length of a body tube
602 * of the length of the root chord of a fin. This is used in positioning the component
603 * relative to its parent.
605 * If the length of a component is settable, the class must define the setter method
608 public final double getLength() {
613 * Get the positioning of the component relative to its parent component.
614 * This is one of the enums of {@link Position}. A setter method is not provided,
615 * but can be provided by a subclass.
617 public final Position getRelativePosition() {
618 return relativePosition;
623 * Set the positioning of the component relative to its parent component.
624 * The actual position of the component is maintained to the best ability.
626 * The default implementation is of protected visibility, since many components
627 * do not support setting the relative position. A component that does support
628 * it should override this with a public method that simply calls this
629 * supermethod AND fire a suitable ComponentChangeEvent.
631 * @param position the relative positioning.
633 protected void setRelativePosition(RocketComponent.Position position) {
634 if (this.relativePosition == position)
637 // Update position so as not to move the component
638 if (this.parent != null) {
639 double thisPos = this.toRelative(Coordinate.NUL,this.parent)[0].x;
643 this.position = this.toAbsolute(Coordinate.NUL)[0].x;
647 this.position = thisPos;
651 this.position = thisPos - (this.parent.length - this.length)/2;
655 this.position = thisPos - (this.parent.length - this.length);
659 assert(false): "Should not occur";
663 this.relativePosition = position;
664 fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE);
671 * Get the position value of the component. The exact meaning of the value is
672 * dependent on the current relative positioning.
674 * @return the positional value.
676 public final double getPositionValue() {
682 * Set the position value of the component. The exact meaning of the value
683 * depends on the current relative positioning.
685 * The default implementation is of protected visibility, since many components
686 * do not support setting the relative position. A component that does support
687 * it should override this with a public method that simply calls this
688 * supermethod AND fire a suitable ComponentChangeEvent.
690 * @param value the position value of the component.
692 public void setPositionValue(double value) {
693 if (MathUtil.equals(this.position, value))
695 this.position = value;
700 /////////// Coordinate changes ///////////
703 * Returns coordinate c in absolute coordinates. Equivalent to toComponent(c,null).
705 public Coordinate[] toAbsolute(Coordinate c) {
706 return toRelative(c,null);
711 * Return coordinate <code>c</code> described in the coordinate system of
712 * <code>dest</code>. If <code>dest</code> is <code>null</code> returns
713 * absolute coordinates.
715 * This method returns an array of coordinates, each of which represents a
716 * position of the coordinate in clustered cases. The array is guaranteed
717 * to contain at least one element.
719 * The current implementation does not support rotating components.
721 * @param c Coordinate in the component's coordinate system.
722 * @param dest Destination component coordinate system.
723 * @return an array of coordinates describing <code>c</code> in coordinates
724 * relative to <code>dest</code>.
726 public final Coordinate[] toRelative(Coordinate c, RocketComponent dest) {
727 double absoluteX = Double.NaN;
728 RocketComponent search = dest;
729 Coordinate[] array = new Coordinate[1];
732 RocketComponent component = this;
733 while ((component != search) && (component.parent != null)) {
735 array = component.shiftCoordinates(array);
737 switch (component.relativePosition) {
739 for (int i=0; i < array.length; i++) {
740 array[i] = array[i].add(component.position,0,0);
745 for (int i=0; i < array.length; i++) {
746 array[i] = array[i].add(component.position +
747 (component.parent.length-component.length)/2,0,0);
752 for (int i=0; i < array.length; i++) {
753 array[i] = array[i].add(component.position +
754 (component.parent.length-component.length),0,0);
759 // Add length of all previous brother-components with POSITION_RELATIVE_AFTER
760 int index = component.parent.children.indexOf(component);
762 for (index--; index >= 0; index--) {
763 RocketComponent comp = component.parent.children.get(index);
764 double length = comp.getTotalLength();
765 for (int i=0; i < array.length; i++) {
766 array[i] = array[i].add(length,0,0);
769 for (int i=0; i < array.length; i++) {
770 array[i] = array[i].add(component.position + component.parent.length,0,0);
775 search = null; // Requires back-search if dest!=null
776 if (Double.isNaN(absoluteX)) {
777 absoluteX = component.position;
782 throw new BugException("Unknown relative positioning type of component"+
783 component+": "+component.relativePosition);
786 component = component.parent; // parent != null
789 if (!Double.isNaN(absoluteX)) {
790 for (int i=0; i < array.length; i++) {
791 array[i] = array[i].setX(absoluteX + c.x);
795 // Check whether destination has been found or whether to backtrack
796 // TODO: LOW: Backtracking into clustered components uses only one component
797 if ((dest != null) && (component != dest)) {
798 Coordinate[] origin = dest.toAbsolute(Coordinate.NUL);
799 for (int i=0; i < array.length; i++) {
800 array[i] = array[i].sub(origin[0]);
809 * Recursively sum the lengths of all subcomponents that have position
812 * @return Sum of the lengths.
814 private final double getTotalLength() {
816 if (relativePosition == Position.AFTER)
818 for (int i=0; i<children.size(); i++)
819 l += children.get(i).getTotalLength();
825 /////////// Total mass and CG calculation ////////////
828 * Return the (possibly overridden) mass of component.
830 * @return The mass of the component or the given override mass.
832 public final double getMass() {
835 return getComponentMass();
839 * Return the (possibly overridden) center of gravity and mass.
841 * Returns the CG with the weight of the coordinate set to the weight of the component.
842 * Both CG and mass may be separately overridden.
844 * @return The CG of the component or the given override CG.
846 public final Coordinate getCG() {
848 return getOverrideCG().setWeight(getMass());
851 return getComponentCG().setWeight(getMass());
853 return getComponentCG();
858 * Return the longitudal (around the y- or z-axis) moment of inertia of this component.
859 * The moment of inertia is scaled in reference to the (possibly overridden) mass
860 * and is relative to the non-overridden CG.
862 * @return the longitudal moment of inertia of this component.
864 public final double getLongitudalInertia() {
865 return getLongitudalUnitInertia() * getMass();
869 * Return the rotational (around the y- or z-axis) moment of inertia of this component.
870 * The moment of inertia is scaled in reference to the (possibly overridden) mass
871 * and is relative to the non-overridden CG.
873 * @return the rotational moment of inertia of this component.
875 public final double getRotationalInertia() {
876 return getRotationalUnitInertia() * getMass();
881 /////////// Children handling ///////////
885 * Adds a child to the rocket component tree. The component is added to the end
886 * of the component's child list. This is a helper method that calls
887 * {@link #addChild(RocketComponent,int)}.
889 * @param component The component to add.
890 * @throws IllegalArgumentException if the component is already part of some
892 * @see #addChild(RocketComponent,int)
894 public final void addChild(RocketComponent component) {
895 addChild(component,children.size());
900 * Adds a child to the rocket component tree. The component is added to
901 * the given position of the component's child list.
903 * This method may be overridden to enforce more strict component addition rules.
904 * The tests should be performed first and then this method called.
906 * @param component The component to add.
907 * @param position Position to add component to.
908 * @throws IllegalArgumentException If the component is already part of
909 * some component tree.
911 public void addChild(RocketComponent component, int position) {
912 if (component.parent != null) {
913 throw new IllegalArgumentException("component "+component.getComponentName()+
914 " is already in a tree");
916 if (!isCompatible(component)) {
917 throw new IllegalStateException("Component "+component.getComponentName()+
918 " not currently compatible with component "+getComponentName());
921 children.add(position,component);
922 component.parent = this;
924 fireAddRemoveEvent(component);
929 * Removes a child from the rocket component tree.
931 * @param n remove the n'th child.
932 * @throws IndexOutOfBoundsException if n is out of bounds
934 public final void removeChild(int n) {
935 RocketComponent component = children.remove(n);
936 component.parent = null;
937 fireAddRemoveEvent(component);
941 * Removes a child from the rocket component tree. Does nothing if the component
942 * is not present as a child.
944 * @param component the component to remove
946 public final void removeChild(RocketComponent component) {
947 if (children.remove(component)) {
948 component.parent = null;
950 fireAddRemoveEvent(component);
958 * Move a child to another position.
960 * @param component the component to move
961 * @param position the component's new position
962 * @throws IllegalArgumentException If an illegal placement was attempted.
964 public final void moveChild(RocketComponent component, int position) {
965 if (children.remove(component)) {
966 children.add(position, component);
967 fireAddRemoveEvent(component);
973 * Fires an AERODYNAMIC_CHANGE, MASS_CHANGE or OTHER_CHANGE event depending on the
974 * type of component removed.
976 private void fireAddRemoveEvent(RocketComponent component) {
977 Iterator<RocketComponent> iter = component.deepIterator(true);
978 int type = ComponentChangeEvent.TREE_CHANGE;
979 while (iter.hasNext()) {
980 RocketComponent c = iter.next();
981 if (c.isAerodynamic())
982 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
984 type |= ComponentChangeEvent.MASS_CHANGE;
987 fireComponentChangeEvent(type);
991 public final int getChildCount() {
992 return children.size();
995 public final RocketComponent getChild(int n) {
996 return children.get(n);
999 public final RocketComponent[] getChildren() {
1000 return children.toArray(new RocketComponent[0]);
1005 * Returns the position of the child in this components child list, or -1 if the
1006 * component is not a child of this component.
1008 * @param child The child to search for.
1009 * @return Position in the list or -1 if not found.
1011 public final int getChildPosition(RocketComponent child) {
1012 return children.indexOf(child);
1016 * Get the parent component of this component. Returns <code>null</code> if the component
1019 * @return The parent of this component or <code>null</code>.
1021 public final RocketComponent getParent() {
1026 * Get the root component of the component tree.
1028 * @return The root component of the component tree.
1030 public final RocketComponent getRoot() {
1031 RocketComponent gp = this;
1032 while (gp.parent != null)
1038 * Returns the root Rocket component of this component tree. Throws an
1039 * IllegalStateException if the root component is not a Rocket.
1041 * @return The root Rocket component of the component tree.
1042 * @throws IllegalStateException If the root component is not a Rocket.
1044 public final Rocket getRocket() {
1045 RocketComponent r = getRoot();
1046 if (r instanceof Rocket)
1048 throw new IllegalStateException("getRocket() called with root component "
1049 +r.getComponentName());
1054 * Return the Stage component that this component belongs to. Throws an
1055 * IllegalStateException if a Stage is not in the parentage of this component.
1057 * @return The Stage component this component belongs to.
1058 * @throws IllegalStateException if a Stage component is not in the parentage.
1060 public final Stage getStage() {
1061 RocketComponent c = this;
1063 if (c instanceof Stage)
1067 throw new IllegalStateException("getStage() called without Stage as a parent.");
1071 * Return the stage number of the stage this component belongs to. The stages
1072 * are numbered from zero upwards.
1074 * @return the stage number this component belongs to.
1076 public final int getStageNumber() {
1077 if (parent == null) {
1078 throw new IllegalArgumentException("getStageNumber() called for root component");
1081 RocketComponent stage = this;
1082 while (!(stage instanceof Stage)) {
1083 stage = stage.parent;
1084 if (stage == null || stage.parent == null) {
1085 throw new IllegalStateException("getStageNumber() could not find parent " +
1089 return stage.parent.getChildPosition(stage);
1094 * Find a component with the given ID. The component tree is searched from this component
1095 * down (including this component) for the ID and the corresponding component is returned,
1096 * or null if not found.
1098 * @param id ID to search for.
1099 * @return The component with the ID, or null if not found.
1101 public final RocketComponent findComponent(String id) {
1102 Iterator<RocketComponent> iter = this.deepIterator(true);
1103 while (iter.hasNext()) {
1104 RocketComponent c = iter.next();
1105 if (c.id.equals(id))
1112 public final RocketComponent getPreviousComponent() {
1115 int pos = parent.getChildPosition(this);
1117 StringBuffer sb = new StringBuffer();
1118 sb.append("Inconsistent internal state: ");
1119 sb.append("this=").append(this).append('[').append(System.identityHashCode(this)).append(']');
1120 sb.append(" parent.children=[");
1121 for (int i=0; i < parent.children.size(); i++) {
1122 RocketComponent c = parent.children.get(i);
1123 sb.append(c).append('[').append(System.identityHashCode(c)).append(']');
1124 if (i < parent.children.size()-1)
1127 throw new IllegalStateException(sb.toString());
1132 RocketComponent c = parent.getChild(pos-1);
1133 while (c.getChildCount() > 0)
1134 c = c.getChild(c.getChildCount()-1);
1138 public final RocketComponent getNextComponent() {
1139 if (getChildCount() > 0)
1142 RocketComponent current = this;
1143 RocketComponent parent = this.parent;
1145 while (parent != null) {
1146 int pos = parent.getChildPosition(current);
1147 if (pos < parent.getChildCount()-1)
1148 return parent.getChild(pos+1);
1151 parent = current.parent;
1157 /////////// Event handling //////////
1159 // Listener lists are provided by the root Rocket component,
1160 // a single listener list for the whole rocket.
1164 * Adds a ComponentChangeListener to the rocket tree. The listener is added to the root
1165 * component, which must be of type Rocket (which overrides this method). Events of all
1166 * subcomponents are sent to all listeners.
1168 * @throws IllegalStateException - if the root component is not a Rocket
1170 public void addComponentChangeListener(ComponentChangeListener l) {
1171 getRocket().addComponentChangeListener(l);
1175 * Removes a ComponentChangeListener from the rocket tree. The listener is removed from
1176 * the root component, which must be of type Rocket (which overrides this method).
1178 * @param l Listener to remove
1179 * @throws IllegalStateException - if the root component is not a Rocket
1181 public void removeComponentChangeListener(ComponentChangeListener l) {
1182 getRocket().removeComponentChangeListener(l);
1187 * Adds a <code>ChangeListener</code> to the rocket tree. This is identical to
1188 * <code>addComponentChangeListener()</code> except that it uses a
1189 * <code>ChangeListener</code>. The same events are dispatched to the
1190 * <code>ChangeListener</code>, as <code>ComponentChangeEvent</code> is a subclass
1191 * of <code>ChangeEvent</code>.
1193 * @throws IllegalStateException - if the root component is not a <code>Rocket</code>
1195 public void addChangeListener(ChangeListener l) {
1196 getRocket().addChangeListener(l);
1200 * Removes a ChangeListener from the rocket tree. This is identical to
1201 * removeComponentChangeListener() except it uses a ChangeListener.
1203 * @param l Listener to remove
1204 * @throws IllegalStateException - if the root component is not a Rocket
1206 public void removeChangeListener(ChangeListener l) {
1207 getRocket().removeChangeListener(l);
1212 * Fires a ComponentChangeEvent on the rocket structure. The call is passed to the
1213 * root component, which must be of type Rocket (which overrides this method).
1214 * Events of all subcomponents are sent to all listeners.
1216 * If the component tree root is not a Rocket, the event is ignored. This is the
1217 * case when constructing components not in any Rocket tree. In this case it
1218 * would be impossible for the component to have listeners in any case.
1220 * @param e Event to send
1222 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
1224 /* Ignore if root invalid. */
1227 getRoot().fireComponentChangeEvent(e);
1232 * Fires a ComponentChangeEvent of the given type. The source of the event is set to
1235 * @param type Type of event
1236 * @see #fireComponentChangeEvent(ComponentChangeEvent)
1238 protected void fireComponentChangeEvent(int type) {
1239 fireComponentChangeEvent(new ComponentChangeEvent(this,type));
1244 /////////// Iterator implementation //////////
1247 * Private inner class to implement the Iterator.
1249 * This iterator is fail-fast if the root of the structure is a Rocket.
1251 private class RocketComponentIterator implements Iterator<RocketComponent> {
1252 // Stack holds iterators which still have some components left.
1253 private final Stack<Iterator<RocketComponent>> iteratorstack =
1254 new Stack<Iterator<RocketComponent>>();
1256 private final Rocket root;
1257 private final int treeModID;
1259 private final RocketComponent original;
1260 private boolean returnSelf=false;
1262 // Construct iterator with component's child's iterator, if it has elements
1263 public RocketComponentIterator(RocketComponent c, boolean returnSelf) {
1265 RocketComponent gp = c.getRoot();
1266 if (gp instanceof Rocket) {
1268 treeModID = root.getTreeModID();
1274 Iterator<RocketComponent> i = c.children.iterator();
1276 iteratorstack.push(i);
1279 this.returnSelf = returnSelf;
1282 public boolean hasNext() {
1286 return !iteratorstack.empty(); // Elements remain if stack is not empty
1289 public RocketComponent next() {
1290 Iterator<RocketComponent> i;
1294 // Return original component first
1300 // Peek first iterator from stack, throw exception if empty
1302 i = iteratorstack.peek();
1303 } catch (EmptyStackException e) {
1304 throw new NoSuchElementException("No further elements in " +
1305 "RocketComponent iterator");
1308 // Retrieve next component of the iterator, remove iterator from stack if empty
1309 RocketComponent c = i.next();
1311 iteratorstack.pop();
1313 // Add iterator of component children to stack if it has children
1314 i = c.children.iterator();
1316 iteratorstack.push(i);
1321 private void checkID() {
1323 if (root.getTreeModID() != treeModID) {
1324 throw new IllegalStateException("Rocket modified while being iterated");
1329 public void remove() {
1330 throw new UnsupportedOperationException("remove() not supported by " +
1331 "RocketComponent iterator");
1336 * Returns an iterator that iterates over all children and sub-children.
1338 * The iterator iterates through all children below this object, including itself if
1339 * returnSelf is true. The order of the iteration is not specified
1340 * (it may be specified in the future).
1342 * If an iterator iterating over only the direct children of the component is required,
1343 * use component.getChildren().iterator()
1345 * @param returnSelf boolean value specifying whether the component itself should be
1347 * @return An iterator for the children and sub-children.
1349 public final Iterator<RocketComponent> deepIterator(boolean returnSelf) {
1350 return new RocketComponentIterator(this,returnSelf);
1354 * Returns an iterator that iterates over all children and sub-children.
1356 * The iterator does NOT return the component itself. It is thus equivalent to
1357 * deepIterator(false).
1360 * @return An iterator for the children and sub-children.
1362 public final Iterator<RocketComponent> deepIterator() {
1363 return new RocketComponentIterator(this,false);
1368 * Return an iterator that iterates of the children of the component. The iterator
1369 * does NOT recurse to sub-children nor return itself.
1371 * @return An iterator for the children.
1373 public final Iterator<RocketComponent> iterator() {
1374 return Collections.unmodifiableList(children).iterator();
1377 //////////// Helper methods for subclasses
1380 * Helper method to add rotationally symmetric bounds at the specified coordinates.
1381 * The X-axis value is <code>x</code> and the radius at the specified position is
1384 protected static final void addBound(Collection<Coordinate> bounds, double x, double r) {
1385 bounds.add(new Coordinate(x,-r,-r));
1386 bounds.add(new Coordinate(x, r,-r));
1387 bounds.add(new Coordinate(x, r, r));
1388 bounds.add(new Coordinate(x,-r, r));
1392 protected static final Coordinate ringCG(double outerRadius, double innerRadius,
1393 double x1, double x2, double density) {
1394 return new Coordinate((x1+x2)/2, 0, 0,
1395 ringMass(outerRadius, innerRadius, x2-x1, density));
1398 protected static final double ringMass(double outerRadius, double innerRadius,
1399 double length, double density) {
1400 return Math.PI*(MathUtil.pow2(outerRadius) - MathUtil.pow2(innerRadius)) *
1404 protected static final double ringLongitudalUnitInertia(double outerRadius,
1405 double innerRadius, double length) {
1406 // 1/12 * (3 * (r1^2 + r2^2) + h^2)
1407 return (3 * (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) +
1408 MathUtil.pow2(length)) / 12;
1411 protected static final double ringRotationalUnitInertia(double outerRadius,
1412 double innerRadius) {
1413 // 1/2 * (r1^2 + r2^2)
1414 return (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius))/2;
1423 * Loads the RocketComponent fields from the given component. This method is meant
1424 * for in-place replacement of a component. It is used with the undo/redo
1425 * mechanism and when converting a finset into a freeform fin set.
1426 * This component must not have a parent, otherwise this method will fail.
1428 * The fields are copied by reference, and the supplied component must not be used
1429 * after the call, as it is in an undefined state.
1431 * TODO: MEDIUM: Make general to copy all private/protected fields...
1433 protected void copyFrom(RocketComponent src) {
1435 if (this.parent != null) {
1436 throw new UnsupportedOperationException("copyFrom called for non-root component "
1440 // Set parents and children
1441 this.children = src.children;
1442 src.children = new ArrayList<RocketComponent>();
1444 for (RocketComponent c: this.children) {
1448 // Set all parameters
1449 this.length = src.length;
1450 this.relativePosition = src.relativePosition;
1451 this.position = src.position;
1452 this.color = src.color;
1453 this.lineStyle = src.lineStyle;
1454 this.overrideMass = src.overrideMass;
1455 this.massOverriden = src.massOverriden;
1456 this.overrideCGX = src.overrideCGX;
1457 this.cgOverriden = src.cgOverriden;
1458 this.overrideSubcomponents = src.overrideSubcomponents;
1459 this.name = src.name;
1460 this.comment = src.comment;