]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipingRules.java
Publish Plant3D feature
[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                 dir.set(startPoint);
341                 dir.sub(endPoint);
342                 if (dir.lengthSquared() > MathTools.NEAR_ZERO)
343                         dir.normalize();
344                 offset.set(0.0, 0.0, 0.0);
345                 for (PipeControlPoint icp : list) {
346                         if (icp.isOffset()) {
347                                 hasOffsets = true;
348                                 offset.add(icp.getSizeChangeOffsetVector(dir));
349                         } else if (icp.isDualSub())
350                                 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
351                 }
352                 return hasOffsets;
353         }
354
355         /**
356          * @param start
357          *            starting point of the pipe run
358          * @param list
359          *            list of inline control points in the pipe run
360          * @param end
361          *            ending point of the pipe run
362          * @param reversed
363          *            boolean flag indicating wether start or end control point was
364          *            modified (if true then end point was modified)
365          * @throws TransactionException
366          */
367         private static void updatePathLeg(PipeControlPoint start, ArrayList<PipeControlPoint> list, PipeControlPoint end, boolean reversed, int iter, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
368                 if (start == end)
369                         return;
370                 // FIXME: direction is calculated wrong way!
371                 boolean hasOffsets = false;
372                 Vector3d offset = new Vector3d();
373                 Vector3d startPoint = start.getWorldPosition();
374                 Vector3d endPoint = end.getWorldPosition();
375                 Vector3d dir = new Vector3d();
376                 hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset);
377                 updatePathLeg(new UpdateStruct2(start, startPoint, list, end, endPoint, dir, offset, hasOffsets, iter, reversed, toRemove, updated), lengthChange);
378
379         }
380
381         private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
382                 int directed = 0;
383                 if (u.start.isDirected())
384                         directed++;
385                 if (u.end.isDirected())
386                         directed++;
387                 switch (directed) {
388                 case 0:
389                         updateFreePathLeg(u, lengthChange);
390                         break;
391                 case 1:
392                         updateDirectedPathLeg(u, lengthChange);
393                         break;
394                 case 2:
395                         updateDualDirectedPathLeg(u, lengthChange);
396                         break;
397                 }
398
399         }
400
401         private static void updateFreePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
402                 if (DEBUG)
403                         System.out.println("PipingRules.updateFreePipeRun " + u + " " + lengthChange);
404                 checkExpandPathLeg(u, lengthChange);
405                 if (u.start.isInline() || u.end.isInline())
406                         processPathLeg(u, true, false);
407         }
408
409         private static void updateInlineControlPoints(UpdateStruct2 u, boolean checkSizes) throws Exception{
410                 if (DEBUG)
411                         System.out.println("PipingRules.updateInlineControlPoints() " + u);
412
413                 if (!u.hasOffsets) {
414                         // FIXME : cache positions
415                         if (!checkSizes) {
416                                 Vector3d start = new Vector3d(u.startPoint);
417                                 Vector3d end = new Vector3d(u.endPoint);
418                                 // create offsets.
419                                 MathTools.mad(start, u.dir, 0.1);
420                                 MathTools.mad(end, u.dir, -0.1);
421                                 for (PipeControlPoint icp : u.list) {
422                                         updateInlineControlPoint(icp, start, end, u.dir);
423                                 }
424                                 return;
425                         }
426
427                         ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<PipeControlPoint>();
428                         pathLegPoints.add(u.start);
429                         for (PipeControlPoint icp : u.list) {
430                                 // updateInlineControlPoint(icp, u.startPoint,
431                                 // u.endPoint,u.dir);
432                                 updateBranchControlPointBranches(icp);
433                                 pathLegPoints.add(icp);
434                         }
435                         pathLegPoints.add(u.end);
436
437                         // TODO : values can be cached in the loop
438                         for (int i = 1; i < pathLegPoints.size(); i++) {
439                                 PipeControlPoint icp = pathLegPoints.get(i);
440
441                                 PipeControlPoint prev;
442                                 Vector3d prevPos;
443                                 prev = pathLegPoints.get(i - 1);
444                                 prevPos = prev.getWorldPosition();
445                                 Vector3d currentPos = icp.getWorldPosition();
446
447                                 if (icp.isVariableLength()) {
448                                         if (i != pathLegPoints.size() - 1) {
449                                                 PipeControlPoint next;
450                                                 Vector3d nextPos;
451                                                 next = pathLegPoints.get(i + 1);
452                                                 nextPos = next.getWorldPosition();
453                                                 Vector3d dir = new Vector3d(nextPos);
454                                                 dir.sub(prevPos);
455                                                 double l = dir.lengthSquared(); // distance between
456                                                                                                                 // control points
457                                                                                                                 // (square)
458                                                 double l2prev = prev.getInlineLength(); // distance
459                                                                                                                                                                         // taken
460                                                                                                                                                                         // by
461                                                                                                                                                                         // components
462                                                 double l2next = next.getInlineLength();
463                                                 double l2 = l2prev + l2next;
464                                                 double l2s = MathTools.square(l2);
465                                                 if (l2s < l) { // check if there is enough space for
466                                                                                 // variable length component.
467                                                         // components fit
468                                                         dir.normalize();
469                                                         double length = Math.sqrt(l) - l2; // true length of
470                                                                                                                                 // the variable
471                                                                                                                                 // length
472                                                                                                                                 // component
473                                                         dir.scale(length * 0.5 + l2prev); // calculate
474                                                                                                                                 // center
475                                                                                                                                 // position of
476                                                                                                                                 // the component
477                                                         dir.add(prevPos);
478                                                         icp.setWorldPosition(dir);
479                                                         icp.setLength(length);
480                                                 } else {
481                                                         // components leave no space to the component and it
482                                                         // must be removed
483                                                         if (icp.isDeletable())
484                                                                 icp._remove();
485                                                 }
486
487                                         } else {
488                                                 // this is variable length component at the end of the
489                                                 // piperun.
490                                                 // the problem is that we want to keep unconnected end
491                                                 // of the component in the same
492                                                 // place, but center of the component must be moved.
493                                                 double currentLength = icp.getLength();
494                                                 
495                                                 Vector3d dir = new Vector3d();
496                                                 dir.sub(currentPos, prevPos);
497                                                 
498                                                 if (currentLength < MathTools.NEAR_ZERO) {
499                                                         currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
500                                                 }
501                                                 
502                                                 if (dir.lengthSquared() > MathTools.NEAR_ZERO)
503                                                         dir.normalize();
504                                                 Point3d endPos = new Point3d(dir);
505                                                 endPos.scale(currentLength * 0.5);
506                                                 endPos.add(currentPos); // this is the free end of the
507                                                                                                 // component
508
509                                                 double offset = prev.getInlineLength();
510                                                 Point3d beginPos = new Point3d(dir);
511                                                 beginPos.scale(offset);
512                                                 beginPos.add(prevPos); // this is the connected end of
513                                                                                                 // the component
514
515                                                 double l = beginPos.distance(endPos);
516                                                 
517                                                 if (Double.isNaN(l))
518                                                         System.out.println();
519
520                                                 dir.scale(l * 0.5);
521                                                 beginPos.add(dir); // center position
522
523                                                 if (DEBUG)
524                                                         System.out.println("PipingRules.updateInlineControlPoints() setting variable length to " + l);
525                                                 icp.setLength(l);
526
527                                                 icp.setWorldPosition(new Vector3d(beginPos));
528                                         }
529
530
531                                 } else if (!prev.isVariableLength()) {
532                                         // If this and previous control point are not variable
533                                         // length pcps, we'll have to check if there is no empty
534                                         // space between them.
535                                         // I there is, we'll have to create new variable length
536                                         // component between them.
537                                         Vector3d dir = new Vector3d(currentPos);
538                                         dir.sub(prevPos);
539                                         double l = dir.lengthSquared();
540                                         double l2prev = prev.getInlineLength();
541                                         double l2next = icp.getInlineLength();
542                                         double l2 = l2prev + l2next;
543                                         double l2s = l2 * l2;
544                                         if (l > l2s) {
545                                                 if (allowInsertRemove) {
546                                                         dir.normalize();
547                                                         double length = Math.sqrt(l) - l2; // true length of the
548                                                                                                                                 // variable length
549                                                                                                                                 // component
550                                                         dir.scale(length * 0.5 + l2prev); // calculate center
551                                                                                                                                 // position of the
552                                                                                                                                 // component
553                                                         dir.add(prevPos);
554                                                         PipeControlPoint scp = insertStraight(prev, icp, dir, length);
555                                                 } else {
556                                                         triedIR = true;
557                                                 }
558                                         }
559                                 }
560                         }
561                 } else {
562                         u.endPoint.sub(u.offset);
563                         // FIXME : straights
564                         for (PipeControlPoint icp : u.list) {
565                                 updateInlineControlPoint(icp, u.startPoint, u.endPoint, u.dir);
566                                 updateBranchControlPointBranches(icp);
567                                 
568                                 if (icp.isOffset()) {
569                                         // TODO : offset vector is already calculated and should be
570                                         // cached
571                                         u.offset = icp.getSizeChangeOffsetVector(u.dir);
572                                         updateOffsetPoint(icp, u.offset);
573                                         u.startPoint.add(u.offset);
574                                         u.endPoint.add(u.offset);
575                                 }
576                         }
577                 }
578         }
579
580         private static void ppNoOffset(UpdateStruct2 u) throws Exception {
581                 if (DEBUG)
582                         System.out.println("PipingRules.ppNoOffset() " + u);
583                 Vector3d offset = new Vector3d();
584                 if (u.hasOffsets) {
585                         u.dir.normalize();
586                         for (PipeControlPoint icp : u.list) {
587                                 if (icp.isOffset()) {
588                                         offset.add(icp.getSizeChangeOffsetVector(u.dir));
589                                 } else if (icp.isDualSub())
590                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
591                         }
592                 }
593                 u.offset = offset;
594                 checkExpandPathLeg(u, PathLegUpdateType.NONE);
595         }
596
597         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 {
598                 if (DEBUG)
599                         System.out.println("PipingRules.ppNoDir() " + start + " " + end + " " + iter + " " + toRemove.size());
600                 // FIXME : extra loop (dir should be calculated here)
601                 Vector3d dir = new Vector3d();
602                 Vector3d offset = new Vector3d();
603                 hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset);
604                 ppNoOffset(new UpdateStruct2(start, startPoint, list, end, endPoint, dir, null, hasOffsets, iter, reversed, toRemove, updated));
605         }
606
607         private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
608                 checkExpandPathLeg(u, lengthChange, false);
609         }
610         
611         private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean forceUpdate) throws Exception {
612                 if (DEBUG)
613                         System.out.println("PipingRules.checkExpandPathLeg() " + u + " " + lengthChange);
614                 if (lengthChange != PathLegUpdateType.NONE) {
615                         // FIXME : turns cannot be checked before inline cps are updated,
616                         // since their position affects calculation of turns
617                         processPathLeg(u, forceUpdate, false);
618                         int type = checkTurns(u, lengthChange);
619                         if (type == REMOVE_NONE) {
620                                 processPathLeg(u, forceUpdate, true);
621                         } else {
622                                 expandPathLeg(u, type);
623                         }
624                 } else {
625                         processPathLeg(u, forceUpdate, true);
626                 }
627         }
628
629         private static void updateDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
630                 if (DEBUG)
631                         System.out.println("PipingRules.updateDirectedPipeRun() " + u + " " + lengthChange);
632                 PipeControlPoint dcp;
633                 PipeControlPoint other;
634                 boolean canMoveOther = false;
635                 boolean dcpStart = false;
636                 boolean inlineEnd = false;
637                 Vector3d position;
638                 if (u.start.isDirected()) {
639                         dcp = u.start;
640                         other = u.end;
641                         position = u.startPoint;
642                         dcpStart = true;
643                         if (!u.reversed)
644                                 canMoveOther = true;
645                         inlineEnd = u.end.isInline();
646                                 
647                 } else {
648                         dcp = u.end;
649                         other = u.start;
650                         position = u.endPoint;
651                         if (u.reversed)
652                                 canMoveOther = true;
653                         inlineEnd = u.start.isInline();
654                 }
655
656                 Vector3d directedDirection = dcp.getDirection();
657                 Point3d directedEndPoint = new Point3d(u.endPoint);
658                 if (u.hasOffsets)
659                         directedEndPoint.add(u.offset);
660
661                 double mu[] = new double[2];
662
663                 Vector3d closest;
664                 Vector3d t = new Vector3d();
665
666                 if (dcpStart) {
667                         closest = MathTools.closestPointOnStraight(directedEndPoint, u.startPoint, directedDirection, mu);
668                         t.sub(closest, directedEndPoint);
669                 } else {
670                         closest = MathTools.closestPointOnStraight(u.startPoint, directedEndPoint, directedDirection, mu);
671                         t.sub(closest, u.startPoint);
672                 }
673
674                 double distance = t.lengthSquared();
675                 boolean aligned = (distance < 0.002);
676                 if (aligned) {
677                         checkExpandPathLeg(u, lengthChange, inlineEnd);
678                         
679                 } else {
680                         if (u.iter > 0) {
681                                 backIter(u);
682                         } else {
683                                 PipeControlPoint nextToMoved;
684
685                                 if (u.list.size() > 0)
686                                         if (dcpStart)
687                                                 nextToMoved = u.list.get(0);
688                                         else
689                                                 nextToMoved = u.list.get(u.list.size() - 1);
690                                 else if (dcpStart)
691                                         nextToMoved = u.end;
692                                 else
693                                         nextToMoved = u.start;
694                                 if (other.isVariableAngle()) {
695
696                                         // TODO calculate needed space from next run end.
697                                         if (mu[0] < 1.0) {
698                                                 if (dcpStart) {
699                                                         closest.set(u.startPoint);
700                                                 } else {
701                                                         closest.set(u.endPoint);
702                                                 }
703                                                 closest.add(directedDirection);
704                                         }
705
706                                         if (canMoveOther) {
707                                                 if (DEBUG)
708                                                         System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + closest);
709                                                 other.setWorldPosition(closest);
710                                                 if (dcpStart) {
711                                                         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));
712                                                         if (u.end.getNext() != null)
713                                                                 updatePathLegNext(u.end, u.updated, PathLegUpdateType.NEXT);
714                                                 } else {
715                                                         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));
716                                                         if (u.start.getPrevious() != null)
717                                                                 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.PREV);
718                                                 }
719                                         } else {
720                                                 // TODO : calculate needed space from next run end.
721                                                 if (allowInsertRemove)
722                                                         insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
723                                                         
724                                                 else
725                                                         triedIR = true;
726                                         }
727                                 } else if (other.isNonDirected() && other.getParentPoint() != null) {
728                                         // FIXME : this code was for updating branches
729                                         Vector3d bintersect = new Vector3d();
730                                         PipeControlPoint bcp = other.getParentPoint();
731                                         if (bcp != null && canMoveOther) {
732                                                 Point3d bstart = new Point3d();
733                                                 Point3d bend = new Point3d();
734                                                 Vector3d bdir = new Vector3d();
735                                                 bcp.getInlineControlPointEnds(bstart, bend, bdir);
736                                                 Vector3d nintersect = new Vector3d();
737
738                                                 MathTools.intersectStraightStraight(position, directedDirection, bend, bdir, nintersect, bintersect, mu);
739                                                 Vector3d dist = new Vector3d(nintersect);
740                                                 dist.sub(bintersect);
741                                                 canMoveOther = mu[1] > 0.0 && mu[1] < 1.0 && dist.lengthSquared() < 0.01;
742                                         } else {
743                                                 // TODO : endControlPoints are undirected: calculcate
744                                                 // correct position for it
745                                                 throw new UnsupportedOperationException("not implemented");
746                                         }
747                                         if (canMoveOther) {
748                                                 if (DEBUG)
749                                                         System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + bintersect);
750                                                 // is required branch position is in possible range
751                                                 bcp.setWorldPosition(bintersect);
752                                                 if (dcpStart) {
753                                                         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);
754                                                 } else {
755                                                         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);
756                                                 }
757                                         } else {
758                                                 // branch cannot be moved into right position, new turn
759                                                 // / elbow must be inserted
760                                                 if (allowInsertRemove)
761                                                         insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
762                                                 else
763                                                         triedIR = true;
764                                         }
765
766                                 } else { // assume that control point cannot be moved, but can
767                                                         // be rotated
768                                         if (allowInsertRemove)
769                                                 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
770                                         else
771                                                 triedIR = true;
772                                 }
773                         }
774                 }
775                 
776                 
777         }
778
779         private static void updateDualDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
780                 if (DEBUG)
781                         System.out.println("PipingRules.updateDualDirectedPipeRun() " + u + " " + lengthChange);
782                 
783                 PipeControlPoint dcp1 = u.start;
784                 PipeControlPoint dcp2 = u.end;
785                 Point3d position1 = new Point3d(u.startPoint);
786                 Point3d position2 = new Point3d(u.endPoint);
787                 Point3d position1offset = new Point3d(position1);
788                 position1offset.sub(u.offset);
789                 Point3d position2offset = new Point3d(position2);
790                 position2offset.add(u.offset);
791                 Vector3d dir1 = dcp1.getDirection();
792                 Vector3d dir2 = dcp2.getDirection();
793                 Vector3d p1 = MathTools.closestPointOnStraight(position1offset, position2, dir2);
794                 Vector3d p2 = MathTools.closestPointOnStraight(position2offset, position1, dir1);
795                 double d1 = position1.distance(new Point3d(p1));
796                 double d2 = position2.distance(new Point3d(p2));
797
798                 boolean aligned = (d1 < 0.01 && d2 < 0.01);
799                 if (aligned) {
800                         processPathLeg(u);
801                 } else {
802                         if (u.iter > 0) {
803                                 backIter(u);
804                         } else if (allowInsertRemove){
805                                 PipeControlPoint dcp;
806                                 PipeControlPoint next;
807                                 if (!u.reversed) {
808                                         dcp = dcp1;
809                                         if (u.list.size() > 0)
810                                                 next = u.list.get(0);
811                                         else
812                                                 next = dcp2;
813                                 } else {
814                                         dcp = dcp2;
815                                         if (u.list.size() > 0)
816                                                 next = u.list.get(u.list.size() - 1);
817                                         else
818                                                 next = dcp1;
819                                 }
820                                 
821                                 p1 = dcp.getWorldPosition();
822                                 // FIXME: calculate position of the elbows properly.
823                                 if (!u.reversed)
824                                         p1.add(dir1);
825                                 else
826                                         p1.add(dir2);
827
828                                 if (!u.reversed)
829                                         p2 = MathTools.closestPointOnStraight(new Point3d(p1), position2, dir2);
830                                 else
831                                         p2 = MathTools.closestPointOnStraight(new Point3d(p1), position1, dir1);
832
833                                 
834                                 PipeControlPoint tcp1 = insertElbow(dcp, next, p1);
835                                 PipeControlPoint tcp2 = insertElbow(tcp1, next, p2);
836
837                                 if (DEBUG)
838                                         System.out.println("PipingRules.updateDualDirectedPipeRun() created two turns " + tcp1 + " " + tcp2);
839
840                                 if (!u.reversed) {
841                                         Vector3d dd = new Vector3d(p2);
842                                         dd.sub(p1);
843                                         dir2.negate();
844                                         updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
845                                         updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
846                                         if (!u.reversed)
847                                                 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
848                                         else
849                                                 updatePathLegPrev(tcp2, u.updated, PathLegUpdateType.NONE);
850                                 } else {
851                                         Vector3d dd = new Vector3d(p1);
852                                         dd.sub(p2);
853                                         dir2.negate();
854                                         updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
855                                         updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
856                                         if (!u.reversed)
857                                                 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
858                                         else
859                                                 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.NONE);
860                                 }
861                         } else {
862                                 triedIR = true;
863                         }
864                 }
865                 
866         }
867
868         private static void insertElbowUpdate(UpdateStruct2 u, PipeControlPoint dcp, PipeControlPoint next, boolean dcpStart, Vector3d position, Vector3d directedDirection) throws Exception{
869
870                 Vector3d closest = new Vector3d(position);
871                 closest.add(directedDirection);
872                 PipeControlPoint tcp = null;
873                 if (dcpStart)
874                         tcp = insertElbow(dcp, next, new Vector3d(closest));
875                 else
876                         tcp = insertElbow(next, dcp, new Vector3d(closest));
877
878                 if (DEBUG)
879                         System.out.println("PipingRules.updateDirectedPipeRun() inserted " + tcp);
880
881                 if (dcpStart) {
882                         // update pipe run from new turn to other end
883                         ppNoDir(tcp, new Vector3d(closest), u.list, u.end, u.endPoint, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
884                         // update pipe run from directed to new turn
885                         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));
886                 } else {
887                         // update pipe run from other end to new turn
888                         ppNoDir(u.start, u.startPoint, u.list, tcp, new Vector3d(closest), u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
889                         // update pipe run from new turn to directed
890                         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));
891                 }
892         }
893
894         /**
895          * Checks if turns can be removed (turn angle near zero)
896          */
897         private static int checkTurns(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
898                 if (DEBUG)
899                         System.out.println("PipingRules.checkTurns() " + u.start + " " + u.end);
900                 boolean startRemoved = false;
901                 boolean endRemoved = false;
902                 if (u.start.isVariableAngle()) {
903                         // this won't work properly if inline control points are not updated
904                         PipeControlPoint startPrev = u.start.getPrevious();
905                         if (startPrev != null) {
906                                 double a;
907                                 if (!u.hasOffsets) {
908                                         a = updateTurnControlPointTurn(u.start, startPrev, u.end);
909                                 } else {
910                                         Vector3d ep = new Vector3d(u.endPoint);
911                                         ep.add(u.offset);
912                                         a = updateTurnControlPointTurn(u.start, u.startPoint, startPrev.getPosition(), ep);
913
914                                 }
915                                 if (a < MIN_TURN_ANGLE && u.start.isDeletable())
916                                         startRemoved = true;
917                                 else if (lengthChange == PathLegUpdateType.PREV || lengthChange == PathLegUpdateType.PREV_S) {
918                                         PathLegUpdateType type;
919                                         if (lengthChange == PathLegUpdateType.PREV_S)
920                                                 type = PathLegUpdateType.PREV;
921                                         else
922                                                 type = PathLegUpdateType.NONE;
923                                         updatePathLegPrev(u.start, u.start, type);
924                                 }
925                         }
926                 }
927                 if (u.end.isVariableAngle()) {
928
929                         PipeControlPoint endNext = u.end.getNext();
930                         if (endNext != null) {
931                                 double a;
932                                 if (!u.hasOffsets) {
933                                         a = updateTurnControlPointTurn(u.end, u.start, endNext);
934                                 } else {
935                                         Vector3d sp = new Vector3d(u.startPoint);
936                                         sp.sub(u.offset);
937                                         a = updateTurnControlPointTurn(u.end, u.endPoint, sp, endNext.getPosition());
938                                 }
939                                 if (a < MIN_TURN_ANGLE && u.end.isDeletable())
940                                         endRemoved = true;
941                                 else if (lengthChange == PathLegUpdateType.NEXT || lengthChange == PathLegUpdateType.NEXT_S) {
942                                         PathLegUpdateType type;
943                                         if (lengthChange == PathLegUpdateType.NEXT_S)
944                                                 type = PathLegUpdateType.NEXT;
945                                         else
946                                                 type = PathLegUpdateType.NONE;
947                                         updatePathLegNext(u.end, u.end, type);
948                                 }
949                         }
950                 }
951                 if (DEBUG)
952                         System.out.println("PipingRules.checkTurns() res " + startRemoved + " " + endRemoved);
953                 if (!startRemoved && !endRemoved)
954                         return REMOVE_NONE;
955                 if (startRemoved && endRemoved)
956                         return REMOVE_BOTH;
957                 if (startRemoved)
958                         return REMOVE_START;
959                 return REMOVE_END;
960         }
961
962         /**
963          * Expands piperun search over turns that are going to be removed
964          * 
965          */
966         private static void expandPathLeg(UpdateStruct2 u, int type) throws Exception {
967                 if (DEBUG)
968                         System.out.println("PipingRules.expandPipeline " + u.start + " " + u.end);
969                 ArrayList<PipeControlPoint> newList = new ArrayList<PipeControlPoint>();
970                 switch (type) {
971                 case REMOVE_NONE:
972                         throw new RuntimeException("Error in piping rules");
973                 case REMOVE_START:
974                         u.toRemove.add(new ExpandIterInfo(u.start, REMOVE_START));
975                         u.start = u.start.findPreviousEnd();
976                         u.startPoint = u.start.getPosition();
977                         u.start.findNextEnd(newList);
978                         newList.addAll(u.list);
979                         u.list = newList;
980                         break;
981                 case REMOVE_END:
982                         u.toRemove.add(new ExpandIterInfo(u.end, REMOVE_END));
983                         u.end = u.end.findNextEnd(newList);
984                         u.endPoint = u.end.getPosition();
985                         u.list.addAll(newList);
986                         break;
987                 case REMOVE_BOTH:
988                         u.toRemove.add(new ExpandIterInfo(u.start, u.end));
989                         u.start = u.start.findPreviousEnd();
990                         u.startPoint = u.start.getPosition();
991                         u.start.findNextEnd(newList);
992                         newList.addAll(u.list);
993                         u.list = newList;
994                         newList = new ArrayList<PipeControlPoint>();
995                         u.end = u.end.findNextEnd(newList);
996                         u.endPoint = u.end.getPosition();
997                         u.list.addAll(newList);
998                         break;
999                 default:
1000                         throw new RuntimeException("Error in piping rules");
1001
1002                 }
1003                 u.offset = new Vector3d();
1004                 if (u.hasOffsets) {
1005                         u.dir.normalize();
1006                         for (PipeControlPoint icp : u.list) {
1007                                 if (icp.isOffset()) {
1008                                         u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1009                                 } else if (icp.isDualSub())
1010                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1011                         }
1012                 }
1013                 if (DEBUG)
1014                         System.out.println("PipingRules.expandPipeline expanded " + u.start + " " + u.end);
1015                 u.iter++;
1016                 updatePathLeg(u, PathLegUpdateType.NONE);
1017         }
1018
1019         /**
1020          * reverts one iteration of turn removing back)
1021          */
1022         private static void backIter(UpdateStruct2 u) throws Exception {
1023
1024                 if (DEBUG)
1025                         System.out.println("PipingRules.backIter" + u.start + " " + u.end);
1026                 if (u.iter == 0)
1027                         throw new RuntimeException("Error in piping rules");
1028                 ExpandIterInfo info = u.toRemove.get(u.toRemove.size() - 1);
1029                 u.toRemove.remove(u.toRemove.size() - 1);
1030                 if (info.getType() == REMOVE_START || info.getType() == REMOVE_BOTH) {
1031                         while (u.list.size() > 0) {
1032                                 PipeControlPoint icp = u.list.get(0);
1033                                 if (icp.getPrevious().equals(info.getStart()))
1034                                         break;
1035                                 u.list.remove(icp);
1036                         }
1037                         u.start = info.getStart();
1038                 }
1039                 if (info.getType() == REMOVE_END || info.getType() == REMOVE_BOTH) {
1040                         while (u.list.size() > 0) {
1041                                 PipeControlPoint icp = u.list.get(u.list.size() - 1);
1042                                 if (icp.getNext().equals(info.getEnd()))
1043                                         break;
1044                                 u.list.remove(icp);
1045                         }
1046                         u.end = info.getEnd();
1047                 }
1048                 u.offset = new Vector3d();
1049                 if (u.hasOffsets) {
1050                         u.dir.normalize();
1051                         for (PipeControlPoint icp : u.list) {
1052                                 if (icp.isOffset()) {
1053                                         u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1054                                 } else if (icp.isDualSub())
1055                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1056                         }
1057                 }
1058                 processPathLeg(u);
1059
1060         }
1061
1062         /**
1063          * Processes pipe run (removes necessary turns and updates run ends)
1064          */
1065         // private static void processPathLeg(PipeControlPoint start, Point3d
1066         // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1067         // end,Point3d endPoint, Vector3d dir,Vector3d offset, boolean
1068         // hasOffsets,int iter, boolean reversed, ArrayList<ExpandIterInfo>
1069         // toRemove) throws TransactionException {
1070
1071         private static void processPathLeg(UpdateStruct2 u) throws Exception {
1072                 if (DEBUG)
1073                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1074                 processPathLeg(u, true, true);
1075         }
1076
1077         private static void processPathLeg(UpdateStruct2 u, boolean updateEnds, boolean updateInline) throws Exception {
1078                 if (DEBUG)
1079                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1080
1081                 if (u.toRemove.size() > 0) {
1082                         for (ExpandIterInfo info : u.toRemove) {
1083                                 if (info.getStart() != null) {
1084                                         info.getStart()._remove();
1085                                 }
1086                                 if (info.getEnd() != null) {
1087                                         info.getEnd()._remove();
1088                                 }
1089                         }
1090                         // ControlPointTools.removeControlPoint may remove mo0re than one
1091                         // CP;
1092                         // we must populate inline CP list again.
1093                         u.list.clear();
1094                         u.start.findNextEnd( u.list);
1095                 }
1096                 // FIXME : inline CPs are update twice because their positions must be
1097                 // updated before and after ends.
1098                 updateInlineControlPoints(u, false);
1099                 
1100                 if (updateEnds) {
1101                         if (u.start.isTurn()) {
1102                                 updateTurnControlPointTurn(u.start, u.start.getPrevious(), u.start.getNext());
1103 //                              updatePathLegPrev(u.start, u.start, PathLegUpdateType.NONE);
1104                         } else if (u.start.isEnd()) {
1105                                 updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint);
1106                         } else if (u.start.isInline()) {
1107                                 updateControlPointOrientation(u.start);
1108                         }
1109                         if (u.end.isTurn()) {
1110                                 updateTurnControlPointTurn(u.end, u.end.getPrevious(), u.end.getNext());
1111 //                              updatePathLegNext(u.end, u.end, PathLegUpdateType.NONE);
1112                         } else if (u.end.isEnd()) {
1113                                 updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint);
1114                         } else if (u.end.isInline()) {
1115                                 updateControlPointOrientation(u.end);
1116                         }
1117
1118                 } else {
1119                         if (u.start.isEnd()) {
1120                                 updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint);
1121                         }
1122                         if (u.end.isEnd()) {
1123                                 updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint);
1124                         }
1125                 }
1126                 if (updateInline)
1127                         updateInlineControlPoints(u, true);
1128
1129         }
1130
1131         /**
1132          * Processes pipe run and recalculates offset
1133          */
1134         // private static void processPathLeg(PipeControlPoint start, Point3d
1135         // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1136         // end,Point3d endPoint, Vector3d dir, boolean hasOffsets,int iter, boolean
1137         // reversed, ArrayList<ExpandIterInfo> toRemove) throws TransactionException
1138         // {
1139         private static void processPathLegNoOffset(UpdateStruct2 u) throws Exception {
1140                 if (DEBUG)
1141                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1142                 Vector3d offset = new Vector3d();
1143                 if (u.hasOffsets) {
1144                         u.dir.normalize();
1145                         for (PipeControlPoint icp : u.list) {
1146                                 if (icp.isOffset()) {
1147                                         offset.add(icp.getSizeChangeOffsetVector(u.dir));
1148                                 } else if (icp.isDualSub()) {
1149                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1150                                 }
1151                         }
1152                 }
1153                 processPathLeg(u);
1154         }
1155
1156         private static void updateOffsetPoint(PipeControlPoint sccp, Vector3d offset) {
1157                 Vector3d world = sccp.getWorldPosition();
1158                 world.add(offset);
1159                 PipeControlPoint ocp = sccp.getSubPoint().iterator().next();
1160                 ocp.setWorldPosition(world);
1161         }
1162
1163         private static void updatePathLegPrev(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
1164                 ArrayList<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
1165                 PipeControlPoint end = start.findPreviousEnd(list);
1166                 updatePathLegPrev(start, list, end, updated, lengthChange);
1167         }
1168
1169         private static void updatePathLegPrev(PipeControlPoint start, ArrayList<PipeControlPoint> list, PipeControlPoint end, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
1170                 // reverses the list
1171                 ArrayList<PipeControlPoint> nextList = new ArrayList<PipeControlPoint>();
1172                 for (PipeControlPoint icp : list) {
1173                         if (icp.isDualSub()) {
1174                                 nextList.add(0, icp.getParentPoint());
1175                         } else {
1176                                 nextList.add(0, icp);
1177                         }
1178
1179                 }
1180                 updatePathLeg(end, nextList, start, true, 0, new ArrayList<ExpandIterInfo>(), updated, lengthChange);
1181
1182         }
1183
1184         /**
1185          * Updates InlineControlPoints position when straight pipe's end(s) have
1186          * been changed)
1187          * 
1188          * @param pipeline
1189          * @param icp
1190          * @param nextPoint
1191          * @param prevPoint
1192          */
1193         private static void updateInlineControlPoint(PipeControlPoint icp, Vector3d nextPoint, Vector3d prevPoint, Vector3d dir) {
1194                 if (DEBUG)
1195                         System.out.println("PipingRules.updateInlineControlPoint() " + icp);
1196
1197                 Vector3d inlinePoint = icp.getWorldPosition();
1198                 if (DEBUG)
1199                         System.out.print("InlineControlPoint update " + icp + " " + inlinePoint + " " + prevPoint + " " + nextPoint);
1200                 Vector3d newInlinePoint = null;
1201                 boolean branchUpdate = false;
1202                 PipeControlPoint becp = null;
1203                 for (PipeControlPoint pcp : icp.getSubPoint())
1204                         if (pcp.isNonDirected()) {
1205                                 branchUpdate = true;
1206                                 becp = pcp;
1207                                 break;
1208                         }
1209
1210                 if (DUMMY || !branchUpdate) {
1211                         newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), new Vector3d(nextPoint), new Vector3d(prevPoint));
1212                 } else {
1213
1214                         // FIXME : can only handle one branch
1215                         PipeControlPoint p = null;
1216                         if (becp.getNext() != null) {
1217                                 p = becp.findNextEnd();
1218                         } else if (becp.getPrevious() != null) {
1219                                 p = becp.findPreviousEnd();
1220                         }
1221                         if (p == null) {
1222                                 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), new Vector3d(nextPoint), new Vector3d(prevPoint));
1223                         } else {
1224                                 Vector3d branchLegEnd = p.getWorldPosition();
1225                                 Vector3d dir2 = new Vector3d(inlinePoint);
1226                                 dir2.sub(branchLegEnd);
1227                                 Vector3d dir1 = new Vector3d(nextPoint);
1228                                 dir1.sub(prevPoint);
1229                                 newInlinePoint = new Vector3d();
1230                                 double mu[] = new double[2];
1231                                 MathTools.intersectStraightStraight(new Vector3d(prevPoint), dir1, new Vector3d(branchLegEnd), dir2, newInlinePoint, new Vector3d(), mu);
1232                                 if (DEBUG)
1233                                         System.out.println(mu[0]);
1234                                 // FIXME : reserve space
1235                                 if (mu[0] < 0.0) {
1236                                         newInlinePoint = new Vector3d(prevPoint);
1237                                 } else if (mu[0] > 1.0) {
1238                                         newInlinePoint = new Vector3d(nextPoint);
1239                                 }
1240                         }
1241                 }
1242                 if (DEBUG)
1243                         System.out.println(" " + newInlinePoint);
1244
1245                 icp.setWorldPosition(newInlinePoint);
1246                 updateControlPointOrientation(icp);
1247         }
1248
1249         /**
1250          * Updates InlineControlPoints position when straight pipe's end(s) have
1251          * been changed)
1252          * 
1253          * @param pipeline
1254          * @param icp
1255          * @param nextPoint
1256          * @param prevPoint
1257          */
1258         private static void updateEndComponentControlPoint(PipeControlPoint ecp, Vector3d start, Vector3d end) throws Exception {
1259                 if (DEBUG)
1260                         System.out.println("PipingRules.updateEndComponentControlPoint() " + ecp);
1261                 // PipeControlPoint next = ecp.getNext();
1262                 // PipeControlPoint prev = ecp.getPrevious();
1263                 // if (next != null) {
1264                 // end = G3DTools.getPoint(next.getLocalPosition());
1265                 // start = G3DTools.getPoint(ecp.getLocalPosition());
1266                 // } else if (prev != null) {
1267                 // end = G3DTools.getPoint(ecp.getLocalPosition());
1268                 // start = G3DTools.getPoint(prev.getLocalPosition());
1269                 // } else {
1270                 // // TODO : warning?
1271                 // return;
1272                 // }
1273                 // Vector3d dir = new Vector3d (end);
1274                 // dir.sub(start);
1275                 // dir.normalize();
1276                 // G3DTools.setTuple(ecp.getDirection(), dir);
1277                 if (!ecp.isFixed())
1278                         updateControlPointOrientation(ecp);
1279
1280                 for (PipeControlPoint pcp : ecp.getSubPoint()) {
1281                         // TODO update position
1282                         updatePathLegEndControlPoint(pcp);
1283                 }
1284         }
1285
1286         private static void updateControlPointOrientation(PipeControlPoint pcp) {
1287                 // FIXME : hack to bypass variable length components orientation
1288 //              if (pcp.getAtMostOneRelatedObject(ProcessResource.g3dResource.HasWorldOrientation) == null)
1289 //                      return;
1290 //              if (pcp.rotationAngle == null)
1291 //                      return;
1292                 Double angleO = pcp.getRotationAngle();
1293                 double angle = 0.0;
1294                 if (angleO != null)
1295                         angle = angleO;
1296
1297                 Quat4d q = pcp.getControlPointOrientationQuat(angle);
1298                 pcp.setWorldOrientation(q);
1299         }
1300
1301         /**
1302          * Updates all branches when branch's position has been changed
1303          * 
1304          * @param bcp
1305          */
1306         private static void updateBranchControlPointBranches(PipeControlPoint bcp) throws Exception {
1307                 if (DEBUG)
1308                         System.out.println("PipingRules.updateBranchControlPointBranches() " + bcp);
1309                 if (bcp.isDualInline())
1310                         return;
1311                 Collection<PipeControlPoint> branches = bcp.getSubPoint();
1312                 if (branches.size() == 0) {
1313                         if (DEBUG)
1314                                 System.out.println("No Branches found");
1315                         return;
1316                 }
1317                 
1318                 for (PipeControlPoint pcp : branches) {
1319                         updatePathLegEndControlPoint(pcp);
1320                 }
1321         }
1322
1323         /**
1324          * Recalculates turn control point's internal data (turn angle and offset)
1325          * 
1326          * @param tcp
1327          * @param prev
1328          * @param next
1329          */
1330         private static double updateTurnControlPointTurn(PipeControlPoint tcp, PipeControlPoint prev, PipeControlPoint next) {
1331                 if (DEBUG)
1332                         System.out.println("PipingTools.updateTurnControlPointTurn()" + tcp);
1333                 if (next == null || prev == null)
1334                         return Math.PI; // FIXME : argh
1335                 Vector3d middlePoint = tcp.getWorldPosition();
1336                 Vector3d nextPoint = next.getWorldPosition();
1337                 Vector3d prevPoint = prev.getWorldPosition();
1338                 return updateTurnControlPointTurn(tcp, middlePoint, prevPoint, nextPoint);
1339         }
1340
1341         /**
1342          * Recalculates turn control point's internal data (turn angle and offset)
1343          * 
1344          * @param tcp
1345          * @param middlePoint
1346          * @param nextPoint
1347          * @param prevPoint
1348          */
1349         private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d middlePoint, Vector3d prevPoint, Vector3d nextPoint) {
1350
1351                 Vector3d dir1 = new Vector3d(middlePoint);
1352                 dir1.sub(prevPoint);
1353                 Vector3d dir2 = new Vector3d(nextPoint);
1354                 dir2.sub(middlePoint);
1355                 if (DEBUG)
1356                         System.out.println("PipingTools.updateTurnControlPointTurn " + tcp + " " + prevPoint + " " + middlePoint + " " + nextPoint);
1357                 return updateTurnControlPointTurn(tcp, dir1, dir2);
1358         }
1359
1360         private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d dir1, Vector3d dir2) {
1361                 double turnAngle = dir1.angle(dir2);
1362
1363                 double angle = Math.PI - turnAngle;
1364
1365                 Vector3d turnAxis = new Vector3d();
1366                 turnAxis.cross(dir1, dir2);
1367                 if (turnAxis.lengthSquared() > MathTools.NEAR_ZERO) {
1368                         double elbowRadius = tcp.getPipelineComponent().getPipeRun().getTurnRadius();
1369                         double R = elbowRadius / Math.tan(angle * 0.5);
1370                         
1371                         turnAxis.normalize();
1372                         tcp.setTurnAngle(turnAngle);
1373                         tcp.setLength(R);// setComponentOffsetValue(R);
1374                         tcp.setTurnAxis(turnAxis);
1375 //                      tcp.setPosition(tcp.getPosition());
1376                 } else {
1377                         turnAngle = 0.0;
1378                         tcp.setTurnAngle(0.0);
1379                         tcp.setLength(0.0);
1380                         tcp.setTurnAxis(MathTools.Y_AXIS);
1381                 }
1382                 updateControlPointOrientation(tcp);
1383                 if (DEBUG)
1384                         System.out.println("PipingTools.updateTurnControlPointTurn " + dir1 + " " + dir2 + " " + turnAngle + " " + turnAxis);
1385                 return turnAngle;
1386         }
1387         
1388         public static List<PipeControlPoint> getControlPoints(PipeRun pipeRun) {
1389                 List<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
1390                 if (pipeRun.getControlPoints().size() == 0)
1391                         return list;
1392                 PipeControlPoint pcp = pipeRun.getControlPoints().iterator().next();
1393                 while (pcp.getPrevious() != null) {
1394                         PipeControlPoint prev = pcp.getPrevious();
1395                         if (prev.getPipeRun() != pipeRun)
1396                                 break;
1397                         pcp = prev;
1398                 }
1399                 if (pcp.isDualSub()) {
1400                         pcp = pcp.getParentPoint();
1401                 }
1402                 list.add(pcp);
1403                 while (pcp.getNext() != null) {
1404                         pcp = pcp.getNext();
1405                         if (pcp.getPipeRun() != pipeRun)
1406                                 break;
1407                         list.add(pcp);
1408                 }
1409                 return list;
1410         }
1411         
1412         public static void reverse(PipeRun pipeRun) {
1413                 List<PipeControlPoint> list = getControlPoints(pipeRun);
1414                 if (list.size() <= 1)
1415                         return; // nothing to do.
1416                 
1417                 for (int i = 0 ; i < list.size(); i++) {
1418                         boolean first = i == 0;
1419                         boolean last = i == list.size() - 1;
1420                         PipeControlPoint current = list.get(i);
1421                         PipeControlPoint currentSub = null;
1422                         if (current.isDualInline())
1423                                 currentSub = current.getSubPoint().get(0);
1424                         if (first) {
1425                                 PipeControlPoint next = list.get(i+1);
1426                                 if (next.isDualInline())
1427                                         next = next.getSubPoint().get(0);
1428                                 current.setNext(null);
1429                                 current.setPrevious(next);
1430                                 if (currentSub != null) {
1431                                         currentSub.setNext(null);
1432                                         currentSub.setPrevious(next);           
1433                                 }
1434                         } else if (last) {
1435                                 PipeControlPoint prev = list.get(i-1);
1436                                 
1437                                 current.setPrevious(null);
1438                                 current.setNext(prev);
1439                                 
1440                                 if (currentSub != null) {
1441                                         currentSub.setPrevious(null);
1442                                         currentSub.setNext(prev);               
1443                                 }
1444                         } else {
1445                                 PipeControlPoint prev = list.get(i-1);
1446                                 PipeControlPoint next = list.get(i+1);
1447                                 if (next.isDualInline())
1448                                         next = next.getSubPoint().get(0);
1449                                 
1450                                 
1451                                 current.setPrevious(next);
1452                                 current.setNext(prev);
1453                                 
1454                                 if (currentSub != null) {
1455                                         currentSub.setPrevious(next);
1456                                         currentSub.setNext(prev);               
1457                                 }
1458                                 
1459                         }
1460                 }
1461         }
1462         
1463         public static void merge(PipeRun run1, PipeRun r2) {
1464                 Map<PipeControlPoint, Vector3d> positions = new HashMap<PipeControlPoint, Vector3d>();
1465                 Map<PipeControlPoint, Quat4d> orientations = new HashMap<PipeControlPoint, Quat4d>();
1466                 for (PipeControlPoint pcp : r2.getControlPoints()) {
1467                         positions.put(pcp, pcp.getWorldPosition());
1468                         orientations.put(pcp, pcp.getWorldOrientation());
1469                 }
1470                 for (PipeControlPoint pcp : r2.getControlPoints()) {
1471                         r2.deattachChild(pcp);
1472                         run1.addChild(pcp);
1473                         PipelineComponent component = pcp.getPipelineComponent();
1474                         if (component != null) {
1475                                 if (!(component instanceof Nozzle)) {
1476                                         component.deattach();
1477                                         run1.addChild(component);
1478                                 } else {
1479                                         Nozzle n = (Nozzle)component;
1480                                         n.setPipeRun(run1);
1481                                 }
1482                         }
1483                 }
1484                 r2.remove();
1485                 
1486         }
1487         
1488         public static void validate(PipeRun pipeRun) {
1489                 if (pipeRun == null)
1490                         return;
1491                 Collection<PipeControlPoint> pcps = pipeRun.getControlPoints();
1492                 int count = 0;
1493                 for (PipeControlPoint pcp : pcps) {
1494                         if (pcp.getParentPoint() == null || pcp.getParentPoint().getPipeRun() != pipeRun)
1495                                 count++;
1496                 }
1497                 List<PipeControlPoint> runPcps = getControlPoints(pipeRun);
1498                 if (runPcps.size() != count) {
1499                         System.out.println("Run is not connected");
1500                 }
1501                 for (PipeControlPoint pcp : pcps) {
1502                         if (pcp.getParentPoint() == null) {
1503                                 PipeControlPoint sub = null;
1504                                 if (pcp.isDualInline())
1505                                         sub = pcp.getSubPoint().get(0);
1506                                 PipeControlPoint next = pcp.getNext();
1507                                 PipeControlPoint prev = pcp.getPrevious();
1508                                 if (next != null) {
1509                                         if (!(next.getPrevious() == pcp || next.getPrevious() == sub)) {
1510                                                 System.out.println("Inconsistency between " + pcp + " -> " +next );
1511                                         }
1512                                 }
1513                                 if (prev != null) {
1514                                         PipeControlPoint prevParent = null;
1515                                         if (prev.isDualSub()) {
1516                                                 prevParent = prev.getParentPoint();
1517                                         } else if (prev.isDualInline()) {
1518                                                 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1519                                         }
1520                                         if (!(prev.getNext() == pcp && (prevParent == null || prevParent.getNext() == pcp))) {
1521                                                 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1522                                         }
1523                                 }
1524                         }
1525                 }
1526         }
1527         
1528         public static void splitVariableLengthComponent(PipelineComponent newComponent, InlineComponent splittingComponent, boolean assignPos) throws Exception{
1529                 assert(!splittingComponent.getControlPoint().isFixed());
1530                 assert(!(newComponent instanceof  InlineComponent && !newComponent.getControlPoint().isFixed()));
1531                 PipeControlPoint newCP = newComponent.getControlPoint();
1532                 PipeControlPoint splittingCP = splittingComponent.getControlPoint();
1533                 PipeControlPoint nextCP = splittingCP.getNext();
1534                 PipeControlPoint prevCP = splittingCP.getPrevious();
1535                 
1536                 /* there are many different cases to insert new component when
1537                    it splits existing VariableLengthinlineComponent.
1538             
1539                1. VariableLengthComponet is connected from both sides:
1540                   - insert new component between VariableLength component and component connected to it
1541                   - insert new VariableLengthComponent between inserted component and component selected in previous step
1542                 
1543                    2. VariableLengthComponent is connected from one side
1544                      - Use previous case or:
1545                      - Insert new component to empty end
1546                      - Insert new VariableLength component to inserted components empty end
1547                      
1548                    3. VariableLength is not connected to any component.
1549                      - Should not be possible, at least in current implementation.
1550                      - Could be done using second case
1551
1552                 */
1553                 
1554                 if (nextCP == null && prevCP == null) {
1555                         // this should not be possible
1556                         throw new RuntimeException("VariableLengthComponent " + splittingComponent + " is not connected to anything.");
1557                 }
1558                 double reservedLength = splittingComponent.getControlPoint().getLength();
1559                 double newLength = newComponent.getControlPoint().getLength();
1560                 
1561                 
1562                 Point3d next = new Point3d();
1563                 Point3d prev = new Point3d();
1564                 splittingCP.getInlineControlPointEnds(prev, next);
1565                 
1566                 Vector3d newPos = null;
1567                 if (assignPos) {
1568                         newPos = new Vector3d(prev);
1569                         Vector3d dir = new Vector3d(next);
1570                         dir.sub(prev);
1571                         dir.scale(0.5);
1572                         newPos.add(dir);
1573                         newComponent.setWorldPosition(newPos);
1574                 } else {
1575                         newPos = newComponent.getWorldPosition();
1576                 }
1577                 
1578                 
1579
1580                 Vector3d dir = new Vector3d(next);
1581                 dir.sub(prev);
1582                 dir.normalize();
1583                 dir.scale(newLength * 0.5);
1584                 Point3d vn = new Point3d(newPos);
1585                 Point3d vp = new Point3d(newPos);
1586                 vn.add(dir);
1587                 vp.sub(dir);
1588                 double ln = vn.distance(next);
1589                 double lp = vp.distance(prev);
1590                 vp.interpolate(prev, 0.5);
1591                 vn.interpolate(next, 0.5);
1592                 
1593                 
1594                 PipeControlPoint newVariableLengthCP = null;//insertStraight(pcp1, pcp2, pos, length);
1595                 if (nextCP == null) {
1596                         newCP.insert(splittingCP, Direction.NEXT);
1597                         newVariableLengthCP = insertStraight(newCP, Direction.NEXT, new Vector3d(vn), ln);
1598                         splittingCP.setWorldPosition(new Vector3d(vp));
1599 //                      ControlPointTools.setWorldPosition(splittingCP, vp);
1600 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
1601                 } else if (prevCP == null) {
1602                         newCP.insert(splittingCP, Direction.PREVIOUS);
1603                         newVariableLengthCP = insertStraight(newCP, Direction.PREVIOUS, new Vector3d(vp), lp);
1604                         splittingCP.setWorldPosition(new Vector3d(vn));
1605 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, ln);
1606                 } else {
1607                         newCP.insert(splittingCP, nextCP);
1608                         newVariableLengthCP = insertStraight(newCP, nextCP, new Vector3d(vn), ln);
1609                         splittingCP.setWorldPosition(new Vector3d(vp));
1610 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
1611                 }
1612                 positionUpdate(newCP);
1613
1614         }
1615         
1616         public static void addSizeChange(boolean reversed, PipeRun pipeRun, PipeRun other, InlineComponent reducer, PipeControlPoint previous, PipeControlPoint next) {
1617                 PipeControlPoint pcp = reducer.getControlPoint();
1618                 PipeControlPoint ocp = pcp.getSubPoint().get(0);
1619                 if (!reversed) {
1620                         String name = pipeRun.getUniqueName("Reducer");
1621                         reducer.setName(name);
1622                         pipeRun.addChild(reducer);
1623                         other.addChild(ocp);
1624                         reducer.setAlternativePipeRun(other);
1625                         
1626                         previous.setNext(pcp);
1627                         pcp.setPrevious(previous);
1628                         ocp.setPrevious(previous);
1629                         if (next != null) {
1630                                 pcp.setNext(next);
1631                                 ocp.setNext(next);
1632                                 next.setPrevious(ocp);
1633                         }
1634                 } else {
1635                         String name = other.getUniqueName("Reducer");
1636                         reducer.setName(name);
1637                         other.addChild(reducer);
1638                         pipeRun.addChild(ocp);
1639                         reducer.setAlternativePipeRun(pipeRun);
1640                         
1641                         if (next != null) {
1642                                 next.setNext(pcp);
1643                                 pcp.setPrevious(next);
1644                                 ocp.setPrevious(next);
1645                         }
1646                         pcp.setNext(previous);
1647                         ocp.setNext(previous);
1648                         previous.setPrevious(ocp);
1649                 }
1650         }
1651 }