]> SALOME platform Git repositories - modules/shaper.git/blob - src/PartSet/PartSet_Tools.cpp
Salome HOME
Remove unused lines of code.
[modules/shaper.git] / src / PartSet / PartSet_Tools.cpp
1 // Copyright (C) 2014-2019  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include <PartSet_Tools.h>
21 #include <PartSet_Module.h>
22 #include <PartSet_SketcherMgr.h>
23
24 #include <ModelAPI_Data.h>
25 #include <ModelAPI_AttributeDouble.h>
26 #include <ModelAPI_AttributeRefList.h>
27 #include <ModelAPI_Document.h>
28 #include <ModelAPI_Session.h>
29 #include <ModelAPI_ResultConstruction.h>
30 #include <ModelAPI_Events.h>
31 #include <ModelAPI_Validator.h>
32 #include <ModelAPI_Tools.h>
33
34 #include <ModuleBase_IViewWindow.h>
35
36 #include <ModelGeomAlgo_Point2D.h>
37
38 #include <Events_Loop.h>
39 #include <Events_InfoMessage.h>
40
41 #include <SketcherPrs_Tools.h>
42
43 #include <XGUI_ModuleConnector.h>
44 #include <XGUI_Displayer.h>
45 #include <XGUI_Workshop.h>
46 #include <XGUI_SelectionMgr.h>
47 #include <XGUI_Selection.h>
48
49 #include <GeomDataAPI_Point.h>
50 #include <GeomDataAPI_Dir.h>
51 #include <GeomDataAPI_Point2D.h>
52 #include <GeomDataAPI_Point2DArray.h>
53 #include <GeomAPI_Pln.h>
54 #include <GeomAPI_Pnt2d.h>
55 #include <GeomAPI_Pnt.h>
56 #include <GeomAPI_Edge.h>
57 #include <GeomAPI_Vertex.h>
58 #include <GeomAPI_ShapeExplorer.h>
59
60 #include <GeomAPI_Dir.h>
61 #include <GeomAPI_XYZ.h>
62
63 #include <SketchPlugin_Feature.h>
64 #include <SketchPlugin_Sketch.h>
65 #include <SketchPlugin_ConstraintCoincidence.h>
66 #include <SketchPlugin_ConstraintDistance.h>
67 #include <SketchPlugin_ConstraintLength.h>
68 #include <SketchPlugin_ConstraintRadius.h>
69 #include <SketchPlugin_ConstraintRigid.h>
70 #include <SketchPlugin_Constraint.h>
71 #include <SketchPlugin_Circle.h>
72 #include <SketchPlugin_Arc.h>
73 #include <SketchPlugin_Line.h>
74 #include <SketchPlugin_Point.h>
75 #include <SketchPlugin_Projection.h>
76 #include <SketchPlugin_IntersectionPoint.h>
77
78 #include <ModuleBase_IWorkshop.h>
79 #include <ModuleBase_ViewerPrs.h>
80 #include <ModuleBase_Tools.h>
81
82 #include <V3d_View.hxx>
83 #include <gp_Pln.hxx>
84 #include <gp_Circ.hxx>
85 #include <ProjLib.hxx>
86 #include <ElSLib.hxx>
87 #include <Geom_Line.hxx>
88 #include <GeomAPI_ProjectPointOnCurve.hxx>
89 #include <BRep_Tool.hxx>
90 #include <TopoDS.hxx>
91 #include <TopoDS_Edge.hxx>
92 #include <TopoDS_Vertex.hxx>
93 #include <AIS_InteractiveObject.hxx>
94 #include <StdSelect_BRepOwner.hxx>
95 #include <SelectMgr_IndexedMapOfOwner.hxx>
96 #include <V3d_Coordinate.hxx>
97
98 #include <QMouseEvent>
99
100 #ifdef _DEBUG
101 #include <QDebug>
102 #endif
103
104 const double PRECISION_TOLERANCE = 0.000001;
105 const int AIS_DEFAULT_WIDTH = 2;
106 const bool SKETCH_PROJECTION_INCLUDE_INTO_RESULT = false; // by default, it is not presented
107
108 int PartSet_Tools::getAISDefaultWidth()
109 {
110   return AIS_DEFAULT_WIDTH;
111 }
112
113 gp_Pnt PartSet_Tools::convertClickToPoint(QPoint thePoint, Handle(V3d_View) theView)
114 {
115   if (theView.IsNull())
116     return gp_Pnt();
117
118   V3d_Coordinate XEye, YEye, ZEye, XAt, YAt, ZAt;
119   theView->Eye(XEye, YEye, ZEye);
120
121   theView->At(XAt, YAt, ZAt);
122   gp_Pnt EyePoint(XEye, YEye, ZEye);
123   gp_Pnt AtPoint(XAt, YAt, ZAt);
124
125   if (EyePoint.Distance(AtPoint) < Precision::Confusion())
126     return gp_Pnt();
127
128   gp_Vec EyeVector(EyePoint, AtPoint);
129   gp_Dir EyeDir(EyeVector);
130
131   gp_Pln PlaneOfTheView = gp_Pln(AtPoint, EyeDir);
132   Standard_Real X, Y, Z;
133   theView->Convert(thePoint.x(), thePoint.y(), X, Y, Z);
134   gp_Pnt ConvertedPoint(X, Y, Z);
135
136   gp_Pnt2d ConvertedPointOnPlane = ProjLib::Project(PlaneOfTheView, ConvertedPoint);
137   return ElSLib::Value(ConvertedPointOnPlane.X(), ConvertedPointOnPlane.Y(),
138                                      PlaneOfTheView);
139 }
140
141 void PartSet_Tools::convertTo2D(const gp_Pnt& thePoint, FeaturePtr theSketch,
142 Handle(V3d_View) theView,
143                                 double& theX, double& theY)
144 {
145   if (!theSketch)
146     return;
147
148   AttributeDoublePtr anAttr;
149   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
150
151   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
152       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
153
154   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
155       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
156   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
157       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
158   std::shared_ptr<GeomAPI_XYZ> anY = aNorm->xyz()->cross(aX->xyz());
159
160   gp_Pnt anOriginPnt(anOrigin->x(), anOrigin->y(), anOrigin->z());
161   gp_Vec aVec(anOriginPnt, thePoint);
162
163   if (!theView.IsNull()) {
164     V3d_Coordinate XEye, YEye, ZEye, XAt, YAt, ZAt;
165     theView->Eye(XEye, YEye, ZEye);
166
167     theView->At(XAt, YAt, ZAt);
168     gp_Pnt EyePoint(XEye, YEye, ZEye);
169     gp_Pnt AtPoint(XAt, YAt, ZAt);
170
171     if (EyePoint.Distance(AtPoint) > gp::Resolution()) {
172       gp_Vec anEyeVec(EyePoint, AtPoint);
173       anEyeVec.Normalize();
174
175       std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
176          aData->attribute(SketchPlugin_Sketch::NORM_ID()));
177       gp_Vec aNormalVec(aNormal->x(), aNormal->y(), aNormal->z());
178
179       double aDen = anEyeVec * aNormalVec;
180       double aLVec = aDen != 0 ? aVec * aNormalVec / aDen : DBL_MAX;
181
182       gp_Vec aDeltaVec = anEyeVec * aLVec;
183       aVec = aVec - aDeltaVec;
184     }
185   }
186   theX = aVec.X() * aX->x() + aVec.Y() * aX->y() + aVec.Z() * aX->z();
187   theY = aVec.X() * anY->x() + aVec.Y() * anY->y() + aVec.Z() * anY->z();
188 }
189
190 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::convertTo2D(FeaturePtr theSketch,
191                                                     const std::shared_ptr<GeomAPI_Pnt>& thePnt)
192 {
193   std::shared_ptr<GeomAPI_Pnt2d> aRes;
194   if (theSketch->getKind() != SketchPlugin_Sketch::ID())
195     return aRes;
196   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
197       theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
198   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
199       theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
200   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
201       theSketch->data()->attribute(SketchPlugin_Sketch::DIRX_ID()));
202   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
203   return thePnt->to2D(aC->pnt(), aX->dir(), aY);
204 }
205
206
207 std::shared_ptr<GeomAPI_Pnt> PartSet_Tools::convertTo3D(const double theX, const double theY,
208                                                         FeaturePtr theSketch)
209 {
210   std::shared_ptr<ModelAPI_Data> aData = theSketch->data();
211
212   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
213       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
214   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
215       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
216   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
217       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
218   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
219
220   std::shared_ptr<GeomAPI_Pnt2d> aPnt2d =
221     std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(theX, theY));
222
223   return aPnt2d->to3D(aC->pnt(), aX->dir(), aY);
224 }
225
226 std::shared_ptr<ModelAPI_Document> PartSet_Tools::document()
227 {
228   return ModelAPI_Session::get()->moduleDocument();
229 }
230
231 void PartSet_Tools::setFeatureValue(FeaturePtr theFeature, double theValue,
232                                     const std::string& theAttribute)
233 {
234   if (!theFeature)
235     return;
236   std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
237   AttributeDoublePtr anAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
238       aData->attribute(theAttribute));
239   if (anAttribute)
240     anAttribute->setValue(theValue);
241 }
242
243 double PartSet_Tools::featureValue(FeaturePtr theFeature, const std::string& theAttribute,
244                                    bool& isValid)
245 {
246   isValid = false;
247   double aValue = 0;
248   if (theFeature) {
249     std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
250     AttributeDoublePtr anAttribute = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
251         aData->attribute(theAttribute));
252     if (anAttribute) {
253       aValue = anAttribute->value();
254       isValid = true;
255     }
256   }
257   return aValue;
258 }
259
260 FeaturePtr PartSet_Tools::feature(FeaturePtr theFeature, const std::string& theAttribute,
261                                   const std::string& theKind)
262 {
263   FeaturePtr aFeature;
264   if (!theFeature)
265     return aFeature;
266
267   std::shared_ptr<ModelAPI_Data> aData = theFeature->data();
268   std::shared_ptr<ModelAPI_AttributeRefAttr> anAttr = std::dynamic_pointer_cast<
269       ModelAPI_AttributeRefAttr>(aData->attribute(theAttribute));
270   if (anAttr) {
271     aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(anAttr->object());
272     if (!theKind.empty() && aFeature && aFeature->getKind() != theKind) {
273       aFeature = FeaturePtr();
274     }
275   }
276   return aFeature;
277 }
278
279 void PartSet_Tools::createConstraint(CompositeFeaturePtr theSketch,
280                                      std::shared_ptr<GeomDataAPI_Point2D> thePoint1,
281                                      std::shared_ptr<GeomDataAPI_Point2D> thePoint2)
282 {
283   FeaturePtr aFeature;
284   if (theSketch) {
285     aFeature = theSketch->addFeature(SketchPlugin_ConstraintCoincidence::ID());
286   } else {
287     std::shared_ptr<ModelAPI_Document> aDoc = document();
288     aFeature = aDoc->addFeature(SketchPlugin_ConstraintCoincidence::ID());
289   }
290
291   std::shared_ptr<ModelAPI_Data> aData = aFeature->data();
292
293   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef1 = std::dynamic_pointer_cast<
294       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_A()));
295   aRef1->setAttr(thePoint1);
296
297   std::shared_ptr<ModelAPI_AttributeRefAttr> aRef2 = std::dynamic_pointer_cast<
298       ModelAPI_AttributeRefAttr>(aData->attribute(SketchPlugin_Constraint::ENTITY_B()));
299   aRef2->setAttr(thePoint2);
300
301   // we need to flush created signal in order to coincidence is processed by solver
302   Events_Loop::loop()->flush(Events_Loop::eventByName(EVENT_OBJECT_CREATED));
303 }
304
305 std::shared_ptr<GeomAPI_Pln> PartSet_Tools::sketchPlane(CompositeFeaturePtr theSketch)
306 {
307   std::shared_ptr<GeomAPI_Pln> aPlane;
308
309   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
310       theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
311   std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
312       theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
313
314   if (aNormal.get() && aNormal->isInitialized() &&
315       anOrigin.get() && anOrigin->isInitialized())
316     aPlane = std::shared_ptr<GeomAPI_Pln>(new GeomAPI_Pln(anOrigin->pnt(), aNormal->dir()));
317
318   return aPlane;
319 }
320
321 void PartSet_Tools::nullifySketchPlane(CompositeFeaturePtr theSketch)
322 {
323   std::shared_ptr<GeomDataAPI_Point> anOrigin = std::dynamic_pointer_cast<GeomDataAPI_Point>(
324     theSketch->data()->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
325   std::shared_ptr<GeomDataAPI_Dir> aNormal = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
326     theSketch->data()->attribute(SketchPlugin_Sketch::NORM_ID()));
327
328   aNormal->reset();
329   anOrigin->reset();
330 }
331
332 std::shared_ptr<GeomAPI_Pnt> PartSet_Tools::point3D(std::shared_ptr<GeomAPI_Pnt2d> thePoint2D,
333                                                       CompositeFeaturePtr theSketch)
334 {
335   std::shared_ptr<GeomAPI_Pnt> aPoint;
336   if (!theSketch || !thePoint2D)
337     return aPoint;
338
339   DataPtr aData = theSketch->data();
340   std::shared_ptr<GeomDataAPI_Point> aC = std::dynamic_pointer_cast<GeomDataAPI_Point>(
341       aData->attribute(SketchPlugin_Sketch::ORIGIN_ID()));
342   std::shared_ptr<GeomDataAPI_Dir> aX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
343       aData->attribute(SketchPlugin_Sketch::DIRX_ID()));
344   std::shared_ptr<GeomDataAPI_Dir> aNorm = std::dynamic_pointer_cast<GeomDataAPI_Dir>(
345       aData->attribute(SketchPlugin_Sketch::NORM_ID()));
346   std::shared_ptr<GeomAPI_Dir> aY(new GeomAPI_Dir(aNorm->dir()->cross(aX->dir())));
347
348   return thePoint2D->to3D(aC->pnt(), aX->dir(), aY);
349 }
350
351 ResultPtr PartSet_Tools::findFixedObjectByExternal(const TopoDS_Shape& theShape,
352                                                    const ObjectPtr& theObject,
353                                                    CompositeFeaturePtr theSketch)
354 {
355   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
356   if (!aResult.get())
357     return ResultPtr();
358
359   for (int i = 0, aNbSubs = theSketch->numberOfSubs(); i < aNbSubs; i++) {
360     FeaturePtr aFeature = theSketch->subFeature(i);
361     if (aFeature->getKind() != SketchPlugin_Projection::PROJECTED_FEATURE_ID())
362       continue;
363     if (aFeature->lastResult() == aResult)
364       return aResult;
365   }
366   return ResultPtr();
367 }
368
369 ResultPtr PartSet_Tools::createFixedObjectByExternal(
370                                    const std::shared_ptr<GeomAPI_Shape>& theShape,
371                                    const ObjectPtr& theObject,
372                                    CompositeFeaturePtr theSketch,
373                                    const bool theTemporary,
374                                    FeaturePtr& theCreatedFeature)
375 {
376   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
377   if (!aResult.get())
378     return ResultPtr();
379
380   FeaturePtr aProjectionFeature = theSketch->addFeature(SketchPlugin_Projection::ID());
381   theCreatedFeature = aProjectionFeature;
382   AttributeSelectionPtr anExternalAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(
383                  aProjectionFeature->attribute(SketchPlugin_Projection::EXTERNAL_FEATURE_ID()));
384   anExternalAttr->setValue(aResult, theShape);
385
386   AttributeBooleanPtr anIntoResult = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>
387     (aProjectionFeature->data()->attribute(SketchPlugin_Projection::INCLUDE_INTO_RESULT()));
388   anIntoResult->setValue(SKETCH_PROJECTION_INCLUDE_INTO_RESULT);
389   aProjectionFeature->execute();
390
391   // if projection feature has not been created, exit
392   AttributeRefAttrPtr aRefAttr = aProjectionFeature->data()->refattr(
393     SketchPlugin_Projection::PROJECTED_FEATURE_ID());
394   if (!aRefAttr || !aRefAttr->isInitialized())
395   {
396     // remove external feature if the attribute is not filled
397     std::set<FeaturePtr> aFeatures;
398     aFeatures.insert(aProjectionFeature);
399     ModelAPI_Tools::removeFeaturesAndReferences(aFeatures);
400     return ResultPtr();
401   }
402
403   FeaturePtr aProjection = ModelAPI_Feature::feature(aRefAttr->object());
404   if (aProjection.get() && aProjection->lastResult().get())
405     return aProjection->lastResult();
406
407   return ResultPtr();
408 }
409
410 bool PartSet_Tools::isContainPresentation(const QList<ModuleBase_ViewerPrsPtr>& theSelected,
411                                           const ModuleBase_ViewerPrsPtr& thePrs)
412 {
413   foreach (ModuleBase_ViewerPrsPtr aPrs, theSelected) {
414     if (aPrs->object() == thePrs->object())
415       return true;
416   }
417   return false;
418 }
419
420 GeomShapePtr PartSet_Tools::findShapeBy2DPoint(const AttributePtr& theAttribute,
421                                                        ModuleBase_IWorkshop* theWorkshop)
422 {
423   GeomShapePtr aShape;
424   XGUI_ModuleConnector* aConnector = dynamic_cast<XGUI_ModuleConnector*>(theWorkshop);
425   XGUI_Displayer* aDisplayer = aConnector->workshop()->displayer();
426
427   // 2. find visualized vertices of the attribute and if the attribute of the vertex is
428   // the same, return it
429   FeaturePtr anAttributeFeature = ModelAPI_Feature::feature(theAttribute->owner());
430   // 2.1 get visualized results of the feature
431   const std::list<ResultPtr>& aResList = anAttributeFeature->results();
432   std::list<ResultPtr>::const_iterator anIt = aResList.begin(), aLast = aResList.end();
433   for (; anIt != aLast; anIt++) {
434     AISObjectPtr aAISObj = aDisplayer->getAISObject(*anIt);
435     if (aAISObj.get() != NULL) {
436       Handle(AIS_InteractiveObject) anAISIO = aAISObj->impl<Handle(AIS_InteractiveObject)>();
437       // 2.2 find selected owners of a visualizedd object
438       SelectMgr_IndexedMapOfOwner aSelectedOwners;
439       aConnector->workshop()->selector()->selection()->entityOwners(anAISIO, aSelectedOwners);
440       for (Standard_Integer i = 1, n = aSelectedOwners.Extent(); i <= n; i++) {
441         Handle(SelectMgr_EntityOwner) anOwner = aSelectedOwners(i);
442         if (!anOwner.IsNull()) {
443           Handle(StdSelect_BRepOwner) aBRepOwner = Handle(StdSelect_BRepOwner)::DownCast(anOwner);
444           if (!aBRepOwner.IsNull() && aBRepOwner->HasShape()) {
445             const TopoDS_Shape& aBRepShape = aBRepOwner->Shape();
446             if (aBRepShape.ShapeType() == TopAbs_VERTEX) {
447               // 2.3 if the owner is vertex and an attribute of the vertex is equal to the initial
448               // attribute, returns the shape
449               PartSet_Module* aModule = dynamic_cast<PartSet_Module*>(theWorkshop->module());
450               PartSet_SketcherMgr* aSketchMgr = aModule->sketchMgr();
451               std::pair<AttributePtr, int> aPntAttrIndex = PartSet_Tools::findAttributeBy2dPoint(
452                   anAttributeFeature, aBRepShape, aSketchMgr->activeSketch());
453               if (aPntAttrIndex.first.get() != NULL && aPntAttrIndex.first == theAttribute) {
454                 aShape = std::shared_ptr<GeomAPI_Shape>(new GeomAPI_Shape);
455                 aShape->setImpl(new TopoDS_Shape(aBRepShape));
456                 break;
457               }
458             }
459           }
460         }
461       }
462     }
463   }
464   return aShape;
465 }
466
467 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPoint(
468                                                   std::shared_ptr<ModelAPI_Feature>& theFeature,
469                                                   const std::string& theAttribute)
470 {
471   std::shared_ptr<GeomDataAPI_Point2D> aPointAttr = ModelGeomAlgo_Point2D::getPointOfRefAttr(
472                                           theFeature.get(), theAttribute, SketchPlugin_Point::ID(),
473                                           SketchPlugin_Point::COORD_ID());
474   if (aPointAttr.get() != NULL)
475     return aPointAttr->pnt();
476   return std::shared_ptr<GeomAPI_Pnt2d>();
477 }
478
479 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPnt2d(QMouseEvent* theEvent,
480                                                 ModuleBase_IViewWindow* theWindow,
481                                                 const FeaturePtr& theSketch)
482 {
483   gp_Pnt aPnt = PartSet_Tools::convertClickToPoint(theEvent->pos(), theWindow->v3dView());
484   double aX, anY;
485   Handle(V3d_View) aView = theWindow->v3dView();
486   PartSet_Tools::convertTo2D(aPnt, theSketch, aView, aX, anY);
487
488   return std::shared_ptr<GeomAPI_Pnt2d>(new GeomAPI_Pnt2d(aX, anY));
489 }
490
491 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getPnt2d(const Handle(V3d_View)& theView,
492                                                        const TopoDS_Shape& theShape,
493                                                        const FeaturePtr& theSketch)
494 {
495   GeomPnt2dPtr aPoint2D;
496   if (!theShape.IsNull() && theShape.ShapeType() == TopAbs_VERTEX) {
497     const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
498     if (!aVertex.IsNull()) {
499       // the case when the point is taken from the existing vertex
500       gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
501       double aX, aY;
502       PartSet_Tools::convertTo2D(aPoint, theSketch, theView, aX, aY);
503       aPoint2D.reset(new GeomAPI_Pnt2d(aX, aY));
504     }
505   }
506   return aPoint2D;
507 }
508
509 FeaturePtr findFirstCoincidenceByData(const DataPtr& theData,
510                                       std::shared_ptr<GeomAPI_Pnt2d> thePoint)
511 {
512   FeaturePtr aCoincident;
513
514   const std::set<AttributePtr>& aRefsList = theData->refsToMe();
515   std::set<AttributePtr>::const_iterator aIt;
516   for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
517     std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
518     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
519     if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
520       std::shared_ptr<GeomAPI_Pnt2d> a2dPnt =
521         PartSet_Tools::getPoint(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_A());
522       if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
523         aCoincident = aConstrFeature;
524         break;
525       } else {
526         a2dPnt = PartSet_Tools::getPoint(aConstrFeature,
527                                           SketchPlugin_ConstraintCoincidence::ENTITY_B());
528         if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
529           aCoincident = aConstrFeature;
530           break;
531         }
532       }
533     }
534   }
535   return aCoincident;
536 }
537
538 FeaturePtr PartSet_Tools::findFirstCoincidence(const FeaturePtr& theFeature,
539                                                std::shared_ptr<GeomAPI_Pnt2d> thePoint)
540 {
541   FeaturePtr aCoincident;
542   if (theFeature.get() == NULL)
543     return aCoincident;
544
545   const std::set<AttributePtr>& aRefsList = theFeature->data()->refsToMe();
546   std::set<AttributePtr>::const_iterator aIt;
547   for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
548     std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
549     FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
550     if (aConstrFeature && aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
551       std::shared_ptr<GeomAPI_Pnt2d> a2dPnt =
552         PartSet_Tools::getPoint(aConstrFeature, SketchPlugin_ConstraintCoincidence::ENTITY_A());
553       if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
554         aCoincident = aConstrFeature;
555         break;
556       } else {
557         a2dPnt = PartSet_Tools::getPoint(aConstrFeature,
558                                           SketchPlugin_ConstraintCoincidence::ENTITY_B());
559         if (a2dPnt.get() && thePoint->isEqual(a2dPnt)) {
560           aCoincident = aConstrFeature;
561           break;
562         }
563       }
564     }
565   }
566   /// Find by result
567   if (!aCoincident.get()) {
568     std::list<ResultPtr> aResults = theFeature->results();
569     std::list<ResultPtr>::const_iterator aIt;
570     for (aIt = aResults.cbegin(); aIt != aResults.cend(); ++aIt) {
571       ResultPtr aResult = *aIt;
572       aCoincident = findFirstCoincidenceByData(aResult->data(), thePoint);
573       if (aCoincident.get())
574         break;
575     }
576   }
577   return aCoincident;
578 }
579
580 void PartSet_Tools::findCoincidences(FeaturePtr theStartCoin, QList<FeaturePtr>& theList,
581                                      QList<FeaturePtr>& theCoincidencies,
582                                      std::string theAttr, QList<bool>& theIsAttributes)
583 {
584   std::shared_ptr<GeomAPI_Pnt2d> aOrig = getCoincedencePoint(theStartCoin);
585   if (aOrig.get() == NULL)
586     return;
587
588   AttributeRefAttrPtr aPnt = theStartCoin->refattr(theAttr);
589   if (!aPnt)
590     return;
591   ObjectPtr aObj = aPnt->object();
592   FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aObj);
593   if (aFeature.get()) {
594     if (!theList.contains(aFeature)) {
595       theList.append(aFeature);
596       theCoincidencies.append(theStartCoin);
597       theIsAttributes.append(true); // point attribute on a feature
598       const std::set<AttributePtr>& aRefsList = aFeature->data()->refsToMe();
599       std::set<AttributePtr>::const_iterator aIt;
600       for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
601         std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
602         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
603         if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
604           if (!theCoincidencies.contains(aConstrFeature)) {
605             std::shared_ptr<GeomAPI_Pnt2d> aPnt = getCoincedencePoint(aConstrFeature);
606             if (aPnt.get() && aOrig->isEqual(aPnt)) {
607               findCoincidences(aConstrFeature, theList, theCoincidencies,
608                 SketchPlugin_ConstraintCoincidence::ENTITY_A(), theIsAttributes);
609               findCoincidences(aConstrFeature, theList, theCoincidencies,
610                 SketchPlugin_ConstraintCoincidence::ENTITY_B(), theIsAttributes);
611             }
612           }
613         }
614       }
615     }
616   } else {
617     // Find by Results
618     ResultConstructionPtr aResult = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(aObj);
619     if (aResult.get()) {
620       FeaturePtr aFeature = ModelAPI_Feature::feature(aPnt->object());
621       if (!theList.contains(aFeature))
622         theList.append(aFeature);
623       theCoincidencies.append(theStartCoin);
624       theIsAttributes.append(false); // point attribute on a feature
625
626       const std::set<AttributePtr>& aRefsList = aResult->data()->refsToMe();
627       std::set<AttributePtr>::const_iterator aIt;
628       for (aIt = aRefsList.cbegin(); aIt != aRefsList.cend(); ++aIt) {
629         std::shared_ptr<ModelAPI_Attribute> aAttr = (*aIt);
630         FeaturePtr aConstrFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(aAttr->owner());
631         if (aConstrFeature->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
632           if (!theCoincidencies.contains(aConstrFeature)) {
633             std::shared_ptr<GeomAPI_Pnt2d> aPnt = getCoincedencePoint(aConstrFeature);
634             if (aPnt.get() && aOrig->isEqual(aPnt)) {
635               findCoincidences(aConstrFeature, theList, theCoincidencies,
636                 SketchPlugin_ConstraintCoincidence::ENTITY_A(), theIsAttributes);
637               findCoincidences(aConstrFeature, theList, theCoincidencies,
638                 SketchPlugin_ConstraintCoincidence::ENTITY_B(), theIsAttributes);
639             }
640           }
641         }
642       }
643     }
644   }
645 }
646
647 std::shared_ptr<GeomAPI_Pnt2d> PartSet_Tools::getCoincedencePoint(FeaturePtr theStartCoin)
648 {
649   std::shared_ptr<GeomAPI_Pnt2d> aPnt = SketcherPrs_Tools::getPoint(theStartCoin.get(),
650                                                         SketchPlugin_Constraint::ENTITY_A());
651   if (aPnt.get() == NULL)
652     aPnt = SketcherPrs_Tools::getPoint(theStartCoin.get(), SketchPlugin_Constraint::ENTITY_B());
653   return aPnt;
654 }
655
656 class PointWrapper
657 {
658 public:
659   PointWrapper(AttributePtr theAttribute)
660     : myPoint(std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute)),
661       myArray(std::dynamic_pointer_cast<GeomDataAPI_Point2DArray>(theAttribute))
662   {}
663
664   int size() const { return myPoint.get() ? 1 : (myArray.get() ? myArray->size() : 0); }
665
666   GeomPointPtr point(int theIndex, FeaturePtr theSketch)
667   {
668     GeomPnt2dPtr aP2d;
669     if (myPoint.get())
670       aP2d = myPoint->pnt();
671     else if (myArray.get())
672       aP2d = myArray->pnt(theIndex);
673
674     GeomPointPtr aP3d;
675     if (aP2d.get())
676       aP3d = PartSet_Tools::convertTo3D(aP2d->x(), aP2d->y(), theSketch);
677     return aP3d;
678   }
679
680   bool isArray() const { return myArray.get(); }
681
682 private:
683   AttributePoint2DPtr myPoint;
684   AttributePoint2DArrayPtr myArray;
685 };
686
687 std::pair<AttributePtr, int> PartSet_Tools::findAttributeBy2dPoint(ObjectPtr theObj,
688                                                                    const TopoDS_Shape theShape,
689                                                                    FeaturePtr theSketch)
690 {
691
692   AttributePtr anAttribute;
693   int aPointIndex = -1;
694   FeaturePtr aFeature = ModelAPI_Feature::feature(theObj);
695   if (aFeature) {
696     if (theShape.ShapeType() == TopAbs_VERTEX) {
697       const TopoDS_Vertex& aVertex = TopoDS::Vertex(theShape);
698       if (!aVertex.IsNull())  {
699         gp_Pnt aPoint = BRep_Tool::Pnt(aVertex);
700         std::shared_ptr<GeomAPI_Pnt> aValue = std::shared_ptr<GeomAPI_Pnt>(
701             new GeomAPI_Pnt(aPoint.X(), aPoint.Y(), aPoint.Z()));
702
703         // find the given point in the feature attributes
704         std::list<AttributePtr> anAttiributes =
705           aFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
706         std::list<AttributePtr> anArrays =
707           aFeature->data()->attributes(GeomDataAPI_Point2DArray::typeId());
708         anAttiributes.insert(anAttiributes.end(), anArrays.begin(), anArrays.end());
709
710         std::list<AttributePtr>::const_iterator anIt = anAttiributes.begin(),
711                                                 aLast = anAttiributes.end();
712         double aMinDistance = 1.e-6; // searching for point with minimal distance and < 1.e-6
713         for (; anIt != aLast && !anAttribute; anIt++) {
714           PointWrapper aWrapper(*anIt);
715           for (int anIndex = 0, aSize = aWrapper.size(); anIndex < aSize; ++anIndex) {
716             std::shared_ptr<GeomAPI_Pnt> aPnt = aWrapper.point(anIndex, theSketch);
717             if (aPnt) {
718               double aDistance = aPnt->distance(aValue);
719               if (aDistance < aMinDistance) {
720                 anAttribute = *anIt;
721                 if (aWrapper.isArray())
722                   aPointIndex = anIndex;
723                 aMinDistance = aPnt->distance(aValue);
724               }
725             }
726           }
727         }
728       }
729     }
730   }
731   return std::pair<AttributePtr, int>(anAttribute, aPointIndex);
732 }
733
734 void PartSet_Tools::sendSubFeaturesEvent(const CompositeFeaturePtr& theComposite,
735                                          const Events_ID theEventId)
736 {
737   if (!theComposite.get())
738     return;
739
740   static Events_Loop* aLoop = Events_Loop::loop();
741   int aNumberOfSubs = theComposite->numberOfSubs();
742   for (int i = 0; i < aNumberOfSubs; i++) {
743     FeaturePtr aSubFeature = theComposite->subFeature(i);
744     static const ModelAPI_EventCreator* aECreator = ModelAPI_EventCreator::get();
745     aECreator->sendUpdated(aSubFeature, theEventId);
746   }
747   Events_Loop::loop()->flush(theEventId);
748 }
749
750 bool PartSet_Tools::isAuxiliarySketchEntity(const ObjectPtr& theObject)
751 {
752   bool isAuxiliaryFeature = false;
753
754   FeaturePtr anObjectFeature = ModelAPI_Feature::feature(theObject);
755   std::string anAuxiliaryAttribute = SketchPlugin_SketchEntity::AUXILIARY_ID();
756   AttributeBooleanPtr anAuxiliaryAttr = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>(
757                                     anObjectFeature->data()->attribute(anAuxiliaryAttribute));
758   if (anAuxiliaryAttr.get())
759     isAuxiliaryFeature = anAuxiliaryAttr->value();
760
761
762   return isAuxiliaryFeature;
763 }
764
765 bool PartSet_Tools::isIncludeIntoSketchResult(const ObjectPtr& theObject)
766 {
767   // check the feature is neither Projection nor IntersectionPoint feature
768   FeaturePtr aFeature = ModelAPI_Feature::feature(theObject);
769   if (aFeature->getKind() == SketchPlugin_Projection::ID() ||
770       aFeature->getKind() == SketchPlugin_IntersectionPoint::ID())
771     return false;
772
773   // go through the references to the feature to check
774   // if it was created by Projection or Intersection
775   const std::set<AttributePtr>& aRefs = theObject->data()->refsToMe();
776   for (std::set<AttributePtr>::const_iterator aRefIt = aRefs.begin();
777        aRefIt != aRefs.end(); ++aRefIt) {
778     AttributePtr anAttr = *aRefIt;
779     std::string anIncludeToResultAttrName;
780     if (anAttr->id() == SketchPlugin_Projection::PROJECTED_FEATURE_ID())
781       anIncludeToResultAttrName = SketchPlugin_Projection::INCLUDE_INTO_RESULT();
782     else if (anAttr->id() == SketchPlugin_IntersectionPoint::INTERSECTION_POINTS_ID())
783       anIncludeToResultAttrName = SketchPlugin_IntersectionPoint::INCLUDE_INTO_RESULT();
784
785     if (!anIncludeToResultAttrName.empty()) {
786       // check "include into result" flag
787       FeaturePtr aParent = ModelAPI_Feature::feature(anAttr->owner());
788       return aParent->boolean(anIncludeToResultAttrName)->value();
789     }
790   }
791   return true;
792 }
793
794
795 ResultPtr PartSet_Tools::createFixedByExternalCenter(
796     const ObjectPtr& theObject,
797     const std::shared_ptr<GeomAPI_Edge>& theEdge,
798     ModelAPI_AttributeSelection::CenterType theType,
799     const CompositeFeaturePtr& theSketch,
800     bool theTemporary,
801     FeaturePtr& theCreatedFeature)
802 {
803   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
804   if (!aResult.get())
805     return ResultPtr();
806
807   FeaturePtr aProjectionFeature = theSketch->addFeature(SketchPlugin_Projection::ID());
808   theCreatedFeature = aProjectionFeature;
809   AttributeSelectionPtr anExternalAttr = std::dynamic_pointer_cast<ModelAPI_AttributeSelection>(
810                  aProjectionFeature->attribute(SketchPlugin_Projection::EXTERNAL_FEATURE_ID()));
811   anExternalAttr->setValueCenter(aResult, theEdge, theType, theTemporary);
812
813   AttributeBooleanPtr anIntoResult = std::dynamic_pointer_cast<ModelAPI_AttributeBoolean>
814     (aProjectionFeature->data()->attribute(SketchPlugin_Projection::INCLUDE_INTO_RESULT()));
815   anIntoResult->setValue(SKETCH_PROJECTION_INCLUDE_INTO_RESULT);
816   aProjectionFeature->execute();
817
818   // if projection feature has not been created, exit
819   AttributeRefAttrPtr aRefAttr = aProjectionFeature->data()->refattr(
820     SketchPlugin_Projection::PROJECTED_FEATURE_ID());
821   if (!aRefAttr || !aRefAttr->isInitialized())
822     return ResultPtr();
823
824   FeaturePtr aProjection = ModelAPI_Feature::feature(aRefAttr->object());
825   if (aProjection.get() && aProjection->lastResult().get())
826     return aProjection->lastResult();
827
828   return ResultPtr();
829 }
830
831 void PartSet_Tools::getFirstAndLastIndexInFolder(const ObjectPtr& theFolder,
832   int& theFirst, int& theLast)
833 {
834   theFirst = -1;
835   theLast = -1;
836
837   DocumentPtr aDoc = theFolder->document();
838   FolderPtr aFolder = std::dynamic_pointer_cast<ModelAPI_Folder>(theFolder);
839   if (!aFolder.get())
840     return;
841
842   AttributeReferencePtr aFirstFeatAttr =
843     aFolder->data()->reference(ModelAPI_Folder::FIRST_FEATURE_ID());
844   if (!aFirstFeatAttr.get())
845     return;
846   FeaturePtr aFirstFeatureInFolder = ModelAPI_Feature::feature(aFirstFeatAttr->value());
847   if (!aFirstFeatureInFolder.get())
848     return;
849
850   FeaturePtr aLastFeatureInFolder = aFolder->lastVisibleFeature();
851   if (!aLastFeatureInFolder.get())
852     return;
853
854   theFirst = aDoc->index(aFirstFeatureInFolder);
855   theLast = aDoc->index(aLastFeatureInFolder);
856 }
857
858
859 void PartSet_Tools::getDefaultColor(ObjectPtr theObject, const bool isEmptyColorValid,
860   std::vector<int>& theColor)
861 {
862   theColor.clear();
863   // get default color from the preferences manager for the given result
864   if (theColor.empty()) {
865     std::string aSection, aName, aDefault;
866     theObject->colorConfigInfo(aSection, aName, aDefault);
867     if (!aSection.empty() && !aName.empty()) {
868       theColor = Config_PropManager::color(aSection, aName);
869     }
870   }
871   if (!isEmptyColorValid && theColor.empty()) {
872     // all AIS objects, where the color is not set, are in black.
873     // The color should be defined in XML or set in the attribute
874     theColor = Config_PropManager::color("Visualization", "object_default_color");
875     Events_InfoMessage("PartSet_Tools",
876       "A default color is not defined in the preferences for this result type").send();
877   }
878 }
879
880 double PartSet_Tools::getDefaultDeflection(const ObjectPtr& theObject)
881 {
882   double aDeflection = -1;
883   ResultPtr aResult = std::dynamic_pointer_cast<ModelAPI_Result>(theObject);
884   if (aResult.get()) {
885     bool isConstruction = false;
886
887     std::string aResultGroup = aResult->groupName();
888     if (aResultGroup == ModelAPI_ResultConstruction::group())
889       isConstruction = true;
890     else if (aResultGroup == ModelAPI_ResultBody::group()) {
891       GeomShapePtr aGeomShape = aResult->shape();
892       if (aGeomShape.get()) {
893         // if the shape could not be exploded on faces, it contains only wires, edges, and vertices
894         // correction of deviation for them should not influence to the application performance
895         GeomAPI_ShapeExplorer anExp(aGeomShape, GeomAPI_Shape::FACE);
896         isConstruction = !anExp.more();
897       }
898     }
899     if (isConstruction)
900       aDeflection = Config_PropManager::real("Visualization", "construction_deflection");
901     else
902       aDeflection = Config_PropManager::real("Visualization", "body_deflection");
903   }
904   return aDeflection;
905 }
906
907
908 double PartSet_Tools::getDefaultTransparency()
909 {
910   return Config_PropManager::integer("Visualization", "shaper_default_transparency") / 100.;
911 }
912
913 QCursor PartSet_Tools::getOperationCursor()
914 {
915   int aId = Config_PropManager::integer(SKETCH_TAB_NAME, "operation_cursor");
916   switch (aId) {
917   case 0:
918     return QCursor(Qt::ArrowCursor);
919   case 1:
920     return QCursor(Qt::CrossCursor);
921   case 2:
922     return QCursor(Qt::PointingHandCursor);
923   }
924   return QCursor();
925 }