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