]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipeControlPoint.java
Let root node determine up direction for rotation angle calculations
[simantics/3d.git] / org.simantics.plant3d / src / org / simantics / plant3d / scenegraph / controlpoint / PipeControlPoint.java
1 package org.simantics.plant3d.scenegraph.controlpoint;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Collection;
6 import java.util.List;
7
8 import javax.vecmath.AxisAngle4d;
9 import javax.vecmath.Matrix3d;
10 import javax.vecmath.Point3d;
11 import javax.vecmath.Quat4d;
12 import javax.vecmath.Tuple3d;
13 import javax.vecmath.Vector3d;
14
15 import org.simantics.g3d.math.MathTools;
16 import org.simantics.g3d.property.annotations.GetPropertyValue;
17 import org.simantics.g3d.scenegraph.G3DNode;
18 import org.simantics.g3d.scenegraph.base.INode;
19 import org.simantics.plant3d.scenegraph.IP3DNode;
20 import org.simantics.plant3d.scenegraph.Nozzle;
21 import org.simantics.plant3d.scenegraph.P3DRootNode;
22 import org.simantics.plant3d.scenegraph.PipeRun;
23 import org.simantics.plant3d.scenegraph.PipelineComponent;
24
25 import vtk.vtkRenderer;
26
27
28 public class PipeControlPoint extends G3DNode implements IP3DNode {
29
30         private static boolean DEBUG = false;
31
32         public enum PointType{INLINE,TURN,END};
33         public enum Direction{NEXT,PREVIOUS};
34         public enum PositionType {SPLIT,NEXT,PREVIOUS,PORT}
35
36         private PipelineComponent component;
37
38         private PointType type;
39         private boolean isFixed = true;        // In-line: fixed-length Turn: fixed-angle
40         private boolean isMod = false;         // Can user modify fixed value manually 
41         private boolean isRotate = false;      // rotates around path leg axis.
42         private boolean isReverse = false;     // definition direction can be swapped
43         private boolean isDeletable = true;    // can be removed by rules
44         private boolean isSizeChange = false;  // changes size of the pipe. The next control point / component is on different PipeRun
45         private boolean isSub = false;         // child point for offset / size change
46
47         private boolean disposed = false;
48         
49         public PipeControlPoint(PipelineComponent component) {
50                 this.component = component;
51                 if (component.getPipeRun() != null)
52                         component.getPipeRun().addChild(this);
53
54         }
55
56         public PipeControlPoint(PipelineComponent component, PipeRun piperun) {
57                 this.component = component;
58                 piperun.addChild(this);
59         }
60
61         @Override
62         public void update(vtkRenderer ren) {
63                 try {
64                         PipingRules.requestUpdate(this);
65                 } catch (Exception e) {
66                         e.printStackTrace();
67                 }
68
69         }
70
71         public PipeRun getPipeRun() {
72                 return (PipeRun)getParent();
73         }
74
75         public PipelineComponent getPipelineComponent() {
76                 return component;
77         }
78
79         public PointType getType() {
80                 return type;
81         }
82
83         public void setType(PointType type) {
84                 this.type = type;
85         }
86
87         @GetPropertyValue(name="Fixed",tabId="Debug",value="fixed")
88         public boolean isFixed() {
89                 return isFixed;
90         }
91
92         public void setFixed(boolean fixed) {
93                 this.isFixed = fixed;
94         }
95         
96         @GetPropertyValue(name="Mod",tabId="Debug",value="mod")
97         public boolean isMod() {
98         return isMod;
99     }
100     
101     public void setMod(boolean isMod) {
102         this.isMod = isMod;
103     }
104
105         @GetPropertyValue(name="Rotate",tabId="Debug",value="rotate")
106         public boolean isRotate() {
107                 return isRotate;
108         }
109
110         public void setRotate(boolean rotate) {
111                 this.isRotate = rotate;
112         }
113
114         @GetPropertyValue(name="Reverse",tabId="Debug",value="reverse")
115         public boolean isReverse() {
116                 return isReverse;
117         }
118
119         public void setReverse(boolean reverse) {
120                 this.isReverse = reverse;
121         }
122
123         public void setSub(boolean sub) {
124                 this.isSub = sub;
125         }
126
127         @GetPropertyValue(name="Deletable",tabId="Debug",value="deletable")
128         public boolean isDeletable() {
129                 return isDeletable;
130         }
131
132         public void setDeletable(boolean deletable) {
133                 this.isDeletable = deletable;
134         }
135
136         public boolean isPathLegEnd() {
137                 return type != PointType.INLINE;
138         }
139
140         public boolean isEnd() {
141                 return type == PointType.END;
142         }
143
144         public boolean isTurn() {
145                 return type == PointType.TURN;
146         }
147
148         public boolean isInline() {
149                 return type == PointType.INLINE;
150         }
151         
152         public boolean asPathLegEnd() {
153             // Ends and Turns are path leg ends by default, but also unconnected inline are path leg ends.
154             return isPathLegEnd() || getNext() == null || getPrevious() == null;
155         }
156
157         /**
158          * True for end components, if control point defines absolute position direction, which rules cannot modify. 
159          * This is typical for nozzles.
160          * @return
161          */
162         public boolean isDirected() {
163                 return isFixed && isEnd();
164         }
165
166         /**
167      * True for end components, if control is opposite to directed, and rules can modify position and orientation.
168      * This is typical for caps, and other end components.
169      * @return
170      */
171         public boolean isNonDirected() {
172                 return !isFixed && isEnd();
173         }
174
175         public boolean isVariableLength() {
176                 return !isFixed && isInline();
177         }
178         
179         /**
180          * Fixed length in-line component is such that piping rules cannot modify the length.
181          * @return
182          */
183         public boolean isFixedLength() {
184         return isFixed && isInline();
185     }
186
187         public boolean isVariableAngle() {
188                 return !isFixed && isTurn();
189         }
190         
191         /**
192          * Fixed angle turn component is such that piping rules cannot modify the angle.
193          * @return
194          */
195         public boolean isFixedAngle() {
196         return isFixed && isTurn();
197     }
198         
199         /**
200          * Does the turn behave like fixed angle?
201          * For variable angle turns, the turn angle is defined by connected components, and without them, we must handle the component as fixed angle. 
202          * @return
203          */
204         public boolean asFixedAngle() {
205         return isTurn() && (isFixed || next == null || previous == null);
206     }
207
208         public boolean isBranchEnd() {
209                 return isDeletable && isEnd();
210         }
211
212         public boolean isOffset() {
213                 return offset != null;
214         }
215
216         public boolean isDualSub() {
217                 return parent != null && isSub;
218         }
219
220         public boolean isDualInline() {
221                 return children.size() == 1 && children.get(0).isDualSub();
222         }
223
224         public boolean isAxial() {
225                 return isInline() && !isDualInline();
226         }
227
228         public boolean isSizeChange() {
229                 return isSizeChange;
230                 //              if (children.size() == 0)
231                 //                      return false;
232                 //              if (!isDualInline())
233                 //                      return false;
234                 //              return getPipeRun() != children.get(0).getPipeRun();
235         }
236
237         public void setSizeChange(boolean isSizeChange) {
238                 this.isSizeChange = isSizeChange;
239         }
240
241
242         private PipeControlPoint next;
243         private PipeControlPoint previous;
244
245         public PipeControlPoint getNext() {
246                 return next;
247         }
248
249         public PipeControlPoint getPrevious() {
250                 return previous;
251         }
252
253         public void setNext(PipeControlPoint next) {
254             if (isSub) {
255                 getParentPoint().setNext(next);
256                 return;
257             }
258             if (next != null && next.isDualSub())
259                 next = next.parent;
260             if (_setNext(next)) {
261                 for (PipeControlPoint pcp : children) {
262                 if (pcp.isSub)
263                     pcp._setNext(next);
264             }
265                 updateSubPoint();
266             }
267         }
268         
269         public void setPrevious(PipeControlPoint prev) {
270         if (isSub) {
271             getParentPoint().setPrevious(prev);
272             return;
273         }
274         if (prev != null && prev.isDualInline())
275             prev = prev.children.get(0);
276         if (_setPrevious(prev)) {
277             for (PipeControlPoint pcp : children) {
278                 if (pcp.isSub)
279                     pcp._setPrevious(prev);
280             }
281             updateSubPoint();
282         }
283     }
284         
285         protected boolean _setNext(PipeControlPoint next) {
286                 if (isEnd() && previous != null && next != null)
287                         throw new RuntimeException("End control points are allowed to have only one connection");
288                 if (next == this)
289                         throw new RuntimeException("Cannot connect to self");
290                 if (this.next == next)
291                         return false;
292                 if (DEBUG) System.out.println(this + " next " + next);
293                 if (next == null && isVariableAngle() && previous != null && !isRemoved()) {
294                     convertVariableAngleToFixed(Direction.NEXT);
295                 }
296                 this.next = next;
297                 if (component != null) {
298                         if (parent == null || isSub)
299                                 component.setNext(next != null ? next.component : null);
300                         else
301                                 component.setBranch0(next != null ? next.component : null);
302                         
303                 }
304                 return true;
305         }
306
307         protected boolean _setPrevious(PipeControlPoint previous) {
308                 if (isEnd() && next != null && previous != null)
309                         throw new RuntimeException("End control points are allowed to have only one connection");
310                 if (previous == this)
311                         throw new RuntimeException("Cannot connect to self");
312                 if (this.previous == previous)
313                         return false;
314                 if (DEBUG) System.out.println(this + " previous " + previous);
315                 if (previous == null && isVariableAngle() && next != null && !isRemoved()) {
316             convertVariableAngleToFixed(Direction.PREVIOUS);
317         }
318                 this.previous = previous;
319                 if (component != null) {
320                         if (parent == null || isSub)
321                                 component.setPrevious(previous != null ? previous.component : null);
322                         else
323                                 component.setBranch0(previous != null ? previous.component : null);
324                         updateSubPoint();
325                 }
326                 return true;
327         }
328         
329         private void convertVariableAngleToFixed(Direction direction) {
330             // We are removing reference, which transforms variable angle to fixed angle.
331         // Since fixed angle is defined differently, we need to calculate fixed angle parameters based on current data
332         // We need to calculate turnAngle and rotationAngle
333             Vector3d dirOut = getPathLegDirection(direction == Direction.NEXT ? Direction.NEXT : Direction.PREVIOUS);
334         Vector3d dir = getPathLegDirection(direction == Direction.NEXT ? Direction.PREVIOUS : Direction.NEXT);
335         if (dir == null || dirOut == null)
336             return;
337         dir.negate();
338         double angle = dir.angle(dirOut);
339         //super._setNext(null);
340         if (direction == Direction.NEXT)
341             next = null;
342         else
343             previous = null;
344         setRotationAngle(0.0);
345         setReversed(direction == Direction.NEXT ? false : true);
346         Vector3d dirOutN = getPathLegDirection(direction == Direction.NEXT ? Direction.NEXT : Direction.PREVIOUS);
347         dirOutN.normalize();
348         AxisAngle4d aa = new AxisAngle4d();
349         if (MathTools.createRotation(dirOutN, dirOut, dir, aa)) {
350             setRotationAngle(aa.angle);
351             setTurnAngle(angle);
352             if (DEBUG) System.out.println("convertToFixed " + dir + " " + dirOut + " " +dirOutN + " " +angle + " "+ aa.angle);
353         }
354         }
355
356         public PipeControlPoint parent;
357         public List<PipeControlPoint> children = new ArrayList<PipeControlPoint>();
358
359         public List<PipeControlPoint> getChildPoints() {
360                 return children;
361         }
362
363         public PipeControlPoint getParentPoint() {
364                 return parent;
365         }
366
367
368         private double length;
369         private Double turnAngle;
370         private Vector3d turnAxis;
371
372         private Double offset;
373         private Double rotationAngle;
374         private Boolean reversed;
375
376         @GetPropertyValue(name="Length",tabId="Debug",value="length")
377         public double getLength() {
378                 return length;
379         }
380
381         public void setLength(double l) {
382                 if (Double.isInfinite(l) || Double.isNaN(l)) {
383                         return;
384                 }
385                 if (Math.abs(this.length-l) < MathTools.NEAR_ZERO)
386                         return;
387                 this.length = l;
388                 firePropertyChanged("length");
389                 if (isDualInline())
390                     getDualSub().setLength(l);
391         }
392
393         @GetPropertyValue(name="Turn Angle",tabId="Debug",value="turnAngle")
394         public Double getTurnAngle() {
395                 return turnAngle;
396         }
397
398         @GetPropertyValue(name="Turn Axis",tabId="Debug",value="turnAxis")
399         public Vector3d getTurnAxis() {
400                 return turnAxis;
401         }
402
403         @GetPropertyValue(name="Offset",tabId="Debug",value="offset")
404         public Double getOffset() {
405                 return offset;
406         }
407
408         @GetPropertyValue(name="Rotation Angle",tabId="Debug",value="rotationAngle")
409         public Double getRotationAngle() {
410             if (isRotate || asFixedAngle())
411                 return rotationAngle;
412             return null;
413         }
414
415         @GetPropertyValue(name="Reversed",tabId="Debug",value="reversed")
416         public Boolean getReversed() {
417                 return reversed;
418         }
419
420         public boolean _getReversed() {
421                 if (reversed == null)
422                         return false;
423                 return reversed;
424         }
425
426         public void setTurnAngle(Double turnAngle) {
427                 if (turnAngle == null || Double.isInfinite(turnAngle) || Double.isNaN(turnAngle)) {
428                         return;
429                 }
430                 if (this.turnAngle != null && Math.abs(this.turnAngle-turnAngle) < MathTools.NEAR_ZERO)
431                         return;
432                 this.turnAngle = turnAngle;
433                 firePropertyChanged("turnAngle");
434         }
435
436         public void setTurnAxis(Vector3d turnAxis) {
437                 if (this.turnAxis != null && MathTools.equals(turnAxis, this.turnAxis))
438                         return;
439                 this.turnAxis = turnAxis;
440                 firePropertyChanged("turnAxis");
441         }
442
443         public void setOffset(Double offset) {
444                 if (Double.isInfinite(offset) || Double.isNaN(offset)) {
445                         return;
446                 }
447                 if (this.offset != null && Math.abs(this.offset-offset) < MathTools.NEAR_ZERO)
448                         return;
449                 this.offset = offset;
450                 firePropertyChanged("offset");
451         }
452
453         public void setRotationAngle(Double rotationAngle) {
454                 if (Double.isInfinite(rotationAngle) || Double.isNaN(rotationAngle)) {
455                         return;
456                 }
457                 if (this.rotationAngle != null && Math.abs(this.rotationAngle-rotationAngle) < MathTools.NEAR_ZERO)
458                         return;
459                 this.rotationAngle = rotationAngle;
460                 firePropertyChanged("rotationAngle");
461         }
462
463         public void setReversed(Boolean reversed) {
464                 this.reversed = reversed;
465                 firePropertyChanged("reversed");
466         }
467
468         public Vector3d getSizeChangeOffsetVector(Vector3d dir) {
469                 Quat4d q;
470                 if (rotationAngle == null)
471                         q = getControlPointOrientationQuat(dir, 0.0);
472                 else
473                         q = getControlPointOrientationQuat(dir, rotationAngle);
474                 Vector3d v = new Vector3d(0.0,offset,0.0);
475                 Vector3d offset = new Vector3d();
476                 MathTools.rotate(q, v, offset);
477                 return offset;
478         }
479
480         public Vector3d getSizeChangeOffsetVector() {
481                 Quat4d q;
482                 if (rotationAngle == null)
483                         q = getControlPointOrientationQuat(0.0);
484                 else
485                         q = getControlPointOrientationQuat(rotationAngle);
486                 Vector3d v = new Vector3d(0.0,offset,0.0);
487                 Vector3d offset = new Vector3d();
488                 MathTools.rotate(q, v, offset);
489                 return offset;
490         }
491
492         @GetPropertyValue(name="Next",tabId="Debug",value="next")
493         private String getNextString() {
494                 if (next == null)
495                         return null;
496                 return next.toString();
497         }
498
499         @GetPropertyValue(name="Previous",tabId="Debug",value="previous")
500         private String getPrevString() {
501                 if (previous == null)
502                         return null;
503                 return previous.toString();
504         }
505
506         @GetPropertyValue(name="Sub",tabId="Debug",value="sub")
507         private String getSubString() {
508                 if (children.size() == 0)
509                         return "";
510                 return Arrays.toString(children.toArray());
511         }
512
513         @GetPropertyValue(name="Type",tabId="Debug",value="type")
514         public String getTypeString() {
515                 return type.name();
516         }
517
518         public Vector3d getPathLegEndpointVector() {
519                 PipeControlPoint a = findPreviousEnd();
520                 PipeControlPoint b = findNextEnd();
521                 
522                 if (a == null || b == null) {
523                         return getPathLegDirection();
524                 }
525                 
526                 Vector3d p1 = a.getWorldPosition();
527                 Vector3d p2 = b.getWorldPosition();
528                 p2.sub(p1);
529                 double l = p2.length();
530                 if (l != 0.0) {
531                         p2.scale(1.0 / l);
532                         return p2;
533                 }
534                 else {
535                         return getPathLegDirection();
536                 }
537         }
538
539         public Vector3d getPathLegDirection() {
540                 if (turnAxis == null) {
541                         return getPathLegDirection(Direction.NEXT);
542                 } else {
543                         Vector3d dir = getPathLegDirection(Direction.PREVIOUS);
544                         if (dir != null) dir.negate();
545                         return dir;
546                 }
547         }
548         
549         public Quat4d getControlPointOrientationQuat(double angle) {
550                 Vector3d dir = getPathLegDirection();
551                 if (turnAxis == null) {
552                         return getControlPointOrientationQuat(dir, angle);
553                 } else {
554                         return getControlPointOrientationQuat(dir, turnAxis, angle);
555                 }
556         }
557         
558         public Quat4d getControlPointOrientationQuat(Vector3d dir, double angle, boolean reversed) {
559             if (turnAxis == null) {
560             if (dir.lengthSquared() > MathTools.NEAR_ZERO)
561                 dir.normalize();
562             Quat4d q =  getControlPointOrientationQuat(dir, angle);
563             if (reversed) {
564                 Quat4d q2 = new Quat4d();
565                 q2.set(new AxisAngle4d(MathTools.Y_AXIS, Math.PI));
566                 q.mulInverse(q2);
567             }
568             return q;
569         } else {
570             if (dir.lengthSquared() > MathTools.NEAR_ZERO)
571                 dir.normalize();
572             return getControlPointOrientationQuat(dir, turnAxis, angle);
573         }
574         }
575
576         public Quat4d getControlPointOrientationQuat(double angle, boolean reversed) {
577                 Vector3d dir = getPathLegDirection();
578                 return getControlPointOrientationQuat(dir, angle, reversed);
579         }
580
581         public Quat4d getControlPointOrientationQuat(Vector3d dir, double angle) {
582                 if (dir == null || dir.lengthSquared() < MathTools.NEAR_ZERO)
583                         return MathTools.getIdentityQuat();
584
585                 final P3DRootNode root = getRoot();
586                 Vector3d up = root != null ? new Vector3d(root.getUpVector()) : new Vector3d(0.0, 1.0, 0.0);
587                 double a = up.angle(getPathLegEndpointVector());
588                 if (a < 0.1 || (Math.PI - a) < 0.1) {
589                         // Rotate components
590                         up.set(up.getY(), up.getZ(), up.getX());
591                 }
592
593                 return getControlPointOrientationQuat(dir, up, angle);
594         }
595
596         public P3DRootNode getRoot() {
597                 INode n = getParent();
598                 while (n != null && !(n instanceof P3DRootNode))
599                         n = n.getParent();
600                 return (P3DRootNode) n;
601         }
602
603         public static Quat4d getControlPointOrientationQuat(Vector3d dir, Vector3d up,  double angle) {
604                 if (dir == null || dir.lengthSquared() < MathTools.NEAR_ZERO)
605                         return MathTools.getIdentityQuat();
606
607                 final Vector3d front = new Vector3d(1.0,0.0,0.0);
608
609                 Quat4d q1 = new Quat4d();
610
611
612                 Vector3d right = new Vector3d();
613                 
614                 up = new Vector3d(up);
615                 right.cross(dir, up);
616                 up.cross(right, dir);
617                 right.normalize();
618                 up.normalize();
619
620                 Matrix3d m = new Matrix3d();
621                 m.m00 = dir.x;
622                 m.m10 = dir.y;
623                 m.m20 = dir.z;
624                 m.m01 = up.x;
625                 m.m11 = up.y;
626                 m.m21 = up.z;
627                 m.m02 = right.x;
628                 m.m12 = right.y;
629                 m.m22 = right.z;
630
631                 //q1.set(m); MathTools contains more stable conversion
632                 MathTools.getQuat(m, q1);
633
634                 //                      if (DEBUG) System.out.println("PipingTools.getPipeComponentOrientationQuat() " + dir+ " " + up + " " + right);
635
636                 Quat4d q2 = new Quat4d();
637                 q2.set(new AxisAngle4d(front, angle));
638                 q1.mul(q2);
639                 return q1;
640         }
641
642         public void insert(PipeControlPoint previous, PipeControlPoint next) {
643                 // inserting an offsetpoint is error, 
644                 if (isDualSub())
645                         throw new RuntimeException("Dual sub points cannot be inserted.");
646                 // size change control point cannot be inserted this way, because it ends PipeRun
647 //              if (isSizeChange())
648 //                      throw new RuntimeException("Size change points cannot be inserted.");
649                 PipeRun piperun = previous.getPipeRun();
650                 // and just to make sure that control point structure is not corrupted
651                 if (getPipeRun() != null) {
652                         if (piperun != getPipeRun() || piperun != next.getPipeRun())
653                                 throw new RuntimeException("All controls points must be located on the same pipe run");
654                 } else {
655                         piperun.addChild(this);
656                 }
657
658                 // insert new BranchControlPoint between straight's control points
659                 PipeControlPoint previousNext = previous.getNext();
660                 PipeControlPoint previousPrevious = previous.getPrevious();
661
662                 PipeControlPoint offsetCP = null;
663                 if (isOffset()) {
664                         offsetCP = getDualSub();
665                 }
666                 if (previousNext != null && previousNext == next) {
667                         if (previous.isDualInline()) {
668                                 throw new RuntimeException();
669                         }
670                         if (next.isDualSub()) {
671                                 throw new RuntimeException();
672                         }
673                         previous.setNext(this);
674                         this.setPrevious(previous);
675                         if (previous.isDualSub()) {
676                                 previous.getParentPoint().setNext(this);
677                         }
678                         this.setNext(next);
679
680                         if (offsetCP == null) {
681                                 next.setPrevious(this);
682                         } else {
683                                 next.setPrevious(offsetCP);
684                                 offsetCP.setNext(next);
685                                 offsetCP.setPrevious(previous);
686                         }
687
688                         if (next.isDualInline()) {
689                                 next.getDualSub().setPrevious(this);
690                         }
691                 } else if (previousPrevious != null && previousPrevious == next) {
692                         // control point were given in reverse order 
693                         if (next.isDualInline())
694                                 throw new RuntimeException();
695                         if (previous.isDualSub())
696                                 throw new RuntimeException();
697
698                         this.setNext(previous);
699                         if (offsetCP == null) {
700                                 previous.setNext(this);
701                         } else {
702                                 previous.setPrevious(offsetCP);
703                                 offsetCP.setNext(previous);
704                                 offsetCP.setPrevious(next);
705                         }
706                         if (previous.isDualInline()) {
707                                 previous.getDualSub().setPrevious(this);
708                         }
709                         this.setPrevious(next);
710                         next.setNext(this);
711                         if (next.isDualSub()) {
712                                 next.getParentPoint().setNext(this);
713                         }
714
715                 } else {
716                         throw new RuntimeException();
717                 }       
718
719                 PipingRules.validate(piperun);
720         }
721
722
723
724         public void insert(PipeControlPoint pcp, Direction direction) {
725                 if (isDualSub())
726                         throw new RuntimeException();
727                 if (direction == Direction.NEXT) {
728                         // if direction is next, user must have given OffsetPoint
729                         if (pcp.isDualInline())
730                                 throw new RuntimeException();
731                         // basic next/prev links
732                         pcp.setNext(this);
733                         this.setPrevious(pcp);
734                         // and last take care of sizechange / offset points
735                         if (pcp.isDualSub()) {
736                                 pcp.getParentPoint().setNext(this);
737                         }
738                         if (isDualInline()) {
739                             getDualSub().setPrevious(this);
740                         }
741                 } else {
742                         // if direction is previous, user must have given sizechange
743                         if (pcp.isDualSub())
744                                 throw new RuntimeException();
745                         // previous direction is more complicated, since if newCP is SizeChangeControlPoint,
746                         // we must link pcp to newCP's OffsetPoint
747                         PipeControlPoint nocp = null;
748                         if (isDualInline()) {
749                                 nocp = getDualSub();
750                                 nocp.setNext(pcp);
751                         }
752                         if (nocp == null) {
753                                 pcp.setPrevious(this);
754                         } else {
755                                 pcp.setPrevious(nocp);
756                         }
757                         this.setNext(pcp);
758                         if (pcp.isDualInline()) {
759                                 PipeControlPoint ocp = pcp.getDualSub();
760                                 if (nocp == null)
761                                         ocp.setPrevious(this);
762                                 else
763                                         ocp.setPrevious(nocp);
764                         }
765
766                 }
767                 PipingRules.validate(getPipeRun());
768         }
769
770         public Vector3d getDirectedControlPointDirection() {
771                 assert (isDirected());
772                 Vector3d dir = new Vector3d();
773                 MathTools.rotate(getWorldOrientation(), new Vector3d(1.0, 0.0, 0.0), dir);
774                 dir.normalize();
775                 return dir;
776         }
777         
778         /**
779          * Returns direction vector. 
780          * 
781          * For directed control points, always returns outwards pointing vector.
782          * 
783          * @param direction
784          * @return normalized vector, or null
785          */
786         public Vector3d getDirection(Direction direction) {
787         if (isDirected())
788             return getDirectedControlPointDirection();
789         if (isTurn() && asFixedAngle()) {
790             if (direction == Direction.NEXT) {
791                 if (previous != null) {
792                     PipeControlPoint pcp = this;
793                     Vector3d dir = new Vector3d();
794                     dir.sub(pcp.getWorldPosition(),previous.getWorldPosition());
795                     if (dir.lengthSquared() > MathTools.NEAR_ZERO)
796                         dir.normalize();
797                     else
798                         return null;
799                     Quat4d q = getControlPointOrientationQuat(dir, pcp.getRotationAngle() != null ? pcp.getRotationAngle() : 0.0);
800                     AxisAngle4d aa = new AxisAngle4d(MathTools.Y_AXIS,pcp.getTurnAngle() == null ? 0.0 : pcp.getTurnAngle());
801                     Quat4d q2 = MathTools.getQuat(aa);
802                     Vector3d v = new Vector3d(1.,0.,0.);
803                     Vector3d offset = new Vector3d();
804                     MathTools.rotate(q2, v, offset);
805                     MathTools.rotate(q, offset, dir);
806                     dir.normalize();
807                     return dir;
808                 }
809             } else {
810                 if (next != null) {
811                     PipeControlPoint pcp = this;
812                     Vector3d dir = new Vector3d();
813                     dir.sub(next.getWorldPosition(),pcp.getWorldPosition());
814                     if (dir.lengthSquared() > MathTools.NEAR_ZERO)
815                         dir.normalize();
816                     else
817                         return null;
818                     Quat4d q = getControlPointOrientationQuat(dir, pcp.getRotationAngle() != null ? pcp.getRotationAngle() : 0.0);
819                     AxisAngle4d aa = new AxisAngle4d(MathTools.Y_AXIS,pcp.getTurnAngle() == null ? 0.0 : pcp.getTurnAngle());
820                     Quat4d q2 = MathTools.getQuat(aa);
821                     Vector3d v = new Vector3d(1.,0.,0.);
822                     Vector3d offset = new Vector3d();
823                     MathTools.rotate(q2, v, offset);
824                     MathTools.rotate(q, offset, dir);
825                     dir.normalize();
826                     return dir;
827                 }
828             }
829         }
830         return null;
831     }
832
833         /**
834          * Returns path leg direction of the control point.
835          * 
836          * This method differs from getDirection by also returning inward pointing vectors for directed control points.
837          * 
838          * @param direction
839          * @return
840          */
841         public Vector3d getPathLegDirection(Direction direction) {
842                 if (direction == Direction.NEXT) {
843                         if (next != null) {
844                                 PipeControlPoint pcp = this;
845                                 if (pcp.isDualInline()) {
846                                         pcp = pcp.getDualSub();
847                                 }
848                                 Vector3d v = new Vector3d();
849                                 v.sub(next.getWorldPosition(),pcp.getWorldPosition());
850                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
851                     v.normalize();
852                 else
853                     return null;
854                                 return v;
855                         } else {
856                                 if (previous == null) {
857                                         if (!isDirected())
858                                                 throw new RuntimeException("Cannot calculate path leg direction for unconnected control point " + this);
859                                         return getDirectedControlPointDirection();
860
861                                 } else {
862                                         if (isVariableAngle() && !asFixedAngle())
863                                                 throw new RuntimeException("Cannot calculate path leg direction for unconnected variable angle control point " + this);
864                                         if (isInline()) {
865                                                 PipeControlPoint pcp = this;
866                                                 if (pcp.isDualSub()) {
867                                                         pcp = pcp.getParentPoint();
868                                                 }
869                                                 Vector3d v = new Vector3d();
870                                                 v.sub(pcp.getWorldPosition(),previous.getWorldPosition());
871                                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
872                                 v.normalize();
873                                                 else
874                                                     return null;
875                                                 return v;
876                                         } else if (isDirected()) {
877                                                 return getDirectedControlPointDirection();
878                                         } else if (isEnd()) {
879                                                 Vector3d v = new Vector3d();
880                                                 v.sub(getWorldPosition(),previous.getWorldPosition());
881                                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
882                             v.normalize();
883                         else
884                             return null;
885                                                 return v;
886                                         } else if (isTurn() && asFixedAngle() && !_getReversed()) {
887                                                 return getDirection(Direction.NEXT);
888                                         }
889                                         throw new RuntimeException("Missing implementation " + this);
890                                 }
891                         }
892                 } else {
893                         if (previous != null) {
894                                 PipeControlPoint pcp = this;
895                                 if (isDualSub()) 
896                                         pcp = getParentPoint();
897                                 Vector3d v = new Vector3d();
898                                 v.sub(previous.getWorldPosition(),pcp.getWorldPosition());
899                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
900                     v.normalize();
901                 else
902                     return null;
903                                 return v;
904                         } else {
905                                 if (next == null)  {
906                                         if (!isDirected())
907                                                 throw new RuntimeException("Cannot calculate path leg direction for unconnected control point " + this);
908                                         Vector3d v = getDirectedControlPointDirection();
909                                         v.negate();
910                                         return v;
911                                 } else {
912                                         if (isVariableAngle() && !asFixedAngle())
913                                                 throw new RuntimeException("Cannot calculate path leg direction for unconnected variable angle control point " + this);
914                                         if (isInline()) {
915                                                 PipeControlPoint pcp = this;
916                                                 if (pcp.isDualInline()) {
917                                                         pcp = pcp.getDualSub();
918                                                 }
919                                                 Vector3d v = new Vector3d();
920                                                 v.sub(pcp.getWorldPosition(),next.getWorldPosition());
921                                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
922                             v.normalize();
923                         else
924                             return null;
925                                                 return v;
926                                         } else if (isDirected()) {
927                                                 Vector3d v = getDirectedControlPointDirection();
928                                                 v.negate();
929                                                 return v;
930                                         } else if (isEnd()) {
931                                                 Vector3d v = new Vector3d();
932                                                 v.sub(getWorldPosition(),next.getWorldPosition());
933                                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
934                             v.normalize();
935                         else
936                             return null;
937                                                 return v;
938                                         } else if (isTurn() && asFixedAngle() && _getReversed()) {
939                                                 return getDirection(Direction.PREVIOUS);
940                                         }
941                                         throw new RuntimeException("Missing implementation " + this);
942                                 }
943                         }
944                 }
945         }
946
947         public void getInlineControlPointEnds(Tuple3d p1, Tuple3d p2) {
948                 assert (isInline());
949
950                 PipeControlPoint sub = isAxial() ? this : getDualSub();
951                 Vector3d pos = getWorldPosition(), pos2 = sub == this ? pos : sub.getWorldPosition();
952                 Vector3d dir = sub.getInlineDir();
953                 
954                 dir.scale(length * 0.5);
955                 p1.set(pos);
956                 p2.set(pos2);
957                 p1.sub(dir);
958                 p2.add(dir);
959         }
960
961         public void getControlPointEnds(Tuple3d p1, Tuple3d p2) {
962                 PipeControlPoint sub = isAxial() || isDirected() || isTurn() ? this : getChildPoints().get(0);
963                 Vector3d pos = getWorldPosition(), pos2 = sub == this ? pos : sub.getWorldPosition();
964                 
965                 Vector3d dir1;
966                 Vector3d dir2;
967                 if (isInline()) {
968                         dir2 = getInlineDir();
969                         dir2.scale(length * 0.5);
970                         dir1 = new Vector3d(dir2);
971                         dir1.negate();
972                 } else {
973                         dir1 = getPathLegDirection(Direction.PREVIOUS);
974                         dir2 = sub.getPathLegDirection(Direction.NEXT);
975                         dir1.scale(length);
976                         dir2.scale(length);
977                 }
978                 p1.set(pos);
979                 p2.set(pos2);
980                 p1.add(dir1);
981                 p2.add(dir2);
982         }
983
984         /**
985          * Get both path leg directions, with (0,0,0) if no connection exists. The returned vectors are not normalized.
986          * 
987          * @param v1  Set to the direction towards the previous control point on output
988          * @param v2  Set to the direction towards the next control point on output
989          */
990         public void getEndDirections(Tuple3d v1, Tuple3d v2) {
991                 PipeControlPoint sub = isAxial() ? this : getDualSub();
992                 
993                 Vector3d dir1 = getPathLegDirection(Direction.PREVIOUS);
994                 Vector3d dir2 = sub.getPathLegDirection(Direction.NEXT);
995                 
996                 if (dir1 != null)
997                         v1.set(dir1);
998                 else
999                         v1.set(0,0,0);
1000                 
1001                 if (dir2 != null)
1002                         v2.set(dir2);
1003                 else
1004                         v2.set(0,0,0);
1005         }
1006
1007         public void getInlineControlPointEnds(Tuple3d p1, Tuple3d p2, Vector3d dir) {
1008                 assert (isInline());
1009
1010                 Vector3d pos = getWorldPosition();
1011                 dir.set(getInlineDir());
1012                 dir.normalize();
1013                 dir.scale(length * 0.5);
1014                 p1.set(pos);
1015                 p2.set(pos);
1016                 p1.sub(dir);
1017                 p2.add(dir);
1018         }
1019
1020         public void getInlineControlPointEnds(Tuple3d center, Tuple3d p1, Tuple3d p2, Vector3d dir) {
1021                 assert (isInline());
1022
1023                 Vector3d pos = getWorldPosition();
1024                 center.set(pos);
1025                 dir.set(getInlineDir());
1026                 dir.normalize();
1027                 dir.scale(length * 0.5);
1028                 p1.set(pos);
1029                 p2.set(pos);
1030                 p1.sub(dir);
1031                 p2.add(dir);
1032         }
1033
1034         public Vector3d getInlineDir() {
1035                 Vector3d dir = getPathLegDirection(Direction.NEXT);
1036                 if (dir == null) {
1037                         dir = getPathLegDirection(Direction.PREVIOUS);
1038                         if (dir != null) {
1039                                 // Use reverse direction
1040                                 dir.scale(-1.0);
1041                         } else {
1042                                 // Control point is not connected at all, use current orientation
1043                                 dir = new Vector3d(1,0,0);
1044                                 MathTools.rotate(getWorldOrientation(), dir, dir);
1045                         }
1046                 }
1047                 return dir;
1048         }
1049
1050         public double getInlineLength() {
1051                 if (type == PointType.TURN)
1052                         return length;
1053                 else if (type == PointType.INLINE)
1054                         return length * 0.5;
1055                 return 0;
1056         }
1057
1058         /**
1059          * Return the position indicated by the argument. If the indicated direction is not connected, the
1060          * control point's wolrd position is returned instead.
1061          * 
1062          * @param type  A selector for the position to be returned
1063          * @return  The selected position
1064          */
1065         public Vector3d getRealPosition(PositionType type) {
1066                 Vector3d pos = getWorldPosition();
1067                 switch (type) {
1068                 case NEXT: {
1069                         double length = getInlineLength();
1070                         Vector3d dir;
1071                         if (isInline()) {
1072                                 dir = getInlineDir();
1073                         } else {
1074                                 dir = getPathLegDirection(Direction.NEXT);
1075                         }
1076                         dir.scale(length);
1077                         pos.add(dir);
1078                         break;
1079                 }
1080                 case PREVIOUS: {
1081                         double length = getInlineLength();
1082                         Vector3d dir;
1083                         if (isInline()) {
1084                                 dir = getInlineDir();
1085                                 dir.negate();
1086                         } else {
1087                                 dir = getPathLegDirection(Direction.PREVIOUS);
1088                         }
1089                         dir.scale(length);
1090                         pos.add(dir);
1091                         break;
1092                 }
1093                 case PORT:
1094                         // IEntity portDir = pcp.getSingleRelatedObject(ProcessResource.plant3Dresource.HasDirection);
1095                         // TODO : how we calculated needed space for a port; does it has an offset from control point's position or not?
1096                         break;
1097                 case SPLIT:
1098                         // do nothing
1099                         break;
1100
1101                 }
1102                 return pos;
1103         }
1104
1105         public void getInlineMovement(Tuple3d start, Tuple3d end) {
1106                 // FIXME : check type of neighbor components and allow movement on top of variable length components,
1107                 //         find proper range for movement (pcp's position is not)
1108                 PipeControlPoint p = previous.getPrevious();
1109                 PipeControlPoint n = next.getNext();
1110                 start.set(p.getWorldPosition());
1111                 end.set(n.getWorldPosition());
1112         }
1113
1114         public PipeControlPoint findNextEnd() {
1115                 ArrayList<PipeControlPoint> t = new ArrayList<PipeControlPoint>();
1116                 return findNextEnd( t);
1117         }
1118
1119         public PipeControlPoint findPreviousEnd() {
1120                 ArrayList<PipeControlPoint> t = new ArrayList<PipeControlPoint>();
1121                 return findPreviousEnd(t);
1122         }
1123
1124         public PipeControlPoint findNextEnd(List<PipeControlPoint> nextList) {
1125                 while (true) {
1126                         PipeControlPoint pcp = null;
1127                         PipeControlPoint p = null;
1128                         if (nextList.size() == 0)
1129                                 p = this;
1130
1131                         else
1132                                 p = nextList.get(nextList.size() - 1);
1133
1134                         pcp = p.getNext();
1135                         if (pcp == null) {
1136                                 pcp = p;
1137                                 if (nextList.size() > 0)
1138                                         nextList.remove(nextList.size() - 1);
1139                                 //              if (DEBUG) System.out.println(" " + pcp.getResource() + " not full");
1140                                 return pcp;
1141                                 //break;
1142                         }
1143                         if (pcp.isPathLegEnd()) {
1144                                 //if (DEBUG) System.out.println(" " + pcp.getResource());
1145                                 return pcp;
1146                         } else {
1147                                 nextList.add(pcp);
1148                                 // if (DEBUG) System.out.print(" " + pcp.getResource());
1149                         }
1150                 }
1151         }
1152
1153         public PipeControlPoint findPreviousEnd(List<PipeControlPoint> prevList) {
1154                 while (true) {
1155                         PipeControlPoint pcp = null;
1156                         PipeControlPoint p = null;
1157                         if (prevList.size() == 0)
1158                                 p = this;
1159
1160                         else
1161                                 p = prevList.get(prevList.size() - 1);
1162
1163                         pcp = p.getPrevious();
1164                         if (pcp == null) {
1165                                 pcp = p;
1166                                 if (prevList.size() > 0)
1167                                         prevList.remove(prevList.size() - 1);
1168                                 //                              if (DEBUG) System.out.println(" " + pcp.getResource() + " not full");
1169                                 return pcp;
1170                         }
1171                         if (pcp.isPathLegEnd()) {
1172                                 //                              if (DEBUG)      System.out.println(" " + pcp.getResource());
1173                                 return pcp;
1174                         } else {
1175                                 prevList.add(pcp);
1176                                 //                              if (DEBUG)System.out.print(" " + pcp.getResource());
1177                         }
1178                 }
1179         }
1180         
1181         public void _remove() {
1182             _remove(true);
1183         }
1184         
1185         
1186         public PipeControlPoint getDualSub() {
1187             if (isDualInline())
1188                 return getChildPoints().get(0);
1189             else
1190                 throw new IllegalStateException("Current control point is not dual inline");
1191         }
1192         
1193
1194         public void _remove(boolean renconnect) {
1195             if (disposed)
1196                 return;
1197                 
1198             if (DEBUG) System.out.println(this + " Remove " + renconnect);
1199
1200                 if (getParentPoint() != null) {
1201                     getParentPoint()._remove(renconnect);
1202                     return;
1203                 }
1204                 PipeRun pipeRun = getPipeRun();
1205 //              PipeRUn removal has been changed, so pipeRun may be null.
1206 //              if (pipeRun == null)
1207 //                      return;
1208
1209                 PipeControlPoint additionalRemove = null;
1210                 if (!PipingRules.isEnabled()) {
1211                     component = null;
1212                         setPrevious(null);
1213                         setNext(null);
1214                 } else {
1215
1216                         PipeControlPoint currentPrev = previous;
1217                         PipeControlPoint currentNext = next;
1218                         if (currentNext == null && currentPrev == null) {
1219                                 removeComponent();
1220                                 if (pipeRun != null) {
1221                                     pipeRun.remChild(this);
1222                                     checkRemove(pipeRun);
1223                                 }
1224                                 return;
1225                         }
1226                         if (currentNext != null && currentPrev != null) {
1227                                 boolean link = renconnect;
1228                                 if (currentNext.isBranchEnd()) {
1229                                         link = false;
1230                                         currentNext.remove();
1231                                         currentNext = null;
1232                                         setNext(null);
1233                                 }
1234                                 if (currentPrev.isBranchEnd()) {
1235                                         link = false;
1236                                         currentPrev.remove();
1237                                         currentPrev = null;
1238                                         setPrevious(null);
1239                                 }
1240                                 if (link) {
1241                                     if (currentPrev.isDirected() && currentNext.isDirected())
1242                                         link = false;
1243                                     else if (this.isDualSub()) {
1244                                         throw new RuntimeException("_remove() is called for parent point, somehow got to child point. " + this);
1245                                     }
1246                                 }
1247                                 if (currentNext == null) {
1248                                         // Nothing to do
1249                                 } else if (currentNext.isDualInline()) {
1250                                         PipeControlPoint sccp = currentNext;
1251                                         PipeControlPoint ocp = currentNext.getDualSub();
1252                                         if (ocp == null) {
1253                                                 throw new RuntimeException("Removing PipeControlPoint " + this+ " structure damaged, no offset control point");
1254                                         }
1255                                         if (link) {
1256                                                 sccp.setPrevious(currentPrev);
1257                                                 //ocp.setPrevious(currentPrev);
1258                                                 assert(ocp.getPrevious() == currentPrev);
1259                                         } else {
1260                                                 sccp.setPrevious(null);
1261                                                 //ocp.setPrevious(null);
1262                                                 assert(ocp.getPrevious() == null);
1263                                         }
1264                                         setNext(null);
1265                                 } else if (currentNext.isDualSub()) {
1266                                         throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, next control point is offset control point");
1267                                 } else if (currentNext.previous == this) {
1268                                         if (link) {
1269                                                 currentNext.setPrevious(currentPrev);
1270                                         } else {
1271                                                 currentNext.setPrevious(null);
1272                                         }
1273                                         setNext(null);
1274                                 } else if (isDualInline()) {
1275                                     if (currentNext.previous != getDualSub()) {
1276                                         throw new RuntimeException("Removing PipeControlPoint "+ this+ " structure damaged");
1277                                     }
1278                                     if (link) {
1279                         currentNext.setPrevious(currentPrev);
1280                     } else {
1281                         currentNext.setPrevious(null);
1282                     }
1283                     setNext(null);
1284                                 } else {
1285                                         throw new RuntimeException("Removing PipeControlPoint "+ this+ " structure damaged");
1286                                 }
1287                                 if (currentPrev == null) {
1288                                         // Nothing to do
1289                                 } else if (currentPrev.isDualInline()) {
1290                                         throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, previous control point is size change control point");
1291                                 } else if (currentPrev.isDualSub()) {
1292                                         PipeControlPoint ocp = currentPrev;
1293                                         PipeControlPoint sccp = currentPrev.getParentPoint();
1294                                         if (sccp == null)
1295                                                 throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, no size change control point");
1296                                         if (link) {
1297                                                 //ocp.setNext(currentNext);
1298                                                 sccp.setNext(currentNext);
1299                                                 assert(ocp.getNext() == currentNext);
1300                                         } else {
1301                                                 //ocp.setNext(null);
1302                                                 sccp.setNext(null);
1303                                                 assert(ocp.getNext() == null);
1304                                         }
1305                                         setPrevious(null);
1306                                 } else if (currentPrev.next == this) {
1307                                         if (link)
1308                                                 currentPrev.setNext(currentNext);
1309                                         else
1310                                                 currentPrev.setNext(null);
1311
1312                                         setPrevious(null);
1313                                 } else {
1314                                         throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged");
1315                                 }
1316                                 if (link) {
1317                                         if (currentNext.isVariableLength() && currentPrev.isVariableLength()) {
1318                                                 // we have to join them into single variable length component.
1319                                                 additionalRemove = currentPrev;
1320                                                 // combine lengths and set the location of remaining control point to the center.
1321                                                 Point3d ps = new Point3d();
1322                                                 Point3d pe = new Point3d();
1323                                                 Point3d ns = new Point3d();
1324                                                 Point3d ne = new Point3d();
1325                                                 currentPrev.getInlineControlPointEnds(ps, pe);
1326                                                 currentNext.getInlineControlPointEnds(ns, ne);
1327                                                 double l = currentPrev.getLength() + currentNext.getLength();
1328                                                 Vector3d cp = new Vector3d();
1329                                                 cp.add(ps, ne);
1330                                                 cp.scale(0.5);
1331                                                 currentNext.setLength(l);
1332                                                 currentNext.setWorldPosition(cp);
1333                                         }
1334                                 } else {
1335                                         // FIXME : pipe run must be split into two parts, since the control point structure is no more continuous. 
1336                                 }
1337                         } else if (currentNext != null) {
1338                                 if (currentNext.isDualInline()) {
1339                                         PipeControlPoint sccp = currentNext;
1340                                         PipeControlPoint ocp = currentNext.getDualSub();
1341                                         if (ocp == null) {
1342                                                 throw new RuntimeException("Removing PipeControlPoint " + this+ " structure damaged, no offset control point");
1343                                         }
1344                                         sccp.setPrevious(null);
1345                                         assert(ocp.getPrevious() == null);
1346                                         //ocp.setPrevious(null);
1347                                 } else if (currentNext.isDualSub()) {
1348                                         throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, next control point is offset control point");
1349                                 } else if (currentNext.previous == this) {
1350                                     currentNext.setPrevious(null);
1351                                 }  else if (isDualInline()) {
1352                     if (currentNext.previous != getDualSub()) {
1353                         throw new RuntimeException("Removing PipeControlPoint "+ this+ " structure damaged");
1354                     }
1355                     currentNext.setPrevious(null);
1356                                 } else {
1357                                         throw new RuntimeException("Removing PipeControlPoint "+ this+ " structure damaged");
1358                                 }
1359                                 setNext(null);
1360                         } else {  //(previous != null)
1361                                 if(currentPrev.isDualInline()) {
1362                                         throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, previous control point is size change control point");
1363                                 } else if (currentPrev.isDualSub()) {
1364                                         PipeControlPoint ocp = currentPrev;
1365                                         PipeControlPoint sccp = currentPrev.getParentPoint();
1366                                         if (sccp == null) {
1367                                                 throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, no size change control point");
1368                                         }
1369                                         sccp.setNext(null);
1370                                         assert(ocp.getNext() == null);
1371                                 } else if (currentPrev.next == this) {
1372                                     currentPrev.setNext(null);
1373                                 } else {
1374                                         throw new RuntimeException("Removing PipeControlPoint "+ this+ " structure damaged");
1375                                 }
1376                                 setPrevious(null);
1377                         }
1378                         if (children.size() > 0 ) {
1379                                 removeSubPoints();
1380                         } else if (parent!= null) {
1381                                 removeParentPoint();
1382                         }
1383
1384                 }
1385
1386                 removeComponent();
1387                 if (pipeRun != null) {
1388                 pipeRun.remChild(this);
1389                 checkRemove(pipeRun);
1390                 if (PipingRules.isEnabled() && pipeRun.getParent() != null && pipeRun.getControlPoints().size() > 0)
1391                         PipingRules.validate(pipeRun);
1392                 }
1393                 if (additionalRemove != null)
1394                         additionalRemove.remove();
1395                 disposed = true;
1396         }
1397
1398         /**
1399          * Removes control point and attempts to reconnect next/prev
1400          * 
1401          * If this point is size change (PipeRuns are different on both sides), then reconnection cannot be made.
1402          */
1403         public void remove() {
1404                 PipeControlPoint currentPrev = previous;
1405                 PipeControlPoint currentNext = next;
1406                 _remove();
1407                 try {
1408                         if (currentNext != null)
1409                             if (!currentNext.checkRemove())
1410                                 PipingRules.requestUpdate(currentNext);
1411                         if (currentPrev != null)
1412                             if (!currentPrev.checkRemove())
1413                                 PipingRules.requestUpdate(currentPrev);
1414                 } catch (Exception e) {
1415                         e.printStackTrace();
1416                 }
1417         }
1418         
1419         
1420         /**
1421          * Removes control point without attempting to reconnect next/prev.
1422          * This usually leads to creation of another PipeRun for the control points after this point. 
1423          */
1424         public void removeAndSplit() {
1425         PipeControlPoint currentPrev = previous;
1426         PipeControlPoint currentNext = next;
1427         
1428         if (next != null && previous != null) {
1429             P3DRootNode root = (P3DRootNode)getPipelineComponent().getRootNode();
1430             PipeRun nextPipeRun = new PipeRun();
1431             nextPipeRun.setName(root.getUniqueName("PipeRun"));
1432             root.addChild(nextPipeRun);
1433             
1434             PipeRun previousRun = previous.getPipeRun();
1435             nextPipeRun.setPipeDiameter(previousRun.getPipeDiameter());
1436             nextPipeRun.setTurnRadiusArray(previousRun.getTurnRadiusArray());
1437             
1438             PipelineComponent n = next.getPipelineComponent();
1439             while (n != null) {
1440                 if (n.getPipeRun() != previousRun)
1441                     break;
1442                 if (! (n instanceof Nozzle)) {
1443                     n.deattach();
1444                     nextPipeRun.addChild(n);
1445                 } else
1446                     n.setPipeRun(nextPipeRun);
1447                 n = n.getNext();
1448             }
1449         }
1450         _remove(false);
1451         try {
1452             if (currentNext != null)
1453                 if (!currentNext.checkRemove())
1454                     PipingRules.requestUpdate(currentNext);
1455             if (currentPrev != null)
1456                 if (!currentPrev.checkRemove())
1457                     PipingRules.requestUpdate(currentPrev);
1458         } catch (Exception e) {
1459             e.printStackTrace();
1460         }
1461     }
1462         
1463         /**
1464          * This is called when adjacent control point is removed.
1465          * 
1466          * This call should remove the give point, if the point cannot exist alone. 
1467          * At the moment there is one such case: branch.
1468          * 
1469          * @return
1470          */
1471         protected boolean checkRemove() {
1472             if (getParentPoint() != null) {
1473                 return getParentPoint().checkRemove();
1474             } else {
1475                 if (getPipelineComponent() == null)
1476                     return true; // already removed
1477             if (getPipelineComponent().getType().equals("Plant3D.URIs.Builtin_BranchSplitComponent")) {
1478                 if (getChildPoints().get(0).getNext() == null && getChildPoints().get(0).getPrevious() == null) {
1479                         remove();
1480                         return true;
1481                 }
1482             }
1483             return checkRemove(getPipeRun());
1484             }
1485     }
1486
1487         private boolean checkRemove(PipeRun pipeRun) {
1488             if (pipeRun == null)
1489                 return false;
1490                 Collection<PipeControlPoint> points = pipeRun.getControlPoints();
1491                 if (points.size() == 0) {
1492                         pipeRun.remove();
1493                         return true;
1494                 } else if (points.size() == 1) {
1495                         PipeControlPoint pcp = points.iterator().next();
1496                         if (pcp.isDeletable() && pcp.getNext() == null && pcp.getPrevious() == null) {
1497                                 pcp._remove(); // This call will recursively call also this method...
1498                                 return true;
1499                         }
1500                 } else if (points.size() == 2) {
1501                     
1502                 }
1503                 return false;
1504         }
1505
1506         private void removeSubPoints() {
1507                 for (PipeControlPoint p : children) {
1508                         p.parent = null;
1509                         p.component = null;
1510                         //p._remove();
1511                         PipeControlPoint currentNext = p.getNext();
1512                         PipeControlPoint currentPrev = p.getPrevious();
1513                         p._setNext(null);
1514                         p._setPrevious(null);
1515                         PipeRun run = p.getPipeRun();
1516                         if (run != null) {
1517                             run.remChild(p);
1518                             checkRemove(run);
1519                         }
1520                         if (currentNext != null)
1521                 if (!currentNext.checkRemove())
1522                     PipingRules.requestUpdate(currentNext);
1523             if (currentPrev != null)
1524                 if (!currentPrev.checkRemove())
1525                     PipingRules.requestUpdate(currentPrev);
1526             
1527                 }
1528                 children.clear();
1529         }
1530
1531         private void removeParentPoint() {
1532                 throw new RuntimeException("Child points cannot be removed directly");
1533         }
1534         
1535         public boolean isRemoved() {
1536             return component == null;
1537         }
1538
1539         private void removeComponent() {
1540                 if (component == null)
1541                         return;
1542                 PipelineComponent next = component.getNext();
1543                 PipelineComponent prev = component.getPrevious();
1544                 PipelineComponent br0 = component.getBranch0();
1545                 component.setNext(null);
1546                 component.setPrevious(null);
1547                 component.setBranch0(null);
1548                 if (next != null) {
1549                         if (next.getNext() == component)
1550                                 next.setNext(null);
1551                         else if (next.getPrevious() == component)
1552                                 next.setPrevious(null);
1553                         else if (next.getBranch0() == component)
1554                                 next.setBranch0(null);
1555                 }
1556                 if (prev != null) {
1557                         if (prev.getNext() == component)
1558                                 prev.setNext(null);
1559                         else if (prev.getPrevious() == component)
1560                                 prev.setPrevious(null);
1561                         else if (prev.getBranch0() == component)
1562                                 prev.setBranch0(null);
1563                 }
1564                 if (br0 != null) {
1565                         if (br0.getNext() == component)
1566                                 br0.setNext(null);
1567                         else if (br0.getPrevious() == component)
1568                                 br0.setPrevious(null);
1569                         else if (br0.getBranch0() == component)
1570                                 br0.setBranch0(null);
1571                 }
1572                 PipelineComponent comp = component;
1573                 component = null;
1574
1575                 comp.remove();
1576         }
1577
1578         @Override
1579         public void setOrientation(Quat4d orientation) {
1580                 if (MathTools.equals(orientation, getOrientation()))
1581                         return;
1582                 if (getPipelineComponent() != null && (getPipelineComponent() instanceof Nozzle))
1583                     System.out.println();
1584                 super.setOrientation(orientation);
1585                 if (getParentPoint() == null && component != null)
1586                         component._setWorldOrientation(getWorldOrientation());
1587                 updateSubPoint();
1588         }
1589
1590         @Override
1591         public void setPosition(Vector3d position) {
1592                 if (MathTools.equals(position, getPosition()))
1593                         return;
1594                 if (Double.isNaN(position.x) || Double.isNaN(position.y) || Double.isNaN(position.z))
1595                         throw new IllegalArgumentException("NaN is not supported");
1596                 super.setPosition(position);
1597                 if (getParentPoint() == null && component != null)
1598                         component._setWorldPosition(getWorldPosition());
1599                 updateSubPoint();
1600         }
1601
1602         private void updateSubPoint() {
1603                 if (isOffset()) {
1604                         if (next == null && previous == null) {
1605                                 for (PipeControlPoint sub : getChildPoints()) {
1606                                         sub.setWorldPosition(getWorldPosition());
1607                                         sub.setWorldOrientation(getWorldOrientation());
1608                                 }
1609                                 return;
1610                         }
1611                         for (PipeControlPoint sub : getChildPoints()) {
1612                                 Vector3d wp = getWorldPosition();
1613                                 wp.add(getSizeChangeOffsetVector());
1614                                 sub.setWorldPosition(wp);
1615                                 sub.setWorldOrientation(getWorldOrientation());
1616                         }
1617                 } else {
1618                         for (PipeControlPoint sub : getChildPoints()) {
1619                                 sub.setWorldPosition(getWorldPosition());
1620                                 sub.setWorldOrientation(getWorldOrientation());
1621                         }
1622                 }
1623         }
1624
1625
1626         public void _setWorldPosition(Vector3d position) {
1627                 Vector3d localPos = getLocalPosition(position);
1628                 super.setPosition(localPos);
1629                 updateSubPoint();
1630         }
1631
1632         public void _setWorldOrientation(Quat4d orientation) {
1633                 Quat4d localOr = getLocalOrientation(orientation);
1634                 super.setOrientation(localOr);
1635                 updateSubPoint();
1636         }
1637
1638         @Override
1639         public String toString() {
1640                 return getClass().getName() + "@" + Integer.toHexString(hashCode());
1641         }
1642
1643 }