1 package org.simantics.plant3d.scenegraph.controlpoint;
3 import java.util.ArrayList;
4 import java.util.Collection;
7 import javax.vecmath.Point3d;
8 import javax.vecmath.Quat4d;
9 import javax.vecmath.Vector3d;
11 import org.simantics.g3d.math.MathTools;
12 import org.simantics.plant3d.scenegraph.InlineComponent;
13 import org.simantics.plant3d.scenegraph.P3DRootNode;
14 import org.simantics.plant3d.scenegraph.PipeRun;
15 import org.simantics.plant3d.scenegraph.PipelineComponent;
16 import org.simantics.plant3d.scenegraph.TurnComponent;
17 import org.simantics.plant3d.scenegraph.controlpoint.PipeControlPoint.Direction;
18 import org.simantics.plant3d.utils.ComponentUtils;
19 import org.simantics.utils.datastructures.Pair;
20 import org.simantics.utils.ui.ErrorLogger;
22 public class PipingRules {
23 private static final boolean DEBUG = false;
24 private static final boolean DUMMY = false;
26 private static double MIN_TURN_ANGLE = 0.001; // Threshold for removing turn components.
27 private static double ALLOWED_OFFSET = 0.001; // Allowed offset for directed path legs
28 private static double MIN_INLINE_LENGTH = 0.0005; // Minimum length of inline components, when component removal is not allowed.
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;
36 // PathLeg iteration indicator. NEXT_S > NEXT > NONE PREV_S > PREV > NONE
37 private enum PathLegUpdateType {
38 NONE, // Only current path leg needs to be updated (for example, inline comp was moved)
39 PREV, // Current and previous path leg need to be updated
40 NEXT, // Current and next path leg need to be updated
41 PREV_S, // Current and previous two path legs need to be updated (turn was moved, which affect other path leg end turns, and thus following path legs
42 NEXT_S // Current and next two path legs need to be updated
45 private static boolean enabled = true; //
46 private static boolean updating = false;
47 private static boolean allowInsertRemove = true;
48 private static boolean triedIR = false;
51 private static List<PipeControlPoint> requestUpdates = new ArrayList<PipeControlPoint>();
52 private static List<PipeControlPoint> currentUpdates = new ArrayList<PipeControlPoint>();
54 private static Object updateMutex = new Object();
55 private static Object ruleMutex = new Object();
57 public static void requestUpdate(PipeControlPoint pcp) {
58 if (!PipingRules.enabled)
60 if (DEBUG) System.out.println("PipingRules request " + pcp);
61 synchronized (updateMutex) {
62 if (!requestUpdates.contains(pcp))
63 requestUpdates.add(pcp);
67 public static boolean update() throws Exception {
68 if (!PipingRules.enabled)
71 if (requestUpdates.size() == 0)
74 List<PipeControlPoint> temp = new ArrayList<PipeControlPoint>(requestUpdates.size());
75 synchronized(updateMutex) {
76 temp.addAll(requestUpdates);
77 requestUpdates.clear();
79 synchronized (ruleMutex) {
80 currentUpdates.clear();
81 currentUpdates.addAll(temp);
82 // TODO : we should remove already processed control points from currentUpdates after each _positionUpdate call.
83 for (PipeControlPoint pcp : currentUpdates)
84 _positionUpdate(pcp, true);
85 currentUpdates.clear();
87 synchronized(updateMutex) {
88 requestUpdates.removeAll(temp);
94 public static boolean positionUpdate(PipeControlPoint pcp) throws Exception {
96 return positionUpdate(pcp, true);
99 public static boolean positionUpdate(PipeControlPoint pcp, boolean allowIR) throws Exception {
100 synchronized (ruleMutex) {
101 currentUpdates.add(pcp);
102 boolean b = _positionUpdate(pcp, allowIR);
103 currentUpdates.clear();
109 private static boolean _positionUpdate(PipeControlPoint pcp, boolean allowIR) throws Exception {
110 if (updating || !enabled)
112 if (pcp.getPipeRun() == null)
115 if (DEBUG) System.out.println("PipingRules " + pcp);
117 allowInsertRemove = allowIR;
119 validate(pcp.getPipeRun());
120 if (pcp.getParentPoint() != null)
121 pcp = pcp.getParentPoint();
122 if (pcp.asPathLegEnd()) {
123 updatePathLegEndControlPoint(pcp); // FIXME: Rules won't work properly, if they are not run twice.
124 //updatePathLegEndControlPoint(pcp);
126 updateInlineControlPoint(pcp);
127 //updateInlineControlPoint(pcp);
129 validate(pcp.getPipeRun());
130 if (!allowInsertRemove)
135 // System.out.println("PipingRules done " + pcp);
139 public static void setEnabled(boolean enabled) {
140 PipingRules.enabled = enabled;
142 currentUpdates.clear();
145 public static boolean isEnabled() {
149 public static class ExpandIterInfo {
150 // these two are turn control points
151 private PipeControlPoint start;
152 private PipeControlPoint end;
155 public ExpandIterInfo() {
159 public ExpandIterInfo(PipeControlPoint tcp, int type) {
160 if (type == REMOVE_START)
167 public ExpandIterInfo(PipeControlPoint start, PipeControlPoint end) {
170 this.type = REMOVE_BOTH;
173 public PipeControlPoint getEnd() {
177 public void setEnd(PipeControlPoint end) {
181 public PipeControlPoint getStart() {
185 public void setStart(PipeControlPoint start) {
189 public int getType() {
193 public void setType(int type) {
199 private static void updatePathLegEndControlPoint(PipeControlPoint pcp) throws Exception {
201 System.out.println("PipingRules.updatePathLegEndControlPoint() " + pcp);
202 if (pcp.getNext() != null) {
203 updatePathLegNext(pcp, pcp, PathLegUpdateType.NEXT_S);
205 if (pcp.getPrevious() != null) {
206 updatePathLegPrev(pcp, pcp, PathLegUpdateType.PREV_S);
211 private static void updateInlineControlPoint(PipeControlPoint pcp) throws Exception {
213 System.out.println("PipingRules.updateInlineControlPoint() " + pcp);
214 PipeControlPoint start = pcp.findPreviousEnd();
215 updatePathLegNext(start, pcp, PathLegUpdateType.NONE);
218 private static PipeControlPoint insertElbow(PipeControlPoint pcp1, PipeControlPoint pcp2, Vector3d pos) throws Exception{
220 System.out.println("PipingRules.insertElbow() " + pcp1 + " " + pcp2 + " " + pos);
221 if (pcp1.getNext() == pcp2 && pcp2.getPrevious() == pcp1) {
223 } else if (pcp1.getNext() == pcp2 && pcp1.isDualInline() && pcp2.getPrevious() == pcp1.getDualSub()) {
224 pcp1 = pcp1.getDualSub();
225 } else if (pcp1.getPrevious() == pcp2 && pcp2.getNext() == pcp1) {
226 PipeControlPoint t = pcp1;
229 } else if (pcp2.isDualInline() && pcp1.getPrevious() == pcp2.getDualSub() && pcp2.getNext() == pcp1) {
230 PipeControlPoint t = pcp1;
231 pcp1 = pcp2.getDualSub();
234 throw new RuntimeException();
236 TurnComponent elbow = ComponentUtils.createTurn((P3DRootNode)pcp1.getRootNode());
237 PipeControlPoint pcp = elbow.getControlPoint();
238 if (pcp1.isDualInline())
239 pcp1 = pcp1.getDualSub();
240 String name = pcp1.getPipeRun().getUniqueName("Elbow");
242 pcp1.getPipeRun().addChild(elbow);
244 pcp.insert(pcp1, pcp2);
246 pcp.setWorldPosition(pos);
247 validate(pcp.getPipeRun());
251 private static PipeControlPoint insertStraight(PipeControlPoint pcp1, PipeControlPoint pcp2, Vector3d pos, double length) throws Exception {
253 System.out.println("PipingRules.insertStraight() " + pcp1 + " " + pcp2 + " " + pos);
254 if (pcp1.getNext() == pcp2 && pcp2.getPrevious() == pcp1) {
256 } else if (pcp1.getNext() == pcp2 && pcp1.isDualInline() && pcp2.getPrevious() == pcp1.getDualSub()) {
257 pcp1 = pcp1.getDualSub();
258 } else if (pcp1.getPrevious() == pcp2 && pcp2.getNext() == pcp1) {
259 PipeControlPoint t = pcp1;
262 } else if (pcp2.isDualInline() && pcp1.getPrevious() == pcp2.getDualSub() && pcp2.getNext() == pcp1) {
263 PipeControlPoint t = pcp1;
264 pcp1 = pcp2.getDualSub();
267 throw new RuntimeException();
269 InlineComponent component = ComponentUtils.createStraight((P3DRootNode)pcp1.getRootNode());
270 PipeControlPoint scp = component.getControlPoint();
271 if (pcp1.isDualInline())
272 pcp1 = pcp1.getDualSub();
273 String name = pcp1.getPipeRun().getUniqueName("Pipe");
274 component.setName(name);
275 pcp1.getPipeRun().addChild(component);
277 scp.insert(pcp1, pcp2);
279 scp.setWorldPosition(pos);
280 scp.setLength(length);
281 validate(scp.getPipeRun());
285 private static PipeControlPoint insertStraight(PipeControlPoint pcp, Direction direction , Vector3d pos, double length) throws Exception {
287 System.out.println("PipingRules.insertStraight() " + pcp + " " + direction + " " + pos);
289 InlineComponent component = ComponentUtils.createStraight((P3DRootNode)pcp.getRootNode());
290 PipeControlPoint scp = component.getControlPoint();
291 if (pcp.isDualInline() && direction == Direction.NEXT)
292 pcp = pcp.getDualSub();
293 String name = pcp.getPipeRun().getUniqueName("Pipe");
294 component.setName(name);
295 pcp.getPipeRun().addChild(component);
297 scp.insert(pcp,direction);
299 scp.setWorldPosition(pos);
300 scp.setLength(length);
301 validate(scp.getPipeRun());
305 private static void updatePathLegNext(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
306 UpdateStruct2 us = createUS(start, Direction.NEXT, 0, new ArrayList<ExpandIterInfo>(), updated);
308 System.out.println("Null update struct " + start);
311 updatePathLeg(us, lengthChange);
314 private static void updatePathLegPrev(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
315 UpdateStruct2 us = createUS(start, Direction.PREVIOUS, 0, new ArrayList<ExpandIterInfo>(), updated);
317 System.out.println("Null update struct " + start);
320 updatePathLeg(us, lengthChange);
323 private static class UpdateStruct2 {
324 public PipeControlPoint start;
325 public Vector3d startPoint;
326 public ArrayList<PipeControlPoint> list;
327 public PipeControlPoint end;
328 public Vector3d endPoint;
330 public Vector3d offset;
331 public boolean hasOffsets;
333 public boolean reversed;
334 public ArrayList<ExpandIterInfo> toRemove;
335 public PipeControlPoint updated;
337 public UpdateStruct2(PipeControlPoint start, Vector3d startPoint, ArrayList<PipeControlPoint> list, PipeControlPoint end, Vector3d endPoint, Vector3d dir, Vector3d offset, boolean hasOffsets, int iter, boolean reversed, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated) {
338 if (start == null || end == null)
339 throw new NullPointerException();
341 this.startPoint = startPoint;
344 this.endPoint = endPoint;
346 this.offset = offset;
347 this.hasOffsets = hasOffsets;
349 this.reversed = reversed;
350 this.toRemove = toRemove;
351 this.updated = updated;
353 if (!MathTools.isValid(startPoint) ||
354 !MathTools.isValid(endPoint) ||
355 !MathTools.isValid(dir)) {
356 throw new RuntimeException();
360 public String toString() {
361 return start + " " + end+ " " + dir + " " + hasOffsets + " " + offset + " " + iter + " " + toRemove.size();
366 @SuppressWarnings("unused")
367 private static boolean calculateOffset(Vector3d startPoint, Vector3d endPoint, PipeControlPoint start, ArrayList<PipeControlPoint> list, PipeControlPoint end, Vector3d dir, Vector3d offset) {
368 boolean hasOffsets = false;
369 List<PipeControlPoint> offsets = new ArrayList<PipeControlPoint>(list.size());
370 // Only start offset affects the calculation
371 if (start.isOffset())
373 for (PipeControlPoint icp : list) {
374 if (icp.isOffset()) {
376 } else if (icp.isDualSub())
377 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
379 if (offsets.size() == 0) {
382 double l = dir.lengthSquared();
383 if (l > MathTools.NEAR_ZERO)
384 dir.scale(1.0/Math.sqrt(l));
385 offset.set(0.0, 0.0, 0.0);
388 Vector3d sp = new Vector3d(startPoint);
389 Point3d ep = new Point3d(endPoint);
392 double l = dir.lengthSquared();
393 if (l > MathTools.NEAR_ZERO)
394 dir.scale(1.0/Math.sqrt(l));
398 offset.set(0.0, 0.0, 0.0);
400 for (PipeControlPoint icp : offsets) {
401 Vector3d v = icp.getSizeChangeOffsetVector(dir);
404 Point3d nep = new Point3d(endPoint);
406 if (nep.distance(ep) < 0.0000000001) {
412 l = dir.lengthSquared();
413 if (l > MathTools.NEAR_ZERO)
414 dir.scale(1.0/Math.sqrt(l));
419 if (DEBUG && hasOffsets)
420 System.out.println("calcOffset s:"+ startPoint + " e:" + endPoint + " d:" + dir + " o:"+offset) ;
424 private static UpdateStruct2 createUS(PipeControlPoint start, Direction direction, int iter, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated) {
425 ArrayList<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
426 PipeControlPoint end = null;
427 if (direction == Direction.NEXT) {
428 end = start.findNextEnd(list);
430 ArrayList<PipeControlPoint> prevList = new ArrayList<PipeControlPoint>();
431 PipeControlPoint tend = start.findPreviousEnd(prevList);
432 for (PipeControlPoint icp : prevList) {
433 if (icp.isDualSub()) {
434 list.add(0, icp.getParentPoint());
444 boolean hasOffsets = false;
445 Vector3d offset = new Vector3d();
446 Vector3d startPoint = start.getWorldPosition();
447 Vector3d endPoint = end.getWorldPosition();
448 Vector3d dir = new Vector3d();
449 hasOffsets = calculateOffset(startPoint, endPoint, start, list, end, dir, offset);
450 System.out.println();
451 return new UpdateStruct2(start, startPoint, list, end, endPoint, dir, offset, hasOffsets, iter, direction == Direction.PREVIOUS, toRemove, updated);
454 private static boolean asDirected(PipeControlPoint pcp, Direction direction) {
455 if (pcp.isDirected())
457 if (pcp.asFixedAngle()) {
458 if (!pcp._getReversed())
459 return direction == Direction.NEXT;
461 return direction == Direction.PREVIOUS;
466 private static Vector3d direction(PipeControlPoint pcp, Direction direction) {
467 return pcp.getDirection(direction);
470 private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
473 if (lengthChange == PathLegUpdateType.NONE) {
477 updatePathLeg(u, lengthChange, rs, re);
480 private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean rs, boolean re) throws Exception {
482 if (asDirected(u.start, Direction.NEXT))
484 if (asDirected(u.end, Direction.PREVIOUS))
487 setErrorForce(u.start, null);
489 setErrorForce(u.end, null);
490 for (PipeControlPoint pcp : u.list)
491 setErrorForce(pcp, null);
494 updateFreePathLeg(u, lengthChange);
497 updateDirectedPathLeg(u, lengthChange);
500 updateDualDirectedPathLeg(u, lengthChange);
506 private static void updateFreePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
508 System.out.println("PipingRules.updateFreePipeRun " + u + " " + lengthChange);
509 checkExpandPathLeg(u, lengthChange);
510 if (u.start.isInline() || u.end.isInline() || u.start.asFixedAngle()|| u.end.asFixedAngle())
511 processPathLeg(u, true, false);
514 private static void updateInlineControlPoints(UpdateStruct2 u, boolean checkSizes) throws Exception{
516 System.out.println("PipingRules.updateInlineControlPoints() " + u);
518 Vector3d start = new Vector3d(u.startPoint);
519 Vector3d end = new Vector3d(u.endPoint);
522 // create offsets for leg ends.
523 if (u.start.isTurn())
524 MathTools.mad(start, u.dir, u.start.getInlineLength());
526 MathTools.mad(end, u.dir, -u.end.getInlineLength());
529 boolean recalcline = false;
531 Vector3d sp = new Vector3d(start);
532 Vector3d ep = new Vector3d(end);
535 if (u.start.isOffset()) {
536 Vector3d offset = u.start.getSizeChangeOffsetVector(u.dir);
537 updateOffsetPoint(u.start, offset);
542 for (PipeControlPoint icp : u.list) {
543 updateInlineControlPoint(icp, sp, ep, u.dir);
544 if (icp.isOffset()) {
545 // TODO : offset vector is already calculated and should be cached
546 Vector3d offset = icp.getSizeChangeOffsetVector(u.dir);
547 updateOffsetPoint(icp, offset);
556 // Collect all path leg points for updating variable length components. This list will also contain leg ends (usually turns)
557 ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<>();
558 // Collect all fixed length components with their offsets.
559 ArrayList<Pair<PipeControlPoint,Vector3d>> fixedLengthPoints = new ArrayList<>();
561 pathLegPoints.add(u.start);
562 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(u.start, new Vector3d()));
563 Vector3d off = new Vector3d();
564 for (PipeControlPoint icp : u.list) {
565 pathLegPoints.add(icp);
566 updateBranchControlPointBranches(icp);
567 if (icp.isOffset()) {
568 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(icp, new Vector3d(off)));
569 Vector3d offset = icp.getSizeChangeOffsetVector(u.dir);
571 } else if (!icp.isVariableLength()) {
572 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(icp, new Vector3d(off)));
575 pathLegPoints.add(u.end);
576 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(u.end, new Vector3d(off)));
578 sp = new Vector3d(start);
579 ep = new Vector3d(end);
582 updateFixedLengths(fixedLengthPoints, sp, ep, u.dir);
584 for (int i = 0; i < pathLegPoints.size(); i++) {
585 PipeControlPoint icp = pathLegPoints.get(i);
587 PipeControlPoint prev = i > 0 ? pathLegPoints.get(i - 1) : null;
588 PipeControlPoint next = i < pathLegPoints.size() - 1 ? pathLegPoints.get(i + 1) : null;
590 if (prev != null && prev.isDualInline())
591 prev = prev.getDualSub();
593 if (icp.isVariableLength()) {
594 if (prev != null && next != null) {
595 recalcline = recalcline | updateVariableLength(icp, prev, next);
598 // this is variable length component at the end of the piperun.
599 // the problem is that we want to keep unconnected end of the component in the same
600 // place, but center of the component must be moved.
601 updateVariableLengthEnd(icp, prev != null ? prev : next);
603 } else if (prev != null && !prev.isVariableLength()) {
604 // If this and previous control point are not variable length pcps,
605 // we'll have to check if there is no empty space between them.
606 // I there is, we'll have to create new variable length component between them.
607 recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
609 if (icp.isOffset()) {
610 // TODO : offset vector is already calculated and should be cached
611 Vector3d offset = icp.getSizeChangeOffsetVector(u.dir);
619 u.start.findNextEnd(u.list);
622 sp = new Vector3d(u.startPoint);
623 ep = new Vector3d(u.endPoint);
625 double pathLegLength = MathTools.distance(sp, ep);
626 double availableLength = pathLegLength;
627 if (u.start.isTurn())
628 availableLength -= u.start.getInlineLength();
630 availableLength -= u.end.getInlineLength();
631 for (PipeControlPoint pcp : u.list) {
632 if (!pcp.isVariableLength())
633 availableLength-= pcp.getLength();
635 if (availableLength < 0.0) {
636 setError(u.start, "Not enough available space");
637 setError(u.end, "Not enough available space");
638 for (PipeControlPoint pcp : u.list)
639 setError(pcp, "Not enough available space");
641 // System.out.println(u.start.getPipelineComponent().toString() + " " + pathLegLength + " " + availableLength + " " + u.end.getPipelineComponent().toString() + " " + u.start.getInlineLength() + " " + u.end.getInlineLength());
645 private enum Gap{ATTACHED,OVERLAP,SPACE};
647 private static class GapObj {
651 Pair<PipeControlPoint,Vector3d> pcp1;
652 Pair<PipeControlPoint,Vector3d> pcp2;
655 private static void updateFixedLengths(List<Pair<PipeControlPoint,Vector3d>> fixedLengthPoints, Vector3d s, Vector3d e, Vector3d dir) {
656 double totalLength = MathTools.distance(s, e);
657 double reservedLength = 0.0;
658 List<Double> distances = new ArrayList<>(fixedLengthPoints.size());
660 for (int i = 1; i < fixedLengthPoints.size()-1; i++) {
661 Pair<PipeControlPoint,Vector3d> pcp = fixedLengthPoints.get(i);
662 reservedLength += pcp.first.getLength();
663 Vector3d p = pcp.first.getWorldPosition();
665 double d= MathTools.distance(s, p);
668 distances.add(totalLength);
670 if (totalLength >= reservedLength) {
671 // There is enough space for all fixed length components.
672 List<GapObj> gaps = new ArrayList<>(fixedLengthPoints.size()-1);
674 // Analyze gaps between components
675 for (int i = 0; i < fixedLengthPoints.size()-1; i++) {
676 Pair<PipeControlPoint,Vector3d> pcp1 = fixedLengthPoints.get(i);
677 Pair<PipeControlPoint,Vector3d> pcp2 = fixedLengthPoints.get(i+1);
678 double d1 = distances.get(i);
679 double d2 = distances.get(i+1);
680 double ld1 = i == 0 ? 0.0 :pcp1.first.getInlineLength();
681 double ld2 = i == fixedLengthPoints.size()-2 ? 0.0 : pcp2.first.getInlineLength();
683 double e1 = d1 + ld1; // End of comp1
684 double s2 = d2 - ld2; // Start of comp2
685 double diff =s2 - e1;
686 GapObj obj = new GapObj();
690 if (diff < -MIN_INLINE_LENGTH) {
691 obj.gap = Gap.OVERLAP;
693 } else if (diff > MIN_INLINE_LENGTH) {
696 obj.gap = Gap.ATTACHED;
700 // If there are no overlaps, there is nothing to do.
703 // Get rid of overlapping components by using closest available free spaces.
704 for (int i = 0; i < gaps.size(); i++) {
705 GapObj gapObj = gaps.get(i);
706 if (gapObj.gap != Gap.OVERLAP)
708 double curr = gapObj.d;
710 while (curr < -MIN_INLINE_LENGTH) {
711 GapObj next = i+d >= 0 ? gaps.get(i+d) : null;
712 GapObj prev = i-d >= 0 ? gaps.get(i-d) : null;
713 if (next != null && next.gap == Gap.SPACE) {
714 double move = Math.min(-curr, next.d);
717 if (next.d < MIN_INLINE_LENGTH)
718 next.gap = Gap.ATTACHED;
719 Vector3d mv = new Vector3d(dir);
722 for (int j = i ; j < i+d; j++) {
723 Pair<PipeControlPoint,Vector3d> pcp = gaps.get(j).pcp2;
724 Vector3d p = new Vector3d(pcp.first.getWorldPosition());
726 pcp.first.setWorldPosition(p);
729 if (curr < -MIN_INLINE_LENGTH && prev != null && prev.gap == Gap.SPACE) {
730 double move = Math.min(-curr, prev.d);
733 if (next.d < MIN_INLINE_LENGTH)
734 next.gap = Gap.ATTACHED;
735 Vector3d mv = new Vector3d(dir);
738 for (int j = i ; j > i-d; j--) {
739 Pair<PipeControlPoint,Vector3d> pcp = gaps.get(j).pcp1;
740 Vector3d p = new Vector3d(pcp.first.getWorldPosition());
742 pcp.first.setWorldPosition(p);
748 for (int i = 1; i < fixedLengthPoints.size()-1; i++) {
749 Pair<PipeControlPoint,Vector3d> prev = i == 0 ? null : fixedLengthPoints.get(i-1);
750 Pair<PipeControlPoint,Vector3d> curr = fixedLengthPoints.get(i);
751 Pair<PipeControlPoint,Vector3d> next = i == fixedLengthPoints.size() -1 ? null : fixedLengthPoints.get(i+1);
752 updateFixedLength(curr, prev, next, s,e, dir);
757 private static void updateFixedLength(Pair<PipeControlPoint,Vector3d> icp, Pair<PipeControlPoint,Vector3d> prev, Pair<PipeControlPoint,Vector3d> next, Vector3d s, Vector3d e, Vector3d dir) {
759 checkOverlap(prev, icp, dir,true);
762 checkOverlap(icp, next, dir,true);
765 private static boolean checkOverlap(Pair<PipeControlPoint,Vector3d> icp, Pair<PipeControlPoint,Vector3d> icp2, Vector3d dir, boolean se) {
766 Vector3d p1 = icp.first.getWorldPosition();
767 Vector3d p2 = icp2.first.getWorldPosition();
770 double u[] = new double[1];
771 MathTools.closestPointOnStraight(p2, p1, dir, u);
776 MathTools.mad(p2, dir, MIN_INLINE_LENGTH);
777 icp2.first.setWorldPosition(p2);
779 double d = MathTools.distance(p1, p2);
780 double r = icp.first.getInlineLength() + icp2.first.getInlineLength();
782 if ((d-r) < - MIN_INLINE_LENGTH) {
784 setError(icp.first, "Overlapping");
785 setError(icp2.first, "Overlapping");
793 * Overrides current error of a component
797 private static void setErrorForce(PipeControlPoint pcp, String error) {
798 PipelineComponent comp = pcp.getPipelineComponent();
801 comp.setError(error);
805 * Sets error for a component, if there is no existing error.
809 private static void setError(PipeControlPoint pcp, String error) {
810 PipelineComponent comp = pcp.getPipelineComponent();
813 if (comp.getError() != null)
815 comp.setError(error);
818 private static boolean updateVariableLength(PipeControlPoint icp, PipeControlPoint prev, PipeControlPoint next) {
819 Vector3d prevPos = prev.getWorldPosition();
820 Vector3d nextPos = next.getWorldPosition();
822 Vector3d dir = new Vector3d(nextPos);
824 double l = dir.length(); // distance between control points
825 double l2prev = prev.getInlineLength(); // distance taken by components
826 double l2next = next.getInlineLength();
827 double l2 = l2prev + l2next;
828 double length = l - l2; // true length of the variable length component
829 if (length >= MIN_INLINE_LENGTH) { // check if there is enough space for variable length component.
832 dir.scale(length * 0.5 + l2prev); // calculate center position of the component
834 icp.setWorldPosition(dir);
835 icp.setLength(length);
838 // components leave no space to the component and it must be removed
839 if (icp.isDeletable()) {
840 if (!allowInsertRemove) {
841 icp.setLength(MIN_INLINE_LENGTH);
842 setError(icp, "Not enough available space");
847 System.out.println("PipingRules.updateVariableLength removing " + icp);
851 icp.setLength(MIN_INLINE_LENGTH);
852 icp.getPipelineComponent().setError("Not enough available space");
858 private static boolean possibleVaribleLengthInsert(PipeControlPoint icp, PipeControlPoint prev) throws Exception{
859 Vector3d currentPos = icp.getWorldPosition();
860 Vector3d prevPos = prev.getWorldPosition();
861 Vector3d dir = new Vector3d(currentPos);
863 double l = dir.lengthSquared();
864 double l2prev = prev.getInlineLength();
865 double l2next = icp.getInlineLength();
866 double l2 = l2prev + l2next;
867 double l2s = l2 * l2;
869 if (allowInsertRemove) {
871 double length = Math.sqrt(l) - l2; // true length of the variable length component
872 dir.scale(length * 0.5 + l2prev); // calculate center position of the component
874 insertStraight(prev, icp, dir, length);
883 private static void updateVariableLengthEnd(PipeControlPoint icp, PipeControlPoint prev) {
884 Vector3d currentPos = icp.getWorldPosition();
885 Vector3d prevPos = prev.getWorldPosition();
887 Vector3d dir = new Vector3d();
888 dir.sub(currentPos, prevPos);
890 boolean simple = currentUpdates.contains(icp);
892 // Update based on position -> adjust length
893 double currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
894 icp.setLength(currentLength);
896 // Update based on neighbour movement -> adjust length and position, so that free end stays in place.
897 double currentLength = icp.getLength();
898 if (currentLength < MathTools.NEAR_ZERO) {
899 currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
902 if (dir.lengthSquared() > MathTools.NEAR_ZERO)
904 Point3d endPos = new Point3d(dir);
905 endPos.scale(currentLength * 0.5);
906 endPos.add(currentPos); // this is the free end of the component
908 double offset = prev.getInlineLength();
909 Point3d beginPos = new Point3d(dir);
910 beginPos.scale(offset);
911 beginPos.add(prevPos); // this is the connected end of the component
913 double l = beginPos.distance(endPos);
916 System.out.println("Length for " + icp + " is NaN");
919 beginPos.add(dir); // center position
922 System.out.println("PipingRules.updateInlineControlPoints() setting variable length to " + l);
925 icp.setWorldPosition(new Vector3d(beginPos));
929 private static void ppNoOffset(UpdateStruct2 u) throws Exception {
931 System.out.println("PipingRules.ppNoOffset() " + u);
932 Vector3d offset = new Vector3d();
935 for (PipeControlPoint icp : u.list) {
936 if (icp.isOffset()) {
937 offset.add(icp.getSizeChangeOffsetVector(u.dir));
938 } else if (icp.isDualSub())
939 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
943 checkExpandPathLeg(u, PathLegUpdateType.NONE);
946 private static void ppNoDir(PipeControlPoint start, Vector3d startPoint, ArrayList<PipeControlPoint> list, PipeControlPoint end, Vector3d endPoint, boolean hasOffsets, int iter, boolean reversed, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated) throws Exception {
948 System.out.println("PipingRules.ppNoDir() " + start + " " + end + " " + iter + " " + toRemove.size());
949 // FIXME : extra loop (dir should be calculated here)
950 Vector3d dir = new Vector3d();
951 Vector3d offset = new Vector3d();
952 hasOffsets = calculateOffset(startPoint, endPoint, start, list, end, dir, offset);
953 ppNoOffset(new UpdateStruct2(start, startPoint, list, end, endPoint, dir, null, hasOffsets, iter, reversed, toRemove, updated));
956 private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
957 checkExpandPathLeg(u, lengthChange, u.updated.isInline() && u.updated.isOffset());
960 private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean updateEnds) throws Exception {
962 System.out.println("PipingRules.checkExpandPathLeg() " + u + " " + lengthChange);
963 if (lengthChange != PathLegUpdateType.NONE) {
964 // FIXME : turns cannot be checked before inline cps are updated,
965 // since their position affects calculation of turns
966 processPathLeg(u, updateEnds, false);
967 int type = checkTurns(u, lengthChange);
968 if (type == REMOVE_NONE) {
969 processPathLeg(u, updateEnds, true);
971 expandPathLeg(u, type);
974 processPathLeg(u, updateEnds, true);
978 private static void updateDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
980 System.out.println("PipingRules.updateDirectedPipeRun() " + u + " " + lengthChange);
981 PipeControlPoint dcp;
982 PipeControlPoint other;
983 boolean canMoveOther = false;
984 boolean dcpStart = false;
985 boolean inlineEnd = false;
987 if (asDirected(u.start, Direction.NEXT)) {
990 position = u.startPoint;
994 inlineEnd = u.end.isInline();
999 position = u.endPoint;
1001 canMoveOther = true;
1002 inlineEnd = u.start.isInline();
1005 Vector3d directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS);
1006 if (directedDirection == null) {
1007 //updateTurnControlPointTurn(dcp, dcp.getPrevious(), dcp.getNext());
1008 updateTurnControlPointTurn(dcp, null, null);
1009 directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS);
1010 if (directedDirection == null) {
1014 Point3d directedEndPoint = new Point3d(u.endPoint);
1016 directedEndPoint.add(u.offset);
1018 double mu[] = new double[2];
1021 Vector3d t = new Vector3d();
1024 closest = MathTools.closestPointOnStraight(directedEndPoint, u.startPoint, directedDirection, mu);
1025 t.sub(closest, directedEndPoint);
1027 closest = MathTools.closestPointOnStraight(u.startPoint, directedEndPoint, directedDirection, mu);
1028 t.sub(closest, u.startPoint);
1031 double distance = t.length();
1032 boolean aligned = (distance < ALLOWED_OFFSET);
1034 if (u.start.isInline() || u.end.isInline() || u.start.asFixedAngle() || u.end.asFixedAngle())
1035 processPathLeg(u, true, false);
1036 checkExpandPathLeg(u, lengthChange, inlineEnd);
1042 PipeControlPoint nextToMoved;
1044 if (u.list.size() > 0)
1046 nextToMoved = u.list.get(0);
1048 nextToMoved = u.list.get(u.list.size() - 1);
1050 nextToMoved = u.end;
1052 nextToMoved = u.start;
1053 if (other.isVariableAngle()) {
1055 // TODO calculate needed space from next run end.
1056 double space = spaceForTurn(other);
1057 if (mu[0] < space) {
1059 closest.set(u.startPoint);
1061 closest.set(u.endPoint);
1063 Vector3d v = new Vector3d(directedDirection);
1070 System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + closest);
1071 other.setWorldPosition(closest);
1073 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));
1074 if (u.end.getNext() != null)
1075 updatePathLegNext(u.end, u.updated, PathLegUpdateType.NEXT);
1077 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));
1078 if (u.start.getPrevious() != null)
1079 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.PREV);
1082 // TODO : calculate needed space from next run end.
1083 if (allowInsertRemove)
1084 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
1089 } else if (other.isNonDirected() && other.getParentPoint() != null) {
1090 // FIXME : this code was for updating branches
1091 Vector3d bintersect = new Vector3d();
1092 PipeControlPoint bcp = other.getParentPoint();
1093 if (bcp != null && canMoveOther) {
1094 Point3d bstart = new Point3d();
1095 Point3d bend = new Point3d();
1096 Vector3d bdir = new Vector3d();
1097 bcp.getInlineControlPointEnds(bstart, bend, bdir);
1098 Vector3d nintersect = new Vector3d();
1100 MathTools.intersectStraightStraight(position, directedDirection, bend, bdir, nintersect, bintersect, mu);
1101 Vector3d dist = new Vector3d(nintersect);
1102 dist.sub(bintersect);
1103 canMoveOther = mu[1] > 0.0 && mu[1] < 1.0 && dist.lengthSquared() < 0.01;
1105 // TODO : endControlPoints are undirected: calculcate
1106 // correct position for it
1107 throw new UnsupportedOperationException("not implemented");
1111 System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + bintersect);
1112 // is required branch position is in possible range
1113 bcp.setWorldPosition(bintersect);
1115 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);
1117 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);
1120 // branch cannot be moved into right position, new turn
1121 // / elbow must be inserted
1122 if (allowInsertRemove)
1123 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
1128 } else { // assume that control point cannot be moved, but can
1130 if (allowInsertRemove)
1131 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
1141 private static void updateDualDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
1143 System.out.println("PipingRules.updateDualDirectedPipeRun() " + u + " " + lengthChange);
1145 PipeControlPoint dcp1 = u.start;
1146 PipeControlPoint dcp2 = u.end;
1147 Point3d position1 = new Point3d(u.startPoint);
1148 Point3d position2 = new Point3d(u.endPoint);
1149 Point3d position1offset = new Point3d(position1);
1150 position1offset.sub(u.offset);
1151 Point3d position2offset = new Point3d(position2);
1152 position2offset.add(u.offset);
1153 Vector3d dir1 = direction(dcp1, Direction.NEXT);
1154 Vector3d dir2 = direction(dcp2, Direction.PREVIOUS);
1155 Vector3d p1 = MathTools.closestPointOnStraight(position1offset, position2, dir2);
1156 Vector3d p2 = MathTools.closestPointOnStraight(position2offset, position1, dir1);
1157 double d1 = position1.distance(new Point3d(p1));
1158 double d2 = position2.distance(new Point3d(p2));
1160 boolean aligned = (d1 < ALLOWED_OFFSET && d2 < ALLOWED_OFFSET);
1166 } else if (allowInsertRemove){
1167 PipeControlPoint dcp;
1168 PipeControlPoint next;
1171 if (u.list.size() > 0)
1172 next = u.list.get(0);
1177 if (u.list.size() > 0)
1178 next = u.list.get(u.list.size() - 1);
1183 p1 = dcp.getWorldPosition();
1184 Vector3d v = new Vector3d();
1190 // Reserve space for 90 deg elbow
1191 double off = dcp1.getPipeRun().getTurnRadius();
1196 p2 = MathTools.closestPointOnStraight(new Point3d(p1), position2, dir2);
1198 p2 = MathTools.closestPointOnStraight(new Point3d(p1), position1, dir1);
1200 // By default, the elbows are placed next to each other, by using 90 deg angles.
1201 // If the distance between elbows is not enough, we must move the other elbow (and create more shallow angle elbows)
1202 if (MathTools.distance(p1, p2) < off*2.05) {
1206 PipeControlPoint tcp1 = insertElbow(dcp, next, p1);
1207 PipeControlPoint tcp2 = insertElbow(tcp1, next, p2);
1210 System.out.println("PipingRules.updateDualDirectedPipeRun() created two turns " + tcp1 + " " + tcp2);
1213 Vector3d dd = new Vector3d(p2);
1216 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1217 updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1219 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1221 updatePathLegPrev(tcp2, u.updated, PathLegUpdateType.NONE);
1223 Vector3d dd = new Vector3d(p1);
1226 updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1227 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1229 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1231 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.NONE);
1240 private static double spaceForTurn(PipeControlPoint tcp) {
1241 // TODO : this returns now space for 90 deg turn.
1242 // The challenge: position of tcp affects the turn angle, which then affects the required space. Perhaps we need to iterate...
1243 // Additionally, if the path legs contain offset, using just positions of opposite path leg ends is not enough,
1244 return ((TurnComponent)tcp.getPipelineComponent()).getTurnRadius();
1247 private static void insertElbowUpdate(UpdateStruct2 u, PipeControlPoint dcp, PipeControlPoint next, boolean dcpStart, Vector3d position, Vector3d directedDirection) throws Exception{
1250 // Vector3d closest = new Vector3d(position);
1251 // closest.add(directedDirection);
1253 PipeControlPoint tcp = null;
1256 closest = MathTools.closestPointOnStraight(next.getWorldPosition(), position, directedDirection);
1257 tcp = insertElbow(dcp, next, closest);
1259 closest = MathTools.closestPointOnStraight(dcp.getWorldPosition(), position, directedDirection);
1260 tcp = insertElbow(next, dcp, closest);
1262 // TODO properly calculate required distance between start and inserted elbow.
1263 double d = MathTools.distance(position, closest);
1264 double s = spaceForTurn(tcp);
1267 Vector3d p = new Vector3d(directedDirection);
1277 System.out.println("PipingRules.updateDirectedPipeRun() inserted " + tcp);
1280 // update pipe run from new turn to other end
1281 ppNoDir(tcp, new Vector3d(closest), u.list, u.end, u.endPoint, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1282 // update pipe run from directed to new turn
1283 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));
1285 // update pipe run from other end to new turn
1286 ppNoDir(u.start, u.startPoint, u.list, tcp, new Vector3d(closest), u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1287 // update pipe run from new turn to directed
1288 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));
1293 * Checks if turns can be removed (turn angle near zero)
1295 private static int checkTurns(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
1297 System.out.println("PipingRules.checkTurns() " + u.start + " " + u.end);
1298 boolean startRemoved = false;
1299 boolean endRemoved = false;
1300 if (u.start.isVariableAngle()) {
1301 // this won't work properly if inline control points are not updated
1302 PipeControlPoint startPrev = u.start.getPrevious();
1303 if (startPrev != null) {
1304 double a = updateTurnControlPointTurn(u.start, null, u.dir);
1305 if (a < MIN_TURN_ANGLE && u.start.isDeletable())
1306 startRemoved = true;
1307 else if (lengthChange == PathLegUpdateType.PREV || lengthChange == PathLegUpdateType.PREV_S) {
1308 PathLegUpdateType type;
1309 if (lengthChange == PathLegUpdateType.PREV_S)
1310 type = PathLegUpdateType.PREV;
1312 type = PathLegUpdateType.NONE;
1313 updatePathLegPrev(u.start, u.start, type);
1317 if (u.end.isVariableAngle()) {
1319 PipeControlPoint endNext = u.end.getNext();
1320 if (endNext != null) {
1321 // TODO: u.end, u.dir, null
1322 double a = updateTurnControlPointTurn(u.end, null, null);
1323 if (a < MIN_TURN_ANGLE && u.end.isDeletable())
1325 else if (lengthChange == PathLegUpdateType.NEXT || lengthChange == PathLegUpdateType.NEXT_S) {
1326 PathLegUpdateType type;
1327 if (lengthChange == PathLegUpdateType.NEXT_S)
1328 type = PathLegUpdateType.NEXT;
1330 type = PathLegUpdateType.NONE;
1331 updatePathLegNext(u.end, u.end, type);
1336 System.out.println("PipingRules.checkTurns() res " + startRemoved + " " + endRemoved);
1337 if (!startRemoved && !endRemoved)
1339 if (startRemoved && endRemoved)
1342 return REMOVE_START;
1347 * Expands piperun search over turns that are going to be removed
1350 private static void expandPathLeg(UpdateStruct2 u, int type) throws Exception {
1352 System.out.println("PipingRules.expandPipeline " + u.start + " " + u.end);
1353 ArrayList<PipeControlPoint> newList = new ArrayList<PipeControlPoint>();
1356 throw new RuntimeException("Error in piping rules");
1358 u.toRemove.add(new ExpandIterInfo(u.start, REMOVE_START));
1359 u.start = u.start.findPreviousEnd();
1360 u.startPoint = u.start.getPosition();
1361 u.start.findNextEnd(newList);
1362 newList.addAll(u.list);
1366 u.toRemove.add(new ExpandIterInfo(u.end, REMOVE_END));
1367 u.end = u.end.findNextEnd(newList);
1368 u.endPoint = u.end.getPosition();
1369 u.list.addAll(newList);
1372 u.toRemove.add(new ExpandIterInfo(u.start, u.end));
1373 u.start = u.start.findPreviousEnd();
1374 u.startPoint = u.start.getPosition();
1375 u.start.findNextEnd(newList);
1376 newList.addAll(u.list);
1378 newList = new ArrayList<PipeControlPoint>();
1379 u.end = u.end.findNextEnd(newList);
1380 u.endPoint = u.end.getPosition();
1381 u.list.addAll(newList);
1384 throw new RuntimeException("Error in piping rules");
1387 u.offset = new Vector3d();
1390 for (PipeControlPoint icp : u.list) {
1391 if (icp.isOffset()) {
1392 u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1393 } else if (icp.isDualSub())
1394 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1398 System.out.println("PipingRules.expandPipeline expanded " + u.start + " " + u.end);
1400 updatePathLeg(u, PathLegUpdateType.NONE);
1404 * reverts one iteration of turn removing back)
1406 private static void backIter(UpdateStruct2 u) throws Exception {
1409 System.out.println("PipingRules.backIter" + u.start + " " + u.end);
1411 throw new RuntimeException("Error in piping rules");
1412 ExpandIterInfo info = u.toRemove.get(u.toRemove.size() - 1);
1413 u.toRemove.remove(u.toRemove.size() - 1);
1414 if (info.getType() == REMOVE_START || info.getType() == REMOVE_BOTH) {
1415 while (u.list.size() > 0) {
1416 PipeControlPoint icp = u.list.get(0);
1417 if (icp.getPrevious().equals(info.getStart()))
1421 u.start = info.getStart();
1423 if (info.getType() == REMOVE_END || info.getType() == REMOVE_BOTH) {
1424 while (u.list.size() > 0) {
1425 PipeControlPoint icp = u.list.get(u.list.size() - 1);
1426 if (icp.getNext().equals(info.getEnd()))
1430 u.end = info.getEnd();
1432 u.offset = new Vector3d();
1435 for (PipeControlPoint icp : u.list) {
1436 if (icp.isOffset()) {
1437 u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1438 } else if (icp.isDualSub())
1439 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1447 * Processes pipe run (removes necessary turns and updates run ends)
1449 // private static void processPathLeg(PipeControlPoint start, Point3d
1450 // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1451 // end,Point3d endPoint, Vector3d dir,Vector3d offset, boolean
1452 // hasOffsets,int iter, boolean reversed, ArrayList<ExpandIterInfo>
1453 // toRemove) throws TransactionException {
1455 private static void processPathLeg(UpdateStruct2 u) throws Exception {
1457 System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1458 processPathLeg(u, true, true);
1461 private static void processPathLeg(UpdateStruct2 u, boolean updateEnds, boolean updateInline) throws Exception {
1463 System.out.println("PipingRules.processPathLeg " + (updateEnds ? "ends " : "") + (updateInline ? "inline " : "") + u.start + " " + u.end);
1465 if (u.toRemove.size() > 0) {
1466 for (ExpandIterInfo info : u.toRemove) {
1467 if (info.getStart() != null) {
1469 System.out.println("PipingRules.processPathLeg removing start " + info.getStart());
1470 info.getStart()._remove();
1472 if (info.getEnd() != null) {
1474 System.out.println("PipingRules.processPathLeg removing end " + info.getEnd());
1475 info.getEnd()._remove();
1478 // ControlPointTools.removeControlPoint may remove more than one CP;
1479 // we must populate inline CP list again.
1481 u.start.findNextEnd( u.list);
1483 // FIXME : inline CPs are update twice because their positions must be
1484 // updated before and after ends.
1485 updateInlineControlPoints(u, false);
1488 if (u.start.isTurn()) {
1489 //updateTurnControlPointTurn(u.start, u.start.getPrevious(), u.start.getNext());
1490 updateTurnControlPointTurn(u.start, null, null);
1491 // updatePathLegPrev(u.start, u.start, PathLegUpdateType.NONE);
1492 } else if (u.start.isEnd()) {
1493 updateEndComponentControlPoint(u.start, u.dir);
1494 } else if (u.start.isInline()) {
1495 updateControlPointOrientation(u.start, u.dir);
1497 if (u.end.isTurn()) {
1498 //updateTurnControlPointTurn(u.end, u.end.getPrevious(), u.end.getNext());
1499 updateTurnControlPointTurn(u.end, null, null);
1500 // updatePathLegNext(u.end, u.end, PathLegUpdateType.NONE);
1501 } else if (u.end.isEnd()) {
1502 updateEndComponentControlPoint(u.end, u.dir);
1503 } else if (u.end.isInline()) {
1504 updateControlPointOrientation(u.end, u.dir);
1508 if (u.start.isEnd()) {
1509 updateEndComponentControlPoint(u.start, u.dir);
1511 if (u.end.isEnd()) {
1512 updateEndComponentControlPoint(u.end, u.dir);
1516 updateInlineControlPoints(u, true);
1521 * Processes pipe run and recalculates offset
1523 // private static void processPathLeg(PipeControlPoint start, Point3d
1524 // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1525 // end,Point3d endPoint, Vector3d dir, boolean hasOffsets,int iter, boolean
1526 // reversed, ArrayList<ExpandIterInfo> toRemove) throws TransactionException
1528 @SuppressWarnings("unused")
1529 private static void processPathLegNoOffset(UpdateStruct2 u) throws Exception {
1531 System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1532 Vector3d offset = new Vector3d();
1535 for (PipeControlPoint icp : u.list) {
1536 if (icp.isOffset()) {
1537 offset.add(icp.getSizeChangeOffsetVector(u.dir));
1538 } else if (icp.isDualSub()) {
1539 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1546 private static void updateOffsetPoint(PipeControlPoint sccp, Vector3d offset) {
1547 Vector3d world = sccp.getWorldPosition();
1549 PipeControlPoint ocp = sccp.getDualSub();
1550 ocp.setWorldPosition(world);
1554 * Updates InlineControlPoints position when straight pipe's end(s) have
1562 private static void updateInlineControlPoint(PipeControlPoint icp, Vector3d prev, Vector3d next, Vector3d dir) {
1564 System.out.println("PipingRules.updateInlineControlPoint() " + icp);
1566 Vector3d inlinePoint = icp.getWorldPosition();
1567 Vector3d prevPoint = new Vector3d(prev);
1568 Vector3d nextPoint = new Vector3d(next);
1569 if (!icp.isVariableLength()) {
1570 // Reserve space for fixed length components.
1571 MathTools.mad(prevPoint, dir, icp.getInlineLength());
1572 MathTools.mad(nextPoint, dir, -icp.getInlineLength());
1573 if (MathTools.distance(prevPoint, nextPoint) < ALLOWED_OFFSET) {
1578 boolean canCalc = MathTools.distance(prevPoint, nextPoint) > ALLOWED_OFFSET;
1580 System.out.print("InlineControlPoint update " + icp + " " + inlinePoint + " " + prevPoint + " " + nextPoint);
1581 Vector3d newInlinePoint = null;
1583 boolean branchUpdate = false;
1584 PipeControlPoint becp = null;
1585 for (PipeControlPoint pcp : icp.getChildPoints())
1586 if (pcp.isNonDirected()) {
1587 branchUpdate = true;
1592 if (DUMMY || !branchUpdate) {
1593 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1597 // FIXME : can only handle one branch
1598 PipeControlPoint p = null;
1599 if (becp.getNext() != null) {
1600 p = becp.findNextEnd();
1601 } else if (becp.getPrevious() != null) {
1602 p = becp.findPreviousEnd();
1605 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1606 } else if (canCalc){
1607 Vector3d branchLegEnd = p.getWorldPosition();
1608 Vector3d dir2 = new Vector3d(inlinePoint);
1609 dir2.sub(branchLegEnd);
1610 Vector3d dir1 = new Vector3d(nextPoint);
1611 dir1.sub(prevPoint);
1612 newInlinePoint = new Vector3d();
1613 double mu[] = new double[2];
1614 MathTools.intersectStraightStraight(new Vector3d(prevPoint), dir1, new Vector3d(branchLegEnd), dir2, newInlinePoint, new Vector3d(), mu);
1616 System.out.println(mu[0]);
1617 // FIXME : reserve space
1619 newInlinePoint = new Vector3d(prevPoint);
1620 } else if (mu[0] > 1.0) {
1621 newInlinePoint = new Vector3d(nextPoint);
1626 // prevPoint == nextPoint
1627 newInlinePoint = new Vector3d(prevPoint);
1630 System.out.println(" " + newInlinePoint);
1632 icp.setWorldPosition(newInlinePoint);
1633 updateControlPointOrientation(icp, dir);
1637 * Updates InlineControlPoints position when straight pipe's end(s) have
1645 private static void updateEndComponentControlPoint(PipeControlPoint ecp, Vector3d dir) throws Exception {
1647 System.out.println("PipingRules.updateEndComponentControlPoint() " + ecp);
1648 //FIXME : end control point cannot be fixed!
1649 //if (!ecp.isFixed())
1650 updateControlPointOrientation(ecp, dir);
1652 for (PipeControlPoint pcp : ecp.getChildPoints()) {
1653 // TODO update position
1654 updatePathLegEndControlPoint(pcp);
1658 private static void updateControlPointOrientation(PipeControlPoint pcp, Vector3d dir) {
1659 Double angleO = pcp.getRotationAngle();
1663 boolean reversed = pcp._getReversed();
1666 q = pcp.getControlPointOrientationQuat(dir, angle, reversed);
1668 q = pcp.getControlPointOrientationQuat(angle, reversed);
1670 pcp.setWorldOrientation(q);
1674 * Updates all branches when branch's position has been changed
1678 private static void updateBranchControlPointBranches(PipeControlPoint bcp) throws Exception {
1680 System.out.println("PipingRules.updateBranchControlPointBranches() " + bcp);
1681 if (bcp.isDualInline())
1683 Collection<PipeControlPoint> branches = bcp.getChildPoints();
1684 if (branches.size() == 0) {
1686 System.out.println("No Branches found");
1690 for (PipeControlPoint pcp : branches) {
1691 updatePathLegEndControlPoint(pcp);
1695 private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d prev, Vector3d next) {
1697 UpdateStruct2 us = createUS(tcp, Direction.NEXT, 0, new ArrayList<PipingRules.ExpandIterInfo>(), tcp);
1702 UpdateStruct2 us = createUS(tcp, Direction.PREVIOUS, 0, new ArrayList<PipingRules.ExpandIterInfo>(), tcp);
1708 if (!tcp.asFixedAngle()) {
1711 if (next == null || prev == null) {
1712 if (tcp.getTurnAngle() != null)
1713 return tcp.getTurnAngle();
1714 return Math.PI; // FIXME : argh
1716 double turnAngle = prev.angle(next);
1718 double angle = Math.PI - turnAngle;
1720 Vector3d turnAxis = new Vector3d();
1721 turnAxis.cross(prev, next);
1722 if (turnAxis.lengthSquared() > MathTools.NEAR_ZERO) {
1723 double elbowRadius = ((TurnComponent)tcp.getPipelineComponent()).getTurnRadius();
1724 double R = elbowRadius / Math.tan(angle * 0.5);
1726 turnAxis.normalize();
1727 tcp.setTurnAngle(turnAngle);
1728 tcp.setLength(R);// setComponentOffsetValue(R);
1729 tcp.setTurnAxis(turnAxis);
1730 // tcp.setPosition(tcp.getPosition());
1733 tcp.setTurnAngle(0.0);
1735 tcp.setTurnAxis(new Vector3d(MathTools.Y_AXIS));
1738 updateControlPointOrientation(tcp,prev);
1741 System.out.println("PipingTools.updateTurnControlPointTurn " + prev + " " + next + " " + turnAngle + " " + turnAxis);
1745 if (prev != null && next != null) {
1747 } else if (prev == null) {
1748 if (!tcp._getReversed())
1749 tcp.setReversed(true);
1750 } else if (next == null) {
1751 if (tcp._getReversed())
1752 tcp.setReversed(false);
1755 Vector3d dir = null;
1756 if (!tcp._getReversed()) {
1763 return Math.PI; // FIXME : argh
1766 Quat4d q = PipeControlPoint.getControlPointOrientationQuat(dir, tcp.getRotationAngle() != null ? tcp.getRotationAngle() : 0.0);
1767 Vector3d v = new Vector3d();
1768 MathTools.rotate(q, MathTools.Y_AXIS,v);
1770 tcp.setWorldOrientation(q);
1771 if (tcp.getTurnAngle() != null)
1772 return tcp.getTurnAngle();
1773 return Math.PI; // FIXME : argh
1779 public static List<PipeControlPoint> getControlPoints(PipeRun pipeRun) {
1780 List<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
1781 if (pipeRun.getControlPoints().size() == 0)
1783 PipeControlPoint pcp = pipeRun.getControlPoints().iterator().next();
1784 while (pcp.getPrevious() != null) {
1785 PipeControlPoint prev = pcp.getPrevious();
1786 if (prev.getPipeRun() != pipeRun && prev.getPipeRun() != null) { // bypass possible corruption
1791 if (pcp.isDualSub()) {
1792 pcp = pcp.getParentPoint();
1795 while (pcp.getNext() != null) {
1796 pcp = pcp.getNext();
1797 if (pcp.getPipeRun() != pipeRun)
1804 public static void reverse(PipeRun pipeRun) {
1807 List<PipeControlPoint> points = getControlPoints(pipeRun);
1808 PipeControlPoint pcp = points.get(0);
1809 if (pcp.isSizeChange() && pcp.getChildPoints().size() > 0) {
1810 PipeRun pr = pcp.getPipeRun();
1818 List<PipeRun> all = new ArrayList<PipeRun>();
1819 List<List<PipeControlPoint>> pcps = new ArrayList<List<PipeControlPoint>>();
1822 List<PipeControlPoint> points = getControlPoints(pipeRun);
1824 PipeControlPoint pcp = points.get(points.size()-1);
1825 if (pcp.getChildPoints().size() > 0) {
1826 PipeRun pipeRun2 = pcp.getChildPoints().get(0).getPipeRun();
1827 if (pipeRun == pipeRun2)
1835 for (int i = 0 ; i < all.size(); i++) {
1836 List<PipeControlPoint> list = pcps.get(i);
1839 for (int i = 0 ; i < all.size(); i++) {
1840 boolean last = i == all.size() - 1;
1841 List<PipeControlPoint> list = pcps.get(i);
1844 List<PipeControlPoint> list2 = pcps.get(i+1);
1845 PipeControlPoint prev = list.get(list.size()-1);
1846 PipeControlPoint next = list2.get(0);
1847 System.out.println();
1849 // Reverse the component on the boundary.
1850 InlineComponent ic = (InlineComponent)prev.getPipelineComponent();
1851 PipeRun r1 = ic.getPipeRun();
1852 PipeRun r2 = ic.getAlternativePipeRun();
1853 if (r1 == null || r2 == null)
1854 throw new RuntimeException("Components on PipeRun changes should refer to bot PipeRuns");
1858 ic.setAlternativePipeRun(r1);
1860 throw new RuntimeException("PipeRun changes should contain shared control points");
1868 private static void _reverse(List<PipeControlPoint> list) {
1869 if (list.size() <= 1)
1870 return; // nothing to do.
1872 for (int i = 0 ; i < list.size(); i++) {
1873 boolean first = i == 0;
1874 boolean last = i == list.size() - 1;
1875 PipeControlPoint current = list.get(i);
1876 PipeControlPoint currentSub = null;
1877 if (current.isDualInline())
1878 currentSub = current.getDualSub();
1880 PipeControlPoint next = list.get(i+1);
1881 if (next.isDualInline())
1882 next = next.getDualSub();
1883 if (current.getNext() == next)
1884 current.setNext(null);
1885 current.setPrevious(next);
1886 if (currentSub != null) {
1887 if (currentSub.getNext() == next)
1888 currentSub.setNext(null);
1889 currentSub.setPrevious(next);
1892 PipeControlPoint prev = list.get(i-1);
1894 if (current.getPrevious() == prev)
1895 current.setPrevious(null);
1896 current.setNext(prev);
1898 if (currentSub != null) {
1899 if (currentSub.getPrevious() == prev)
1900 currentSub.setPrevious(null);
1901 currentSub.setNext(prev);
1904 PipeControlPoint prev = list.get(i-1);
1905 PipeControlPoint next = list.get(i+1);
1906 if (next.isDualInline())
1907 next = next.getDualSub();
1910 current.setPrevious(next);
1911 current.setNext(prev);
1913 if (currentSub != null) {
1914 currentSub.setPrevious(next);
1915 currentSub.setNext(prev);
1919 //if (current.isTurn() && current.isFixed()) {
1920 if (current.asFixedAngle()) {
1921 current.setReversed(!current._getReversed());
1923 if (current.isInline() && current.isReverse()) {
1924 current.setReversed(!current._getReversed());
1931 public static void validate(PipeRun pipeRun) {
1932 if (pipeRun == null)
1934 Collection<PipeControlPoint> pcps = pipeRun.getControlPoints();
1936 //System.out.println("Validate " + pipeRun.getName());
1937 for (PipeControlPoint pcp : pcps) {
1938 if (pcp.getParentPoint() == null || pcp.getParentPoint().getPipeRun() != pipeRun)
1941 List<PipeControlPoint> runPcps = getControlPoints(pipeRun);
1942 if (runPcps.size() != count) {
1943 System.out.println("Run " + pipeRun.getName() + " contains unconnected control points, found " + runPcps.size() + " connected, " + pcps.size() + " total.");
1944 for (PipeControlPoint pcp : pcps) {
1945 if (!runPcps.contains(pcp)) {
1946 System.out.println("Unconnected " + pcp + " " + pcp.getPipelineComponent());
1950 for (PipeControlPoint pcp : pcps) {
1951 if (pcp.getPipeRun() == null) {
1952 System.out.println("PipeRun ref missing " + pcp + " " + pcp.getPipelineComponent());
1954 if (!pcp.isDirected() && pcp.getNext() == null && pcp.getPrevious() == null)
1955 System.out.println("Orphan undirected " + pcp + " " + pcp.getPipelineComponent());
1957 for (PipeControlPoint pcp : pcps) {
1958 if (pcp.getParentPoint() == null) {
1959 PipeControlPoint sub = null;
1960 if (pcp.isDualInline())
1961 sub = pcp.getDualSub();
1962 PipeControlPoint next = pcp.getNext();
1963 PipeControlPoint prev = pcp.getPrevious();
1965 if (!(next.getPrevious() == pcp || next.getPrevious() == sub)) {
1966 System.out.println("Inconsistency between " + pcp + " -> " +next );
1970 PipeControlPoint prevParent = null;
1971 if (prev.isDualSub()) {
1972 prevParent = prev.getParentPoint();
1973 } else if (prev.isDualInline()) {
1974 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1976 if (!(prev.getNext() == pcp && (prevParent == null || prevParent.getNext() == pcp))) {
1977 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1984 public static void splitVariableLengthComponent(PipelineComponent newComponent, InlineComponent splittingComponent, boolean assignPos) throws Exception{
1985 assert(!splittingComponent.getControlPoint().isFixedLength());
1986 assert(!(newComponent instanceof InlineComponent && !newComponent.getControlPoint().isFixedLength()));
1987 PipeControlPoint newCP = newComponent.getControlPoint();
1988 PipeControlPoint splittingCP = splittingComponent.getControlPoint();
1989 PipeControlPoint nextCP = splittingCP.getNext();
1990 PipeControlPoint prevCP = splittingCP.getPrevious();
1992 /* there are many different cases to insert new component when
1993 it splits existing VariableLengthinlineComponent.
1995 1. VariableLengthComponet is connected from both sides:
1996 - insert new component between VariableLength component and component connected to it
1997 - insert new VariableLengthComponent between inserted component and component selected in previous step
1999 2. VariableLengthComponent is connected from one side
2000 - Use previous case or:
2001 - Insert new component to empty end
2002 - Insert new VariableLength component to inserted components empty end
2004 3. VariableLength is not connected to any component.
2005 - Should not be possible, at least in current implementation.
2006 - Could be done using second case
2010 if (nextCP == null && prevCP == null) {
2011 // this should not be possible
2012 throw new RuntimeException("VariableLengthComponent " + splittingComponent + " is not connected to anything.");
2014 double newLength = newComponent.getControlPoint().getLength();
2017 Point3d next = new Point3d();
2018 Point3d prev = new Point3d();
2019 splittingCP.getInlineControlPointEnds(prev, next);
2021 Vector3d newPos = null;
2023 newPos = new Vector3d(prev);
2024 Vector3d dir = new Vector3d(next);
2028 newComponent.setWorldPosition(newPos);
2030 newPos = newComponent.getWorldPosition();
2035 Vector3d dir = new Vector3d(next);
2038 dir.scale(newLength * 0.5);
2039 Point3d vn = new Point3d(newPos);
2040 Point3d vp = new Point3d(newPos);
2043 double ln = vn.distance(next);
2044 double lp = vp.distance(prev);
2045 vp.interpolate(prev, 0.5);
2046 vn.interpolate(next, 0.5);
2049 if (nextCP == null) {
2050 newCP.insert(splittingCP, Direction.NEXT);
2051 insertStraight(newCP, Direction.NEXT, new Vector3d(vn), ln);
2052 splittingCP.setWorldPosition(new Vector3d(vp));
2053 // ControlPointTools.setWorldPosition(splittingCP, vp);
2054 // splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
2055 } else if (prevCP == null) {
2056 newCP.insert(splittingCP, Direction.PREVIOUS);
2057 insertStraight(newCP, Direction.PREVIOUS, new Vector3d(vp), lp);
2058 splittingCP.setWorldPosition(new Vector3d(vn));
2059 // splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, ln);
2061 newCP.insert(splittingCP, nextCP);
2062 insertStraight(newCP, nextCP, new Vector3d(vn), ln);
2063 splittingCP.setWorldPosition(new Vector3d(vp));
2064 // splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
2066 positionUpdate(newCP);
2070 public static void addSizeChange(boolean reversed, PipeRun pipeRun, PipeRun other, InlineComponent reducer, PipeControlPoint previous, PipeControlPoint next) {
2071 PipeControlPoint pcp = reducer.getControlPoint();
2072 PipeControlPoint ocp = pcp.getDualSub();
2074 String name = pipeRun.getUniqueName("Reducer");
2075 reducer.setName(name);
2076 pipeRun.addChild(reducer);
2077 other.addChild(ocp);
2078 reducer.setAlternativePipeRun(other);
2080 previous.setNext(pcp);
2081 pcp.setPrevious(previous);
2082 ocp.setPrevious(previous);
2086 next.setPrevious(ocp);
2089 String name = other.getUniqueName("Reducer");
2090 reducer.setName(name);
2091 other.addChild(reducer);
2092 pipeRun.addChild(ocp);
2093 reducer.setAlternativePipeRun(pipeRun);
2097 pcp.setPrevious(next);
2098 ocp.setPrevious(next);
2100 pcp.setNext(previous);
2101 ocp.setNext(previous);
2102 previous.setPrevious(ocp);