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