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