Salome HOME
Copyright update 2020
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Fillet.cpp
1 // Copyright (C) 2014-2020  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   // remove auxilary entities from set of coincident features
227   if (aFilletFeatures.size() > 2) {
228     std::set<FeaturePtr>::iterator anIt = aFilletFeatures.begin();
229     while (anIt != aFilletFeatures.end()) {
230       if ((*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
231         std::set<FeaturePtr>::iterator aRemoveIt = anIt++;
232         aFilletFeatures.erase(aRemoveIt);
233       }
234       else
235         ++anIt;
236     }
237   }
238   if (aFilletFeatures.size() != 2) {
239     setError("Error: Selected point does not have two suitable edges for fillet.");
240     return false;
241   }
242
243   std::set<FeaturePtr>::iterator aFIt = aFilletFeatures.begin();
244   myBaseFeatures[0] = *aFIt;
245   myBaseFeatures[1] = *(++aFIt);
246
247   std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
248   double aRadius = calculateFilletRadius(myBaseFeatures);
249
250   // Calculate arc attributes.
251   static const int aNbFeatures = 2;
252   // First pair of points relate to first feature, second pair -  to second.
253   std::shared_ptr<GeomAPI_Pnt2d> aStartEndPnt[aNbFeatures * 2];
254   for (int i = 0; i < aNbFeatures; i++) {
255     std::string aStartAttr, aEndAttr;
256     if (myBaseFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
257       aStartAttr = SketchPlugin_Line::START_ID();
258       aEndAttr = SketchPlugin_Line::END_ID();
259     } else if (myBaseFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
260       aStartAttr = SketchPlugin_Arc::START_ID();
261       aEndAttr = SketchPlugin_Arc::END_ID();
262     } else { // Wrong argument.
263       setError("Error: One of the points has wrong coincide feature");
264       return false;
265     }
266     myFeatAttributes[2*i] = aStartAttr;
267     aStartEndPnt[2*i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
268       myBaseFeatures[i]->attribute(aStartAttr))->pnt();
269     myFeatAttributes[2*i+1] = aEndAttr;
270     aStartEndPnt[2*i+1] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
271       myBaseFeatures[i]->attribute(aEndAttr))->pnt();
272   }
273   for (int aFeatInd = 0; aFeatInd < aNbFeatures; aFeatInd++) {
274     for (int j = 0; j < 2; j++) // loop on start-end of each feature
275       if (aStartEndPnt[aFeatInd * aNbFeatures + j]->distance(aFilletPnt2d) < 1.e-10) {
276         myIsNotInversed[aFeatInd] = (j==0);
277         break;
278       }
279   }
280
281   std::shared_ptr<GeomAPI_Ax3> aSketchPlane = SketchPlugin_Sketch::plane(sketch());
282   calculateFilletCenter(myBaseFeatures, aRadius, aSketchPlane,
283                         myCenterXY, myTangentXY1, myTangentXY2);
284
285   // Tangent directions of the features in coincident point.
286   std::shared_ptr<GeomAPI_Dir2d> aTangentDir[aNbFeatures];
287   for (int i = 0; i < aNbFeatures; i++) {
288     std::shared_ptr<GeomAPI_XY> aDir;
289     if (myBaseFeatures[i]->getKind() == SketchPlugin_Line::ID()) {
290       aDir = aStartEndPnt[2*i+1]->xy()->decreased(aStartEndPnt[2*i]->xy());
291       if (!myIsNotInversed[i])
292         aDir = aDir->multiplied(-1.0);
293     } else if (myBaseFeatures[i]->getKind() == SketchPlugin_Arc::ID()) {
294       std::shared_ptr<GeomAPI_Pnt2d> aCenterPoint =
295         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
296         myBaseFeatures[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
297       aDir = myIsNotInversed[i] ? aStartEndPnt[2*i]->xy() : aStartEndPnt[2*i+1]->xy();
298       aDir = aDir->decreased(aCenterPoint->xy());
299
300       double x = aDir->x();
301       double y = aDir->y();
302       aDir->setX(-y);
303       aDir->setY(x);
304       if (myIsNotInversed[i] ==
305           std::dynamic_pointer_cast<SketchPlugin_Arc>(myBaseFeatures[i])->isReversed())
306         aDir = aDir->multiplied(-1.0);
307     }
308     aTangentDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aDir));
309   }
310
311   // By default, the start point of fillet arc is connected to FeatureA,
312   // and the end point - to FeatureB. But when the angle between TangentDirA and
313   // TangentDirB greater 180 degree, the sequaence of features need to be reversed.
314   double cosBA = aTangentDir[0]->cross(aTangentDir[1]); // cos(B-A),
315   // where A and B - angles between corresponding tanget direction and the X axis
316   myIsReversed = cosBA > 0.0;
317
318   if(myIsReversed) {
319     std::shared_ptr<GeomAPI_XY> aTmp = myTangentXY1;
320     myTangentXY1 = myTangentXY2;
321     myTangentXY2 = aTmp;
322   }
323   return true;
324 }
325
326 FeaturePtr SketchPlugin_Fillet::createFilletArc()
327 {
328   // Calculate Fillet parameters if does not yet
329   if (!myBaseFeatures[0] || !myBaseFeatures[1])
330     calculateFilletParameters();
331
332   // fix for issue #2810 (sometimes, myCenterXY is NULL, fillet should report an error)
333   if (!myCenterXY)
334     return FeaturePtr();
335
336   // Create arc feature.
337   FeaturePtr aFilletArc = sketch()->addFeature(SketchPlugin_Arc::ID());
338
339   // Set arc attributes.
340   bool aWasBlocked = aFilletArc->data()->blockSendAttributeUpdated(true);
341   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
342       aFilletArc->attribute(SketchPlugin_Arc::CENTER_ID()))->setValue(myCenterXY->x(),
343                                                                       myCenterXY->y());
344   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint =
345       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
346           aFilletArc->attribute(SketchPlugin_Arc::START_ID()));
347   std::shared_ptr<GeomDataAPI_Point2D> aEndPoint =
348       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
349           aFilletArc->attribute(SketchPlugin_Arc::END_ID()));
350   if(aStartPoint->isInitialized() && aEndPoint->isInitialized()
351       && (aStartPoint->pnt()->xy()->distance(myTangentXY1) > tolerance
352       || aEndPoint->pnt()->xy()->distance(myTangentXY2) > tolerance)) {
353     std::dynamic_pointer_cast<SketchPlugin_Arc>(aFilletArc)->setReversed(false);
354   }
355   aStartPoint->setValue(myTangentXY1->x(), myTangentXY1->y());
356   aEndPoint->setValue(myTangentXY2->x(), myTangentXY2->y());
357   aFilletArc->data()->blockSendAttributeUpdated(aWasBlocked);
358   aFilletArc->execute();
359
360   return aFilletArc;
361 }
362
363 FeaturePtr SketchPlugin_Fillet::createFilletApex(const GeomPnt2dPtr& theCoordinates)
364 {
365   FeaturePtr anApex = sketch()->addFeature(SketchPlugin_Point::ID());
366   AttributePoint2DPtr aCoord = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
367       anApex->attribute(SketchPlugin_Point::COORD_ID()));
368   aCoord->setValue(theCoordinates);
369   anApex->boolean(SketchPlugin_Point::AUXILIARY_ID())->setValue(true);
370
371   // additional coincidence constraints
372   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
373   FeaturePtr aConstraint;
374   for (int i = 0; i < 2; i++) {
375     aConstraint = SketchPlugin_Tools::createConstraintAttrObject(sketch(),
376                       SketchPlugin_ConstraintCoincidence::ID(),
377                       aCoord,
378                       myBaseFeatures[i]->lastResult());
379     aConstraint->execute();
380     ModelAPI_EventCreator::get()->sendUpdated(aConstraint, anUpdateEvent);
381   }
382
383   return anApex;
384 }
385
386 struct Length {
387   AttributePtr myPoints[2];
388   std::string myValueText;
389   double myValueDouble;
390   GeomPnt2dPtr myFlyoutPoint;
391   int myLocationType;
392 };
393
394 void SketchPlugin_Fillet::removeReferencesButKeepDistances(
395     std::set<FeaturePtr>& theFeaturesToRemove,
396     const AttributePoint2DPtr theFilletPoints[2])
397 {
398   FeaturePtr aFilletApex;
399   std::list<Length> aLengthToDistance;
400
401   std::set<FeaturePtr>::iterator aFeat = theFeaturesToRemove.begin();
402   while (aFeat != theFeaturesToRemove.end()) {
403     std::shared_ptr<SketchPlugin_ConstraintDistance> aDistance =
404         std::dynamic_pointer_cast<SketchPlugin_ConstraintDistance>(*aFeat);
405     if (aDistance) {
406       if (!aFilletApex)
407         aFilletApex = createFilletApex(theFilletPoints[0]->pnt());
408       // update attributes of distance constraints
409       bool isUpdated = false;
410       for (int attrInd = 0; attrInd < CONSTRAINT_ATTR_SIZE && !isUpdated; ++attrInd) {
411         AttributeRefAttrPtr aRefAttr =
412             aDistance->refattr(SketchPlugin_Constraint::ATTRIBUTE(attrInd));
413         if (aRefAttr && !aRefAttr->isObject() &&
414            (aRefAttr->attr() == theFilletPoints[0] || aRefAttr->attr() == theFilletPoints[1])) {
415           aRefAttr->setAttr(aFilletApex->attribute(SketchPlugin_Point::COORD_ID()));
416           isUpdated = true;
417         }
418       }
419       // avoid distance from removing if it is updated
420       std::set<FeaturePtr>::iterator aKeepIt = aFeat++;
421       if (isUpdated)
422         theFeaturesToRemove.erase(aKeepIt);
423
424     } else {
425       std::shared_ptr<SketchPlugin_ConstraintLength> aLength =
426           std::dynamic_pointer_cast<SketchPlugin_ConstraintLength>(*aFeat);
427       if (aLength) {
428         if (!aFilletApex)
429           aFilletApex = createFilletApex(theFilletPoints[0]->pnt());
430         // remove Length, but create new distance constraint
431         AttributeRefAttrPtr aRefAttr =
432           aLength->refattr(SketchPlugin_Constraint::ENTITY_A());
433         FeaturePtr aLine = ModelAPI_Feature::feature(aRefAttr->object());
434         if (aLine) {
435           aLengthToDistance.push_back(Length());
436           Length& aNewLength = aLengthToDistance.back();
437           // main attrbutes
438           for (int i = 0; i < 2; ++i) {
439             AttributePtr anAttr = aLine->attribute(
440                 i == 0 ? SketchPlugin_Line::START_ID() : SketchPlugin_Line::END_ID());
441             if (anAttr == theFilletPoints[0] || anAttr == theFilletPoints[1])
442               aNewLength.myPoints[i] = aFilletApex->attribute(SketchPlugin_Point::COORD_ID());
443             else
444               aNewLength.myPoints[i] = anAttr;
445           }
446           // value
447           AttributeDoublePtr aValue = aLength->real(SketchPlugin_Constraint::VALUE());
448           aNewLength.myValueDouble = aValue->value();
449           aNewLength.myValueText = aValue->text();
450           // auxiliary attributes
451           AttributePoint2DPtr aFlyoutAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
452               aLength->attribute(SketchPlugin_ConstraintLength::FLYOUT_VALUE_PNT()));
453           if (aFlyoutAttr && aFlyoutAttr->isInitialized())
454             aNewLength.myFlyoutPoint = SketchPlugin_Tools::flyoutPointCoordinates(aLength);
455           AttributeIntegerPtr aLocationAttr =
456               aLength->integer(SketchPlugin_ConstraintLength::LOCATION_TYPE_ID());
457           if (aLocationAttr && aLocationAttr->isInitialized())
458             aNewLength.myLocationType = aLocationAttr->value();
459           else
460             aNewLength.myLocationType = -1;
461         }
462       }
463
464       ++aFeat;
465     }
466   }
467
468   // remove references
469   ModelAPI_Tools::removeFeaturesAndReferences(theFeaturesToRemove);
470   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_DELETED));
471
472   // restore Length constraints as point-point distances
473   FeaturePtr aConstraint;
474   std::list<Length>::iterator anIt = aLengthToDistance.begin();
475   for (; anIt != aLengthToDistance.end(); ++anIt) {
476     aConstraint = SketchPlugin_Tools::createConstraintAttrAttr(sketch(),
477         SketchPlugin_ConstraintDistance::ID(), anIt->myPoints[0], anIt->myPoints[1]);
478     // set value
479     AttributeDoublePtr aValue = aConstraint->real(SketchPlugin_Constraint::VALUE());
480     if (anIt->myValueText.empty())
481       aValue->setValue(anIt->myValueDouble);
482     else
483       aValue->setText(anIt->myValueText);
484     // set flyout point if exists
485     if (anIt->myFlyoutPoint) {
486       AttributePoint2DPtr aFlyoutAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
487           aConstraint->attribute(SketchPlugin_ConstraintDistance::FLYOUT_VALUE_PNT()));
488       aFlyoutAttr->setValue(anIt->myFlyoutPoint);
489     }
490     // set location type if initialized
491     if (anIt->myLocationType >= 0) {
492       AttributeIntegerPtr aLocationType =
493           aConstraint->integer(SketchPlugin_ConstraintDistance::LOCATION_TYPE_ID());
494       aLocationType->setValue(anIt->myLocationType);
495     }
496     aConstraint->execute();
497     ModelAPI_EventCreator::get()->sendUpdated(aConstraint,
498         Events_Loop::eventByName(EVENT_OBJECT_UPDATED));
499   }
500 }
501
502 // =========   Auxiliary functions   =================
503 void recalculateAttributes(FeaturePtr theNewArc,  const std::string& theNewArcAttribute,
504                            FeaturePtr theFeature, const std::string& theFeatureAttribute)
505 {
506   std::shared_ptr<GeomAPI_Pnt2d> anArcPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
507       theNewArc->attribute(theNewArcAttribute))->pnt();
508   std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
509       theFeature->attribute(theFeatureAttribute))->setValue(anArcPoint->x(), anArcPoint->y());
510 }
511
512 static std::shared_ptr<GeomAPI_Pnt2d> toPoint(const AttributePtr& theAttribute)
513 {
514   std::shared_ptr<GeomAPI_Pnt2d> aPoint;
515   AttributePoint2DPtr aPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
516   if (aPointAttr)
517     aPoint = aPointAttr->pnt();
518   return aPoint;
519 }
520
521 static std::shared_ptr<GeomAPI_Lin2d> toLine(const FeaturePtr& theFeature)
522 {
523   std::shared_ptr<GeomAPI_Lin2d> aLine;
524   if (theFeature->getKind() == SketchPlugin_Line::ID()) {
525     std::shared_ptr<GeomAPI_Pnt2d> aStart =
526         toPoint( theFeature->attribute(SketchPlugin_Line::START_ID()) );
527     std::shared_ptr<GeomAPI_Pnt2d> aEnd =
528         toPoint( theFeature->attribute(SketchPlugin_Line::END_ID()) );
529     aLine = std::shared_ptr<GeomAPI_Lin2d>(new GeomAPI_Lin2d(aStart, aEnd));
530   }
531   return aLine;
532 }
533
534 static std::shared_ptr<GeomAPI_Circ2d> toCircle(const FeaturePtr& theFeature)
535 {
536   std::shared_ptr<GeomAPI_Circ2d> aCircle;
537   if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
538     std::shared_ptr<GeomAPI_Pnt2d> aCenter =
539         toPoint( theFeature->attribute(SketchPlugin_Arc::CENTER_ID()) );
540     std::shared_ptr<GeomAPI_Pnt2d> aStart =
541         toPoint( theFeature->attribute(SketchPlugin_Arc::START_ID()) );
542     aCircle = std::shared_ptr<GeomAPI_Circ2d>(new GeomAPI_Circ2d(aCenter, aStart));
543   }
544   return aCircle;
545 }
546
547
548 void calculateFilletCenter(FeaturePtr theFilletFeatures[2],
549                            double theFilletRadius,
550                            const std::shared_ptr<GeomAPI_Ax3>& theSketchPlane,
551                            std::shared_ptr<GeomAPI_XY>& theCenter,
552                            std::shared_ptr<GeomAPI_XY>& theTangentA,
553                            std::shared_ptr<GeomAPI_XY>& theTangentB)
554 {
555   GeomShapePtr aShapeA = theFilletFeatures[0]->lastResult()->shape();
556   GeomShapePtr aShapeB = theFilletFeatures[1]->lastResult()->shape();
557
558   GeomAlgoAPI_Circ2dBuilder aCircBuilder(theSketchPlane);
559   aCircBuilder.addTangentCurve(aShapeA);
560   aCircBuilder.addTangentCurve(aShapeB);
561   aCircBuilder.setRadius(theFilletRadius);
562
563   std::shared_ptr<GeomAPI_Circ2d> aFilletCircle = aCircBuilder.circle();
564   if (!aFilletCircle)
565     return;
566
567   theCenter = aFilletCircle->center()->xy();
568   // tangent points
569   std::shared_ptr<GeomAPI_Pnt2d> aTgPoints[2];
570   for (int i = 0; i < 2; ++i) {
571     std::shared_ptr<GeomAPI_Circ2d> aCircle = toCircle(theFilletFeatures[i]);
572     if (aCircle)
573       aTgPoints[i] = aCircle->project(aFilletCircle->center());
574     else {
575       std::shared_ptr<GeomAPI_Lin2d> aLine = toLine(theFilletFeatures[i]);
576       if (aLine)
577         aTgPoints[i] = aLine->project(aFilletCircle->center());
578     }
579   }
580   theTangentA = aTgPoints[0]->xy();
581   theTangentB = aTgPoints[1]->xy();
582 }
583
584 double calculateFilletRadius(FeaturePtr theFilletFeatures[2])
585 {
586   double aLengths[2] = { 0, 0 };
587   for (int i = 0; i < 2; ++i) {
588     GeomShapePtr aShape = theFilletFeatures[i]->lastResult()->shape();
589     std::shared_ptr<GeomAPI_Edge> anEdge = std::dynamic_pointer_cast<GeomAPI_Edge>(aShape);
590     if (anEdge)
591       aLengths[i] = anEdge->length();
592   }
593   return (aLengths[0] < aLengths[1] ? aLengths[0] : aLengths[1]) / 6.0;
594 }
595
596 std::set<FeaturePtr> findFeaturesToRemove(const FeaturePtr theFeature,
597                                           const AttributePtr theAttribute) {
598   std::set<FeaturePtr> aFeaturesToBeRemoved;
599   std::set<AttributePtr> aRefs = theFeature->data()->refsToMe();
600   std::list<ResultPtr> aResults = theFeature->results();
601   for(std::list<ResultPtr>::const_iterator aResultsIt = aResults.cbegin();
602       aResultsIt != aResults.cend();
603       ++aResultsIt) {
604     ResultPtr aResult = *aResultsIt;
605     std::set<AttributePtr> aResultRefs = aResult->data()->refsToMe();
606     aRefs.insert(aResultRefs.begin(), aResultRefs.end());
607   }
608   for(std::set<AttributePtr>::const_iterator anIt = aRefs.cbegin();
609     anIt != aRefs.cend();
610     ++anIt) {
611     std::shared_ptr<ModelAPI_Attribute> anAttr = (*anIt);
612     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
613     if(aFeature->getKind() == SketchPlugin_Fillet::ID()) {
614       continue;
615     }
616     if(aFeature->getKind() == SketchPlugin_ConstraintLength::ID()
617         || aFeature->getKind() == SketchPlugin_ConstraintEqual::ID()
618         || aFeature->getKind() == SketchPlugin_ConstraintMiddle::ID()) {
619       aFeaturesToBeRemoved.insert(aFeature);
620     } else {
621       std::list<AttributePtr> anAttrs =
622           aFeature->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
623       for(std::list<AttributePtr>::const_iterator aRefAttrsIt = anAttrs.cbegin();
624           aRefAttrsIt != anAttrs.cend();
625           ++aRefAttrsIt) {
626         AttributeRefAttrPtr anAttrRefAttr =
627           std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*aRefAttrsIt);
628         if(anAttrRefAttr.get() && anAttrRefAttr->attr() == theAttribute) {
629           aFeaturesToBeRemoved.insert(aFeature);
630         }
631       }
632     }
633   }
634   return aFeaturesToBeRemoved;
635 }