]> SALOME platform Git repositories - modules/geom.git/blob - src/CurveCreator/CurveCreator_Utils.cxx
Salome HOME
refs #1331: access to methods for testing purposes
[modules/geom.git] / src / CurveCreator / CurveCreator_Utils.cxx
1 // Copyright (C) 2013-2016  CEA/DEN, EDF R&D, OPEN CASCADE
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 "CurveCreator_Utils.hxx"
21 #include "CurveCreator.hxx"
22 #include "CurveCreator_Curve.hxx"
23 #include "CurveCreator_Section.hxx"
24 #include "CurveCreator_UtilsICurve.hxx"
25
26 #include <Basics_OCCTVersion.hxx>
27
28 #include <GEOMUtils.hxx>
29
30 #include <gp_Pln.hxx>
31
32 #include <TopoDS.hxx>
33 #include <TopoDS_Vertex.hxx>
34 #include <TopoDS_Wire.hxx>
35 #include <TopoDS_Edge.hxx>
36 #include <TopoDS_Compound.hxx>
37
38 #include <AIS_ListOfInteractive.hxx>
39 #include <AIS_ListIteratorOfListOfInteractive.hxx>
40 #include <AIS_Shape.hxx>
41 #include <AIS_Line.hxx>
42 #include <AIS_Trihedron.hxx>
43 #include <AIS_LocalContext.hxx>
44
45 #include <Geom_Point.hxx>
46 #include <Geom_BSplineCurve.hxx>
47 #include <Geom_Line.hxx>
48 #include <Geom_Curve.hxx>
49 #include <Geom_TrimmedCurve.hxx>
50
51 #include <TopExp.hxx>
52 #include <TopExp_Explorer.hxx>
53 #include <TopTools_ListIteratorOfListOfShape.hxx>
54 #include <GeomAPI_ProjectPointOnCurve.hxx>
55 #include <SelectMgr_EntityOwner.hxx>
56 #include <SelectMgr_Selection.hxx>
57 #include <Select3D_SensitivePoint.hxx>
58
59 #include <BRep_Tool.hxx>
60 #include <BRep_Builder.hxx>
61 #include <BRepBuilderAPI_MakeVertex.hxx>
62 #include <BRepBuilderAPI_MakeEdge.hxx>
63 #include <BRepBuilderAPI_MakeWire.hxx>
64 #include <BRepTools_WireExplorer.hxx>
65
66 #include <TColgp_HArray1OfPnt.hxx>
67 #include <TColStd_HArray1OfBoolean.hxx>
68 #include <TColStd_Array1OfReal.hxx>
69 #include <TColgp_Array1OfVec.hxx>
70 #include <GeomAPI_Interpolate.hxx>
71
72 #include <ProjLib.hxx>
73 #include <ElSLib.hxx>
74
75 #include <math.h>
76
77 #include "CurveCreator_ICurve.hxx"
78
79 const double LOCAL_SELECTION_TOLERANCE = 0.0001;
80 const int    SCENE_PIXEL_PROJECTION_TOLERANCE = 10;
81 const int    SCENE_PIXEL_POINT_TOLERANCE = 5;
82
83 #define PLN_FREE   0
84 #define PLN_ORIGIN 1
85 #define PLN_OX     2
86 #define PLN_FIXED  3
87
88 /**
89  * This static function returns the curve of original type from the edge.
90  *
91  * \param theEdge the edge
92  * \return the curve of original type. Can be null handle.
93  */
94 static Handle(Geom_Curve) GetCurve(const TopoDS_Edge &theEdge)
95 {
96   Handle(Geom_Curve) aResult;
97
98   if (theEdge.IsNull()) {
99     return aResult;
100   }
101
102   Standard_Real aF;
103   Standard_Real aL;
104
105   aResult = BRep_Tool::Curve(theEdge, aF, aL);
106
107   if (aResult.IsNull()) {
108     return aResult;
109   }
110
111   // Get the curve of original type
112   Handle(Standard_Type) aType = aResult->DynamicType();
113
114   while (aType == STANDARD_TYPE(Geom_TrimmedCurve)) {
115     Handle(Geom_TrimmedCurve) aTrCurve =
116       Handle(Geom_TrimmedCurve)::DownCast(aResult);
117
118     aResult = aTrCurve->BasisCurve();
119     aType  = aResult->DynamicType();
120   }
121
122   return aResult;
123 }
124
125 //=======================================================================
126 // function : ConvertClickToPoint()
127 // purpose  : Returns the point clicked in 3D view
128 //=======================================================================
129 void CurveCreator_Utils::ConvertPointToClick( const gp_Pnt& thePoint,
130                                               Handle(V3d_View) theView,
131                                               int& x, int& y )
132 {
133   theView->Convert(thePoint.X(), thePoint.Y(), thePoint.Z(), x, y );
134 }
135
136
137 //=======================================================================
138 // function : ConvertClickToPoint()
139 // purpose  : Returns the point clicked in 3D view
140 //=======================================================================
141 gp_Pnt CurveCreator_Utils::ConvertClickToPoint( int x, int y, Handle(V3d_View) aView )
142 {
143   // the 3D point, that is a projection of the pixels to the XYZ view plane
144   //return GEOMUtils::ConvertClickToPoint( x, y, aView );
145
146   // we need the projection to the XOY plane
147   // 1. find a point in the plane of the eye and the normal to the plane
148   Standard_Real X, Y, Z;
149   Quantity_Parameter Vx, Vy, Vz;
150   aView->ConvertWithProj( x, y, X, Y, Z, Vx, Vy, Vz );
151
152   // 2. build a ray from the point by the normal to the XOY plane and intersect it
153   // The ray equation is the following : p(x,y,z) = p0(x,y,z) + t*V(x,y,z)
154   // X,Y,Z - defines p0(x,y,z), Vx,Vy,Vz - defines V(x,y,z)
155   // p(x,y,z) - is a searched point, t - should to be calculated by the condition of XOY plane
156   // The system of equations is the following:
157   // p(x) = p0(x)+t*V(x)
158   // p(y) = p0(y)+t*V(y)
159   // p(z) = p0(z)+t*V(z)
160   // p(z) = 0
161
162   Standard_Real aXp, aYp, aZp;
163   //It is not possible to use Precision::Confusion(), because it is e-0.8, but V is sometimes e-6
164   Standard_Real aPrec = LOCAL_SELECTION_TOLERANCE;
165   if ( fabs( Vz ) > aPrec ) {
166     Standard_Real aT = -Z/Vz;
167     aXp = X + aT*Vx;
168     aYp = Y + aT*Vy;
169     aZp = Z + aT*Vz;
170   }
171   else { // Vz = 0 - the eyed plane is orthogonal to Z plane - XOZ, or YOZ
172     aXp = aYp = aZp = 0;
173     if ( fabs( Vy ) < aPrec ) // Vy = 0 - the YOZ plane
174       aYp = Y;
175     else if ( fabs( Vx ) < aPrec ) // Vx = 0 - the XOZ plane
176       aXp = X;
177   }
178   /*std::cout << "ConvertClickToPoint: " << std::endl
179             << "XYZ1 = (" << X << ", " << Y << ", " << Z << "); " << std::endl
180             << "Vxyz = (" << Vx << ", " << Vy << ", " << Vz << "); " << std::endl
181             << "Resp = (" << aXp << ", " << aYp << ", " << aZp << "); " << std::endl;*/
182
183   gp_Pnt ResultPoint( aXp, aYp, aZp );
184   return ResultPoint;
185 }
186
187 //=======================================================================
188 // function : constructBSpline
189 // purpose  :
190 //=======================================================================
191 bool CurveCreator_Utils::constructBSpline(
192   const Handle(TColgp_HArray1OfPnt)& thePoints,
193   const Standard_Boolean theIsClosed,
194   Handle(Geom_BSplineCurve)& theBSpline)
195 {
196   const int aPointCount = thePoints->Length();
197   if (aPointCount <= 1)
198   {
199     return false;
200   }
201
202   // Calculate the tangents.
203   TColgp_Array1OfVec aTangents(1, aPointCount);
204   Handle(TColStd_HArray1OfBoolean) aTangentFlags =
205     new TColStd_HArray1OfBoolean(1, aPointCount);
206   GeomAPI_Interpolate aInterpolator(thePoints, theIsClosed, 0);
207   if (aPointCount == 2)
208   {
209     aTangentFlags->SetValue(1, Standard_False);
210     aTangentFlags->SetValue(2, Standard_False);
211   }
212   else
213   {
214     for (Standard_Integer aPN = 1; aPN <= aPointCount; ++aPN)
215     {
216       gp_Vec aTangent;
217       if (aPN != 1 || theIsClosed)
218       {
219         const Standard_Integer aPN1 = (aPN != 1) ? (aPN - 1) : aPointCount;
220         aTangent = gp_Vec(thePoints->Value(aPN1),
221           thePoints->Value(aPN)).Normalized();
222       }
223       if (aPN < aPointCount || theIsClosed)
224       {
225         const Standard_Integer aPN2 = (aPN != aPointCount) ? (aPN + 1) : 1;
226         const gp_Vec aTangent2 = aTangent +
227           gp_Vec(thePoints->Value(aPN), thePoints->Value(aPN2)).Normalized();
228         if (aTangent2.SquareMagnitude() >= Precision::SquareConfusion())
229         {
230           aTangent = aTangent2.Normalized();
231         }
232         else
233         {
234           aTangent = -aTangent;
235         }
236       }
237       aTangents.SetValue(aPN, aTangent);
238       aTangentFlags->SetValue(aPN, Standard_True);
239     }
240   }
241
242   // Interpolate.
243   aInterpolator.Load(aTangents, aTangentFlags, Standard_False);
244   aInterpolator.Perform();
245   const bool aResult = (aInterpolator.IsDone() == Standard_True);
246   if (aResult)
247   {
248     theBSpline = aInterpolator.Curve();
249   }
250   return aResult;
251 }
252
253 //=======================================================================
254 // function : constructWire
255 // purpose  :
256 //=======================================================================
257 TopoDS_Wire CurveCreator_Utils::ConstructWire(
258   Handle(TColgp_HArray1OfPnt) thePoints,
259   const bool theIsPolyline,
260   const bool theIsClosed)
261 {
262   TopoDS_Wire aWire;
263   BRep_Builder aBuilder;
264   aBuilder.MakeWire(aWire);
265   const int aPointCount = thePoints->Length();
266   if (theIsPolyline)
267   {
268     const TopoDS_Vertex aFirstVertex =
269       BRepBuilderAPI_MakeVertex(thePoints->Value(1));
270     TopoDS_Vertex aVertex = aFirstVertex;
271     for (Standard_Integer aPN = 1; aPN < aPointCount; ++aPN)
272     {
273       const TopoDS_Vertex aVertex2 =
274         BRepBuilderAPI_MakeVertex(thePoints->Value(aPN + 1));
275       aBuilder.Add(aWire, BRepBuilderAPI_MakeEdge(aVertex, aVertex2));
276       aVertex = aVertex2;
277     }
278     if (theIsClosed && aPointCount > 1)
279     {
280       aBuilder.Add(aWire, BRepBuilderAPI_MakeEdge(aVertex, aFirstVertex));
281     }
282   }
283   else
284   {
285     Handle(Geom_BSplineCurve) aBSpline;
286     if (constructBSpline(thePoints, theIsClosed, aBSpline))
287     {
288       aBuilder.Add(aWire, BRepBuilderAPI_MakeEdge(aBSpline));
289     }
290   }
291   return aWire;
292 }
293
294 //=======================================================================
295 // function : constructShape
296 // purpose  :
297 //=======================================================================
298 void CurveCreator_Utils::constructShape(
299   const CurveCreator_ICurve* theCurve, TopoDS_Shape& theShape)
300 {
301   BRep_Builder aBuilder;
302   TopoDS_Compound aShape;
303   aBuilder.MakeCompound(aShape);
304   const int aSectionCount = theCurve->getNbSections();
305   for (int aSectionI = 0; aSectionI < aSectionCount; ++aSectionI)
306   {
307     const int aTmpPointCount = theCurve->getNbPoints(aSectionI);
308     if (aTmpPointCount == 0)
309     {
310       continue;
311     }
312
313     // Get the different points.
314     Handle(TColgp_HArray1OfPnt) aPoints = theCurve->GetDifferentPoints( aSectionI );
315     const int aPointCount = aPoints->Length();
316     const bool isClosed = theCurve->isClosed(aSectionI);
317
318     // Add the vertices to the shape.
319     for (Standard_Integer aPN = 1; aPN <= aPointCount; ++aPN)
320     {
321       aBuilder.Add(aShape, BRepBuilderAPI_MakeVertex(aPoints->Value(aPN)));
322     }
323
324     // Add the wire to the shape.
325     const bool isPolyline =
326       (theCurve->getSectionType(aSectionI) == CurveCreator::Polyline);
327     const TopoDS_Wire aWire = ConstructWire(aPoints, isPolyline, isClosed);
328     if (!aWire.IsNull())
329     {
330       aBuilder.Add(aShape, aWire);
331     }
332   }
333   theShape = aShape;
334 }
335
336 /**
337  * This is an intermediate structure for curve construction.
338  */
339 struct Section3D
340 {
341   Section3D() : myIsClosed(false), myIsBSpline(false)
342   { }
343
344   bool                        myIsClosed;
345   bool                        myIsBSpline;
346   Handle(TColgp_HArray1OfPnt) myPoints;
347 };
348
349 //=======================================================================
350 // function : constructCurve
351 // purpose  : 
352 //=======================================================================
353 bool CurveCreator_Utils::constructCurve
354                       (const TopoDS_Shape        theShape,
355                              CurveCreator_Curve *theCurve,
356                              gp_Ax3             &theLocalCS)
357 {
358   if (theShape.IsNull()) {
359     return false;
360   }
361
362   // Collect wires or vertices from shape.
363   TopTools_ListOfShape aWOrV;
364   TopAbs_ShapeEnum     aType = theShape.ShapeType();
365
366   if (aType == TopAbs_WIRE || aType == TopAbs_VERTEX) {
367     aWOrV.Append(theShape);
368   } else if (aType == TopAbs_COMPOUND) {
369     TopoDS_Iterator aShIter(theShape);
370
371     for (; aShIter.More(); aShIter.Next()) {
372       const TopoDS_Shape &aSubShape = aShIter.Value();
373
374       aType = aSubShape.ShapeType();
375
376       if (aType == TopAbs_WIRE || aType == TopAbs_VERTEX) {
377         aWOrV.Append(aSubShape);
378       } else {
379         // Only subshapes of types wire or vertex are supported.
380         return false;
381       }
382     }
383   } else {
384     // Only wire (vertex) or compound of wires (vertices) are supported.
385     return false;
386   }
387
388   // Treat each wire or vertex. Get points, compute the working plane.
389   gp_Pln                             aPlane;
390   Standard_Integer                   aPlaneStatus = PLN_FREE;
391   TopTools_ListIteratorOfListOfShape anIter(aWOrV);
392   std::list<Section3D>               aListSec;
393
394   for (; anIter.More(); anIter.Next()) {
395     Section3D aSec3D;
396
397     aSec3D.myPoints = CurveCreator_Utils::getPoints
398       (anIter.Value(), aSec3D.myIsClosed, aSec3D.myIsBSpline);
399
400     if (aSec3D.myPoints.IsNull()) {
401       return false;
402     }
403
404     aListSec.push_back(aSec3D);
405
406     if (aPlaneStatus != PLN_FIXED) {
407       // Compute plane
408       CurveCreator_Utils::FindPlane(aSec3D.myPoints, aPlane, aPlaneStatus);
409     }
410   }
411
412   // Check if it is possible to change a computed coordinate system by
413   // XOY, XOZ or YOZ or parallel to them.
414   gp_Pnt        aO(0., 0., 0.);
415   gp_Dir        aNDir(0., 0., 1.);
416   gp_Dir        aXDir(1., 0., 0.);
417   gp_Ax3        anAxis;
418   Standard_Real aTolAng = Precision::Confusion(); // Angular() is too small.
419
420   switch (aPlaneStatus) {
421     case PLN_ORIGIN:
422       {
423         // Change the location.
424         aO.SetZ(aPlane.Location().Z());
425         anAxis.SetLocation(aO);
426         aPlane.SetPosition(anAxis);
427       }
428       break;
429     case PLN_OX:
430       {
431         // Fixed origin + OX axis
432         const gp_Dir &aPlnX = aPlane.Position().XDirection();
433
434         if (Abs(aPlnX.Z()) <= aTolAng) {
435           // Make a coordinate system parallel to XOY.
436           aO.SetZ(aPlane.Location().Z());
437           anAxis.SetLocation(aO);
438           aPlane.SetPosition(anAxis);
439         } else if (Abs(aPlnX.Y()) <= aTolAng) {
440           // Make a coordinate system parallel to XOZ.
441           aO.SetY(aPlane.Location().Y());
442           aNDir.SetCoord(0., 1., 0.);
443           aXDir.SetCoord(0., 0., 1.);
444           anAxis = gp_Ax3(aO, aNDir, aXDir);
445           aPlane.SetPosition(anAxis);
446         } else if (Abs(aPlnX.X()) <= aTolAng) {
447           // Make a coordinate system parallel to YOZ.
448           aO.SetX(aPlane.Location().X());
449           aNDir.SetCoord(1., 0., 0.);
450           aXDir.SetCoord(0., 1., 0.);
451           anAxis = gp_Ax3(aO, aNDir, aXDir);
452           aPlane.SetPosition(anAxis);
453         }
454       }
455       break;
456     case PLN_FIXED:
457       {
458         const gp_Dir &aPlnN = aPlane.Position().Direction();
459         gp_Dir        aYDir(0., 1., 0.);
460
461         if (aPlnN.IsParallel(aNDir, aTolAng)) {
462           // Make a coordinate system parallel to XOY.
463           aO.SetZ(aPlane.Location().Z());
464           anAxis.SetLocation(aO);
465           aPlane.SetPosition(anAxis);
466         } else if (aPlnN.IsParallel(aYDir, aTolAng)) {
467           // Make a coordinate system parallel to XOZ.
468           aO.SetY(aPlane.Location().Y());
469           aNDir.SetCoord(0., 1., 0.);
470           aXDir.SetCoord(0., 0., 1.);
471           anAxis = gp_Ax3(aO, aNDir, aXDir);
472           aPlane.SetPosition(anAxis);
473         } else if (aPlnN.IsParallel(aXDir, aTolAng)) {
474           // Make a coordinate system parallel to YOZ.
475           aO.SetX(aPlane.Location().X());
476           aNDir.SetCoord(1., 0., 0.);
477           aXDir.SetCoord(0., 1., 0.);
478           anAxis = gp_Ax3(aO, aNDir, aXDir);
479           aPlane.SetPosition(anAxis);
480         }
481       }
482       break;
483     case PLN_FREE:
484     default:
485       // Use XOY plane.
486       aPlane.SetPosition(anAxis);
487       break;
488   }
489
490   // Compute 2d points.
491   std::list<Section3D>::const_iterator aSecIt = aListSec.begin();
492   Standard_Real                        aTolConf2 =
493     Precision::Confusion()*Precision::Confusion();
494   Standard_Real                        aX;
495   Standard_Real                        aY;
496
497   for (; aSecIt != aListSec.end(); ++aSecIt) {
498     Standard_Integer          i;
499     CurveCreator::Coordinates aCoords;
500
501     for (i = aSecIt->myPoints->Lower(); i <= aSecIt->myPoints->Upper(); ++i) {
502       const gp_Pnt &aPnt = aSecIt->myPoints->Value(i);
503
504       if (aPlane.SquareDistance(aPnt) > aTolConf2) {
505         // The point doesn't lie on the plane.
506         return false;
507       }
508
509       ElSLib::Parameters(aPlane, aPnt, aX, aY);
510       aCoords.push_back(aX);
511       aCoords.push_back(aY);
512     }
513
514     // Add a new section to the curve.
515     const std::string               aSecName =
516       CurveCreator_UtilsICurve::getUniqSectionName(theCurve);
517     const CurveCreator::SectionType aSecType = aSecIt->myIsBSpline ?
518       CurveCreator::Spline : CurveCreator::Polyline;
519
520     theCurve->addSectionInternal(aSecName, aSecType,
521                                  aSecIt->myIsClosed, aCoords);
522   }
523
524   // Set the local coordinate system.
525   theLocalCS = aPlane.Position();
526
527   return true;
528 }
529
530 class CompareSectionToPoint
531 {
532 public:
533   CompareSectionToPoint( const int theISection = -1, const int theIPoint = -1 )
534     : mySectionId( theISection ), myPointId( theIPoint ) {};
535   ~CompareSectionToPoint() {}
536
537   bool operator < ( const CompareSectionToPoint& theOther ) const
538   {
539     bool isLess = mySectionId < theOther.mySectionId;
540     if ( !isLess && mySectionId == theOther.mySectionId )
541       isLess = myPointId < theOther.myPointId;
542     return isLess;
543   }
544
545 private:
546   int mySectionId;
547   int myPointId;
548 };
549
550
551 void CurveCreator_Utils::getSelectedPoints( Handle(AIS_InteractiveContext) theContext,
552                                             const CurveCreator_ICurve* theCurve,
553                                             CurveCreator_ICurve::SectionToPointList& thePoints )
554 {
555   thePoints.clear();
556
557   std::list<double> aSelectedPoints;
558   gp_Pnt aPnt;
559   std::map<CompareSectionToPoint, int> aPointsMap;
560
561   CurveCreator_ICurve::SectionToPointList aPoints;
562   for ( theContext->InitSelected(); theContext->MoreSelected(); theContext->NextSelected() ) {
563     TopoDS_Vertex aVertex;
564     TopoDS_Shape aShape = theContext->SelectedShape();
565     if ( !aShape.IsNull() && aShape.ShapeType() == TopAbs_VERTEX )
566       aVertex = TopoDS::Vertex( theContext->SelectedShape() );
567
568     if ( aVertex.IsNull() )
569       continue;
570     aPnt = BRep_Tool::Pnt( aVertex );
571
572     CurveCreator_UtilsICurve::findSectionsToPoints( theCurve, aPnt.X(), aPnt.Y(), aPoints );
573     CurveCreator_ICurve::SectionToPointList::const_iterator anIt = aPoints.begin(),
574                                                             aLast = aPoints.end();
575     CompareSectionToPoint aPoint;
576     for ( ; anIt != aLast; anIt++ ) {
577       aPoint = CompareSectionToPoint( (*anIt).first, (*anIt).second );
578       if ( aPointsMap.find( aPoint ) != aPointsMap.end() )
579         continue;
580       aPointsMap[aPoint] = 0;
581
582       thePoints.push_back( *anIt );
583     }
584   }
585 }
586
587 void CurveCreator_Utils::setSelectedPoints( Handle(AIS_InteractiveContext) theContext,
588                                             const CurveCreator_ICurve* theCurve,
589                                             const CurveCreator_ICurve::SectionToPointList& thePoints )
590 {
591   if ( !theCurve )
592     return;
593
594   Handle(AIS_InteractiveObject) anAIS = theCurve->getAISObject();
595   if ( anAIS.IsNull() )
596     return;
597   Handle(AIS_Shape) anAISShape = Handle(AIS_Shape)::DownCast( anAIS );
598   if ( anAISShape.IsNull() )
599     return;
600
601   //ASL: we convert list of point indices to list of points coordinates
602   int aSize = thePoints.size();
603   std::vector<gp_Pnt> aPntsToSelect( aSize );
604
605   CurveCreator_ICurve::SectionToPointList::const_iterator
606                      aPIt = thePoints.begin(), aPLast = thePoints.end();
607   CurveCreator_ICurve::SectionToPoint aSToPoint;
608   for( int i=0; aPIt != aPLast; aPIt++, i++ )
609   {
610     gp_Pnt aPntToSelect;
611     CurveCreator_UtilsICurve::getPoint( theCurve, aPIt->first, aPIt->second, aPntToSelect );
612     aPntsToSelect[i] = aPntToSelect;
613   }
614
615   theContext->ClearSelected( Standard_False );
616   //ASL: we switch off automatic highlight to improve performance of selection
617   theContext->SetAutomaticHilight( Standard_False );
618
619   Handle(SelectMgr_Selection) aSelection = anAISShape->Selection( AIS_Shape::SelectionMode( TopAbs_VERTEX ) );
620
621   CurveCreator_ICurve::SectionToPointList::const_iterator anIt = thePoints.begin(),
622                                                           aLast = thePoints.end();
623   bool isFound = false;
624   for( int i=0; i<aSize; i++ )
625   {
626     for( aSelection->Init(); aSelection->More(); aSelection->Next() )
627     {    
628 #if OCC_VERSION_LARGE > 0x06080100
629       const Handle(SelectMgr_SensitiveEntity) aHSenEntity = aSelection->Sensitive();
630       if( aHSenEntity.IsNull() )
631         continue;
632       Handle(SelectBasics_SensitiveEntity) aSenEntity = aHSenEntity->BaseSensitive();
633 #else
634       Handle(SelectBasics_SensitiveEntity) aSenEntity = aSelection->Sensitive();
635 #endif
636
637       Handle(Select3D_SensitivePoint) aSenPnt = Handle(Select3D_SensitivePoint)::DownCast( aSenEntity );
638   
639       gp_Pnt anOwnerPnt = aSenPnt->Point();
640       Handle(SelectMgr_EntityOwner) anOwner = Handle(SelectMgr_EntityOwner)::DownCast( aSenPnt->OwnerId() );
641
642       bool isIntersect = fabs( aPntsToSelect[i].X() - anOwnerPnt.X() ) < LOCAL_SELECTION_TOLERANCE &&
643                          fabs( aPntsToSelect[i].Y() - anOwnerPnt.Y() ) < LOCAL_SELECTION_TOLERANCE;
644       if( isIntersect )
645       {
646         theContext->AddOrRemoveSelected( anOwner, Standard_False );
647         break;
648       }
649     }
650   }
651
652   //ASL: we switch on again automatic highlight (otherwise selection will not be shown)
653   //     and call HilightPicked to draw selected owners
654   theContext->SetAutomaticHilight( Standard_True );
655   theContext->LocalContext()->HilightPicked( Standard_True );
656 }
657
658 //=======================================================================
659 // function : setLocalPointContext
660 // purpose  : Open/close the viewer local context
661 //=======================================================================
662 void CurveCreator_Utils::setLocalPointContext( const CurveCreator_ICurve* theCurve,
663                                                Handle(AIS_InteractiveContext) theContext,
664                                                const bool theOpen )
665 {
666   if ( !theContext )
667     return;
668
669   if ( theOpen ) {
670     // Open local context if there is no one
671     if ( !theContext->HasOpenedContext() ) {
672       theContext->ClearCurrents( false );
673       theContext->OpenLocalContext( false/*use displayed objects*/, true/*allow shape decomposition*/ );
674     }
675     // load the curve AIS object to the local context with the point selection
676     Handle(AIS_InteractiveObject) anAIS = theCurve->getAISObject();
677     if ( !anAIS.IsNull() )
678     {
679       if ( anAIS->IsKind( STANDARD_TYPE( AIS_Shape ) ) )
680       {
681         theContext->Load( anAIS, -1/*selection mode*/, true/*allow decomposition*/ );
682         theContext->Activate( anAIS, AIS_Shape::SelectionMode( (TopAbs_ShapeEnum)TopAbs_VERTEX ) );
683       }
684     }
685   }
686   else {
687     if ( theContext->HasOpenedContext() )
688       theContext->CloseAllContexts( Standard_True );
689   }
690 }
691
692 bool CurveCreator_Utils::pointOnObject( Handle(V3d_View) theView,
693                                         Handle(AIS_InteractiveObject) theObject,
694                                         const int theX, const int theY,
695                                         gp_Pnt& thePoint,
696                                         gp_Pnt& thePoint1, gp_Pnt& thePoint2 )
697 {
698   bool isFullFound = false;
699
700   if ( theObject.IsNull() || theView.IsNull() )
701     return isFullFound;
702   Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast( theObject );
703   if ( aShape.IsNull() )
704     return isFullFound;
705   const TopoDS_Compound& aCompound = TopoDS::Compound( aShape->Shape() );
706   if ( aCompound.IsNull() )
707     return isFullFound;
708
709   gp_Pnt aCurPoint, aCurPoint1, aCurPoint2;
710   gp_Pnt aFoundPoint, aFoundPnt1, aFoundPnt2;
711   Standard_Real aParameter;
712   bool isFound = false;
713   int aDelta, aMinDelta = 2*SCENE_PIXEL_PROJECTION_TOLERANCE*SCENE_PIXEL_PROJECTION_TOLERANCE;
714   TopExp_Explorer anExp( aCompound, TopAbs_EDGE );
715   for ( ; anExp.More(); anExp.Next())
716   {
717     const TopoDS_Edge& anEdge = TopoDS::Edge(anExp.Current());
718     if ( anEdge.IsNull() )
719       continue;
720     Standard_Real aFirst, aLast;
721     Handle(Geom_Curve) aCurve = BRep_Tool::Curve( anEdge, aFirst, aLast );
722     if ( aCurve->IsKind( STANDARD_TYPE(Geom_BSplineCurve) ) ) {
723       Handle(Geom_BSplineCurve) aBSplineCurve =
724                           Handle(Geom_BSplineCurve)::DownCast( aCurve );
725       if ( !aBSplineCurve.IsNull() ) {
726         isFound = hasProjectPointOnCurve( theView, theX, theY, aBSplineCurve,
727                                           aParameter, aDelta );
728         if ( isFound ) {
729           aCurPoint = aBSplineCurve->Value( aParameter );
730           Standard_Integer anI1, anI2;
731           aBSplineCurve->LocateU( aParameter, LOCAL_SELECTION_TOLERANCE, anI1, anI2 );
732           aCurPoint1 = aBSplineCurve->Value( aBSplineCurve->Knot( anI1 ) );
733           aCurPoint2 = aBSplineCurve->Value( aBSplineCurve->Knot( anI2 ) );
734         }
735       }
736     }
737     else { // a curve built on a polyline edge
738       Handle(Geom_Line) aGLine = Handle(Geom_Line)::DownCast( aCurve );
739       if ( aGLine.IsNull() )
740         continue;
741       isFound = hasProjectPointOnCurve( theView, theX, theY, aGLine, aParameter,
742                                         aDelta );
743       if ( isFound ) {
744         aCurPoint = aGLine->Value( aParameter );
745         TopoDS_Vertex V1, V2;
746         TopExp::Vertices( anEdge, V1, V2, Standard_True );
747         if ( V1.IsNull() || V2.IsNull() )
748           continue;
749         aCurPoint1 = BRep_Tool::Pnt(V1);
750         aCurPoint2 = BRep_Tool::Pnt(V2);
751
752         // check that the projected point is on the bounded curve
753         gp_Vec aVec1( aCurPoint1, aCurPoint );
754         gp_Vec aVec2( aCurPoint2, aCurPoint );
755         isFound = fabs( aVec1.Angle( aVec2 ) - M_PI ) < LOCAL_SELECTION_TOLERANCE;
756       }
757     }
758     if ( isFound && aMinDelta >= aDelta ) {
759       aMinDelta = aDelta;
760
761       isFullFound = true;
762       aFoundPnt1 = aCurPoint1;
763       aFoundPnt2 = aCurPoint2;
764       aFoundPoint = aCurPoint;
765     }
766   }
767   if ( isFullFound ) {
768     int aX, anY, aX1, anY1, aX2, anY2;
769     int aDelta;
770     CurveCreator_Utils::ConvertPointToClick( aFoundPoint, theView, aX, anY );
771     CurveCreator_Utils::ConvertPointToClick( aFoundPnt1, theView, aX1, anY1 );
772     CurveCreator_Utils::ConvertPointToClick( aFoundPnt2, theView, aX2, anY2 );
773
774     isFullFound = !isEqualPixels( aX, anY, aX1, anY1, SCENE_PIXEL_POINT_TOLERANCE, aDelta ) &&
775                   !isEqualPixels( aX, anY, aX2, anY2, SCENE_PIXEL_POINT_TOLERANCE, aDelta );
776     if ( isFullFound ) {
777       thePoint = aFoundPoint;
778       thePoint1 = aFoundPnt1;
779       thePoint2 = aFoundPnt2;
780     }
781   }
782   return isFullFound;
783 }
784
785 bool CurveCreator_Utils::hasProjectPointOnCurve( Handle(V3d_View) theView,
786                                                  const int theX, const int theY,
787                                                  const Handle(Geom_Curve)& theCurve,
788                                                  Standard_Real& theParameter,
789                                                  int& theDelta )
790 {
791   bool isFound = false;
792   if ( theView.IsNull() )
793     return isFound;
794
795   gp_Pnt aPoint = CurveCreator_Utils::ConvertClickToPoint( theX, theY, theView );
796
797   GeomAPI_ProjectPointOnCurve aProj( aPoint, theCurve );
798   Standard_Integer aNbPoint = aProj.NbPoints();
799   if (aNbPoint > 0) {
800     for (Standard_Integer j = 1; j <= aNbPoint && !isFound; j++) {
801       gp_Pnt aNewPoint = aProj.Point( j );
802       theParameter = aProj.Parameter( j );
803
804       int aX, anY;
805       CurveCreator_Utils::ConvertPointToClick( aNewPoint, theView, aX, anY );
806
807       isFound = isEqualPixels( aX, anY, theX, theY, SCENE_PIXEL_PROJECTION_TOLERANCE, theDelta );
808     }
809   }
810   return isFound;
811 }
812
813 bool CurveCreator_Utils::isEqualPixels( const int theX, const int theY, const int theOtherX,
814                                         const int theOtherY, const double theTolerance, int& theDelta )
815 {
816   int aXDelta = abs( theX - theOtherX );
817   int anYDelta = abs( theY - theOtherY );
818
819   theDelta = aXDelta*aXDelta + anYDelta*anYDelta;
820
821   return aXDelta < theTolerance && anYDelta < theTolerance;
822 }
823
824 bool CurveCreator_Utils::isEqualPoints( const gp_Pnt& thePoint, const gp_Pnt& theOtherPoint )
825 {
826   return theOtherPoint.IsEqual( thePoint, LOCAL_SELECTION_TOLERANCE );
827 }
828
829 //=======================================================================
830 // function : getPoints
831 // purpose  : 
832 //=======================================================================
833 Handle(TColgp_HArray1OfPnt) CurveCreator_Utils::getPoints
834                   (const TopoDS_Shape &theShape,
835                          bool         &IsClosed,
836                          bool         &IsBSpline)
837 {
838   Handle(TColgp_HArray1OfPnt) aResult;
839
840   IsClosed  = false;
841   IsBSpline = false;
842
843   if (theShape.IsNull()) {
844     return aResult;
845   }
846
847   const TopAbs_ShapeEnum aShType = theShape.ShapeType();
848
849   if (aShType == TopAbs_VERTEX) {
850     // There is a single point.
851     gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(theShape));
852
853     aResult = new TColgp_HArray1OfPnt(1, 1, aPnt);
854
855     return aResult;
856   } else if (aShType != TopAbs_WIRE) {
857     // The shape is neither a vertex nor a wire.
858     return aResult;
859   }
860
861   // Treat wire.
862   BRepTools_WireExplorer anExp(TopoDS::Wire(theShape));
863
864   if (!anExp.More()) {
865     // Empty wires are not allowed.
866     return aResult;
867   }
868
869   // Treat the first edge.
870   TopoDS_Edge        anEdge = anExp.Current();
871   Handle(Geom_Curve) aCurve = GetCurve(anEdge);
872
873   if (aCurve.IsNull()) {
874     return aResult;
875   }
876
877   // Check the curve type.
878   Handle(Standard_Type) aType     = aCurve->DynamicType();
879
880   if (aType == STANDARD_TYPE(Geom_BSplineCurve)) {
881     IsBSpline = true;
882   } else if (aType != STANDARD_TYPE(Geom_Line)) {
883     // The curve is neither a line or a BSpline. It is not valid.
884     return aResult;
885   }
886
887   // Go to the next edge.
888   TopoDS_Vertex aFirstVtx = anExp.CurrentVertex();
889
890   anExp.Next();
891
892   if (IsBSpline)
893   {
894     // There should be a single BSpline curve in the wire.
895     if (anExp.More()) {
896       return aResult;
897     }
898
899     // Construct a section from poles of BSpline.
900     Handle(Geom_BSplineCurve) aBSplCurve =
901       Handle(Geom_BSplineCurve)::DownCast(aCurve);
902
903     // Check if the edge is valid. It should not be based on trimmed curve.
904     gp_Pnt aCP[2] = { aBSplCurve->StartPoint(), aBSplCurve->EndPoint() };
905     TopoDS_Vertex aV[2];
906     Standard_Integer i;
907
908     TopExp::Vertices(anEdge, aV[0], aV[1]);
909
910     for (i = 0; i < 2; i++) {
911       gp_Pnt        aPnt = BRep_Tool::Pnt(aV[i]);
912       Standard_Real aTol = BRep_Tool::Tolerance(aV[i]);
913
914       if (!aPnt.IsEqual(aCP[i], aTol)) {
915         return aResult;
916       }
917     }
918
919     IsClosed = aV[0].IsSame(aV[1]) ? true : false;
920     
921     Standard_Integer aNbPoints = aBSplCurve->NbKnots();
922     TColStd_Array1OfReal aKnots(1, aNbPoints);
923     aBSplCurve->Knots(aKnots);
924
925     // Don't consider the last point as it coincides with the first
926     if (IsClosed)
927       --aNbPoints;
928
929     aResult = new TColgp_HArray1OfPnt(1, aNbPoints);
930     for (i = 1; i <= aNbPoints; ++i)
931       aResult->SetValue(i, aBSplCurve->Value( aKnots.Value(i) ));
932   }
933   else
934   {
935     // This is a polyline.
936     TopTools_ListOfShape aVertices;
937     Standard_Integer     aNbVtx = 1;
938
939
940     aVertices.Append(aFirstVtx);
941
942     for (; anExp.More(); anExp.Next(), ++aNbVtx) {
943       anEdge = anExp.Current();
944       aCurve = GetCurve(anEdge);
945
946       if (aCurve.IsNull()) {
947         return aResult;
948       }
949
950       aType = aCurve->DynamicType();
951
952       if (aType != STANDARD_TYPE(Geom_Line)) {
953         // The curve is not a line. It is not valid.
954         return aResult;
955       }
956
957       // Add the current vertex to the list.
958       aVertices.Append(anExp.CurrentVertex());
959     }
960
961     // Check if the section is closed.
962     TopoDS_Vertex aLastVtx = TopExp::LastVertex(anEdge, Standard_True);
963
964     IsClosed = aFirstVtx.IsSame(aLastVtx) ? true : false;
965
966     // Store a last vertex
967     if (!IsClosed)
968     {
969       aVertices.Append(aLastVtx);
970       aNbVtx++;
971     }
972
973     // Fill the array of points.
974     aResult = new TColgp_HArray1OfPnt(1, aNbVtx);
975
976     Standard_Integer i;
977     TopTools_ListIteratorOfListOfShape aVtxIter(aVertices);
978
979     for (i = 1; aVtxIter.More(); aVtxIter.Next(), ++i) {
980       gp_Pnt aPnt = BRep_Tool::Pnt(TopoDS::Vertex(aVtxIter.Value()));
981
982       aResult->SetValue(i, aPnt);
983     }
984   }
985
986   return aResult;
987 }
988 //=======================================================================
989 // function : FindPlane
990 // purpose  : 
991 //=======================================================================
992 void CurveCreator_Utils::FindPlane
993                        (const Handle(TColgp_HArray1OfPnt) &thePoints,
994                               gp_Pln                     &thePlane,
995                               Standard_Integer           &thePlnStatus)
996 {
997   if (thePoints.IsNull() || thePlnStatus == PLN_FIXED) {
998     // The plane can't be defined or is fixed. Nothing to change.
999     return;
1000   }
1001
1002   Standard_Integer    i;
1003   const Standard_Real aTolConf = Precision::Confusion();
1004
1005   for (i = thePoints->Lower(); i <= thePoints->Upper(); ++i) {
1006     const gp_Pnt &aPnt = thePoints->Value(i);
1007
1008     switch (thePlnStatus) {
1009       case PLN_FREE:
1010         // Fix the origin.
1011         thePlane.SetLocation(aPnt);
1012         thePlnStatus = PLN_ORIGIN;
1013         break;
1014       case PLN_ORIGIN:
1015         {
1016           // Fix origin + OX axis
1017           const gp_Pnt &aPlnLoc = thePlane.Location();
1018
1019           if (!aPnt.IsEqual(aPlnLoc, aTolConf)) {
1020             // Set the X axis.
1021             gp_Dir aXDir(aPnt.XYZ().Subtracted(aPlnLoc.XYZ()));
1022             gp_Ax3 aXNorm(aPlnLoc, aXDir);
1023             gp_Ax3 aNewPlnPos(aPlnLoc, aXNorm.XDirection(), aXNorm.Direction());
1024
1025             thePlane.SetPosition(aNewPlnPos);
1026             thePlnStatus = PLN_OX;
1027           }
1028         }
1029         break;
1030       case PLN_OX:
1031         {
1032           // Fix OY axis
1033           gp_Lin aXLin(thePlane.XAxis());
1034           Standard_Real aSqrDist = aXLin.SquareDistance(aPnt);
1035
1036           if (aSqrDist > aTolConf*aTolConf) {
1037             // Compute main axis.
1038             const gp_Pnt &aPlnLoc = thePlane.Location();
1039             gp_Dir        aDir(aPnt.XYZ().Subtracted(aPlnLoc.XYZ()));
1040             gp_Ax3        aXNorm(aPlnLoc, aXLin.Direction(), aDir);
1041             gp_Ax3        aNewPlnPos(aPlnLoc, aXNorm.YDirection(),
1042                                      aXNorm.Direction());
1043
1044             thePlane.SetPosition(aNewPlnPos);
1045             thePlnStatus = PLN_FIXED;
1046             return;
1047           }
1048         }
1049         break;
1050       default:
1051         return;
1052     }
1053   }
1054 }