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