]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchPlugin/SketchPlugin_ConstraintFillet.cpp
Salome HOME
Fixed validators for Boolean and Intersection
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_ConstraintFillet.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
2
3 // File:    SketchPlugin_ConstraintFillet.cpp
4 // Created: 19 Mar 2015
5 // Author:  Artem ZHIDKOV
6
7 #include "SketchPlugin_ConstraintFillet.h"
8
9 #include <GeomAPI_Circ2d.h>
10 #include <GeomAPI_Dir2d.h>
11 #include <GeomAPI_Lin2d.h>
12 #include <GeomAPI_Pnt2d.h>
13 #include <GeomAPI_XY.h>
14 #include <GeomDataAPI_Point2D.h>
15 #include <ModelAPI_AttributeDouble.h>
16 #include <ModelAPI_AttributeRefList.h>
17 #include <ModelAPI_AttributeRefAttrList.h>
18 #include <ModelAPI_Data.h>
19 #include <ModelAPI_Events.h>
20 #include <ModelAPI_Session.h>
21 #include <ModelAPI_Validator.h>
22
23 #include <SketchPlugin_Arc.h>
24 #include <SketchPlugin_Line.h>
25 #include <SketchPlugin_Point.h>
26 #include <SketchPlugin_Sketch.h>
27 #include <SketchPlugin_ConstraintCoincidence.h>
28 #include <SketchPlugin_ConstraintTangent.h>
29 #include <SketchPlugin_ConstraintRadius.h>
30 #include <SketchPlugin_Tools.h>
31
32 #include <Events_Loop.h>
33
34 #include <math.h>
35
36 const double tolerance = 1.e-7;
37 const double paramTolerance = 1.e-4;
38
39 /// \brief Attract specified point on theNewArc to the attribute of theFeature
40 static void recalculateAttributes(FeaturePtr theNewArc, const std::string& theNewArcAttribute,
41   FeaturePtr theFeature, const std::string& theFeatureAttribute);
42
43 /// \brief Calculates center of fillet arc and coordinates of tangency points
44 static void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
45                                   double theRadius, bool theNotInversed[2],
46                                   std::shared_ptr<GeomAPI_XY>& theCenter,
47                                   std::shared_ptr<GeomAPI_XY>& theTangentA,
48                                   std::shared_ptr<GeomAPI_XY>& theTangentB);
49
50 /// Get point on 1/3 length of edge from fillet point
51 static void getPointOnEdge(const FeaturePtr theFeature,
52                            const std::shared_ptr<GeomAPI_Pnt2d> theFilletPoint,
53                            std::shared_ptr<GeomAPI_Pnt2d>& thePoint);
54
55 /// Get distance from point to feature
56 static double getProjectionDistance(const FeaturePtr theFeature,
57                              const std::shared_ptr<GeomAPI_Pnt2d> thePoint);
58
59 /// Get coincide edges for fillet
60 static std::set<FeaturePtr> getCoincides(const FeaturePtr& theConstraintCoincidence);
61
62 SketchPlugin_ConstraintFillet::SketchPlugin_ConstraintFillet()
63 : myListOfPointsChangedInCode(false),
64   myRadiusChangedByUser(false),
65   myRadiusChangedInCode(false),
66   myRadiusInitialized(false)
67 {
68 }
69
70 void SketchPlugin_ConstraintFillet::initAttributes()
71 {
72   data()->addAttribute(SketchPlugin_Constraint::VALUE(), ModelAPI_AttributeDouble::typeId());
73   data()->addAttribute(SketchPlugin_Constraint::ENTITY_A(), ModelAPI_AttributeRefAttrList::typeId());
74 }
75
76 void SketchPlugin_ConstraintFillet::execute()
77 {
78   std::shared_ptr<ModelAPI_Data> aData = data();
79
80   // Check the base objects are initialized.
81   AttributeRefAttrListPtr aPointsRefList = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(
82     aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
83   if(!aPointsRefList->isInitialized()) {
84     setError("Error: List of points is not initialized.");
85     return;
86   }
87
88   // Get fillet radius.
89   double aFilletRadius = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
90     aData->attribute(SketchPlugin_Constraint::VALUE()))->value();
91
92   // Wait all constraints being created, then send update events
93   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
94   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
95   if (isUpdateFlushed)
96     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
97
98   for(std::set<AttributePtr>::iterator aPointsIter = myNewPoints.begin();
99       aPointsIter != myNewPoints.end();
100       ++aPointsIter) {
101     AttributePtr aPointAttr = *aPointsIter;
102     std::shared_ptr<GeomDataAPI_Point2D> aFilletPoint2d = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aPointAttr);
103     if(!aFilletPoint2d.get()) {
104       setError("Error: One of the selected points is empty.");
105       return;
106     }
107     std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2d->pnt();
108
109     // Obtain base lines for fillet.
110     bool anIsNeedNewObjects = true;
111     FilletFeatures aFilletFeatures;
112     std::map<AttributePtr, FilletFeatures>::iterator aPrevPointsIter = myPointFeaturesMap.find(aPointAttr);
113     if(aPrevPointsIter != myPointFeaturesMap.end()) {
114       anIsNeedNewObjects = false;
115       aFilletFeatures = aPrevPointsIter->second;
116     }
117     FeaturePtr aBaseEdgeA, aBaseEdgeB;
118     if(!anIsNeedNewObjects) {
119       aBaseEdgeA = aFilletFeatures.baseEdgesState.front().first;
120       aBaseEdgeB = aFilletFeatures.baseEdgesState.back().first;
121     } else {
122       // Obtain constraint coincidence for the fillet point.
123       FeaturePtr aConstraintCoincidence;
124       const std::set<AttributePtr>& aRefsList = aFilletPoint2d->owner()->data()->refsToMe();
125       for(std::set<AttributePtr>::const_iterator anIt = aRefsList.cbegin(); anIt != aRefsList.cend(); ++anIt) {
126         std::shared_ptr<ModelAPI_Attribute> anAttr = (*anIt);
127         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
128         if(aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
129           AttributeRefAttrPtr anAttrRefA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
130             aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_A()));
131           AttributeRefAttrPtr anAttrRefB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
132             aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_B()));
133           if(anAttrRefA.get() && !anAttrRefA->isObject()) {
134             AttributePtr anAttrA = anAttrRefA->attr();
135             if(aFilletPoint2d == anAttrA) {
136               aConstraintCoincidence = aConstrFeature;
137               break;
138             }
139           }
140           if(anAttrRefB.get() && !anAttrRefB->isObject()) {
141             AttributePtr anAttrB = anAttrRefB->attr();
142             if(aFilletPoint2d == anAttrB) {
143               aConstraintCoincidence = aConstrFeature;
144               break;
145             }
146           }
147         }
148       }
149
150       if(!aConstraintCoincidence.get()) {
151         setError("Error: No coincident edges at one of the selected points.");
152         return;
153       }
154
155       // Get coincide edges.
156       std::set<FeaturePtr> aCoincides = getCoincides(aConstraintCoincidence);
157       if(aCoincides.size() != 2) {
158         setError("Error: One of the selected points does not have two suitable edges for fillet.");
159         return;
160       }
161
162       std::set<FeaturePtr>::iterator aLinesIt = aCoincides.begin();
163       aBaseEdgeA = *aLinesIt++;
164       aBaseEdgeB = *aLinesIt;
165
166       std::pair<FeaturePtr, bool> aBasePairA = std::make_pair(aBaseEdgeA, aBaseEdgeA->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value());
167       std::pair<FeaturePtr, bool> aBasePairB = std::make_pair(aBaseEdgeB, aBaseEdgeB->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value());
168       aFilletFeatures.baseEdgesState.push_back(aBasePairA);
169       aFilletFeatures.baseEdgesState.push_back(aBasePairB);
170     }
171
172     if(!aBaseEdgeA.get() || !aBaseEdgeB.get()) {
173       setError("Error: One of the base edges is empty.");
174       return;
175     }
176
177     // Create new edges and arc if needed.
178     FeaturePtr aResultEdgeA, aResultEdgeB, aResultArc;
179     if(!anIsNeedNewObjects) {
180       // Obtain features from the list.
181       std::list<FeaturePtr>::iterator aResultEdgesIt = aFilletFeatures.resultEdges.begin();
182       aResultEdgeA = *aResultEdgesIt++;
183       aResultEdgeB = *aResultEdgesIt++;
184       aResultArc = *aResultEdgesIt;
185     } else {
186       // Copy edges and create arc.
187       aResultEdgeA = SketchPlugin_Sketch::addUniqueNamedCopiedFeature(aBaseEdgeA, sketch());
188       aResultEdgeA->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(false);
189       aResultEdgeB = SketchPlugin_Sketch::addUniqueNamedCopiedFeature(aBaseEdgeB, sketch());
190       aResultEdgeB->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(false);
191       aResultArc = sketch()->addFeature(SketchPlugin_Arc::ID());
192
193       aFilletFeatures.resultEdges.push_back(aResultEdgeA);
194       aFilletFeatures.resultEdges.push_back(aResultEdgeB);
195       aFilletFeatures.resultEdges.push_back(aResultArc);
196     }
197
198     // Calculate arc attributes
199     static const int aNbFeatures = 2;
200     FeaturePtr aBaseFeatures[aNbFeatures] = {aBaseEdgeA, aBaseEdgeB};
201     FeaturePtr aResultFeatures[aNbFeatures] = {aResultEdgeA, aResultEdgeB};
202     std::shared_ptr<GeomAPI_Dir2d> aTangentDir[aNbFeatures]; // tangent directions of the features in coincident point
203     bool isStart[aNbFeatures]; // indicates which point the features share
204     std::shared_ptr<GeomAPI_Pnt2d> aStartEndPnt[aNbFeatures * 2]; // first pair of points relate to first feature, second pair -  to second
205     std::string aFeatAttributes[aNbFeatures * 2]; // attributes of features
206     for (int i = 0; i < aNbFeatures; i++) {
207       std::string aStartAttr, aEndAttr;
208       if (aResultFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
209         aStartAttr = SketchPlugin_Line::START_ID();
210         aEndAttr = SketchPlugin_Line::END_ID();
211       } else if (aResultFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
212         aStartAttr = SketchPlugin_Arc::START_ID();
213         aEndAttr = SketchPlugin_Arc::END_ID();
214       } else { // wrong argument
215         setError("Error: One of the points has wrong coincide feature");
216         return;
217       }
218       aFeatAttributes[2*i] = aStartAttr;
219       aStartEndPnt[2*i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
220         aBaseFeatures[i]->attribute(aStartAttr))->pnt();
221       aFeatAttributes[2*i+1] = aEndAttr;
222       aStartEndPnt[2*i+1] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
223         aBaseFeatures[i]->attribute(aEndAttr))->pnt();
224     }
225     for (int aFeatInd = 0; aFeatInd < aNbFeatures; aFeatInd++) {
226       for (int j = 0; j < 2; j++) // loop on start-end of each feature
227         if (aStartEndPnt[aFeatInd * aNbFeatures + j]->distance(aFilletPnt2d) < 1.e-10) {
228           isStart[aFeatInd] = (j==0);
229           break;
230         }
231     }
232     // tangent directions of the features
233     for (int i = 0; i < aNbFeatures; i++) {
234       std::shared_ptr<GeomAPI_XY> aDir;
235       if (aResultFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
236         aDir = aStartEndPnt[2*i+1]->xy()->decreased(aStartEndPnt[2*i]->xy());
237         if (!isStart[i])
238           aDir = aDir->multiplied(-1.0);
239       } else if (aResultFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
240         std::shared_ptr<GeomAPI_Pnt2d> aCenterPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
241           aResultFeatures[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
242         aDir = isStart[i] ? aStartEndPnt[2*i]->xy() : aStartEndPnt[2*i+1]->xy();
243         aDir = aDir->decreased(aCenterPoint->xy());
244
245         double x = aDir->x();
246         double y = aDir->y();
247         aDir->setX(-y);
248         aDir->setY(x);
249         if (isStart[i] == std::dynamic_pointer_cast<SketchPlugin_Arc>(aBaseFeatures[i])->isReversed())
250           aDir = aDir->multiplied(-1.0);
251       }
252       aTangentDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aDir));
253     }
254
255     // By default, the start point of fillet arc is connected to FeatureA,
256     // and the end point - to FeatureB. But when the angle between TangentDirA and
257     // TangentDirB greater 180 degree, the sequaence of features need to be reversed.
258     double cosBA = aTangentDir[0]->cross(aTangentDir[1]); // cos(B-A), where A and B - angles between corresponding tanget direction and the X axis
259     bool isReversed = cosBA > 0.0;
260
261     // Calculate fillet arc parameters
262     std::shared_ptr<GeomAPI_XY> aCenter, aTangentPntA, aTangentPntB;
263     calculateFilletCenter(aBaseEdgeA, aBaseEdgeB, aFilletRadius, isStart, aCenter, aTangentPntA, aTangentPntB);
264     if(!aCenter.get() || !aTangentPntA.get() || !aTangentPntB.get()) {
265       setError("Can not create fillet with the specified parameters.");
266       return;
267     }
268     // update features
269     std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
270       aResultEdgeA->attribute(aFeatAttributes[isStart[0] ? 0 : 1]))->setValue(aTangentPntA->x(), aTangentPntA->y());
271     aResultEdgeA->execute();
272     std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
273       aResultEdgeB->attribute(aFeatAttributes[2 + (isStart[1] ? 0 : 1)]))->setValue(aTangentPntB->x(), aTangentPntB->y());
274     aResultEdgeB->execute();
275     // update fillet arc: make the arc correct for sure, so, it is not needed to process the "attribute updated"
276     // by arc; moreover, it may cause cyclicity in hte mechanism of updater
277     aResultArc->data()->blockSendAttributeUpdated(true);
278     std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
279       aResultArc->attribute(SketchPlugin_Arc::CENTER_ID()))->setValue(aCenter->x(), aCenter->y());
280     if(isReversed) {
281       std::shared_ptr<GeomAPI_XY> aTmp = aTangentPntA;
282       aTangentPntA = aTangentPntB;
283       aTangentPntB = aTmp;
284     }
285     std::shared_ptr<GeomDataAPI_Point2D> aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
286       aResultArc->attribute(SketchPlugin_Arc::START_ID()));
287     std::shared_ptr<GeomDataAPI_Point2D> aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
288       aResultArc->attribute(SketchPlugin_Arc::END_ID()));
289     if(aStartPoint->isInitialized() && aEndPoint->isInitialized() &&
290       (aStartPoint->pnt()->xy()->distance(aTangentPntA) > tolerance ||
291        aEndPoint->pnt()->xy()->distance(aTangentPntB) > tolerance)) {
292       std::dynamic_pointer_cast<SketchPlugin_Arc>(aResultArc)->setReversed(false);
293     }
294     aStartPoint->setValue(aTangentPntA->x(), aTangentPntA->y());
295     aEndPoint->setValue(aTangentPntB->x(), aTangentPntB->y());
296     aResultArc->data()->blockSendAttributeUpdated(false);
297     aResultArc->execute();
298
299     if(anIsNeedNewObjects) {
300       // Create list of additional constraints:
301       // 1. Coincidence of boundary points of features (copied lines/arcs) and fillet arc
302       // 1.1. coincidence
303       FeaturePtr aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
304       AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
305           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
306       aRefAttr->setAttr(aResultArc->attribute(SketchPlugin_Arc::START_ID()));
307       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
308           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
309       int aFeatInd = isReversed ? 1 : 0;
310       int anAttrInd = (isReversed ? 2 : 0) + (isStart[isReversed ? 1 : 0] ? 0 : 1);
311       aRefAttr->setAttr(aResultFeatures[aFeatInd]->attribute(aFeatAttributes[anAttrInd]));
312       recalculateAttributes(aResultArc, SketchPlugin_Arc::START_ID(), aResultFeatures[aFeatInd], aFeatAttributes[anAttrInd]);
313       aConstraint->execute();
314       aFilletFeatures.resultConstraints.push_back(aConstraint);
315       ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
316       // 1.2. coincidence
317       aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
318       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
319           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
320       aRefAttr->setAttr(aResultArc->attribute(SketchPlugin_Arc::END_ID()));
321       aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
322           aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
323       aFeatInd = isReversed ? 0 : 1;
324       anAttrInd = (isReversed ? 0 : 2) + (isStart[isReversed ? 0 : 1] ? 0 : 1);
325       aRefAttr->setAttr(aResultFeatures[aFeatInd]->attribute(aFeatAttributes[anAttrInd]));
326       recalculateAttributes(aResultArc, SketchPlugin_Arc::END_ID(), aResultFeatures[aFeatInd], aFeatAttributes[anAttrInd]);
327       aConstraint->execute();
328       aFilletFeatures.resultConstraints.push_back(aConstraint);
329       ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
330       // 2. Fillet arc radius
331       //aConstraint = sketch()->addFeature(SketchPlugin_ConstraintRadius::ID());
332       //aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
333       //    aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
334       //aRefAttr->setObject(aNewArc->lastResult());
335       //std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
336       //    aConstraint->attribute(SketchPlugin_Constraint::VALUE()))->setValue(aFilletRadius);
337       //std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
338       //    aConstraint->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT()))->setValue(
339       //    isStart[0] ? aStartEndPnt[0] : aStartEndPnt[1]);
340       //aConstraint->execute();
341       //myProducedFeatures.push_back(aConstraint);
342       //ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
343       // 3. Tangency of fillet arc and features
344       for (int i = 0; i < aNbFeatures; i++) {
345         aConstraint = sketch()->addFeature(SketchPlugin_ConstraintTangent::ID());
346         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
347             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
348         aRefAttr->setObject(aResultArc->lastResult());
349         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
350             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
351         bool isArc = aResultFeatures[i]->getKind() == SketchPlugin_Arc::ID();
352         aRefAttr->setObject(isArc ? aResultFeatures[i]->lastResult() : aResultFeatures[i]->firstResult());
353         aConstraint->execute();
354         aFilletFeatures.resultConstraints.push_back(aConstraint);
355         ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
356       }
357       // 4. Coincidence of free boundaries of base and copied features
358       for (int i = 0; i < aNbFeatures; i++) {
359         anAttrInd = 2*i + (isStart[i] ? 1 : 0);
360         aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
361         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
362             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
363         aRefAttr->setAttr(aBaseFeatures[i]->attribute(aFeatAttributes[anAttrInd]));
364         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
365             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
366         aRefAttr->setAttr(aResultFeatures[i]->attribute(aFeatAttributes[anAttrInd]));
367         aFilletFeatures.resultConstraints.push_back(aConstraint);
368       }
369       // 4.1. Additional tangency constraints when the fillet is based on arcs.
370       //      It is used to verify the created arc will be placed on a source.
371       for (int i = 0; i < aNbFeatures; ++i) {
372         if (aResultFeatures[i]->getKind() != SketchPlugin_Arc::ID())
373           continue;
374         aConstraint = sketch()->addFeature(SketchPlugin_ConstraintTangent::ID());
375         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
376             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
377         aRefAttr->setObject(aBaseFeatures[i]->lastResult());
378         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
379             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
380         aRefAttr->setObject(aResultFeatures[i]->lastResult());
381         aConstraint->execute();
382         aFilletFeatures.resultConstraints.push_back(aConstraint);
383         ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
384       }
385       // 5. Tangent points should be placed on the base features
386       for (int i = 0; i < aNbFeatures; i++) {
387         anAttrInd = 2*i + (isStart[i] ? 0 : 1);
388         aConstraint = sketch()->addFeature(SketchPlugin_ConstraintCoincidence::ID());
389         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
390             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
391         aRefAttr->setAttr(aResultFeatures[i]->attribute(aFeatAttributes[anAttrInd]));
392         aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
393             aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
394         aRefAttr->setObject(aBaseFeatures[i]->lastResult());
395         aFilletFeatures.resultConstraints.push_back(aConstraint);
396       }
397       // make base features auxiliary
398       aBaseEdgeA->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(true);
399       aBaseEdgeB->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(true);
400
401       // exchange the naming IDs of newly created and old line that become auxiliary
402       sketch()->exchangeIDs(aBaseEdgeA, aResultEdgeA);
403       sketch()->exchangeIDs(aBaseEdgeB, aResultEdgeB);
404
405       // store point and features in the map.
406       myPointFeaturesMap[aPointAttr] = aFilletFeatures;
407     } else {
408       // Update radius value
409       int aNbSubs = sketch()->numberOfSubs();
410       FeaturePtr aSubFeature;
411       for (int aSub = 0; aSub < aNbSubs; aSub++) {
412         aSubFeature = sketch()->subFeature(aSub);
413         if (aSubFeature->getKind() != SketchPlugin_ConstraintRadius::ID())
414           continue;
415         AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
416             aSubFeature->attribute(SketchPlugin_Constraint::ENTITY_A()));
417         if (!aRefAttr || !aRefAttr->isObject())
418           continue;
419         FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
420         if (aFeature == aResultArc) {
421           AttributeDoublePtr aRadius = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
422             aSubFeature->attribute(SketchPlugin_Constraint::VALUE()));
423           aRadius->setValue(aFilletRadius);
424           break;
425         }
426       }
427     }
428   }
429
430   // Send events to update the sub-features by the solver.
431   if(isUpdateFlushed) {
432     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
433   }
434 }
435
436 void SketchPlugin_ConstraintFillet::attributeChanged(const std::string& theID)
437 {
438   if(theID == SketchPlugin_Constraint::ENTITY_A()) {
439     if(myListOfPointsChangedInCode) {
440       return;
441     }
442
443     // Clear results.
444     clearResults();
445
446     // Clear list of new points.
447     myNewPoints.clear();
448
449     // Get list of points for fillets and current radius.
450     AttributeRefAttrListPtr aRefListOfFilletPoints = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(
451       data()->attribute(SketchPlugin_Constraint::ENTITY_A()));
452     AttributeDoublePtr aRadiusAttribute = real(VALUE());
453     int aListSize = aRefListOfFilletPoints->size();
454     if(aListSize == 0 && !myRadiusChangedByUser) {
455       // If list is empty reset radius to zero (if it was not changed by user).
456       myRadiusChangedInCode = true;
457       aRadiusAttribute->setValue(0);
458       myRadiusChangedInCode = false;
459       return;
460     }
461
462     // Iterate over points to get base lines an calculate radius for fillets.
463     double aMinimumRadius = 0;
464     std::list<std::pair<ObjectPtr, AttributePtr>> aSelectedPointsList = aRefListOfFilletPoints->list();
465     std::list<std::pair<ObjectPtr, AttributePtr>>::iterator anIter = aSelectedPointsList.begin();
466     std::set<AttributePtr> aPointsToSkeep;
467     for(int anIndex = 0; anIndex < aListSize; anIndex++, anIter++) {
468       AttributePtr aFilletPointAttr = (*anIter).second;
469       std::shared_ptr<GeomDataAPI_Point2D> aFilletPoint2D =
470         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aFilletPointAttr);
471       if(!aFilletPoint2D.get()) {
472         myNewPoints.clear();
473         setError("Error: One of the selected points is invalid.");
474         return;
475       }
476
477       // If point or coincident point is already in list remove it from attribute.
478       if(aPointsToSkeep.find(aFilletPointAttr) != aPointsToSkeep.end()) {
479         myListOfPointsChangedInCode = true;
480         aRefListOfFilletPoints->remove(aFilletPointAttr);
481         myListOfPointsChangedInCode = false;
482         continue;
483       }
484
485       // Obtain constraint coincidence for the fillet point.
486       FeaturePtr aConstraintCoincidence;
487       const std::set<AttributePtr>& aRefsList = aFilletPointAttr->owner()->data()->refsToMe();
488       for(std::set<AttributePtr>::const_iterator anIt = aRefsList.cbegin(); anIt != aRefsList.cend(); ++anIt) {
489         std::shared_ptr<ModelAPI_Attribute> anAttr = (*anIt);
490         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
491         if(aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
492           AttributeRefAttrPtr anAttrRefA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
493             aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_A()));
494           AttributeRefAttrPtr anAttrRefB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
495             aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_B()));
496           if(anAttrRefA.get()) {
497             AttributePtr anAttrA = anAttrRefA->attr();
498             if(aFilletPointAttr == anAttrA) {
499               aConstraintCoincidence = aConstrFeature;
500               break;
501             }
502           }
503           if(anAttrRefB.get()) {
504             AttributePtr anAttrB = anAttrRefB->attr();
505             if(aFilletPointAttr == anAttrB) {
506               aConstraintCoincidence = aConstrFeature;
507               break;
508             }
509           }
510         }
511       }
512
513       if(!aConstraintCoincidence.get()) {
514         myNewPoints.clear();
515         setError("Error: No coincident edges at one of the selected points.");
516         return;
517       }
518
519       // Get coincides from constraint.
520       std::set<FeaturePtr> aCoincides;
521
522
523       SketchPlugin_Tools::findCoincidences(aConstraintCoincidence,
524                                            SketchPlugin_ConstraintCoincidence::ENTITY_A(),
525                                            aCoincides);
526       SketchPlugin_Tools::findCoincidences(aConstraintCoincidence,
527                                            SketchPlugin_ConstraintCoincidence::ENTITY_B(),
528                                            aCoincides);
529
530       // Remove points from set of coincides. Also get all attributes which is equal to this point to exclude it.
531       std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
532       std::set<FeaturePtr> aNewSetOfCoincides;
533       for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
534         std::string aFeatureKind = (*anIt)->getKind();
535         if(aFeatureKind == SketchPlugin_Point::ID()) {
536           AttributePtr anAttr = (*anIt)->attribute(SketchPlugin_Point::COORD_ID());
537           std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
538             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr);
539           if(aPoint2D.get() && aFilletPnt2d->isEqual(aPoint2D->pnt())) {
540             aPointsToSkeep.insert(anAttr);
541           }
542         } else if(aFeatureKind == SketchPlugin_Line::ID()) {
543           AttributePtr anAttrStart = (*anIt)->attribute(SketchPlugin_Line::START_ID());
544           std::shared_ptr<GeomDataAPI_Point2D> aPointStart2D =
545             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrStart);
546           if(aPointStart2D.get() && aFilletPnt2d->isEqual(aPointStart2D->pnt())) {
547             aPointsToSkeep.insert(anAttrStart);
548           }
549           AttributePtr anAttrEnd = (*anIt)->attribute(SketchPlugin_Line::END_ID());
550           std::shared_ptr<GeomDataAPI_Point2D> aPointEnd2D =
551             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrEnd);
552           if(aPointEnd2D.get() && aFilletPnt2d->isEqual(aPointEnd2D->pnt())) {
553             aPointsToSkeep.insert(anAttrEnd);
554           }
555           aNewSetOfCoincides.insert(*anIt);
556         } else if(aFeatureKind == SketchPlugin_Arc::ID() ) {
557           AttributePtr anAttrCenter = (*anIt)->attribute(SketchPlugin_Arc::CENTER_ID());
558           std::shared_ptr<GeomDataAPI_Point2D> aPointCenter2D =
559             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrCenter);
560           if(aPointCenter2D.get() && aFilletPnt2d->isEqual(aPointCenter2D->pnt())) {
561             aPointsToSkeep.insert(anAttrCenter);
562             continue;
563           }
564           AttributePtr anAttrStart = (*anIt)->attribute(SketchPlugin_Arc::START_ID());
565           std::shared_ptr<GeomDataAPI_Point2D> aPointStart2D =
566             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrStart);
567           if(aPointStart2D.get() && aFilletPnt2d->isEqual(aPointStart2D->pnt())) {
568             aPointsToSkeep.insert(anAttrStart);
569           }
570           AttributePtr anAttrEnd = (*anIt)->attribute(SketchPlugin_Arc::END_ID());
571           std::shared_ptr<GeomDataAPI_Point2D> aPointEnd2D =
572             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrEnd);
573           if(aPointEnd2D.get() && aFilletPnt2d->isEqual(aPointEnd2D->pnt())) {
574             aPointsToSkeep.insert(anAttrEnd);
575           }
576           aNewSetOfCoincides.insert(*anIt);
577         }
578       }
579       aCoincides = aNewSetOfCoincides;
580
581       // If we still have more than two coincides remove auxilary entities from set of coincides.
582       if(aCoincides.size() > 2) {
583         aNewSetOfCoincides.clear();
584         for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
585           if(!(*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
586             aNewSetOfCoincides.insert(*anIt);
587           }
588         }
589         aCoincides = aNewSetOfCoincides;
590       }
591
592       if(aCoincides.size() != 2) {
593         myNewPoints.clear();
594         setError("Error: One of the selected points does not have two suitable edges for fillet.");
595         return;
596       }
597
598       // Store base point for fillet.
599       aPointsToSkeep.insert(aFilletPointAttr);
600       myNewPoints.insert(aFilletPointAttr);
601
602       // Get base lines for fillet.
603       FeaturePtr anOldFeatureA, anOldFeatureB;
604       std::set<FeaturePtr>::iterator aLinesIt = aCoincides.begin();
605       anOldFeatureA = *aLinesIt++;
606       anOldFeatureB = *aLinesIt;
607
608       // Getting radius value if it was not changed by user.
609       if(!myRadiusChangedByUser) {
610         // Getting points located at 1/3 of edge length from fillet point.
611         std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
612         std::shared_ptr<GeomAPI_Pnt2d> aPntA, aPntB;
613         getPointOnEdge(anOldFeatureA, aFilletPnt2d, aPntA);
614         getPointOnEdge(anOldFeatureB, aFilletPnt2d, aPntB);
615
616         /// Getting distances.
617         double aDistanceA = getProjectionDistance(anOldFeatureB, aPntA);
618         double aDistanceB = getProjectionDistance(anOldFeatureA, aPntB);
619         double aRadius = aDistanceA < aDistanceB ? aDistanceA / 2.0 : aDistanceB / 2.0;
620         aMinimumRadius = aMinimumRadius == 0 ? aRadius : aRadius < aMinimumRadius ? aRadius : aMinimumRadius;
621       }
622     }
623
624     // Set new default radius if it was not changed by user.
625     if(!myRadiusChangedByUser) {
626       myRadiusChangedInCode = true;
627       aRadiusAttribute->setValue(aMinimumRadius);
628       myRadiusChangedInCode = false;
629     }
630
631   } else if(theID == SketchPlugin_Constraint::VALUE()) {
632     if(myRadiusInitialized && !myRadiusChangedInCode) {
633       myRadiusChangedByUser = true;
634     }
635     if(!myRadiusInitialized) {
636       myRadiusInitialized = true;
637     }
638   }
639 }
640
641 AISObjectPtr SketchPlugin_ConstraintFillet::getAISObject(AISObjectPtr thePrevious)
642 {
643   if (!sketch())
644     return thePrevious;
645
646   AISObjectPtr anAIS = thePrevious;
647   /// TODO: Equal constraint presentation should be put here
648   return anAIS;
649 }
650
651 bool SketchPlugin_ConstraintFillet::isMacro() const
652 {
653   return true;
654 }
655
656 void SketchPlugin_ConstraintFillet::clearResults()
657 {
658   // Clear auxiliary flag on initial objects.
659   for(std::map<AttributePtr, FilletFeatures>::iterator aPointsIter = myPointFeaturesMap.begin();
660       aPointsIter != myPointFeaturesMap.end();) {
661     const FilletFeatures& aFilletFeatures = aPointsIter->second;
662     std::list<std::pair<FeaturePtr, bool>>::const_iterator aFeatureIt;
663     for(aFeatureIt = aFilletFeatures.baseEdgesState.cbegin();
664         aFeatureIt != aFilletFeatures.baseEdgesState.cend();
665         ++aFeatureIt) {
666       aFeatureIt->first->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(aFeatureIt->second);
667     }
668     ++aPointsIter;
669   }
670
671   // And remove all produced features.
672   DocumentPtr aDoc = sketch()->document();
673   for(std::map<AttributePtr, FilletFeatures>::iterator aPointsIter = myPointFeaturesMap.begin();
674       aPointsIter != myPointFeaturesMap.end();) {
675     // Remove all produced constraints.
676     const FilletFeatures& aFilletFeatures = aPointsIter->second;
677     std::list<FeaturePtr>::const_iterator aFeatureIt;
678     for(aFeatureIt = aFilletFeatures.resultConstraints.cbegin();
679         aFeatureIt != aFilletFeatures.resultConstraints.cend();
680         ++aFeatureIt) {
681       aDoc->removeFeature(*aFeatureIt);
682     }
683
684     // Remove all result edges.
685     for(aFeatureIt = aFilletFeatures.resultEdges.cbegin();
686         aFeatureIt != aFilletFeatures.resultEdges.cend();
687         ++aFeatureIt) {
688       aDoc->removeFeature(*aFeatureIt);
689     }
690
691     // Remove point from map.
692     myPointFeaturesMap.erase(aPointsIter++);
693   }
694 };
695
696
697 // =========   Auxiliary functions   =================
698 void recalculateAttributes(FeaturePtr theNewArc,  const std::string& theNewArcAttribute,
699                            FeaturePtr theFeature, const std::string& theFeatureAttribute)
700 {
701   std::shared_ptr<GeomAPI_Pnt2d> anArcPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
702       theNewArc->attribute(theNewArcAttribute))->pnt();
703   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
704       theFeature->attribute(theFeatureAttribute))->setValue(anArcPoint->x(), anArcPoint->y());
705 }
706
707 /// \brief Find intersections of lines shifted along normal direction
708 void possibleFilletCenterLineLine(
709     std::shared_ptr<GeomAPI_XY> thePointA, std::shared_ptr<GeomAPI_Dir2d> theDirA,
710     std::shared_ptr<GeomAPI_XY> thePointB, std::shared_ptr<GeomAPI_Dir2d> theDirB,
711     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
712 {
713   std::shared_ptr<GeomAPI_Dir2d> aDirAT(new GeomAPI_Dir2d(-theDirA->y(), theDirA->x()));
714   std::shared_ptr<GeomAPI_Dir2d> aDirBT(new GeomAPI_Dir2d(-theDirB->y(), theDirB->x()));
715   std::shared_ptr<GeomAPI_XY> aPntA, aPntB;
716   double aDet = theDirA->cross(theDirB);
717   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
718     aPntA = thePointA->added(aDirAT->xy()->multiplied(aStepA * theRadius));
719     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
720       aPntB = thePointB->added(aDirBT->xy()->multiplied(aStepB * theRadius));
721       double aVX = aDirAT->xy()->dot(aPntA);
722       double aVY = aDirBT->xy()->dot(aPntB);
723       std::shared_ptr<GeomAPI_XY> aPoint(new GeomAPI_XY(
724           (theDirB->x() * aVX - theDirA->x() * aVY) / aDet,
725           (theDirB->y() * aVX - theDirA->y() * aVY) / aDet));
726       theCenters.push_back(aPoint);
727     }
728   }
729 }
730
731 /// \brief Find intersections of line shifted along normal direction in both sides
732 ///        and a circle with extended radius
733 void possibleFilletCenterLineArc(
734     std::shared_ptr<GeomAPI_XY> theStartLine, std::shared_ptr<GeomAPI_Dir2d> theDirLine,
735     std::shared_ptr<GeomAPI_XY> theCenterArc, double theRadiusArc,
736     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
737 {
738   std::shared_ptr<GeomAPI_Dir2d> aDirT(new GeomAPI_Dir2d(-theDirLine->y(), theDirLine->x()));
739   std::shared_ptr<GeomAPI_XY> aPnt;
740   double aDirNorm2 = theDirLine->dot(theDirLine);
741   double aRad = 0.0;
742   double aDirX = theDirLine->x();
743   double aDirX2 = theDirLine->x() * theDirLine->x();
744   double aDirY2 = theDirLine->y() * theDirLine->y();
745   double aDirXY = theDirLine->x() * theDirLine->y();
746   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
747     aPnt = theStartLine->added(aDirT->xy()->multiplied(aStepA * theRadius));
748     double aCoeff = aDirT->xy()->dot(aPnt->decreased(theCenterArc));
749     double aCoeff2 = aCoeff * aCoeff;
750     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
751       aRad = theRadiusArc + aStepB * theRadius;
752       double aD = aRad * aRad * aDirNorm2 - aCoeff2;
753       if (aD < 0.0)
754         continue;
755       double aDs = sqrt(aD);
756       double x1 = theCenterArc->x() + (aCoeff * aDirT->x() - aDirT->y() * aDs) / aDirNorm2;
757       double x2 = theCenterArc->x() + (aCoeff * aDirT->x() + aDirT->y() * aDs) / aDirNorm2;
758       double y1 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
759           aDirXY * (aPnt->x() - theCenterArc->x()) - theDirLine->y() * aDs) / aDirNorm2;
760       double y2 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
761           aDirXY * (aPnt->x() - theCenterArc->x()) + theDirLine->y() * aDs) / aDirNorm2;
762
763       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
764       theCenters.push_back(aPoint1);
765       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
766       theCenters.push_back(aPoint2);
767     }
768   }
769 }
770
771 /// \brief Find intersections of two circles with extended radii
772 void possibleFilletCenterArcArc(
773     std::shared_ptr<GeomAPI_XY> theCenterA, double theRadiusA,
774     std::shared_ptr<GeomAPI_XY> theCenterB, double theRadiusB,
775     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
776 {
777   std::shared_ptr<GeomAPI_XY> aCenterDir = theCenterB->decreased(theCenterA);
778   double aCenterDist2 = aCenterDir->dot(aCenterDir);
779   double aCenterDist = sqrt(aCenterDist2);
780
781   double aRadA, aRadB;
782   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
783     aRadA = theRadiusA + aStepA * theRadius;
784     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
785       aRadB = theRadiusB + aStepB * theRadius;
786       if (aRadA + aRadB < aCenterDist || fabs(aRadA - aRadB) > aCenterDist)
787         continue; // there is no intersections
788
789       double aMedDist = (aRadA * aRadA - aRadB * aRadB + aCenterDist2) / (2.0 * aCenterDist);
790       double aHeight = sqrt(aRadA * aRadA - aMedDist * aMedDist);
791
792       double x1 = theCenterA->x() + (aMedDist * aCenterDir->x() + aCenterDir->y() * aHeight) / aCenterDist;
793       double y1 = theCenterA->y() + (aMedDist * aCenterDir->y() - aCenterDir->x() * aHeight) / aCenterDist;
794
795       double x2 = theCenterA->x() + (aMedDist * aCenterDir->x() - aCenterDir->y() * aHeight) / aCenterDist;
796       double y2 = theCenterA->y() + (aMedDist * aCenterDir->y() + aCenterDir->x() * aHeight) / aCenterDist;
797
798       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
799       theCenters.push_back(aPoint1);
800       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
801       theCenters.push_back(aPoint2);
802     }
803   }
804 }
805
806 void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
807                            double theRadius, bool theNotInversed[2],
808                            std::shared_ptr<GeomAPI_XY>& theCenter,
809                            std::shared_ptr<GeomAPI_XY>& theTangentA,
810                            std::shared_ptr<GeomAPI_XY>& theTangentB)
811 {
812   static const int aNbFeatures = 2;
813   FeaturePtr aFeature[aNbFeatures] = {theFeatureA, theFeatureB};
814   std::shared_ptr<GeomAPI_XY> aStart[aNbFeatures], aEnd[aNbFeatures], aCenter[aNbFeatures];
815   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint, aEndPoint;
816
817   for (int i = 0; i < aNbFeatures; i++) {
818     if (aFeature[i]->getKind() == SketchPlugin_Line::ID()) {
819       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
820           aFeature[i]->attribute(SketchPlugin_Line::START_ID()));
821       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
822           aFeature[i]->attribute(SketchPlugin_Line::END_ID()));
823     } else if (aFeature[i]->getKind() == SketchPlugin_Arc::ID()) {
824       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
825           aFeature[i]->attribute(SketchPlugin_Arc::START_ID()));
826       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
827           aFeature[i]->attribute(SketchPlugin_Arc::END_ID()));
828       aCenter[i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
829           aFeature[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt()->xy();
830     } else
831       return;
832     aStart[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
833         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()) :
834         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()));
835     aEnd[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
836         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()) :
837         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()));
838   }
839
840   if (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
841       theFeatureB->getKind() == SketchPlugin_Line::ID()) {
842     std::shared_ptr<GeomAPI_Dir2d> aDir[2];
843     std::shared_ptr<GeomAPI_Dir2d> aDirT[2];
844     for (int i = 0; i < aNbFeatures; i++) {
845       aDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aEnd[i]->decreased(aStart[i])));
846       aDirT[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(-aDir[i]->y(), aDir[i]->x()));
847     }
848
849     // get and filter possible centers
850     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
851     possibleFilletCenterLineLine(aStart[0], aDir[0], aStart[1], aDir[1], theRadius, aSuspectCenters);
852     double aDot = 0.0;
853     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
854     for (; anIt != aSuspectCenters.end(); anIt++) {
855       aDot = aDirT[0]->xy()->dot(aStart[0]->decreased(*anIt));
856       theTangentA = (*anIt)->added(aDirT[0]->xy()->multiplied(aDot));
857       if (theTangentA->decreased(aStart[0])->dot(aDir[0]->xy()) < 0.0)
858         continue; // incorrect position
859       aDot = aDirT[1]->xy()->dot(aStart[1]->decreased(*anIt));
860       theTangentB = (*anIt)->added(aDirT[1]->xy()->multiplied(aDot));
861       if (theTangentB->decreased(aStart[1])->dot(aDir[1]->xy()) < 0.0)
862         continue; // incorrect position
863       // the center is found, stop searching
864       theCenter = *anIt;
865       return;
866     }
867   } else if ((theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
868       theFeatureB->getKind() == SketchPlugin_Line::ID()) || 
869       (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
870       theFeatureB->getKind() == SketchPlugin_Arc::ID())) {
871     int aLineInd = theFeatureA->getKind() == SketchPlugin_Line::ID() ? 0 : 1;
872     double anArcRadius = aStart[1-aLineInd]->distance(aCenter[1-aLineInd]);
873     std::shared_ptr<GeomAPI_Dir2d> aDirLine = std::shared_ptr<GeomAPI_Dir2d>(
874         new GeomAPI_Dir2d(aEnd[aLineInd]->decreased(aStart[aLineInd])));
875     std::shared_ptr<GeomAPI_Dir2d> aDirT = std::shared_ptr<GeomAPI_Dir2d>(
876         new GeomAPI_Dir2d(-aDirLine->y(), aDirLine->x()));
877
878     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir = std::shared_ptr<GeomAPI_Dir2d>(
879         new GeomAPI_Dir2d(aStart[1-aLineInd]->decreased(aCenter[1-aLineInd])));
880     std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
881         new GeomAPI_Dir2d(aEnd[1-aLineInd]->decreased(aCenter[1-aLineInd])));
882     double anArcAngle = aEndArcDir->angle(aStartArcDir);
883
884     // get possible centers and filter them
885     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
886     possibleFilletCenterLineArc(aStart[aLineInd], aDirLine, aCenter[1-aLineInd], anArcRadius, theRadius, aSuspectCenters);
887     double aDot = 0.0;
888     // the line is forward into the arc
889     double innerArc = aCenter[1-aLineInd]->decreased(aStart[aLineInd])->dot(aDirLine->xy());
890     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
891     // The possible centers are ranged by their positions.
892     // If the point is not satisfy one of criteria, the weight is decreased with penalty.
893     int aBestWeight = 0;
894     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
895     for (; anIt != aSuspectCenters.end(); anIt++) {
896       int aWeight = 2;
897       aDot = aDirT->xy()->dot(aStart[aLineInd]->decreased(*anIt));
898       aLineTgPoint = (*anIt)->added(aDirT->xy()->multiplied(aDot));
899       // Check the point is placed on the correct arc (penalty if false)
900       if (aCenter[1-aLineInd]->distance(*anIt) * innerArc > anArcRadius * innerArc)
901         aWeight -= 1;
902       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
903           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1-aLineInd])));
904       double aCurAngle = aCurDir->angle(aStartArcDir);
905       if (anArcAngle < 0.0) aCurAngle *= -1.0;
906       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle))
907         continue;
908       if (aWeight > aBestWeight)
909         aBestWeight = aWeight;
910       else if (aWeight < aBestWeight ||
911                aStart[aLineInd]->distance(*anIt) >
912                aStart[aLineInd]->distance(theCenter)) // <-- take closer point
913         continue;
914       // the center is found, stop searching
915       theCenter = *anIt;
916       anArcTgPoint = aCenter[1-aLineInd]->added(aCurDir->xy()->multiplied(anArcRadius));
917       if (theFeatureA->getKind() == SketchPlugin_Line::ID()) {
918         theTangentA = aLineTgPoint;
919         theTangentB = anArcTgPoint;
920       } else {
921         theTangentA = anArcTgPoint;
922         theTangentB = aLineTgPoint;
923       }
924       //return;
925     }
926   } else if (theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
927       theFeatureB->getKind() == SketchPlugin_Arc::ID()) {
928     double anArcRadius[aNbFeatures];
929     double anArcAngle[aNbFeatures];
930     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir[aNbFeatures];
931     for (int i = 0; i < aNbFeatures; i++) {
932       anArcRadius[i] = aStart[i]->distance(aCenter[i]);
933       aStartArcDir[i] = std::shared_ptr<GeomAPI_Dir2d>(
934           new GeomAPI_Dir2d(aStart[i]->decreased(aCenter[i])));
935       std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
936           new GeomAPI_Dir2d(aEnd[i]->decreased(aCenter[i])));
937       anArcAngle[i] = aEndArcDir->angle(aStartArcDir[i]);
938     }
939
940     // get and filter possible centers
941     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
942     possibleFilletCenterArcArc(aCenter[0], anArcRadius[0], aCenter[1], anArcRadius[1], theRadius, aSuspectCenters);
943     double aDot = 0.0;
944     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
945     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
946     for (; anIt != aSuspectCenters.end(); anIt++) {
947       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
948           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[0])));
949       double aCurAngle = aCurDir->angle(aStartArcDir[0]);
950       if (anArcAngle[0] < 0.0) aCurAngle *= -1.0;
951       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[0]))
952         continue; // incorrect position
953       theTangentA = aCenter[0]->added(aCurDir->xy()->multiplied(anArcRadius[0]));
954
955       aCurDir = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1])));
956       aCurAngle = aCurDir->angle(aStartArcDir[1]);
957       if (anArcAngle[1] < 0.0) aCurAngle *= -1.0;
958       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[1]))
959         continue; // incorrect position
960       theTangentB = aCenter[1]->added(aCurDir->xy()->multiplied(anArcRadius[1]));
961
962       // the center is found, stop searching
963       theCenter = *anIt;
964       return;
965     }
966   }
967 }
968
969 void getPointOnEdge(const FeaturePtr theFeature,
970                     const std::shared_ptr<GeomAPI_Pnt2d> theFilletPoint,
971                     std::shared_ptr<GeomAPI_Pnt2d>& thePoint) {
972   if(theFeature->getKind() == SketchPlugin_Line::ID()) {
973     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
974       theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
975     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
976       theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
977     if(aPntStart->distance(theFilletPoint) > 1.e-7) {
978       aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
979         theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
980       aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
981         theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
982     }
983     thePoint.reset( new GeomAPI_Pnt2d(aPntStart->xy()->added( aPntEnd->xy()->decreased( aPntStart->xy() )->multiplied(1.0 / 3.0) ) ) );
984   } else {
985     std::shared_ptr<GeomAPI_Pnt2d> aPntTemp;
986     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
987       theFeature->attribute(SketchPlugin_Arc::START_ID()))->pnt();
988     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
989       theFeature->attribute(SketchPlugin_Arc::END_ID()))->pnt();
990     if(theFeature->attribute(SketchPlugin_Arc::INVERSED_ID())) {
991       aPntTemp = aPntStart;
992       aPntStart = aPntEnd;
993       aPntEnd = aPntTemp;
994     }
995     std::shared_ptr<GeomAPI_Pnt2d> aCenterPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
996       theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
997     std::shared_ptr<GeomAPI_Circ2d> aCirc(new GeomAPI_Circ2d(aCenterPnt, aPntStart));
998     double aStartParameter(0), anEndParameter(0);
999     aCirc->parameter(aPntStart, paramTolerance, aStartParameter);
1000     aCirc->parameter(aPntEnd, paramTolerance, anEndParameter);
1001     if(aPntStart->distance(theFilletPoint) > tolerance) {
1002       double aTmpParameter = aStartParameter;
1003       aStartParameter = anEndParameter;
1004       anEndParameter = aTmpParameter;
1005     }
1006     double aPntParameter = aStartParameter + (anEndParameter - aStartParameter) / 3.0;
1007     aCirc->D0(aPntParameter, thePoint);
1008   }
1009 }
1010
1011 double getProjectionDistance(const FeaturePtr theFeature,
1012                              const std::shared_ptr<GeomAPI_Pnt2d> thePoint)
1013 {
1014   std::shared_ptr<GeomAPI_Pnt2d> aProjectPnt;
1015   if(theFeature->getKind() == SketchPlugin_Line::ID()) {
1016     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1017       theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
1018     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1019       theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
1020     std::shared_ptr<GeomAPI_Lin2d> aLin(new GeomAPI_Lin2d(aPntStart, aPntEnd));
1021     aProjectPnt = aLin->project(thePoint);
1022   } else {
1023     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1024       theFeature->attribute(SketchPlugin_Arc::START_ID()))->pnt();
1025     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1026       theFeature->attribute(SketchPlugin_Arc::END_ID()))->pnt();
1027     std::shared_ptr<GeomAPI_Pnt2d> aCenterPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1028       theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
1029     std::shared_ptr<GeomAPI_Circ2d> aCirc(new GeomAPI_Circ2d(aCenterPnt, aPntStart));
1030     aProjectPnt = aCirc->project(thePoint);
1031   }
1032   if(aProjectPnt.get()) {
1033     return aProjectPnt->distance(thePoint);
1034   }
1035   return -1;
1036 }
1037
1038 std::set<FeaturePtr> getCoincides(const FeaturePtr& theConstraintCoincidence)
1039 {
1040   std::set<FeaturePtr> aCoincides;
1041
1042   std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt = SketchPlugin_Tools::getCoincidencePoint(theConstraintCoincidence);
1043
1044   SketchPlugin_Tools::findCoincidences(theConstraintCoincidence,
1045                                        SketchPlugin_ConstraintCoincidence::ENTITY_A(),
1046                                        aCoincides);
1047   SketchPlugin_Tools::findCoincidences(theConstraintCoincidence,
1048                                        SketchPlugin_ConstraintCoincidence::ENTITY_B(),
1049                                        aCoincides);
1050
1051   // Remove points from set of coincides.
1052   std::set<FeaturePtr> aNewSetOfCoincides;
1053   for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
1054     if((*anIt)->getKind() == SketchPlugin_Line::ID()) {
1055       aNewSetOfCoincides.insert(*anIt);
1056     } else if((*anIt)->getKind() == SketchPlugin_Arc::ID()) {
1057       AttributePtr anAttrCenter = (*anIt)->attribute(SketchPlugin_Arc::CENTER_ID());
1058       std::shared_ptr<GeomDataAPI_Point2D> aPointCenter2D =
1059         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrCenter);
1060       if(aPointCenter2D.get() && aFilletPnt->isEqual(aPointCenter2D->pnt())) {
1061         continue;
1062       }
1063       aNewSetOfCoincides.insert(*anIt);
1064     }
1065   }
1066   aCoincides = aNewSetOfCoincides;
1067
1068   // If we still have more than two coincides remove auxilary entities from set of coincides.
1069   if(aCoincides.size() > 2) {
1070     aNewSetOfCoincides.clear();
1071     for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
1072       if(!(*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
1073         aNewSetOfCoincides.insert(*anIt);
1074       }
1075     }
1076     aCoincides = aNewSetOfCoincides;
1077   }
1078
1079   return aCoincides;
1080 }