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