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