Salome HOME
9507cad1a9970b0b557863383d559d498b114031
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Fillet.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "SketchPlugin_Fillet.h"
21
22 #include "SketchPlugin_Arc.h"
23 #include "SketchPlugin_Line.h"
24 #include "SketchPlugin_Point.h"
25 #include "SketchPlugin_Sketch.h"
26 #include "SketchPlugin_ConstraintDistance.h"
27 #include "SketchPlugin_ConstraintEqual.h"
28 #include "SketchPlugin_ConstraintCoincidence.h"
29 #include "SketchPlugin_ConstraintLength.h"
30 #include "SketchPlugin_ConstraintMiddle.h"
31 #include "SketchPlugin_ConstraintTangent.h"
32 #include "SketchPlugin_ConstraintRadius.h"
33 #include "SketchPlugin_Tools.h"
34
35 #include <ModelAPI_AttributeDouble.h>
36 #include <ModelAPI_AttributeInteger.h>
37 #include <ModelAPI_AttributeRefAttr.h>
38 #include <ModelAPI_Data.h>
39 #include <ModelAPI_Events.h>
40 #include <ModelAPI_Session.h>
41 #include <ModelAPI_Tools.h>
42 #include <ModelAPI_Validator.h>
43
44 #include <GeomAlgoAPI_Circ2dBuilder.h>
45 #include <GeomAlgoAPI_EdgeBuilder.h>
46
47 #include <GeomAPI_Circ2d.h>
48 #include <GeomAPI_Dir2d.h>
49 #include <GeomAPI_Lin2d.h>
50 #include <GeomAPI_Pnt2d.h>
51 #include <GeomAPI_XY.h>
52
53 #include <GeomDataAPI_Point2D.h>
54
55 #include <Events_Loop.h>
56
57 #include <math.h>
58
59 const double tolerance = 1.e-7;
60 const double paramTolerance = 1.e-4;
61 const double PI = 3.141592653589793238463;
62
63 /// \brief Attract specified point on theNewArc to the attribute of theFeature
64 static void recalculateAttributes(FeaturePtr theNewArc, const std::string& theNewArcAttribute,
65   FeaturePtr theFeature, const std::string& theFeatureAttribute);
66
67
68 /// \brief Calculate radius of a fillet.
69 ///        It should not be greater than 1/3 of shortest edge length.
70 static double calculateFilletRadius(FeaturePtr theFilletFeatures[2]);
71
72 /// \brief Calculates center of fillet arc and coordinates of tangency points
73 static void calculateFilletCenter(FeaturePtr theFilletFeatures[2],
74                                   double theFilletRadius,
75                                   const std::shared_ptr<GeomAPI_Ax3>& theSketchPlane,
76                                   std::shared_ptr<GeomAPI_XY>& theCenter,
77                                   std::shared_ptr<GeomAPI_XY>& theTangentA,
78                                   std::shared_ptr<GeomAPI_XY>& theTangentB);
79
80 static std::set<FeaturePtr> findFeaturesToRemove(const FeaturePtr theFeature,
81                                                  const AttributePtr theAttribute);
82
83 SketchPlugin_Fillet::SketchPlugin_Fillet()
84 : myFilletCreated(false), myIsReversed(false)
85 {
86   myIsNotInversed[0] = myIsNotInversed[1] = true;
87 }
88
89 void SketchPlugin_Fillet::initAttributes()
90 {
91   data()->addAttribute(FILLET_POINT_ID(), ModelAPI_AttributeRefAttr::typeId());
92 }
93
94 void SketchPlugin_Fillet::execute()
95 {
96   // Wait all constraints being created, then send update events
97   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
98   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
99   if (isUpdateFlushed)
100     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
101
102   // set flag here to avoid building Fillet presentation if "Redisplay" event appears
103   myFilletCreated = true;
104
105   // create feature for fillet arc
106   FeaturePtr aFilletArc = createFilletArc();
107   if (!aFilletArc) {
108     setError("Error: unable to create a fillet arc.");
109     return;
110   }
111
112   // collect features referred to the edges participating in fillet
113   AttributePoint2DPtr aFilletPoints[2];
114   int aFeatInd[2];
115   int anAttrInd[2];
116   std::set<FeaturePtr> aFeaturesToBeRemoved;
117   for (int i = 0; i < 2; ++i) {
118     bool isFirstIndex = (i == 0);
119     aFeatInd[i] = myIsReversed == isFirstIndex ? 1 : 0;
120     anAttrInd[i] = (myIsReversed == isFirstIndex ? 2 : 0) + (myIsNotInversed[aFeatInd[i]] ? 0 : 1);
121     aFilletPoints[i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
122         myBaseFeatures[aFeatInd[i]]->attribute(myFeatAttributes[anAttrInd[i]]));
123     std::set<FeaturePtr> aRemove =
124         findFeaturesToRemove(myBaseFeatures[aFeatInd[i]], aFilletPoints[i]);
125     aFeaturesToBeRemoved.insert(aRemove.begin(), aRemove.end());
126   }
127
128   // keep "distance" constraints and remove all other references
129   removeReferencesButKeepDistances(aFeaturesToBeRemoved, aFilletPoints);
130
131   // Update fillet edges.
132   recalculateAttributes(aFilletArc, SketchPlugin_Arc::START_ID(),
133                         myBaseFeatures[aFeatInd[0]], myFeatAttributes[anAttrInd[0]]);
134   recalculateAttributes(aFilletArc, SketchPlugin_Arc::END_ID(),
135                         myBaseFeatures[aFeatInd[1]], myFeatAttributes[anAttrInd[1]]);
136
137   FeaturePtr aConstraint;
138
139   // Create coincidence features.
140   aConstraint = SketchPlugin_Tools::createConstraintAttrAttr(sketch(),
141                     SketchPlugin_ConstraintCoincidence::ID(),
142                     aFilletArc->attribute(SketchPlugin_Arc::START_ID()),
143                     myBaseFeatures[aFeatInd[0]]->attribute(myFeatAttributes[anAttrInd[0]]));
144   ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
145   aConstraint = SketchPlugin_Tools::createConstraintAttrAttr(sketch(),
146                     SketchPlugin_ConstraintCoincidence::ID(),
147                     aFilletArc->attribute(SketchPlugin_Arc::END_ID()),
148                     myBaseFeatures[aFeatInd[1]]->attribute(myFeatAttributes[anAttrInd[1]]));
149   ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
150
151   // Create tangent features.
152   for (int i = 0; i < 2; i++) {
153     aConstraint = SketchPlugin_Tools::createConstraintObjectObject(sketch(),
154                       SketchPlugin_ConstraintTangent::ID(),
155                       aFilletArc->lastResult(),
156                       myBaseFeatures[i]->lastResult());
157     aConstraint->execute();
158     ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
159   }
160
161   // Send events to update the sub-features by the solver.
162   if (isUpdateFlushed)
163     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
164 }
165
166 AISObjectPtr SketchPlugin_Fillet::getAISObject(AISObjectPtr thePrevious)
167 {
168   if(myFilletCreated) {
169     return AISObjectPtr();
170   }
171
172   SketchPlugin_Sketch* aSketch = sketch();
173   if(!aSketch) {
174     return AISObjectPtr();
175   }
176
177   if (!calculateFilletParameters())
178     return AISObjectPtr();
179
180   // Create arc for presentation.
181   std::shared_ptr<GeomAPI_Pnt> aCenterPnt(aSketch->to3D(myCenterXY->x(), myCenterXY->y()));
182   std::shared_ptr<GeomAPI_Pnt> aTangentPnt1(aSketch->to3D(myTangentXY1->x(),
183                                                           myTangentXY1->y()));
184   std::shared_ptr<GeomAPI_Pnt> aTangentPnt2(aSketch->to3D(myTangentXY2->x(),
185                                                           myTangentXY2->y()));
186   std::shared_ptr<GeomDataAPI_Dir> aNDir = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
187     aSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
188   std::shared_ptr<GeomAPI_Shape> anArcShape =
189       GeomAlgoAPI_EdgeBuilder::lineCircleArc(aCenterPnt, aTangentPnt1, aTangentPnt2, aNDir->dir());
190
191   AISObjectPtr anAISObject = thePrevious;
192   if(!anAISObject.get()) {
193     anAISObject = AISObjectPtr(new GeomAPI_AISObject);
194   }
195   anAISObject->createShape(anArcShape);
196   bool isAxiliary = false;
197   AttributeBooleanPtr aAttr = boolean(AUXILIARY_ID());
198   if (aAttr.get())
199     isAxiliary = aAttr->value();
200   SketchPlugin_Tools::customizeFeaturePrs(anAISObject, isAxiliary);
201   return anAISObject;
202 }
203
204 bool SketchPlugin_Fillet::calculateFilletParameters()
205 {
206   // Get fillet point.
207   AttributeRefAttrPtr aPointRefAttr = refattr(FILLET_POINT_ID());
208   if (!aPointRefAttr->isInitialized() || aPointRefAttr->isObject())
209     return false;
210   std::shared_ptr<GeomDataAPI_Point2D> aFilletPoint2D =
211     std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aPointRefAttr->attr());
212   if (!aFilletPoint2D.get())
213     return false;
214
215   std::set<AttributePoint2DPtr> aCoincidentPoints =
216       SketchPlugin_Tools::findPointsCoincidentToPoint(aFilletPoint2D);
217   std::set<FeaturePtr> aFilletFeatures;
218   for (std::set<AttributePoint2DPtr>::iterator aCPIt = aCoincidentPoints.begin();
219        aCPIt != aCoincidentPoints.end(); ++aCPIt) {
220     std::shared_ptr<SketchPlugin_Feature> anOwner =
221         std::dynamic_pointer_cast<SketchPlugin_Feature>(
222         ModelAPI_Feature::feature((*aCPIt)->owner()));
223     if (anOwner && !anOwner->isExternal())
224       aFilletFeatures.insert(anOwner);
225   }
226   if (aFilletFeatures.size() != 2) {
227     setError("Error: Selected point does not have two suitable edges for fillet.");
228     return false;
229   }
230
231   std::set<FeaturePtr>::iterator aFIt = aFilletFeatures.begin();
232   myBaseFeatures[0] = *aFIt;
233   myBaseFeatures[1] = *(++aFIt);
234
235   std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
236   double aRadius = calculateFilletRadius(myBaseFeatures);
237
238   // Calculate arc attributes.
239   static const int aNbFeatures = 2;
240   // First pair of points relate to first feature, second pair -  to second.
241   std::shared_ptr<GeomAPI_Pnt2d> aStartEndPnt[aNbFeatures * 2];
242   for (int i = 0; i < aNbFeatures; i++) {
243     std::string aStartAttr, aEndAttr;
244     if (myBaseFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
245       aStartAttr = SketchPlugin_Line::START_ID();
246       aEndAttr = SketchPlugin_Line::END_ID();
247     } else if (myBaseFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
248       aStartAttr = SketchPlugin_Arc::START_ID();
249       aEndAttr = SketchPlugin_Arc::END_ID();
250     } else { // Wrong argument.
251       setError("Error: One of the points has wrong coincide feature");
252       return false;
253     }
254     myFeatAttributes[2*i] = aStartAttr;
255     aStartEndPnt[2*i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
256       myBaseFeatures[i]->attribute(aStartAttr))->pnt();
257     myFeatAttributes[2*i+1] = aEndAttr;
258     aStartEndPnt[2*i+1] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
259       myBaseFeatures[i]->attribute(aEndAttr))->pnt();
260   }
261   for (int aFeatInd = 0; aFeatInd < aNbFeatures; aFeatInd++) {
262     for (int j = 0; j < 2; j++) // loop on start-end of each feature
263       if (aStartEndPnt[aFeatInd * aNbFeatures + j]->distance(aFilletPnt2d) < 1.e-10) {
264         myIsNotInversed[aFeatInd] = (j==0);
265         break;
266       }
267   }
268
269   std::shared_ptr<GeomAPI_Ax3> aSketchPlane = SketchPlugin_Sketch::plane(sketch());
270   calculateFilletCenter(myBaseFeatures, aRadius, aSketchPlane,
271                         myCenterXY, myTangentXY1, myTangentXY2);
272
273   // Tangent directions of the features in coincident point.
274   std::shared_ptr<GeomAPI_Dir2d> aTangentDir[aNbFeatures];
275   for (int i = 0; i < aNbFeatures; i++) {
276     std::shared_ptr<GeomAPI_XY> aDir;
277     if (myBaseFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
278       aDir = aStartEndPnt[2*i+1]->xy()->decreased(aStartEndPnt[2*i]->xy());
279       if (!myIsNotInversed[i])
280         aDir = aDir->multiplied(-1.0);
281     } else if (myBaseFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
282       std::shared_ptr<GeomAPI_Pnt2d> aCenterPoint =
283         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
284         myBaseFeatures[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
285       aDir = myIsNotInversed[i] ? aStartEndPnt[2*i]->xy() : aStartEndPnt[2*i+1]->xy();
286       aDir = aDir->decreased(aCenterPoint->xy());
287
288       double x = aDir->x();
289       double y = aDir->y();
290       aDir->setX(-y);
291       aDir->setY(x);
292       if (myIsNotInversed[i] ==
293           std::dynamic_pointer_cast<SketchPlugin_Arc>(myBaseFeatures[i])->isReversed())
294         aDir = aDir->multiplied(-1.0);
295     }
296     aTangentDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aDir));
297   }
298
299   // By default, the start point of fillet arc is connected to FeatureA,
300   // and the end point - to FeatureB. But when the angle between TangentDirA and
301   // TangentDirB greater 180 degree, the sequaence of features need to be reversed.
302   double cosBA = aTangentDir[0]->cross(aTangentDir[1]); // cos(B-A),
303   // where A and B - angles between corresponding tanget direction and the X axis
304   myIsReversed = cosBA > 0.0;
305
306   if(myIsReversed) {
307     std::shared_ptr<GeomAPI_XY> aTmp = myTangentXY1;
308     myTangentXY1 = myTangentXY2;
309     myTangentXY2 = aTmp;
310   }
311   return true;
312 }
313
314 FeaturePtr SketchPlugin_Fillet::createFilletArc()
315 {
316   // Calculate Fillet parameters if does not yet
317   if (!myBaseFeatures[0] || !myBaseFeatures[1])
318     calculateFilletParameters();
319
320   // fix for issue #2810 (sometimes, myCenterXY is NULL, fillet should report an error)
321   if (!myCenterXY)
322     return FeaturePtr();
323
324   // Create arc feature.
325   FeaturePtr aFilletArc = sketch()->addFeature(SketchPlugin_Arc::ID());
326
327   // Set arc attributes.
328   bool aWasBlocked = aFilletArc->data()->blockSendAttributeUpdated(true);
329   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
330       aFilletArc->attribute(SketchPlugin_Arc::CENTER_ID()))->setValue(myCenterXY->x(),
331                                                                       myCenterXY->y());
332   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint =
333       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
334           aFilletArc->attribute(SketchPlugin_Arc::START_ID()));
335   std::shared_ptr<GeomDataAPI_Point2D> aEndPoint =
336       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
337           aFilletArc->attribute(SketchPlugin_Arc::END_ID()));
338   if(aStartPoint->isInitialized() && aEndPoint->isInitialized()
339       && (aStartPoint->pnt()->xy()->distance(myTangentXY1) > tolerance
340       || aEndPoint->pnt()->xy()->distance(myTangentXY2) > tolerance)) {
341     std::dynamic_pointer_cast<SketchPlugin_Arc>(aFilletArc)->setReversed(false);
342   }
343   aStartPoint->setValue(myTangentXY1->x(), myTangentXY1->y());
344   aEndPoint->setValue(myTangentXY2->x(), myTangentXY2->y());
345   aFilletArc->data()->blockSendAttributeUpdated(aWasBlocked);
346   aFilletArc->execute();
347
348   return aFilletArc;
349 }
350
351 FeaturePtr SketchPlugin_Fillet::createFilletApex(const GeomPnt2dPtr& theCoordinates)
352 {
353   FeaturePtr anApex = sketch()->addFeature(SketchPlugin_Point::ID());
354   AttributePoint2DPtr aCoord = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
355       anApex->attribute(SketchPlugin_Point::COORD_ID()));
356   aCoord->setValue(theCoordinates);
357   anApex->boolean(SketchPlugin_Point::AUXILIARY_ID())->setValue(true);
358
359   // additional coincidence constraints
360   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
361   FeaturePtr aConstraint;
362   for (int i = 0; i < 2; i++) {
363     aConstraint = SketchPlugin_Tools::createConstraintAttrObject(sketch(),
364                       SketchPlugin_ConstraintCoincidence::ID(),
365                       aCoord,
366                       myBaseFeatures[i]->lastResult());
367     aConstraint->execute();
368     ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
369   }
370
371   return anApex;
372 }
373
374 struct Length {
375   AttributePtr myPoints[2];
376   std::string myValueText;
377   double myValueDouble;
378   GeomPnt2dPtr myFlyoutPoint;
379   int myLocationType;
380 };
381
382 void SketchPlugin_Fillet::removeReferencesButKeepDistances(
383     std::set<FeaturePtr>& theFeaturesToRemove,
384     const AttributePoint2DPtr theFilletPoints[2])
385 {
386   FeaturePtr aFilletApex;
387   std::list<Length> aLengthToDistance;
388
389   std::set<FeaturePtr>::iterator aFeat = theFeaturesToRemove.begin();
390   while (aFeat != theFeaturesToRemove.end()) {
391     std::shared_ptr<SketchPlugin_ConstraintDistance> aDistance =
392         std::dynamic_pointer_cast<SketchPlugin_ConstraintDistance>(*aFeat);
393     if (aDistance) {
394       if (!aFilletApex)
395         aFilletApex = createFilletApex(theFilletPoints[0]->pnt());
396       // update attributes of distance constraints
397       bool isUpdated = false;
398       for (int attrInd = 0; attrInd < CONSTRAINT_ATTR_SIZE && !isUpdated; ++attrInd) {
399         AttributeRefAttrPtr aRefAttr =
400             aDistance->refattr(SketchPlugin_Constraint::ATTRIBUTE(attrInd));
401         if (aRefAttr && !aRefAttr->isObject() &&
402            (aRefAttr->attr() == theFilletPoints[0] || aRefAttr->attr() == theFilletPoints[1])) {
403           aRefAttr->setAttr(aFilletApex->attribute(SketchPlugin_Point::COORD_ID()));
404           isUpdated = true;
405         }
406       }
407       // avoid distance from removing if it is updated
408       std::set<FeaturePtr>::iterator aKeepIt = aFeat++;
409       if (isUpdated)
410         theFeaturesToRemove.erase(aKeepIt);
411
412     } else {
413       std::shared_ptr<SketchPlugin_ConstraintLength> aLength =
414           std::dynamic_pointer_cast<SketchPlugin_ConstraintLength>(*aFeat);
415       if (aLength) {
416         if (!aFilletApex)
417           aFilletApex = createFilletApex(theFilletPoints[0]->pnt());
418         // remove Length, but create new distance constraint
419         AttributeRefAttrPtr aRefAttr =
420           aLength->refattr(SketchPlugin_Constraint::ENTITY_A());
421         FeaturePtr aLine = ModelAPI_Feature::feature(aRefAttr->object());
422         if (aLine) {
423           aLengthToDistance.push_back(Length());
424           Length& aNewLength = aLengthToDistance.back();
425           // main attrbutes
426           for (int i = 0; i < 2; ++i) {
427             AttributePtr anAttr = aLine->attribute(
428                 i == 0 ? SketchPlugin_Line::START_ID() : SketchPlugin_Line::END_ID());
429             if (anAttr == theFilletPoints[0] || anAttr == theFilletPoints[1])
430               aNewLength.myPoints[i] = aFilletApex->attribute(SketchPlugin_Point::COORD_ID());
431             else
432               aNewLength.myPoints[i] = anAttr;
433           }
434           // value
435           AttributeDoublePtr aValue = aLength->real(SketchPlugin_Constraint::VALUE());
436           aNewLength.myValueDouble = aValue->value();
437           aNewLength.myValueText = aValue->text();
438           // auxiliary attributes
439           AttributePoint2DPtr aFlyoutAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
440               aLength->attribute(SketchPlugin_ConstraintLength::FLYOUT_VALUE_PNT()));
441           if (aFlyoutAttr && aFlyoutAttr->isInitialized())
442             aNewLength.myFlyoutPoint = SketchPlugin_Tools::flyoutPointCoordinates(aLength);
443           AttributeIntegerPtr aLocationAttr =
444               aLength->integer(SketchPlugin_ConstraintLength::LOCATION_TYPE_ID());
445           if (aLocationAttr && aLocationAttr->isInitialized())
446             aNewLength.myLocationType = aLocationAttr->value();
447           else
448             aNewLength.myLocationType = -1;
449         }
450       }
451
452       ++aFeat;
453     }
454   }
455
456   // remove references
457   ModelAPI_Tools::removeFeaturesAndReferences(theFeaturesToRemove);
458   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
459
460   // restore Length constraints as point-point distances
461   FeaturePtr aConstraint;
462   std::list<Length>::iterator anIt = aLengthToDistance.begin();
463   for (; anIt != aLengthToDistance.end(); ++anIt) {
464     aConstraint = SketchPlugin_Tools::createConstraintAttrAttr(sketch(),
465         SketchPlugin_ConstraintDistance::ID(), anIt->myPoints[0], anIt->myPoints[1]);
466     // set value
467     AttributeDoublePtr aValue = aConstraint->real(SketchPlugin_Constraint::VALUE());
468     if (anIt->myValueText.empty())
469       aValue->setValue(anIt->myValueDouble);
470     else
471       aValue->setText(anIt->myValueText);
472     // set flyout point if exists
473     if (anIt->myFlyoutPoint) {
474       AttributePoint2DPtr aFlyoutAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
475           aConstraint->attribute(SketchPlugin_ConstraintDistance::FLYOUT_VALUE_PNT()));
476       aFlyoutAttr->setValue(anIt->myFlyoutPoint);
477     }
478     // set location type if initialized
479     if (anIt->myLocationType >= 0) {
480       AttributeIntegerPtr aLocationType =
481           aConstraint->integer(SketchPlugin_ConstraintDistance::LOCATION_TYPE_ID());
482       aLocationType->setValue(anIt->myLocationType);
483     }
484     aConstraint->execute();
485     ModelAPI_EventCreator::get()->sendUpdated(aConstraint,
486         Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
487   }
488 }
489
490 // =========   Auxiliary functions   =================
491 void recalculateAttributes(FeaturePtr theNewArc,  const std::string& theNewArcAttribute,
492                            FeaturePtr theFeature, const std::string& theFeatureAttribute)
493 {
494   std::shared_ptr<GeomAPI_Pnt2d> anArcPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
495       theNewArc->attribute(theNewArcAttribute))->pnt();
496   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
497       theFeature->attribute(theFeatureAttribute))->setValue(anArcPoint->x(), anArcPoint->y());
498 }
499
500 static std::shared_ptr<GeomAPI_Pnt2d> toPoint(const AttributePtr& theAttribute)
501 {
502   std::shared_ptr<GeomAPI_Pnt2d> aPoint;
503   AttributePoint2DPtr aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
504   if (aPointAttr)
505     aPoint = aPointAttr->pnt();
506   return aPoint;
507 }
508
509 static std::shared_ptr<GeomAPI_Lin2d> toLine(const FeaturePtr& theFeature)
510 {
511   std::shared_ptr<GeomAPI_Lin2d> aLine;
512   if (theFeature->getKind() == SketchPlugin_Line::ID()) {
513     std::shared_ptr<GeomAPI_Pnt2d> aStart =
514         toPoint( theFeature->attribute(SketchPlugin_Line::START_ID()) );
515     std::shared_ptr<GeomAPI_Pnt2d> aEnd =
516         toPoint( theFeature->attribute(SketchPlugin_Line::END_ID()) );
517     aLine = std::shared_ptr<GeomAPI_Lin2d>(new GeomAPI_Lin2d(aStart, aEnd));
518   }
519   return aLine;
520 }
521
522 static std::shared_ptr<GeomAPI_Circ2d> toCircle(const FeaturePtr& theFeature)
523 {
524   std::shared_ptr<GeomAPI_Circ2d> aCircle;
525   if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
526     std::shared_ptr<GeomAPI_Pnt2d> aCenter =
527         toPoint( theFeature->attribute(SketchPlugin_Arc::CENTER_ID()) );
528     std::shared_ptr<GeomAPI_Pnt2d> aStart =
529         toPoint( theFeature->attribute(SketchPlugin_Arc::START_ID()) );
530     aCircle = std::shared_ptr<GeomAPI_Circ2d>(new GeomAPI_Circ2d(aCenter, aStart));
531   }
532   return aCircle;
533 }
534
535
536 void calculateFilletCenter(FeaturePtr theFilletFeatures[2],
537                            double theFilletRadius,
538                            const std::shared_ptr<GeomAPI_Ax3>& theSketchPlane,
539                            std::shared_ptr<GeomAPI_XY>& theCenter,
540                            std::shared_ptr<GeomAPI_XY>& theTangentA,
541                            std::shared_ptr<GeomAPI_XY>& theTangentB)
542 {
543   GeomShapePtr aShapeA = theFilletFeatures[0]->lastResult()->shape();
544   GeomShapePtr aShapeB = theFilletFeatures[1]->lastResult()->shape();
545
546   GeomAlgoAPI_Circ2dBuilder aCircBuilder(theSketchPlane);
547   aCircBuilder.addTangentCurve(aShapeA);
548   aCircBuilder.addTangentCurve(aShapeB);
549   aCircBuilder.setRadius(theFilletRadius);
550
551   std::shared_ptr<GeomAPI_Circ2d> aFilletCircle = aCircBuilder.circle();
552   if (!aFilletCircle)
553     return;
554
555   theCenter = aFilletCircle->center()->xy();
556   // tangent points
557   std::shared_ptr<GeomAPI_Pnt2d> aTgPoints[2];
558   for (int i = 0; i < 2; ++i) {
559     std::shared_ptr<GeomAPI_Circ2d> aCircle = toCircle(theFilletFeatures[i]);
560     if (aCircle)
561       aTgPoints[i] = aCircle->project(aFilletCircle->center());
562     else {
563       std::shared_ptr<GeomAPI_Lin2d> aLine = toLine(theFilletFeatures[i]);
564       if (aLine)
565         aTgPoints[i] = aLine->project(aFilletCircle->center());
566     }
567   }
568   theTangentA = aTgPoints[0]->xy();
569   theTangentB = aTgPoints[1]->xy();
570 }
571
572 double calculateFilletRadius(FeaturePtr theFilletFeatures[2])
573 {
574   double aLengths[2] = { 0, 0 };
575   for (int i = 0; i < 2; ++i) {
576     GeomShapePtr aShape = theFilletFeatures[i]->lastResult()->shape();
577     std::shared_ptr<GeomAPI_Edge> anEdge = std::dynamic_pointer_cast<GeomAPI_Edge>(aShape);
578     if (anEdge)
579       aLengths[i] = anEdge->length();
580   }
581   return (aLengths[0] < aLengths[1] ? aLengths[0] : aLengths[1]) / 6.0;
582 }
583
584 std::set<FeaturePtr> findFeaturesToRemove(const FeaturePtr theFeature,
585                                           const AttributePtr theAttribute) {
586   std::set<FeaturePtr> aFeaturesToBeRemoved;
587   std::set<AttributePtr> aRefs = theFeature->data()->refsToMe();
588   std::list<ResultPtr> aResults = theFeature->results();
589   for(std::list<ResultPtr>::const_iterator aResultsIt = aResults.cbegin();
590       aResultsIt != aResults.cend();
591       ++aResultsIt) {
592     ResultPtr aResult = *aResultsIt;
593     std::set<AttributePtr> aResultRefs = aResult->data()->refsToMe();
594     aRefs.insert(aResultRefs.begin(), aResultRefs.end());
595   }
596   for(std::set<AttributePtr>::const_iterator anIt = aRefs.cbegin();
597     anIt != aRefs.cend();
598     ++anIt) {
599     std::shared_ptr<ModelAPI_Attribute> anAttr = (*anIt);
600     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
601     if(aFeature->getKind() == SketchPlugin_Fillet::ID()) {
602       continue;
603     }
604     if(aFeature->getKind() == SketchPlugin_ConstraintLength::ID()
605         || aFeature->getKind() == SketchPlugin_ConstraintEqual::ID()
606         || aFeature->getKind() == SketchPlugin_ConstraintMiddle::ID()) {
607       aFeaturesToBeRemoved.insert(aFeature);
608     } else {
609       std::list<AttributePtr> anAttrs =
610           aFeature->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
611       for(std::list<AttributePtr>::const_iterator aRefAttrsIt = anAttrs.cbegin();
612           aRefAttrsIt != anAttrs.cend();
613           ++aRefAttrsIt) {
614         AttributeRefAttrPtr anAttrRefAttr =
615           std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*aRefAttrsIt);
616         if(anAttrRefAttr.get() && anAttrRefAttr->attr() == theAttribute) {
617           aFeaturesToBeRemoved.insert(aFeature);
618         }
619       }
620     }
621   }
622   return aFeaturesToBeRemoved;
623 }