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