Salome HOME
Merge remote-tracking branch 'origin/CEA_2019'
[modules/shaper.git] / src / SketchPlugin / SketchPlugin_Sketch.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <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           // update position of the sketch
319           std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast
320             <GeomDataAPI_Point>(data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
321           anOrigin->setValue(anOrigPnt);
322           std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
323             data()->attribute(SketchPlugin_Sketch::NORM_ID()));
324           aNormal->setValue(aNormDir);
325           std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
326             data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
327           aDirX->setValue(aXDir);
328           std::shared_ptr<GeomAPI_Dir> aDir = aPlane->direction();
329         }
330       }
331     }
332   } else if (theID == NORM_ID() || theID == DIRX_ID() || theID == ORIGIN_ID()) {
333     // check if current and previous sketch planes are coordinate planes and they are different
334     GeomAx3Ptr aCurPlane;
335     bool areCoordPlanes = false;
336     if (isPlaneSet()) {
337       aCurPlane = coordinatePlane();
338       areCoordPlanes = isCoordinatePlane(aCurPlane) && isCoordinatePlane(myPlane);
339     }
340
341     // send all sub-elements are also updated: all entities become created on different plane
342     static Events_ID anUpdateEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
343     std::list<ObjectPtr> aSubs = data()->reflist(SketchPlugin_Sketch::FEATURES_ID())->list();
344     std::list<ObjectPtr>::iterator aSub = aSubs.begin();
345     for(; aSub != aSubs.end(); aSub++) {
346       if (aSub->get()) {
347         if (areCoordPlanes)
348           updateCoordinateAxis(*aSub, aCurPlane);
349
350         ModelAPI_EventCreator::get()->sendUpdated(*aSub, anUpdateEvent);
351       }
352     }
353     if (aCurPlane)
354       myPlane = aCurPlane;
355   }
356 }
357
358 void SketchPlugin_Sketch::createPoint2DResult(ModelAPI_Feature* theFeature,
359                                               SketchPlugin_Sketch* theSketch,
360                                               const std::string& theAttributeID, const int theIndex)
361 {
362   std::shared_ptr<GeomDataAPI_Point2D> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
363     theFeature->attribute(theAttributeID));
364
365   if (!aPoint || !aPoint->isInitialized())
366     return;
367
368   std::shared_ptr<GeomAPI_Pnt> aCenter(theSketch->to3D(aPoint->x(), aPoint->y()));
369   //std::cout<<"Execute circle "<<aCenter->x()<<" "<<aCenter->y()<<" "<<aCenter->z()<<std::endl;
370   // make a visible point
371   std::shared_ptr<GeomAPI_Shape> aCenterPointShape = GeomAlgoAPI_PointBuilder::vertex(aCenter);
372   std::shared_ptr<ModelAPI_ResultConstruction> aResult = theFeature->document()->createConstruction(
373                      theFeature->data(), theIndex);
374   aResult->setShape(aCenterPointShape);
375   aResult->setIsInHistory(false);
376
377   theFeature->setResult(aResult, theIndex);
378 }
379
380 void SketchPlugin_Sketch::createLine2DResult(ModelAPI_Feature* theFeature,
381                                              SketchPlugin_Sketch* theSketch,
382                                              const std::string& theStartAttrID,
383                                              const std::string& theEndAttrID,
384                                              const int theIndex)
385 {
386   std::shared_ptr<GeomDataAPI_Point2D> aStartAttr =
387       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theFeature->attribute(theStartAttrID));
388   std::shared_ptr<GeomDataAPI_Point2D> anEndAttr =
389       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theFeature->attribute(theEndAttrID));
390
391   if (!aStartAttr || !aStartAttr->isInitialized() ||
392       !anEndAttr || !anEndAttr->isInitialized())
393     return;
394
395   std::shared_ptr<GeomAPI_Pnt> aStart(theSketch->to3D(aStartAttr->x(), aStartAttr->y()));
396   std::shared_ptr<GeomAPI_Pnt> anEnd(theSketch->to3D(anEndAttr->x(), anEndAttr->y()));
397   //std::cout<<"Execute line "<<aStart->x()<<" "<<aStart->y()<<" "<<aStart->z()<<" - "
398   //  <<anEnd->x()<<" "<<anEnd->y()<<" "<<anEnd->z()<<std::endl;
399   // make linear edge
400   std::shared_ptr<GeomAPI_Edge> anEdge = GeomAlgoAPI_EdgeBuilder::line(aStart, anEnd);
401   // store the result
402   std::shared_ptr<ModelAPI_ResultConstruction> aResult =
403       theFeature->document()->createConstruction(theFeature->data(), theIndex);
404   aResult->setShape(anEdge);
405   aResult->setIsInHistory(false);
406   theFeature->setResult(aResult, theIndex);
407 }
408
409 FeaturePtr SketchPlugin_Sketch::addUniqueNamedCopiedFeature(FeaturePtr theFeature,
410                                                             SketchPlugin_Sketch* theSketch,
411                                                             const bool theIsCopy)
412 {
413   FeaturePtr aNewFeature = theSketch->addFeature(theFeature->getKind());
414   // addFeature generates a unique name for the feature, it caches the name
415   std::string aUniqueFeatureName = aNewFeature->data()->name();
416   // all attribute values are copied\pasted to the new feature, name is not an exception
417   theFeature->data()->copyTo(aNewFeature->data());
418   // external state should not be copied as a new object is an object of the current sketch
419   if (theFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID()).get())
420     aNewFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->setValue(ResultPtr(),
421                                                                                GeomShapePtr());
422   aNewFeature->data()->setName(aUniqueFeatureName);
423   // text expressions could block setValue of some attributes
424   SketchPlugin_Tools::clearExpressions(aNewFeature);
425   // Set copy attribute
426   AttributeBooleanPtr anAttr = aNewFeature->data()->boolean(SketchPlugin_SketchEntity::COPY_ID());
427   if(anAttr.get()) {
428     anAttr->setValue(theIsCopy);
429   }
430
431   return aNewFeature;
432 }
433
434 std::shared_ptr<GeomAPI_Ax3> SketchPlugin_Sketch::plane(SketchPlugin_Sketch* theSketch)
435 {
436   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
437
438   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
439       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
440   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
441       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
442   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
443       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
444
445   return std::shared_ptr<GeomAPI_Ax3>(new GeomAPI_Ax3(anOrigin->pnt(), aDirX->dir(), aNorm->dir()));
446 }
447
448 bool SketchPlugin_Sketch::customAction(const std::string& theActionId)
449 {
450   bool isOk = false;
451   if (theActionId == ACTION_REMOVE_EXTERNAL())
452     isOk = removeLinksToExternal();
453   else {
454     std::string aMsg = "Error: Feature \"%1\" does not support action \"%2\".";
455     Events_InfoMessage("SketchPlugin_Sketch", aMsg).arg(getKind()).arg(theActionId).send();
456   }
457   return isOk;
458 }
459
460 static bool isExternalBased(const FeaturePtr theFeature)
461 {
462   return theFeature->getKind() == SketchPlugin_Projection::ID() ||
463          theFeature->getKind() == SketchPlugin_IntersectionPoint::ID();
464 }
465
466 bool SketchPlugin_Sketch::removeLinksToExternal()
467 {
468   std::list<FeaturePtr> aRemove;
469   std::list<ObjectPtr> aSubs = reflist(FEATURES_ID())->list();
470   for (std::list<ObjectPtr>::iterator anIt = aSubs.begin(); anIt != aSubs.end(); ++anIt) {
471     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
472     if (!aFeature)
473       continue;
474     if (isExternalBased(aFeature)) {
475       // mark feature as to be removed
476       aRemove.push_back(aFeature);
477     }
478     else {
479       AttributeSelectionPtr anExtAttr =
480           aFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID());
481       ResultPtr anExternal = anExtAttr ? anExtAttr->context() : ResultPtr();
482       if (anExternal) {
483         FeaturePtr anExtFeature = ModelAPI_Feature::feature(anExternal);
484         if (anExtFeature && isExternalBased(anExtFeature)) {
485           // make result of projection/intersection as non-external,
486           aFeature->selection(SketchPlugin_SketchEntity::EXTERNAL_ID())->setValue(
487             ObjectPtr(), GeomShapePtr());
488           // set feature auxiliary if the parent is not included into sketch result
489           bool isIncludedToSketchResult = false;
490           if (anExtFeature->getKind() == SketchPlugin_Projection::ID()) {
491             isIncludedToSketchResult = anExtFeature->boolean(
492                 SketchPlugin_Projection::INCLUDE_INTO_RESULT())->value();
493           }
494           if (anExtFeature->getKind() == SketchPlugin_IntersectionPoint::ID()) {
495             isIncludedToSketchResult = anExtFeature->boolean(
496                 SketchPlugin_IntersectionPoint::INCLUDE_INTO_RESULT())->value();
497           }
498
499           aFeature->boolean(SketchPlugin_SketchEntity::COPY_ID())->setValue(false);
500           aFeature->boolean(SketchPlugin_SketchEntity::AUXILIARY_ID())->setValue(
501               !isIncludedToSketchResult);
502         }
503       }
504     }
505   }
506   for (std::list<FeaturePtr>::iterator anIt = aRemove.begin(); anIt != aRemove.end(); ++anIt)
507     document()->removeFeature(*anIt);
508   return true;
509 }
510
511
512 static ObjectPtr findAxis(GeomShapePtr theAxisToCompare,
513                           ObjectPtr theOX,
514                           ObjectPtr theOY,
515                           ObjectPtr theOZ)
516 {
517   if (theAxisToCompare) {
518     ObjectPtr anAxes[] = { theOX, theOY, theOZ };
519     for (int i = 0; i < 3; ++i) {
520       ResultPtr anAx = std::dynamic_pointer_cast<ModelAPI_Result>(anAxes[i]);
521       if (anAx && theAxisToCompare->isEqual(anAx->shape()))
522         return anAxes[i];
523     }
524   }
525   return ObjectPtr();
526 }
527
528 static ObjectPtr findAxis(ObjectPtr theAxisToCompare,
529                           ObjectPtr theOX,
530                           ObjectPtr theOY,
531                           ObjectPtr theOZ)
532 {
533   if (theAxisToCompare == theOX)
534     return theOX;
535   else if (theAxisToCompare == theOY)
536     return theOY;
537   else if (theAxisToCompare == theOZ)
538     return theOZ;
539   // nothing helped, search by shape
540   ResultPtr anAxis = std::dynamic_pointer_cast<ModelAPI_Result>(theAxisToCompare);
541   return findAxis(anAxis ? anAxis->shape() : GeomShapePtr(), theOX, theOY, theOZ);
542 }
543
544 GeomShapePtr axisOnNewPlane(ObjectPtr theAxis, GeomAx3Ptr theOldPlane, GeomAx3Ptr theNewPlane)
545 {
546   ResultPtr anAxis = std::dynamic_pointer_cast<ModelAPI_Result>(theAxis);
547   if (!anAxis)
548     return GeomShapePtr();
549
550   GeomEdgePtr anAxisEdge = anAxis->shape()->edge();
551   GeomLinePtr anAxisLine = anAxisEdge->line();
552   GeomDirPtr anAxisDir = anAxisLine->direction();
553
554   double aFirstParam, aLastParam;
555   anAxisEdge->getRange(aFirstParam, aLastParam);
556
557   if (theOldPlane->dirX()->isParallel(anAxisDir))
558     anAxisDir = theNewPlane->dirX();
559   else if (theOldPlane->dirY()->isParallel(anAxisDir))
560     anAxisDir = theNewPlane->dirY();
561   else if (theOldPlane->normal()->isParallel(anAxisDir))
562     anAxisDir = theNewPlane->normal();
563
564   GeomPointPtr aFirstPoint(new GeomAPI_Pnt(aFirstParam * anAxisDir->x(),
565                                            aFirstParam * anAxisDir->y(),
566                                            aFirstParam * anAxisDir->z()));
567   GeomPointPtr aLastPoint(new GeomAPI_Pnt(aLastParam * anAxisDir->x(),
568                                           aLastParam * anAxisDir->y(),
569                                           aLastParam * anAxisDir->z()));
570   return GeomAlgoAPI_EdgeBuilder::line(aFirstPoint, aLastPoint);
571 }
572
573 void  SketchPlugin_Sketch::updateCoordinateAxis(ObjectPtr theSub, GeomAx3Ptr thePlane)
574 {
575   FeaturePtr aFeature = ModelAPI_Feature::feature(theSub);
576   if (!aFeature)
577     return;
578
579   DocumentPtr aRootDoc = ModelAPI_Session::get()->moduleDocument();
580   ObjectPtr anOX = aRootDoc->objectByName(ModelAPI_ResultConstruction::group(), "OX");
581   ObjectPtr anOY = aRootDoc->objectByName(ModelAPI_ResultConstruction::group(), "OY");
582   ObjectPtr anOZ = aRootDoc->objectByName(ModelAPI_ResultConstruction::group(), "OZ");
583
584   AttributeSelectionPtr anExtFeature;
585   if (aFeature->getKind() == SketchPlugin_Projection::ID())
586     anExtFeature = aFeature->selection(SketchPlugin_Projection::EXTERNAL_FEATURE_ID());
587   else if (aFeature->getKind() == SketchPlugin_IntersectionPoint::ID())
588     anExtFeature = aFeature->selection(SketchPlugin_IntersectionPoint::EXTERNAL_FEATURE_ID());
589   else
590     return;
591
592   ObjectPtr aContext = anExtFeature->context();
593   GeomShapePtr aShape = anExtFeature->value();
594   if (!aShape) { // selected object is a construction
595     ObjectPtr anAxis = findAxis(aContext, anOX, anOY, anOZ);
596     GeomShapePtr aNewAxis = axisOnNewPlane(anAxis, myPlane, thePlane);
597     anAxis = findAxis(aNewAxis, anOX, anOY, anOZ);
598     if (anAxis)
599       anExtFeature->setValue(anAxis, aShape);
600   }
601 }