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 return new UpdateStruct2(start, startPoint, list, end, endPoint, dir, offset, hasOffsets, iter, direction == Direction.PREVIOUS, toRemove, updated);
453 private static boolean asDirected(PipeControlPoint pcp, Direction direction) {
454 if (pcp.isDirected())
456 if (pcp.asFixedAngle()) {
457 if (!pcp._getReversed())
458 return direction == Direction.NEXT;
460 return direction == Direction.PREVIOUS;
465 private static Vector3d direction(PipeControlPoint pcp, Direction direction) {
466 return pcp.getDirection(direction);
469 private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
472 if (lengthChange == PathLegUpdateType.NONE) {
476 updatePathLeg(u, lengthChange, rs, re);
479 private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean rs, boolean re) throws Exception {
481 if (asDirected(u.start, Direction.NEXT))
483 if (asDirected(u.end, Direction.PREVIOUS))
486 setErrorForce(u.start, null);
488 setErrorForce(u.end, null);
489 for (PipeControlPoint pcp : u.list)
490 setErrorForce(pcp, null);
493 updateFreePathLeg(u, lengthChange);
496 updateDirectedPathLeg(u, lengthChange);
499 updateDualDirectedPathLeg(u, lengthChange);
505 private static void updateFreePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
507 System.out.println("PipingRules.updateFreePipeRun " + u + " " + lengthChange);
508 checkExpandPathLeg(u, lengthChange);
509 if (u.start.isInline() || u.end.isInline() || u.start.asFixedAngle()|| u.end.asFixedAngle())
510 processPathLeg(u, true, false);
513 private static void updateInlineControlPoints(UpdateStruct2 u, boolean checkSizes) throws Exception{
515 System.out.println("PipingRules.updateInlineControlPoints() " + u);
517 Vector3d start = new Vector3d(u.startPoint);
518 Vector3d end = new Vector3d(u.endPoint);
521 // create offsets for leg ends.
522 if (u.start.isTurn())
523 MathTools.mad(start, u.dir, u.start.getInlineLength());
525 MathTools.mad(end, u.dir, -u.end.getInlineLength());
528 boolean recalcline = false;
530 Vector3d sp = new Vector3d(start);
531 Vector3d ep = new Vector3d(end);
534 if (u.start.isOffset()) {
535 Vector3d offset = u.start.getSizeChangeOffsetVector(u.dir);
536 updateOffsetPoint(u.start, offset);
541 for (PipeControlPoint icp : u.list) {
542 updateInlineControlPoint(icp, sp, ep, u.dir);
543 if (icp.isOffset()) {
544 // TODO : offset vector is already calculated and should be cached
545 Vector3d offset = icp.getSizeChangeOffsetVector(u.dir);
546 updateOffsetPoint(icp, offset);
555 // Collect all path leg points for updating variable length components. This list will also contain leg ends (usually turns)
556 ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<>();
557 // Collect all fixed length components with their offsets.
558 ArrayList<Pair<PipeControlPoint,Vector3d>> fixedLengthPoints = new ArrayList<>();
560 pathLegPoints.add(u.start);
561 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(u.start, new Vector3d()));
562 Vector3d off = new Vector3d();
563 for (PipeControlPoint icp : u.list) {
564 pathLegPoints.add(icp);
565 updateBranchControlPointBranches(icp);
566 if (icp.isOffset()) {
567 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(icp, new Vector3d(off)));
568 Vector3d offset = icp.getSizeChangeOffsetVector(u.dir);
570 } else if (!icp.isVariableLength()) {
571 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(icp, new Vector3d(off)));
574 pathLegPoints.add(u.end);
575 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(u.end, new Vector3d(off)));
577 sp = new Vector3d(start);
578 ep = new Vector3d(end);
581 updateFixedLengths(fixedLengthPoints, sp, ep, u.dir);
583 for (int i = 0; i < pathLegPoints.size(); i++) {
584 PipeControlPoint icp = pathLegPoints.get(i);
586 PipeControlPoint prev = i > 0 ? pathLegPoints.get(i - 1) : null;
587 PipeControlPoint next = i < pathLegPoints.size() - 1 ? pathLegPoints.get(i + 1) : null;
589 if (prev != null && prev.isDualInline())
590 prev = prev.getDualSub();
592 if (icp.isVariableLength()) {
593 if (prev != null && next != null) {
594 recalcline = recalcline | updateVariableLength(icp, prev, next);
597 // this is variable length component at the end of the piperun.
598 // the problem is that we want to keep unconnected end of the component in the same
599 // place, but center of the component must be moved.
600 updateVariableLengthEnd(icp, prev != null ? prev : next);
602 } else if (prev != null && !prev.isVariableLength()) {
603 // If this and previous control point are not variable length pcps,
604 // we'll have to check if there is no empty space between them.
605 // I there is, we'll have to create new variable length component between them.
606 recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
608 if (icp.isOffset()) {
609 // TODO : offset vector is already calculated and should be cached
610 Vector3d offset = icp.getSizeChangeOffsetVector(u.dir);
618 u.start.findNextEnd(u.list);
621 sp = new Vector3d(u.startPoint);
622 ep = new Vector3d(u.endPoint);
624 double pathLegLength = MathTools.distance(sp, ep);
625 double availableLength = pathLegLength;
626 if (u.start.isTurn())
627 availableLength -= u.start.getInlineLength();
629 availableLength -= u.end.getInlineLength();
630 for (PipeControlPoint pcp : u.list) {
631 if (!pcp.isVariableLength())
632 availableLength-= pcp.getLength();
634 if (availableLength < 0.0) {
635 setError(u.start, "Not enough available space");
636 setError(u.end, "Not enough available space");
637 for (PipeControlPoint pcp : u.list)
638 setError(pcp, "Not enough available space");
640 // System.out.println(u.start.getPipelineComponent().toString() + " " + pathLegLength + " " + availableLength + " " + u.end.getPipelineComponent().toString() + " " + u.start.getInlineLength() + " " + u.end.getInlineLength());
644 private enum Gap{ATTACHED,OVERLAP,SPACE};
646 private static class GapObj {
650 Pair<PipeControlPoint,Vector3d> pcp1;
651 Pair<PipeControlPoint,Vector3d> pcp2;
654 private static void updateFixedLengths(List<Pair<PipeControlPoint,Vector3d>> fixedLengthPoints, Vector3d s, Vector3d e, Vector3d dir) {
655 double totalLength = MathTools.distance(s, e);
656 double reservedLength = 0.0;
657 List<Double> distances = new ArrayList<>(fixedLengthPoints.size());
659 for (int i = 1; i < fixedLengthPoints.size()-1; i++) {
660 Pair<PipeControlPoint,Vector3d> pcp = fixedLengthPoints.get(i);
661 reservedLength += pcp.first.getLength();
662 Vector3d p = pcp.first.getWorldPosition();
664 double d= MathTools.distance(s, p);
667 distances.add(totalLength);
669 if (totalLength >= reservedLength) {
670 // There is enough space for all fixed length components.
671 List<GapObj> gaps = new ArrayList<>(fixedLengthPoints.size()-1);
673 // Analyze gaps between components
674 for (int i = 0; i < fixedLengthPoints.size()-1; i++) {
675 Pair<PipeControlPoint,Vector3d> pcp1 = fixedLengthPoints.get(i);
676 Pair<PipeControlPoint,Vector3d> pcp2 = fixedLengthPoints.get(i+1);
677 double d1 = distances.get(i);
678 double d2 = distances.get(i+1);
679 double ld1 = i == 0 ? 0.0 :pcp1.first.getInlineLength();
680 double ld2 = i == fixedLengthPoints.size()-2 ? 0.0 : pcp2.first.getInlineLength();
682 double e1 = d1 + ld1; // End of comp1
683 double s2 = d2 - ld2; // Start of comp2
684 double diff =s2 - e1;
685 GapObj obj = new GapObj();
689 if (diff < -MIN_INLINE_LENGTH) {
690 obj.gap = Gap.OVERLAP;
692 } else if (diff > MIN_INLINE_LENGTH) {
695 obj.gap = Gap.ATTACHED;
699 // If there are no overlaps, there is nothing to do.
702 // Get rid of overlapping components by using closest available free spaces.
703 for (int i = 0; i < gaps.size(); i++) {
704 GapObj gapObj = gaps.get(i);
705 if (gapObj.gap != Gap.OVERLAP)
707 double curr = gapObj.d;
709 while (curr < -MIN_INLINE_LENGTH) {
710 GapObj next = i+d >= 0 ? gaps.get(i+d) : null;
711 GapObj prev = i-d >= 0 ? gaps.get(i-d) : null;
712 if (next != null && next.gap == Gap.SPACE) {
713 double move = Math.min(-curr, next.d);
716 if (next.d < MIN_INLINE_LENGTH)
717 next.gap = Gap.ATTACHED;
718 Vector3d mv = new Vector3d(dir);
721 for (int j = i ; j < i+d; j++) {
722 Pair<PipeControlPoint,Vector3d> pcp = gaps.get(j).pcp2;
723 Vector3d p = new Vector3d(pcp.first.getWorldPosition());
725 pcp.first.setWorldPosition(p);
728 if (curr < -MIN_INLINE_LENGTH && prev != null && prev.gap == Gap.SPACE) {
729 double move = Math.min(-curr, prev.d);
732 if (next.d < MIN_INLINE_LENGTH)
733 next.gap = Gap.ATTACHED;
734 Vector3d mv = new Vector3d(dir);
737 for (int j = i ; j > i-d; j--) {
738 Pair<PipeControlPoint,Vector3d> pcp = gaps.get(j).pcp1;
739 Vector3d p = new Vector3d(pcp.first.getWorldPosition());
741 pcp.first.setWorldPosition(p);
747 for (int i = 1; i < fixedLengthPoints.size()-1; i++) {
748 Pair<PipeControlPoint,Vector3d> prev = i == 0 ? null : fixedLengthPoints.get(i-1);
749 Pair<PipeControlPoint,Vector3d> curr = fixedLengthPoints.get(i);
750 Pair<PipeControlPoint,Vector3d> next = i == fixedLengthPoints.size() -1 ? null : fixedLengthPoints.get(i+1);
751 updateFixedLength(curr, prev, next, s,e, dir);
756 private static void updateFixedLength(Pair<PipeControlPoint,Vector3d> icp, Pair<PipeControlPoint,Vector3d> prev, Pair<PipeControlPoint,Vector3d> next, Vector3d s, Vector3d e, Vector3d dir) {
758 checkOverlap(prev, icp, dir,true);
761 checkOverlap(icp, next, dir,true);
764 private static boolean checkOverlap(Pair<PipeControlPoint,Vector3d> icp, Pair<PipeControlPoint,Vector3d> icp2, Vector3d dir, boolean se) {
765 Vector3d p1 = icp.first.getWorldPosition();
766 Vector3d p2 = icp2.first.getWorldPosition();
769 double u[] = new double[1];
770 MathTools.closestPointOnStraight(p2, p1, dir, u);
775 MathTools.mad(p2, dir, MIN_INLINE_LENGTH);
776 icp2.first.setWorldPosition(p2);
778 double d = MathTools.distance(p1, p2);
779 double r = icp.first.getInlineLength() + icp2.first.getInlineLength();
781 if ((d-r) < - MIN_INLINE_LENGTH) {
783 setError(icp.first, "Overlapping");
784 setError(icp2.first, "Overlapping");
792 * Overrides current error of a component
796 private static void setErrorForce(PipeControlPoint pcp, String error) {
797 PipelineComponent comp = pcp.getPipelineComponent();
800 comp.setError(error);
804 * Sets error for a component, if there is no existing error.
808 private static void setError(PipeControlPoint pcp, String error) {
809 PipelineComponent comp = pcp.getPipelineComponent();
812 if (comp.getError() != null)
814 comp.setError(error);
817 private static boolean updateVariableLength(PipeControlPoint icp, PipeControlPoint prev, PipeControlPoint next) {
818 Vector3d prevPos = prev.getWorldPosition();
819 Vector3d nextPos = next.getWorldPosition();
821 Vector3d dir = new Vector3d(nextPos);
823 double l = dir.length(); // distance between control points
824 double l2prev = prev.getInlineLength(); // distance taken by components
825 double l2next = next.getInlineLength();
826 double l2 = l2prev + l2next;
827 double length = l - l2; // true length of the variable length component
828 if (length >= MIN_INLINE_LENGTH) { // check if there is enough space for variable length component.
831 dir.scale(length * 0.5 + l2prev); // calculate center position of the component
833 icp.setWorldPosition(dir);
834 icp.setLength(length);
837 // components leave no space to the component and it must be removed
838 if (icp.isDeletable()) {
839 if (!allowInsertRemove) {
840 icp.setLength(MIN_INLINE_LENGTH);
841 setError(icp, "Not enough available space");
846 System.out.println("PipingRules.updateVariableLength removing " + icp);
850 icp.setLength(MIN_INLINE_LENGTH);
851 icp.getPipelineComponent().setError("Not enough available space");
857 private static boolean possibleVaribleLengthInsert(PipeControlPoint icp, PipeControlPoint prev) throws Exception{
858 Vector3d currentPos = icp.getWorldPosition();
859 Vector3d prevPos = prev.getWorldPosition();
860 Vector3d dir = new Vector3d(currentPos);
862 double l = dir.lengthSquared();
863 double l2prev = prev.getInlineLength();
864 double l2next = icp.getInlineLength();
865 double l2 = l2prev + l2next;
866 double l2s = l2 * l2;
868 if (allowInsertRemove) {
870 double length = Math.sqrt(l) - l2; // true length of the variable length component
871 dir.scale(length * 0.5 + l2prev); // calculate center position of the component
873 insertStraight(prev, icp, dir, length);
882 private static void updateVariableLengthEnd(PipeControlPoint icp, PipeControlPoint prev) {
883 Vector3d currentPos = icp.getWorldPosition();
884 Vector3d prevPos = prev.getWorldPosition();
886 Vector3d dir = new Vector3d();
887 dir.sub(currentPos, prevPos);
889 boolean simple = currentUpdates.contains(icp);
891 // Update based on position -> adjust length
892 double currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
893 icp.setLength(currentLength);
895 // Update based on neighbour movement -> adjust length and position, so that free end stays in place.
896 double currentLength = icp.getLength();
897 if (currentLength < MathTools.NEAR_ZERO) {
898 currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
901 if (dir.lengthSquared() > MathTools.NEAR_ZERO)
903 Point3d endPos = new Point3d(dir);
904 endPos.scale(currentLength * 0.5);
905 endPos.add(currentPos); // this is the free end of the component
907 double offset = prev.getInlineLength();
908 Point3d beginPos = new Point3d(dir);
909 beginPos.scale(offset);
910 beginPos.add(prevPos); // this is the connected end of the component
912 double l = beginPos.distance(endPos);
915 System.out.println("Length for " + icp + " is NaN");
918 beginPos.add(dir); // center position
921 System.out.println("PipingRules.updateInlineControlPoints() setting variable length to " + l);
924 icp.setWorldPosition(new Vector3d(beginPos));
928 private static void ppNoOffset(UpdateStruct2 u) throws Exception {
930 System.out.println("PipingRules.ppNoOffset() " + u);
931 Vector3d offset = new Vector3d();
934 for (PipeControlPoint icp : u.list) {
935 if (icp.isOffset()) {
936 offset.add(icp.getSizeChangeOffsetVector(u.dir));
937 } else if (icp.isDualSub())
938 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
942 checkExpandPathLeg(u, PathLegUpdateType.NONE);
945 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 {
947 System.out.println("PipingRules.ppNoDir() " + start + " " + end + " " + iter + " " + toRemove.size());
948 // FIXME : extra loop (dir should be calculated here)
949 Vector3d dir = new Vector3d();
950 Vector3d offset = new Vector3d();
951 hasOffsets = calculateOffset(startPoint, endPoint, start, list, end, dir, offset);
952 ppNoOffset(new UpdateStruct2(start, startPoint, list, end, endPoint, dir, null, hasOffsets, iter, reversed, toRemove, updated));
955 private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
956 checkExpandPathLeg(u, lengthChange, u.updated.isInline() && u.updated.isOffset());
959 private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean updateEnds) throws Exception {
961 System.out.println("PipingRules.checkExpandPathLeg() " + u + " " + lengthChange);
962 if (lengthChange != PathLegUpdateType.NONE) {
963 // FIXME : turns cannot be checked before inline cps are updated,
964 // since their position affects calculation of turns
965 processPathLeg(u, updateEnds, false);
966 int type = checkTurns(u, lengthChange);
967 if (type == REMOVE_NONE) {
968 processPathLeg(u, updateEnds, true);
970 expandPathLeg(u, type);
973 processPathLeg(u, updateEnds, true);
977 private static void updateDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
979 System.out.println("PipingRules.updateDirectedPipeRun() " + u + " " + lengthChange);
980 PipeControlPoint dcp;
981 PipeControlPoint other;
982 boolean canMoveOther = false;
983 boolean dcpStart = false;
984 boolean inlineEnd = false;
986 if (asDirected(u.start, Direction.NEXT)) {
989 position = u.startPoint;
991 inlineEnd = u.end.isInline();
996 position = u.endPoint;
997 inlineEnd = u.start.isInline();
999 canMoveOther = !(other == u.updated);
1001 Vector3d directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS);
1002 if (directedDirection == null) {
1003 //updateTurnControlPointTurn(dcp, dcp.getPrevious(), dcp.getNext());
1004 updateTurnControlPointTurn(dcp, null, null);
1005 directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS);
1006 if (directedDirection == null) {
1010 Point3d directedEndPoint = new Point3d(u.endPoint);
1012 directedEndPoint.sub(u.offset);
1014 double mu[] = new double[2];
1017 Vector3d t = new Vector3d();
1020 closest = MathTools.closestPointOnStraight(directedEndPoint, u.startPoint, directedDirection, mu);
1021 t.sub(closest, directedEndPoint);
1023 closest = MathTools.closestPointOnStraight(u.startPoint, directedEndPoint, directedDirection, mu);
1024 t.sub(closest, u.startPoint);
1027 double distance = t.length();
1028 boolean aligned = (distance < ALLOWED_OFFSET);
1029 double requiredSpace = 0.0;
1030 if (other.isVariableAngle()) {
1031 requiredSpace = spaceForTurn(other, dcp);
1033 if (mu[0] < requiredSpace) {
1034 // At the moment, if next component is directly behind the nozzle, we must force moving the other component.
1035 // Trying to solve the situation by adding new turn creates infinite loop...
1037 canMoveOther = true;
1040 if (u.start.isInline() || u.end.isInline() || u.start.asFixedAngle() || u.end.asFixedAngle())
1041 processPathLeg(u, true, false);
1042 checkExpandPathLeg(u, lengthChange, inlineEnd);
1048 PipeControlPoint nextToMoved;
1050 if (u.list.size() > 0)
1052 nextToMoved = u.list.get(0);
1054 nextToMoved = u.list.get(u.list.size() - 1);
1056 nextToMoved = u.end;
1058 nextToMoved = u.start;
1059 if (other.isVariableAngle()) {
1061 // TODO calculate needed space from next run end.
1062 if (mu[0] < requiredSpace) {
1064 closest.set(u.startPoint);
1066 closest.set(u.endPoint);
1068 Vector3d v = new Vector3d(directedDirection);
1069 v.scale(requiredSpace);
1075 System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + closest);
1076 other.setWorldPosition(closest);
1078 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));
1079 if (u.end.getNext() != null)
1080 updatePathLegNext(u.end, u.updated, PathLegUpdateType.NEXT);
1082 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));
1083 if (u.start.getPrevious() != null)
1084 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.PREV);
1087 // TODO : calculate needed space from next run end.
1088 if (allowInsertRemove)
1089 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
1094 } else if (other.isNonDirected() && other.getParentPoint() != null) {
1095 // FIXME : this code was for updating branches
1096 Vector3d bintersect = new Vector3d();
1097 PipeControlPoint bcp = other.getParentPoint();
1098 if (bcp != null && canMoveOther) {
1099 Point3d bstart = new Point3d();
1100 Point3d bend = new Point3d();
1101 Vector3d bdir = new Vector3d();
1102 bcp.getInlineControlPointEnds(bstart, bend, bdir);
1103 Vector3d nintersect = new Vector3d();
1105 MathTools.intersectStraightStraight(position, directedDirection, bend, bdir, nintersect, bintersect, mu);
1106 Vector3d dist = new Vector3d(nintersect);
1107 dist.sub(bintersect);
1108 canMoveOther = mu[1] > 0.0 && mu[1] < 1.0 && dist.lengthSquared() < 0.01;
1110 // TODO : endControlPoints are undirected: calculcate
1111 // correct position for it
1112 throw new UnsupportedOperationException("not implemented");
1116 System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + bintersect);
1117 // is required branch position is in possible range
1118 bcp.setWorldPosition(bintersect);
1120 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);
1122 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);
1125 // branch cannot be moved into right position, new turn
1126 // / elbow must be inserted
1127 if (allowInsertRemove)
1128 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
1133 } else { // assume that control point cannot be moved, but can
1135 if (allowInsertRemove)
1136 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
1146 private static void updateDualDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
1148 System.out.println("PipingRules.updateDualDirectedPipeRun() " + u + " " + lengthChange);
1150 PipeControlPoint dcp1 = u.start;
1151 PipeControlPoint dcp2 = u.end;
1152 Point3d position1 = new Point3d(u.startPoint);
1153 Point3d position2 = new Point3d(u.endPoint);
1154 Point3d position1offset = new Point3d(position1);
1155 position1offset.sub(u.offset);
1156 Point3d position2offset = new Point3d(position2);
1157 position2offset.add(u.offset);
1158 Vector3d dir1 = direction(dcp1, Direction.NEXT);
1159 Vector3d dir2 = direction(dcp2, Direction.PREVIOUS);
1160 Vector3d p1 = MathTools.closestPointOnStraight(position1offset, position2, dir2);
1161 Vector3d p2 = MathTools.closestPointOnStraight(position2offset, position1, dir1);
1162 double d1 = position1.distance(new Point3d(p1));
1163 double d2 = position2.distance(new Point3d(p2));
1165 boolean aligned = (d1 < ALLOWED_OFFSET && d2 < ALLOWED_OFFSET);
1171 } else if (allowInsertRemove){
1172 PipeControlPoint dcp;
1173 PipeControlPoint next;
1176 if (u.list.size() > 0)
1177 next = u.list.get(0);
1182 if (u.list.size() > 0)
1183 next = u.list.get(u.list.size() - 1);
1188 p1 = dcp.getWorldPosition();
1189 Vector3d v = new Vector3d();
1195 // Reserve space for 90 deg elbow
1196 double off = dcp1.getPipeRun().getTurnRadius();
1201 p2 = MathTools.closestPointOnStraight(new Point3d(p1), position2, dir2);
1203 p2 = MathTools.closestPointOnStraight(new Point3d(p1), position1, dir1);
1205 // By default, the elbows are placed next to each other, by using 90 deg angles.
1206 // If the distance between elbows is not enough, we must move the other elbow (and create more shallow angle elbows)
1207 if (MathTools.distance(p1, p2) < off*2.05) {
1211 PipeControlPoint tcp1 = insertElbow(dcp, next, p1);
1212 PipeControlPoint tcp2 = insertElbow(tcp1, next, p2);
1215 System.out.println("PipingRules.updateDualDirectedPipeRun() created two turns " + tcp1 + " " + tcp2);
1218 Vector3d dd = new Vector3d(p2);
1221 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1222 updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1224 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1226 updatePathLegPrev(tcp2, u.updated, PathLegUpdateType.NONE);
1228 Vector3d dd = new Vector3d(p1);
1231 updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1232 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1234 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1236 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.NONE);
1245 private static double spaceForTurn(PipeControlPoint tcp, PipeControlPoint dcp) {
1246 // TODO : if the path legs contain offset, using just positions of opposite path leg ends is not enough.
1247 // TODO : current iterative way for calculating required space may return longer length that is required.
1248 double tr = ((TurnComponent)tcp.getPipelineComponent()).getTurnRadius();
1250 return tr; // space for 90 deg
1251 PipeControlPoint ne = tcp.findNextEnd();
1252 PipeControlPoint pe = tcp.findPreviousEnd();
1253 PipeControlPoint other = null;
1259 return tr; // space for 90 deg
1261 return tr; // space for 90 deg
1262 Vector3d dir = dcp.getDirectedControlPointDirection();
1263 Vector3d dp = dcp.getWorldPosition();
1264 Vector3d op = other.getWorldPosition();
1265 double u[] = new double[1];
1266 Vector3d closest = MathTools.closestPointOnStraight(op, dp, dir,u);
1267 if (MathTools.distanceSquared(closest, op) <= MIN_INLINE_LENGTH) {
1268 if (u[0] > -MIN_INLINE_LENGTH)
1269 return 0.0; // point following turn is directly in the front of the nozzle.
1271 return tr*2.0; // point following turn is directly behind the nozzle, in theory, we should return Double.Inf...
1273 double curr = tr*0.1;
1275 Vector3d v1 = new Vector3d();
1276 Vector3d v2 = new Vector3d();
1278 Vector3d tp = new Vector3d(dp);
1279 MathTools.mad(tp, dir, curr);
1280 v1.sub(tp, dp); // Vector from nozzle to turn
1281 v2.sub(op,tp); // Vector from turn to other
1282 double a = v1.angle(v2);
1283 double t = Math.tan((Math.PI - a) * 0.5);
1285 if (t > MathTools.NEAR_ZERO)
1295 private static void insertElbowUpdate(UpdateStruct2 u, PipeControlPoint dcp, PipeControlPoint next, boolean dcpStart, Vector3d position, Vector3d directedDirection) throws Exception{
1298 // Vector3d closest = new Vector3d(position);
1299 // closest.add(directedDirection);
1301 PipeControlPoint tcp = null;
1304 closest = MathTools.closestPointOnStraight(next.getWorldPosition(), position, directedDirection);
1305 tcp = insertElbow(dcp, next, closest);
1307 closest = MathTools.closestPointOnStraight(dcp.getWorldPosition(), position, directedDirection);
1308 tcp = insertElbow(next, dcp, closest);
1310 double d = MathTools.distance(position, closest);
1311 double s = spaceForTurn(tcp,dcp);
1314 Vector3d p = new Vector3d(directedDirection);
1324 System.out.println("PipingRules.updateDirectedPipeRun() inserted " + tcp);
1327 // update pipe run from new turn to other end
1328 ppNoDir(tcp, new Vector3d(closest), u.list, u.end, u.endPoint, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1329 // update pipe run from directed to new turn
1330 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));
1332 // update pipe run from other end to new turn
1333 ppNoDir(u.start, u.startPoint, u.list, tcp, new Vector3d(closest), u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1334 // update pipe run from new turn to directed
1335 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));
1340 * Checks if turns can be removed (turn angle near zero)
1342 private static int checkTurns(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
1344 System.out.println("PipingRules.checkTurns() " + u.start + " " + u.end);
1345 boolean startRemoved = false;
1346 boolean endRemoved = false;
1347 if (u.start.isVariableAngle()) {
1348 // this won't work properly if inline control points are not updated
1349 PipeControlPoint startPrev = u.start.getPrevious();
1350 if (startPrev != null) {
1351 double a = updateTurnControlPointTurn(u.start, null, u.dir);
1352 if (a < MIN_TURN_ANGLE && u.start.isDeletable())
1353 startRemoved = true;
1354 else if (lengthChange == PathLegUpdateType.PREV || lengthChange == PathLegUpdateType.PREV_S) {
1355 PathLegUpdateType type;
1356 if (lengthChange == PathLegUpdateType.PREV_S)
1357 type = PathLegUpdateType.PREV;
1359 type = PathLegUpdateType.NONE;
1360 updatePathLegPrev(u.start, u.start, type);
1364 if (u.end.isVariableAngle()) {
1366 PipeControlPoint endNext = u.end.getNext();
1367 if (endNext != null) {
1368 // TODO: u.end, u.dir, null
1369 double a = updateTurnControlPointTurn(u.end, null, null);
1370 if (a < MIN_TURN_ANGLE && u.end.isDeletable())
1372 else if (lengthChange == PathLegUpdateType.NEXT || lengthChange == PathLegUpdateType.NEXT_S) {
1373 PathLegUpdateType type;
1374 if (lengthChange == PathLegUpdateType.NEXT_S)
1375 type = PathLegUpdateType.NEXT;
1377 type = PathLegUpdateType.NONE;
1378 updatePathLegNext(u.end, u.end, type);
1383 System.out.println("PipingRules.checkTurns() res " + startRemoved + " " + endRemoved);
1384 if (!startRemoved && !endRemoved)
1386 if (startRemoved && endRemoved)
1389 return REMOVE_START;
1394 * Expands piperun search over turns that are going to be removed
1397 private static void expandPathLeg(UpdateStruct2 u, int type) throws Exception {
1399 System.out.println("PipingRules.expandPipeline " + u.start + " " + u.end);
1400 ArrayList<PipeControlPoint> newList = new ArrayList<PipeControlPoint>();
1403 throw new RuntimeException("Error in piping rules");
1405 u.toRemove.add(new ExpandIterInfo(u.start, REMOVE_START));
1406 u.start = u.start.findPreviousEnd();
1407 u.startPoint = u.start.getPosition();
1408 u.start.findNextEnd(newList);
1409 newList.addAll(u.list);
1413 u.toRemove.add(new ExpandIterInfo(u.end, REMOVE_END));
1414 u.end = u.end.findNextEnd(newList);
1415 u.endPoint = u.end.getPosition();
1416 u.list.addAll(newList);
1419 u.toRemove.add(new ExpandIterInfo(u.start, u.end));
1420 u.start = u.start.findPreviousEnd();
1421 u.startPoint = u.start.getPosition();
1422 u.start.findNextEnd(newList);
1423 newList.addAll(u.list);
1425 newList = new ArrayList<PipeControlPoint>();
1426 u.end = u.end.findNextEnd(newList);
1427 u.endPoint = u.end.getPosition();
1428 u.list.addAll(newList);
1431 throw new RuntimeException("Error in piping rules");
1434 u.offset = new Vector3d();
1437 for (PipeControlPoint icp : u.list) {
1438 if (icp.isOffset()) {
1439 u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1440 } else if (icp.isDualSub())
1441 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1445 System.out.println("PipingRules.expandPipeline expanded " + u.start + " " + u.end);
1447 updatePathLeg(u, PathLegUpdateType.NONE);
1451 * reverts one iteration of turn removing back)
1453 private static void backIter(UpdateStruct2 u) throws Exception {
1456 System.out.println("PipingRules.backIter" + u.start + " " + u.end);
1458 throw new RuntimeException("Error in piping rules");
1459 ExpandIterInfo info = u.toRemove.get(u.toRemove.size() - 1);
1460 u.toRemove.remove(u.toRemove.size() - 1);
1461 if (info.getType() == REMOVE_START || info.getType() == REMOVE_BOTH) {
1462 while (u.list.size() > 0) {
1463 PipeControlPoint icp = u.list.get(0);
1464 if (icp.getPrevious().equals(info.getStart()))
1468 u.start = info.getStart();
1470 if (info.getType() == REMOVE_END || info.getType() == REMOVE_BOTH) {
1471 while (u.list.size() > 0) {
1472 PipeControlPoint icp = u.list.get(u.list.size() - 1);
1473 if (icp.getNext().equals(info.getEnd()))
1477 u.end = info.getEnd();
1479 u.offset = new Vector3d();
1482 for (PipeControlPoint icp : u.list) {
1483 if (icp.isOffset()) {
1484 u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1485 } else if (icp.isDualSub())
1486 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1494 * Processes pipe run (removes necessary turns and updates run ends)
1496 // private static void processPathLeg(PipeControlPoint start, Point3d
1497 // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1498 // end,Point3d endPoint, Vector3d dir,Vector3d offset, boolean
1499 // hasOffsets,int iter, boolean reversed, ArrayList<ExpandIterInfo>
1500 // toRemove) throws TransactionException {
1502 private static void processPathLeg(UpdateStruct2 u) throws Exception {
1504 System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1505 processPathLeg(u, true, true);
1508 private static void processPathLeg(UpdateStruct2 u, boolean updateEnds, boolean updateInline) throws Exception {
1510 System.out.println("PipingRules.processPathLeg " + (updateEnds ? "ends " : "") + (updateInline ? "inline " : "") + u.start + " " + u.end);
1512 if (u.toRemove.size() > 0) {
1513 for (ExpandIterInfo info : u.toRemove) {
1514 if (info.getStart() != null) {
1516 System.out.println("PipingRules.processPathLeg removing start " + info.getStart());
1517 info.getStart()._remove();
1519 if (info.getEnd() != null) {
1521 System.out.println("PipingRules.processPathLeg removing end " + info.getEnd());
1522 info.getEnd()._remove();
1525 // ControlPointTools.removeControlPoint may remove more than one CP;
1526 // we must populate inline CP list again.
1528 u.start.findNextEnd( u.list);
1530 // FIXME : inline CPs are update twice because their positions must be
1531 // updated before and after ends.
1532 updateInlineControlPoints(u, false);
1535 if (u.start.isTurn()) {
1536 //updateTurnControlPointTurn(u.start, u.start.getPrevious(), u.start.getNext());
1537 updateTurnControlPointTurn(u.start, null, null);
1538 // updatePathLegPrev(u.start, u.start, PathLegUpdateType.NONE);
1539 } else if (u.start.isEnd()) {
1540 updateEndComponentControlPoint(u.start, u.dir);
1541 } else if (u.start.isInline()) {
1542 updateControlPointOrientation(u.start, u.dir);
1544 if (u.end.isTurn()) {
1545 //updateTurnControlPointTurn(u.end, u.end.getPrevious(), u.end.getNext());
1546 updateTurnControlPointTurn(u.end, null, null);
1547 // updatePathLegNext(u.end, u.end, PathLegUpdateType.NONE);
1548 } else if (u.end.isEnd()) {
1549 updateEndComponentControlPoint(u.end, u.dir);
1550 } else if (u.end.isInline()) {
1551 updateControlPointOrientation(u.end, u.dir);
1555 if (u.start.isEnd()) {
1556 updateEndComponentControlPoint(u.start, u.dir);
1558 if (u.end.isEnd()) {
1559 updateEndComponentControlPoint(u.end, u.dir);
1563 updateInlineControlPoints(u, true);
1568 * Processes pipe run and recalculates offset
1570 // private static void processPathLeg(PipeControlPoint start, Point3d
1571 // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1572 // end,Point3d endPoint, Vector3d dir, boolean hasOffsets,int iter, boolean
1573 // reversed, ArrayList<ExpandIterInfo> toRemove) throws TransactionException
1575 @SuppressWarnings("unused")
1576 private static void processPathLegNoOffset(UpdateStruct2 u) throws Exception {
1578 System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1579 Vector3d offset = new Vector3d();
1582 for (PipeControlPoint icp : u.list) {
1583 if (icp.isOffset()) {
1584 offset.add(icp.getSizeChangeOffsetVector(u.dir));
1585 } else if (icp.isDualSub()) {
1586 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1593 private static void updateOffsetPoint(PipeControlPoint sccp, Vector3d offset) {
1594 Vector3d world = sccp.getWorldPosition();
1596 PipeControlPoint ocp = sccp.getDualSub();
1597 ocp.setWorldPosition(world);
1601 * Updates InlineControlPoints position when straight pipe's end(s) have
1609 private static void updateInlineControlPoint(PipeControlPoint icp, Vector3d prev, Vector3d next, Vector3d dir) {
1611 System.out.println("PipingRules.updateInlineControlPoint() " + icp);
1613 Vector3d inlinePoint = icp.getWorldPosition();
1614 Vector3d prevPoint = new Vector3d(prev);
1615 Vector3d nextPoint = new Vector3d(next);
1616 if (!icp.isVariableLength()) {
1617 // Reserve space for fixed length components.
1618 MathTools.mad(prevPoint, dir, icp.getInlineLength());
1619 MathTools.mad(nextPoint, dir, -icp.getInlineLength());
1620 if (MathTools.distance(prevPoint, nextPoint) < ALLOWED_OFFSET) {
1625 boolean canCalc = MathTools.distance(prevPoint, nextPoint) > ALLOWED_OFFSET;
1627 System.out.print("InlineControlPoint update " + icp + " " + inlinePoint + " " + prevPoint + " " + nextPoint);
1628 Vector3d newInlinePoint = null;
1630 boolean branchUpdate = false;
1631 PipeControlPoint becp = null;
1632 for (PipeControlPoint pcp : icp.getChildPoints())
1633 if (pcp.isNonDirected()) {
1634 branchUpdate = true;
1639 if (DUMMY || !branchUpdate) {
1640 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1644 // FIXME : can only handle one branch
1645 PipeControlPoint p = null;
1646 if (becp.getNext() != null) {
1647 p = becp.findNextEnd();
1648 } else if (becp.getPrevious() != null) {
1649 p = becp.findPreviousEnd();
1652 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1653 } else if (canCalc){
1654 Vector3d branchLegEnd = p.getWorldPosition();
1655 Vector3d dir2 = new Vector3d(inlinePoint);
1656 dir2.sub(branchLegEnd);
1657 Vector3d dir1 = new Vector3d(nextPoint);
1658 dir1.sub(prevPoint);
1659 newInlinePoint = new Vector3d();
1660 double mu[] = new double[2];
1661 MathTools.intersectStraightStraight(new Vector3d(prevPoint), dir1, new Vector3d(branchLegEnd), dir2, newInlinePoint, new Vector3d(), mu);
1663 System.out.println(mu[0]);
1664 // FIXME : reserve space
1666 newInlinePoint = new Vector3d(prevPoint);
1667 } else if (mu[0] > 1.0) {
1668 newInlinePoint = new Vector3d(nextPoint);
1673 // prevPoint == nextPoint
1674 newInlinePoint = new Vector3d(prevPoint);
1677 System.out.println(" " + newInlinePoint);
1679 icp.setWorldPosition(newInlinePoint);
1680 updateControlPointOrientation(icp, dir);
1684 * Updates InlineControlPoints position when straight pipe's end(s) have
1692 private static void updateEndComponentControlPoint(PipeControlPoint ecp, Vector3d dir) throws Exception {
1694 System.out.println("PipingRules.updateEndComponentControlPoint() " + ecp);
1696 if (!ecp.isFixed()) // prevent overriding nozzle orientations..
1697 updateControlPointOrientation(ecp, dir);
1699 for (PipeControlPoint pcp : ecp.getChildPoints()) {
1700 // TODO update position
1701 updatePathLegEndControlPoint(pcp);
1705 private static void updateControlPointOrientation(PipeControlPoint pcp, Vector3d dir) {
1706 Double angleO = pcp.getRotationAngle();
1710 boolean reversed = pcp._getReversed();
1713 q = pcp.getControlPointOrientationQuat(dir, angle, reversed);
1715 q = pcp.getControlPointOrientationQuat(angle, reversed);
1717 pcp.setWorldOrientation(q);
1721 * Updates all branches when branch's position has been changed
1725 private static void updateBranchControlPointBranches(PipeControlPoint bcp) throws Exception {
1727 System.out.println("PipingRules.updateBranchControlPointBranches() " + bcp);
1728 if (bcp.isDualInline())
1730 Collection<PipeControlPoint> branches = bcp.getChildPoints();
1731 if (branches.size() == 0) {
1733 System.out.println("No Branches found");
1737 for (PipeControlPoint pcp : branches) {
1738 updatePathLegEndControlPoint(pcp);
1742 private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d prev, Vector3d next) {
1744 UpdateStruct2 us = createUS(tcp, Direction.NEXT, 0, new ArrayList<PipingRules.ExpandIterInfo>(), tcp);
1749 UpdateStruct2 us = createUS(tcp, Direction.PREVIOUS, 0, new ArrayList<PipingRules.ExpandIterInfo>(), tcp);
1755 if (!tcp.asFixedAngle()) {
1758 if (next == null || prev == null) {
1759 if (tcp.getTurnAngle() != null)
1760 return tcp.getTurnAngle();
1761 return Math.PI; // FIXME : argh
1763 double turnAngle = prev.angle(next);
1765 double angle = Math.PI - turnAngle;
1767 Vector3d turnAxis = new Vector3d();
1768 turnAxis.cross(prev, next);
1769 if (turnAxis.lengthSquared() > MathTools.NEAR_ZERO) {
1770 double elbowRadius = ((TurnComponent)tcp.getPipelineComponent()).getTurnRadius();
1771 double R = elbowRadius / Math.tan(angle * 0.5);
1773 turnAxis.normalize();
1774 tcp.setTurnAngle(turnAngle);
1775 tcp.setLength(R);// setComponentOffsetValue(R);
1776 tcp.setTurnAxis(turnAxis);
1777 // tcp.setPosition(tcp.getPosition());
1780 tcp.setTurnAngle(0.0);
1782 tcp.setTurnAxis(new Vector3d(MathTools.Y_AXIS));
1785 updateControlPointOrientation(tcp,prev);
1788 System.out.println("PipingTools.updateTurnControlPointTurn " + prev + " " + next + " " + turnAngle + " " + turnAxis);
1792 if (prev != null && next != null) {
1794 } else if (prev == null) {
1795 if (!tcp._getReversed())
1796 tcp.setReversed(true);
1797 } else if (next == null) {
1798 if (tcp._getReversed())
1799 tcp.setReversed(false);
1802 Vector3d dir = null;
1803 if (!tcp._getReversed()) {
1810 return Math.PI; // FIXME : argh
1813 Quat4d q = PipeControlPoint.getControlPointOrientationQuat(dir, tcp.getRotationAngle() != null ? tcp.getRotationAngle() : 0.0);
1814 Vector3d v = new Vector3d();
1815 MathTools.rotate(q, MathTools.Y_AXIS,v);
1817 tcp.setWorldOrientation(q);
1818 if (tcp.getTurnAngle() != null)
1819 return tcp.getTurnAngle();
1820 return Math.PI; // FIXME : argh
1826 public static List<PipeControlPoint> getControlPoints(PipeRun pipeRun) {
1827 List<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
1828 if (pipeRun.getControlPoints().size() == 0)
1830 PipeControlPoint pcp = pipeRun.getControlPoints().iterator().next();
1831 while (pcp.getPrevious() != null) {
1832 PipeControlPoint prev = pcp.getPrevious();
1833 if (prev.getPipeRun() != pipeRun && prev.getPipeRun() != null) { // bypass possible corruption
1838 if (pcp.isDualSub()) {
1839 pcp = pcp.getParentPoint();
1842 while (pcp.getNext() != null) {
1843 pcp = pcp.getNext();
1844 if (pcp.getPipeRun() != pipeRun)
1851 public static void reverse(PipeRun pipeRun) {
1854 List<PipeControlPoint> points = getControlPoints(pipeRun);
1855 PipeControlPoint pcp = points.get(0);
1856 if (pcp.isSizeChange() && pcp.getChildPoints().size() > 0) {
1857 PipeRun pr = pcp.getPipeRun();
1865 List<PipeRun> all = new ArrayList<PipeRun>();
1866 List<List<PipeControlPoint>> pcps = new ArrayList<List<PipeControlPoint>>();
1869 List<PipeControlPoint> points = getControlPoints(pipeRun);
1871 PipeControlPoint pcp = points.get(points.size()-1);
1872 if (pcp.getChildPoints().size() > 0) {
1873 PipeRun pipeRun2 = pcp.getChildPoints().get(0).getPipeRun();
1874 if (pipeRun == pipeRun2)
1882 for (int i = 0 ; i < all.size(); i++) {
1883 List<PipeControlPoint> list = pcps.get(i);
1886 for (int i = 0 ; i < all.size(); i++) {
1887 boolean last = i == all.size() - 1;
1888 List<PipeControlPoint> list = pcps.get(i);
1891 List<PipeControlPoint> list2 = pcps.get(i+1);
1892 PipeControlPoint prev = list.get(list.size()-1);
1893 PipeControlPoint next = list2.get(0);
1895 // Reverse the component on the boundary.
1896 InlineComponent ic = (InlineComponent)prev.getPipelineComponent();
1897 PipeRun r1 = ic.getPipeRun();
1898 PipeRun r2 = ic.getAlternativePipeRun();
1899 if (r1 == null || r2 == null)
1900 throw new RuntimeException("Components on PipeRun changes should refer to bot PipeRuns");
1904 ic.setAlternativePipeRun(r1);
1906 throw new RuntimeException("PipeRun changes should contain shared control points");
1914 private static void _reverse(List<PipeControlPoint> list) {
1915 if (list.size() <= 1)
1916 return; // nothing to do.
1918 for (int i = 0 ; i < list.size(); i++) {
1919 boolean first = i == 0;
1920 boolean last = i == list.size() - 1;
1921 PipeControlPoint current = list.get(i);
1922 PipeControlPoint currentSub = null;
1923 if (current.isDualInline())
1924 currentSub = current.getDualSub();
1926 PipeControlPoint next = list.get(i+1);
1927 if (next.isDualInline())
1928 next = next.getDualSub();
1929 if (current.getNext() == next)
1930 current.setNext(null);
1931 current.setPrevious(next);
1932 if (currentSub != null) {
1933 if (currentSub.getNext() == next)
1934 currentSub.setNext(null);
1935 currentSub.setPrevious(next);
1938 PipeControlPoint prev = list.get(i-1);
1940 if (current.getPrevious() == prev)
1941 current.setPrevious(null);
1942 current.setNext(prev);
1944 if (currentSub != null) {
1945 if (currentSub.getPrevious() == prev)
1946 currentSub.setPrevious(null);
1947 currentSub.setNext(prev);
1950 PipeControlPoint prev = list.get(i-1);
1951 PipeControlPoint next = list.get(i+1);
1952 if (next.isDualInline())
1953 next = next.getDualSub();
1956 current.setPrevious(next);
1957 current.setNext(prev);
1959 if (currentSub != null) {
1960 currentSub.setPrevious(next);
1961 currentSub.setNext(prev);
1965 //if (current.isTurn() && current.isFixed()) {
1966 if (current.asFixedAngle()) {
1967 current.setReversed(!current._getReversed());
1969 if (current.isInline() && current.isReverse()) {
1970 current.setReversed(!current._getReversed());
1977 public static void validate(PipeRun pipeRun) {
1978 if (pipeRun == null)
1980 Collection<PipeControlPoint> pcps = pipeRun.getControlPoints();
1982 //System.out.println("Validate " + pipeRun.getName());
1983 for (PipeControlPoint pcp : pcps) {
1984 if (pcp.getParentPoint() == null || pcp.getParentPoint().getPipeRun() != pipeRun)
1987 List<PipeControlPoint> runPcps = getControlPoints(pipeRun);
1988 if (runPcps.size() != count) {
1989 System.out.println("Run " + pipeRun.getName() + " contains unconnected control points, found " + runPcps.size() + " connected, " + pcps.size() + " total.");
1990 for (PipeControlPoint pcp : pcps) {
1991 if (!runPcps.contains(pcp)) {
1992 System.out.println("Unconnected " + pcp + " " + pcp.getPipelineComponent());
1996 for (PipeControlPoint pcp : pcps) {
1997 if (pcp.getPipeRun() == null) {
1998 System.out.println("PipeRun ref missing " + pcp + " " + pcp.getPipelineComponent());
2000 if (!pcp.isDirected() && pcp.getNext() == null && pcp.getPrevious() == null)
2001 System.out.println("Orphan undirected " + pcp + " " + pcp.getPipelineComponent());
2003 for (PipeControlPoint pcp : pcps) {
2004 if (pcp.getParentPoint() == null) {
2005 PipeControlPoint sub = null;
2006 if (pcp.isDualInline())
2007 sub = pcp.getDualSub();
2008 PipeControlPoint next = pcp.getNext();
2009 PipeControlPoint prev = pcp.getPrevious();
2011 if (!(next.getPrevious() == pcp || next.getPrevious() == sub)) {
2012 System.out.println("Inconsistency between " + pcp + " -> " +next );
2016 PipeControlPoint prevParent = null;
2017 if (prev.isDualSub()) {
2018 prevParent = prev.getParentPoint();
2019 } else if (prev.isDualInline()) {
2020 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
2022 if (!(prev.getNext() == pcp && (prevParent == null || prevParent.getNext() == pcp))) {
2023 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
2030 public static void splitVariableLengthComponent(PipelineComponent newComponent, InlineComponent splittingComponent, boolean assignPos) throws Exception{
2031 assert(!splittingComponent.getControlPoint().isFixedLength());
2032 assert(!(newComponent instanceof InlineComponent && !newComponent.getControlPoint().isFixedLength()));
2033 PipeControlPoint newCP = newComponent.getControlPoint();
2034 PipeControlPoint splittingCP = splittingComponent.getControlPoint();
2035 PipeControlPoint nextCP = splittingCP.getNext();
2036 PipeControlPoint prevCP = splittingCP.getPrevious();
2038 /* there are many different cases to insert new component when
2039 it splits existing VariableLengthinlineComponent.
2041 1. VariableLengthComponet is connected from both sides:
2042 - insert new component between VariableLength component and component connected to it
2043 - insert new VariableLengthComponent between inserted component and component selected in previous step
2045 2. VariableLengthComponent is connected from one side
2046 - Use previous case or:
2047 - Insert new component to empty end
2048 - Insert new VariableLength component to inserted components empty end
2050 3. VariableLength is not connected to any component.
2051 - Should not be possible, at least in current implementation.
2052 - Could be done using second case
2056 if (nextCP == null && prevCP == null) {
2057 // this should not be possible
2058 throw new RuntimeException("VariableLengthComponent " + splittingComponent + " is not connected to anything.");
2060 double newLength = newComponent.getControlPoint().getLength();
2063 Point3d next = new Point3d();
2064 Point3d prev = new Point3d();
2065 splittingCP.getInlineControlPointEnds(prev, next);
2067 Vector3d newPos = null;
2069 newPos = new Vector3d(prev);
2070 Vector3d dir = new Vector3d(next);
2074 newComponent.setWorldPosition(newPos);
2076 newPos = newComponent.getWorldPosition();
2081 Vector3d dir = new Vector3d(next);
2084 dir.scale(newLength * 0.5);
2085 Point3d vn = new Point3d(newPos);
2086 Point3d vp = new Point3d(newPos);
2089 double ln = vn.distance(next);
2090 double lp = vp.distance(prev);
2091 vp.interpolate(prev, 0.5);
2092 vn.interpolate(next, 0.5);
2095 if (nextCP == null) {
2096 newCP.insert(splittingCP, Direction.NEXT);
2097 insertStraight(newCP, Direction.NEXT, new Vector3d(vn), ln);
2098 splittingCP.setWorldPosition(new Vector3d(vp));
2099 // ControlPointTools.setWorldPosition(splittingCP, vp);
2100 // splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
2101 } else if (prevCP == null) {
2102 newCP.insert(splittingCP, Direction.PREVIOUS);
2103 insertStraight(newCP, Direction.PREVIOUS, new Vector3d(vp), lp);
2104 splittingCP.setWorldPosition(new Vector3d(vn));
2105 // splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, ln);
2107 newCP.insert(splittingCP, nextCP);
2108 insertStraight(newCP, nextCP, new Vector3d(vn), ln);
2109 splittingCP.setWorldPosition(new Vector3d(vp));
2110 // splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
2112 positionUpdate(newCP);
2116 public static void addSizeChange(boolean reversed, PipeRun pipeRun, PipeRun other, InlineComponent reducer, PipeControlPoint previous, PipeControlPoint next) {
2117 PipeControlPoint pcp = reducer.getControlPoint();
2118 PipeControlPoint ocp = pcp.getDualSub();
2120 String name = pipeRun.getUniqueName("Reducer");
2121 reducer.setName(name);
2122 pipeRun.addChild(reducer);
2123 other.addChild(ocp);
2124 reducer.setAlternativePipeRun(other);
2126 previous.setNext(pcp);
2127 pcp.setPrevious(previous);
2128 ocp.setPrevious(previous);
2132 next.setPrevious(ocp);
2135 String name = other.getUniqueName("Reducer");
2136 reducer.setName(name);
2137 other.addChild(reducer);
2138 pipeRun.addChild(ocp);
2139 reducer.setAlternativePipeRun(pipeRun);
2143 pcp.setPrevious(next);
2144 ocp.setPrevious(next);
2146 pcp.setNext(previous);
2147 ocp.setNext(previous);
2148 previous.setPrevious(ocp);