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