Salome HOME
2e4ffff3315ad5fc26c2634915bcfd4868664d98
[modules/hydro.git] / src / HYDROData / HYDROData_PolylineOperator.cxx
1 // Copyright (C) 2014-2015  EDF-R&D
2 // This library is free software; you can redistribute it and/or
3 // modify it under the terms of the GNU Lesser General Public
4 // License as published by the Free Software Foundation; either
5 // version 2.1 of the License, or (at your option) any later version.
6 //
7 // This library is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10 // Lesser General Public License for more details.
11 //
12 // You should have received a copy of the GNU Lesser General Public
13 // License along with this library; if not, write to the Free Software
14 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
15 //
16 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
17 //
18
19 #include <HYDROData_PolylineOperator.h>
20 #include <HYDROData_Document.h>
21 #include <HYDROData_TopoCurve.h>
22 #include <HYDROData_Object.h>
23
24 #ifndef LIGHT_MODE
25 #include <CurveCreator_Utils.hxx>
26 #endif
27
28 #include <BRepAdaptor_Curve.hxx>
29 #include <BRep_Builder.hxx>
30 #include <BRep_Tool.hxx>
31 #include <BRepBuilderAPI_MakeEdge2d.hxx>
32 #include <BRepBuilderAPI_MakeEdge.hxx>
33 #include <BRepBuilderAPI_MakeWire.hxx>
34 #include <Extrema_ExtCC.hxx>
35 #include <Extrema_ExtPC.hxx>
36 #include <GeomAPI_Interpolate.hxx>
37 #include <NCollection_Vector.hxx>
38 #include <Precision.hxx>
39 #include <ShapeAnalysis_TransferParametersProj.hxx>
40 #include <ShapeBuild_Edge.hxx>
41 #include <TColgp_Array1OfVec.hxx>
42 #include <TColgp_HArray1OfPnt.hxx>
43 #include <TColStd_HArray1OfBoolean.hxx>
44 #include <TopoDS.hxx>
45 #include <TopoDS_Edge.hxx>
46 #include <TopoDS_Wire.hxx>
47 #include <TopExp.hxx>
48 #include <TopExp_Explorer.hxx>
49 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
50 #include <QStringList>
51 #include <QColor>
52 #include <Geom_BSplineCurve.hxx>
53
54 #define _DEVDEBUG_
55 #include "HYDRO_trace.hxx"
56 #include <BRepTools.hxx>
57 #include <sstream>
58
59 template<class T> void append( std::vector<T>& theList, const std::vector<T>& theList2 )
60 {
61   int aSize = theList.size();
62   int aNewSize = aSize + theList2.size();
63
64   if( aSize==aNewSize )
65     return;
66
67   theList.resize( aNewSize );
68   for( int i=aSize, j=0; i<aNewSize; i++, j++ )
69     theList[i] = theList2[j];
70 }
71
72 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
73                                         const Handle( HYDROData_PolylineXY )& thePolyline,
74                                         const gp_Pnt2d& thePoint,
75                                         double theTolerance ) const
76 {
77   if (thePolyline.IsNull())
78   {
79     return false;
80   }
81
82   std::vector<gp_Pnt2d> aPointsList( 1 );
83   aPointsList[0] = thePoint;
84   std::vector<TopoDS_Wire> aCurves;
85   GetWires(thePolyline, aCurves);
86   bool isOK = true;
87   for( int i=0, n=aCurves.size(); i<n; i++ )
88   {
89     std::vector<TopoDS_Shape> aCurvesList;
90     Split( aCurves[i], thePoint, theTolerance, aCurvesList );
91     bool isLocalOK = CreatePolylines( theDoc, thePolyline->GetName(),
92       aCurvesList, true, thePolyline->GetWireColor() );
93     isOK = isOK && isLocalOK;
94   }
95   return isOK;
96 }
97
98 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
99               const Handle( HYDROData_PolylineXY )& thePolyline,
100               const Handle( HYDROData_PolylineXY )& theTool,
101               double theTolerance,
102               bool& theIsIntersected) const
103 {
104   if (thePolyline.IsNull() || theTool.IsNull())
105   {
106     return false;
107   }
108
109   HYDROData_SequenceOfObjects aSeq;
110   aSeq.Append( theTool );
111   return split( theDoc, thePolyline, aSeq, theTolerance, -1, theIsIntersected);
112 }
113
114 bool HYDROData_PolylineOperator::Split( const Handle( HYDROData_Document )& theDoc,
115                                         const HYDROData_SequenceOfObjects& thePolylines,
116                                         double theTolerance )
117 {
118   int f = thePolylines.Lower(), l = thePolylines.Upper();
119   for( int i=f; i<=l; i++ )
120   {
121     Handle( HYDROData_PolylineXY ) aPolyline = Handle( HYDROData_PolylineXY )::DownCast( thePolylines.Value( i ) );
122     bool isIntersected;
123     if( !split( theDoc, aPolyline, thePolylines, theTolerance, i, isIntersected) )
124       return false;
125   }
126   return true;
127 }
128
129 bool HYDROData_PolylineOperator::Merge( const Handle( HYDROData_Document )& theDoc,
130                                         const QString& theName,
131                                         const HYDROData_SequenceOfObjects& thePolylines,
132                                         bool isConnectByNewSegment,
133                                         double theTolerance )
134 {
135   std::deque<HYDROData_TopoCurve> aMergedCurves;
136   HYDROData_SequenceOfObjects::Iterator aPIt(thePolylines);
137   for (; aPIt.More(); aPIt.Next())
138   {
139     Handle(HYDROData_PolylineXY) aPolyline =
140       Handle(HYDROData_PolylineXY)::DownCast(aPIt.Value());
141     std::vector<TopoDS_Wire> aWires;
142     GetWires(aPolyline, aWires);
143     for (std::vector<TopoDS_Wire>::const_iterator aWIt = aWires.begin(),
144       aLastWIt = aWires.end(); aWIt != aLastWIt; ++aWIt)
145     {
146       const Standard_Boolean aResult = !isConnectByNewSegment ?
147         HYDROData_TopoCurve::Merge(theTolerance, *aWIt, aMergedCurves) :
148         HYDROData_TopoCurve::Connect(theTolerance, *aWIt, aMergedCurves);
149       if (!aResult)
150       {
151         return false;
152       }
153     }
154   }
155
156   TopoDS_Compound aWireSet;
157   BRep_Builder aBuilder;
158   aBuilder.MakeCompound(aWireSet);
159   std::deque<HYDROData_TopoCurve>::iterator aCIt = aMergedCurves.begin();
160   std::deque<HYDROData_TopoCurve>::iterator aLastCIt = aMergedCurves.end();
161   for (; aCIt != aLastCIt; ++aCIt)
162   {
163     if (!aCIt->IsEmpty())
164     {
165       aBuilder.Add(aWireSet, aCIt->Wire());
166     }
167   }
168
169   std::vector<TopoDS_Shape> aPolylines(1);
170   aPolylines[0] = aWireSet;
171   QString aName = theName;
172   if( aName.isEmpty() )
173     aName = "merged";
174   CreatePolylines( theDoc, aName, aPolylines, true, QColor() );
175   return true;
176 }
177
178 bool HYDROData_PolylineOperator::split( const Handle( HYDROData_Document )& theDoc,
179                                         const Handle( HYDROData_PolylineXY )& thePolyline,
180                                         const HYDROData_SequenceOfObjects& theTools,
181                                         double theTolerance,
182                                         int theIgnoreIndex,
183                                         bool& theIsIntersected) const
184 {
185   theIsIntersected = false;
186
187   if (thePolyline.IsNull())
188   {
189     return false;
190   }
191
192   std::vector<TopoDS_Wire> aCurves;
193   GetWires(thePolyline, aCurves);
194   std::vector<TopoDS_Wire> aToolCurves;
195   for( int i=theTools.Lower(), n=theTools.Upper(); i<=n; i++ )
196     if( i!=theIgnoreIndex )
197     {
198       Handle( HYDROData_PolylineXY ) aToolPolyline = 
199         Handle( HYDROData_PolylineXY )::DownCast( theTools.Value( i ) );
200       if (!aToolPolyline.IsNull())
201       {
202         std::vector<TopoDS_Wire> aTCurves;
203         GetWires(aToolPolyline, aTCurves);
204         append( aToolCurves, aTCurves);
205       }
206     }
207
208   if (aToolCurves.empty())
209   {
210     return false;
211   }
212
213   const int aPSCount = aCurves.size();
214   const int aTSCount = aToolCurves.size();
215   std::vector<TopoDS_Shape> aResult;
216   for (int aPSI = 0; aPSI < aPSCount; ++aPSI)
217   {
218     HYDROData_TopoCurve aCurve;
219     DEBTRACE("Initialize curve " << aPSI);
220     if (!aCurve.Initialize(aCurves[aPSI]))
221     {
222       continue;
223     }
224
225     std::deque<std::list<double> > aParams;
226     for (int aTSI = 0; aTSI < aTSCount; ++aTSI)
227     {
228       aCurve.Intersect(aToolCurves[aTSI], aParams);
229     }
230
231     std::deque<HYDROData_TopoCurve> aSplitCurves;
232     theIsIntersected |= aCurve.Cut(aParams, aSplitCurves);
233     std::deque<HYDROData_TopoCurve>::const_iterator aCIt =
234       aSplitCurves.begin();
235     std::deque<HYDROData_TopoCurve>::const_iterator aLastCIt =
236       aSplitCurves.end();
237     for (int iw=0; aCIt != aLastCIt; ++aCIt, iw++)
238     {
239         std::stringstream brepName;
240         brepName << "theSplitWire_";
241         brepName << iw;
242         brepName << ".brep";
243         BRepTools::Write(aCIt->Wire() , brepName.str().c_str() );
244      aResult.push_back(aCIt->Wire());
245     }
246   }
247
248   CreatePolylines( theDoc, thePolyline->GetName(), aResult, true, thePolyline->GetWireColor() );
249   //CreatePolylinesSplit( theDoc, thePolyline, aResult, true );
250   return true;
251 }
252
253 void HYDROData_PolylineOperator::GetWires(
254   const Handle( HYDROData_PolylineXY )& thePolyline,
255   std::vector<TopoDS_Wire>& theWires)
256 {
257   TopoDS_Shape aShape = thePolyline->GetShape();
258   if( aShape.ShapeType()==TopAbs_WIRE )
259   {
260     theWires.push_back( TopoDS::Wire( aShape ) );
261   }
262   else
263   {
264     TopExp_Explorer anExp( aShape, TopAbs_WIRE );
265     for( ; anExp.More(); anExp.Next() )
266     {
267       theWires.push_back( TopoDS::Wire( anExp.Current() ) );
268     }
269   }
270 }
271
272 void HYDROData_PolylineOperator::Split(
273   const TopoDS_Wire& theWire,
274   const gp_Pnt2d& thePoint,
275   double theTolerance,
276   std::vector<TopoDS_Shape>& theWires)
277 {
278   HYDROData_TopoCurve aCurve;
279   if (!aCurve.Initialize(theWire))
280   {
281     theWires.push_back(theWire);
282     return;
283   }
284
285   const gp_XYZ aP(thePoint.X(), thePoint.Y(), 0);
286   std::list<TopoDS_Edge>::const_iterator aEPos;
287   double aParam;
288   aCurve.Project(aP, aEPos, aParam);
289   HYDROData_TopoCurve aCurve1, aCurve2;
290   aCurve.Cut(aEPos, aParam, aCurve1, aCurve2);
291   theWires.push_back(aCurve1.Wire());
292   if (!aCurve2.IsEmpty())
293   {
294     theWires.push_back(aCurve2.Wire());
295   }
296 }
297
298 //bool HYDROData_PolylineOperator::CreatePolylinesSplit(const Handle( HYDROData_Document )& theDoc,
299 //                                                      const Handle( HYDROData_PolylineXY )& thePolyline,
300 //                                                      const std::vector<TopoDS_Shape>& theShapes, bool isUseIndices)
301 //{
302 //
303 //  if (theDoc.IsNull())
304 //    return false;
305 //
306 //  int nbSections = thePolyline->NbSections();
307 //  const QString& theNamePrefix = thePolyline->GetName();
308 //  const QColor& theColor = thePolyline->GetWireColor();
309 //
310 //  int n = theShapes.size();
311 //  DEBTRACE("theShapes.size() "<< n);
312 //  int anIndex = 1;
313 //  for (int i = 0; i < n; i++)
314 //    {
315 //      Handle( HYDROData_PolylineXY ) aPolyline =
316 //      Handle( HYDROData_PolylineXY )::DownCast(theDoc->CreateObject(KIND_POLYLINEXY));
317 //      if (aPolyline.IsNull())
318 //        return false;
319 //
320 //      for (int isec = 0; isec < nbSections; isec++)
321 //        {
322 //          gp_XY p = gp_XY(0, 0);
323 //          //double d = thePolyline->GetMinDistance(isec, p);
324 //        }
325 //
326 //      if (isUseIndices)
327 //        {
328 //          QString aNewName = theNamePrefix + "_" + QString::number(anIndex);
329 //          while (!theDoc->FindObjectByName(aNewName).IsNull())  // the object with such a name is not found
330 //            {
331 //              anIndex++;
332 //              aNewName = theNamePrefix + "_" + QString::number(anIndex);
333 //            }
334 //          aPolyline->SetName(aNewName);
335 //        }
336 //      else
337 //        {
338 //          aPolyline->SetName(theNamePrefix);
339 //        }
340 //
341 //      if (theColor.isValid())
342 //        aPolyline->SetWireColor(theColor);
343 //    }
344 //  return true;
345 //
346 //}
347
348 bool HYDROData_PolylineOperator::CreatePolylines( const Handle( HYDROData_Document )& theDoc,
349                                                   const QString& theNamePrefix,
350                                                   const std::vector<TopoDS_Shape>& theShapes,
351                                                   bool isUseIndices,
352                                                   const QColor& theColor )
353 {
354   if( theDoc.IsNull() )
355     return false;
356
357   int n = theShapes.size();
358   DEBTRACE("theShapes.size() "<< n);
359   int anIndex = 1;
360   for( int i=0; i<n; i++ )
361   {
362     Handle( HYDROData_PolylineXY ) aPolyline = 
363       Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
364     if( aPolyline.IsNull() )
365       return false;
366
367     aPolyline->ImportShape(theShapes[i], false);
368     //aPolyline->SetShape( theShapes[i] );
369
370
371     if( isUseIndices )
372     {
373       QString aNewName = theNamePrefix + "_" + QString::number( anIndex );
374       while( !theDoc->FindObjectByName( aNewName ).IsNull() )  // the object with such a name is not found
375       {
376         anIndex++;
377         aNewName = theNamePrefix + "_" + QString::number( anIndex );
378       }
379       aPolyline->SetName( aNewName );
380     }
381     else
382     {
383       aPolyline->SetName( theNamePrefix );
384     }
385
386     if( theColor.isValid() )
387       aPolyline->SetWireColor( theColor );
388   }
389   return true;
390 }
391
392 double HYDROData_PolylineOperator::ReduceDeflection(
393   const double theDeflection,
394   HYDROData_TopoCurve& theCurve,
395   int& thePieceCount)
396 {
397   // Construct the approximating B-spline.
398   std::list<gp_XYZ> aPs;
399   if (!theCurve.ValuesInKnots(aPs))
400   {
401     return -1;
402   }
403
404   Handle(TColgp_HArray1OfPnt) aPs2 = new TColgp_HArray1OfPnt(1, aPs.size());
405   {
406     std::list<gp_XYZ>::const_iterator aLastPIt = aPs.end();
407     std::list<gp_XYZ>::const_iterator aPIt = aPs.begin();
408     for (int aPN = 1; aPIt != aLastPIt; ++aPN, ++aPIt)
409     {
410       aPs2->SetValue(aPN, *aPIt);
411     }
412   }
413   Handle(Geom_BSplineCurve) aBSpline2;
414   const bool isClosed = theCurve.IsClosed();
415 #ifndef LIGHT_MODE
416   if (!CurveCreator_Utils::constructBSpline(aPs2, isClosed, aBSpline2))
417 #endif
418   {
419     return -1;
420   }
421
422   // Calculate the piece deflections.
423   std::deque<double> aSqDefls;
424   double aMaxSqDefl = 0;
425   std::list<TopoDS_Edge>& aEdges = theCurve.Edges();
426   std::list<TopoDS_Edge>::const_iterator aLastEIt = aEdges.end();
427   {
428     std::list<TopoDS_Edge>::const_iterator aEIt = aEdges.begin();
429     for (int aPrevKCount = 0; aEIt != aLastEIt; ++aEIt)
430     {
431       TopLoc_Location aLoc;
432       double aParams[2];
433       Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
434         BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
435       const int aKCount = aBSpline->NbKnots();
436       for (int aKN = 1; aKN < aKCount; ++aKN)
437       {
438         const double aParam =
439           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5;
440         const double aParam2 = (aBSpline2->Knot(aPrevKCount + aKN) +
441           aBSpline2->Knot(aPrevKCount + aKN + 1)) * 0.5;
442         const double aSqDefl = Abs(aBSpline->Value(aParam).
443           SquareDistance(aBSpline2->Value(aParam2)));
444         aSqDefls.push_back(aSqDefl);
445         if (aMaxSqDefl < aSqDefl)
446         {
447           aMaxSqDefl = aSqDefl;
448         }
449       }
450       aPrevKCount += aKCount - 1;
451     }
452   }
453
454   // Check whether the reducing is necessary.
455   const double aMaxDefl = Sqrt(aMaxSqDefl);
456   if (aMaxDefl <= theDeflection)
457   {
458     return aMaxDefl;
459   }
460
461   // Reduce the deflections.
462   const double aThresSqDefl =
463     Max(aMaxSqDefl * 0.25, theDeflection * theDeflection);
464   std::list<TopoDS_Edge>::iterator aEIt = aEdges.begin();
465   std::deque<double>::const_iterator aSqDIt = aSqDefls.begin();
466   thePieceCount = 0;
467   for (; aEIt != aLastEIt; ++aEIt)
468   {
469     TopLoc_Location aLoc;
470     double aParams[2];
471     Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
472       BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
473     Handle(Geom_BSplineCurve) aBSpline2 =
474       Handle(Geom_BSplineCurve)::DownCast(aBSpline->Copy());
475     const int aKCount = aBSpline->NbKnots();
476     for (int aKN = 1; aKN < aKCount; ++aSqDIt, ++aKN)
477     {
478       if (*aSqDIt > aThresSqDefl)
479       {
480         aBSpline2->InsertKnot(
481           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5);
482       }
483     }
484     TopoDS_Edge aEdge;
485     BRep_Builder().MakeEdge(aEdge, aBSpline2, Precision::Confusion());
486     BRep_Builder().Add(aEdge, TopExp::FirstVertex(*aEIt));
487     BRep_Builder().Add(aEdge, TopExp::LastVertex(*aEIt));
488     thePieceCount += aBSpline2->NbKnots() - 1;
489     *aEIt = aEdge;
490   }
491   return aMaxDefl;
492 }
493
494 bool HYDROData_PolylineOperator::Extract( const Handle(HYDROData_Document)& theDocument,
495                                           const Handle(HYDROData_Object)& theObject )
496 {
497   if( theObject.IsNull() || theDocument.IsNull() )
498     return false;
499
500   QList<TopoDS_Shape> aBoundShapes;
501   QStringList aBoundNames;
502
503   theObject->GetBoundaries( aBoundShapes, aBoundNames );
504
505   for( int i=0, n=aBoundShapes.size(); i<n; i++ )
506   {
507     TopoDS_Shape aShape = aBoundShapes[i];
508     if( aShape.IsNull() )
509       continue;
510
511     QString aBoundName = i<aBoundNames.size() ? aBoundNames[i] : "";
512
513     Handle( HYDROData_PolylineXY ) aPolyline = 
514       Handle( HYDROData_PolylineXY )::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
515     
516     if( aPolyline.IsNull() )
517       return false;
518
519     aPolyline->SetShape( aShape );
520
521     int anIndex = 0;
522     QString aName = aBoundName;
523     while( !theDocument->FindObjectByName( aName ).IsNull() )
524     {
525       anIndex++;
526       aName = aBoundName + "_" + QString::number( anIndex );
527     }
528     aPolyline->SetName( aName );
529   }
530
531   return true;
532 }