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