Salome HOME
Issue #1448 problem with saved study and visualization of distance: linux compilation...
[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 anAttrStart = (*anIt)->attribute(SketchPlugin_Arc::START_ID());
558           std::shared_ptr<GeomDataAPI_Point2D> aPointStart2D =
559             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrStart);
560           if(aPointStart2D.get() && aFilletPnt2d->isEqual(aPointStart2D->pnt())) {
561             aPointsToSkeep.insert(anAttrStart);
562           }
563           AttributePtr anAttrEnd = (*anIt)->attribute(SketchPlugin_Arc::END_ID());
564           std::shared_ptr<GeomDataAPI_Point2D> aPointEnd2D =
565             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrEnd);
566           if(aPointEnd2D.get() && aFilletPnt2d->isEqual(aPointEnd2D->pnt())) {
567             aPointsToSkeep.insert(anAttrEnd);
568           }
569           aNewSetOfCoincides.insert(*anIt);
570         }
571       }
572       aCoincides = aNewSetOfCoincides;
573
574       // If we still have more than two coincides remove auxilary entities from set of coincides.
575       if(aCoincides.size() > 2) {
576         aNewSetOfCoincides.clear();
577         for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
578           if(!(*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
579             aNewSetOfCoincides.insert(*anIt);
580           }
581         }
582         aCoincides = aNewSetOfCoincides;
583       }
584
585       if(aCoincides.size() != 2) {
586         myNewPoints.clear();
587         setError("Error: One of the selected points does not have two suitable edges for fillet.");
588         return;
589       }
590
591       // Store base point for fillet.
592       aPointsToSkeep.insert(aFilletPointAttr);
593       myNewPoints.insert(aFilletPointAttr);
594
595       // Get base lines for fillet.
596       FeaturePtr anOldFeatureA, anOldFeatureB;
597       std::set<FeaturePtr>::iterator aLinesIt = aCoincides.begin();
598       anOldFeatureA = *aLinesIt++;
599       anOldFeatureB = *aLinesIt;
600
601       // Getting radius value if it was not changed by user.
602       if(!myRadiusChangedByUser) {
603         // Getting points located at 1/3 of edge length from fillet point.
604         std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
605         std::shared_ptr<GeomAPI_Pnt2d> aPntA, aPntB;
606         getPointOnEdge(anOldFeatureA, aFilletPnt2d, aPntA);
607         getPointOnEdge(anOldFeatureB, aFilletPnt2d, aPntB);
608
609         /// Getting distances.
610         double aDistanceA = getProjectionDistance(anOldFeatureB, aPntA);
611         double aDistanceB = getProjectionDistance(anOldFeatureA, aPntB);
612         double aRadius = aDistanceA < aDistanceB ? aDistanceA / 2.0 : aDistanceB / 2.0;
613         aMinimumRadius = aMinimumRadius == 0 ? aRadius : aRadius < aMinimumRadius ? aRadius : aMinimumRadius;
614       }
615     }
616
617     // Set new default radius if it was not changed by user.
618     if(!myRadiusChangedByUser) {
619       myRadiusChangedInCode = true;
620       aRadiusAttribute->setValue(aMinimumRadius);
621       myRadiusChangedInCode = false;
622     }
623
624   } else if(theID == SketchPlugin_Constraint::VALUE()) {
625     if(myRadiusInitialized && !myRadiusChangedInCode) {
626       myRadiusChangedByUser = true;
627     }
628     if(!myRadiusInitialized) {
629       myRadiusInitialized = true;
630     }
631   }
632 }
633
634 AISObjectPtr SketchPlugin_ConstraintFillet::getAISObject(AISObjectPtr thePrevious)
635 {
636   if (!sketch())
637     return thePrevious;
638
639   AISObjectPtr anAIS = thePrevious;
640   /// TODO: Equal constraint presentation should be put here
641   return anAIS;
642 }
643
644 bool SketchPlugin_ConstraintFillet::isMacro() const
645 {
646   return true;
647 }
648
649 void SketchPlugin_ConstraintFillet::clearResults()
650 {
651   // Clear auxiliary flag on initial objects.
652   for(std::map<AttributePtr, FilletFeatures>::iterator aPointsIter = myPointFeaturesMap.begin();
653       aPointsIter != myPointFeaturesMap.end();) {
654     const FilletFeatures& aFilletFeatures = aPointsIter->second;
655     std::list<std::pair<FeaturePtr, bool>>::const_iterator aFeatureIt;
656     for(aFeatureIt = aFilletFeatures.baseEdgesState.cbegin();
657         aFeatureIt != aFilletFeatures.baseEdgesState.cend();
658         ++aFeatureIt) {
659       aFeatureIt->first->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(aFeatureIt->second);
660     }
661     ++aPointsIter;
662   }
663
664   // And remove all produced features.
665   DocumentPtr aDoc = sketch()->document();
666   for(std::map<AttributePtr, FilletFeatures>::iterator aPointsIter = myPointFeaturesMap.begin();
667       aPointsIter != myPointFeaturesMap.end();) {
668     // Remove all produced constraints.
669     const FilletFeatures& aFilletFeatures = aPointsIter->second;
670     std::list<FeaturePtr>::const_iterator aFeatureIt;
671     for(aFeatureIt = aFilletFeatures.resultConstraints.cbegin();
672         aFeatureIt != aFilletFeatures.resultConstraints.cend();
673         ++aFeatureIt) {
674       aDoc->removeFeature(*aFeatureIt);
675     }
676
677     // Remove all result edges.
678     for(aFeatureIt = aFilletFeatures.resultEdges.cbegin();
679         aFeatureIt != aFilletFeatures.resultEdges.cend();
680         ++aFeatureIt) {
681       aDoc->removeFeature(*aFeatureIt);
682     }
683
684     // Remove point from map.
685     myPointFeaturesMap.erase(aPointsIter++);
686   }
687 };
688
689
690 // =========   Auxiliary functions   =================
691 void recalculateAttributes(FeaturePtr theNewArc,  const std::string& theNewArcAttribute,
692                            FeaturePtr theFeature, const std::string& theFeatureAttribute)
693 {
694   std::shared_ptr<GeomAPI_Pnt2d> anArcPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
695       theNewArc->attribute(theNewArcAttribute))->pnt();
696   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
697       theFeature->attribute(theFeatureAttribute))->setValue(anArcPoint->x(), anArcPoint->y());
698 }
699
700 /// \brief Find intersections of lines shifted along normal direction
701 void possibleFilletCenterLineLine(
702     std::shared_ptr<GeomAPI_XY> thePointA, std::shared_ptr<GeomAPI_Dir2d> theDirA,
703     std::shared_ptr<GeomAPI_XY> thePointB, std::shared_ptr<GeomAPI_Dir2d> theDirB,
704     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
705 {
706   std::shared_ptr<GeomAPI_Dir2d> aDirAT(new GeomAPI_Dir2d(-theDirA->y(), theDirA->x()));
707   std::shared_ptr<GeomAPI_Dir2d> aDirBT(new GeomAPI_Dir2d(-theDirB->y(), theDirB->x()));
708   std::shared_ptr<GeomAPI_XY> aPntA, aPntB;
709   double aDet = theDirA->cross(theDirB);
710   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
711     aPntA = thePointA->added(aDirAT->xy()->multiplied(aStepA * theRadius));
712     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
713       aPntB = thePointB->added(aDirBT->xy()->multiplied(aStepB * theRadius));
714       double aVX = aDirAT->xy()->dot(aPntA);
715       double aVY = aDirBT->xy()->dot(aPntB);
716       std::shared_ptr<GeomAPI_XY> aPoint(new GeomAPI_XY(
717           (theDirB->x() * aVX - theDirA->x() * aVY) / aDet,
718           (theDirB->y() * aVX - theDirA->y() * aVY) / aDet));
719       theCenters.push_back(aPoint);
720     }
721   }
722 }
723
724 /// \brief Find intersections of line shifted along normal direction in both sides
725 ///        and a circle with extended radius
726 void possibleFilletCenterLineArc(
727     std::shared_ptr<GeomAPI_XY> theStartLine, std::shared_ptr<GeomAPI_Dir2d> theDirLine,
728     std::shared_ptr<GeomAPI_XY> theCenterArc, double theRadiusArc,
729     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
730 {
731   std::shared_ptr<GeomAPI_Dir2d> aDirT(new GeomAPI_Dir2d(-theDirLine->y(), theDirLine->x()));
732   std::shared_ptr<GeomAPI_XY> aPnt;
733   double aDirNorm2 = theDirLine->dot(theDirLine);
734   double aRad = 0.0;
735   double aDirX = theDirLine->x();
736   double aDirX2 = theDirLine->x() * theDirLine->x();
737   double aDirY2 = theDirLine->y() * theDirLine->y();
738   double aDirXY = theDirLine->x() * theDirLine->y();
739   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
740     aPnt = theStartLine->added(aDirT->xy()->multiplied(aStepA * theRadius));
741     double aCoeff = aDirT->xy()->dot(aPnt->decreased(theCenterArc));
742     double aCoeff2 = aCoeff * aCoeff;
743     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
744       aRad = theRadiusArc + aStepB * theRadius;
745       double aD = aRad * aRad * aDirNorm2 - aCoeff2;
746       if (aD < 0.0)
747         continue;
748       double aDs = sqrt(aD);
749       double x1 = theCenterArc->x() + (aCoeff * aDirT->x() - aDirT->y() * aDs) / aDirNorm2;
750       double x2 = theCenterArc->x() + (aCoeff * aDirT->x() + aDirT->y() * aDs) / aDirNorm2;
751       double y1 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
752           aDirXY * (aPnt->x() - theCenterArc->x()) - theDirLine->y() * aDs) / aDirNorm2;
753       double y2 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
754           aDirXY * (aPnt->x() - theCenterArc->x()) + theDirLine->y() * aDs) / aDirNorm2;
755
756       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
757       theCenters.push_back(aPoint1);
758       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
759       theCenters.push_back(aPoint2);
760     }
761   }
762 }
763
764 /// \brief Find intersections of two circles with extended radii
765 void possibleFilletCenterArcArc(
766     std::shared_ptr<GeomAPI_XY> theCenterA, double theRadiusA,
767     std::shared_ptr<GeomAPI_XY> theCenterB, double theRadiusB,
768     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
769 {
770   std::shared_ptr<GeomAPI_XY> aCenterDir = theCenterB->decreased(theCenterA);
771   double aCenterDist2 = aCenterDir->dot(aCenterDir);
772   double aCenterDist = sqrt(aCenterDist2);
773
774   double aRadA, aRadB;
775   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
776     aRadA = theRadiusA + aStepA * theRadius;
777     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
778       aRadB = theRadiusB + aStepB * theRadius;
779       if (aRadA + aRadB < aCenterDist || fabs(aRadA - aRadB) > aCenterDist)
780         continue; // there is no intersections
781
782       double aMedDist = (aRadA * aRadA - aRadB * aRadB + aCenterDist2) / (2.0 * aCenterDist);
783       double aHeight = sqrt(aRadA * aRadA - aMedDist * aMedDist);
784
785       double x1 = theCenterA->x() + (aMedDist * aCenterDir->x() + aCenterDir->y() * aHeight) / aCenterDist;
786       double y1 = theCenterA->y() + (aMedDist * aCenterDir->y() - aCenterDir->x() * aHeight) / aCenterDist;
787
788       double x2 = theCenterA->x() + (aMedDist * aCenterDir->x() - aCenterDir->y() * aHeight) / aCenterDist;
789       double y2 = theCenterA->y() + (aMedDist * aCenterDir->y() + aCenterDir->x() * aHeight) / aCenterDist;
790
791       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
792       theCenters.push_back(aPoint1);
793       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
794       theCenters.push_back(aPoint2);
795     }
796   }
797 }
798
799 void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
800                            double theRadius, bool theNotInversed[2],
801                            std::shared_ptr<GeomAPI_XY>& theCenter,
802                            std::shared_ptr<GeomAPI_XY>& theTangentA,
803                            std::shared_ptr<GeomAPI_XY>& theTangentB)
804 {
805   static const int aNbFeatures = 2;
806   FeaturePtr aFeature[aNbFeatures] = {theFeatureA, theFeatureB};
807   std::shared_ptr<GeomAPI_XY> aStart[aNbFeatures], aEnd[aNbFeatures], aCenter[aNbFeatures];
808   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint, aEndPoint;
809
810   for (int i = 0; i < aNbFeatures; i++) {
811     if (aFeature[i]->getKind() == SketchPlugin_Line::ID()) {
812       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
813           aFeature[i]->attribute(SketchPlugin_Line::START_ID()));
814       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
815           aFeature[i]->attribute(SketchPlugin_Line::END_ID()));
816     } else if (aFeature[i]->getKind() == SketchPlugin_Arc::ID()) {
817       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
818           aFeature[i]->attribute(SketchPlugin_Arc::START_ID()));
819       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
820           aFeature[i]->attribute(SketchPlugin_Arc::END_ID()));
821       aCenter[i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
822           aFeature[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt()->xy();
823     } else
824       return;
825     aStart[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
826         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()) :
827         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()));
828     aEnd[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
829         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()) :
830         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()));
831   }
832
833   if (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
834       theFeatureB->getKind() == SketchPlugin_Line::ID()) {
835     std::shared_ptr<GeomAPI_Dir2d> aDir[2];
836     std::shared_ptr<GeomAPI_Dir2d> aDirT[2];
837     for (int i = 0; i < aNbFeatures; i++) {
838       aDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aEnd[i]->decreased(aStart[i])));
839       aDirT[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(-aDir[i]->y(), aDir[i]->x()));
840     }
841
842     // get and filter possible centers
843     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
844     possibleFilletCenterLineLine(aStart[0], aDir[0], aStart[1], aDir[1], theRadius, aSuspectCenters);
845     double aDot = 0.0;
846     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
847     for (; anIt != aSuspectCenters.end(); anIt++) {
848       aDot = aDirT[0]->xy()->dot(aStart[0]->decreased(*anIt));
849       theTangentA = (*anIt)->added(aDirT[0]->xy()->multiplied(aDot));
850       if (theTangentA->decreased(aStart[0])->dot(aDir[0]->xy()) < 0.0)
851         continue; // incorrect position
852       aDot = aDirT[1]->xy()->dot(aStart[1]->decreased(*anIt));
853       theTangentB = (*anIt)->added(aDirT[1]->xy()->multiplied(aDot));
854       if (theTangentB->decreased(aStart[1])->dot(aDir[1]->xy()) < 0.0)
855         continue; // incorrect position
856       // the center is found, stop searching
857       theCenter = *anIt;
858       return;
859     }
860   } else if ((theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
861       theFeatureB->getKind() == SketchPlugin_Line::ID()) || 
862       (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
863       theFeatureB->getKind() == SketchPlugin_Arc::ID())) {
864     int aLineInd = theFeatureA->getKind() == SketchPlugin_Line::ID() ? 0 : 1;
865     double anArcRadius = aStart[1-aLineInd]->distance(aCenter[1-aLineInd]);
866     std::shared_ptr<GeomAPI_Dir2d> aDirLine = std::shared_ptr<GeomAPI_Dir2d>(
867         new GeomAPI_Dir2d(aEnd[aLineInd]->decreased(aStart[aLineInd])));
868     std::shared_ptr<GeomAPI_Dir2d> aDirT = std::shared_ptr<GeomAPI_Dir2d>(
869         new GeomAPI_Dir2d(-aDirLine->y(), aDirLine->x()));
870
871     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir = std::shared_ptr<GeomAPI_Dir2d>(
872         new GeomAPI_Dir2d(aStart[1-aLineInd]->decreased(aCenter[1-aLineInd])));
873     std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
874         new GeomAPI_Dir2d(aEnd[1-aLineInd]->decreased(aCenter[1-aLineInd])));
875     double anArcAngle = aEndArcDir->angle(aStartArcDir);
876
877     // get possible centers and filter them
878     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
879     possibleFilletCenterLineArc(aStart[aLineInd], aDirLine, aCenter[1-aLineInd], anArcRadius, theRadius, aSuspectCenters);
880     double aDot = 0.0;
881     // the line is forward into the arc
882     double innerArc = aCenter[1-aLineInd]->decreased(aStart[aLineInd])->dot(aDirLine->xy());
883     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
884     // The possible centers are ranged by their positions.
885     // If the point is not satisfy one of criteria, the weight is decreased with penalty.
886     int aBestWeight = 0;
887     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
888     for (; anIt != aSuspectCenters.end(); anIt++) {
889       int aWeight = 2;
890       aDot = aDirT->xy()->dot(aStart[aLineInd]->decreased(*anIt));
891       aLineTgPoint = (*anIt)->added(aDirT->xy()->multiplied(aDot));
892       // Check the point is placed on the correct arc (penalty if false)
893       if (aCenter[1-aLineInd]->distance(*anIt) * innerArc > anArcRadius * innerArc)
894         aWeight -= 1;
895       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
896           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1-aLineInd])));
897       double aCurAngle = aCurDir->angle(aStartArcDir);
898       if (anArcAngle < 0.0) aCurAngle *= -1.0;
899       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle))
900         continue;
901       if (aWeight > aBestWeight)
902         aBestWeight = aWeight;
903       else if (aWeight < aBestWeight ||
904                aStart[aLineInd]->distance(*anIt) >
905                aStart[aLineInd]->distance(theCenter)) // <-- take closer point
906         continue;
907       // the center is found, stop searching
908       theCenter = *anIt;
909       anArcTgPoint = aCenter[1-aLineInd]->added(aCurDir->xy()->multiplied(anArcRadius));
910       if (theFeatureA->getKind() == SketchPlugin_Line::ID()) {
911         theTangentA = aLineTgPoint;
912         theTangentB = anArcTgPoint;
913       } else {
914         theTangentA = anArcTgPoint;
915         theTangentB = aLineTgPoint;
916       }
917       //return;
918     }
919   } else if (theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
920       theFeatureB->getKind() == SketchPlugin_Arc::ID()) {
921     double anArcRadius[aNbFeatures];
922     double anArcAngle[aNbFeatures];
923     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir[aNbFeatures];
924     for (int i = 0; i < aNbFeatures; i++) {
925       anArcRadius[i] = aStart[i]->distance(aCenter[i]);
926       aStartArcDir[i] = std::shared_ptr<GeomAPI_Dir2d>(
927           new GeomAPI_Dir2d(aStart[i]->decreased(aCenter[i])));
928       std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
929           new GeomAPI_Dir2d(aEnd[i]->decreased(aCenter[i])));
930       anArcAngle[i] = aEndArcDir->angle(aStartArcDir[i]);
931     }
932
933     // get and filter possible centers
934     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
935     possibleFilletCenterArcArc(aCenter[0], anArcRadius[0], aCenter[1], anArcRadius[1], theRadius, aSuspectCenters);
936     double aDot = 0.0;
937     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
938     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
939     for (; anIt != aSuspectCenters.end(); anIt++) {
940       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
941           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[0])));
942       double aCurAngle = aCurDir->angle(aStartArcDir[0]);
943       if (anArcAngle[0] < 0.0) aCurAngle *= -1.0;
944       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[0]))
945         continue; // incorrect position
946       theTangentA = aCenter[0]->added(aCurDir->xy()->multiplied(anArcRadius[0]));
947
948       aCurDir = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1])));
949       aCurAngle = aCurDir->angle(aStartArcDir[1]);
950       if (anArcAngle[1] < 0.0) aCurAngle *= -1.0;
951       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[1]))
952         continue; // incorrect position
953       theTangentB = aCenter[1]->added(aCurDir->xy()->multiplied(anArcRadius[1]));
954
955       // the center is found, stop searching
956       theCenter = *anIt;
957       return;
958     }
959   }
960 }
961
962 void getPointOnEdge(const FeaturePtr theFeature,
963                     const std::shared_ptr<GeomAPI_Pnt2d> theFilletPoint,
964                     std::shared_ptr<GeomAPI_Pnt2d>& thePoint) {
965   if(theFeature->getKind() == SketchPlugin_Line::ID()) {
966     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
967       theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
968     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
969       theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
970     if(aPntStart->distance(theFilletPoint) > 1.e-7) {
971       aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
972         theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
973       aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
974         theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
975     }
976     thePoint.reset( new GeomAPI_Pnt2d(aPntStart->xy()->added( aPntEnd->xy()->decreased( aPntStart->xy() )->multiplied(1.0 / 3.0) ) ) );
977   } else {
978     std::shared_ptr<GeomAPI_Pnt2d> aPntTemp;
979     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
980       theFeature->attribute(SketchPlugin_Arc::START_ID()))->pnt();
981     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
982       theFeature->attribute(SketchPlugin_Arc::END_ID()))->pnt();
983     if(theFeature->attribute(SketchPlugin_Arc::INVERSED_ID())) {
984       aPntTemp = aPntStart;
985       aPntStart = aPntEnd;
986       aPntEnd = aPntTemp;
987     }
988     std::shared_ptr<GeomAPI_Pnt2d> aCenterPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
989       theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
990     std::shared_ptr<GeomAPI_Circ2d> aCirc(new GeomAPI_Circ2d(aCenterPnt, aPntStart));
991     double aStartParameter(0), anEndParameter(0);
992     aCirc->parameter(aPntStart, paramTolerance, aStartParameter);
993     aCirc->parameter(aPntEnd, paramTolerance, anEndParameter);
994     if(aPntStart->distance(theFilletPoint) > tolerance) {
995       double aTmpParameter = aStartParameter;
996       aStartParameter = anEndParameter;
997       anEndParameter = aTmpParameter;
998     }
999     double aPntParameter = aStartParameter + (anEndParameter - aStartParameter) / 3.0;
1000     aCirc->D0(aPntParameter, thePoint);
1001   }
1002 }
1003
1004 double getProjectionDistance(const FeaturePtr theFeature,
1005                              const std::shared_ptr<GeomAPI_Pnt2d> thePoint)
1006 {
1007   std::shared_ptr<GeomAPI_Pnt2d> aProjectPnt;
1008   if(theFeature->getKind() == SketchPlugin_Line::ID()) {
1009     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1010       theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
1011     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1012       theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
1013     std::shared_ptr<GeomAPI_Lin2d> aLin(new GeomAPI_Lin2d(aPntStart, aPntEnd));
1014     aProjectPnt = aLin->project(thePoint);
1015   } else {
1016     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1017       theFeature->attribute(SketchPlugin_Arc::START_ID()))->pnt();
1018     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1019       theFeature->attribute(SketchPlugin_Arc::END_ID()))->pnt();
1020     std::shared_ptr<GeomAPI_Pnt2d> aCenterPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
1021       theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
1022     std::shared_ptr<GeomAPI_Circ2d> aCirc(new GeomAPI_Circ2d(aCenterPnt, aPntStart));
1023     aProjectPnt = aCirc->project(thePoint);
1024   }
1025   if(aProjectPnt.get()) {
1026     return aProjectPnt->distance(thePoint);
1027   }
1028   return -1;
1029 }
1030
1031 std::set<FeaturePtr> getCoincides(const FeaturePtr& theConstraintCoincidence)
1032 {
1033   std::set<FeaturePtr> aCoincides;
1034
1035   SketchPlugin_Tools::findCoincidences(theConstraintCoincidence,
1036                                        SketchPlugin_ConstraintCoincidence::ENTITY_A(),
1037                                        aCoincides);
1038   SketchPlugin_Tools::findCoincidences(theConstraintCoincidence,
1039                                        SketchPlugin_ConstraintCoincidence::ENTITY_B(),
1040                                        aCoincides);
1041
1042   // Remove points from set of coincides.
1043   std::set<FeaturePtr> aNewSetOfCoincides;
1044   for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
1045     if((*anIt)->getKind() == SketchPlugin_Line::ID() ||
1046         (*anIt)->getKind() == SketchPlugin_Arc::ID() ) {
1047       aNewSetOfCoincides.insert(*anIt);
1048     }
1049   }
1050   aCoincides = aNewSetOfCoincides;
1051
1052   // If we still have more than two coincides remove auxilary entities from set of coincides.
1053   if(aCoincides.size() > 2) {
1054     aNewSetOfCoincides.clear();
1055     for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
1056       if(!(*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
1057         aNewSetOfCoincides.insert(*anIt);
1058       }
1059     }
1060     aCoincides = aNewSetOfCoincides;
1061   }
1062
1063   return aCoincides;
1064 }