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