Salome HOME
Issue #2484: Fix for re-creation of a sketcher
[modules/shaper.git] / src / SketcherPrs / SketcherPrs_PositionMgr.cpp
1 // Copyright (C) 2014-2017  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or
18 // email : webmaster.salome@opencascade.com<mailto:webmaster.salome@opencascade.com>
19 //
20
21 #include "SketcherPrs_PositionMgr.h"
22 #include "SketcherPrs_Tools.h"
23
24 #include <GeomAPI_Edge.h>
25 #include <GeomAPI_Curve.h>
26 #include <GeomAPI_Vertex.h>
27 #include <GeomAPI_Dir.h>
28 #include <GeomAPI_Ax3.h>
29 #include <GeomAPI_Circ.h>
30 #include <GeomAPI_Lin2d.h>
31
32 #include <GeomDataAPI_Point2D.h>
33
34 #include <SketchPlugin_Line.h>
35 #include <SketchPlugin_Circle.h>
36 #include <SketchPlugin_Arc.h>
37 #include <SketchPlugin_ConstraintTangent.h>
38 #include <SketchPlugin_ConstraintPerpendicular.h>
39
40 #include <TopoDS_Vertex.hxx>
41 #include <Geom_Curve.hxx>
42 #include <GeomAPI_ProjectPointOnCurve.hxx>
43 #include <TColGeom_SequenceOfCurve.hxx>
44 #include <gp_Dir.hxx>
45
46 #include <array>
47
48 static SketcherPrs_PositionMgr* MyPosMgr = NULL;
49
50 #define PI 3.1415926535897932
51
52 // The class is implemented as a singlton
53 SketcherPrs_PositionMgr* SketcherPrs_PositionMgr::get()
54 {
55   if (MyPosMgr == NULL)
56     MyPosMgr = new SketcherPrs_PositionMgr();
57   return MyPosMgr;
58 }
59
60 SketcherPrs_PositionMgr::SketcherPrs_PositionMgr()
61 {
62 }
63
64 int SketcherPrs_PositionMgr::getPositionIndex(ObjectPtr theLine,
65                                               const SketcherPrs_SymbolPrs* thePrs)
66 {
67   if (myShapes.count(theLine) == 1) {
68     // Find the map and add new [Presentation - Index] pair
69     PositionsMap& aPosMap = myShapes[theLine];
70     if (aPosMap.count(thePrs) == 1) {
71       // return existing index
72       return aPosMap[thePrs];
73     } else {
74       // Add a new [Presentation - Index] pair
75       int aInd = int(aPosMap.size());
76       aPosMap[thePrs] = aInd;
77       return aInd;
78     }
79   } else {
80     // Create a new map with initial index
81     PositionsMap aPosMap;
82     aPosMap[thePrs] = 0;
83     myShapes[theLine] = aPosMap;
84     return 0;
85   }
86 }
87
88
89 bool SketcherPrs_PositionMgr::isPntConstraint(const std::string& theName)
90 {
91   return ((theName == SketchPlugin_ConstraintTangent::ID()) ||
92     (theName == SketchPlugin_ConstraintPerpendicular::ID()));
93 }
94
95 bool containsPoint(const FeaturePtr& theFeature, GeomPnt2dPtr thePnt2d, GeomPointPtr thePos)
96 {
97   if (theFeature->getKind() == SketchPlugin_Line::ID()) {
98     AttributePoint2DPtr aSPnt1 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
99       theFeature->data()->attribute(SketchPlugin_Line::START_ID()));
100     AttributePoint2DPtr aSPnt2 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
101       theFeature->data()->attribute(SketchPlugin_Line::END_ID()));
102
103     GeomPnt2dPtr aPnt1 = aSPnt1->pnt();
104     GeomPnt2dPtr aPnt2 = aSPnt2->pnt();
105
106     if (aPnt1->isEqual(thePnt2d) || aPnt2->isEqual(thePnt2d))
107       return true;
108   } else if ((theFeature->getKind() == SketchPlugin_Circle::ID()) ||
109              (theFeature->getKind() == SketchPlugin_Arc::ID())) {
110     GeomCurvePtr aCurve;
111     ObjectPtr aResObj;
112     std::list<ResultPtr> aResults = theFeature->results();
113     std::list<ResultPtr>::const_iterator aIt;
114     for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
115       GeomShapePtr aShp = SketcherPrs_Tools::getShape((*aIt));
116       if (aShp->isEdge()) {
117         aResObj = (*aIt);
118         aCurve = std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(aShp));
119         break;
120       }
121     }
122     if (aCurve.get()) {
123       double aStart = aCurve->startParam();
124       double aEnd = aCurve->endParam();
125       GeomCirclePtr  aCircle = GeomCirclePtr(new GeomAPI_Circ(aCurve));
126       double aParam;
127       if (aCircle->parameter(thePos, 1.e-4, aParam) && (aParam >= aStart) && (aParam <= aEnd))
128         return true;
129     }
130   }
131   return false;
132 }
133
134 const std::array<int, 2>& SketcherPrs_PositionMgr::getPositionIndex(GeomPointPtr thePos,
135                                               const SketcherPrs_SymbolPrs* thePrs)
136 {
137   if (myPntShapes.count(thePrs->feature()) == 0) {
138     // Renumerate positions around the specified constraint point for all constraints
139     GeomAx3Ptr aAx3 = thePrs->plane();
140     ModelAPI_CompositeFeature* aOwner = thePrs->sketcher();
141     GeomPnt2dPtr aPnt2d = thePos->to2D(aAx3->origin(), aAx3->dirX(), aAx3->dirY());
142
143     int aNbSubs = aOwner->numberOfSubs();
144     int aId = 0;
145     std::list<const ModelAPI_Feature*> aFeaList;
146     for (int i = 0; i < aNbSubs; i++) {
147       FeaturePtr aFeature = aOwner->subFeature(i);
148
149       bool aUseFeature = ((myPntShapes.count(aFeature.get()) == 1) ||
150                          (isPntConstraint(aFeature->getKind())));
151       if (aUseFeature) {
152         DataPtr aData = aFeature->data();
153         AttributeRefAttrPtr aObjRef = aData->refattr(SketchPlugin_Constraint::ENTITY_A());
154         FeaturePtr aObj = ModelAPI_Feature::feature(aObjRef->object());
155         bool aContains = false;
156         if (containsPoint(aObj, aPnt2d, thePos)) {
157           aContains = true;
158         } else {
159           aObjRef = aData->refattr(SketchPlugin_Constraint::ENTITY_B());
160           aObj = ModelAPI_Feature::feature(aObjRef->object());
161           if (containsPoint(aObj, aPnt2d, thePos)) {
162             aContains = true;
163           }
164         }
165         if (aContains) {
166           myPntShapes[aFeature.get()][0] = aId;
167           aId++;
168           aFeaList.push_back(aFeature.get());
169         }
170       }
171     }
172     int aSize = (int) aFeaList.size();
173     std::list<const ModelAPI_Feature*>::const_iterator aIt;
174     for (aIt = aFeaList.cbegin(); aIt != aFeaList.cend(); aIt++) {
175       myPntShapes[*aIt][1] = aSize;
176     }
177   }
178   return myPntShapes[thePrs->feature()];
179 }
180
181 //*****************************************************************
182 gp_Vec getVector(ObjectPtr theShape, GeomDirPtr theDir, gp_Pnt theP)
183 {
184   gp_Vec aVec;
185   std::shared_ptr<GeomAPI_Shape> aShape = SketcherPrs_Tools::getShape(theShape);
186   if (aShape->isEdge()) {
187     std::shared_ptr<GeomAPI_Curve> aCurve =
188       std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(aShape));
189
190     if (aCurve->isCircle()) {
191       Handle(Geom_Curve) aCurv = aCurve->impl<Handle_Geom_Curve>();
192       GeomAPI_ProjectPointOnCurve anExtr(theP, aCurv);
193       double aParam = anExtr.LowerDistanceParameter();
194       gp_Pnt aP;
195       aCurv->D1(aParam, aP, aVec);
196       // 2458: check correct orientation of the vector
197       if (aVec.SquareMagnitude() > Precision::Confusion()) {
198         std::shared_ptr<GeomAPI_Edge> aCircEdge(new GeomAPI_Edge(aShape));
199         double aFirstParam, aLastParam;
200         aCircEdge->getRange(aFirstParam, aLastParam);
201         // if parameter is near the LastParam, make the vector go inside (reverse)
202         double aDelta = aLastParam - aParam;
203         while (aDelta < -Precision::Confusion())
204           aDelta += 2. * M_PI;
205         while (aDelta > 2. * M_PI - Precision::Confusion())
206           aDelta -= 2. * M_PI;
207         if (fabs(aDelta) < Precision::Confusion())
208           aVec.Reverse();
209       }
210     } else {
211       GeomPointPtr aPnt1 = aCurve->getPoint(aCurve->endParam());
212       GeomPointPtr aPnt2 = aCurve->getPoint(aCurve->startParam());
213
214       gp_Pnt aPn2 = aPnt2->impl<gp_Pnt>();
215       if (aPn2.IsEqual(theP, Precision::Confusion()))
216         aVec = gp_Vec(aPn2, aPnt1->impl<gp_Pnt>());
217       else
218         aVec = gp_Vec(aPnt1->impl<gp_Pnt>(), aPn2);
219     }
220   } else {
221     aVec = gp_Vec(theDir->impl<gp_Dir>());
222   }
223   return aVec;
224 }
225
226 //*****************************************************************
227 gp_Pnt SketcherPrs_PositionMgr::getPosition(ObjectPtr theShape,
228                                             const SketcherPrs_SymbolPrs* thePrs,
229                                             double theStep, GeomPointPtr thePnt)
230 {
231   std::shared_ptr<GeomAPI_Shape> aShape = SketcherPrs_Tools::getShape(theShape);
232   gp_Pnt aP; // Central point
233
234   if (thePnt.get()) {
235     return getPointPosition(theShape, thePrs, theStep, thePnt);
236   } else {
237     if (aShape->isEdge()) {
238       std::shared_ptr<GeomAPI_Curve> aCurve =
239         std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(aShape));
240       // this is a circle or arc
241       double aMidParam = (aCurve->startParam() + aCurve->endParam()) / 2.;
242       std::shared_ptr<GeomAPI_Pnt> aPnt = aCurve->getPoint(aMidParam);
243       aP = aPnt->impl<gp_Pnt>();
244     } else {
245       // This is a point
246       std::shared_ptr<GeomAPI_Vertex> aVertex =
247         std::shared_ptr<GeomAPI_Vertex>(new GeomAPI_Vertex(aShape));
248       std::shared_ptr<GeomAPI_Pnt> aPnt = aVertex->point();
249       aP = aPnt->impl<gp_Pnt>();
250     }
251   }
252   // main vector
253   gp_Vec aVec1 = getVector(theShape, thePrs->plane()->dirX(), aP);
254
255   // Compute shifting vector for a one symbol
256   gp_Vec aShift = aVec1.Crossed(thePrs->plane()->normal()->impl<gp_Dir>());
257   aShift.Normalize();
258   aShift.Multiply(theStep * 0.8);
259
260   // Shift the position coordinate according to position index
261   int aPos = getPositionIndex(theShape, thePrs);
262   int aM = 1;
263   if ((aPos % 2) == 0) {
264     // Even position
265     aP.Translate(aShift);
266     if (aPos > 0) {
267       if (aPos % 4 == 0)
268         aM = aPos / 4;
269       else
270         aM = -(aPos + 2) / 4;
271     }
272   } else {
273     // Odd position
274     aP.Translate(-aShift);
275     if (aPos > 1) {
276       if ((aPos - 1) % 4 == 0)
277         aM = (aPos - 1) / 4;
278       else
279         aM = -(aPos + 1) / 4;
280     }
281   }
282   if (aPos > 1) {
283     // Normalize vector along the line
284     aVec1.Normalize();
285     aVec1.Multiply(theStep);
286     aP.Translate(aVec1.Multiplied(aM));
287   }
288   return aP;
289 }
290
291
292 //*****************************************************************
293 //! Returns curves connected to the given point
294 std::list<ObjectPtr> getCurves(const GeomPointPtr& thePnt, const SketcherPrs_SymbolPrs* thePrs)
295 {
296   std::list<ObjectPtr> aList;
297   GeomAx3Ptr aAx3 = thePrs->plane();
298   ModelAPI_CompositeFeature* aOwner = thePrs->sketcher();
299   GeomPnt2dPtr aPnt2d = thePnt->to2D(aAx3->origin(), aAx3->dirX(), aAx3->dirY());
300
301   int aNbSubs = aOwner->numberOfSubs();
302   for (int i = 0; i < aNbSubs; i++) {
303     FeaturePtr aFeature = aOwner->subFeature(i);
304     if (!aFeature->firstResult().get() || aFeature->firstResult()->isDisabled())
305       continue;  // There is no result
306
307     if (aFeature->getKind() == SketchPlugin_Line::ID()) {
308       AttributePoint2DPtr aSPnt1 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
309         aFeature->data()->attribute(SketchPlugin_Line::START_ID()));
310       AttributePoint2DPtr aSPnt2 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
311         aFeature->data()->attribute(SketchPlugin_Line::END_ID()));
312
313       GeomPnt2dPtr aPnt1 = aSPnt1->pnt();
314       GeomPnt2dPtr aPnt2 = aSPnt2->pnt();
315
316       if (aPnt1->distance(aPnt2d) <= Precision::Confusion() ||
317           aPnt2->distance(aPnt2d) <= Precision::Confusion()) {
318         // a point corresponds to one of the line end
319         GeomShapePtr aShp = SketcherPrs_Tools::getShape(aFeature->firstResult());
320         GeomCurvePtr aCurv = std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(aShp));
321         aList.push_back(aFeature->firstResult());
322       } else {
323         // Check that a point belongs to the curve
324         GeomAPI_Lin2d aLin2d(aPnt1, aPnt2);
325         double aDist = aLin2d.distance(aPnt2d);
326         if (aDist <= Precision::Confusion())
327           aList.push_back(aFeature->firstResult());
328       }
329     } else if ((aFeature->getKind() == SketchPlugin_Circle::ID()) ||
330               (aFeature->getKind() == SketchPlugin_Arc::ID())) {
331       GeomCurvePtr aCurve;
332       ObjectPtr aResObj;
333       std::list<ResultPtr> aResults = aFeature->results();
334       std::list<ResultPtr>::const_iterator aIt;
335       for (aIt = aResults.cbegin(); aIt != aResults.cend(); aIt++) {
336         GeomShapePtr aShp = SketcherPrs_Tools::getShape((*aIt));
337         if (aShp->isEdge()) {
338           aResObj = (*aIt);
339           aCurve = std::shared_ptr<GeomAPI_Curve>(new GeomAPI_Curve(aShp));
340           break;
341         }
342       }
343       if (aCurve.get()) {
344         double aStart = aCurve->startParam();
345         double aEnd = aCurve->endParam();
346         GeomCirclePtr  aCircle = GeomCirclePtr(new GeomAPI_Circ(aCurve));
347         GeomPointPtr aProjPnt = aCircle->project(thePnt);
348         if (aProjPnt && thePnt->distance(aProjPnt) <= Precision::Confusion())
349           aList.push_back(aResObj);
350       }
351     }
352   }
353   return aList;
354 }
355
356 //*****************************************************************
357 gp_Pnt SketcherPrs_PositionMgr::getPointPosition(
358   ObjectPtr theLine, const SketcherPrs_SymbolPrs* thePrs,
359   double theStep, GeomPointPtr thePnt)
360 {
361   gp_Pnt aP = thePnt->impl<gp_Pnt>();
362   GeomDirPtr aNormal = thePrs->plane()->normal();
363   gp_Dir aNormDir = aNormal->impl<gp_Dir>();
364
365   std::list<ObjectPtr> aCurves = getCurves(thePnt, thePrs);
366   std::list<ObjectPtr>::const_iterator aItCurv;
367   std::list<gp_Vec> aVectorsList;
368   // Calculate all vectors
369   for (aItCurv = aCurves.cbegin(); aItCurv != aCurves.cend(); aItCurv++) {
370     aVectorsList.push_back(getVector((*aItCurv), thePrs->plane()->dirX(), aP));
371   }
372
373   // Position of the symbol
374   const std::array<int, 2>& aPos = getPositionIndex(thePnt, thePrs);
375
376   // Angle size of a symbol
377   //double aAngleStep = PI * 50./180.;
378   double aAngleStep = PI/4.;
379
380   std::list<gp_Vec>::const_iterator aItVec;
381   std::list<double> aAngles;
382   std::list<gp_Vec> aVectors;
383   // Select closest vectors and calculate angles between base vector and closest vector
384   for (aItVec = aVectorsList.cbegin(); aItVec != aVectorsList.cend(); aItVec++) {
385     std::list<gp_Vec>::const_iterator aIt;
386     double aMinAng = 0;
387     gp_Vec aVec = *aItVec;
388     for (aIt = aVectorsList.cbegin(); aIt != aVectorsList.cend(); aIt++) {
389       double aAng = aVec.AngleWithRef(*aIt, aNormDir);
390       if (aAng != 0) {
391         if (aAng < 0)
392           aAng = 2 * PI + aAng;
393
394         if (aMinAng == 0)
395           aMinAng = aAng;
396         else if (aAng < aMinAng) {
397           aMinAng = aAng;
398         }
399       }
400     }
401     if (aMinAng >= aAngleStep) {
402       aVectors.push_back(aVec);
403       aAngles.push_back(aMinAng);
404     }
405   }
406
407   gp_Ax1 aRotAx(aP, aNormDir);
408   gp_Vec aVecPos;
409   // If number of angle less then number of symbols then each symbol can be placed
410   // directly inside of the angle
411   if (aAngles.size() >= aPos[1] && !aVectors.empty()) {
412     int aId = aPos[0];
413     aVecPos = *(std::next(aVectors.begin(), aId));
414
415     gp_Vec aShift = aVecPos.Rotated(aRotAx, aAngleStep);
416     aShift.Normalize();
417     aShift.Multiply(theStep * 1.5);
418     return aP.Translated(aShift);
419   }
420
421   // A case when there are a lot of symbols
422   int aPosCount = 0;
423   double aAng;
424   std::list<double>::const_iterator aItAng;
425
426   double aAngPos;
427   bool aHasPlace = false;
428   //int aIntId = 0; // a position inside a one sector
429   while (aPosCount < aPos[1]) {
430     for (aItAng = aAngles.cbegin(), aItVec = aVectors.cbegin();
431          aItAng != aAngles.cend(); ++aItAng, ++aItVec) {
432       aAng = (*aItAng);
433       int Nb = int(aAng / aAngleStep);
434       aPosCount += Nb;
435
436       if ((!aHasPlace) && (aPosCount >= (aPos[0] + 1))) {
437         aHasPlace = true;
438         aAngPos = (*aItAng);
439         aVecPos = (*aItVec);
440         //aIntId = aPos[0] - (aPosCount - Nb);
441       }
442     }
443     if (aPosCount < aPos[1]) {
444       aAngleStep -= 0.1;
445       aHasPlace = false;
446       aPosCount = 0;
447     }
448     if (aAngleStep <= 0)
449       break;
450   }
451
452   if (aHasPlace) {
453     // rotate base vector on a necessary angle
454     gp_Vec aShift = aVecPos.Rotated(aRotAx, aAngleStep + aAngleStep * aPos[0]);
455     aShift.Normalize();
456     aShift.Multiply(theStep * 1.5);
457     return aP.Translated(aShift);
458   }
459   return aP;
460 }
461
462 //*****************************************************************
463 void SketcherPrs_PositionMgr::deleteConstraint(const SketcherPrs_SymbolPrs* thePrs)
464 {
465   std::map<ObjectPtr, PositionsMap>::iterator aIt;
466   std::list<ObjectPtr> aToDel;
467   // Clear map for deleted presentation
468   for (aIt = myShapes.begin(); aIt != myShapes.end(); ++aIt) {
469     PositionsMap& aPosMap = aIt->second;
470     if (aPosMap.count(thePrs) > 0) {
471       // Erase index
472       aPosMap.erase(aPosMap.find(thePrs));
473       if (aPosMap.size() == 0)
474         // Delete the map
475         aToDel.push_back(aIt->first);
476       else {
477         // Reindex objects positions in order to avoid spaces
478         PositionsMap::iterator aIt;
479         int i = 0;
480         for (aIt = aPosMap.begin(); aIt != aPosMap.end(); aIt++, i++)
481           aIt->second = i;
482       }
483     }
484   }
485   std::list<ObjectPtr>::const_iterator aListIt;
486   for (aListIt = aToDel.cbegin(); aListIt != aToDel.cend(); ++aListIt) {
487     myShapes.erase(*aListIt);
488   }
489 }