]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchPlugin/SketchPlugin_Offset.cpp
Salome HOME
2f01c4a8ccf409816a12e3142b83737d3aaa2c9d
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Offset.cpp
1 // Copyright (C) 2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <SketchPlugin_Offset.h>
21
22 #include <SketchPlugin_Sketch.h>
23 #include <SketchPlugin_Line.h>
24 #include <SketchPlugin_Point.h>
25 #include <SketchPlugin_Arc.h>
26 #include <SketchPlugin_Circle.h>
27 #include <SketchPlugin_Ellipse.h>
28 #include <SketchPlugin_EllipticArc.h>
29 #include <SketchPlugin_BSpline.h>
30 #include <SketchPlugin_BSplinePeriodic.h>
31 #include <SketchPlugin_Tools.h>
32
33 #include <SketcherPrs_Factory.h>
34
35 #include <Events_InfoMessage.h>
36
37 #include <ModelAPI_AttributeBoolean.h>
38 #include <ModelAPI_AttributeDouble.h>
39 #include <ModelAPI_AttributeDoubleArray.h>
40 #include <ModelAPI_AttributeInteger.h>
41 #include <ModelAPI_AttributeIntArray.h>
42 #include <ModelAPI_AttributeRefList.h>
43 #include <ModelAPI_Events.h>
44 #include <ModelAPI_ResultConstruction.h>
45 #include <ModelAPI_Tools.h>
46 #include <ModelAPI_Validator.h>
47
48 #include <GeomAlgoAPI_MakeShapeList.h>
49 #include <GeomAlgoAPI_Offset.h>
50 #include <GeomAlgoAPI_ShapeTools.h>
51 #include <GeomAlgoAPI_WireBuilder.h>
52
53 #include <GeomAPI_BSpline.h>
54 #include <GeomAPI_Circ.h>
55 #include <GeomAPI_Edge.h>
56 #include <GeomAPI_Ellipse.h>
57 #include <GeomAPI_ShapeExplorer.h>
58 #include <GeomAPI_Wire.h>
59 #include <GeomAPI_WireExplorer.h>
60
61 #include <GeomDataAPI_Point2D.h>
62 #include <GeomDataAPI_Point2DArray.h>
63
64 #include <iostream>
65
66 static const double tolerance = 1.e-7;
67
68 SketchPlugin_Offset::SketchPlugin_Offset()
69 {
70 }
71
72 void SketchPlugin_Offset::initAttributes()
73 {
74   data()->addAttribute(EDGES_ID(), ModelAPI_AttributeRefList::typeId());
75   data()->addAttribute(VALUE_ID(), ModelAPI_AttributeDouble::typeId());
76   data()->addAttribute(REVERSED_ID(), ModelAPI_AttributeBoolean::typeId());
77
78   // store original entities
79   data()->addAttribute(SketchPlugin_Constraint::ENTITY_A(), ModelAPI_AttributeRefList::typeId());
80   // store offset entities
81   data()->addAttribute(SketchPlugin_Constraint::ENTITY_B(), ModelAPI_AttributeRefList::typeId());
82   // store mapping between original entity and index of the corresponding offset entity
83   data()->addAttribute(SketchPlugin_Constraint::ENTITY_C(), ModelAPI_AttributeIntArray::typeId());
84
85   ModelAPI_Session::get()->validators()->
86       registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_A());
87   ModelAPI_Session::get()->validators()->
88       registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_B());
89   ModelAPI_Session::get()->validators()->
90       registerNotObligatory(getKind(), SketchPlugin_Constraint::ENTITY_C());
91 }
92
93 void SketchPlugin_Offset::execute()
94 {
95   SketchPlugin_Sketch* aSketch = sketch();
96   if (!aSketch) return;
97
98   // 1. Sketch plane
99   std::shared_ptr<GeomAPI_Pln> aPlane = aSketch->plane();
100
101   // 2. Offset value
102   AttributeDoublePtr aValueAttr = real(VALUE_ID());
103   if (!aValueAttr->isInitialized()) return;
104   double aValue = aValueAttr->value();
105   if (aValue < tolerance) return;
106
107   // 2.a. Reversed?
108   AttributeBooleanPtr aReversedAttr = boolean(REVERSED_ID());
109   if (!aReversedAttr->isInitialized()) return;
110   if (aReversedAttr->value()) aValue = -aValue; // reverse offset direction
111
112   // 3. List of all selected edges
113   AttributeRefListPtr aSelectedEdges = reflist(EDGES_ID());
114   std::list<ObjectPtr> anEdgesList = aSelectedEdges->list();
115
116   // 4. Put all selected edges in a set to pass them into findWireOneWay() below
117   std::set<FeaturePtr> anEdgesSet;
118   std::list<ObjectPtr>::const_iterator anEdgesIt = anEdgesList.begin();
119   for (; anEdgesIt != anEdgesList.end(); anEdgesIt++) {
120     FeaturePtr aFeature = ModelAPI_Feature::feature(*anEdgesIt);
121     if (aFeature) {
122       anEdgesSet.insert(aFeature);
123     }
124   }
125
126   // Wait all objects being created, then send update events
127   static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
128   bool isUpdateFlushed = Events_Loop::loop()->isFlushed(anUpdateEvent);
129   if (isUpdateFlushed)
130     Events_Loop::loop()->setFlushed(anUpdateEvent, false);
131
132   // 5. Gather wires and make offset for each wire
133   ListOfMakeShape anOffsetAlgos;
134   for (anEdgesIt = anEdgesList.begin(); anEdgesIt != anEdgesList.end(); anEdgesIt++) {
135     FeaturePtr aFeature = ModelAPI_Feature::feature(*anEdgesIt);
136     if (aFeature.get()) {
137       if (anEdgesSet.find(aFeature) == anEdgesSet.end())
138         continue;
139
140       // 5.a. End points (if any)
141       std::shared_ptr<GeomDataAPI_Point2D> aStartPoint, anEndPoint;
142       SketchPlugin_SegmentationTools::getFeaturePoints(aFeature, aStartPoint, anEndPoint);
143
144       // 5.b. Find a chain of edges
145       std::list<FeaturePtr> aChain;
146       aChain.push_back(aFeature);
147       if (aStartPoint && anEndPoint) { // not closed edge
148         bool isClosed = findWireOneWay(aFeature, aFeature, aStartPoint, anEdgesSet, aChain, true);
149         if (!isClosed)
150           findWireOneWay(aFeature, aFeature, anEndPoint, anEdgesSet, aChain, false);
151       }
152       std::set<FeaturePtr>::iterator aPos = anEdgesSet.find(aFeature);
153       if (aPos != anEdgesSet.end())
154         anEdgesSet.erase(aPos);
155
156       // 5.c. Make wire
157       ListOfShape aTopoChain;
158       std::list<FeaturePtr>::iterator aChainIt = aChain.begin();
159       for (; aChainIt != aChain.end(); ++aChainIt) {
160         FeaturePtr aChainFeature = (*aChainIt);
161         GeomShapePtr aTopoEdge = aChainFeature->lastResult()->shape();
162         if (aTopoEdge->shapeType() == GeomAPI_Shape::EDGE) {
163           aTopoChain.push_back(aTopoEdge);
164         }
165       }
166       std::shared_ptr<GeomAlgoAPI_WireBuilder> aWireBuilder(
167           new GeomAlgoAPI_WireBuilder(aTopoChain));
168
169       GeomShapePtr aWireShape = aWireBuilder->shape();
170       GeomWirePtr aWire (new GeomAPI_Wire (aWireShape));
171
172       // Fix for a problem of offset side change with selection change.
173       // Wire direction is defined by the first selected edge of this wire.
174       if (!aWire->isClosed()) {
175         ListOfShape aModified;
176         // First selected edge of current chain
177         GeomShapePtr aFirstSel = aFeature->lastResult()->shape();
178         aWireBuilder->modified(aFirstSel, aModified);
179         GeomShapePtr aModFS = aModified.front();
180         if (aModFS->orientation() != aFirstSel->orientation())
181           aValue = -aValue;
182       }
183
184       // 5.d. Make offset for the wire
185       std::shared_ptr<GeomAlgoAPI_Offset> anOffsetShape(
186           new GeomAlgoAPI_Offset(aPlane, aWireShape, aValue));
187
188       std::shared_ptr<GeomAlgoAPI_MakeShapeList> aMakeList(new GeomAlgoAPI_MakeShapeList);
189       aMakeList->appendAlgo(aWireBuilder);
190       aMakeList->appendAlgo(anOffsetShape);
191       anOffsetAlgos.push_back(aMakeList);
192     }
193   }
194
195   // 6. Store offset results.
196   //    Create sketch feature for each edge of anOffsetShape, and also store
197   //    created features in CREATED_ID() to remove them on next execute()
198   addToSketch(anOffsetAlgos);
199
200   // send events to update the sub-features by the solver
201   if (isUpdateFlushed)
202     Events_Loop::loop()->setFlushed(anUpdateEvent, true);
203 }
204
205 bool SketchPlugin_Offset::findWireOneWay (const FeaturePtr& theFirstEdge,
206                                           const FeaturePtr& theEdge,
207                                           const std::shared_ptr<GeomDataAPI_Point2D>& theEndPoint,
208                                           std::set<FeaturePtr>& theEdgesSet,
209                                           std::list<FeaturePtr>& theChain,
210                                           const bool isPrepend)
211 {
212   // 1. Find a single edge, coincident to theEndPoint by one of its ends
213   if (!theEndPoint) return false;
214
215   FeaturePtr aNextEdgeFeature;
216   int nbFound = 0;
217
218   std::set<AttributePoint2DPtr> aCoincPoints =
219       SketchPlugin_Tools::findPointsCoincidentToPoint(theEndPoint);
220
221   std::set<AttributePoint2DPtr>::iterator aPointsIt = aCoincPoints.begin();
222   for (; aPointsIt != aCoincPoints.end(); aPointsIt++) {
223     AttributePoint2DPtr aP = (*aPointsIt);
224     FeaturePtr aCoincFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aP->owner());
225     bool isInSet = (theEdgesSet.find(aCoincFeature) != theEdgesSet.end());
226
227     // Condition 0: not auxiliary
228     if (!isInSet && aCoincFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value())
229       continue;
230
231     // Condition 1: not a point feature
232     if (aCoincFeature->getKind() != SketchPlugin_Point::ID()) {
233       // Condition 2: it is not the current edge
234       if (aCoincFeature != theEdge) {
235         // Condition 3: it is in the set of interest.
236         //              Empty set means all sketch edges.
237         if (isInSet || theEdgesSet.empty()) {
238           // Condition 4: consider only features with two end points
239           std::shared_ptr<GeomDataAPI_Point2D> aP1, aP2;
240           SketchPlugin_SegmentationTools::getFeaturePoints(aCoincFeature, aP1, aP2);
241           if (aP1 && aP2) {
242             // Condition 5: consider only features, that have aP as one of they ends.
243             //              For example, we do not need an arc, coincident to aP by its center.
244             if (theEndPoint->pnt()->isEqual(aP1->pnt()) ||
245                 theEndPoint->pnt()->isEqual(aP2->pnt())) {
246               // Condition 6: only one edge can prolongate the chain. If several, we stop here.
247               nbFound++;
248               if (nbFound > 1)
249                 return false;
250
251               // One found
252               aNextEdgeFeature = aCoincFeature;
253             }
254           }
255         }
256       }
257     }
258   }
259
260   // Only one edge can prolongate the chain. If several or none, we stop here.
261   if (nbFound != 1)
262     return false;
263
264   // 2. So, we have the single edge, that prolongate the chain
265
266   // Condition 7: if we reached the very first edge of the chain
267   if (aNextEdgeFeature == theFirstEdge)
268     // Closed chain found
269     return true;
270
271   // 3. Add the found edge to the chain
272   if (isPrepend)
273     theChain.push_front(aNextEdgeFeature);
274   else
275     theChain.push_back(aNextEdgeFeature);
276   // remove from the set, if the set is used
277   if (theEdgesSet.size()) {
278     std::set<FeaturePtr>::iterator aPos = theEdgesSet.find(aNextEdgeFeature);
279     if (aPos != theEdgesSet.end())
280       theEdgesSet.erase(aPos);
281   }
282
283   // 4. Which end of aNextEdgeFeature we need to proceed
284   std::shared_ptr<GeomDataAPI_Point2D> aP1, aP2;
285   SketchPlugin_SegmentationTools::getFeaturePoints(aNextEdgeFeature, aP1, aP2);
286   if (aP2->pnt()->isEqual(theEndPoint->pnt())) {
287     // reversed
288     aP2 = aP1;
289   }
290
291   // 5. Continue gathering the chain (recursive)
292   return findWireOneWay (theFirstEdge, aNextEdgeFeature, aP2, theEdgesSet, theChain, isPrepend);
293 }
294
295 static void setRefListValue(AttributeRefListPtr theList, int theListSize,
296                             ObjectPtr theValue, int theIndex)
297 {
298   if (theIndex < theListSize) {
299     ObjectPtr aCur = theList->object(theIndex);
300     if (aCur != theValue)
301       theList->substitute(aCur, theValue);
302   }
303   else
304     theList->append(theValue);
305 }
306
307 // Reorder shapes according to the wire's order
308 static void reorderShapes(ListOfShape& theShapes, GeomShapePtr theWire)
309 {
310   std::set<GeomShapePtr, GeomAPI_Shape::Comparator> aShapes;
311   aShapes.insert(theShapes.begin(), theShapes.end());
312   theShapes.clear();
313
314   GeomWirePtr aWire(new GeomAPI_Wire(theWire));
315   GeomAPI_WireExplorer anExp(aWire);
316   for (; anExp.more(); anExp.next()) {
317     GeomShapePtr aCurEdge = anExp.current();
318     auto aFound = aShapes.find(aCurEdge);
319     if (aFound != aShapes.end()) {
320       theShapes.push_back(aCurEdge);
321       aShapes.erase(aFound);
322     }
323   }
324 }
325
326 static void removeLastFromIndex(AttributeRefListPtr theList, int theListSize, int& theLastIndex)
327 {
328   if (theLastIndex < theListSize) {
329     std::set<int> anIndicesToRemove;
330     for (; theLastIndex < theListSize; ++theLastIndex)
331       anIndicesToRemove.insert(theLastIndex);
332     theList->remove(anIndicesToRemove);
333   }
334 }
335
336 void SketchPlugin_Offset::addToSketch(const ListOfMakeShape& theOffsetAlgos)
337 {
338   AttributeRefListPtr aSelectedRefList = reflist(EDGES_ID());
339   AttributeRefListPtr aBaseRefList = reflist(ENTITY_A());
340   AttributeRefListPtr anOffsetRefList = reflist(ENTITY_B());
341   AttributeIntArrayPtr anOffsetToBaseMap = intArray(ENTITY_C());
342
343   // compare the list of selected edges and the previously stored,
344   // and store maping between them
345   std::map<ObjectPtr, std::list<ObjectPtr> > aMapExistent;
346   std::list<ObjectPtr> anObjectsToRemove;
347   std::list<ObjectPtr> aSelectedList = aSelectedRefList->list();
348   for (std::list<ObjectPtr>::iterator aSIt = aSelectedList.begin();
349        aSIt != aSelectedList.end(); ++aSIt) {
350     aMapExistent[*aSIt] = std::list<ObjectPtr>();
351   }
352   for (int anIndex = 0, aSize = anOffsetRefList->size(); anIndex < aSize; ++anIndex) {
353     ObjectPtr aCurrent = anOffsetRefList->object(anIndex);
354     int aBaseIndex = anOffsetToBaseMap->value(anIndex);
355     if (aBaseIndex >= 0) {
356       ObjectPtr aBaseObj = aBaseRefList->object(aBaseIndex);
357       std::map<ObjectPtr, std::list<ObjectPtr> >::iterator aFound = aMapExistent.find(aBaseObj);
358       if (aFound != aMapExistent.end())
359         aFound->second.push_back(aCurrent);
360       else
361         anObjectsToRemove.push_back(aCurrent);
362     }
363     else
364       anObjectsToRemove.push_back(aCurrent);
365   }
366
367   // update lists of base shapes and of offset shapes
368   int aBaseListSize = aBaseRefList->size();
369   int anOffsetListSize = anOffsetRefList->size();
370   int aBaseListIndex = 0, anOffsetListIndex = 0;
371   std::list<int> anOffsetBaseBackRefs;
372   std::set<GeomShapePtr, GeomAPI_Shape::ComparatorWithOri> aProcessedOffsets;
373   for (std::list<ObjectPtr>::iterator aSIt = aSelectedList.begin();
374        aSIt != aSelectedList.end(); ++aSIt) {
375     // find an offseted edge
376     FeaturePtr aBaseFeature = ModelAPI_Feature::feature(*aSIt);
377     GeomShapePtr aBaseShape = aBaseFeature->lastResult()->shape();
378     ListOfShape aNewShapes;
379     for (ListOfMakeShape::const_iterator anAlgoIt = theOffsetAlgos.begin();
380          anAlgoIt != theOffsetAlgos.end(); ++anAlgoIt) {
381       (*anAlgoIt)->generated(aBaseShape, aNewShapes);
382       if (!aNewShapes.empty()) {
383         reorderShapes(aNewShapes, (*anAlgoIt)->shape());
384         break;
385       }
386     }
387
388     // store base feature
389     setRefListValue(aBaseRefList, aBaseListSize, *aSIt, aBaseListIndex);
390
391     // create or update an offseted feature
392     const std::list<ObjectPtr>& anImages = aMapExistent[*aSIt];
393     std::list<ObjectPtr>::const_iterator anImgIt = anImages.begin();
394     for (ListOfShape::iterator aNewIt = aNewShapes.begin(); aNewIt != aNewShapes.end(); ++aNewIt) {
395       FeaturePtr aNewFeature;
396       if (anImgIt != anImages.end())
397         aNewFeature = ModelAPI_Feature::feature(*anImgIt++);
398       updateExistentOrCreateNew(*aNewIt, aNewFeature, anObjectsToRemove);
399       aProcessedOffsets.insert(*aNewIt);
400
401       // store an offseted feature
402       setRefListValue(anOffsetRefList, anOffsetListSize, aNewFeature, anOffsetListIndex);
403
404       anOffsetBaseBackRefs.push_back(aBaseListIndex);
405       ++anOffsetListIndex;
406     }
407     ++aBaseListIndex;
408     anObjectsToRemove.insert(anObjectsToRemove.end(), anImgIt, anImages.end());
409   }
410   // create arcs generated from vertices
411   for (ListOfMakeShape::const_iterator anAlgoIt = theOffsetAlgos.begin();
412        anAlgoIt != theOffsetAlgos.end(); ++anAlgoIt) {
413     GeomShapePtr aCurWire = (*anAlgoIt)->shape();
414     GeomAPI_ShapeExplorer anExp(aCurWire, GeomAPI_Shape::EDGE);
415     for (; anExp.more(); anExp.next()) {
416       GeomShapePtr aCurEdge = anExp.current();
417       if (aProcessedOffsets.find(aCurEdge) == aProcessedOffsets.end()) {
418         FeaturePtr aNewFeature;
419         updateExistentOrCreateNew(aCurEdge, aNewFeature, anObjectsToRemove);
420         aProcessedOffsets.insert(aCurEdge);
421
422         // store an offseted feature
423         setRefListValue(anOffsetRefList, anOffsetListSize, aNewFeature, anOffsetListIndex);
424
425         anOffsetBaseBackRefs.push_back(-1);
426         ++anOffsetListIndex;
427       }
428     }
429   }
430
431   removeLastFromIndex(aBaseRefList, aBaseListSize, aBaseListIndex);
432   removeLastFromIndex(anOffsetRefList, anOffsetListSize, anOffsetListIndex);
433
434   anOffsetToBaseMap->setSize((int)anOffsetBaseBackRefs.size(), false);
435   int anIndex = 0;
436   for (std::list<int>::iterator anIt = anOffsetBaseBackRefs.begin();
437        anIt != anOffsetBaseBackRefs.end(); ++anIt) {
438     anOffsetToBaseMap->setValue(anIndex++, *anIt, false);
439   }
440
441   // remove unused objects
442   std::set<FeaturePtr> aSet;
443   for (std::list<ObjectPtr>::iterator anIt = anObjectsToRemove.begin();
444        anIt != anObjectsToRemove.end(); ++anIt) {
445     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
446     if (aFeature)
447       aSet.insert(aFeature);
448   }
449   ModelAPI_Tools::removeFeaturesAndReferences(aSet);
450 }
451
452 static void findOrCreateFeatureByKind(SketchPlugin_Sketch* theSketch,
453                                       const std::string& theFeatureKind,
454                                       FeaturePtr& theFeature,
455                                       std::list<ObjectPtr>& thePoolOfFeatures)
456 {
457   if (theFeature) {
458     // check the feature type is the same as required
459     if (theFeature->getKind() != theFeatureKind) {
460       // return feature to the pool and try to find the most appropriate
461       thePoolOfFeatures.push_back(theFeature);
462       theFeature = FeaturePtr();
463     }
464   }
465   if (!theFeature) {
466     // try to find appropriate feature in the pool
467     for (std::list<ObjectPtr>::iterator it = thePoolOfFeatures.begin();
468          it != thePoolOfFeatures.end(); ++it) {
469       FeaturePtr aCurFeature = ModelAPI_Feature::feature(*it);
470       if (aCurFeature->getKind() == theFeatureKind) {
471         theFeature = aCurFeature;
472         thePoolOfFeatures.erase(it);
473         break;
474       }
475     }
476     // feature not found, create new
477     if (!theFeature)
478       theFeature = theSketch->addFeature(theFeatureKind);
479   }
480 }
481
482 void SketchPlugin_Offset::updateExistentOrCreateNew(const GeomShapePtr& theShape,
483                                                     FeaturePtr& theFeature,
484                                                     std::list<ObjectPtr>& thePoolOfFeatures)
485 {
486   if (theShape->shapeType() != GeomAPI_Shape::EDGE)
487     return;
488
489   std::shared_ptr<GeomAPI_Edge> aResEdge(new GeomAPI_Edge(theShape));
490
491   std::shared_ptr<GeomAPI_Pnt2d> aFP, aLP;
492   std::shared_ptr<GeomAPI_Pnt> aFP3d = aResEdge->firstPoint();
493   std::shared_ptr<GeomAPI_Pnt> aLP3d = aResEdge->lastPoint();
494   if (aFP3d && aLP3d) {
495     aFP = sketch()->to2D(aFP3d);
496     aLP = sketch()->to2D(aLP3d);
497   }
498
499   if (aResEdge->isLine()) {
500     findOrCreateFeatureByKind(sketch(), SketchPlugin_Line::ID(), theFeature, thePoolOfFeatures);
501
502     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
503       (theFeature->attribute(SketchPlugin_Line::START_ID()))->setValue(aFP);
504     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
505       (theFeature->attribute(SketchPlugin_Line::END_ID()))->setValue(aLP);
506   }
507   else if (aResEdge->isArc()) {
508     std::shared_ptr<GeomAPI_Circ> aCircEdge = aResEdge->circle();
509     std::shared_ptr<GeomAPI_Pnt> aCP3d = aCircEdge->center();
510     std::shared_ptr<GeomAPI_Pnt2d> aCP = sketch()->to2D(aCP3d);
511
512     findOrCreateFeatureByKind(sketch(), SketchPlugin_Arc::ID(), theFeature, thePoolOfFeatures);
513
514     GeomDirPtr aCircNormal = aCircEdge->normal();
515     GeomDirPtr aSketchNormal = sketch()->coordinatePlane()->normal();
516     if (aSketchNormal->dot(aCircNormal) < -tolerance)
517       std::swap(aFP, aLP);
518
519     bool aWasBlocked = theFeature->data()->blockSendAttributeUpdated(true);
520     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
521       (theFeature->attribute(SketchPlugin_Arc::END_ID()))->setValue(aLP);
522     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
523       (theFeature->attribute(SketchPlugin_Arc::START_ID()))->setValue(aFP);
524     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
525       (theFeature->attribute(SketchPlugin_Arc::CENTER_ID()))->setValue(aCP);
526     theFeature->data()->blockSendAttributeUpdated(aWasBlocked);
527   }
528   else if (aResEdge->isCircle()) {
529     std::shared_ptr<GeomAPI_Circ> aCircEdge = aResEdge->circle();
530     std::shared_ptr<GeomAPI_Pnt> aCP3d = aCircEdge->center();
531     std::shared_ptr<GeomAPI_Pnt2d> aCP = sketch()->to2D(aCP3d);
532
533     findOrCreateFeatureByKind(sketch(), SketchPlugin_Circle::ID(), theFeature, thePoolOfFeatures);
534
535     std::dynamic_pointer_cast<GeomDataAPI_Point2D>
536       (theFeature->attribute(SketchPlugin_Circle::CENTER_ID()))->setValue(aCP);
537     theFeature->real(SketchPlugin_Circle::RADIUS_ID())->setValue(aCircEdge->radius());
538   }
539   else if (aResEdge->isEllipse()) {
540     std::shared_ptr<GeomAPI_Ellipse> anEllipseEdge = aResEdge->ellipse();
541
542     GeomPointPtr aCP3d = anEllipseEdge->center();
543     GeomPnt2dPtr aCP = sketch()->to2D(aCP3d);
544
545     GeomPointPtr aFocus3d = anEllipseEdge->firstFocus();
546     GeomPnt2dPtr aFocus = sketch()->to2D(aFocus3d);
547
548     if (aFP3d && aLP3d) {
549       // Elliptic arc
550       findOrCreateFeatureByKind(sketch(), SketchPlugin_EllipticArc::ID(),
551                                 theFeature, thePoolOfFeatures);
552
553       bool aWasBlocked = theFeature->data()->blockSendAttributeUpdated(true);
554       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
555         (theFeature->attribute(SketchPlugin_EllipticArc::CENTER_ID()))->setValue(aCP);
556       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
557         (theFeature->attribute(SketchPlugin_EllipticArc::FIRST_FOCUS_ID()))->setValue(aFocus);
558       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
559         (theFeature->attribute(SketchPlugin_EllipticArc::START_POINT_ID()))->setValue(aFP);
560       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
561         (theFeature->attribute(SketchPlugin_EllipticArc::END_POINT_ID()))->setValue(aLP);
562       theFeature->data()->blockSendAttributeUpdated(aWasBlocked);
563     }
564     else {
565       // Ellipse
566       findOrCreateFeatureByKind(sketch(), SketchPlugin_Ellipse::ID(),
567                                 theFeature, thePoolOfFeatures);
568
569       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
570         (theFeature->attribute(SketchPlugin_Ellipse::CENTER_ID()))->setValue(aCP);
571       std::dynamic_pointer_cast<GeomDataAPI_Point2D>
572         (theFeature->attribute(SketchPlugin_Ellipse::FIRST_FOCUS_ID()))->setValue(aFocus);
573       theFeature->real(SketchPlugin_Ellipse::MINOR_RADIUS_ID())->setValue(
574         anEllipseEdge->minorRadius());
575     }
576   }
577   else {
578     // convert to b-spline
579     mkBSpline(theFeature, aResEdge, thePoolOfFeatures);
580   }
581
582   if (theFeature.get()) {
583     theFeature->boolean(SketchPlugin_SketchEntity::COPY_ID())->setValue(true);
584     theFeature->execute();
585
586     static Events_ID aRedisplayEvent = Events_Loop::eventByName(EVENT_OBJECT_TO_REDISPLAY);
587     ModelAPI_EventCreator::get()->sendUpdated(theFeature, aRedisplayEvent);
588     const std::list<ResultPtr>& aResults = theFeature->results();
589     for (std::list<ResultPtr>::const_iterator anIt = aResults.begin();
590          anIt != aResults.end(); ++anIt)
591       ModelAPI_EventCreator::get()->sendUpdated(*anIt, aRedisplayEvent);
592   }
593 }
594
595 void SketchPlugin_Offset::mkBSpline (FeaturePtr& theResult,
596                                      const GeomEdgePtr& theEdge,
597                                      std::list<ObjectPtr>& thePoolOfFeatures)
598 {
599   GeomCurvePtr aCurve (new GeomAPI_Curve (theEdge));
600   // Forced conversion to b-spline, if aCurve is not b-spline
601   GeomBSplinePtr aBSpline = GeomAPI_BSpline::convertToBSpline(aCurve);
602
603   const std::string& aBSplineKind = aBSpline->isPeriodic() ? SketchPlugin_BSplinePeriodic::ID()
604                                                            : SketchPlugin_BSpline::ID();
605   findOrCreateFeatureByKind(sketch(), aBSplineKind, theResult, thePoolOfFeatures);
606
607   theResult->integer(SketchPlugin_BSpline::DEGREE_ID())->setValue(aBSpline->degree());
608
609   AttributePoint2DArrayPtr aPolesAttr = std::dynamic_pointer_cast<GeomDataAPI_Point2DArray>
610     (theResult->attribute(SketchPlugin_BSpline::POLES_ID()));
611   std::list<GeomPointPtr> aPoles = aBSpline->poles();
612   aPolesAttr->setSize((int)aPoles.size());
613   std::list<GeomPointPtr>::iterator anIt = aPoles.begin();
614   for (int anIndex = 0; anIt != aPoles.end(); ++anIt, ++anIndex) {
615     GeomPnt2dPtr aPoleInSketch = sketch()->to2D(*anIt);
616     aPolesAttr->setPnt(anIndex, aPoleInSketch);
617   }
618
619   AttributeDoubleArrayPtr aWeightsAttr =
620       theResult->data()->realArray(SketchPlugin_BSpline::WEIGHTS_ID());
621   std::list<double> aWeights = aBSpline->weights();
622   if (aWeights.empty()) { // rational B-spline
623     int aSize = (int)aPoles.size();
624     aWeightsAttr->setSize(aSize);
625     for (int anIndex = 0; anIndex < aSize; ++anIndex)
626       aWeightsAttr->setValue(anIndex, 1.0);
627   }
628   else { // non-rational B-spline
629     aWeightsAttr->setSize((int)aWeights.size());
630     std::list<double>::iterator anIt = aWeights.begin();
631     for (int anIndex = 0; anIt != aWeights.end(); ++anIt, ++anIndex)
632       aWeightsAttr->setValue(anIndex, *anIt);
633   }
634
635   AttributeDoubleArrayPtr aKnotsAttr =
636       theResult->data()->realArray(SketchPlugin_BSpline::KNOTS_ID());
637   std::list<double> aKnots = aBSpline->knots();
638   int aSize = (int)aKnots.size();
639   aKnotsAttr->setSize(aSize);
640   std::list<double>::iterator aKIt = aKnots.begin();
641   for (int index = 0; index < aSize; ++index, ++aKIt)
642     aKnotsAttr->setValue(index, *aKIt);
643
644   AttributeIntArrayPtr aMultsAttr =
645       theResult->data()->intArray(SketchPlugin_BSpline::MULTS_ID());
646   std::list<int> aMultiplicities = aBSpline->mults();
647   aSize = (int)aMultiplicities.size();
648   aMultsAttr->setSize(aSize);
649   std::list<int>::iterator aMIt = aMultiplicities.begin();
650   for (int index = 0; index < aSize; ++index, ++aMIt)
651     aMultsAttr->setValue(index, *aMIt);
652 }
653
654 void SketchPlugin_Offset::attributeChanged(const std::string& theID)
655 {
656 ////  if (theID == EDGES_ID())
657 ////    removeCreated();
658 }
659
660 bool SketchPlugin_Offset::customAction(const std::string& theActionId)
661 {
662   bool isOk = false;
663   if (theActionId == ADD_WIRE_ACTION_ID()) {
664     isOk = findWires();
665   }
666   else {
667     std::string aMsg = "Error: Feature \"%1\" does not support action \"%2\".";
668     Events_InfoMessage("SketchPlugin_Offset", aMsg).arg(getKind()).arg(theActionId).send();
669   }
670   return isOk;
671 }
672
673 bool SketchPlugin_Offset::findWires()
674 {
675   AttributeRefListPtr aSelectedEdges = reflist(EDGES_ID());
676   std::list<ObjectPtr> anEdgesList = aSelectedEdges->list();
677
678   // Empty set
679   std::set<FeaturePtr> anEdgesSet;
680
681   // Processed set
682   std::set<FeaturePtr> aProcessedSet;
683
684   // Put all selected edges in a set to avoid adding them in reflist(EDGES_ID())
685   std::set<FeaturePtr> aSelectedSet;
686   std::list<ObjectPtr>::const_iterator anEdgesIt = anEdgesList.begin();
687   for (; anEdgesIt != anEdgesList.end(); anEdgesIt++) {
688     FeaturePtr aFeature = ModelAPI_Feature::feature(*anEdgesIt);
689     if (aFeature) {
690       aSelectedSet.insert(aFeature);
691     }
692   }
693
694   bool aWasBlocked = data()->blockSendAttributeUpdated(true);
695
696   // Gather chains of edges
697   for (anEdgesIt = anEdgesList.begin(); anEdgesIt != anEdgesList.end(); anEdgesIt++) {
698     FeaturePtr aFeature = ModelAPI_Feature::feature(*anEdgesIt);
699     if (aFeature.get()) {
700       if (aProcessedSet.find(aFeature) != aProcessedSet.end())
701         continue;
702       aProcessedSet.insert(aFeature);
703
704       // End points (if any)
705       std::shared_ptr<GeomDataAPI_Point2D> aStartPoint, anEndPoint;
706       SketchPlugin_SegmentationTools::getFeaturePoints(aFeature, aStartPoint, anEndPoint);
707
708       std::list<FeaturePtr> aChain;
709       aChain.push_back(aFeature);
710       bool isClosed = findWireOneWay(aFeature, aFeature, aStartPoint, anEdgesSet, aChain, true);
711       if (!isClosed)
712         findWireOneWay(aFeature, aFeature, anEndPoint, anEdgesSet, aChain, false);
713
714       std::list<FeaturePtr>::iterator aChainIt = aChain.begin();
715       for (; aChainIt != aChain.end(); ++aChainIt) {
716         FeaturePtr aChainFeature = (*aChainIt);
717         aProcessedSet.insert(aChainFeature);
718         if (aSelectedSet.find(aChainFeature) == aSelectedSet.end()) {
719           aSelectedEdges->append(aChainFeature->lastResult());
720         }
721       }
722     }
723   }
724   // TODO: hilight selection in the viewer
725
726   data()->blockSendAttributeUpdated(aWasBlocked);
727   return true;
728 }
729
730
731 AISObjectPtr SketchPlugin_Offset::getAISObject(AISObjectPtr thePrevious)
732 {
733   if (!sketch())
734     return thePrevious;
735
736   AISObjectPtr anAIS = SketcherPrs_Factory::offsetObject(this, sketch(),
737     thePrevious);
738   return anAIS;
739 }