Salome HOME
a285ea2431c1e7b8a2364b91047292a88f43e56e
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Tools.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_Tools.h"
21
22 #include "SketchPlugin_Arc.h"
23 #include "SketchPlugin_Circle.h"
24 #include "SketchPlugin_ConstraintCoincidence.h"
25 #include "SketchPlugin_ConstraintCoincidenceInternal.h"
26 #include "SketchPlugin_ConstraintLength.h"
27 #include "SketchPlugin_ConstraintTangent.h"
28 #include "SketchPlugin_Ellipse.h"
29 #include "SketchPlugin_EllipticArc.h"
30 #include "SketchPlugin_Line.h"
31 #include "SketchPlugin_Point.h"
32 #include "SketchPlugin_Projection.h"
33 #include "SketchPlugin_SketchEntity.h"
34 #include "SketchPlugin_Split.h"
35 #include "SketchPlugin_Trim.h"
36
37 #include <SketcherPrs_Tools.h>
38
39 #include <ModelAPI_AttributeDouble.h>
40
41 #include <ModelGeomAlgo_Point2D.h>
42 #include <ModelGeomAlgo_Shape.h>
43
44 #include <GeomAPI_Dir2d.h>
45 #include <GeomAPI_Edge.h>
46 #include <GeomAPI_Pnt2d.h>
47 #include <GeomAPI_XY.h>
48
49 #include <GeomAlgoAPI_CompoundBuilder.h>
50 #include <GeomAlgoAPI_ShapeTools.h>
51
52 #include <GeomDataAPI_Point.h>
53 #include <GeomDataAPI_Point2D.h>
54
55 #ifdef DEBUG_TRIM
56 #include <iostream>
57 #endif
58
59 namespace SketchPlugin_Tools {
60
61 void clearExpressions(AttributeDoublePtr theAttribute)
62 {
63   theAttribute->setText(std::string());
64 }
65
66 void clearExpressions(AttributePointPtr theAttribute)
67 {
68   theAttribute->setText(std::string(), std::string(), std::string());
69 }
70
71 void clearExpressions(AttributePoint2DPtr theAttribute)
72 {
73   theAttribute->setText(std::string(), std::string());
74 }
75
76 void clearExpressions(AttributePtr theAttribute)
77 {
78   // Double
79   AttributeDoublePtr anAttributeDouble =
80       std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
81   if (anAttributeDouble.get())
82     clearExpressions(anAttributeDouble);
83   // Point
84   AttributePointPtr anAttributePoint =
85       std::dynamic_pointer_cast<GeomDataAPI_Point>(theAttribute);
86   if (anAttributePoint.get())
87     clearExpressions(anAttributePoint);
88   // Point2D
89   AttributePoint2DPtr anAttributePoint2D =
90       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
91   if (anAttributePoint2D.get())
92     clearExpressions(anAttributePoint2D);
93 }
94
95 void clearExpressions(FeaturePtr theFeature)
96 {
97   if (!theFeature.get())
98     return;
99
100   std::list<AttributePtr> anAttributes = theFeature->data()->attributes(std::string());
101   std::list<AttributePtr>::iterator anAttributeIt = anAttributes.begin();
102   for (; anAttributeIt != anAttributes.end(); ++anAttributeIt) {
103     clearExpressions(*anAttributeIt);
104   }
105 }
106
107 std::shared_ptr<GeomAPI_Pnt2d> getCoincidencePoint(const FeaturePtr theStartCoin)
108 {
109   std::shared_ptr<GeomAPI_Pnt2d> aPnt = SketcherPrs_Tools::getPoint(theStartCoin.get(),
110                                                           SketchPlugin_Constraint::ENTITY_A());
111   if (aPnt.get() == NULL)
112     aPnt = SketcherPrs_Tools::getPoint(theStartCoin.get(), SketchPlugin_Constraint::ENTITY_B());
113   return aPnt;
114 }
115
116 std::set<FeaturePtr> findCoincidentConstraints(const FeaturePtr& theFeature)
117 {
118   std::set<FeaturePtr> aCoincident;
119   const std::set<AttributePtr>& aRefsList = theFeature->data()->refsToMe();
120   std::set<AttributePtr>::const_iterator aIt;
121   for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
122     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>((*aIt)->owner());
123     if (aConstrFeature && aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID())
124       aCoincident.insert(aConstrFeature);
125   }
126   return aCoincident;
127 }
128
129 void findCoincidences(const FeaturePtr theStartCoin,
130                       const std::string& theAttr,
131                       std::set<FeaturePtr>& theList,
132                       const bool theIsAttrOnly)
133 {
134   AttributeRefAttrPtr aPnt = theStartCoin->refattr(theAttr);
135   if(!aPnt) {
136     return;
137   }
138   FeaturePtr aObj = ModelAPI_Feature::feature(aPnt->object());
139   if(theList.find(aObj) == theList.end()) {
140     std::shared_ptr<GeomAPI_Pnt2d> aOrig = getCoincidencePoint(theStartCoin);
141     if(aOrig.get() == NULL) {
142       return;
143     }
144     if(!theIsAttrOnly || !aPnt->isObject()) {
145       theList.insert(aObj);
146     }
147     std::set<FeaturePtr> aCoincidences = findCoincidentConstraints(aObj);
148     std::set<FeaturePtr>::const_iterator aCIt = aCoincidences.begin();
149     for (; aCIt != aCoincidences.end(); ++aCIt) {
150       FeaturePtr aConstrFeature = *aCIt;
151       std::shared_ptr<GeomAPI_Pnt2d> aPnt = getCoincidencePoint(aConstrFeature);
152       if(aPnt.get() && aOrig->isEqual(aPnt)) {
153         findCoincidences(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_A(),
154                          theList, theIsAttrOnly);
155         findCoincidences(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_B(),
156                          theList, theIsAttrOnly);
157       }
158     }
159   }
160 }
161
162 std::set<FeaturePtr> findFeaturesCoincidentToPoint(const AttributePoint2DPtr& thePoint)
163 {
164   std::set<FeaturePtr> aCoincidentFeatures;
165
166   FeaturePtr anOwner = ModelAPI_Feature::feature(thePoint->owner());
167   aCoincidentFeatures.insert(anOwner);
168
169   std::set<FeaturePtr> aCoincidences = findCoincidentConstraints(anOwner);
170   std::set<FeaturePtr>::const_iterator aCIt = aCoincidences.begin();
171   for (; aCIt != aCoincidences.end(); ++aCIt) {
172     bool isPointUsedInCoincidence = false;
173     AttributeRefAttrPtr anOtherCoincidentAttr;
174     for (int i = 0; i < CONSTRAINT_ATTR_SIZE; ++i) {
175       AttributeRefAttrPtr aRefAttr = (*aCIt)->refattr(SketchPlugin_Constraint::ATTRIBUTE(i));
176       if (!aRefAttr)
177         continue;
178       if (!aRefAttr->isObject() && aRefAttr->attr() == thePoint)
179         isPointUsedInCoincidence = true;
180       else
181         anOtherCoincidentAttr = aRefAttr;
182     }
183
184     if (isPointUsedInCoincidence) {
185       ObjectPtr anObj;
186       if (anOtherCoincidentAttr->isObject())
187         anObj = anOtherCoincidentAttr->object();
188       else
189         anObj = anOtherCoincidentAttr->attr()->owner();
190       aCoincidentFeatures.insert(ModelAPI_Feature::feature(anObj));
191     }
192   }
193
194   return aCoincidentFeatures;
195 }
196
197 // Container for point-point coincidences.
198 // Useful to find points coincident to a given point.
199 class CoincidentPoints
200 {
201 public:
202   void addCoincidence(const AttributePoint2DPtr& thePoint1,
203                       const AttributePoint2DPtr& thePoint2 = AttributePoint2DPtr())
204   {
205     std::list< std::set<AttributePoint2DPtr> >::iterator aFound1 = find(thePoint1);
206     std::list< std::set<AttributePoint2DPtr> >::iterator aFound2 = find(thePoint2);
207     if (aFound1 == myCoincidentPoints.end()) {
208       if (aFound2 == myCoincidentPoints.end()) {
209         std::set<AttributePoint2DPtr> aNewSet;
210         aNewSet.insert(thePoint1);
211         if (thePoint2)
212           aNewSet.insert(thePoint2);
213         myCoincidentPoints.push_back(aNewSet);
214       } else
215         aFound2->insert(thePoint1);
216     } else if (aFound2 == myCoincidentPoints.end()) {
217       if (thePoint2)
218         aFound1->insert(thePoint2);
219     } else {
220       aFound1->insert(aFound2->begin(), aFound2->end());
221       myCoincidentPoints.erase(aFound2);
222     }
223   }
224
225   std::set<AttributePoint2DPtr> coincidentPoints(const AttributePoint2DPtr& thePoint)
226   {
227     collectCoincidentPoints(thePoint);
228
229     std::list< std::set<AttributePoint2DPtr> >::iterator aFound = find(thePoint);
230     if (aFound == myCoincidentPoints.end())
231       return std::set<AttributePoint2DPtr>();
232     return *aFound;
233   }
234
235 private:
236   void coincidences(const FeaturePtr& theFeature,
237                     std::set<FeaturePtr>& theCoincidences) const
238   {
239     // iterate through coincideces for the given feature
240     std::set<FeaturePtr> aCoincidences = SketchPlugin_Tools::findCoincidentConstraints(theFeature);
241     std::set<FeaturePtr>::const_iterator aCIt = aCoincidences.begin();
242     for (; aCIt != aCoincidences.end(); ++aCIt)
243     {
244       if (theCoincidences.find(*aCIt) != theCoincidences.end())
245         continue; // already processed
246       theCoincidences.insert(*aCIt);
247       // iterate on coincident attributes
248       for (int i = 0, aPtInd = 0; i < CONSTRAINT_ATTR_SIZE; ++i) {
249         AttributeRefAttrPtr aRefAttr = (*aCIt)->refattr(SketchPlugin_Constraint::ATTRIBUTE(i));
250         if (aRefAttr && !aRefAttr->isObject())
251         {
252           FeaturePtr anOwner = ModelAPI_Feature::feature(aRefAttr->attr()->owner());
253           if (anOwner != theFeature)
254             coincidences(anOwner, theCoincidences);
255         }
256       }
257     }
258   }
259
260   // Iteratively search points coincident to the given point
261   // (two points may be coincident through the third point)
262   void collectCoincidentPoints(const AttributePoint2DPtr& thePoint)
263   {
264     AttributePoint2DPtr aPoints[2];
265
266     FeaturePtr anOwner = ModelAPI_Feature::feature(thePoint->owner());
267     std::set<FeaturePtr> aCoincidences;
268     coincidences(anOwner, aCoincidences);
269
270     std::set<FeaturePtr>::const_iterator aCIt = aCoincidences.begin();
271     for (; aCIt != aCoincidences.end(); ++aCIt) {
272       aPoints[0] = AttributePoint2DPtr();
273       aPoints[1] = AttributePoint2DPtr();
274       for (int i = 0, aPtInd = 0; i < CONSTRAINT_ATTR_SIZE; ++i) {
275         AttributeRefAttrPtr aRefAttr = (*aCIt)->refattr(SketchPlugin_Constraint::ATTRIBUTE(i));
276         if (aRefAttr && !aRefAttr->isObject())
277           aPoints[aPtInd++] = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aRefAttr->attr());
278       }
279
280       if (aPoints[0] && aPoints[1])
281         addCoincidence(aPoints[0], aPoints[1]);
282     }
283   }
284
285   std::list< std::set<AttributePoint2DPtr> >::iterator find(const AttributePoint2DPtr& thePoint)
286   {
287     std::list< std::set<AttributePoint2DPtr> >::iterator aSeek = myCoincidentPoints.begin();
288     for (; aSeek != myCoincidentPoints.end(); ++aSeek)
289       if (aSeek->find(thePoint) != aSeek->end())
290         return aSeek;
291     return myCoincidentPoints.end();
292   }
293
294 private:
295   std::list< std::set<AttributePoint2DPtr> > myCoincidentPoints;
296 };
297
298 std::set<AttributePoint2DPtr> findPointsCoincidentToPoint(const AttributePoint2DPtr& thePoint)
299 {
300   CoincidentPoints aCoincidentPoints;
301   return aCoincidentPoints.coincidentPoints(thePoint);
302 }
303
304 void resetAttribute(SketchPlugin_Feature* theFeature,
305                     const std::string& theId)
306 {
307   AttributePtr anAttr = theFeature->attribute(theId);
308   if(anAttr.get()) {
309     anAttr->reset();
310   }
311 }
312
313 void createCoincidenceOrTangency(SketchPlugin_Feature* theFeature,
314                                  const std::string& theId,
315                                  const AttributePtr theAttr,
316                                  const ObjectPtr theObject,
317                                  const bool theIsCanBeTangent)
318 {
319   AttributeRefAttrPtr aRefAttr = theFeature->refattr(theId);
320   if(aRefAttr.get() && aRefAttr->isInitialized()) {
321     FeaturePtr aConstraint;
322     if(!theIsCanBeTangent) {
323       aConstraint = theFeature->sketch()
324                               ->addFeature(SketchPlugin_ConstraintCoincidence::ID());
325     } else {
326       if(aRefAttr->isObject()) {
327         ObjectPtr anObject = aRefAttr->object();
328         FeaturePtr aFeature = ModelAPI_Feature::feature(anObject);
329         if(aFeature->getKind() == SketchPlugin_Point::ID()) {
330           aConstraint = theFeature->sketch()
331                                   ->addFeature(SketchPlugin_ConstraintCoincidence::ID());
332         } else {
333           aConstraint = theFeature->sketch()
334                                   ->addFeature(SketchPlugin_ConstraintTangent::ID());
335         }
336       } else {
337         aConstraint = theFeature->sketch()
338                                 ->addFeature(SketchPlugin_ConstraintCoincidence::ID());
339       }
340     }
341     AttributeRefAttrPtr aRefAttrA = aConstraint->refattr(SketchPlugin_Constraint::ENTITY_A());
342     aRefAttr->isObject() ? aRefAttrA->setObject(aRefAttr->object())
343                          : aRefAttrA->setAttr(aRefAttr->attr());
344     AttributeRefAttrPtr aRefAttrB = aConstraint->refattr(SketchPlugin_Constraint::ENTITY_B());
345     if(theObject.get()) {
346       aRefAttrB->setObject(theObject);
347     } else if(theAttr.get()) {
348       aRefAttrB->setAttr(theAttr);
349     }
350   }
351 }
352
353 void convertRefAttrToPointOrTangentCurve(const AttributeRefAttrPtr&      theRefAttr,
354                                          const AttributePtr&             theDefaultAttr,
355                                          std::shared_ptr<GeomAPI_Shape>& theTangentCurve,
356                                          std::shared_ptr<GeomAPI_Pnt2d>& thePassingPoint)
357 {
358   AttributePtr anAttr = theDefaultAttr;
359   if (theRefAttr->isObject()) {
360     FeaturePtr aTgFeature = ModelAPI_Feature::feature(theRefAttr->object());
361     if (aTgFeature) {
362       if (aTgFeature->getKind() != SketchPlugin_Point::ID()) {
363         theTangentCurve = aTgFeature->lastResult()->shape();
364         return;
365       }
366       anAttr = aTgFeature->attribute(SketchPlugin_Point::COORD_ID());
367     }
368   } else
369     anAttr = theRefAttr->attr();
370
371   thePassingPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(anAttr)->pnt();
372 }
373
374
375 FeaturePtr createConstraintAttrAttr(SketchPlugin_Sketch* theSketch,
376                                     const std::string& theConstraintId,
377                                     const AttributePtr& theFirstAttribute,
378                                     const AttributePtr& theSecondAttribute)
379 {
380   FeaturePtr aConstraint = theSketch->addFeature(theConstraintId);
381   AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
382                                  aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
383   aRefAttr->setAttr(theFirstAttribute);
384
385   aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
386                                  aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
387   aRefAttr->setAttr(theSecondAttribute);
388
389 #if defined(DEBUG_TRIM) || defined(DEBUG_SPLIT)
390   std::cout << "<createConstraint to attribute> :"
391             << " first attribute - " << theFirstAttribute->id()
392             << " second attribute - " << theSecondAttribute->id()
393             << std::endl;
394 #endif
395
396   return aConstraint;
397 }
398
399 FeaturePtr createConstraintAttrObject(SketchPlugin_Sketch* theSketch,
400                                       const std::string& theConstraintId,
401                                       const AttributePtr& theFirstAttribute,
402                                       const ObjectPtr& theSecondObject)
403 {
404   FeaturePtr aConstraint = theSketch->addFeature(theConstraintId);
405   AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
406                                  aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
407   aRefAttr->setAttr(theFirstAttribute);
408
409   aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
410                                  aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
411   aRefAttr->setObject(theSecondObject);
412
413 #if defined(DEBUG_TRIM) || defined(DEBUG_SPLIT)
414   std::cout << "<createConstraint to attribute> :"
415             << " first attribute - " << theFirstAttribute->id()
416             << " second object - " << ModelAPI_Feature::feature(theSecondObject)->getKind()
417             << std::endl;
418 #endif
419
420   return aConstraint;
421 }
422
423 FeaturePtr createConstraintObjectObject(SketchPlugin_Sketch* theSketch,
424                                         const std::string& theConstraintId,
425                                         const ObjectPtr& theFirstObject,
426                                         const ObjectPtr& theSecondObject)
427 {
428   FeaturePtr aConstraint = theSketch->addFeature(theConstraintId);
429   AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
430                                  aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
431   aRefAttr->setObject(theFirstObject);
432
433   aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
434                                  aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
435   aRefAttr->setObject(theSecondObject);
436
437 #if defined(DEBUG_TRIM) || defined(DEBUG_SPLIT)
438   std::cout << "<createConstraint to attribute> :"
439             << " first object - " << ModelAPI_Feature::feature(theFirstObject)->getKind()
440             << " second object - " << ModelAPI_Feature::feature(theSecondObject)->getKind()
441             << std::endl;
442 #endif
443
444   return aConstraint;
445 }
446
447 void createAuxiliaryPointOnEllipse(const FeaturePtr& theEllipseFeature,
448                                    const std::string& theEllipsePoint)
449 {
450   SketchPlugin_Sketch* aSketch =
451       std::dynamic_pointer_cast<SketchPlugin_Feature>(theEllipseFeature)->sketch();
452
453   FeaturePtr aPointFeature = aSketch->addFeature(SketchPlugin_Point::ID());
454   aPointFeature->boolean(SketchPlugin_Point::AUXILIARY_ID())->setValue(true);
455   aPointFeature->reference(SketchPlugin_Point::PARENT_ID())->setValue(theEllipseFeature);
456
457   AttributePoint2DPtr anElPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
458     theEllipseFeature->attribute(theEllipsePoint));
459
460   AttributePoint2DPtr aCoord = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
461     aPointFeature->attribute(SketchPlugin_Point::COORD_ID()));
462   aCoord->setValue(anElPoint->x(), anElPoint->y());
463
464   aPointFeature->execute();
465   std::string aName = theEllipseFeature->name() + "_" + theEllipsePoint;
466   aPointFeature->data()->setName(aName);
467   aPointFeature->lastResult()->data()->setName(aName);
468
469   createConstraintAttrAttr(aSketch,
470       SketchPlugin_ConstraintCoincidenceInternal::ID(), anElPoint, aCoord);
471 }
472
473 void createAuxiliaryAxisOfEllipse(const FeaturePtr& theEllipseFeature,
474                                   const std::string& theStartPoint,
475                                   const std::string& theEndPoint)
476 {
477   SketchPlugin_Sketch* aSketch =
478       std::dynamic_pointer_cast<SketchPlugin_Feature>(theEllipseFeature)->sketch();
479
480   FeaturePtr aLineFeature = aSketch->addFeature(SketchPlugin_Line::ID());
481   aLineFeature->boolean(SketchPlugin_Point::AUXILIARY_ID())->setValue(true);
482   aLineFeature->reference(SketchPlugin_Point::PARENT_ID())->setValue(theEllipseFeature);
483
484   AttributePoint2DPtr aStartPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
485     theEllipseFeature->attribute(theStartPoint));
486   AttributePoint2DPtr aEndPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
487     theEllipseFeature->attribute(theEndPoint));
488
489   AttributePoint2DPtr aLineStart = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
490     aLineFeature->attribute(SketchPlugin_Line::START_ID()));
491   aLineStart->setValue(aStartPoint->x(), aStartPoint->y());
492
493   AttributePoint2DPtr aLineEnd = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
494     aLineFeature->attribute(SketchPlugin_Line::END_ID()));
495   aLineEnd->setValue(aEndPoint->x(), aEndPoint->y());
496
497   aLineFeature->execute();
498   std::string aName = theEllipseFeature->name() + "_" +
499     (theStartPoint == SketchPlugin_Ellipse::MAJOR_AXIS_START_ID() ? "major_axis" : "minor_axis");
500   aLineFeature->data()->setName(aName);
501   aLineFeature->lastResult()->data()->setName(aName);
502
503   createConstraintAttrAttr(aSketch,
504       SketchPlugin_ConstraintCoincidenceInternal::ID(), aStartPoint, aLineStart);
505   createConstraintAttrAttr(aSketch,
506       SketchPlugin_ConstraintCoincidenceInternal::ID(), aEndPoint, aLineEnd);
507 }
508
509 GeomPnt2dPtr flyoutPointCoordinates(const ConstraintPtr& theConstraint)
510 {
511   // currently process Length constraints only
512   if (theConstraint->getKind() != SketchPlugin_ConstraintLength::ID())
513     return GeomPnt2dPtr();
514
515   AttributeRefAttrPtr aLineAttr = theConstraint->refattr(SketchPlugin_Constraint::ENTITY_A());
516   if (!aLineAttr || !aLineAttr->isObject())
517     return GeomPnt2dPtr();
518   FeaturePtr aLine = ModelAPI_Feature::feature(aLineAttr->object());
519   if (!aLine || aLine->getKind() != SketchPlugin_Line::ID())
520     return GeomPnt2dPtr();
521
522   std::shared_ptr<GeomAPI_XY> aStartPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
523       aLine->attribute(SketchPlugin_Line::START_ID()))->pnt()->xy();
524   std::shared_ptr<GeomAPI_XY> aEndPnt = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
525       aLine->attribute(SketchPlugin_Line::END_ID()))->pnt()->xy();
526
527   std::shared_ptr<GeomDataAPI_Point2D> aFlyoutAttr =
528       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
529       theConstraint->attribute(SketchPlugin_Constraint::FLYOUT_VALUE_PNT()));
530   std::shared_ptr<GeomAPI_Pnt2d> aFltPnt = aFlyoutAttr->pnt();
531
532   std::shared_ptr<GeomAPI_Dir2d> aLineDir(new GeomAPI_Dir2d(aEndPnt->decreased(aStartPnt)));
533
534   double X = aStartPnt->x() + aFltPnt->x() * aLineDir->x() - aFltPnt->y() * aLineDir->y();
535   double Y = aStartPnt->y() + aFltPnt->x() * aLineDir->y() + aFltPnt->y() * aLineDir->x();
536
537   return GeomPnt2dPtr(new GeomAPI_Pnt2d(X, Y));
538 }
539
540 } // namespace SketchPlugin_Tools
541
542
543 // =================================================================================================
544 //                 namespace SketchPlugin_SegmentationTools
545 // =================================================================================================
546
547 void SketchPlugin_SegmentationTools::getFeaturePoints(const FeaturePtr& theFeature,
548                                                       AttributePoint2DPtr& theStartPointAttr,
549                                                       AttributePoint2DPtr& theEndPointAttr)
550 {
551   std::string aFeatureKind = theFeature->getKind();
552   std::string aStartAttributeName, anEndAttributeName;
553   if (aFeatureKind == SketchPlugin_Line::ID()) {
554     aStartAttributeName = SketchPlugin_Line::START_ID();
555     anEndAttributeName = SketchPlugin_Line::END_ID();
556   }
557   else if (aFeatureKind == SketchPlugin_Arc::ID()) {
558     aStartAttributeName = SketchPlugin_Arc::START_ID();
559     anEndAttributeName = SketchPlugin_Arc::END_ID();
560   }
561   else if (aFeatureKind == SketchPlugin_EllipticArc::ID()) {
562     aStartAttributeName = SketchPlugin_EllipticArc::START_POINT_ID();
563     anEndAttributeName = SketchPlugin_EllipticArc::END_POINT_ID();
564   }
565   if (!aStartAttributeName.empty() && !anEndAttributeName.empty()) {
566     theStartPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
567         theFeature->attribute(aStartAttributeName));
568     theEndPointAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
569         theFeature->attribute(anEndAttributeName));
570   }
571 }
572
573
574 void SketchPlugin_SegmentationTools::getRefAttributes(
575     const FeaturePtr& theFeature,
576     std::map<AttributePtr, std::list<AttributePtr> >& theRefs,
577     std::list<AttributePtr>& theRefsToFeature)
578 {
579   theRefs.clear();
580
581   std::list<AttributePtr> aPointAttributes =
582     theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
583   std::set<AttributePtr> aPointAttributesSet;
584
585   std::list<AttributePtr>::const_iterator aPIt =
586     aPointAttributes.begin(), aPLast = aPointAttributes.end();
587   for (; aPIt != aPLast; aPIt++)
588     aPointAttributesSet.insert(*aPIt);
589
590   std::set<AttributePtr> aRefsAttributes = theFeature->lastResult()->data()->refsToMe();
591   std::set<AttributePtr> aFRefsList = theFeature->data()->refsToMe();
592   aRefsAttributes.insert(aFRefsList.begin(), aFRefsList.end());
593
594   std::set<AttributePtr>::const_iterator aIt;
595   for (aIt = aRefsAttributes.cbegin(); aIt != aRefsAttributes.cend(); ++aIt) {
596     AttributePtr anAttr = (*aIt);
597     FeaturePtr anAttrFeature = ModelAPI_Feature::feature(anAttr->owner());
598     if (!anAttrFeature->isMacro() && // <- skip reference from Trim or Split feature
599         anAttr.get() && anAttr->attributeType() == ModelAPI_AttributeRefAttr::typeId()) {
600       AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(anAttr);
601       if (!aRefAttr->isObject()) { // find attributes referenced to feature point attributes
602         AttributePtr anAttrInRef = aRefAttr->attr();
603         if (anAttrInRef.get() &&
604             aPointAttributesSet.find(anAttrInRef) != aPointAttributesSet.end()) {
605           if (theRefs.find(anAttrInRef) != theRefs.end())
606             theRefs[anAttrInRef].push_back(aRefAttr);
607           else {
608             std::list<AttributePtr> anAttrList;
609             anAttrList.push_back(aRefAttr);
610             theRefs[anAttrInRef] = anAttrList;
611           }
612         }
613       }
614       else { // find attributes referenced to feature itself
615         theRefsToFeature.push_back(anAttr);
616       }
617     }
618   }
619 }
620
621 GeomShapePtr SketchPlugin_SegmentationTools::getSubShape(
622     SketchPlugin_Feature* theFeature,
623     const std::string& theObjectAttributeId,
624     const std::string& thePointAttributeId,
625     std::map<ObjectPtr, std::set<GeomShapePtr> >& theCashedShapes,
626     std::map<ObjectPtr, GeomAlgoAPI_ShapeTools::PointToRefsMap>& theObjectToPoints)
627 {
628   GeomShapePtr aBaseShape;
629
630   AttributeReferencePtr anObjectAttr = theFeature->reference(theObjectAttributeId);
631   ObjectPtr aBaseObject = anObjectAttr->value();
632   if (!aBaseObject.get())
633     return aBaseShape;
634
635   // point on feature
636   AttributePoint2DPtr aPointAttr =
637       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theFeature->attribute(thePointAttributeId));
638   std::shared_ptr<GeomAPI_Pnt2d> anAttributePnt2d = aPointAttr->pnt();
639   std::shared_ptr<GeomAPI_Pnt> anAttributePnt =
640       theFeature->sketch()->to3D(anAttributePnt2d->x(), anAttributePnt2d->y());
641
642   if (theCashedShapes.find(aBaseObject) == theCashedShapes.end())
643     fillObjectShapes(theFeature, aBaseObject, theCashedShapes, theObjectToPoints);
644
645   std::shared_ptr<GeomAPI_Pnt> aStartPoint;
646   std::shared_ptr<GeomAPI_Pnt> aSecondPoint;
647   const std::set<GeomShapePtr>& aShapes = theCashedShapes[aBaseObject];
648   std::set<GeomShapePtr>::const_iterator anIt = aShapes.begin(), aLast = aShapes.end();
649   for (; anIt != aLast; anIt++) {
650     GeomShapePtr aCurrentShape = *anIt;
651     std::shared_ptr<GeomAPI_Pnt> aProjectedPoint;
652     if (ModelGeomAlgo_Point2D::isPointOnEdge(aCurrentShape, anAttributePnt, aProjectedPoint)) {
653       if (theFeature->getKind() == SketchPlugin_Split::ID()) {
654         // for Split operation collect start and end points of the shape
655         if (aCurrentShape->shapeType() == GeomAPI_Shape::EDGE) {
656           std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aCurrentShape));
657           aStartPoint = anEdge->firstPoint();
658           aSecondPoint = anEdge->lastPoint();
659         }
660       }
661       else
662         aBaseShape = aCurrentShape;
663       break;
664     }
665   }
666
667   if (!aStartPoint.get() || !aSecondPoint.get())
668     return aBaseShape;
669
670   FeaturePtr aBaseFeature = ModelAPI_Feature::feature(aBaseObject);
671   if (anObjectAttr->isInitialized() && aBaseFeature.get() && aPointAttr->isInitialized()) {
672     ResultPtr aResult = aBaseFeature->lastResult();
673     GeomShapePtr aResultShape = aResult->shape();
674     std::list<std::shared_ptr<GeomAPI_Pnt> > aPoints;
675
676     aPoints.push_back(aStartPoint);
677     aPoints.push_back(aSecondPoint);
678
679     std::set<std::shared_ptr<GeomAPI_Shape> > aSplitShapes;
680     GeomAlgoAPI_ShapeTools::splitShape_p(aResultShape, aPoints, aSplitShapes);
681     aBaseShape = GeomAlgoAPI_ShapeTools::findShape(aPoints, aSplitShapes);
682   }
683   return aBaseShape;
684 }
685
686 void SketchPlugin_SegmentationTools::fillObjectShapes(
687     SketchPlugin_Feature* theOpFeature,
688     const ObjectPtr& theObject,
689     std::map<ObjectPtr, std::set<GeomShapePtr> >& theCashedShapes,
690     std::map<ObjectPtr, GeomAlgoAPI_ShapeTools::PointToRefsMap>& theObjectToPoints)
691 {
692   SketchPlugin_Sketch* aSketch = theOpFeature->sketch();
693
694   GeomAlgoAPI_ShapeTools::PointToRefsMap aPoints;
695   std::set<GeomShapePtr> aShapes;
696
697   std::set<AttributePoint2DPtr > aRefAttributes;
698   // current feature
699   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
700   std::set<ResultPtr> anEdgeShapes;
701   // edges on feature
702   ModelGeomAlgo_Shape::shapesOfType(aFeature, GeomAPI_Shape::EDGE, anEdgeShapes);
703   if (!anEdgeShapes.empty()) {
704     GeomShapePtr aFeatureShape = (*anEdgeShapes.begin())->shape();
705
706     // coincidences to the feature
707     ModelGeomAlgo_Point2D::getPointsOfReference(aFeature, SketchPlugin_ConstraintCoincidence::ID(),
708                          aRefAttributes, SketchPlugin_Point::ID(), SketchPlugin_Point::COORD_ID());
709     // layed on feature coincidences to divide it on several shapes
710     std::shared_ptr<ModelAPI_Data> aData = aSketch->data();
711     std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
712         aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
713     std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
714         aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
715     std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
716         aData->attribute(SketchPlugin_Sketch::NORM_ID()));
717     std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
718
719     ModelGeomAlgo_Point2D::getPointsInsideShape(aFeatureShape, aRefAttributes, aC->pnt(),
720                                                   aX->dir(), aY, aPoints);
721
722     if (theOpFeature->getKind() == SketchPlugin_Trim::ID()) {
723       // collect all intersection points with other edges for Trim operation only
724       std::list<FeaturePtr> aFeatures;
725       for (int i = 0; i < aSketch->numberOfSubs(); i++) {
726         FeaturePtr aFeature = aSketch->subFeature(i);
727         if (aFeature.get() && aFeature->getKind() != SketchPlugin_Projection::ID())
728           aFeatures.push_back(aFeature);
729       }
730       ModelGeomAlgo_Point2D::getPointsIntersectedShape(aFeature, aFeatures, aPoints);
731     }
732
733     if (!aPoints.empty())
734       GeomAlgoAPI_ShapeTools::splitShape(aFeatureShape, aPoints, aShapes);
735   }
736   theObjectToPoints[theObject] = aPoints;
737   theCashedShapes[theObject] = aShapes;
738 }
739
740 void SketchPlugin_SegmentationTools::updateRefAttConstraints(
741     const std::map<AttributePtr, std::list<AttributePtr> >& theBaseRefAttributes,
742     const std::set<std::pair<AttributePtr, AttributePtr> >& theModifiedAttributes)
743 {
744 #if defined DEBUG_SPLIT || defined DEBUG_TRIM
745   std::cout << "updateRefAttConstraints" << std::endl;
746 #endif
747
748   std::set<std::pair<AttributePtr, AttributePtr> >::const_iterator
749     anIt = theModifiedAttributes.begin(),  aLast = theModifiedAttributes.end();
750   for (; anIt != aLast; anIt++) {
751     AttributePtr anAttribute = anIt->first;
752     AttributePtr aNewAttribute = anIt->second;
753
754     // not found in references
755     if (!aNewAttribute.get() ||
756         theBaseRefAttributes.find(anAttribute) == theBaseRefAttributes.end())
757       continue;
758     std::list<AttributePtr> aRefAttributes = theBaseRefAttributes.at(anAttribute);
759     std::list<AttributePtr>::const_iterator aRefIt = aRefAttributes.begin(),
760                                             aRLast = aRefAttributes.end();
761
762     for (; aRefIt != aRLast; aRefIt++) {
763       AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*aRefIt);
764       if (aRefAttr.get()) {
765         aRefAttr->setAttr(aNewAttribute);
766 #ifdef DEBUG_SPLIT
767         FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->owner());
768         std::cout << " -" << getFeatureInfo(aFeature) << std::endl;
769 #endif
770       }
771     }
772   }
773 }
774
775 void SketchPlugin_SegmentationTools::updateFeaturesAfterOperation(
776     const std::set<FeaturePtr>& theFeaturesToUpdate)
777 {
778   std::set<FeaturePtr>::const_iterator anIt = theFeaturesToUpdate.begin(),
779                                        aLast = theFeaturesToUpdate.end();
780   for (; anIt != aLast; anIt++) {
781     FeaturePtr aRefFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anIt);
782     std::string aRefFeatureKind = aRefFeature->getKind();
783     if (aRefFeatureKind == SketchPlugin_ConstraintLength::ID()) {
784       std::shared_ptr<SketchPlugin_ConstraintLength> aLenghtFeature =
785                               std::dynamic_pointer_cast<SketchPlugin_ConstraintLength>(*anIt);
786       if (aLenghtFeature.get()) {
787         std::shared_ptr<ModelAPI_AttributeDouble> aValueAttr = std::dynamic_pointer_cast<
788             ModelAPI_AttributeDouble>(aLenghtFeature->attribute(SketchPlugin_Constraint::VALUE()));
789         double aValue;
790         if (aLenghtFeature->computeLenghtValue(aValue) && aValueAttr.get())
791           aValueAttr->setValue(aValue);
792       }
793     }
794   }
795 }
796
797 AISObjectPtr SketchPlugin_SegmentationTools::getAISObject(
798     AISObjectPtr thePrevious,
799     SketchPlugin_Feature* theOpFeature,
800     const std::string& thePreviewObjectAttrName,
801     const std::string& thePreviewPointAttrName,
802     const std::string& theSelectedObjectAttrName,
803     const std::string& theSelectedPointAttrName)
804 {
805 #if defined DEBUG_SPLIT || defined DEBUG_TRIM_METHODS
806   std::cout << "getAISObject: " << theOpFeature->data()->name() << std::endl;
807 #endif
808
809   AISObjectPtr anAIS = thePrevious;
810
811   std::list<std::shared_ptr<GeomAPI_Shape> > aShapes;
812   std::map<ObjectPtr, std::set<GeomShapePtr> > aCashedShapes;
813   std::map<ObjectPtr, GeomAlgoAPI_ShapeTools::PointToRefsMap> aObjectToPoints;
814   GeomShapePtr aPreviewShape = getSubShape(theOpFeature,
815       thePreviewObjectAttrName, thePreviewPointAttrName, aCashedShapes, aObjectToPoints);
816   if (aPreviewShape.get())
817     aShapes.push_back(aPreviewShape);
818   GeomShapePtr aSelectedShape = getSubShape(theOpFeature,
819       theSelectedObjectAttrName, theSelectedPointAttrName, aCashedShapes, aObjectToPoints);
820   if (aSelectedShape.get())
821     aShapes.push_back(aSelectedShape);
822
823   if (aShapes.empty())
824     return AISObjectPtr();
825
826   GeomShapePtr aBaseShape = GeomAlgoAPI_CompoundBuilder::compound(aShapes);
827   if (!aBaseShape.get())
828     return AISObjectPtr();
829
830   if (aBaseShape.get()) {
831     if (!anAIS)
832       anAIS = AISObjectPtr(new GeomAPI_AISObject);
833     anAIS->createShape(aBaseShape);
834
835     std::vector<int> aColor;
836     aColor = Config_PropManager::color("Visualization", "operation_remove_feature_color");
837     double aWidth = SketchPlugin_SketchEntity::SKETCH_LINE_WIDTH();
838     int aLineStyle = SketchPlugin_SketchEntity::SKETCH_LINE_STYLE();
839     anAIS->setColor(aColor[0], aColor[1], aColor[2]);
840     // width when there is not base object should be extened in several points
841     // in order to see this preview over highlight
842     anAIS->setWidth(aWidth+4);
843     anAIS->setLineStyle(aLineStyle);
844   }
845   else
846     anAIS = AISObjectPtr();
847   return anAIS;
848 }
849
850 #define GEOM_DATA_POINT2D(f, a) std::dynamic_pointer_cast<GeomDataAPI_Point2D>((f)->attribute(a))
851
852 FeaturePtr SketchPlugin_SegmentationTools::createLineFeature(
853     const FeaturePtr& theBaseFeature,
854     const std::shared_ptr<GeomAPI_Pnt2d>& theFirstPoint,
855     const std::shared_ptr<GeomAPI_Pnt2d>& theSecondPoint)
856 {
857   FeaturePtr aFeature;
858   std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
859       std::dynamic_pointer_cast<SketchPlugin_Feature>(theBaseFeature);
860   SketchPlugin_Sketch* aSketch = aSketchFeature->sketch();
861   if (!aSketch || !theBaseFeature.get())
862     return aFeature;
863
864   aFeature = aSketch->addFeature(SketchPlugin_Line::ID());
865
866   GEOM_DATA_POINT2D(aFeature, SketchPlugin_Line::START_ID())->setValue(theFirstPoint);
867   GEOM_DATA_POINT2D(aFeature, SketchPlugin_Line::END_ID())->setValue(theSecondPoint);
868
869   aFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(
870       theBaseFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value());
871   aFeature->execute(); // to obtain result
872
873   return aFeature;
874 }
875
876 struct ArcAttributes
877 {
878   std::string myKind;
879   std::string myCenter;
880   std::string myFocus;
881   std::string myStart;
882   std::string myEnd;
883   std::string myReversed;
884
885   ArcAttributes() {}
886
887   ArcAttributes(const std::string& theKind) : myKind(theKind)
888   {
889     if (myKind == SketchPlugin_Arc::ID()) {
890       myCenter = SketchPlugin_Arc::CENTER_ID();
891       myStart = SketchPlugin_Arc::START_ID();
892       myEnd = SketchPlugin_Arc::END_ID();
893       myReversed = SketchPlugin_Arc::REVERSED_ID();
894     }
895     else if (myKind == SketchPlugin_Circle::ID()) {
896       myCenter = SketchPlugin_Circle::CENTER_ID();
897     }
898     else if (myKind == SketchPlugin_Ellipse::ID()) {
899       myCenter = SketchPlugin_Ellipse::CENTER_ID();
900       myFocus = SketchPlugin_Ellipse::FIRST_FOCUS_ID();
901     }
902     else if (myKind == SketchPlugin_EllipticArc::ID()) {
903       myCenter = SketchPlugin_EllipticArc::CENTER_ID();
904       myFocus = SketchPlugin_EllipticArc::FIRST_FOCUS_ID();
905       myStart = SketchPlugin_EllipticArc::START_POINT_ID();
906       myEnd = SketchPlugin_EllipticArc::END_POINT_ID();
907       myReversed = SketchPlugin_EllipticArc::REVERSED_ID();
908     }
909   }
910 };
911
912 FeaturePtr SketchPlugin_SegmentationTools::createArcFeature(
913     const FeaturePtr& theBaseFeature,
914     const std::shared_ptr<GeomAPI_Pnt2d>& theFirstPoint,
915     const std::shared_ptr<GeomAPI_Pnt2d>& theSecondPoint)
916 {
917   FeaturePtr aFeature;
918   std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
919       std::dynamic_pointer_cast<SketchPlugin_Feature>(theBaseFeature);
920   SketchPlugin_Sketch* aSketch = aSketchFeature->sketch();
921   if (!aSketch || !theBaseFeature.get())
922     return aFeature;
923
924   ArcAttributes aBaseAttrs(theBaseFeature->getKind());
925   ArcAttributes aTargetAttrs;
926   if (aBaseAttrs.myKind == SketchPlugin_Arc::ID() ||
927       aBaseAttrs.myKind == SketchPlugin_Circle::ID())
928     aTargetAttrs = ArcAttributes(SketchPlugin_Arc::ID());
929   else if (aBaseAttrs.myKind == SketchPlugin_Ellipse::ID() ||
930            aBaseAttrs.myKind == SketchPlugin_EllipticArc::ID())
931     aTargetAttrs = ArcAttributes(SketchPlugin_EllipticArc::ID());
932
933   if (aTargetAttrs.myKind.empty())
934     return aFeature;
935
936   aFeature = aSketch->addFeature(aTargetAttrs.myKind);
937   // update fillet arc: make the arc correct for sure, so, it is not needed to process
938   // the "attribute updated"
939   // by arc; moreover, it may cause cyclicity in hte mechanism of updater
940   bool aWasBlocked = aFeature->data()->blockSendAttributeUpdated(true);
941
942   GEOM_DATA_POINT2D(aFeature, aTargetAttrs.myCenter)->setValue(
943       GEOM_DATA_POINT2D(theBaseFeature, aBaseAttrs.myCenter)->pnt());
944   if (!aTargetAttrs.myFocus.empty()) {
945     GEOM_DATA_POINT2D(aFeature, aTargetAttrs.myFocus)->setValue(
946         GEOM_DATA_POINT2D(theBaseFeature, aBaseAttrs.myFocus)->pnt());
947   }
948   GEOM_DATA_POINT2D(aFeature, aTargetAttrs.myStart)->setValue(theFirstPoint);
949   GEOM_DATA_POINT2D(aFeature, aTargetAttrs.myEnd)->setValue(theSecondPoint);
950
951   aFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(
952       theBaseFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value());
953
954   /// fill referersed state of created arc as it is on the base arc
955   bool aReversed = aBaseAttrs.myReversed.empty() ? false :
956                    theBaseFeature->boolean(aBaseAttrs.myReversed)->value();
957   aFeature->boolean(aTargetAttrs.myReversed)->setValue(aReversed);
958
959   aFeature->execute(); // to obtain result (need to calculate arc parameters before sending Update)
960   aFeature->data()->blockSendAttributeUpdated(aWasBlocked);
961
962   return aFeature;
963 }