Salome HOME
Copyright update 2020
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Sketch.cpp
1 // Copyright (C) 2014-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <Config_PropManager.h>
21
22 #include <GeomAlgoAPI_CompoundBuilder.h>
23 #include <GeomAlgoAPI_EdgeBuilder.h>
24 #include <GeomAlgoAPI_FaceBuilder.h>
25
26 #include <GeomAPI_Dir.h>
27 #include <GeomAPI_Lin.h>
28 #include <GeomAPI_PlanarEdges.h>
29 #include <GeomAPI_ShapeIterator.h>
30 #include <GeomAPI_Vertex.h>
31
32 #include <GeomDataAPI_Point2D.h>
33 #include <GeomAlgoAPI_PointBuilder.h>
34
35 #include <ModelAPI_AttributeRefList.h>
36 #include <ModelAPI_AttributeString.h>
37 #include <ModelAPI_Data.h>
38 #include <ModelAPI_Document.h>
39 #include <ModelAPI_Feature.h>
40 #include <ModelAPI_Object.h>
41 #include <ModelAPI_ResultConstruction.h>
42 #include <ModelAPI_Validator.h>
43 #include <ModelAPI_Session.h>
44 #include <ModelAPI_Events.h>
45
46 #include <SketchPlugin_Sketch.h>
47 #include <SketchPlugin_Feature.h>
48 #include <SketchPlugin_IntersectionPoint.h>
49 #include <SketchPlugin_Projection.h>
50 #include <SketchPlugin_SketchEntity.h>
51 #include <SketchPlugin_Tools.h>
52
53 #include <Events_InfoMessage.h>
54 #include <Events_Loop.h>
55
56 #include <memory>
57
58 #include <math.h>
59 #include <vector>
60
61 SketchPlugin_Sketch::SketchPlugin_Sketch()
62 {
63 }
64
65 void SketchPlugin_Sketch::initAttributes()
66 {
67   data()->addAttribute(SketchPlugin_Sketch::ORIGIN_ID(), GeomDataAPI_Point::typeId());
68   data()->addAttribute(SketchPlugin_Sketch::DIRX_ID(), GeomDataAPI_Dir::typeId());
69   data()->addAttribute(SketchPlugin_Sketch::NORM_ID(), GeomDataAPI_Dir::typeId());
70   data()->addAttribute(SketchPlugin_Sketch::FEATURES_ID(), ModelAPI_AttributeRefList::typeId());
71   // the selected face, base for the sketcher plane, not obligatory
72   data()->addAttribute(SketchPlugin_SketchEntity::EXTERNAL_ID(),
73     ModelAPI_AttributeSelection::typeId());
74   ModelAPI_Session::get()->validators()->registerNotObligatory(
75     getKind(), SketchPlugin_SketchEntity::EXTERNAL_ID());
76   data()->addAttribute(SketchPlugin_Sketch::SOLVER_ERROR(), ModelAPI_AttributeString::typeId());
77   ModelAPI_Session::get()->validators()->registerNotObligatory(
78     getKind(), SketchPlugin_Sketch::SOLVER_ERROR());
79   data()->addAttribute(SketchPlugin_Sketch::SOLVER_DOF(), ModelAPI_AttributeString::typeId());
80   ModelAPI_Session::get()->validators()->registerNotObligatory(
81     getKind(), SketchPlugin_Sketch::SOLVER_DOF());
82 }
83
84 void SketchPlugin_Sketch::execute()
85 {
86   if (!data()->isValid())
87     return;
88   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
89       ModelAPI_AttributeRefList>(data()->attribute(SketchPlugin_Sketch::FEATURES_ID()));
90
91   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
92       data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
93   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
94       data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
95   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
96       data()->attribute(SketchPlugin_Sketch::NORM_ID()));
97
98   std::list<ObjectPtr> aFeatures = aRefList->list();
99   if (aFeatures.empty()) // actually, this must be avoided by the validators
100     return;
101
102   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin(), aLast = aFeatures.end();
103   std::shared_ptr<SketchPlugin_Feature> aFeature;
104   std::list<std::shared_ptr<GeomAPI_Shape> > aFeaturesPreview;
105   for (; anIt != aLast; anIt++) {
106     aFeature = std::dynamic_pointer_cast<SketchPlugin_Feature>(*anIt);
107     if (aFeature) {
108       if (!aFeature->sketch()) // on load document the back references are missed
109         aFeature->setSketch(this);
110       // do not include into the result the external edges with disabled flag "Include into result"
111       if (aFeature->data()->attribute(SketchPlugin_SketchEntity::EXTERNAL_ID())) {
112         if (aFeature->data()->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->context()) {
113           const std::string& anAttrName =
114               aFeature->getKind() == SketchPlugin_Projection::ID() ?
115               SketchPlugin_Projection::INCLUDE_INTO_RESULT() :
116               SketchPlugin_IntersectionPoint::INCLUDE_INTO_RESULT();
117           AttributeBooleanPtr aKeepResult = aFeature->boolean(anAttrName);
118           if (!aKeepResult || !aKeepResult->value())
119             continue;
120         }
121       }
122       // do not include the construction entities in the result
123       if (aFeature->data()->attribute(SketchPlugin_SketchEntity::AUXILIARY_ID())) {
124         if (aFeature->data()->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->value())
125           continue;
126       }
127
128       const std::list<std::shared_ptr<ModelAPI_Result> >& aRes = aFeature->results();
129       std::list<std::shared_ptr<ModelAPI_Result> >::const_iterator aResIter = aRes.cbegin();
130       for (; aResIter != aRes.cend(); aResIter++) {
131         std::shared_ptr<ModelAPI_ResultConstruction> aConstr = std::dynamic_pointer_cast<
132             ModelAPI_ResultConstruction>(*aResIter);
133         if (aConstr) {
134           std::shared_ptr<GeomAPI_Shape> aShape = aConstr->shape();
135           if (aShape)
136             aFeaturesPreview.push_back(aShape);
137         }
138       }
139     }
140   }
141
142   // Collect all edges as one big wire
143   std::shared_ptr<GeomAPI_PlanarEdges> aBigWire(new GeomAPI_PlanarEdges);
144   std::list<std::shared_ptr<GeomAPI_Shape> >::const_iterator aShapeIt = aFeaturesPreview.begin();
145   for (; aShapeIt != aFeaturesPreview.end(); ++aShapeIt) {
146     aBigWire->addEdge(*aShapeIt);
147   }
148   aBigWire->setPlane(anOrigin->pnt(), aDirX->dir(), aNorm->dir());
149   std::shared_ptr<ModelAPI_ResultConstruction> aConstr = document()->createConstruction(data());
150   aConstr->setShape(aBigWire);
151   setResult(aConstr);
152 }
153
154 std::shared_ptr<ModelAPI_Feature> SketchPlugin_Sketch::addFeature(std::string theID)
155 {
156   // Set last feature of the sketch as current feature.
157   // Reason: Changing of parameter through Python API may lead to creation of new features
158   //         (e.g. changing number of copies in MultiRotation). If the sketch is not the last
159   //         feature in the Object Browser, then new features will be added to the end feature.
160   //         Therefore, setting any feature below the sketch as a current feature will disable
161   //         these newly created features.
162   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
163       ModelAPI_AttributeRefList>(data()->attribute(SketchPlugin_Sketch::FEATURES_ID()));
164   int aSize = aRefList->size(false);
165   ObjectPtr aLastObject = aSize == 0 ? data()->owner() : aRefList->object(aSize - 1, false);
166   FeaturePtr aLastFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aLastObject);
167   document()->setCurrentFeature(aLastFeature, false);
168
169   // add new feature
170   std::shared_ptr<ModelAPI_Feature> aNew = document()->addFeature(theID, false);
171   if (aNew) {
172     // the sketch cannot be specified for the macro-features defined in python
173     // like SketchRectangle, so we need to check the type of new feature
174     std::shared_ptr<SketchPlugin_Feature> aSketchFeature =
175         std::dynamic_pointer_cast<SketchPlugin_Feature>(aNew);
176     if (aSketchFeature)
177       aSketchFeature->setSketch(this);
178     data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->append(aNew);
179   }
180    // set as current also after it becomes sub to set correctly enabled for other sketch subs
181   document()->setCurrentFeature(aNew, false);
182
183   return aNew;
184 }
185
186 void SketchPlugin_Sketch::removeFeature(std::shared_ptr<ModelAPI_Feature> theFeature)
187 {
188   if (!data()->isValid()) // sketch is already removed (case on undo of sketch), sync is not needed
189     return;
190   AttributeRefListPtr aList = reflist(SketchPlugin_Sketch::FEATURES_ID());
191   // if the object is last, remove it from the list
192   // (needed to skip empty transaction on edit of sketch feature)
193   if (aList->object(aList->size(true) - 1, true) == theFeature) {
194     aList->remove(theFeature);
195   } else {
196     // to keep the persistent sub-elements indexing, do not remove elements from list,
197     // but substitute by nulls
198     aList->substitute(theFeature, ObjectPtr());
199   }
200 }
201
202 int SketchPlugin_Sketch::numberOfSubs(bool forTree) const
203 {
204   if (forTree)
205     return 0;
206   return data()->reflist(FEATURES_ID())->size(false);
207 }
208
209 std::shared_ptr<ModelAPI_Feature> SketchPlugin_Sketch::subFeature(
210   const int theIndex, bool forTree)
211 {
212   if (forTree)
213     return FeaturePtr();
214
215   ObjectPtr anObj = data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->object(theIndex, false);
216   FeaturePtr aRes = std::dynamic_pointer_cast<ModelAPI_Feature>(anObj);
217   return aRes;
218 }
219
220 int SketchPlugin_Sketch::subFeatureId(const int theIndex) const
221 {
222   std::shared_ptr<ModelAPI_AttributeRefList> aRefList = std::dynamic_pointer_cast<
223       ModelAPI_AttributeRefList>(data()->attribute(SketchPlugin_Sketch::FEATURES_ID()));
224   std::list<ObjectPtr> aFeatures = aRefList->list();
225   std::list<ObjectPtr>::const_iterator anIt = aFeatures.begin();
226   int aResultIndex = 1; // number of the counted (created) features, started from 1
227   int aFeatureIndex = -1; // number of the not-empty features in the list
228   for (; anIt != aFeatures.end(); anIt++) {
229     if (anIt->get())
230       aFeatureIndex++;
231     if (aFeatureIndex == theIndex)
232       break;
233     aResultIndex++;
234   }
235   return aResultIndex;
236 }
237
238 bool SketchPlugin_Sketch::isSub(ObjectPtr theObject) const
239 {
240   // check is this feature of result
241   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(theObject);
242   if (!aFeature) {
243     ResultPtr aRes = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
244     if (aRes)
245       aFeature = document()->feature(aRes);
246   }
247   if (aFeature) {
248     return data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->isInList(aFeature);
249   }
250   return false;
251 }
252
253
254 static bool isOrigin(const GeomPointPtr& thePoint, const double theTolerance)
255 {
256   return fabs(thePoint->x()) < theTolerance &&
257          fabs(thePoint->y()) < theTolerance &&
258          fabs(thePoint->z()) < theTolerance;
259 }
260
261 static bool isCoordinateAxis(const GeomDirPtr& theDir, const double theTolerance)
262 {
263   return fabs(theDir->x() - 1.0) < theTolerance || fabs(theDir->x() + 1.0) < theTolerance ||
264          fabs(theDir->y() - 1.0) < theTolerance || fabs(theDir->y() + 1.0) < theTolerance ||
265          fabs(theDir->z() - 1.0) < theTolerance || fabs(theDir->z() + 1.0) < theTolerance;
266 }
267
268 static bool isCoordinatePlane(const GeomAx3Ptr& thePlane)
269 {
270   static const double THE_TOLERANCE = 1.e-7;
271   if (!thePlane)
272     return false;
273
274   GeomPointPtr anOrigin = thePlane->origin();
275   GeomDirPtr aNormal = thePlane->normal();
276   GeomDirPtr aDirX = thePlane->dirX();
277
278   return isOrigin(anOrigin, THE_TOLERANCE) &&
279          isCoordinateAxis(aNormal, THE_TOLERANCE) &&
280          isCoordinateAxis(aDirX, THE_TOLERANCE);
281 }
282
283 void SketchPlugin_Sketch::attributeChanged(const std::string& theID) {
284   if (theID == SketchPlugin_SketchEntity::EXTERNAL_ID()) {
285     AttributeSelectionPtr aSelAttr = selection(SketchPlugin_SketchEntity::EXTERNAL_ID());
286     if (aSelAttr->context().get()) { // update arguments due to the selection value
287       std::shared_ptr<GeomAPI_Shape> aSelection = aSelAttr->value();
288       if (!aSelection.get()) aSelection = aSelAttr->context()->shape();
289       // update the sketch plane
290       std::shared_ptr<GeomAPI_Face> aFace;
291       if (aSelection->isFace()) {
292         aFace = aSelection->face();
293       } else if (aSelection->isCompound()) {
294         GeomAPI_ShapeIterator anIt(aSelection);
295         aFace = anIt.current()->face();
296       }
297       if (aFace.get()) {
298         std::shared_ptr<GeomAPI_Pln> aPlane = aFace->getPlane();
299         if (aPlane.get()) {
300           double anA, aB, aC, aD;
301           aPlane->coefficients(anA, aB, aC, aD);
302
303           // calculate attributes of the sketch
304           std::shared_ptr<GeomAPI_Dir> aNormDir(new GeomAPI_Dir(anA, aB, aC));
305           std::shared_ptr<GeomAPI_XYZ> aCoords = aNormDir->xyz();
306           std::shared_ptr<GeomAPI_XYZ> aZero(new GeomAPI_XYZ(0, 0, 0));
307           aCoords = aCoords->multiplied(-aD * aCoords->distance(aZero));
308           std::shared_ptr<GeomAPI_Pnt> anOrigPnt(new GeomAPI_Pnt(aCoords));
309           // X axis is preferable to be dirX on the sketch
310           // here can not be very small value to avoid very close to X normal axis (issue 595)
311           static const double tol = 0.1;
312           bool isX = fabs(anA) - 1.0 < tol && fabs(aB) < tol && fabs(aC) < tol;
313           std::shared_ptr<GeomAPI_Dir> aTempDir(
314             isX ? new GeomAPI_Dir(0, 1, 0) : new GeomAPI_Dir(1, 0, 0));
315           std::shared_ptr<GeomAPI_Dir> aYDir(new GeomAPI_Dir(aNormDir->cross(aTempDir)));
316           std::shared_ptr<GeomAPI_Dir> aXDir(new GeomAPI_Dir(aYDir->cross(aNormDir)));
317
318           bool aWasBlocked = data()->blockSendAttributeUpdated(true);
319           // update position of the sketch
320           std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast
321             <GeomDataAPI_Point>(data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
322           anOrigin->setValue(anOrigPnt);
323           std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
324             data()->attribute(SketchPlugin_Sketch::NORM_ID()));
325           aNormal->setValue(aNormDir);
326           std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
327             data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
328           aDirX->setValue(aXDir);
329           data()->blockSendAttributeUpdated(aWasBlocked, true);
330         }
331       }
332     }
333   } else if (theID == NORM_ID() || theID == DIRX_ID() || theID == ORIGIN_ID()) {
334     // check if current and previous sketch planes are coordinate planes and they are different
335     GeomAx3Ptr aCurPlane;
336     bool areCoordPlanes = false;
337     if (isPlaneSet()) {
338       aCurPlane = coordinatePlane();
339       areCoordPlanes = isCoordinatePlane(aCurPlane) && isCoordinatePlane(myPlane);
340     }
341
342     // send all sub-elements are also updated: all entities become created on different plane
343     static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
344     std::list<ObjectPtr> aSubs = data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->list();
345     std::list<ObjectPtr>::iterator aSub = aSubs.begin();
346     for(; aSub != aSubs.end(); aSub++) {
347       if (aSub->get()) {
348         if (areCoordPlanes)
349           updateCoordinateAxis(*aSub, aCurPlane);
350
351         ModelAPI_EventCreator::get()->sendUpdated(*aSub, anUpdateEvent);
352       }
353     }
354     if (aCurPlane)
355       myPlane = aCurPlane;
356   }
357 }
358
359 void SketchPlugin_Sketch::createPoint2DResult(ModelAPI_Feature* theFeature,
360                                               SketchPlugin_Sketch* theSketch,
361                                               const std::string& theAttributeID, const int theIndex)
362 {
363   std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
364     theFeature->attribute(theAttributeID));
365
366   if (!aPoint || !aPoint->isInitialized())
367     return;
368
369   std::shared_ptr<GeomAPI_Pnt> aCenter(theSketch->to3D(aPoint->x(), aPoint->y()));
370   //std::cout<<"Execute circle "<<aCenter->x()<<" "<<aCenter->y()<<" "<<aCenter->z()<<std::endl;
371   // make a visible point
372   std::shared_ptr<GeomAPI_Shape> aCenterPointShape = GeomAlgoAPI_PointBuilder::vertex(aCenter);
373   std::shared_ptr<ModelAPI_ResultConstruction> aResult = theFeature->document()->createConstruction(
374                      theFeature->data(), theIndex);
375   aResult->setShape(aCenterPointShape);
376   aResult->setIsInHistory(false);
377
378   theFeature->setResult(aResult, theIndex);
379 }
380
381 void SketchPlugin_Sketch::createLine2DResult(ModelAPI_Feature* theFeature,
382                                              SketchPlugin_Sketch* theSketch,
383                                              const std::string& theStartAttrID,
384                                              const std::string& theEndAttrID,
385                                              const int theIndex)
386 {
387   std::shared_ptr<GeomDataAPI_Point2D> aStartAttr =
388       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theFeature->attribute(theStartAttrID));
389   std::shared_ptr<GeomDataAPI_Point2D> anEndAttr =
390       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theFeature->attribute(theEndAttrID));
391
392   if (!aStartAttr || !aStartAttr->isInitialized() ||
393       !anEndAttr || !anEndAttr->isInitialized())
394     return;
395
396   std::shared_ptr<GeomAPI_Pnt> aStart(theSketch->to3D(aStartAttr->x(), aStartAttr->y()));
397   std::shared_ptr<GeomAPI_Pnt> anEnd(theSketch->to3D(anEndAttr->x(), anEndAttr->y()));
398   //std::cout<<"Execute line "<<aStart->x()<<" "<<aStart->y()<<" "<<aStart->z()<<" - "
399   //  <<anEnd->x()<<" "<<anEnd->y()<<" "<<anEnd->z()<<std::endl;
400   // make linear edge
401   std::shared_ptr<GeomAPI_Edge> anEdge = GeomAlgoAPI_EdgeBuilder::line(aStart, anEnd);
402   // store the result
403   std::shared_ptr<ModelAPI_ResultConstruction> aResult =
404       theFeature->document()->createConstruction(theFeature->data(), theIndex);
405   aResult->setShape(anEdge);
406   aResult->setIsInHistory(false);
407   theFeature->setResult(aResult, theIndex);
408 }
409
410 FeaturePtr SketchPlugin_Sketch::addUniqueNamedCopiedFeature(FeaturePtr theFeature,
411                                                             SketchPlugin_Sketch* theSketch,
412                                                             const bool theIsCopy)
413 {
414   FeaturePtr aNewFeature = theSketch->addFeature(theFeature->getKind());
415   // addFeature generates a unique name for the feature, it caches the name
416   std::string aUniqueFeatureName = aNewFeature->data()->name();
417   // all attribute values are copied\pasted to the new feature, name is not an exception
418   theFeature->data()->copyTo(aNewFeature->data());
419   // external state should not be copied as a new object is an object of the current sketch
420   if (theFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID()).get())
421     aNewFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->setValue(ResultPtr(),
422                                                                                GeomShapePtr());
423   aNewFeature->data()->setName(aUniqueFeatureName);
424   // text expressions could block setValue of some attributes
425   SketchPlugin_Tools::clearExpressions(aNewFeature);
426   // Set copy attribute
427   AttributeBooleanPtr anAttr = aNewFeature->data()->boolean(SketchPlugin_SketchEntity::COPY_ID());
428   if(anAttr.get()) {
429     anAttr->setValue(theIsCopy);
430   }
431
432   return aNewFeature;
433 }
434
435 std::shared_ptr<GeomAPI_Ax3> SketchPlugin_Sketch::plane(SketchPlugin_Sketch* theSketch)
436 {
437   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
438
439   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
440       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
441   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
442       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
443   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
444       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
445
446   if (aNorm.get() && aNorm->isInitialized() && anOrigin.get() && anOrigin->isInitialized())
447     return std::shared_ptr<GeomAPI_Ax3>(
448       new GeomAPI_Ax3(anOrigin->pnt(), aDirX->dir(), aNorm->dir()));
449
450   return std::shared_ptr<GeomAPI_Ax3>();
451 }
452
453 bool SketchPlugin_Sketch::customAction(const std::string& theActionId)
454 {
455   bool isOk = false;
456   if (theActionId == ACTION_REMOVE_EXTERNAL())
457     isOk = removeLinksToExternal();
458   else {
459     std::string aMsg = "Error: Feature \"%1\" does not support action \"%2\".";
460     Events_InfoMessage("SketchPlugin_Sketch", aMsg).arg(getKind()).arg(theActionId).send();
461   }
462   return isOk;
463 }
464
465 static bool isExternalBased(const FeaturePtr theFeature)
466 {
467   return theFeature->getKind() == SketchPlugin_Projection::ID() ||
468          theFeature->getKind() == SketchPlugin_IntersectionPoint::ID();
469 }
470
471 bool SketchPlugin_Sketch::removeLinksToExternal()
472 {
473   std::list<FeaturePtr> aRemove;
474   std::list<ObjectPtr> aSubs = reflist(FEATURES_ID())->list();
475   for (std::list<ObjectPtr>::iterator anIt = aSubs.begin(); anIt != aSubs.end(); ++anIt) {
476     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
477     if (!aFeature)
478       continue;
479     if (isExternalBased(aFeature)) {
480       // mark feature as to be removed
481       aRemove.push_back(aFeature);
482     }
483     else {
484       AttributeSelectionPtr anExtAttr =
485           aFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID());
486       ResultPtr anExternal = anExtAttr ? anExtAttr->context() : ResultPtr();
487       if (anExternal) {
488         FeaturePtr anExtFeature = ModelAPI_Feature::feature(anExternal);
489         if (anExtFeature && isExternalBased(anExtFeature)) {
490           // make result of projection/intersection as non-external,
491           aFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->setValue(
492             ObjectPtr(), GeomShapePtr());
493           // set feature auxiliary if the parent is not included into sketch result
494           bool isIncludedToSketchResult = false;
495           if (anExtFeature->getKind() == SketchPlugin_Projection::ID()) {
496             isIncludedToSketchResult = anExtFeature->boolean(
497                 SketchPlugin_Projection::INCLUDE_INTO_RESULT())->value();
498           }
499           if (anExtFeature->getKind() == SketchPlugin_IntersectionPoint::ID()) {
500             isIncludedToSketchResult = anExtFeature->boolean(
501                 SketchPlugin_IntersectionPoint::INCLUDE_INTO_RESULT())->value();
502           }
503
504           aFeature->boolean(SketchPlugin_SketchEntity::COPY_ID())->setValue(false);
505           aFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(
506               !isIncludedToSketchResult);
507         }
508       }
509     }
510   }
511   for (std::list<FeaturePtr>::iterator anIt = aRemove.begin(); anIt != aRemove.end(); ++anIt)
512     document()->removeFeature(*anIt);
513   return true;
514 }
515
516
517 static ObjectPtr findAxis(GeomShapePtr theAxisToCompare,
518                           ObjectPtr theOX,
519                           ObjectPtr theOY,
520                           ObjectPtr theOZ)
521 {
522   if (theAxisToCompare) {
523     ObjectPtr anAxes[] = { theOX, theOY, theOZ };
524     for (int i = 0; i < 3; ++i) {
525       ResultPtr anAx = std::dynamic_pointer_cast<ModelAPI_Result>(anAxes[i]);
526       if (anAx && theAxisToCompare->isEqual(anAx->shape()))
527         return anAxes[i];
528     }
529   }
530   return ObjectPtr();
531 }
532
533 static ObjectPtr findAxis(ObjectPtr theAxisToCompare,
534                           ObjectPtr theOX,
535                           ObjectPtr theOY,
536                           ObjectPtr theOZ)
537 {
538   if (theAxisToCompare == theOX)
539     return theOX;
540   else if (theAxisToCompare == theOY)
541     return theOY;
542   else if (theAxisToCompare == theOZ)
543     return theOZ;
544   // nothing helped, search by shape
545   ResultPtr anAxis = std::dynamic_pointer_cast<ModelAPI_Result>(theAxisToCompare);
546   return findAxis(anAxis ? anAxis->shape() : GeomShapePtr(), theOX, theOY, theOZ);
547 }
548
549 GeomShapePtr axisOnNewPlane(ObjectPtr theAxis, GeomAx3Ptr theOldPlane, GeomAx3Ptr theNewPlane)
550 {
551   ResultPtr anAxis = std::dynamic_pointer_cast<ModelAPI_Result>(theAxis);
552   if (!anAxis)
553     return GeomShapePtr();
554
555   GeomEdgePtr anAxisEdge = anAxis->shape()->edge();
556   GeomLinePtr anAxisLine = anAxisEdge->line();
557   GeomDirPtr anAxisDir = anAxisLine->direction();
558
559   double aFirstParam, aLastParam;
560   anAxisEdge->getRange(aFirstParam, aLastParam);
561
562   if (theOldPlane->dirX()->isParallel(anAxisDir))
563     anAxisDir = theNewPlane->dirX();
564   else if (theOldPlane->dirY()->isParallel(anAxisDir))
565     anAxisDir = theNewPlane->dirY();
566   else if (theOldPlane->normal()->isParallel(anAxisDir))
567     anAxisDir = theNewPlane->normal();
568
569   GeomPointPtr aFirstPoint(new GeomAPI_Pnt(aFirstParam * anAxisDir->x(),
570                                            aFirstParam * anAxisDir->y(),
571                                            aFirstParam * anAxisDir->z()));
572   GeomPointPtr aLastPoint(new GeomAPI_Pnt(aLastParam * anAxisDir->x(),
573                                           aLastParam * anAxisDir->y(),
574                                           aLastParam * anAxisDir->z()));
575   return GeomAlgoAPI_EdgeBuilder::line(aFirstPoint, aLastPoint);
576 }
577
578 void  SketchPlugin_Sketch::updateCoordinateAxis(ObjectPtr theSub, GeomAx3Ptr thePlane)
579 {
580   FeaturePtr aFeature = ModelAPI_Feature::feature(theSub);
581   if (!aFeature)
582     return;
583
584   DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
585   ObjectPtr anOX = aRootDoc->objectByName(ModelAPI_ResultConstruction::group(), "OX");
586   ObjectPtr anOY = aRootDoc->objectByName(ModelAPI_ResultConstruction::group(), "OY");
587   ObjectPtr anOZ = aRootDoc->objectByName(ModelAPI_ResultConstruction::group(), "OZ");
588
589   AttributeSelectionPtr anExtFeature;
590   if (aFeature->getKind() == SketchPlugin_Projection::ID())
591     anExtFeature = aFeature->selection(SketchPlugin_Projection::EXTERNAL_FEATURE_ID());
592   else if (aFeature->getKind() == SketchPlugin_IntersectionPoint::ID())
593     anExtFeature = aFeature->selection(SketchPlugin_IntersectionPoint::EXTERNAL_FEATURE_ID());
594   else
595     return;
596
597   ObjectPtr aContext = anExtFeature->context();
598   GeomShapePtr aShape = anExtFeature->value();
599   if (!aShape) { // selected object is a construction
600     ObjectPtr anAxis = findAxis(aContext, anOX, anOY, anOZ);
601     GeomShapePtr aNewAxis = axisOnNewPlane(anAxis, myPlane, thePlane);
602     anAxis = findAxis(aNewAxis, anOX, anOY, anOZ);
603     if (anAxis)
604       anExtFeature->setValue(anAxis, aShape);
605   }
606 }