Salome HOME
9a163403fdd93b9249d2deae0ae5839fddb2cce4
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Fillet.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
2
3 // File:    SketchPlugin_Fillet.cpp
4 // Created: 19 Mar 2015
5 // Author:  Artem ZHIDKOV
6
7 #include "SketchPlugin_Fillet.h"
8
9 #include "SketchPlugin_Arc.h"
10 #include "SketchPlugin_Line.h"
11 #include "SketchPlugin_Point.h"
12 #include "SketchPlugin_Sketch.h"
13 #include "SketchPlugin_ConstraintEqual.h"
14 #include "SketchPlugin_ConstraintCoincidence.h"
15 #include "SketchPlugin_ConstraintLength.h"
16 #include "SketchPlugin_ConstraintTangent.h"
17 #include "SketchPlugin_ConstraintRadius.h"
18 #include "SketchPlugin_Tools.h"
19
20 #include <ModelAPI_AttributeRefAttr.h>
21 #include <ModelAPI_Data.h>
22 #include <ModelAPI_Events.h>
23 #include <ModelAPI_Session.h>
24 #include <ModelAPI_Tools.h>
25 #include <ModelAPI_Validator.h>
26
27 #include <GeomAlgoAPI_EdgeBuilder.h>
28
29 #include <GeomAPI_Circ2d.h>
30 #include <GeomAPI_Dir2d.h>
31 #include <GeomAPI_Lin2d.h>
32 #include <GeomAPI_Pnt2d.h>
33 #include <GeomAPI_XY.h>
34
35 #include <GeomDataAPI_Point2D.h>
36
37 #include <Events_Loop.h>
38
39 #include <math.h>
40
41 const double tolerance = 1.e-7;
42 const double paramTolerance = 1.e-4;
43
44 /// \brief Attract specified point on theNewArc to the attribute of theFeature
45 static void recalculateAttributes(FeaturePtr theNewArc, const std::string& theNewArcAttribute,
46   FeaturePtr theFeature, const std::string& theFeatureAttribute);
47
48 /// \brief Calculates center of fillet arc and coordinates of tangency points
49 static void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
50                                   double theRadius, bool theNotInversed[2],
51                                   std::shared_ptr<GeomAPI_XY>& theCenter,
52                                   std::shared_ptr<GeomAPI_XY>& theTangentA,
53                                   std::shared_ptr<GeomAPI_XY>& theTangentB);
54
55 /// Get point on 1/3 length of edge from fillet point
56 static void getPointOnEdge(const FeaturePtr theFeature,
57                            const std::shared_ptr<GeomAPI_Pnt2d> theFilletPoint,
58                            std::shared_ptr<GeomAPI_Pnt2d>& thePoint);
59
60 /// Get distance from point to feature
61 static double getProjectionDistance(const FeaturePtr theFeature,
62                              const std::shared_ptr<GeomAPI_Pnt2d> thePoint);
63
64 /// Get coincide edges for fillet
65 static std::set<FeaturePtr> getCoincides(const FeaturePtr& theConstraintCoincidence);
66
67 static std::set<FeaturePtr> findFeaturesToRemove(const FeaturePtr theFeature,
68                                                  const AttributePtr theAttribute);
69
70 SketchPlugin_Fillet::SketchPlugin_Fillet()
71 : myFilletCreated(false)
72 {
73 }
74
75 void SketchPlugin_Fillet::initAttributes()
76 {
77   data()->addAttribute(FILLET_POINT_ID(), ModelAPI_AttributeRefAttr::typeId());
78 }
79
80 void SketchPlugin_Fillet::execute()
81 {
82   // Wait all constraints being created, then send update events
83   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
84   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
85   if (isUpdateFlushed)
86     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
87
88   // Create arc feature.
89   FeaturePtr aFilletArc = sketch()->addFeature(SketchPlugin_Arc::ID());
90
91   // Set arc attributes.
92   bool aWasBlocked = aFilletArc->data()->blockSendAttributeUpdated(true);
93   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
94       aFilletArc->attribute(SketchPlugin_Arc::CENTER_ID()))->setValue(myCenterXY->x(),
95                                                                       myCenterXY->y());
96   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint =
97       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
98           aFilletArc->attribute(SketchPlugin_Arc::START_ID()));
99   std::shared_ptr<GeomDataAPI_Point2D> aEndPoint =
100       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
101           aFilletArc->attribute(SketchPlugin_Arc::END_ID()));
102   if(aStartPoint->isInitialized() && aEndPoint->isInitialized()
103       && (aStartPoint->pnt()->xy()->distance(myTangentXY1) > tolerance
104       || aEndPoint->pnt()->xy()->distance(myTangentXY2) > tolerance)) {
105     std::dynamic_pointer_cast<SketchPlugin_Arc>(aFilletArc)->setReversed(false);
106   }
107   aStartPoint->setValue(myTangentXY1->x(), myTangentXY1->y());
108   aEndPoint->setValue(myTangentXY2->x(), myTangentXY2->y());
109   aFilletArc->data()->blockSendAttributeUpdated(aWasBlocked);
110   aFilletArc->execute();
111
112   // Delete features with refs to points of edges.
113   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint1;
114   int aFeatInd1 = myIsReversed ? 1 : 0;
115   int anAttrInd1 = (myIsReversed ? 2 : 0) + (myIsNotInversed[aFeatInd1] ? 0 : 1);
116   aStartPoint1 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
117       myBaseFeatures[aFeatInd1]->attribute(myFeatAttributes[anAttrInd1]));
118   std::set<FeaturePtr> aFeaturesToBeRemoved1 =
119     findFeaturesToRemove(myBaseFeatures[aFeatInd1], aStartPoint1);
120
121   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint2;
122   int aFeatInd2 = myIsReversed ? 0 : 1;
123   int anAttrInd2 = (myIsReversed ? 0 : 2) + (myIsNotInversed[aFeatInd2] ? 0 : 1);
124   aStartPoint2 = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
125       myBaseFeatures[aFeatInd2]->attribute(myFeatAttributes[anAttrInd2]));
126   std::set<FeaturePtr> aFeaturesToBeRemoved2 =
127     findFeaturesToRemove(myBaseFeatures[aFeatInd2], aStartPoint2);
128
129   aFeaturesToBeRemoved1.insert(aFeaturesToBeRemoved2.begin(), aFeaturesToBeRemoved2.end());
130   ModelAPI_Tools::removeFeaturesAndReferences(aFeaturesToBeRemoved1);
131
132   // Update fillet edges.
133   recalculateAttributes(aFilletArc, SketchPlugin_Arc::START_ID(),
134                         myBaseFeatures[aFeatInd1], myFeatAttributes[anAttrInd1]);
135   recalculateAttributes(aFilletArc, SketchPlugin_Arc::END_ID(),
136                         myBaseFeatures[aFeatInd2], myFeatAttributes[anAttrInd2]);
137
138   // Create coincidence features.
139   FeaturePtr aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
140   AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
141       aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
142   aRefAttr->setAttr(aFilletArc->attribute(SketchPlugin_Arc::START_ID()));
143   aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
144       aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
145   aRefAttr->setAttr(myBaseFeatures[aFeatInd1]->attribute(myFeatAttributes[anAttrInd1]));
146   aConstraint->execute();
147   ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
148   aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
149   aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
150       aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
151   aRefAttr->setAttr(aFilletArc->attribute(SketchPlugin_Arc::END_ID()));
152   aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
153       aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
154   aRefAttr->setAttr(myBaseFeatures[aFeatInd2]->attribute(myFeatAttributes[anAttrInd2]));
155   aConstraint->execute();
156   ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
157
158   // Create tangent features.
159   for (int i = 0; i < 2; i++) {
160     aConstraint = sketch()->addFeature(SketchPlugin_ConstraintTangent::ID());
161     aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
162         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
163     aRefAttr->setObject(aFilletArc->lastResult());
164     aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
165         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
166     bool isArc = myBaseFeatures[i]->getKind() == SketchPlugin_Arc::ID();
167     aRefAttr->setObject(isArc ? myBaseFeatures[i]->lastResult() :
168                                 myBaseFeatures[i]->firstResult());
169     aConstraint->execute();
170     ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
171   }
172
173   // Send events to update the sub-features by the solver.
174   if(isUpdateFlushed) {
175     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
176   }
177
178   myFilletCreated = true;
179 }
180
181 AISObjectPtr SketchPlugin_Fillet::getAISObject(AISObjectPtr thePrevious)
182 {
183   if(myFilletCreated) {
184     return AISObjectPtr();
185   }
186
187   SketchPlugin_Sketch* aSketch = sketch();
188   if(!aSketch) {
189     return AISObjectPtr();
190   }
191
192   // Get fillet point.
193   AttributeRefAttrPtr aPointRefAttr = refattr(FILLET_POINT_ID());
194   if (!aPointRefAttr->isInitialized() || aPointRefAttr->isObject()) {
195     return AISObjectPtr();
196   }
197   std::shared_ptr<GeomDataAPI_Point2D> aFilletPoint2D =
198     std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aPointRefAttr->attr());
199   if (!aFilletPoint2D.get()) {
200     return AISObjectPtr();
201   }
202
203   // Obtain constraint coincidence for the fillet point.
204   FeaturePtr aConstraintCoincidence;
205   const std::set<AttributePtr>& aRefsList = aFilletPoint2D->owner()->data()->refsToMe();
206   for(std::set<AttributePtr>::const_iterator anIt = aRefsList.cbegin();
207       anIt != aRefsList.cend();
208       ++anIt) {
209     std::shared_ptr<ModelAPI_Attribute> anAttr = (*anIt);
210     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
211     if(aFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
212       AttributeRefAttrPtr anAttrRefA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
213         aFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_A()));
214       AttributeRefAttrPtr anAttrRefB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
215         aFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_B()));
216       if(anAttrRefA.get() && !anAttrRefA->isObject()) {
217         AttributePtr anAttrA = anAttrRefA->attr();
218         if(aFilletPoint2D == anAttrA) {
219           aConstraintCoincidence = aFeature;
220           break;
221         }
222       }
223       if(anAttrRefB.get() && !anAttrRefB->isObject()) {
224         AttributePtr anAttrB = anAttrRefB->attr();
225         if(aFilletPoint2D == anAttrB) {
226           aConstraintCoincidence = aFeature;
227           break;
228         }
229       }
230     }
231   }
232
233   if(!aConstraintCoincidence.get()) {
234     setError("Error: No coincident edges at selected point.");
235     return AISObjectPtr();
236   }
237
238   // Get coincide edges.
239   std::set<FeaturePtr> anEdgeFeatures = getCoincides(aConstraintCoincidence);
240   if(anEdgeFeatures.size() != 2) {
241     setError("Error: Selected point does not have two suitable edges for fillet.");
242     return AISObjectPtr();
243   }
244
245   FeaturePtr anEdgeFeature1, anEdgeFeature2;
246   std::set<FeaturePtr>::iterator aLinesIt = anEdgeFeatures.begin();
247   anEdgeFeature1 = *aLinesIt++;
248   anEdgeFeature2 = *aLinesIt;
249
250   // Getting points located at 1/3 of edge length from fillet point.
251   std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
252   std::shared_ptr<GeomAPI_Pnt2d> aPnt1, aPnt2;
253   getPointOnEdge(anEdgeFeature1, aFilletPnt2d, aPnt1);
254   getPointOnEdge(anEdgeFeature2, aFilletPnt2d, aPnt2);
255
256   /// Getting distances.
257   double aDistance1 = getProjectionDistance(anEdgeFeature2, aPnt1);
258   double aDistance2 = getProjectionDistance(anEdgeFeature1, aPnt2);
259
260   // Calculate radius value for fillet.
261   double aRadius = aDistance1 < aDistance2 ? aDistance1 / 2.0 : aDistance2 / 2.0;
262
263   // Calculate arc attributes.
264   static const int aNbFeatures = 2;
265   myBaseFeatures[0] = anEdgeFeature1;
266   myBaseFeatures[1] = anEdgeFeature2;
267   // First pair of points relate to first feature, second pair -  to second.
268   std::shared_ptr<GeomAPI_Pnt2d> aStartEndPnt[aNbFeatures * 2];
269   for (int i = 0; i < aNbFeatures; i++) {
270     std::string aStartAttr, aEndAttr;
271     if (myBaseFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
272       aStartAttr = SketchPlugin_Line::START_ID();
273       aEndAttr = SketchPlugin_Line::END_ID();
274     } else if (myBaseFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
275       aStartAttr = SketchPlugin_Arc::START_ID();
276       aEndAttr = SketchPlugin_Arc::END_ID();
277     } else { // Wrong argument.
278       setError("Error: One of the points has wrong coincide feature");
279       return AISObjectPtr();
280     }
281     myFeatAttributes[2*i] = aStartAttr;
282     aStartEndPnt[2*i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
283       myBaseFeatures[i]->attribute(aStartAttr))->pnt();
284     myFeatAttributes[2*i+1] = aEndAttr;
285     aStartEndPnt[2*i+1] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
286       myBaseFeatures[i]->attribute(aEndAttr))->pnt();
287   }
288   for (int aFeatInd = 0; aFeatInd < aNbFeatures; aFeatInd++) {
289     for (int j = 0; j < 2; j++) // loop on start-end of each feature
290       if (aStartEndPnt[aFeatInd * aNbFeatures + j]->distance(aFilletPnt2d) < 1.e-10) {
291         myIsNotInversed[aFeatInd] = (j==0);
292         break;
293       }
294   }
295
296   calculateFilletCenter(anEdgeFeature1, anEdgeFeature2, aRadius,
297       myIsNotInversed, myCenterXY, myTangentXY1, myTangentXY2);
298
299   // Tangent directions of the features in coincident point.
300   std::shared_ptr<GeomAPI_Dir2d> aTangentDir[aNbFeatures];
301   for (int i = 0; i < aNbFeatures; i++) {
302     std::shared_ptr<GeomAPI_XY> aDir;
303     if (myBaseFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
304       aDir = aStartEndPnt[2*i+1]->xy()->decreased(aStartEndPnt[2*i]->xy());
305       if (!myIsNotInversed[i])
306         aDir = aDir->multiplied(-1.0);
307     } else if (myBaseFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
308       std::shared_ptr<GeomAPI_Pnt2d> aCenterPoint =
309         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
310         myBaseFeatures[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
311       aDir = myIsNotInversed[i] ? aStartEndPnt[2*i]->xy() : aStartEndPnt[2*i+1]->xy();
312       aDir = aDir->decreased(aCenterPoint->xy());
313
314       double x = aDir->x();
315       double y = aDir->y();
316       aDir->setX(-y);
317       aDir->setY(x);
318       if (myIsNotInversed[i] ==
319           std::dynamic_pointer_cast<SketchPlugin_Arc>(myBaseFeatures[i])->isReversed())
320         aDir = aDir->multiplied(-1.0);
321     }
322     aTangentDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aDir));
323   }
324
325   // By default, the start point of fillet arc is connected to FeatureA,
326   // and the end point - to FeatureB. But when the angle between TangentDirA and
327   // TangentDirB greater 180 degree, the sequaence of features need to be reversed.
328   double cosBA = aTangentDir[0]->cross(aTangentDir[1]); // cos(B-A),
329   // where A and B - angles between corresponding tanget direction and the X axis
330   myIsReversed = cosBA > 0.0;
331
332   if(myIsReversed) {
333     std::shared_ptr<GeomAPI_XY> aTmp = myTangentXY1;
334     myTangentXY1 = myTangentXY2;
335     myTangentXY2 = aTmp;
336   }
337
338   // Create arc for presentation.
339   std::shared_ptr<GeomAPI_Pnt> aCenterPnt(aSketch->to3D(myCenterXY->x(), myCenterXY->y()));
340   std::shared_ptr<GeomAPI_Pnt> aTangentPnt1(aSketch->to3D(myTangentXY1->x(),
341                                                           myTangentXY1->y()));
342   std::shared_ptr<GeomAPI_Pnt> aTangentPnt2(aSketch->to3D(myTangentXY2->x(),
343                                                           myTangentXY2->y()));
344   std::shared_ptr<GeomDataAPI_Dir> aNDir = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
345     aSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
346   std::shared_ptr<GeomAPI_Shape> anArcShape =
347       GeomAlgoAPI_EdgeBuilder::lineCircleArc(aCenterPnt, aTangentPnt1, aTangentPnt2, aNDir->dir());
348
349   AISObjectPtr anAISObject = thePrevious;
350   if(!anAISObject.get()) {
351     anAISObject = AISObjectPtr(new GeomAPI_AISObject);
352   }
353   anAISObject->createShape(anArcShape);
354   return anAISObject;
355 }
356
357 // =========   Auxiliary functions   =================
358 void recalculateAttributes(FeaturePtr theNewArc,  const std::string& theNewArcAttribute,
359                            FeaturePtr theFeature, const std::string& theFeatureAttribute)
360 {
361   std::shared_ptr<GeomAPI_Pnt2d> anArcPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
362       theNewArc->attribute(theNewArcAttribute))->pnt();
363   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
364       theFeature->attribute(theFeatureAttribute))->setValue(anArcPoint->x(), anArcPoint->y());
365 }
366
367 /// \brief Find intersections of lines shifted along normal direction
368 void possibleFilletCenterLineLine(
369     std::shared_ptr<GeomAPI_XY> thePointA, std::shared_ptr<GeomAPI_Dir2d> theDirA,
370     std::shared_ptr<GeomAPI_XY> thePointB, std::shared_ptr<GeomAPI_Dir2d> theDirB,
371     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
372 {
373   std::shared_ptr<GeomAPI_Dir2d> aDirAT(new GeomAPI_Dir2d(-theDirA->y(), theDirA->x()));
374   std::shared_ptr<GeomAPI_Dir2d> aDirBT(new GeomAPI_Dir2d(-theDirB->y(), theDirB->x()));
375   std::shared_ptr<GeomAPI_XY> aPntA, aPntB;
376   double aDet = theDirA->cross(theDirB);
377   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
378     aPntA = thePointA->added(aDirAT->xy()->multiplied(aStepA * theRadius));
379     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
380       aPntB = thePointB->added(aDirBT->xy()->multiplied(aStepB * theRadius));
381       double aVX = aDirAT->xy()->dot(aPntA);
382       double aVY = aDirBT->xy()->dot(aPntB);
383       std::shared_ptr<GeomAPI_XY> aPoint(new GeomAPI_XY(
384           (theDirB->x() * aVX - theDirA->x() * aVY) / aDet,
385           (theDirB->y() * aVX - theDirA->y() * aVY) / aDet));
386       theCenters.push_back(aPoint);
387     }
388   }
389 }
390
391 /// \brief Find intersections of line shifted along normal direction in both sides
392 ///        and a circle with extended radius
393 void possibleFilletCenterLineArc(
394     std::shared_ptr<GeomAPI_XY> theStartLine, std::shared_ptr<GeomAPI_Dir2d> theDirLine,
395     std::shared_ptr<GeomAPI_XY> theCenterArc, double theRadiusArc,
396     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
397 {
398   std::shared_ptr<GeomAPI_Dir2d> aDirT(new GeomAPI_Dir2d(-theDirLine->y(), theDirLine->x()));
399   std::shared_ptr<GeomAPI_XY> aPnt;
400   double aDirNorm2 = theDirLine->dot(theDirLine);
401   double aRad = 0.0;
402   double aDirX = theDirLine->x();
403   double aDirX2 = theDirLine->x() * theDirLine->x();
404   double aDirY2 = theDirLine->y() * theDirLine->y();
405   double aDirXY = theDirLine->x() * theDirLine->y();
406   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
407     aPnt = theStartLine->added(aDirT->xy()->multiplied(aStepA * theRadius));
408     double aCoeff = aDirT->xy()->dot(aPnt->decreased(theCenterArc));
409     double aCoeff2 = aCoeff * aCoeff;
410     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
411       aRad = theRadiusArc + aStepB * theRadius;
412       double aD = aRad * aRad * aDirNorm2 - aCoeff2;
413       if (aD < 0.0)
414         continue;
415       double aDs = sqrt(aD);
416       double x1 = theCenterArc->x() + (aCoeff * aDirT->x() - aDirT->y() * aDs) / aDirNorm2;
417       double x2 = theCenterArc->x() + (aCoeff * aDirT->x() + aDirT->y() * aDs) / aDirNorm2;
418       double y1 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
419           aDirXY * (aPnt->x() - theCenterArc->x()) - theDirLine->y() * aDs) / aDirNorm2;
420       double y2 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
421           aDirXY * (aPnt->x() - theCenterArc->x()) + theDirLine->y() * aDs) / aDirNorm2;
422
423       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
424       theCenters.push_back(aPoint1);
425       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
426       theCenters.push_back(aPoint2);
427     }
428   }
429 }
430
431 /// \brief Find intersections of two circles with extended radii
432 void possibleFilletCenterArcArc(
433     std::shared_ptr<GeomAPI_XY> theCenterA, double theRadiusA,
434     std::shared_ptr<GeomAPI_XY> theCenterB, double theRadiusB,
435     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
436 {
437   std::shared_ptr<GeomAPI_XY> aCenterDir = theCenterB->decreased(theCenterA);
438   double aCenterDist2 = aCenterDir->dot(aCenterDir);
439   double aCenterDist = sqrt(aCenterDist2);
440
441   double aRadA, aRadB;
442   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
443     aRadA = theRadiusA + aStepA * theRadius;
444     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
445       aRadB = theRadiusB + aStepB * theRadius;
446       if (aRadA + aRadB < aCenterDist || fabs(aRadA - aRadB) > aCenterDist)
447         continue; // there is no intersections
448
449       double aMedDist = (aRadA * aRadA - aRadB * aRadB + aCenterDist2) / (2.0 * aCenterDist);
450       double aHeight = sqrt(aRadA * aRadA - aMedDist * aMedDist);
451
452       double x1 = theCenterA->x() +
453         (aMedDist * aCenterDir->x() + aCenterDir->y() * aHeight) / aCenterDist;
454       double y1 = theCenterA->y() +
455         (aMedDist * aCenterDir->y() - aCenterDir->x() * aHeight) / aCenterDist;
456
457       double x2 = theCenterA->x() +
458         (aMedDist * aCenterDir->x() - aCenterDir->y() * aHeight) / aCenterDist;
459       double y2 = theCenterA->y() +
460         (aMedDist * aCenterDir->y() + aCenterDir->x() * aHeight) / aCenterDist;
461
462       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
463       theCenters.push_back(aPoint1);
464       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
465       theCenters.push_back(aPoint2);
466     }
467   }
468 }
469
470 void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
471                            double theRadius, bool theNotInversed[2],
472                            std::shared_ptr<GeomAPI_XY>& theCenter,
473                            std::shared_ptr<GeomAPI_XY>& theTangentA,
474                            std::shared_ptr<GeomAPI_XY>& theTangentB)
475 {
476   static const int aNbFeatures = 2;
477   FeaturePtr aFeature[aNbFeatures] = {theFeatureA, theFeatureB};
478   std::shared_ptr<GeomAPI_XY> aStart[aNbFeatures], aEnd[aNbFeatures], aCenter[aNbFeatures];
479   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint, aEndPoint;
480
481   for (int i = 0; i < aNbFeatures; i++) {
482     if (aFeature[i]->getKind() == SketchPlugin_Line::ID()) {
483       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
484           aFeature[i]->attribute(SketchPlugin_Line::START_ID()));
485       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
486           aFeature[i]->attribute(SketchPlugin_Line::END_ID()));
487     } else if (aFeature[i]->getKind() == SketchPlugin_Arc::ID()) {
488       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
489           aFeature[i]->attribute(SketchPlugin_Arc::START_ID()));
490       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
491           aFeature[i]->attribute(SketchPlugin_Arc::END_ID()));
492       aCenter[i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
493           aFeature[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt()->xy();
494     } else
495       return;
496     aStart[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
497         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()) :
498         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()));
499     aEnd[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
500         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()) :
501         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()));
502   }
503
504   if (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
505       theFeatureB->getKind() == SketchPlugin_Line::ID()) {
506     std::shared_ptr<GeomAPI_Dir2d> aDir[2];
507     std::shared_ptr<GeomAPI_Dir2d> aDirT[2];
508     for (int i = 0; i < aNbFeatures; i++) {
509       aDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aEnd[i]->decreased(aStart[i])));
510       aDirT[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(-aDir[i]->y(), aDir[i]->x()));
511     }
512
513     // get and filter possible centers
514     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
515     possibleFilletCenterLineLine(aStart[0], aDir[0], aStart[1], aDir[1],
516                                  theRadius, aSuspectCenters);
517     double aDot = 0.0;
518     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
519     for (; anIt != aSuspectCenters.end(); anIt++) {
520       aDot = aDirT[0]->xy()->dot(aStart[0]->decreased(*anIt));
521       theTangentA = (*anIt)->added(aDirT[0]->xy()->multiplied(aDot));
522       if (theTangentA->decreased(aStart[0])->dot(aDir[0]->xy()) < 0.0)
523         continue; // incorrect position
524       aDot = aDirT[1]->xy()->dot(aStart[1]->decreased(*anIt));
525       theTangentB = (*anIt)->added(aDirT[1]->xy()->multiplied(aDot));
526       if (theTangentB->decreased(aStart[1])->dot(aDir[1]->xy()) < 0.0)
527         continue; // incorrect position
528       // the center is found, stop searching
529       theCenter = *anIt;
530       return;
531     }
532   } else if ((theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
533       theFeatureB->getKind() == SketchPlugin_Line::ID()) ||
534       (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
535       theFeatureB->getKind() == SketchPlugin_Arc::ID())) {
536     int aLineInd = theFeatureA->getKind() == SketchPlugin_Line::ID() ? 0 : 1;
537     double anArcRadius = aStart[1-aLineInd]->distance(aCenter[1-aLineInd]);
538     std::shared_ptr<GeomAPI_Dir2d> aDirLine = std::shared_ptr<GeomAPI_Dir2d>(
539         new GeomAPI_Dir2d(aEnd[aLineInd]->decreased(aStart[aLineInd])));
540     std::shared_ptr<GeomAPI_Dir2d> aDirT = std::shared_ptr<GeomAPI_Dir2d>(
541         new GeomAPI_Dir2d(-aDirLine->y(), aDirLine->x()));
542
543     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir = std::shared_ptr<GeomAPI_Dir2d>(
544         new GeomAPI_Dir2d(aStart[1-aLineInd]->decreased(aCenter[1-aLineInd])));
545     std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
546         new GeomAPI_Dir2d(aEnd[1-aLineInd]->decreased(aCenter[1-aLineInd])));
547     double anArcAngle = aEndArcDir->angle(aStartArcDir);
548
549     // get possible centers and filter them
550     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
551     possibleFilletCenterLineArc(aStart[aLineInd], aDirLine, aCenter[1-aLineInd],
552                                 anArcRadius, theRadius, aSuspectCenters);
553     double aDot = 0.0;
554     // the line is forward into the arc
555     double innerArc = aCenter[1-aLineInd]->decreased(aStart[aLineInd])->dot(aDirLine->xy());
556     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
557     // The possible centers are ranged by their positions.
558     // If the point is not satisfy one of criteria, the weight is decreased with penalty.
559     int aBestWeight = 0;
560     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
561     for (; anIt != aSuspectCenters.end(); anIt++) {
562       int aWeight = 2;
563       aDot = aDirT->xy()->dot(aStart[aLineInd]->decreased(*anIt));
564       aLineTgPoint = (*anIt)->added(aDirT->xy()->multiplied(aDot));
565       // Check the point is placed on the correct arc (penalty if false)
566       if (aCenter[1-aLineInd]->distance(*anIt) * innerArc > anArcRadius * innerArc)
567         aWeight -= 1;
568       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
569           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1-aLineInd])));
570       double aCurAngle = aCurDir->angle(aStartArcDir);
571       if (anArcAngle < 0.0) aCurAngle *= -1.0;
572       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle))
573         continue;
574       if (aWeight > aBestWeight)
575         aBestWeight = aWeight;
576       else if (aWeight < aBestWeight ||
577                aStart[aLineInd]->distance(*anIt) >
578                aStart[aLineInd]->distance(theCenter)) // <-- take closer point
579         continue;
580       // the center is found, stop searching
581       theCenter = *anIt;
582       anArcTgPoint = aCenter[1-aLineInd]->added(aCurDir->xy()->multiplied(anArcRadius));
583       if (theFeatureA->getKind() == SketchPlugin_Line::ID()) {
584         theTangentA = aLineTgPoint;
585         theTangentB = anArcTgPoint;
586       } else {
587         theTangentA = anArcTgPoint;
588         theTangentB = aLineTgPoint;
589       }
590       //return;
591     }
592   } else if (theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
593       theFeatureB->getKind() == SketchPlugin_Arc::ID()) {
594     double anArcRadius[aNbFeatures];
595     double anArcAngle[aNbFeatures];
596     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir[aNbFeatures];
597     for (int i = 0; i < aNbFeatures; i++) {
598       anArcRadius[i] = aStart[i]->distance(aCenter[i]);
599       aStartArcDir[i] = std::shared_ptr<GeomAPI_Dir2d>(
600           new GeomAPI_Dir2d(aStart[i]->decreased(aCenter[i])));
601       std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
602           new GeomAPI_Dir2d(aEnd[i]->decreased(aCenter[i])));
603       anArcAngle[i] = aEndArcDir->angle(aStartArcDir[i]);
604     }
605
606     // get and filter possible centers
607     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
608     possibleFilletCenterArcArc(aCenter[0], anArcRadius[0], aCenter[1],
609                                anArcRadius[1], theRadius, aSuspectCenters);
610     double aDot = 0.0;
611     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
612     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
613     for (; anIt != aSuspectCenters.end(); anIt++) {
614       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
615           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[0])));
616       double aCurAngle = aCurDir->angle(aStartArcDir[0]);
617       if (anArcAngle[0] < 0.0) aCurAngle *= -1.0;
618       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[0]))
619         continue; // incorrect position
620       theTangentA = aCenter[0]->added(aCurDir->xy()->multiplied(anArcRadius[0]));
621
622       aCurDir = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1])));
623       aCurAngle = aCurDir->angle(aStartArcDir[1]);
624       if (anArcAngle[1] < 0.0) aCurAngle *= -1.0;
625       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[1]))
626         continue; // incorrect position
627       theTangentB = aCenter[1]->added(aCurDir->xy()->multiplied(anArcRadius[1]));
628
629       // the center is found, stop searching
630       theCenter = *anIt;
631       return;
632     }
633   }
634 }
635
636 void getPointOnEdge(const FeaturePtr theFeature,
637                     const std::shared_ptr<GeomAPI_Pnt2d> theFilletPoint,
638                     std::shared_ptr<GeomAPI_Pnt2d>& thePoint) {
639   if(theFeature->getKind() == SketchPlugin_Line::ID()) {
640     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
641       theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
642     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
643       theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
644     if(aPntStart->distance(theFilletPoint) > 1.e-7) {
645       aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
646         theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
647       aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
648         theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
649     }
650     thePoint.reset(
651       new GeomAPI_Pnt2d(aPntStart->xy()->added(
652       aPntEnd->xy()->decreased( aPntStart->xy() )->multiplied(1.0 / 3.0) ) ) );
653   } else {
654     std::shared_ptr<GeomAPI_Pnt2d> aPntTemp;
655     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
656       theFeature->attribute(SketchPlugin_Arc::START_ID()))->pnt();
657     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
658       theFeature->attribute(SketchPlugin_Arc::END_ID()))->pnt();
659     if(theFeature->attribute(SketchPlugin_Arc::INVERSED_ID())) {
660       aPntTemp = aPntStart;
661       aPntStart = aPntEnd;
662       aPntEnd = aPntTemp;
663     }
664     std::shared_ptr<GeomAPI_Pnt2d> aCenterPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
665       theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
666     std::shared_ptr<GeomAPI_Circ2d> aCirc(new GeomAPI_Circ2d(aCenterPnt, aPntStart));
667     double aStartParameter(0), anEndParameter(0);
668     aCirc->parameter(aPntStart, paramTolerance, aStartParameter);
669     aCirc->parameter(aPntEnd, paramTolerance, anEndParameter);
670     if(aPntStart->distance(theFilletPoint) > tolerance) {
671       double aTmpParameter = aStartParameter;
672       aStartParameter = anEndParameter;
673       anEndParameter = aTmpParameter;
674     }
675     double aPntParameter = aStartParameter + (anEndParameter - aStartParameter) / 3.0;
676     aCirc->D0(aPntParameter, thePoint);
677   }
678 }
679
680 double getProjectionDistance(const FeaturePtr theFeature,
681                              const std::shared_ptr<GeomAPI_Pnt2d> thePoint)
682 {
683   std::shared_ptr<GeomAPI_Pnt2d> aProjectPnt;
684   if(theFeature->getKind() == SketchPlugin_Line::ID()) {
685     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
686       theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
687     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
688       theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
689     std::shared_ptr<GeomAPI_Lin2d> aLin(new GeomAPI_Lin2d(aPntStart, aPntEnd));
690     aProjectPnt = aLin->project(thePoint);
691   } else {
692     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
693       theFeature->attribute(SketchPlugin_Arc::START_ID()))->pnt();
694     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
695       theFeature->attribute(SketchPlugin_Arc::END_ID()))->pnt();
696     std::shared_ptr<GeomAPI_Pnt2d> aCenterPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
697       theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
698     std::shared_ptr<GeomAPI_Circ2d> aCirc(new GeomAPI_Circ2d(aCenterPnt, aPntStart));
699     aProjectPnt = aCirc->project(thePoint);
700   }
701   if(aProjectPnt.get()) {
702     return aProjectPnt->distance(thePoint);
703   }
704   return -1;
705 }
706
707 std::set<FeaturePtr> getCoincides(const FeaturePtr& theConstraintCoincidence)
708 {
709   std::set<FeaturePtr> aCoincides;
710
711   std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt =
712     SketchPlugin_Tools::getCoincidencePoint(theConstraintCoincidence);
713
714   SketchPlugin_Tools::findCoincidences(theConstraintCoincidence,
715                                        SketchPlugin_ConstraintCoincidence::ENTITY_A(),
716                                        aCoincides);
717   SketchPlugin_Tools::findCoincidences(theConstraintCoincidence,
718                                        SketchPlugin_ConstraintCoincidence::ENTITY_B(),
719                                        aCoincides);
720
721   // Remove points from set of coincides.
722   std::set<FeaturePtr> aNewSetOfCoincides;
723   for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
724     std::shared_ptr<SketchPlugin_SketchEntity> aSketchEntity =
725       std::dynamic_pointer_cast<SketchPlugin_SketchEntity>(*anIt);
726     if(aSketchEntity.get() && aSketchEntity->isCopy()) {
727       continue;
728     }
729     if((*anIt)->getKind() == SketchPlugin_Line::ID()) {
730       aNewSetOfCoincides.insert(*anIt);
731     } else if((*anIt)->getKind() == SketchPlugin_Arc::ID()) {
732       AttributePtr anAttrCenter = (*anIt)->attribute(SketchPlugin_Arc::CENTER_ID());
733       std::shared_ptr<GeomDataAPI_Point2D> aPointCenter2D =
734         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrCenter);
735       if(aPointCenter2D.get() && aFilletPnt->isEqual(aPointCenter2D->pnt())) {
736         continue;
737       }
738       aNewSetOfCoincides.insert(*anIt);
739     }
740   }
741   aCoincides = aNewSetOfCoincides;
742
743   // If we still have more than two coincides remove auxilary entities from set of coincides.
744   if(aCoincides.size() > 2) {
745     aNewSetOfCoincides.clear();
746     for(std::set<FeaturePtr>::iterator
747         anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
748       if(!(*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
749         aNewSetOfCoincides.insert(*anIt);
750       }
751     }
752     aCoincides = aNewSetOfCoincides;
753   }
754
755   return aCoincides;
756 }
757
758 std::set<FeaturePtr> findFeaturesToRemove(const FeaturePtr theFeature,
759                                           const AttributePtr theAttribute) {
760   std::set<FeaturePtr> aFeaturesToBeRemoved;
761   std::set<AttributePtr> aRefs = theFeature->data()->refsToMe();
762   std::list<ResultPtr> aResults = theFeature->results();
763   for(std::list<ResultPtr>::const_iterator aResultsIt = aResults.cbegin();
764       aResultsIt != aResults.cend();
765       ++aResultsIt) {
766     ResultPtr aResult = *aResultsIt;
767     std::set<AttributePtr> aResultRefs = aResult->data()->refsToMe();
768     aRefs.insert(aResultRefs.begin(), aResultRefs.end());
769   }
770   for(std::set<AttributePtr>::const_iterator anIt = aRefs.cbegin();
771     anIt != aRefs.cend();
772     ++anIt) {
773     std::shared_ptr<ModelAPI_Attribute> anAttr = (*anIt);
774     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
775     if(aFeature->getKind() == SketchPlugin_Fillet::ID()) {
776       continue;
777     }
778     if(aFeature->getKind() == SketchPlugin_ConstraintLength::ID()
779         || aFeature->getKind() == SketchPlugin_ConstraintEqual::ID()) {
780       aFeaturesToBeRemoved.insert(aFeature);
781     } else {
782       std::list<AttributePtr> anAttrs =
783           aFeature->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
784       for(std::list<AttributePtr>::const_iterator aRefAttrsIt = anAttrs.cbegin();
785           aRefAttrsIt != anAttrs.cend();
786           ++aRefAttrsIt) {
787         AttributeRefAttrPtr anAttrRefAttr =
788           std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*aRefAttrsIt);
789         if(anAttrRefAttr.get() && anAttrRefAttr->attr() == theAttribute) {
790           aFeaturesToBeRemoved.insert(aFeature);
791         }
792       }
793     }
794   }
795   return aFeaturesToBeRemoved;
796 }