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