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