Salome HOME
Issue #1664: In the Sketcher, add the function Split a segment:
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_ConstraintSplit.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D -->
2
3 // File:    SketchPlugin_ConstraintSplit.cpp
4 // Created: 17 Jul 2016
5 // Author:  Natalia ERMOLAEVA
6
7 #include "SketchPlugin_ConstraintSplit.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_AttributeReference.h>
17 #include <ModelAPI_AttributeString.h>
18 //#include <ModelAPI_AttributeRefList.h>
19 #include <ModelAPI_AttributeRefAttr.h>
20
21 #include <ModelAPI_Validator.h>
22 #include <ModelAPI_Session.h>
23
24 #include <SketchPlugin_Line.h>
25 #include <SketchPlugin_Arc.h>
26 #include <SketchPlugin_Circle.h>
27 #include <SketchPlugin_ConstraintCoincidence.h>
28 #include <SketchPlugin_ConstraintEqual.h>
29 #include <SketchPlugin_ConstraintParallel.h>
30 #include <SketchPlugin_ConstraintTangent.h>
31
32 //#include <ModelAPI_Data.h>
33 #include <ModelAPI_Events.h>
34 //#include <ModelAPI_Session.h>
35 //#include <ModelAPI_Validator.h>
36 //
37 //#include <SketchPlugin_Arc.h>
38 //#include <SketchPlugin_Line.h>
39 //#include <SketchPlugin_Point.h>
40 //#include <SketchPlugin_Sketch.h>
41 //#include <SketchPlugin_ConstraintCoincidence.h>
42 //#include <SketchPlugin_ConstraintTangent.h>
43 //#include <SketchPlugin_ConstraintRadius.h>
44 //#include <SketchPlugin_Tools.h>
45 //
46 #include <Events_Loop.h>
47 //
48 //#include <math.h>
49 //
50 //const double tolerance = 1.e-7;
51 //const double paramTolerance = 1.e-4;
52
53 ///// \brief Attract specified point on theNewArc to the attribute of theFeature
54 //static void recalculateAttributes(FeaturePtr theNewArc, const std::string& theNewArcAttribute,
55 //  FeaturePtr theFeature, const std::string& theFeatureAttribute);
56 //
57 ///// \brief Calculates center of fillet arc and coordinates of tangency points
58 //static void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
59 //                                  double theRadius, bool theNotInversed[2],
60 //                                  std::shared_ptr<GeomAPI_XY>& theCenter,
61 //                                  std::shared_ptr<GeomAPI_XY>& theTangentA,
62 //                                  std::shared_ptr<GeomAPI_XY>& theTangentB);
63 //
64 ///// Get point on 1/3 length of edge from fillet point
65 //static void getPointOnEdge(const FeaturePtr theFeature,
66 //                           const std::shared_ptr<GeomAPI_Pnt2d> theFilletPoint,
67 //                           std::shared_ptr<GeomAPI_Pnt2d>& thePoint);
68 //
69 ///// Get distance from point to feature
70 //static double getProjectionDistance(const FeaturePtr theFeature,
71 //                             const std::shared_ptr<GeomAPI_Pnt2d> thePoint);
72 //
73 ///// Get coincide edges for fillet
74 //static std::set<FeaturePtr> getCoincides(const FeaturePtr& theConstraintCoincidence);
75
76 SketchPlugin_ConstraintSplit::SketchPlugin_ConstraintSplit()
77 //: myListOfPointsChangedInCode(false),
78 //  myRadiusChangedByUser(false),
79 //  myRadiusChangedInCode(false),
80 //  myRadiusInitialized(false)
81 {
82 }
83
84 void SketchPlugin_ConstraintSplit::initAttributes()
85 {
86   data()->addAttribute(SketchPlugin_Constraint::VALUE(), ModelAPI_AttributeReference::typeId());
87   data()->addAttribute(SketchPlugin_Constraint::ENTITY_A(), ModelAPI_AttributeRefAttr::typeId());
88   data()->addAttribute(SketchPlugin_Constraint::ENTITY_B(), ModelAPI_AttributeRefAttr::typeId());
89
90   //data()->addAttribute(SketchPlugin_Constraint::VALUE(), ModelAPI_AttributeDouble::typeId());
91   //data()->addAttribute(SketchPlugin_Constraint::ENTITY_A(), ModelAPI_AttributeRefAttrList::typeId());
92 }
93
94 void SketchPlugin_ConstraintSplit::execute()
95 {
96   std::shared_ptr<ModelAPI_Data> aData = data();
97
98   // Check the base objects are initialized.
99   AttributeReferencePtr aBaseObjectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
100                                             aData->attribute(SketchPlugin_Constraint::VALUE()));
101   if(!aBaseObjectAttr->isInitialized()) {
102     setError("Error: Base object is not initialized.");
103     return;
104   }
105   AttributePoint2DPtr aFirstPointAttr = getPointOfRefAttr(aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
106   AttributePoint2DPtr aSecondPointAttr = getPointOfRefAttr(aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
107   if (!aFirstPointAttr.get() || !aFirstPointAttr->isInitialized() ||
108       !aSecondPointAttr.get() || !aSecondPointAttr->isInitialized()) {
109     setError("Error: Sub-shape is not initialized.");
110     return;
111   }
112
113   // Wait all constraints being created, then send update events
114   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
115   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
116   if (isUpdateFlushed)
117     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
118
119
120   FeaturePtr aBaseFeature = ModelAPI_Feature::feature(aBaseObjectAttr->value());
121   std::string aFeatureKind = aBaseFeature->getKind();
122   FeaturePtr aSplitFeature, aBeforeFeature, anAfterFeature;
123   /*if (aFeatureKind == SketchPlugin_Line::ID())
124     splitLine(aSplitFeature, anOtherFeatures);
125   else*/ if (aFeatureKind == SketchPlugin_Arc::ID())
126     splitArc(aSplitFeature, aBeforeFeature, anAfterFeature);
127   /*if (aFeatureKind == SketchPlugin_Circle::ID())
128     splitCircle(aSplitFeature, anOtherFeatures);
129   FeaturePtr aSplitFeature;
130   std::set<FeaturePtr> anOtherFeatures;*/
131
132   // Send events to update the sub-features by the solver.
133   if(isUpdateFlushed) {
134     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
135   }
136 }
137
138 void SketchPlugin_ConstraintSplit::attributeChanged(const std::string& theID)
139 {
140 /*  if(theID == SketchPlugin_Constraint::ENTITY_A()) {
141     if(myListOfPointsChangedInCode) {
142       return;
143     }
144
145     // Clear results.
146     clearResults();
147
148     // Clear list of new points.
149     myNewPoints.clear();
150
151     // Get list of points for fillets and current radius.
152     AttributeRefAttrListPtr aRefListOfFilletPoints = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttrList>(
153       data()->attribute(SketchPlugin_Constraint::ENTITY_A()));
154     AttributeDoublePtr aRadiusAttribute = real(VALUE());
155     int aListSize = aRefListOfFilletPoints->size();
156     if(aListSize == 0 && !myRadiusChangedByUser) {
157       // If list is empty reset radius to zero (if it was not changed by user).
158       myRadiusChangedInCode = true;
159       aRadiusAttribute->setValue(0);
160       myRadiusChangedInCode = false;
161       return;
162     }
163
164     // Iterate over points to get base lines an calculate radius for fillets.
165     double aMinimumRadius = 0;
166     std::list<std::pair<ObjectPtr, AttributePtr>> aSelectedPointsList = aRefListOfFilletPoints->list();
167     std::list<std::pair<ObjectPtr, AttributePtr>>::iterator anIter = aSelectedPointsList.begin();
168     std::set<AttributePtr> aPointsToSkeep;
169     for(int anIndex = 0; anIndex < aListSize; anIndex++, anIter++) {
170       AttributePtr aFilletPointAttr = (*anIter).second;
171       std::shared_ptr<GeomDataAPI_Point2D> aFilletPoint2D =
172         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aFilletPointAttr);
173       if(!aFilletPoint2D.get()) {
174         myNewPoints.clear();
175         setError("Error: One of the selected points is invalid.");
176         return;
177       }
178
179       // If point or coincident point is already in list remove it from attribute.
180       if(aPointsToSkeep.find(aFilletPointAttr) != aPointsToSkeep.end()) {
181         myListOfPointsChangedInCode = true;
182         aRefListOfFilletPoints->remove(aFilletPointAttr);
183         myListOfPointsChangedInCode = false;
184         continue;
185       }
186
187       // Obtain constraint coincidence for the fillet point.
188       FeaturePtr aConstraintCoincidence;
189       const std::set<AttributePtr>& aRefsList = aFilletPointAttr->owner()->data()->refsToMe();
190       for(std::set<AttributePtr>::const_iterator anIt = aRefsList.cbegin(); anIt != aRefsList.cend(); ++anIt) {
191         std::shared_ptr<ModelAPI_Attribute> anAttr = (*anIt);
192         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->owner());
193         if(aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
194           AttributeRefAttrPtr anAttrRefA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
195             aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_A()));
196           AttributeRefAttrPtr anAttrRefB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
197             aConstrFeature->attribute(SketchPlugin_ConstraintCoincidence::ENTITY_B()));
198           if(anAttrRefA.get()) {
199             AttributePtr anAttrA = anAttrRefA->attr();
200             if(aFilletPointAttr == anAttrA) {
201               aConstraintCoincidence = aConstrFeature;
202               break;
203             }
204           }
205           if(anAttrRefB.get()) {
206             AttributePtr anAttrB = anAttrRefB->attr();
207             if(aFilletPointAttr == anAttrB) {
208               aConstraintCoincidence = aConstrFeature;
209               break;
210             }
211           }
212         }
213       }
214
215       if(!aConstraintCoincidence.get()) {
216         myNewPoints.clear();
217         setError("Error: No coincident edges at one of the selected points.");
218         return;
219       }
220
221       // Get coincides from constraint.
222       std::set<FeaturePtr> aCoincides;
223
224
225       SketchPlugin_Tools::findCoincidences(aConstraintCoincidence,
226                                            SketchPlugin_ConstraintCoincidence::ENTITY_A(),
227                                            aCoincides);
228       SketchPlugin_Tools::findCoincidences(aConstraintCoincidence,
229                                            SketchPlugin_ConstraintCoincidence::ENTITY_B(),
230                                            aCoincides);
231
232       // Remove points from set of coincides. Also get all attributes which is equal to this point to exclude it.
233       std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
234       std::set<FeaturePtr> aNewSetOfCoincides;
235       for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
236         std::string aFeatureKind = (*anIt)->getKind();
237         if(aFeatureKind == SketchPlugin_Point::ID()) {
238           AttributePtr anAttr = (*anIt)->attribute(SketchPlugin_Point::COORD_ID());
239           std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
240             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr);
241           if(aPoint2D.get() && aFilletPnt2d->isEqual(aPoint2D->pnt())) {
242             aPointsToSkeep.insert(anAttr);
243           }
244         } else if(aFeatureKind == SketchPlugin_Line::ID()) {
245           AttributePtr anAttrStart = (*anIt)->attribute(SketchPlugin_Line::START_ID());
246           std::shared_ptr<GeomDataAPI_Point2D> aPointStart2D =
247             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrStart);
248           if(aPointStart2D.get() && aFilletPnt2d->isEqual(aPointStart2D->pnt())) {
249             aPointsToSkeep.insert(anAttrStart);
250           }
251           AttributePtr anAttrEnd = (*anIt)->attribute(SketchPlugin_Line::END_ID());
252           std::shared_ptr<GeomDataAPI_Point2D> aPointEnd2D =
253             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrEnd);
254           if(aPointEnd2D.get() && aFilletPnt2d->isEqual(aPointEnd2D->pnt())) {
255             aPointsToSkeep.insert(anAttrEnd);
256           }
257           aNewSetOfCoincides.insert(*anIt);
258         } else if(aFeatureKind == SketchPlugin_Arc::ID() ) {
259           AttributePtr anAttrCenter = (*anIt)->attribute(SketchPlugin_Arc::CENTER_ID());
260           std::shared_ptr<GeomDataAPI_Point2D> aPointCenter2D =
261             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrCenter);
262           if(aPointCenter2D.get() && aFilletPnt2d->isEqual(aPointCenter2D->pnt())) {
263             aPointsToSkeep.insert(anAttrCenter);
264             continue;
265           }
266           AttributePtr anAttrStart = (*anIt)->attribute(SketchPlugin_Arc::START_ID());
267           std::shared_ptr<GeomDataAPI_Point2D> aPointStart2D =
268             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrStart);
269           if(aPointStart2D.get() && aFilletPnt2d->isEqual(aPointStart2D->pnt())) {
270             aPointsToSkeep.insert(anAttrStart);
271           }
272           AttributePtr anAttrEnd = (*anIt)->attribute(SketchPlugin_Arc::END_ID());
273           std::shared_ptr<GeomDataAPI_Point2D> aPointEnd2D =
274             std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrEnd);
275           if(aPointEnd2D.get() && aFilletPnt2d->isEqual(aPointEnd2D->pnt())) {
276             aPointsToSkeep.insert(anAttrEnd);
277           }
278           aNewSetOfCoincides.insert(*anIt);
279         }
280       }
281       aCoincides = aNewSetOfCoincides;
282
283       // If we still have more than two coincides remove auxilary entities from set of coincides.
284       if(aCoincides.size() > 2) {
285         aNewSetOfCoincides.clear();
286         for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
287           if(!(*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
288             aNewSetOfCoincides.insert(*anIt);
289           }
290         }
291         aCoincides = aNewSetOfCoincides;
292       }
293
294       if(aCoincides.size() != 2) {
295         myNewPoints.clear();
296         setError("Error: One of the selected points does not have two suitable edges for fillet.");
297         return;
298       }
299
300       // Store base point for fillet.
301       aPointsToSkeep.insert(aFilletPointAttr);
302       myNewPoints.insert(aFilletPointAttr);
303
304       // Get base lines for fillet.
305       FeaturePtr anOldFeatureA, anOldFeatureB;
306       std::set<FeaturePtr>::iterator aLinesIt = aCoincides.begin();
307       anOldFeatureA = *aLinesIt++;
308       anOldFeatureB = *aLinesIt;
309
310       // Getting radius value if it was not changed by user.
311       if(!myRadiusChangedByUser) {
312         // Getting points located at 1/3 of edge length from fillet point.
313         std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt2d = aFilletPoint2D->pnt();
314         std::shared_ptr<GeomAPI_Pnt2d> aPntA, aPntB;
315         getPointOnEdge(anOldFeatureA, aFilletPnt2d, aPntA);
316         getPointOnEdge(anOldFeatureB, aFilletPnt2d, aPntB);
317
318         /// Getting distances.
319         double aDistanceA = getProjectionDistance(anOldFeatureB, aPntA);
320         double aDistanceB = getProjectionDistance(anOldFeatureA, aPntB);
321         double aRadius = aDistanceA < aDistanceB ? aDistanceA / 2.0 : aDistanceB / 2.0;
322         aMinimumRadius = aMinimumRadius == 0 ? aRadius : aRadius < aMinimumRadius ? aRadius : aMinimumRadius;
323       }
324     }
325
326     // Set new default radius if it was not changed by user.
327     if(!myRadiusChangedByUser) {
328       myRadiusChangedInCode = true;
329       aRadiusAttribute->setValue(aMinimumRadius);
330       myRadiusChangedInCode = false;
331     }
332
333   } else if(theID == SketchPlugin_Constraint::VALUE()) {
334     if(myRadiusInitialized && !myRadiusChangedInCode) {
335       myRadiusChangedByUser = true;
336     }
337     if(!myRadiusInitialized) {
338       myRadiusInitialized = true;
339     }
340   }
341 */
342 }
343
344 //AISObjectPtr SketchPlugin_ConstraintSplit::getAISObject(AISObjectPtr thePrevious)
345 //{
346 //  if (!sketch())
347 //    return thePrevious;
348 //
349 //  AISObjectPtr anAIS = thePrevious;
350 //  /// TODO: Equal constraint presentation should be put here
351 //  return anAIS;
352 //}
353
354 bool SketchPlugin_ConstraintSplit::isMacro() const
355 {
356   return true;
357 }
358
359 //void SketchPlugin_ConstraintSplit::clearResults()
360 //{
361 ///*  // Clear auxiliary flag on initial objects.
362 //  for(std::map<AttributePtr, FilletFeatures>::iterator aPointsIter = myPointFeaturesMap.begin();
363 //      aPointsIter != myPointFeaturesMap.end();) {
364 //    const FilletFeatures& aFilletFeatures = aPointsIter->second;
365 //    std::list<std::pair<FeaturePtr, bool>>::const_iterator aFeatureIt;
366 //    for(aFeatureIt = aFilletFeatures.baseEdgesState.cbegin();
367 //        aFeatureIt != aFilletFeatures.baseEdgesState.cend();
368 //        ++aFeatureIt) {
369 //      aFeatureIt->first->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(aFeatureIt->second);
370 //    }
371 //    ++aPointsIter;
372 //  }
373 //
374 //  // And remove all produced features.
375 //  DocumentPtr aDoc = sketch()->document();
376 //  for(std::map<AttributePtr, FilletFeatures>::iterator aPointsIter = myPointFeaturesMap.begin();
377 //      aPointsIter != myPointFeaturesMap.end();) {
378 //    // Remove all produced constraints.
379 //    const FilletFeatures& aFilletFeatures = aPointsIter->second;
380 //    std::list<FeaturePtr>::const_iterator aFeatureIt;
381 //    for(aFeatureIt = aFilletFeatures.resultConstraints.cbegin();
382 //        aFeatureIt != aFilletFeatures.resultConstraints.cend();
383 //        ++aFeatureIt) {
384 //      aDoc->removeFeature(*aFeatureIt);
385 //    }
386 //
387 //    // Remove all result edges.
388 //    for(aFeatureIt = aFilletFeatures.resultEdges.cbegin();
389 //        aFeatureIt != aFilletFeatures.resultEdges.cend();
390 //        ++aFeatureIt) {
391 //      aDoc->removeFeature(*aFeatureIt);
392 //    }
393 //
394 //    // Remove point from map.
395 //    myPointFeaturesMap.erase(aPointsIter++);
396 //  }
397 //*/
398 //};
399 //
400 //
401 //// =========   Auxiliary functions   =================
402 //void recalculateAttributes(FeaturePtr theNewArc,  const std::string& theNewArcAttribute,
403 //                           FeaturePtr theFeature, const std::string& theFeatureAttribute)
404 //{
405 //  std::shared_ptr<GeomAPI_Pnt2d> anArcPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
406 //      theNewArc->attribute(theNewArcAttribute))->pnt();
407 //  std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
408 //      theFeature->attribute(theFeatureAttribute))->setValue(anArcPoint->x(), anArcPoint->y());
409 //}
410
411 /*/// \brief Find intersections of lines shifted along normal direction
412 void possibleFilletCenterLineLine(
413     std::shared_ptr<GeomAPI_XY> thePointA, std::shared_ptr<GeomAPI_Dir2d> theDirA,
414     std::shared_ptr<GeomAPI_XY> thePointB, std::shared_ptr<GeomAPI_Dir2d> theDirB,
415     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
416 {
417   std::shared_ptr<GeomAPI_Dir2d> aDirAT(new GeomAPI_Dir2d(-theDirA->y(), theDirA->x()));
418   std::shared_ptr<GeomAPI_Dir2d> aDirBT(new GeomAPI_Dir2d(-theDirB->y(), theDirB->x()));
419   std::shared_ptr<GeomAPI_XY> aPntA, aPntB;
420   double aDet = theDirA->cross(theDirB);
421   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
422     aPntA = thePointA->added(aDirAT->xy()->multiplied(aStepA * theRadius));
423     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
424       aPntB = thePointB->added(aDirBT->xy()->multiplied(aStepB * theRadius));
425       double aVX = aDirAT->xy()->dot(aPntA);
426       double aVY = aDirBT->xy()->dot(aPntB);
427       std::shared_ptr<GeomAPI_XY> aPoint(new GeomAPI_XY(
428           (theDirB->x() * aVX - theDirA->x() * aVY) / aDet,
429           (theDirB->y() * aVX - theDirA->y() * aVY) / aDet));
430       theCenters.push_back(aPoint);
431     }
432   }
433 }
434
435 /// \brief Find intersections of line shifted along normal direction in both sides
436 ///        and a circle with extended radius
437 void possibleFilletCenterLineArc(
438     std::shared_ptr<GeomAPI_XY> theStartLine, std::shared_ptr<GeomAPI_Dir2d> theDirLine,
439     std::shared_ptr<GeomAPI_XY> theCenterArc, double theRadiusArc,
440     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
441 {
442   std::shared_ptr<GeomAPI_Dir2d> aDirT(new GeomAPI_Dir2d(-theDirLine->y(), theDirLine->x()));
443   std::shared_ptr<GeomAPI_XY> aPnt;
444   double aDirNorm2 = theDirLine->dot(theDirLine);
445   double aRad = 0.0;
446   double aDirX = theDirLine->x();
447   double aDirX2 = theDirLine->x() * theDirLine->x();
448   double aDirY2 = theDirLine->y() * theDirLine->y();
449   double aDirXY = theDirLine->x() * theDirLine->y();
450   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
451     aPnt = theStartLine->added(aDirT->xy()->multiplied(aStepA * theRadius));
452     double aCoeff = aDirT->xy()->dot(aPnt->decreased(theCenterArc));
453     double aCoeff2 = aCoeff * aCoeff;
454     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
455       aRad = theRadiusArc + aStepB * theRadius;
456       double aD = aRad * aRad * aDirNorm2 - aCoeff2;
457       if (aD < 0.0)
458         continue;
459       double aDs = sqrt(aD);
460       double x1 = theCenterArc->x() + (aCoeff * aDirT->x() - aDirT->y() * aDs) / aDirNorm2;
461       double x2 = theCenterArc->x() + (aCoeff * aDirT->x() + aDirT->y() * aDs) / aDirNorm2;
462       double y1 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
463           aDirXY * (aPnt->x() - theCenterArc->x()) - theDirLine->y() * aDs) / aDirNorm2;
464       double y2 = (aDirX2 * aPnt->y() + aDirY2 * theCenterArc->y() -
465           aDirXY * (aPnt->x() - theCenterArc->x()) + theDirLine->y() * aDs) / aDirNorm2;
466
467       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
468       theCenters.push_back(aPoint1);
469       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
470       theCenters.push_back(aPoint2);
471     }
472   }
473 }
474
475 /// \brief Find intersections of two circles with extended radii
476 void possibleFilletCenterArcArc(
477     std::shared_ptr<GeomAPI_XY> theCenterA, double theRadiusA,
478     std::shared_ptr<GeomAPI_XY> theCenterB, double theRadiusB,
479     double theRadius, std::list< std::shared_ptr<GeomAPI_XY> >& theCenters)
480 {
481   std::shared_ptr<GeomAPI_XY> aCenterDir = theCenterB->decreased(theCenterA);
482   double aCenterDist2 = aCenterDir->dot(aCenterDir);
483   double aCenterDist = sqrt(aCenterDist2);
484
485   double aRadA, aRadB;
486   for (double aStepA = -1.0; aStepA <= 1.0; aStepA += 2.0) {
487     aRadA = theRadiusA + aStepA * theRadius;
488     for (double aStepB = -1.0; aStepB <= 1.0; aStepB += 2.0) {
489       aRadB = theRadiusB + aStepB * theRadius;
490       if (aRadA + aRadB < aCenterDist || fabs(aRadA - aRadB) > aCenterDist)
491         continue; // there is no intersections
492
493       double aMedDist = (aRadA * aRadA - aRadB * aRadB + aCenterDist2) / (2.0 * aCenterDist);
494       double aHeight = sqrt(aRadA * aRadA - aMedDist * aMedDist);
495
496       double x1 = theCenterA->x() + (aMedDist * aCenterDir->x() + aCenterDir->y() * aHeight) / aCenterDist;
497       double y1 = theCenterA->y() + (aMedDist * aCenterDir->y() - aCenterDir->x() * aHeight) / aCenterDist;
498
499       double x2 = theCenterA->x() + (aMedDist * aCenterDir->x() - aCenterDir->y() * aHeight) / aCenterDist;
500       double y2 = theCenterA->y() + (aMedDist * aCenterDir->y() + aCenterDir->x() * aHeight) / aCenterDist;
501
502       std::shared_ptr<GeomAPI_XY> aPoint1(new GeomAPI_XY(x1, y1));
503       theCenters.push_back(aPoint1);
504       std::shared_ptr<GeomAPI_XY> aPoint2(new GeomAPI_XY(x2, y2));
505       theCenters.push_back(aPoint2);
506     }
507   }
508 }
509
510 void calculateFilletCenter(FeaturePtr theFeatureA, FeaturePtr theFeatureB,
511                            double theRadius, bool theNotInversed[2],
512                            std::shared_ptr<GeomAPI_XY>& theCenter,
513                            std::shared_ptr<GeomAPI_XY>& theTangentA,
514                            std::shared_ptr<GeomAPI_XY>& theTangentB)
515 {
516   static const int aNbFeatures = 2;
517   FeaturePtr aFeature[aNbFeatures] = {theFeatureA, theFeatureB};
518   std::shared_ptr<GeomAPI_XY> aStart[aNbFeatures], aEnd[aNbFeatures], aCenter[aNbFeatures];
519   std::shared_ptr<GeomDataAPI_Point2D> aStartPoint, aEndPoint;
520
521   for (int i = 0; i < aNbFeatures; i++) {
522     if (aFeature[i]->getKind() == SketchPlugin_Line::ID()) {
523       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
524           aFeature[i]->attribute(SketchPlugin_Line::START_ID()));
525       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
526           aFeature[i]->attribute(SketchPlugin_Line::END_ID()));
527     } else if (aFeature[i]->getKind() == SketchPlugin_Arc::ID()) {
528       aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
529           aFeature[i]->attribute(SketchPlugin_Arc::START_ID()));
530       aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
531           aFeature[i]->attribute(SketchPlugin_Arc::END_ID()));
532       aCenter[i] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
533           aFeature[i]->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt()->xy();
534     } else
535       return;
536     aStart[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
537         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()) :
538         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()));
539     aEnd[i] = std::shared_ptr<GeomAPI_XY>(theNotInversed[i] ?
540         new GeomAPI_XY(aEndPoint->x(), aEndPoint->y()) :
541         new GeomAPI_XY(aStartPoint->x(), aStartPoint->y()));
542   }
543
544   if (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
545       theFeatureB->getKind() == SketchPlugin_Line::ID()) {
546     std::shared_ptr<GeomAPI_Dir2d> aDir[2];
547     std::shared_ptr<GeomAPI_Dir2d> aDirT[2];
548     for (int i = 0; i < aNbFeatures; i++) {
549       aDir[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(aEnd[i]->decreased(aStart[i])));
550       aDirT[i] = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d(-aDir[i]->y(), aDir[i]->x()));
551     }
552
553     // get and filter possible centers
554     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
555     possibleFilletCenterLineLine(aStart[0], aDir[0], aStart[1], aDir[1], theRadius, aSuspectCenters);
556     double aDot = 0.0;
557     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
558     for (; anIt != aSuspectCenters.end(); anIt++) {
559       aDot = aDirT[0]->xy()->dot(aStart[0]->decreased(*anIt));
560       theTangentA = (*anIt)->added(aDirT[0]->xy()->multiplied(aDot));
561       if (theTangentA->decreased(aStart[0])->dot(aDir[0]->xy()) < 0.0)
562         continue; // incorrect position
563       aDot = aDirT[1]->xy()->dot(aStart[1]->decreased(*anIt));
564       theTangentB = (*anIt)->added(aDirT[1]->xy()->multiplied(aDot));
565       if (theTangentB->decreased(aStart[1])->dot(aDir[1]->xy()) < 0.0)
566         continue; // incorrect position
567       // the center is found, stop searching
568       theCenter = *anIt;
569       return;
570     }
571   } else if ((theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
572       theFeatureB->getKind() == SketchPlugin_Line::ID()) || 
573       (theFeatureA->getKind() == SketchPlugin_Line::ID() &&
574       theFeatureB->getKind() == SketchPlugin_Arc::ID())) {
575     int aLineInd = theFeatureA->getKind() == SketchPlugin_Line::ID() ? 0 : 1;
576     double anArcRadius = aStart[1-aLineInd]->distance(aCenter[1-aLineInd]);
577     std::shared_ptr<GeomAPI_Dir2d> aDirLine = std::shared_ptr<GeomAPI_Dir2d>(
578         new GeomAPI_Dir2d(aEnd[aLineInd]->decreased(aStart[aLineInd])));
579     std::shared_ptr<GeomAPI_Dir2d> aDirT = std::shared_ptr<GeomAPI_Dir2d>(
580         new GeomAPI_Dir2d(-aDirLine->y(), aDirLine->x()));
581
582     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir = std::shared_ptr<GeomAPI_Dir2d>(
583         new GeomAPI_Dir2d(aStart[1-aLineInd]->decreased(aCenter[1-aLineInd])));
584     std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
585         new GeomAPI_Dir2d(aEnd[1-aLineInd]->decreased(aCenter[1-aLineInd])));
586     double anArcAngle = aEndArcDir->angle(aStartArcDir);
587
588     // get possible centers and filter them
589     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
590     possibleFilletCenterLineArc(aStart[aLineInd], aDirLine, aCenter[1-aLineInd], anArcRadius, theRadius, aSuspectCenters);
591     double aDot = 0.0;
592     // the line is forward into the arc
593     double innerArc = aCenter[1-aLineInd]->decreased(aStart[aLineInd])->dot(aDirLine->xy());
594     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
595     // The possible centers are ranged by their positions.
596     // If the point is not satisfy one of criteria, the weight is decreased with penalty.
597     int aBestWeight = 0;
598     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
599     for (; anIt != aSuspectCenters.end(); anIt++) {
600       int aWeight = 2;
601       aDot = aDirT->xy()->dot(aStart[aLineInd]->decreased(*anIt));
602       aLineTgPoint = (*anIt)->added(aDirT->xy()->multiplied(aDot));
603       // Check the point is placed on the correct arc (penalty if false)
604       if (aCenter[1-aLineInd]->distance(*anIt) * innerArc > anArcRadius * innerArc)
605         aWeight -= 1;
606       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
607           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1-aLineInd])));
608       double aCurAngle = aCurDir->angle(aStartArcDir);
609       if (anArcAngle < 0.0) aCurAngle *= -1.0;
610       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle))
611         continue;
612       if (aWeight > aBestWeight)
613         aBestWeight = aWeight;
614       else if (aWeight < aBestWeight ||
615                aStart[aLineInd]->distance(*anIt) >
616                aStart[aLineInd]->distance(theCenter)) // <-- take closer point
617         continue;
618       // the center is found, stop searching
619       theCenter = *anIt;
620       anArcTgPoint = aCenter[1-aLineInd]->added(aCurDir->xy()->multiplied(anArcRadius));
621       if (theFeatureA->getKind() == SketchPlugin_Line::ID()) {
622         theTangentA = aLineTgPoint;
623         theTangentB = anArcTgPoint;
624       } else {
625         theTangentA = anArcTgPoint;
626         theTangentB = aLineTgPoint;
627       }
628       //return;
629     }
630   } else if (theFeatureA->getKind() == SketchPlugin_Arc::ID() &&
631       theFeatureB->getKind() == SketchPlugin_Arc::ID()) {
632     double anArcRadius[aNbFeatures];
633     double anArcAngle[aNbFeatures];
634     std::shared_ptr<GeomAPI_Dir2d> aStartArcDir[aNbFeatures];
635     for (int i = 0; i < aNbFeatures; i++) {
636       anArcRadius[i] = aStart[i]->distance(aCenter[i]);
637       aStartArcDir[i] = std::shared_ptr<GeomAPI_Dir2d>(
638           new GeomAPI_Dir2d(aStart[i]->decreased(aCenter[i])));
639       std::shared_ptr<GeomAPI_Dir2d> aEndArcDir = std::shared_ptr<GeomAPI_Dir2d>(
640           new GeomAPI_Dir2d(aEnd[i]->decreased(aCenter[i])));
641       anArcAngle[i] = aEndArcDir->angle(aStartArcDir[i]);
642     }
643
644     // get and filter possible centers
645     std::list< std::shared_ptr<GeomAPI_XY> > aSuspectCenters;
646     possibleFilletCenterArcArc(aCenter[0], anArcRadius[0], aCenter[1], anArcRadius[1], theRadius, aSuspectCenters);
647     double aDot = 0.0;
648     std::shared_ptr<GeomAPI_XY> aLineTgPoint, anArcTgPoint;
649     std::list< std::shared_ptr<GeomAPI_XY> >::iterator anIt = aSuspectCenters.begin();
650     for (; anIt != aSuspectCenters.end(); anIt++) {
651       std::shared_ptr<GeomAPI_Dir2d> aCurDir = std::shared_ptr<GeomAPI_Dir2d>(
652           new GeomAPI_Dir2d((*anIt)->decreased(aCenter[0])));
653       double aCurAngle = aCurDir->angle(aStartArcDir[0]);
654       if (anArcAngle[0] < 0.0) aCurAngle *= -1.0;
655       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[0]))
656         continue; // incorrect position
657       theTangentA = aCenter[0]->added(aCurDir->xy()->multiplied(anArcRadius[0]));
658
659       aCurDir = std::shared_ptr<GeomAPI_Dir2d>(new GeomAPI_Dir2d((*anIt)->decreased(aCenter[1])));
660       aCurAngle = aCurDir->angle(aStartArcDir[1]);
661       if (anArcAngle[1] < 0.0) aCurAngle *= -1.0;
662       if (aCurAngle < 0.0 || aCurAngle > fabs(anArcAngle[1]))
663         continue; // incorrect position
664       theTangentB = aCenter[1]->added(aCurDir->xy()->multiplied(anArcRadius[1]));
665
666       // the center is found, stop searching
667       theCenter = *anIt;
668       return;
669     }
670   }
671 }
672
673 void getPointOnEdge(const FeaturePtr theFeature,
674                     const std::shared_ptr<GeomAPI_Pnt2d> theFilletPoint,
675                     std::shared_ptr<GeomAPI_Pnt2d>& thePoint) {
676   if(theFeature->getKind() == SketchPlugin_Line::ID()) {
677     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
678       theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
679     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
680       theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
681     if(aPntStart->distance(theFilletPoint) > 1.e-7) {
682       aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
683         theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
684       aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
685         theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
686     }
687     thePoint.reset( new GeomAPI_Pnt2d(aPntStart->xy()->added( aPntEnd->xy()->decreased( aPntStart->xy() )->multiplied(1.0 / 3.0) ) ) );
688   } else {
689     std::shared_ptr<GeomAPI_Pnt2d> aPntTemp;
690     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
691       theFeature->attribute(SketchPlugin_Arc::START_ID()))->pnt();
692     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
693       theFeature->attribute(SketchPlugin_Arc::END_ID()))->pnt();
694     if(theFeature->attribute(SketchPlugin_Arc::INVERSED_ID())) {
695       aPntTemp = aPntStart;
696       aPntStart = aPntEnd;
697       aPntEnd = aPntTemp;
698     }
699     std::shared_ptr<GeomAPI_Pnt2d> aCenterPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
700       theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
701     std::shared_ptr<GeomAPI_Circ2d> aCirc(new GeomAPI_Circ2d(aCenterPnt, aPntStart));
702     double aStartParameter(0), anEndParameter(0);
703     aCirc->parameter(aPntStart, paramTolerance, aStartParameter);
704     aCirc->parameter(aPntEnd, paramTolerance, anEndParameter);
705     if(aPntStart->distance(theFilletPoint) > tolerance) {
706       double aTmpParameter = aStartParameter;
707       aStartParameter = anEndParameter;
708       anEndParameter = aTmpParameter;
709     }
710     double aPntParameter = aStartParameter + (anEndParameter - aStartParameter) / 3.0;
711     aCirc->D0(aPntParameter, thePoint);
712   }
713 }
714
715 double getProjectionDistance(const FeaturePtr theFeature,
716                              const std::shared_ptr<GeomAPI_Pnt2d> thePoint)
717 {
718   std::shared_ptr<GeomAPI_Pnt2d> aProjectPnt;
719   if(theFeature->getKind() == SketchPlugin_Line::ID()) {
720     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
721       theFeature->attribute(SketchPlugin_Line::START_ID()))->pnt();
722     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
723       theFeature->attribute(SketchPlugin_Line::END_ID()))->pnt();
724     std::shared_ptr<GeomAPI_Lin2d> aLin(new GeomAPI_Lin2d(aPntStart, aPntEnd));
725     aProjectPnt = aLin->project(thePoint);
726   } else {
727     std::shared_ptr<GeomAPI_Pnt2d> aPntStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
728       theFeature->attribute(SketchPlugin_Arc::START_ID()))->pnt();
729     std::shared_ptr<GeomAPI_Pnt2d> aPntEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
730       theFeature->attribute(SketchPlugin_Arc::END_ID()))->pnt();
731     std::shared_ptr<GeomAPI_Pnt2d> aCenterPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
732       theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->pnt();
733     std::shared_ptr<GeomAPI_Circ2d> aCirc(new GeomAPI_Circ2d(aCenterPnt, aPntStart));
734     aProjectPnt = aCirc->project(thePoint);
735   }
736   if(aProjectPnt.get()) {
737     return aProjectPnt->distance(thePoint);
738   }
739   return -1;
740 }
741
742 std::set<FeaturePtr> getCoincides(const FeaturePtr& theConstraintCoincidence)
743 {
744   std::set<FeaturePtr> aCoincides;
745
746   std::shared_ptr<GeomAPI_Pnt2d> aFilletPnt = SketchPlugin_Tools::getCoincidencePoint(theConstraintCoincidence);
747
748   SketchPlugin_Tools::findCoincidences(theConstraintCoincidence,
749                                        SketchPlugin_ConstraintCoincidence::ENTITY_A(),
750                                        aCoincides);
751   SketchPlugin_Tools::findCoincidences(theConstraintCoincidence,
752                                        SketchPlugin_ConstraintCoincidence::ENTITY_B(),
753                                        aCoincides);
754
755   // Remove points from set of coincides.
756   std::set<FeaturePtr> aNewSetOfCoincides;
757   for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
758     if((*anIt)->getKind() == SketchPlugin_Line::ID()) {
759       aNewSetOfCoincides.insert(*anIt);
760     } else if((*anIt)->getKind() == SketchPlugin_Arc::ID()) {
761       AttributePtr anAttrCenter = (*anIt)->attribute(SketchPlugin_Arc::CENTER_ID());
762       std::shared_ptr<GeomDataAPI_Point2D> aPointCenter2D =
763         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttrCenter);
764       if(aPointCenter2D.get() && aFilletPnt->isEqual(aPointCenter2D->pnt())) {
765         continue;
766       }
767       aNewSetOfCoincides.insert(*anIt);
768     }
769   }
770   aCoincides = aNewSetOfCoincides;
771
772   // If we still have more than two coincides remove auxilary entities from set of coincides.
773   if(aCoincides.size() > 2) {
774     aNewSetOfCoincides.clear();
775     for(std::set<FeaturePtr>::iterator anIt = aCoincides.begin(); anIt != aCoincides.end(); ++anIt) {
776       if(!(*anIt)->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value()) {
777         aNewSetOfCoincides.insert(*anIt);
778       }
779     }
780     aCoincides = aNewSetOfCoincides;
781   }
782
783   return aCoincides;
784 }
785 */
786
787 std::shared_ptr<GeomDataAPI_Point2D> SketchPlugin_ConstraintSplit::getPointOfRefAttr(
788                                                                   const AttributePtr& theAttribute)
789 {
790   AttributePoint2DPtr aPointAttribute;
791
792   if (theAttribute->attributeType() == ModelAPI_AttributeRefAttr::typeId()) {
793     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(theAttribute);
794     if (aRefAttr.get() && aRefAttr->isInitialized()) {
795       AttributePtr anAttribute = aRefAttr->attr();
796       if (anAttribute.get() && anAttribute->attributeType() == GeomDataAPI_Point2D::typeId())
797         aPointAttribute = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttribute);
798     }
799   }
800   return aPointAttribute;
801 }
802
803 void SketchPlugin_ConstraintSplit::getFeaturePoints(AttributePoint2DPtr& theStartPointAttr,
804                                                     AttributePoint2DPtr& theEndPointAttr)
805 {
806   AttributePoint2DPtr aPointAttribute;
807
808   AttributeReferencePtr aBaseObjectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
809                                            data()->attribute(SketchPlugin_Constraint::VALUE()));
810   FeaturePtr aBaseFeature = ModelAPI_Feature::feature(aBaseObjectAttr->value());
811
812   std::string aFeatureKind = aBaseFeature->getKind();
813   std::string aStartAttributeName, anEndAttributeName;
814   if (aFeatureKind == SketchPlugin_Line::ID()) {
815     aStartAttributeName = SketchPlugin_Line::START_ID();
816     anEndAttributeName = SketchPlugin_Line::END_ID();
817   }
818   else if (aFeatureKind == SketchPlugin_Arc::ID()) {
819     aStartAttributeName = SketchPlugin_Arc::START_ID();
820     anEndAttributeName = SketchPlugin_Arc::END_ID();
821   }
822   if (!aStartAttributeName.empty() && !anEndAttributeName.empty()) {
823     theStartPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
824                                                          aBaseFeature->attribute(aStartAttributeName));
825     theEndPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
826                                                          aBaseFeature->attribute(anEndAttributeName));
827   }
828 }
829
830 void SketchPlugin_ConstraintSplit::splitArc(FeaturePtr& theSplitFeature,
831                                             FeaturePtr& theBeforeFeature,
832                                             FeaturePtr& theAfterFeature)
833 {
834   SketchPlugin_Sketch* aSketch = sketch();
835   if (!aSketch)
836     return;
837
838   AttributeReferencePtr aBaseObjectAttr = std::dynamic_pointer_cast<ModelAPI_AttributeReference>(
839                                            data()->attribute(SketchPlugin_Constraint::VALUE()));
840   FeaturePtr aBaseFeature = ModelAPI_Feature::feature(aBaseObjectAttr->value());
841   std::string aFeatureKind = aBaseFeature->getKind();
842   if (aFeatureKind != SketchPlugin_Arc::ID())
843     return;
844
845   AttributePoint2DPtr aFirstPointAttr = getPointOfRefAttr(data()->attribute(SketchPlugin_Constraint::ENTITY_A()));
846   AttributePoint2DPtr aSecondPointAttr = getPointOfRefAttr(data()->attribute(SketchPlugin_Constraint::ENTITY_B()));
847   AttributePoint2DPtr aStartPointAttr, anEndPointAttr;
848   getFeaturePoints(aStartPointAttr, anEndPointAttr);
849   if (!aStartPointAttr.get() && !anEndPointAttr.get()) {
850     setError("Error: Feature has no start and end points.");
851     return;
852   }
853
854   arrangePoints(aStartPointAttr, anEndPointAttr, aFirstPointAttr, aSecondPointAttr);
855
856   /// split feature
857   theSplitFeature = createArcFeature(aBaseFeature, aFirstPointAttr, aSecondPointAttr);
858   static ModelAPI_ValidatorsFactory* aFactory = ModelAPI_Session::get()->validators();
859   aFactory->validate(theSplitFeature); // need to be validated to update the "Apply" state if not previewed
860   std::string anError = theSplitFeature->error();
861
862   if (!aStartPointAttr->pnt()->isEqual(aFirstPointAttr->pnt())) {
863     theBeforeFeature = aBaseFeature; ///< use base feature to store all constraints here
864     /// move end arc point to start of split
865     fillAttribute(theBeforeFeature->attribute(SketchPlugin_Arc::END_ID()), aFirstPointAttr);
866     createConstraint(SketchPlugin_ConstraintCoincidence::ID(),
867                      theBeforeFeature->attribute(SketchPlugin_Arc::END_ID()),
868                      theSplitFeature->attribute(SketchPlugin_Arc::START_ID()));
869   }
870
871   if (!aSecondPointAttr->pnt()->isEqual(anEndPointAttr->pnt())) {
872     if (!theBeforeFeature) {
873       theAfterFeature = aBaseFeature; ///< use base feature to store all constraints here
874       fillAttribute(theAfterFeature->attribute(SketchPlugin_Arc::START_ID()), aSecondPointAttr);
875     }
876     else
877       theAfterFeature = createArcFeature(aBaseFeature, aSecondPointAttr, anEndPointAttr);
878
879     createConstraint(SketchPlugin_ConstraintCoincidence::ID(),
880                      theSplitFeature->attribute(SketchPlugin_Arc::END_ID()),
881                      theAfterFeature->attribute(SketchPlugin_Arc::START_ID()));
882   }
883
884   // additional constraints between split and base features
885   createConstraint(SketchPlugin_ConstraintEqual::ID(), getFeatureResult(aBaseFeature),
886                                                        getFeatureResult(theSplitFeature));
887   createConstraint(SketchPlugin_ConstraintTangent::ID(), getFeatureResult(theSplitFeature),
888                                                          getFeatureResult(aBaseFeature));
889   if (theAfterFeature.get()) {
890     createConstraint(SketchPlugin_ConstraintEqual::ID(), getFeatureResult(aBaseFeature),
891                                                          getFeatureResult(theAfterFeature));
892     createConstraint(SketchPlugin_ConstraintTangent::ID(), getFeatureResult(theSplitFeature),
893                                                          getFeatureResult(theAfterFeature));
894   }
895 }
896
897 void SketchPlugin_ConstraintSplit::arrangePoints(const AttributePoint2DPtr& theStartPointAttr,
898                                                  const AttributePoint2DPtr& theEndPointAttr,
899                                                  AttributePoint2DPtr& theFirstPointAttr,
900                                                  AttributePoint2DPtr& theLastPointAttr)
901 {
902   /// if first point is closer to last point, wrap first and last values
903   if (theStartPointAttr->pnt()->distance(theFirstPointAttr->pnt()) >
904       theEndPointAttr->pnt()->distance(theLastPointAttr->pnt())) {
905     AttributePoint2DPtr aTmpPoint = theFirstPointAttr;
906     theFirstPointAttr = theLastPointAttr;
907     theLastPointAttr = aTmpPoint;
908   }
909 }
910
911 void SketchPlugin_ConstraintSplit::fillAttribute(const AttributePtr& theModifiedAttribute,
912                                                  const AttributePtr& theSourceAttribute)
913 {
914   AttributePoint2DPtr aModifiedAttribute = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
915                                             theModifiedAttribute);
916   AttributePoint2DPtr aSourceAttribute = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
917                                             theSourceAttribute);
918
919   if (aModifiedAttribute.get() && aSourceAttribute.get())
920     aSourceAttribute->setValue(aModifiedAttribute->pnt());
921 }
922
923 FeaturePtr SketchPlugin_ConstraintSplit::createArcFeature(const FeaturePtr& theBaseFeature,
924                                                           const AttributePtr& theFirstPointAttr,
925                                                           const AttributePtr& theSecondPointAttr)
926 {
927   FeaturePtr aFeature;
928   SketchPlugin_Sketch* aSketch = sketch();
929   if (!aSketch || !theBaseFeature.get())
930     return aFeature;
931
932   aFeature = aSketch->addFeature(theBaseFeature->getKind());
933   // update fillet arc: make the arc correct for sure, so, it is not needed to process the "attribute updated"
934   // by arc; moreover, it may cause cyclicity in hte mechanism of updater
935   aFeature->data()->blockSendAttributeUpdated(true);
936
937   aFeature->string(SketchPlugin_Arc::ARC_TYPE())->setValue(
938                 SketchPlugin_Arc::ARC_TYPE_CENTER_START_END());
939   fillAttribute(aFeature->attribute(SketchPlugin_Arc::CENTER_ID()),
940                 theBaseFeature->attribute(SketchPlugin_Arc::CENTER_ID()));
941   fillAttribute(aFeature->attribute(SketchPlugin_Arc::START_ID()), theFirstPointAttr);
942   fillAttribute(aFeature->attribute(SketchPlugin_Arc::END_ID()), theSecondPointAttr);
943   aFeature->data()->blockSendAttributeUpdated(false);
944   aFeature->execute();
945
946   return aFeature;
947 }
948
949 void SketchPlugin_ConstraintSplit::createConstraint(const std::string& theConstraintId,
950                                                     const AttributePtr& theFirstAttribute,
951                                                     const AttributePtr& theSecondAttribute)
952 {
953   FeaturePtr aConstraint = sketch()->addFeature(theConstraintId);
954   AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
955                                  aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
956   aRefAttr->setAttr(theFirstAttribute);
957
958   aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
959                                  aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
960   aRefAttr->setAttr(theSecondAttribute);
961 }
962
963 void SketchPlugin_ConstraintSplit::createConstraint(const std::string& theConstraintId,
964                                                     const ObjectPtr& theFirstObject,
965                                                     const ObjectPtr& theSecondObject)
966 {
967   FeaturePtr aConstraint = sketch()->addFeature(theConstraintId);
968   AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
969                                  aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
970   aRefAttr->setObject(theFirstObject);
971
972   aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
973                                  aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
974   aRefAttr->setObject(theSecondObject);
975 }
976
977 std::shared_ptr<ModelAPI_Object> SketchPlugin_ConstraintSplit::getFeatureResult(
978                                     const std::shared_ptr<ModelAPI_Feature>& theFeature)
979 {
980   std::shared_ptr<ModelAPI_Object> aResult;
981
982   std::string aFeatureKind = theFeature->getKind();
983   if (aFeatureKind == SketchPlugin_Line::ID())
984     aResult = theFeature->firstResult();
985   else if (aFeatureKind == SketchPlugin_Arc::ID())
986     aResult = theFeature->lastResult();
987   else if (aFeatureKind == SketchPlugin_Circle::ID())
988     aResult = theFeature->lastResult();
989
990   return aResult;
991 }
992