]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipingRules.java
3094f7d20651527c8ca1728a7760a3b4187ce2d5
[simantics/3d.git] / org.simantics.plant3d / src / org / simantics / plant3d / scenegraph / controlpoint / PipingRules.java
1 package org.simantics.plant3d.scenegraph.controlpoint;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.HashMap;
6 import java.util.List;
7 import java.util.Map;
8
9 import javax.vecmath.Point3d;
10 import javax.vecmath.Quat4d;
11 import javax.vecmath.Vector3d;
12
13 import org.simantics.g3d.math.MathTools;
14 import org.simantics.plant3d.scenegraph.InlineComponent;
15 import org.simantics.plant3d.scenegraph.Nozzle;
16 import org.simantics.plant3d.scenegraph.P3DRootNode;
17 import org.simantics.plant3d.scenegraph.PipeRun;
18 import org.simantics.plant3d.scenegraph.PipelineComponent;
19 import org.simantics.plant3d.scenegraph.TurnComponent;
20 import org.simantics.plant3d.scenegraph.controlpoint.PipeControlPoint.Direction;
21 import org.simantics.plant3d.utils.ComponentUtils;
22 import org.simantics.utils.ui.ErrorLogger;
23
24 public class PipingRules {
25         private static final boolean DEBUG = false;
26         private static final boolean DUMMY = false;
27
28         private static double MIN_TURN_ANGLE = 0.001; // Threshold for removing turn components.
29         private static double ALLOWED_OFFSET = 0.001; // Allowed offset for directed path legs
30
31         private static final int REMOVE_NONE = 0;
32         private static final int REMOVE_START = 1;
33         private static final int REMOVE_END = 2;
34         private static final int REMOVE_BOTH = 3;
35         
36
37         private enum PathLegUpdateType {
38                 NONE, PREV, NEXT, PREV_S, NEXT_S
39         };
40         
41         private static boolean enabled = true;
42         private static boolean updating = false;
43         private static boolean allowInsertRemove = true;
44         private static boolean triedIR = false;
45
46         
47         private static List<PipeControlPoint> requestUpdates = new ArrayList<PipeControlPoint>();
48         private static List<PipeControlPoint> currentUpdates = new ArrayList<PipeControlPoint>();
49         
50         private static Object updateMutex = new Object();
51         private static Object ruleMutex = new Object();
52         
53         public static void requestUpdate(PipeControlPoint pcp) {
54             if (!PipingRules.enabled)
55                 return;
56                 if (DEBUG) System.out.println("PipingRules request " + pcp);
57                 synchronized (updateMutex) {
58                         if (!requestUpdates.contains(pcp))
59                                 requestUpdates.add(pcp);
60                 }
61         }
62         
63         public static boolean update() throws Exception {
64             if (!PipingRules.enabled)
65                 return false;
66             
67                 if (requestUpdates.size() == 0)
68                         return false;
69                 
70                 List<PipeControlPoint> temp = new ArrayList<PipeControlPoint>(requestUpdates.size());
71                 synchronized(updateMutex) {
72                         temp.addAll(requestUpdates);
73                         requestUpdates.clear();
74                 }
75                 synchronized (ruleMutex) {
76                         currentUpdates.clear();
77                         currentUpdates.addAll(temp);
78                         // TODO : we should remove already processed control points from currentUpdates after each _positionUpdate call.
79                         for (PipeControlPoint pcp : currentUpdates)
80                                 _positionUpdate(pcp, true);
81                         currentUpdates.clear();
82                 }
83                 synchronized(updateMutex) {
84                         requestUpdates.removeAll(temp);
85                 }
86                 
87                 return true;
88         }
89         
90         public static boolean positionUpdate(PipeControlPoint pcp) throws Exception {
91                 
92                 return positionUpdate(pcp, true);
93         }
94         
95         public static boolean positionUpdate(PipeControlPoint pcp, boolean allowIR) throws Exception {
96                 synchronized (ruleMutex) {
97                         currentUpdates.add(pcp);
98                         boolean b = _positionUpdate(pcp, allowIR);
99                         currentUpdates.clear();
100                         return b;
101                 }
102                 
103         }
104         
105         private static boolean _positionUpdate(PipeControlPoint pcp, boolean allowIR) throws Exception {
106                 if (updating || !enabled)
107                         return true;
108                 if (pcp.getPipeRun() == null)
109                         return false;
110                 try {
111                         if (DEBUG) System.out.println("PipingRules " + pcp);
112                         updating = true;
113                         allowInsertRemove = allowIR;
114                         triedIR = false;
115                         validate(pcp.getPipeRun());
116                         if (pcp.isPathLegEnd()) {
117                                 updatePathLegEndControlPoint(pcp); // FIXME: Rules won't work properly, if they are not run twice.
118                                 updatePathLegEndControlPoint(pcp);
119                         } else {
120                                 updateInlineControlPoint(pcp);
121                                 updateInlineControlPoint(pcp);
122                         }
123                         validate(pcp.getPipeRun());
124                         if (!allowInsertRemove)
125                                 return !triedIR;
126                         return true;
127                 } finally {
128                         updating = false;
129 //                      System.out.println("PipingRules done " + pcp);
130                 }
131         }
132         
133         public static void setEnabled(boolean enabled) {
134                 PipingRules.enabled = enabled;
135                 if(!enabled)
136                         currentUpdates.clear();
137         }
138         
139         public static boolean isEnabled() {
140                 return enabled;
141         }
142         
143 //      private void commit() {
144 //              root.getNodeMap().commit();
145 //      }
146
147         public static class ExpandIterInfo {
148                 // these two are turn control points
149                 private PipeControlPoint start;
150                 private PipeControlPoint end;
151                 private int type;
152
153                 public ExpandIterInfo() {
154
155                 }
156
157                 public ExpandIterInfo(PipeControlPoint tcp, int type) {
158                         if (type == REMOVE_START)
159                                 start = tcp;
160                         else
161                                 end = tcp;
162                         this.type = type;
163                 }
164
165                 public ExpandIterInfo(PipeControlPoint start, PipeControlPoint end) {
166                         this.start = start;
167                         this.end = end;
168                         this.type = REMOVE_BOTH;
169                 }
170
171                 public PipeControlPoint getEnd() {
172                         return end;
173                 }
174
175                 public void setEnd(PipeControlPoint end) {
176                         this.end = end;
177                 }
178
179                 public PipeControlPoint getStart() {
180                         return start;
181                 }
182
183                 public void setStart(PipeControlPoint start) {
184                         this.start = start;
185                 }
186
187                 public int getType() {
188                         return type;
189                 }
190
191                 public void setType(int type) {
192                         this.type = type;
193                 }
194
195         }
196
197         private static void updatePathLegEndControlPoint(PipeControlPoint pcp) throws Exception {
198                 if (DEBUG)
199                         System.out.println("PipingRules.updatePathLegEndControlPoint() " + pcp);
200                 if (pcp.getNext() != null) {
201                         updatePathLegNext(pcp, pcp, PathLegUpdateType.NEXT_S);
202                 }
203                 if (pcp.getPrevious() != null) {
204                         updatePathLegPrev(pcp, pcp, PathLegUpdateType.PREV_S);
205                 }
206
207         }
208
209         private static void updateInlineControlPoint(PipeControlPoint pcp) throws Exception {
210                 if (DEBUG)
211                         System.out.println("PipingRules.updateInlineControlPoint() " + pcp);
212                 PipeControlPoint start = pcp.findPreviousEnd();
213                 updatePathLegNext(start, pcp, PathLegUpdateType.NONE);
214         }
215
216         private static PipeControlPoint insertElbow(PipeControlPoint pcp1, PipeControlPoint pcp2, Vector3d pos) throws Exception{
217                 if (DEBUG)
218                         System.out.println("PipingRules.insertElbow() " + pcp1 + " " + pcp2 + " " + pos);
219                 if (pcp1.getNext() == pcp2 && pcp2.getPrevious() == pcp1) {
220                         
221                 } else if (pcp1.getNext() == pcp2 && pcp1.isDualInline() && pcp2.getPrevious() == pcp1.getDualSub()) {
222                         pcp1 = pcp1.getDualSub();       
223                 } else if (pcp1.getPrevious() == pcp2 && pcp2.getNext() == pcp1) {
224                         PipeControlPoint t = pcp1;
225                         pcp1 = pcp2;
226                         pcp2 = t;
227                 } else if (pcp2.isDualInline() && pcp1.getPrevious() == pcp2.getDualSub() && pcp2.getNext() == pcp1) {
228                         PipeControlPoint t = pcp1;
229                         pcp1 = pcp2.getDualSub();
230                         pcp2 = t;
231                 } else {
232                         throw new RuntimeException();
233                 }
234                 TurnComponent elbow = ComponentUtils.createTurn((P3DRootNode)pcp1.getRootNode());
235                 PipeControlPoint pcp = elbow.getControlPoint();
236                 if (pcp1.isDualInline())
237                         pcp1 = pcp1.getDualSub();
238                 String name = pcp1.getPipeRun().getUniqueName("Elbow");
239                 elbow.setName(name);
240                 pcp1.getPipeRun().addChild(elbow);
241
242                 pcp.insert(pcp1, pcp2);
243
244                 pcp.setWorldPosition(pos);
245                 validate(pcp.getPipeRun());
246                 return pcp;
247         }
248         
249         private static PipeControlPoint insertStraight(PipeControlPoint pcp1, PipeControlPoint pcp2, Vector3d pos, double length) throws Exception {
250                 if (DEBUG)
251                         System.out.println("PipingRules.insertStraight() " + pcp1 + " " + pcp2 + " " + pos);
252                 if (pcp1.getNext() == pcp2 && pcp2.getPrevious() == pcp1) {
253                         
254                 } else if (pcp1.getNext() == pcp2 && pcp1.isDualInline() && pcp2.getPrevious() == pcp1.getDualSub()) {
255                         pcp1 = pcp1.getDualSub();       
256                 } else if (pcp1.getPrevious() == pcp2 && pcp2.getNext() == pcp1) {
257                         PipeControlPoint t = pcp1;
258                         pcp1 = pcp2;
259                         pcp2 = t;
260                 } else if (pcp2.isDualInline() && pcp1.getPrevious() == pcp2.getDualSub() && pcp2.getNext() == pcp1) {
261                         PipeControlPoint t = pcp1;
262                         pcp1 = pcp2.getDualSub();
263                         pcp2 = t;
264                 } else {
265                         throw new RuntimeException();
266                 }
267                 InlineComponent component = ComponentUtils.createStraight((P3DRootNode)pcp1.getRootNode());
268                 PipeControlPoint scp = component.getControlPoint();
269                 if (pcp1.isDualInline())
270                         pcp1 = pcp1.getDualSub();
271                 String name = pcp1.getPipeRun().getUniqueName("Pipe");
272                 component.setName(name);
273                 pcp1.getPipeRun().addChild(component);
274                 
275                 scp.insert(pcp1, pcp2);
276
277                 scp.setWorldPosition(pos);
278                 scp.setLength(length);
279                 validate(scp.getPipeRun());
280                 return scp;
281         }
282         
283         private static PipeControlPoint insertStraight(PipeControlPoint pcp, Direction direction , Vector3d pos, double length) throws Exception {
284                 if (DEBUG)
285                         System.out.println("PipingRules.insertStraight() " + pcp + " " + direction + " " + pos);
286                 
287                 InlineComponent component = ComponentUtils.createStraight((P3DRootNode)pcp.getRootNode());
288                 PipeControlPoint scp = component.getControlPoint();
289                 if (pcp.isDualInline() && direction == Direction.NEXT)
290                         pcp = pcp.getDualSub();
291                 String name = pcp.getPipeRun().getUniqueName("Pipe");
292                 component.setName(name);
293                 pcp.getPipeRun().addChild(component);
294                 
295                 scp.insert(pcp,direction);
296
297                 scp.setWorldPosition(pos);
298                 scp.setLength(length);
299                 validate(scp.getPipeRun());
300                 return scp;
301         }
302
303         private static void updatePathLegNext(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
304
305                 UpdateStruct2 us = createUS(start, Direction.NEXT, 0, new ArrayList<ExpandIterInfo>(), updated);
306                 if (lengthChange == PathLegUpdateType.NONE) {
307                         if (start.equals(updated))
308                                 lengthChange = PathLegUpdateType.NEXT;
309                         else if (us.end.equals(updated))
310                                 lengthChange = PathLegUpdateType.PREV;
311                 }
312                 if (us == null) {
313                     System.out.println("Null update struct " + start);
314                     return; 
315                 }
316                 updatePathLeg(us, lengthChange);
317         }
318         
319         private static void updatePathLegPrev(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
320                 // TODO: this method is not symmetric with updatePathLegNext, which may alter lengthChange parameter?
321                 UpdateStruct2 us = createUS(start, Direction.PREVIOUS, 0, new ArrayList<ExpandIterInfo>(), updated);
322 //        if (lengthChange == PathLegUpdateType.NONE) {
323 //            if (start.equals(updated))
324 //                lengthChange = PathLegUpdateType.NEXT;
325 //            else if (us.end.equals(updated))
326 //                lengthChange = PathLegUpdateType.PREV;
327 //        }
328                 if (us == null) {
329             System.out.println("Null update struct " + start);
330             return; 
331         }
332                 updatePathLeg(us, lengthChange);
333         }
334
335         private static class UpdateStruct2 {
336                 public PipeControlPoint start;
337                 public Vector3d startPoint;
338                 public ArrayList<PipeControlPoint> list;
339                 public PipeControlPoint end;
340                 public Vector3d endPoint;
341                 public Vector3d dir;
342                 public Vector3d offset;
343                 public boolean hasOffsets;
344                 public int iter;
345                 public boolean reversed;
346                 public ArrayList<ExpandIterInfo> toRemove;
347                 public PipeControlPoint updated;
348
349                 public UpdateStruct2(PipeControlPoint start, Vector3d startPoint, ArrayList<PipeControlPoint> list, PipeControlPoint end, Vector3d endPoint, Vector3d dir, Vector3d offset, boolean hasOffsets, int iter, boolean reversed, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated) {
350                         if (start == null || end == null)
351                                 throw new NullPointerException();
352                         this.start = start;
353                         this.startPoint = startPoint;
354                         this.list = list;
355                         this.end = end;
356                         this.endPoint = endPoint;
357                         this.dir = dir;
358                         this.offset = offset;
359                         this.hasOffsets = hasOffsets;
360                         this.iter = iter;
361                         this.reversed = reversed;
362                         this.toRemove = toRemove;
363                         this.updated = updated;
364                         
365                         if (!MathTools.isValid(startPoint) || 
366                                 !MathTools.isValid(endPoint) || 
367                                 !MathTools.isValid(dir)) {
368                                 throw new RuntimeException();
369                         }
370                 }
371
372                 public String toString() {
373                         return start + " " + end+ " " + dir + " " + hasOffsets + " " + offset + " " + iter + " " + toRemove.size();
374                 }
375
376         }
377
378         @SuppressWarnings("unused")
379         private static boolean calculateOffset(Vector3d startPoint, Vector3d endPoint, ArrayList<PipeControlPoint> list, Vector3d dir, Vector3d offset) {
380                 boolean hasOffsets = false;
381                 List<PipeControlPoint> offsets = new ArrayList<PipeControlPoint>(list.size());
382                 for (PipeControlPoint icp : list) {
383                         if (icp.isOffset()) {
384                                 offsets.add(icp);
385                         } else if (icp.isDualSub())
386                                 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
387                 }
388                 if (offsets.size() == 0) {
389                         dir.set(endPoint);
390                         dir.sub(startPoint);
391                         double l = dir.lengthSquared(); 
392                         if (l > MathTools.NEAR_ZERO)
393                                 dir.scale(1.0/Math.sqrt(l));
394                         offset.set(0.0, 0.0, 0.0);
395                         return false;
396                 } else {
397                         Vector3d sp = new Vector3d(startPoint);
398                         Point3d ep = new Point3d(endPoint);
399                         dir.set(ep);
400                         dir.sub(sp);
401                         double l = dir.lengthSquared(); 
402                         if (l > MathTools.NEAR_ZERO)
403                                 dir.scale(1.0/Math.sqrt(l));
404                         int iter = 100;
405                         while (iter >= 0) {
406                                 iter--;
407                                 offset.set(0.0, 0.0, 0.0);
408                                 
409                                 for (PipeControlPoint icp : offsets) {
410                                         Vector3d v = icp.getSizeChangeOffsetVector(dir);
411                                         offset.add(v);
412                                 }
413                                 Point3d nep = new Point3d(endPoint);
414                                 nep.sub(offset);
415                                 if (nep.distance(ep) < 0.0000000001) {
416                                         break;
417                                 } 
418                                 ep = nep;
419                                 dir.set(ep);
420                                 dir.sub(sp);
421                                 l = dir.lengthSquared(); 
422                                 if (l > MathTools.NEAR_ZERO)
423                                         dir.scale(1.0/Math.sqrt(l));
424                         }
425                         hasOffsets = true;
426                 }
427                 
428                 if (DEBUG && hasOffsets)
429                         System.out.println("calcOffset s:"+ startPoint + " e:" + endPoint + " d:" + dir + " o:"+offset) ;
430                 return hasOffsets;
431         }
432         
433         private static UpdateStruct2 createUS(PipeControlPoint start, Direction direction, int iter, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated) {
434                 ArrayList<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
435                 PipeControlPoint end = null;
436                 if (direction == Direction.NEXT) {
437                         end = start.findNextEnd(list);
438                 } else {
439                         ArrayList<PipeControlPoint> prevList = new ArrayList<PipeControlPoint>();
440                         PipeControlPoint tend = start.findPreviousEnd(prevList);
441                         for (PipeControlPoint icp : prevList) {
442                                 if (icp.isDualSub()) {
443                                         list.add(0, icp.getParentPoint());
444                                 } else {
445                                         list.add(0, icp);
446                                 }
447                         }  
448                         end = start;
449                         start = tend;
450                 }
451                 if (start == end)
452                         return null;
453                 boolean hasOffsets = false;
454                 Vector3d offset = new Vector3d();
455                 Vector3d startPoint = start.getWorldPosition();
456                 Vector3d endPoint = end.getWorldPosition();
457                 Vector3d dir = new Vector3d();
458                 hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset);
459                 return new UpdateStruct2(start, startPoint, list, end, endPoint, dir, offset, hasOffsets, iter, direction == Direction.PREVIOUS, toRemove, updated);
460         }
461         
462         private static boolean asDirected(PipeControlPoint pcp, Direction direction) {
463                 if (pcp.isDirected())
464                         return true;
465                 if (pcp.asFixedAngle()) {
466                         if (!pcp._getReversed())
467                                 return direction == Direction.NEXT;
468                         else
469                                 return direction == Direction.PREVIOUS;
470                 }
471                 return false;
472         }
473         
474         private static Vector3d direction(PipeControlPoint pcp, Direction direction) {
475                 return pcp.getDirection(direction);
476         }
477  
478         private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
479                 int directed = 0;
480                 if (asDirected(u.start, Direction.NEXT))
481                         directed++;
482                 if (asDirected(u.end, Direction.PREVIOUS))
483                         directed++;
484                 switch (directed) {
485                 case 0:
486                         updateFreePathLeg(u, lengthChange);
487                         break;
488                 case 1:
489                         updateDirectedPathLeg(u, lengthChange);
490                         break;
491                 case 2:
492                         updateDualDirectedPathLeg(u, lengthChange);
493                         break;
494                 }
495
496         }
497
498         private static void updateFreePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
499                 if (DEBUG)
500                         System.out.println("PipingRules.updateFreePipeRun " + u + " " + lengthChange);
501                 checkExpandPathLeg(u, lengthChange);
502                 if (u.start.isInline() || u.end.isInline() || u.start.asFixedAngle()|| u.end.asFixedAngle())
503                         processPathLeg(u, true, false);
504         }
505
506         private static void updateInlineControlPoints(UpdateStruct2 u, boolean checkSizes) throws Exception{
507                 if (DEBUG)
508                         System.out.println("PipingRules.updateInlineControlPoints() " + u);
509
510                 Vector3d start = new Vector3d(u.startPoint);
511                 Vector3d end = new Vector3d(u.endPoint);
512                 
513                 if (checkSizes) {
514                         // create offsets for leg ends.
515                         MathTools.mad(start, u.dir, u.start.getInlineLength());
516                         MathTools.mad(end, u.dir, -u.end.getInlineLength());
517                 }
518                 
519                 boolean recalcline = false;
520                 if (!u.hasOffsets) {
521                         
522                         
523                         for (PipeControlPoint icp : u.list) {
524                                 updateInlineControlPoint(icp, start, end, u.dir);
525                                 
526                                 if (icp.isOffset()) {
527                                         // TODO : offset vector is already calculated and should be cached
528                                         Vector3d off = icp.getSizeChangeOffsetVector(u.dir);
529                                         updateOffsetPoint(icp, off);
530                                 }
531                         }
532                         if (!checkSizes)
533                                 return;                 
534
535                         ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<PipeControlPoint>();
536                         pathLegPoints.add(u.start);
537                         for (PipeControlPoint icp : u.list) {
538                                 // updateInlineControlPoint(icp, u.startPoint,
539                                 // u.endPoint,u.dir);
540                                 updateBranchControlPointBranches(icp);
541                                 pathLegPoints.add(icp);
542                         }
543                         pathLegPoints.add(u.end);
544
545                         // TODO : values can be cached in the loop
546                         for (int i = 0; i < pathLegPoints.size(); i++) {
547                                 PipeControlPoint icp = pathLegPoints.get(i);
548
549                                 PipeControlPoint prev = i > 0 ? pathLegPoints.get(i - 1) : null;
550                                 PipeControlPoint next = i < pathLegPoints.size() - 1 ? pathLegPoints.get(i + 1) : null;
551
552                                 if (icp.isVariableLength()) {
553                                         if (prev != null && next != null) {
554                                                 
555                                                 recalcline = recalcline | updateVariableLength(icp,  prev, next);
556
557                                         } else {
558                                                 // this is variable length component at the end of the
559                                                 // piperun.
560                                                 // the problem is that we want to keep unconnected end
561                                                 // of the component in the same
562                                                 // place, but center of the component must be moved.
563                                                 updateVariableLengthEnd(icp, prev != null ? prev : next);
564                                         }
565
566
567                                 } else if (prev != null && !prev.isVariableLength()) {
568                                         // If this and previous control point are not variable
569                                         // length pcps, we'll have to check if there is no empty
570                                         // space between them.
571                                         // I there is, we'll have to create new variable length
572                                         // component between them.
573                                         recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
574                                 }
575                         }
576                 } else { // with offset
577                         Vector3d sp = new Vector3d(start);
578                         Vector3d ep = new Vector3d(end);
579                         ep.sub(u.offset);
580                         
581                         ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<PipeControlPoint>();
582                         pathLegPoints.add(u.start);
583
584                         for (PipeControlPoint icp : u.list) {
585                                 updateInlineControlPoint(icp, sp, ep, u.dir);
586                                 updateBranchControlPointBranches(icp);
587                                 pathLegPoints.add(icp);
588                                 if (icp.isOffset()) {
589                                         // TODO : offset vector is already calculated and should be
590                                         // cached
591                                         Vector3d  offset = icp.getSizeChangeOffsetVector(u.dir);
592                                         updateOffsetPoint(icp, offset);
593                                         sp.add(offset);
594                                         ep.add(offset);
595                                 }
596                         }
597                         pathLegPoints.add(u.end);
598                         
599                         if (!checkSizes)
600                                 return; 
601                         
602                         sp = new Vector3d(u.startPoint);
603                         ep = new Vector3d(u.endPoint);
604                         ep.sub(u.offset);
605                         
606                         for (int i = 0; i < pathLegPoints.size(); i++) {
607                                 PipeControlPoint icp = pathLegPoints.get(i);
608
609                                 PipeControlPoint prev = i > 0 ? pathLegPoints.get(i - 1) : null;
610                                 PipeControlPoint next = i < pathLegPoints.size() - 1 ? pathLegPoints.get(i + 1) : null;
611                                 
612                                 if (prev != null && prev.isDualInline())
613                                         prev = prev.getDualSub();
614                                 
615
616                                 if (icp.isVariableLength()) {
617                                         if (prev != null && next != null) {
618                                                 recalcline = recalcline | updateVariableLength(icp,  prev, next);
619
620                                         } else {
621                                                 // this is variable length component at the end of the
622                                                 // piperun.
623                                                 // the problem is that we want to keep unconnected end
624                                                 // of the component in the same
625                                                 // place, but center of the component must be moved.
626                                                 updateVariableLengthEnd(icp, prev != null ? prev : next);
627                                         }
628                                 } else if (prev != null && !prev.isVariableLength()) {
629                                         // If this and previous control point are not variable
630                                         // length pcps, we'll have to check if there is no empty
631                                         // space between them.
632                                         // I there is, we'll have to create new variable length
633                                         // component between them.
634                                         recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
635                                 }
636                                 if (icp.isOffset()) {
637                                         // TODO : offset vector is already calculated and should be
638                                         // cached
639                                         Vector3d  offset = icp.getSizeChangeOffsetVector(u.dir);
640                                         sp.add(offset);
641                                         ep.add(offset);
642                                 }
643                         }
644                 }
645                 if (recalcline) {
646                         u.list.clear();
647                         u.start.findNextEnd(u.list);
648                 }
649         }
650         
651         private static boolean updateVariableLength(PipeControlPoint icp, PipeControlPoint prev,  PipeControlPoint next) {
652                 Vector3d prevPos = prev.getWorldPosition();
653                 Vector3d nextPos = next.getWorldPosition();
654                 
655                 Vector3d dir = new Vector3d(nextPos);
656                 dir.sub(prevPos);
657                 double l = dir.lengthSquared(); // distance between
658                                                                                 // control points
659                                                                                 // (square)
660                 double l2prev = prev.getInlineLength(); // distance
661                                                                                                                                         // taken
662                                                                                                                                         // by
663                                                                                                                                         // components
664                 double l2next = next.getInlineLength();
665                 double l2 = l2prev + l2next;
666                 double l2s = MathTools.square(l2);
667                 if (l2s < l) { // check if there is enough space for
668                                                 // variable length component.
669                         // components fit
670                         dir.normalize();
671                         double length = Math.sqrt(l) - l2; // true length of
672                                                                                                 // the variable
673                                                                                                 // length
674                                                                                                 // component
675                         dir.scale(length * 0.5 + l2prev); // calculate
676                                                                                                 // center
677                                                                                                 // position of
678                                                                                                 // the component
679                         dir.add(prevPos);
680                         icp.setWorldPosition(dir);
681                         icp.setLength(length);
682                         return false;
683                 } else {
684                         // components leave no space to the component and it
685                         // must be removed
686                         
687                         if (icp.isDeletable()) {
688                             if (!allowInsertRemove) {
689                                 icp.setLength(0.0001);
690                                 triedIR = true;
691                                 return false;
692                             }
693                                 if (DEBUG)
694                                         System.out.println("PipingRules.updateVariableLength removing " + icp);
695                                 icp._remove();
696                                 return true;
697                         }
698                         return false;
699                 }
700         }
701         
702         private static boolean possibleVaribleLengthInsert(PipeControlPoint icp, PipeControlPoint prev) throws Exception{
703                 Vector3d currentPos = icp.getWorldPosition();
704                 Vector3d prevPos = prev.getWorldPosition();
705                 Vector3d dir = new Vector3d(currentPos);
706                 dir.sub(prevPos);
707                 double l = dir.lengthSquared();
708                 double l2prev = prev.getInlineLength();
709                 double l2next = icp.getInlineLength();
710                 double l2 = l2prev + l2next;
711                 double l2s = l2 * l2;
712                 if (l > l2s) {
713                         if (allowInsertRemove) {
714                                 dir.normalize();
715                                 double length = Math.sqrt(l) - l2; // true length of the
716                                                                                                         // variable length
717                                                                                                         // component
718                                 dir.scale(length * 0.5 + l2prev); // calculate center
719                                                                                                         // position of the
720                                                                                                         // component
721                                 dir.add(prevPos);
722                                 insertStraight(prev, icp, dir, length);
723                                 return true;
724                         } else {
725                                 triedIR = true;
726                         }
727                 }
728                 return false;
729         }
730         
731         private static void updateVariableLengthEnd(PipeControlPoint icp,  PipeControlPoint prev) {
732                 Vector3d currentPos = icp.getWorldPosition();
733                 Vector3d prevPos = prev.getWorldPosition();
734                 
735                 Vector3d dir = new Vector3d();
736                 dir.sub(currentPos, prevPos);
737                 
738                 boolean simple = currentUpdates.contains(icp);
739                 if (simple) {
740                         // Update based on position -> adjust length
741                         double currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
742                         icp.setLength(currentLength);
743                 } else {
744                         // Update based on neighbour movement -> adjust length and position, so that free end stays in place.
745                         double currentLength = icp.getLength();
746                         if (currentLength < MathTools.NEAR_ZERO) {
747                                 currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
748                         }
749                         
750                         if (dir.lengthSquared() > MathTools.NEAR_ZERO)
751                                 dir.normalize();
752                         Point3d endPos = new Point3d(dir);
753                         endPos.scale(currentLength * 0.5);
754                         endPos.add(currentPos); // this is the free end of the component
755         
756                         double offset = prev.getInlineLength();
757                         Point3d beginPos = new Point3d(dir);
758                         beginPos.scale(offset);
759                         beginPos.add(prevPos); // this is the connected end of the component
760         
761                         double l = beginPos.distance(endPos);
762                         
763                         if (Double.isNaN(l))
764                                 System.out.println("Length for " + icp + " is NaN");
765         
766                         dir.scale(l * 0.5);
767                         beginPos.add(dir); // center position
768         
769                         if (DEBUG)
770                                 System.out.println("PipingRules.updateInlineControlPoints() setting variable length to " + l);
771                         icp.setLength(l);
772         
773                         icp.setWorldPosition(new Vector3d(beginPos));
774                 }
775         }
776
777         private static void ppNoOffset(UpdateStruct2 u) throws Exception {
778                 if (DEBUG)
779                         System.out.println("PipingRules.ppNoOffset() " + u);
780                 Vector3d offset = new Vector3d();
781                 if (u.hasOffsets) {
782                         u.dir.normalize();
783                         for (PipeControlPoint icp : u.list) {
784                                 if (icp.isOffset()) {
785                                         offset.add(icp.getSizeChangeOffsetVector(u.dir));
786                                 } else if (icp.isDualSub())
787                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
788                         }
789                 }
790                 u.offset = offset;
791                 checkExpandPathLeg(u, PathLegUpdateType.NONE);
792         }
793
794         private static void ppNoDir(PipeControlPoint start, Vector3d startPoint, ArrayList<PipeControlPoint> list, PipeControlPoint end, Vector3d endPoint, boolean hasOffsets, int iter, boolean reversed, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated) throws Exception {
795                 if (DEBUG)
796                         System.out.println("PipingRules.ppNoDir() " + start + " " + end + " " + iter + " " + toRemove.size());
797                 // FIXME : extra loop (dir should be calculated here)
798                 Vector3d dir = new Vector3d();
799                 Vector3d offset = new Vector3d();
800                 hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset);
801                 ppNoOffset(new UpdateStruct2(start, startPoint, list, end, endPoint, dir, null, hasOffsets, iter, reversed, toRemove, updated));
802         }
803
804         private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
805                 checkExpandPathLeg(u, lengthChange, u.updated.isInline() && u.updated.isOffset());
806         }
807         
808         private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean updateEnds) throws Exception {
809                 if (DEBUG)
810                         System.out.println("PipingRules.checkExpandPathLeg() " + u + " " + lengthChange);
811                 if (lengthChange != PathLegUpdateType.NONE) {
812                         // FIXME : turns cannot be checked before inline cps are updated,
813                         // since their position affects calculation of turns
814                         processPathLeg(u, updateEnds, false);
815                         int type = checkTurns(u, lengthChange);
816                         if (type == REMOVE_NONE) {
817                                 processPathLeg(u, updateEnds, true);
818                         } else {
819                                 expandPathLeg(u, type);
820                         }
821                 } else {
822                         processPathLeg(u, updateEnds, true);
823                 }
824         }
825
826         private static void updateDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
827                 if (DEBUG)
828                         System.out.println("PipingRules.updateDirectedPipeRun() " + u + " " + lengthChange);
829                 PipeControlPoint dcp;
830                 PipeControlPoint other;
831                 boolean canMoveOther = false;
832                 boolean dcpStart = false;
833                 boolean inlineEnd = false;
834                 Vector3d position;
835                 if (asDirected(u.start, Direction.NEXT)) {
836                         dcp = u.start;
837                         other = u.end;
838                         position = u.startPoint;
839                         dcpStart = true;
840                         if (!u.reversed)
841                                 canMoveOther = true;
842                         inlineEnd = u.end.isInline();
843                                 
844                 } else {
845                         dcp = u.end;
846                         other = u.start;
847                         position = u.endPoint;
848                         if (u.reversed)
849                                 canMoveOther = true;
850                         inlineEnd = u.start.isInline();
851                 }
852
853                 Vector3d directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS);
854                 if (directedDirection == null) {
855                         //updateTurnControlPointTurn(dcp, dcp.getPrevious(), dcp.getNext());
856                         updateTurnControlPointTurn(dcp, null, null);
857                         directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS);
858                         if (directedDirection == null) {
859                                 return;
860                         }
861                 }
862                 Point3d directedEndPoint = new Point3d(u.endPoint);
863                 if (u.hasOffsets)
864                         directedEndPoint.add(u.offset);
865
866                 double mu[] = new double[2];
867
868                 Vector3d closest;
869                 Vector3d t = new Vector3d();
870
871                 if (dcpStart) {
872                         closest = MathTools.closestPointOnStraight(directedEndPoint, u.startPoint, directedDirection, mu);
873                         t.sub(closest, directedEndPoint);
874                 } else {
875                         closest = MathTools.closestPointOnStraight(u.startPoint, directedEndPoint, directedDirection, mu);
876                         t.sub(closest, u.startPoint);
877                 }
878
879                 double distance = t.length();
880                 boolean aligned = (distance < ALLOWED_OFFSET);
881                 if (aligned) {
882                         if (u.start.isInline() || u.end.isInline() || u.start.asFixedAngle() || u.end.asFixedAngle())
883                                 processPathLeg(u, true, false);
884                         checkExpandPathLeg(u, lengthChange, inlineEnd);
885                         
886                 } else {
887                         if (u.iter > 0) {
888                                 backIter(u);
889                         } else {
890                                 PipeControlPoint nextToMoved;
891
892                                 if (u.list.size() > 0)
893                                         if (dcpStart)
894                                                 nextToMoved = u.list.get(0);
895                                         else
896                                                 nextToMoved = u.list.get(u.list.size() - 1);
897                                 else if (dcpStart)
898                                         nextToMoved = u.end;
899                                 else
900                                         nextToMoved = u.start;
901                                 if (other.isVariableAngle()) {
902
903                                         // TODO calculate needed space from next run end.
904                                     double space = spaceForTurn(other);
905                                         if (mu[0] < space) {
906                                                 if (dcpStart) {
907                                                         closest.set(u.startPoint);
908                                                 } else {
909                                                         closest.set(u.endPoint);
910                                                 }
911                                                 Vector3d v = new Vector3d(directedDirection);
912                                                 v.scale(space);
913                                                 closest.add(v);
914                                         }
915
916                                         if (canMoveOther) {
917                                                 if (DEBUG)
918                                                         System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + closest);
919                                                 other.setWorldPosition(closest);
920                                                 if (dcpStart) {
921                                                         ppNoOffset(new UpdateStruct2(u.start, u.startPoint, u.list, u.end, new Vector3d(closest), directedDirection, null, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated));
922                                                         if (u.end.getNext() != null)
923                                                                 updatePathLegNext(u.end, u.updated, PathLegUpdateType.NEXT);
924                                                 } else {
925                                                         ppNoOffset(new UpdateStruct2(u.start, new Vector3d(closest), u.list, u.end, u.endPoint, directedDirection, null, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated));
926                                                         if (u.start.getPrevious() != null)
927                                                                 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.PREV);
928                                                 }
929                                         } else {
930                                                 // TODO : calculate needed space from next run end.
931                                                 if (allowInsertRemove)
932                                                         insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
933                                                         
934                                                 else
935                                                         triedIR = true;
936                                         }
937                                 } else if (other.isNonDirected() && other.getParentPoint() != null) {
938                                         // FIXME : this code was for updating branches
939                                         Vector3d bintersect = new Vector3d();
940                                         PipeControlPoint bcp = other.getParentPoint();
941                                         if (bcp != null && canMoveOther) {
942                                                 Point3d bstart = new Point3d();
943                                                 Point3d bend = new Point3d();
944                                                 Vector3d bdir = new Vector3d();
945                                                 bcp.getInlineControlPointEnds(bstart, bend, bdir);
946                                                 Vector3d nintersect = new Vector3d();
947
948                                                 MathTools.intersectStraightStraight(position, directedDirection, bend, bdir, nintersect, bintersect, mu);
949                                                 Vector3d dist = new Vector3d(nintersect);
950                                                 dist.sub(bintersect);
951                                                 canMoveOther = mu[1] > 0.0 && mu[1] < 1.0 && dist.lengthSquared() < 0.01;
952                                         } else {
953                                                 // TODO : endControlPoints are undirected: calculcate
954                                                 // correct position for it
955                                                 throw new UnsupportedOperationException("not implemented");
956                                         }
957                                         if (canMoveOther) {
958                                                 if (DEBUG)
959                                                         System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + bintersect);
960                                                 // is required branch position is in possible range
961                                                 bcp.setWorldPosition(bintersect);
962                                                 if (dcpStart) {
963                                                         checkExpandPathLeg(new UpdateStruct2(u.start, u.startPoint, u.list, u.end, new Vector3d(bintersect), directedDirection, u.offset, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated), lengthChange);
964                                                 } else {
965                                                         checkExpandPathLeg(new UpdateStruct2(u.start, new Vector3d(bintersect), u.list, u.end, u.endPoint, directedDirection, u.offset, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated), lengthChange);
966                                                 }
967                                         } else {
968                                                 // branch cannot be moved into right position, new turn
969                                                 // / elbow must be inserted
970                                                 if (allowInsertRemove)
971                                                         insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
972                                                 else
973                                                         triedIR = true;
974                                         }
975
976                                 } else { // assume that control point cannot be moved, but can
977                                                         // be rotated
978                                         if (allowInsertRemove)
979                                                 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
980                                         else
981                                                 triedIR = true;
982                                 }
983                         }
984                 }
985                 
986                 
987         }
988
989         private static void updateDualDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
990                 if (DEBUG)
991                         System.out.println("PipingRules.updateDualDirectedPipeRun() " + u + " " + lengthChange);
992                 
993                 PipeControlPoint dcp1 = u.start;
994                 PipeControlPoint dcp2 = u.end;
995                 Point3d position1 = new Point3d(u.startPoint);
996                 Point3d position2 = new Point3d(u.endPoint);
997                 Point3d position1offset = new Point3d(position1);
998                 position1offset.sub(u.offset);
999                 Point3d position2offset = new Point3d(position2);
1000                 position2offset.add(u.offset);
1001                 Vector3d dir1 = direction(dcp1, Direction.NEXT);
1002                 Vector3d dir2 = direction(dcp2, Direction.PREVIOUS);
1003                 Vector3d p1 = MathTools.closestPointOnStraight(position1offset, position2, dir2);
1004                 Vector3d p2 = MathTools.closestPointOnStraight(position2offset, position1, dir1);
1005                 double d1 = position1.distance(new Point3d(p1));
1006                 double d2 = position2.distance(new Point3d(p2));
1007
1008                 boolean aligned = (d1 < ALLOWED_OFFSET && d2 < ALLOWED_OFFSET);
1009                 if (aligned) {
1010                         processPathLeg(u);
1011                 } else {
1012                         if (u.iter > 0) {
1013                                 backIter(u);
1014                         } else if (allowInsertRemove){
1015                                 PipeControlPoint dcp;
1016                                 PipeControlPoint next;
1017                                 if (!u.reversed) {
1018                                         dcp = dcp1;
1019                                         if (u.list.size() > 0)
1020                                                 next = u.list.get(0);
1021                                         else
1022                                                 next = dcp2;
1023                                 } else {
1024                                         dcp = dcp2;
1025                                         if (u.list.size() > 0)
1026                                                 next = u.list.get(u.list.size() - 1);
1027                                         else
1028                                                 next = dcp1;
1029                                 }
1030                                 
1031                                 p1 = dcp.getWorldPosition();
1032                                 Vector3d v = new Vector3d();
1033                                 if (!u.reversed)
1034                                         v.set(dir1);
1035                                 else
1036                                         v.set(dir2);
1037                                 
1038                                 // Reserve space for 90 deg elbow
1039                                 double off = dcp1.getPipeRun().getTurnRadius();
1040                                 v.scale(off);
1041                                 p1.add(v);
1042
1043                                 if (!u.reversed)
1044                                         p2 = MathTools.closestPointOnStraight(new Point3d(p1), position2, dir2);
1045                                 else
1046                                         p2 = MathTools.closestPointOnStraight(new Point3d(p1), position1, dir1);
1047
1048                                 // By default, the elbows are placed next to each other, by using 90 deg angles.
1049                                 // If the distance between elbows is not enough, we must move the other elbow (and create more shallow angle elbows)
1050                                 if (MathTools.distance(p1, p2) < off*2.05) {
1051                                         p2.add(v);
1052                                 }
1053                                 
1054                                 PipeControlPoint tcp1 = insertElbow(dcp, next, p1);
1055                                 PipeControlPoint tcp2 = insertElbow(tcp1, next, p2);
1056
1057                                 if (DEBUG)
1058                                         System.out.println("PipingRules.updateDualDirectedPipeRun() created two turns " + tcp1 + " " + tcp2);
1059
1060                                 if (!u.reversed) {
1061                                         Vector3d dd = new Vector3d(p2);
1062                                         dd.sub(p1);
1063                                         dir2.negate();
1064                                         updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1065                                         updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1066                                         if (!u.reversed)
1067                                                 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1068                                         else
1069                                                 updatePathLegPrev(tcp2, u.updated, PathLegUpdateType.NONE);
1070                                 } else {
1071                                         Vector3d dd = new Vector3d(p1);
1072                                         dd.sub(p2);
1073                                         dir2.negate();
1074                                         updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1075                                         updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1076                                         if (!u.reversed)
1077                                                 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1078                                         else
1079                                                 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.NONE);
1080                                 }
1081                         } else {
1082                                 triedIR = true;
1083                         }
1084                 }
1085                 
1086         }
1087         
1088         private static double spaceForTurn(PipeControlPoint tcp) {
1089                 // TODO : this returns now space for 90 deg turn.
1090                 // The challenge: position of tcp affects the turn angle, which then affects the required space. Perhaps we need to iterate...
1091                 // Additionally, if the path legs contain offset, using just positions of opposite path leg ends is not enough,    
1092                 return ((TurnComponent)tcp.getPipelineComponent()).getTurnRadius();
1093         }
1094
1095         private static void insertElbowUpdate(UpdateStruct2 u, PipeControlPoint dcp, PipeControlPoint next, boolean dcpStart, Vector3d position, Vector3d directedDirection) throws Exception{
1096
1097                 
1098 //              Vector3d closest = new Vector3d(position);
1099 //              closest.add(directedDirection);
1100                 
1101                 PipeControlPoint tcp = null;
1102                 Vector3d closest;
1103                 if (dcpStart) {
1104                         closest = MathTools.closestPointOnStraight(next.getWorldPosition(), position, directedDirection);
1105                         tcp = insertElbow(dcp, next, closest);
1106                 } else {
1107                         closest = MathTools.closestPointOnStraight(dcp.getWorldPosition(), position, directedDirection);
1108                         tcp = insertElbow(next, dcp, closest);
1109                 }
1110                 // TODO properly calculate required distance between start and inserted elbow.
1111                 double d = MathTools.distance(position, closest);
1112                 double s = spaceForTurn(tcp);
1113                 if (d < s)  {
1114                         d = s - d;
1115                         Vector3d p = new Vector3d(directedDirection);
1116                         p.scale(d);
1117                         p.add(closest);
1118                         tcp.setPosition(p);
1119                         closest = p;
1120                 }
1121                 
1122                 
1123
1124                 if (DEBUG)
1125                         System.out.println("PipingRules.updateDirectedPipeRun() inserted " + tcp);
1126
1127                 if (dcpStart) {
1128                         // update pipe run from new turn to other end
1129                         ppNoDir(tcp, new Vector3d(closest), u.list, u.end, u.endPoint, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1130                         // update pipe run from directed to new turn
1131                         processPathLeg(new UpdateStruct2(u.start, u.startPoint, new ArrayList<PipeControlPoint>(), tcp, new Vector3d(closest), directedDirection, new Vector3d(), false, 0, false, new ArrayList<ExpandIterInfo>(), u.updated));
1132                 } else {
1133                         // update pipe run from other end to new turn
1134                         ppNoDir(u.start, u.startPoint, u.list, tcp, new Vector3d(closest), u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1135                         // update pipe run from new turn to directed
1136                         processPathLeg(new UpdateStruct2(tcp, new Vector3d(closest), new ArrayList<PipeControlPoint>(), u.end, u.endPoint, directedDirection, new Vector3d(), false, 0, false, new ArrayList<ExpandIterInfo>(), u.updated));
1137                 }
1138         }
1139
1140         /**
1141          * Checks if turns can be removed (turn angle near zero)
1142          */
1143         private static int checkTurns(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
1144                 if (DEBUG)
1145                         System.out.println("PipingRules.checkTurns() " + u.start + " " + u.end);
1146                 boolean startRemoved = false;
1147                 boolean endRemoved = false;
1148                 if (u.start.isVariableAngle()) {
1149                         // this won't work properly if inline control points are not updated
1150                         PipeControlPoint startPrev = u.start.getPrevious();
1151                         if (startPrev != null) {
1152                                 double a = updateTurnControlPointTurn(u.start, null, u.dir);
1153                                 if (a < MIN_TURN_ANGLE && u.start.isDeletable())
1154                                         startRemoved = true;
1155                                 else if (lengthChange == PathLegUpdateType.PREV || lengthChange == PathLegUpdateType.PREV_S) {
1156                                         PathLegUpdateType type;
1157                                         if (lengthChange == PathLegUpdateType.PREV_S)
1158                                                 type = PathLegUpdateType.PREV;
1159                                         else
1160                                                 type = PathLegUpdateType.NONE;
1161                                         updatePathLegPrev(u.start, u.start, type);
1162                                 }
1163                         }
1164                 }
1165                 if (u.end.isVariableAngle()) {
1166
1167                         PipeControlPoint endNext = u.end.getNext();
1168                         if (endNext != null) {
1169                                 // TODO: u.end, u.dir, null
1170                                 double a = updateTurnControlPointTurn(u.end, null, null);
1171                                 if (a < MIN_TURN_ANGLE && u.end.isDeletable())
1172                                         endRemoved = true;
1173                                 else if (lengthChange == PathLegUpdateType.NEXT || lengthChange == PathLegUpdateType.NEXT_S) {
1174                                         PathLegUpdateType type;
1175                                         if (lengthChange == PathLegUpdateType.NEXT_S)
1176                                                 type = PathLegUpdateType.NEXT;
1177                                         else
1178                                                 type = PathLegUpdateType.NONE;
1179                                         updatePathLegNext(u.end, u.end, type);
1180                                 }
1181                         }
1182                 }
1183                 if (DEBUG)
1184                         System.out.println("PipingRules.checkTurns() res " + startRemoved + " " + endRemoved);
1185                 if (!startRemoved && !endRemoved)
1186                         return REMOVE_NONE;
1187                 if (startRemoved && endRemoved)
1188                         return REMOVE_BOTH;
1189                 if (startRemoved)
1190                         return REMOVE_START;
1191                 return REMOVE_END;
1192         }
1193
1194         /**
1195          * Expands piperun search over turns that are going to be removed
1196          * 
1197          */
1198         private static void expandPathLeg(UpdateStruct2 u, int type) throws Exception {
1199                 if (DEBUG)
1200                         System.out.println("PipingRules.expandPipeline " + u.start + " " + u.end);
1201                 ArrayList<PipeControlPoint> newList = new ArrayList<PipeControlPoint>();
1202                 switch (type) {
1203                 case REMOVE_NONE:
1204                         throw new RuntimeException("Error in piping rules");
1205                 case REMOVE_START:
1206                         u.toRemove.add(new ExpandIterInfo(u.start, REMOVE_START));
1207                         u.start = u.start.findPreviousEnd();
1208                         u.startPoint = u.start.getPosition();
1209                         u.start.findNextEnd(newList);
1210                         newList.addAll(u.list);
1211                         u.list = newList;
1212                         break;
1213                 case REMOVE_END:
1214                         u.toRemove.add(new ExpandIterInfo(u.end, REMOVE_END));
1215                         u.end = u.end.findNextEnd(newList);
1216                         u.endPoint = u.end.getPosition();
1217                         u.list.addAll(newList);
1218                         break;
1219                 case REMOVE_BOTH:
1220                         u.toRemove.add(new ExpandIterInfo(u.start, u.end));
1221                         u.start = u.start.findPreviousEnd();
1222                         u.startPoint = u.start.getPosition();
1223                         u.start.findNextEnd(newList);
1224                         newList.addAll(u.list);
1225                         u.list = newList;
1226                         newList = new ArrayList<PipeControlPoint>();
1227                         u.end = u.end.findNextEnd(newList);
1228                         u.endPoint = u.end.getPosition();
1229                         u.list.addAll(newList);
1230                         break;
1231                 default:
1232                         throw new RuntimeException("Error in piping rules");
1233
1234                 }
1235                 u.offset = new Vector3d();
1236                 if (u.hasOffsets) {
1237                         u.dir.normalize();
1238                         for (PipeControlPoint icp : u.list) {
1239                                 if (icp.isOffset()) {
1240                                         u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1241                                 } else if (icp.isDualSub())
1242                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1243                         }
1244                 }
1245                 if (DEBUG)
1246                         System.out.println("PipingRules.expandPipeline expanded " + u.start + " " + u.end);
1247                 u.iter++;
1248                 updatePathLeg(u, PathLegUpdateType.NONE);
1249         }
1250
1251         /**
1252          * reverts one iteration of turn removing back)
1253          */
1254         private static void backIter(UpdateStruct2 u) throws Exception {
1255
1256                 if (DEBUG)
1257                         System.out.println("PipingRules.backIter" + u.start + " " + u.end);
1258                 if (u.iter == 0)
1259                         throw new RuntimeException("Error in piping rules");
1260                 ExpandIterInfo info = u.toRemove.get(u.toRemove.size() - 1);
1261                 u.toRemove.remove(u.toRemove.size() - 1);
1262                 if (info.getType() == REMOVE_START || info.getType() == REMOVE_BOTH) {
1263                         while (u.list.size() > 0) {
1264                                 PipeControlPoint icp = u.list.get(0);
1265                                 if (icp.getPrevious().equals(info.getStart()))
1266                                         break;
1267                                 u.list.remove(icp);
1268                         }
1269                         u.start = info.getStart();
1270                 }
1271                 if (info.getType() == REMOVE_END || info.getType() == REMOVE_BOTH) {
1272                         while (u.list.size() > 0) {
1273                                 PipeControlPoint icp = u.list.get(u.list.size() - 1);
1274                                 if (icp.getNext().equals(info.getEnd()))
1275                                         break;
1276                                 u.list.remove(icp);
1277                         }
1278                         u.end = info.getEnd();
1279                 }
1280                 u.offset = new Vector3d();
1281                 if (u.hasOffsets) {
1282                         u.dir.normalize();
1283                         for (PipeControlPoint icp : u.list) {
1284                                 if (icp.isOffset()) {
1285                                         u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1286                                 } else if (icp.isDualSub())
1287                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1288                         }
1289                 }
1290                 processPathLeg(u);
1291
1292         }
1293
1294         /**
1295          * Processes pipe run (removes necessary turns and updates run ends)
1296          */
1297         // private static void processPathLeg(PipeControlPoint start, Point3d
1298         // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1299         // end,Point3d endPoint, Vector3d dir,Vector3d offset, boolean
1300         // hasOffsets,int iter, boolean reversed, ArrayList<ExpandIterInfo>
1301         // toRemove) throws TransactionException {
1302
1303         private static void processPathLeg(UpdateStruct2 u) throws Exception {
1304                 if (DEBUG)
1305                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1306                 processPathLeg(u, true, true);
1307         }
1308
1309         private static void processPathLeg(UpdateStruct2 u, boolean updateEnds, boolean updateInline) throws Exception {
1310                 if (DEBUG)
1311                         System.out.println("PipingRules.processPathLeg " + (updateEnds ? "ends " : "") + (updateInline ? "inline " : "") + u.start + " " + u.end);
1312
1313                 if (u.toRemove.size() > 0) {
1314                         for (ExpandIterInfo info : u.toRemove) {
1315                                 if (info.getStart() != null) {
1316                                         if (DEBUG)
1317                                                 System.out.println("PipingRules.processPathLeg removing start " + info.getStart());
1318                                         info.getStart()._remove();
1319                                 }
1320                                 if (info.getEnd() != null) {
1321                                         if (DEBUG)
1322                                                 System.out.println("PipingRules.processPathLeg removing end " + info.getEnd());
1323                                         info.getEnd()._remove();
1324                                 }
1325                         }
1326                         // ControlPointTools.removeControlPoint may remove more than one CP;
1327                         // we must populate inline CP list again.
1328                         u.list.clear();
1329                         u.start.findNextEnd( u.list);
1330                 }
1331                 // FIXME : inline CPs are update twice because their positions must be
1332                 // updated before and after ends.
1333                 updateInlineControlPoints(u, false);
1334                 
1335                 if (updateEnds) {
1336                         if (u.start.isTurn()) {
1337                                 //updateTurnControlPointTurn(u.start, u.start.getPrevious(), u.start.getNext());
1338                                 updateTurnControlPointTurn(u.start, null, null);
1339 //                              updatePathLegPrev(u.start, u.start, PathLegUpdateType.NONE);
1340                         } else if (u.start.isEnd()) {
1341                                 updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint);
1342                         } else if (u.start.isInline()) {
1343                                 updateControlPointOrientation(u.start);
1344                         }
1345                         if (u.end.isTurn()) {
1346                                 //updateTurnControlPointTurn(u.end, u.end.getPrevious(), u.end.getNext());
1347                                 updateTurnControlPointTurn(u.end, null, null);
1348 //                              updatePathLegNext(u.end, u.end, PathLegUpdateType.NONE);
1349                         } else if (u.end.isEnd()) {
1350                                 updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint);
1351                         } else if (u.end.isInline()) {
1352                                 updateControlPointOrientation(u.end);
1353                         }
1354
1355                 } else {
1356                         if (u.start.isEnd()) {
1357                                 updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint);
1358                         }
1359                         if (u.end.isEnd()) {
1360                                 updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint);
1361                         }
1362                 }
1363                 if (updateInline)
1364                         updateInlineControlPoints(u, true);
1365
1366         }
1367
1368         /**
1369          * Processes pipe run and recalculates offset
1370          */
1371         // private static void processPathLeg(PipeControlPoint start, Point3d
1372         // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1373         // end,Point3d endPoint, Vector3d dir, boolean hasOffsets,int iter, boolean
1374         // reversed, ArrayList<ExpandIterInfo> toRemove) throws TransactionException
1375         // {
1376         @SuppressWarnings("unused")
1377         private static void processPathLegNoOffset(UpdateStruct2 u) throws Exception {
1378                 if (DEBUG)
1379                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1380                 Vector3d offset = new Vector3d();
1381                 if (u.hasOffsets) {
1382                         u.dir.normalize();
1383                         for (PipeControlPoint icp : u.list) {
1384                                 if (icp.isOffset()) {
1385                                         offset.add(icp.getSizeChangeOffsetVector(u.dir));
1386                                 } else if (icp.isDualSub()) {
1387                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1388                                 }
1389                         }
1390                 }
1391                 processPathLeg(u);
1392         }
1393
1394         private static void updateOffsetPoint(PipeControlPoint sccp, Vector3d offset) {
1395                 Vector3d world = sccp.getWorldPosition();
1396                 world.add(offset);
1397                 PipeControlPoint ocp = sccp.getDualSub();
1398                 ocp.setWorldPosition(world);
1399         }
1400
1401         /**
1402          * Updates InlineControlPoints position when straight pipe's end(s) have
1403          * been changed)
1404          * 
1405          * @param pipeline
1406          * @param icp
1407          * @param nextPoint
1408          * @param prevPoint
1409          */
1410         private static void updateInlineControlPoint(PipeControlPoint icp, Vector3d prev, Vector3d next,  Vector3d dir) {
1411                 if (DEBUG)
1412                         System.out.println("PipingRules.updateInlineControlPoint() " + icp);
1413
1414                 Vector3d inlinePoint = icp.getWorldPosition();
1415                 Vector3d prevPoint = new Vector3d(prev);
1416                 Vector3d nextPoint = new Vector3d(next);
1417                 if (!icp.isVariableLength()) {
1418                         // Reserve space for fixed length components. 
1419                         MathTools.mad(prevPoint, dir, icp.getInlineLength());
1420                         MathTools.mad(nextPoint, dir, -icp.getInlineLength());
1421                         if (MathTools.distance(prevPoint, nextPoint) < ALLOWED_OFFSET) {
1422                                 prevPoint = prev;
1423                                 nextPoint = next;
1424                         }
1425                 }
1426                 boolean canCalc = MathTools.distance(prevPoint, nextPoint) > ALLOWED_OFFSET;
1427                 if (DEBUG)
1428                         System.out.print("InlineControlPoint update " + icp + " " + inlinePoint + " " + prevPoint + " " + nextPoint);
1429                 Vector3d newInlinePoint = null;
1430                 if (canCalc) {
1431                         boolean branchUpdate = false;
1432                         PipeControlPoint becp = null;
1433                         for (PipeControlPoint pcp : icp.getChildPoints())
1434                                 if (pcp.isNonDirected()) {
1435                                         branchUpdate = true;
1436                                         becp = pcp;
1437                                         break;
1438                                 }
1439         
1440                         if (DUMMY || !branchUpdate) {
1441                                 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1442                                 
1443                         } else {
1444         
1445                                 // FIXME : can only handle one branch
1446                                 PipeControlPoint p = null;
1447                                 if (becp.getNext() != null) {
1448                                         p = becp.findNextEnd();
1449                                 } else if (becp.getPrevious() != null) {
1450                                         p = becp.findPreviousEnd();
1451                                 }
1452                                 if (p == null) {
1453                                         newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1454                                 } else if (canCalc){
1455                                         Vector3d branchLegEnd = p.getWorldPosition();
1456                                         Vector3d dir2 = new Vector3d(inlinePoint);
1457                                         dir2.sub(branchLegEnd);
1458                                         Vector3d dir1 = new Vector3d(nextPoint);
1459                                         dir1.sub(prevPoint);
1460                                         newInlinePoint = new Vector3d();
1461                                         double mu[] = new double[2];
1462                                         MathTools.intersectStraightStraight(new Vector3d(prevPoint), dir1, new Vector3d(branchLegEnd), dir2, newInlinePoint, new Vector3d(), mu);
1463                                         if (DEBUG)
1464                                                 System.out.println(mu[0]);
1465                                         // FIXME : reserve space
1466                                         if (mu[0] < 0.0) {
1467                                                 newInlinePoint = new Vector3d(prevPoint);
1468                                         } else if (mu[0] > 1.0) {
1469                                                 newInlinePoint = new Vector3d(nextPoint);
1470                                         }
1471                                 }
1472                         }
1473                 } else {
1474                         // prevPoint == nextPoint
1475                         newInlinePoint = new Vector3d(prevPoint);
1476                 }
1477                 if (DEBUG)
1478                         System.out.println(" " + newInlinePoint);
1479
1480                 icp.setWorldPosition(newInlinePoint);
1481                 updateControlPointOrientation(icp);
1482         }
1483
1484         /**
1485          * Updates InlineControlPoints position when straight pipe's end(s) have
1486          * been changed)
1487          * 
1488          * @param pipeline
1489          * @param icp
1490          * @param nextPoint
1491          * @param prevPoint
1492          */
1493         private static void updateEndComponentControlPoint(PipeControlPoint ecp, Vector3d start, Vector3d end) throws Exception {
1494                 if (DEBUG)
1495                         System.out.println("PipingRules.updateEndComponentControlPoint() " + ecp);
1496                 //FIXME : end control point cannot be fixed!
1497                 //if (!ecp.isFixed())
1498                 updateControlPointOrientation(ecp);
1499
1500                 for (PipeControlPoint pcp : ecp.getChildPoints()) {
1501                         // TODO update position
1502                         updatePathLegEndControlPoint(pcp);
1503                 }
1504         }
1505
1506         private static void updateControlPointOrientation(PipeControlPoint pcp) {
1507                 // FIXME : hack to bypass variable length components orientation
1508 //              if (pcp.getAtMostOneRelatedObject(ProcessResource.g3dResource.HasWorldOrientation) == null)
1509 //                      return;
1510 //              if (pcp.rotationAngle == null)
1511 //                      return;
1512                 Double angleO = pcp.getRotationAngle();
1513                 double angle = 0.0;
1514                 if (angleO != null)
1515                         angle = angleO;
1516                 Boolean reversedO = pcp.getReversed();
1517                 boolean reversed = false;
1518                 if (reversedO != null)
1519                         reversed = reversedO;
1520                 Quat4d q = pcp.getControlPointOrientationQuat(angle, reversed);
1521                 pcp.setWorldOrientation(q);
1522         }
1523
1524         /**
1525          * Updates all branches when branch's position has been changed
1526          * 
1527          * @param bcp
1528          */
1529         private static void updateBranchControlPointBranches(PipeControlPoint bcp) throws Exception {
1530                 if (DEBUG)
1531                         System.out.println("PipingRules.updateBranchControlPointBranches() " + bcp);
1532                 if (bcp.isDualInline())
1533                         return;
1534                 Collection<PipeControlPoint> branches = bcp.getChildPoints();
1535                 if (branches.size() == 0) {
1536                         if (DEBUG)
1537                                 System.out.println("No Branches found");
1538                         return;
1539                 }
1540                 
1541                 for (PipeControlPoint pcp : branches) {
1542                         updatePathLegEndControlPoint(pcp);
1543                 }
1544         }
1545
1546         private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d prev, Vector3d next) {
1547                 if (next == null) {
1548                         UpdateStruct2 us = createUS(tcp, Direction.NEXT, 0, new ArrayList<PipingRules.ExpandIterInfo>(), tcp);
1549                         if (us != null)
1550                                 next = us.dir;
1551                 }
1552                 if (prev == null) {
1553                         UpdateStruct2 us = createUS(tcp, Direction.PREVIOUS, 0, new ArrayList<PipingRules.ExpandIterInfo>(), tcp);
1554                         if (us != null) {
1555                                 prev = us.dir;
1556                         }
1557                 }
1558                 
1559                 if (!tcp.asFixedAngle()) {
1560                         
1561                         
1562                         if (next == null || prev == null) {
1563                                 if (tcp.getTurnAngle() != null)
1564                                         return tcp.getTurnAngle();
1565                                 return Math.PI; // FIXME : argh
1566                         }
1567                         double turnAngle = prev.angle(next);
1568         
1569                         double angle = Math.PI - turnAngle;
1570         
1571                         Vector3d turnAxis = new Vector3d();
1572                         turnAxis.cross(prev, next);
1573                         if (turnAxis.lengthSquared() > MathTools.NEAR_ZERO) {
1574                                 double elbowRadius = ((TurnComponent)tcp.getPipelineComponent()).getTurnRadius();
1575                                 double R = elbowRadius / Math.tan(angle * 0.5);
1576                                 
1577                                 turnAxis.normalize();
1578                                 tcp.setTurnAngle(turnAngle);
1579                                 tcp.setLength(R);// setComponentOffsetValue(R);
1580                                 tcp.setTurnAxis(turnAxis);
1581         //                      tcp.setPosition(tcp.getPosition());
1582                         } else {
1583                                 turnAngle = 0.0;
1584                                 tcp.setTurnAngle(0.0);
1585                                 tcp.setLength(0.0);
1586                                 tcp.setTurnAxis(new Vector3d(MathTools.Y_AXIS));
1587                         }
1588                         
1589                         updateControlPointOrientation(tcp);
1590                         
1591                         if (DEBUG)
1592                                 System.out.println("PipingTools.updateTurnControlPointTurn " + prev + " " + next + " " + turnAngle + " " + turnAxis);
1593                         return turnAngle;
1594                 } else {
1595                         
1596                         if (prev != null && next != null) {
1597                                 // Nothing to do
1598                         } else if (prev == null) {
1599                                 if (!tcp._getReversed())
1600                                         tcp.setReversed(true);
1601                         } else if (next == null) {
1602                                 if (tcp._getReversed())
1603                                         tcp.setReversed(false);
1604                         }
1605                         
1606                         Vector3d dir = null;
1607                         if (!tcp._getReversed()) {
1608                                 dir = prev;
1609                         } else {
1610                                 dir = next;
1611                                 dir.negate();
1612                         }
1613                         if (dir == null) {
1614                                 return Math.PI; // FIXME : argh
1615                         }
1616                         
1617                         Quat4d q = PipeControlPoint.getControlPointOrientationQuat(dir, tcp.getRotationAngle() != null ? tcp.getRotationAngle() : 0.0);
1618                         Vector3d v = new Vector3d();
1619                         MathTools.rotate(q, MathTools.Y_AXIS,v);
1620                         tcp.setTurnAxis(v);
1621                         tcp.setWorldOrientation(q);
1622                         if (tcp.getTurnAngle() != null)
1623                                 return tcp.getTurnAngle();
1624                         return Math.PI; // FIXME : argh
1625                 }
1626                 
1627                 
1628         }
1629         
1630         public static List<PipeControlPoint> getControlPoints(PipeRun pipeRun) {
1631                 List<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
1632                 if (pipeRun.getControlPoints().size() == 0)
1633                         return list;
1634                 PipeControlPoint pcp = pipeRun.getControlPoints().iterator().next();
1635                 while (pcp.getPrevious() != null) {
1636                         PipeControlPoint prev = pcp.getPrevious();
1637                         if (prev.getPipeRun() != pipeRun && prev.getPipeRun() != null) { // bypass possible corruption
1638                             break;
1639                         }
1640                         pcp = prev;
1641                 }
1642                 if (pcp.isDualSub()) {
1643                         pcp = pcp.getParentPoint();
1644                 }
1645                 list.add(pcp);
1646                 while (pcp.getNext() != null) {
1647                         pcp = pcp.getNext();
1648                         if (pcp.getPipeRun() != pipeRun)
1649                                 break;
1650                         list.add(pcp);
1651                 }
1652                 return list;
1653         }
1654         
1655         public static void reverse(PipeRun pipeRun) {
1656                 
1657                 while (true) {
1658                         List<PipeControlPoint> points = getControlPoints(pipeRun);
1659                         PipeControlPoint pcp = points.get(0);
1660                         if (pcp.isSizeChange() && pcp.getChildPoints().size() > 0) {
1661                                 pipeRun = pcp.getPipeRun();
1662                         } else {
1663                                 break;
1664                         }
1665                 }
1666                 List<PipeRun> all = new ArrayList<PipeRun>();
1667                 List<List<PipeControlPoint>> pcps = new ArrayList<List<PipeControlPoint>>();
1668                 while (true) {
1669                         all.add(pipeRun);
1670                         List<PipeControlPoint> points = getControlPoints(pipeRun);
1671                         pcps.add(points);
1672                         PipeControlPoint pcp = points.get(points.size()-1);
1673                         if (pcp.getChildPoints().size() > 0) {
1674                                 pipeRun = pcp.getChildPoints().get(0).getPipeRun();
1675                         } else {
1676                                 break;
1677                         }
1678                 }
1679                 for (int i = 0 ; i < all.size(); i++) {
1680                         List<PipeControlPoint> list = pcps.get(i);
1681                         _reverse(list);
1682                 }
1683                 for (int i = 0 ; i < all.size(); i++) {
1684                         boolean last = i == all.size() - 1;
1685                         List<PipeControlPoint> list = pcps.get(i);
1686                         
1687                         if (!last) {
1688                                 List<PipeControlPoint> list2 = pcps.get(i+1);
1689                                 PipeControlPoint prev = list.get(list.size()-1);
1690                                 PipeControlPoint next = list2.get(0);
1691                                 System.out.println();
1692                                 if (prev == next) {
1693                                         // Reverse the component on the boundary.
1694                                         InlineComponent ic = (InlineComponent)prev.getPipelineComponent();
1695                                         PipeRun r1 = ic.getPipeRun();
1696                                         PipeRun r2 = ic.getAlternativePipeRun();
1697                                         if (r1 == null || r2 == null)
1698                                                 throw new RuntimeException("Components on PipeRun changes should refer to bot PipeRuns");
1699                                         ic.deattach();
1700                                         r2.addChild(ic);
1701                                         ic.setPipeRun(r2);
1702                                         ic.setAlternativePipeRun(r1);
1703                                 } else {
1704                                         throw new RuntimeException("PipeRun changes should contain shared control points");
1705                                 }
1706                                 
1707                         }
1708                 }
1709                         
1710         }
1711         
1712         private static void _reverse(List<PipeControlPoint> list) {
1713                 if (list.size() <= 1)
1714                         return; // nothing to do.
1715                 
1716                 for (int i = 0 ; i < list.size(); i++) {
1717                         boolean first = i == 0;
1718                         boolean last = i == list.size() - 1;
1719                         PipeControlPoint current = list.get(i);
1720                         PipeControlPoint currentSub = null;
1721                         if (current.isDualInline())
1722                                 currentSub = current.getDualSub();
1723                         if (first) {
1724                                 PipeControlPoint next = list.get(i+1);
1725                                 if (next.isDualInline())
1726                                         next = next.getDualSub();
1727                                 if (current.getNext() == next)
1728                                         current.setNext(null);
1729                                 current.setPrevious(next);
1730                                 if (currentSub != null) {
1731                                         if (currentSub.getNext() == next)
1732                                                 currentSub.setNext(null);
1733                                         currentSub.setPrevious(next);       
1734                                 }
1735                         } else if (last) {
1736                                 PipeControlPoint prev = list.get(i-1);
1737                                 
1738                                 if (current.getPrevious() == prev)
1739                                         current.setPrevious(null);
1740                                 current.setNext(prev);
1741                                 
1742                                 if (currentSub != null) {
1743                                         if (currentSub.getPrevious() == prev)
1744                                                 currentSub.setPrevious(null);
1745                                         currentSub.setNext(prev);       
1746                                 }
1747                         } else {
1748                                 PipeControlPoint prev = list.get(i-1);
1749                                 PipeControlPoint next = list.get(i+1);
1750                                 if (next.isDualInline())
1751                                         next = next.getDualSub();
1752                                 
1753                                 
1754                                 current.setPrevious(next);
1755                                 current.setNext(prev);
1756                                 
1757                                 if (currentSub != null) {
1758                                         currentSub.setPrevious(next);
1759                                         currentSub.setNext(prev);       
1760                                 }
1761                                 
1762                         }
1763                         //if (current.isTurn() && current.isFixed()) {
1764                         if (current.asFixedAngle()) {
1765                                 current.setReversed(!current._getReversed());
1766                         }
1767                         if (current.isInline() && current.isReverse()) {
1768                                 current.setReversed(!current._getReversed());
1769                         }   
1770                 }
1771         }
1772         
1773         
1774         
1775         public static void validate(PipeRun pipeRun) {
1776                 if (pipeRun == null)
1777                         return;
1778                 Collection<PipeControlPoint> pcps = pipeRun.getControlPoints();
1779                 int count = 0;
1780                 //System.out.println("Validate " + pipeRun.getName());
1781                 for (PipeControlPoint pcp : pcps) {
1782                         if (pcp.getParentPoint() == null || pcp.getParentPoint().getPipeRun() != pipeRun)
1783                                 count++;
1784                 }
1785                 List<PipeControlPoint> runPcps = getControlPoints(pipeRun);
1786                 if (runPcps.size() != count) {
1787                         System.out.println("Run " + pipeRun.getName() + " contains unconnected control points, found " + runPcps.size() + " connected, " + pcps.size() + " total.");
1788                         for (PipeControlPoint pcp : pcps) {
1789                             if (!runPcps.contains(pcp)) {
1790                                 System.out.println("Unconnected " + pcp + " " + pcp.getPipelineComponent());
1791                             }
1792                         }
1793                 }
1794                 for (PipeControlPoint pcp : pcps) {
1795                     if (pcp.getPipeRun() == null) {
1796                         System.out.println("PipeRun ref missing " + pcp + " " + pcp.getPipelineComponent());
1797                     }
1798                         if (!pcp.isDirected() && pcp.getNext() == null && pcp.getPrevious() == null)
1799                                 System.out.println("Orphan undirected " + pcp + " " + pcp.getPipelineComponent());
1800                 }
1801                 for (PipeControlPoint pcp : pcps) {
1802                         if (pcp.getParentPoint() == null) {
1803                                 PipeControlPoint sub = null;
1804                                 if (pcp.isDualInline())
1805                                         sub = pcp.getDualSub();
1806                                 PipeControlPoint next = pcp.getNext();
1807                                 PipeControlPoint prev = pcp.getPrevious();
1808                                 if (next != null) {
1809                                         if (!(next.getPrevious() == pcp || next.getPrevious() == sub)) {
1810                                                 System.out.println("Inconsistency between " + pcp + " -> " +next );
1811                                         }
1812                                 }
1813                                 if (prev != null) {
1814                                         PipeControlPoint prevParent = null;
1815                                         if (prev.isDualSub()) {
1816                                                 prevParent = prev.getParentPoint();
1817                                         } else if (prev.isDualInline()) {
1818                                                 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1819                                         }
1820                                         if (!(prev.getNext() == pcp && (prevParent == null || prevParent.getNext() == pcp))) {
1821                                                 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1822                                         }
1823                                 }
1824                         }
1825                 }
1826         }
1827         
1828         public static void splitVariableLengthComponent(PipelineComponent newComponent, InlineComponent splittingComponent, boolean assignPos) throws Exception{
1829                 assert(!splittingComponent.getControlPoint().isFixedLength());
1830                 assert(!(newComponent instanceof  InlineComponent && !newComponent.getControlPoint().isFixedLength()));
1831                 PipeControlPoint newCP = newComponent.getControlPoint();
1832                 PipeControlPoint splittingCP = splittingComponent.getControlPoint();
1833                 PipeControlPoint nextCP = splittingCP.getNext();
1834                 PipeControlPoint prevCP = splittingCP.getPrevious();
1835                 
1836                 /* there are many different cases to insert new component when
1837                    it splits existing VariableLengthinlineComponent.
1838                 
1839                    1. VariableLengthComponet is connected from both sides:
1840                           - insert new component between VariableLength component and component connected to it
1841                           - insert new VariableLengthComponent between inserted component and component selected in previous step
1842                 
1843                    2. VariableLengthComponent is connected from one side
1844                          - Use previous case or:
1845                          - Insert new component to empty end
1846                          - Insert new VariableLength component to inserted components empty end
1847                          
1848                    3. VariableLength is not connected to any component.
1849                          - Should not be possible, at least in current implementation.
1850                          - Could be done using second case
1851
1852                 */
1853                 
1854                 if (nextCP == null && prevCP == null) {
1855                         // this should not be possible
1856                         throw new RuntimeException("VariableLengthComponent " + splittingComponent + " is not connected to anything.");
1857                 }
1858                 double newLength = newComponent.getControlPoint().getLength();
1859                 
1860                 
1861                 Point3d next = new Point3d();
1862                 Point3d prev = new Point3d();
1863                 splittingCP.getInlineControlPointEnds(prev, next);
1864                 
1865                 Vector3d newPos = null;
1866                 if (assignPos) {
1867                         newPos = new Vector3d(prev);
1868                         Vector3d dir = new Vector3d(next);
1869                         dir.sub(prev);
1870                         dir.scale(0.5);
1871                         newPos.add(dir);
1872                         newComponent.setWorldPosition(newPos);
1873                 } else {
1874                         newPos = newComponent.getWorldPosition();
1875                 }
1876                 
1877                 
1878
1879                 Vector3d dir = new Vector3d(next);
1880                 dir.sub(prev);
1881                 dir.normalize();
1882                 dir.scale(newLength * 0.5);
1883                 Point3d vn = new Point3d(newPos);
1884                 Point3d vp = new Point3d(newPos);
1885                 vn.add(dir);
1886                 vp.sub(dir);
1887                 double ln = vn.distance(next);
1888                 double lp = vp.distance(prev);
1889                 vp.interpolate(prev, 0.5);
1890                 vn.interpolate(next, 0.5);
1891                 
1892                 
1893                 if (nextCP == null) {
1894                         newCP.insert(splittingCP, Direction.NEXT);
1895                         insertStraight(newCP, Direction.NEXT, new Vector3d(vn), ln);
1896                         splittingCP.setWorldPosition(new Vector3d(vp));
1897 //                      ControlPointTools.setWorldPosition(splittingCP, vp);
1898 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
1899                 } else if (prevCP == null) {
1900                         newCP.insert(splittingCP, Direction.PREVIOUS);
1901                         insertStraight(newCP, Direction.PREVIOUS, new Vector3d(vp), lp);
1902                         splittingCP.setWorldPosition(new Vector3d(vn));
1903 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, ln);
1904                 } else {
1905                         newCP.insert(splittingCP, nextCP);
1906                         insertStraight(newCP, nextCP, new Vector3d(vn), ln);
1907                         splittingCP.setWorldPosition(new Vector3d(vp));
1908 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
1909                 }
1910                 positionUpdate(newCP);
1911
1912         }
1913         
1914         public static void addSizeChange(boolean reversed, PipeRun pipeRun, PipeRun other, InlineComponent reducer, PipeControlPoint previous, PipeControlPoint next) {
1915                 PipeControlPoint pcp = reducer.getControlPoint();
1916                 PipeControlPoint ocp = pcp.getDualSub();
1917                 if (!reversed) {
1918                         String name = pipeRun.getUniqueName("Reducer");
1919                         reducer.setName(name);
1920                         pipeRun.addChild(reducer);
1921                         other.addChild(ocp);
1922                         reducer.setAlternativePipeRun(other);
1923                         
1924                         previous.setNext(pcp);
1925                         pcp.setPrevious(previous);
1926                         ocp.setPrevious(previous);
1927                         if (next != null) {
1928                                 pcp.setNext(next);
1929                                 ocp.setNext(next);
1930                                 next.setPrevious(ocp);
1931                         }
1932                 } else {
1933                         String name = other.getUniqueName("Reducer");
1934                         reducer.setName(name);
1935                         other.addChild(reducer);
1936                         pipeRun.addChild(ocp);
1937                         reducer.setAlternativePipeRun(pipeRun);
1938                         
1939                         if (next != null) {
1940                                 next.setNext(pcp);
1941                                 pcp.setPrevious(next);
1942                                 ocp.setPrevious(next);
1943                         }
1944                         pcp.setNext(previous);
1945                         ocp.setNext(previous);
1946                         previous.setPrevious(ocp);
1947                 }
1948         }
1949 }