Salome HOME
947de75126b262b8c489d02e56ca53c365e30980
[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   Handle( HYDROData_PolylineXY ) aNewPolyline =
136     Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
137   int ins =0;
138
139   HYDROData_SequenceOfObjects::Iterator aPIt(thePolylines);
140
141   for (int ip=1; aPIt.More(); aPIt.Next(), ip++)
142   {
143     Handle(HYDROData_PolylineXY) aPolyline =
144       Handle(HYDROData_PolylineXY)::DownCast(aPIt.Value());
145     NCollection_Sequence<TCollection_AsciiString>           aSectNames;
146     NCollection_Sequence<HYDROData_PolylineXY::SectionType> aSectTypes;
147     NCollection_Sequence<bool>                              aSectClosures;
148     aPolyline->GetSections( aSectNames, aSectTypes, aSectClosures );
149
150     for ( int i = 1, n = aSectNames.Size(); i <= n; ++i )
151     {
152       const TCollection_AsciiString& aSectName = aSectNames.Value( i ) + "_" + ip;
153       const HYDROData_PolylineXY::SectionType& aSectType = aSectTypes.Value( i );
154       bool aSectClosure = aSectClosures.Value( i );
155       aNewPolyline->AddSection(aSectName, aSectType, aSectClosure);
156       HYDROData_PolylineXY::PointsList aPointsList = aPolyline->GetPoints(i-1, false);
157       aNewPolyline->SetPoints(ins++, aPointsList);
158     }
159   }
160   QString aName = theName;
161   if( aName.isEmpty() )
162     aName = "merged";
163   aNewPolyline->SetName(aName);
164   return true;
165 }
166
167 bool HYDROData_PolylineOperator::split( const Handle( HYDROData_Document )& theDoc,
168                                         const Handle( HYDROData_PolylineXY )& thePolyline,
169                                         const HYDROData_SequenceOfObjects& theTools,
170                                         double theTolerance,
171                                         int theIgnoreIndex,
172                                         bool& theIsIntersected) const
173 {
174   theIsIntersected = false;
175
176   if (thePolyline.IsNull())
177   {
178     return false;
179   }
180
181   std::vector<TopoDS_Wire> aCurves;
182   GetWires(thePolyline, aCurves);
183   std::vector<TopoDS_Wire> aToolCurves;
184   for( int i=theTools.Lower(), n=theTools.Upper(); i<=n; i++ )
185     if( i!=theIgnoreIndex )
186     {
187       Handle( HYDROData_PolylineXY ) aToolPolyline = 
188         Handle( HYDROData_PolylineXY )::DownCast( theTools.Value( i ) );
189       if (!aToolPolyline.IsNull())
190       {
191         std::vector<TopoDS_Wire> aTCurves;
192         GetWires(aToolPolyline, aTCurves);
193         append( aToolCurves, aTCurves);
194       }
195     }
196
197   if (aToolCurves.empty())
198   {
199     return false;
200   }
201
202   const int aPSCount = aCurves.size();
203   const int aTSCount = aToolCurves.size();
204   std::vector<TopoDS_Shape> aResult;
205   for (int aPSI = 0; aPSI < aPSCount; ++aPSI)
206   {
207     HYDROData_TopoCurve aCurve;
208     DEBTRACE("Initialize curve " << aPSI);
209     if (!aCurve.Initialize(aCurves[aPSI]))
210     {
211       continue;
212     }
213
214     std::deque<std::list<double> > aParams;
215     for (int aTSI = 0; aTSI < aTSCount; ++aTSI)
216     {
217       aCurve.Intersect(aToolCurves[aTSI], aParams);
218     }
219
220     std::deque<HYDROData_TopoCurve> aSplitCurves;
221     theIsIntersected |= aCurve.Cut(aParams, aSplitCurves);
222     std::deque<HYDROData_TopoCurve>::const_iterator aCIt =
223       aSplitCurves.begin();
224     std::deque<HYDROData_TopoCurve>::const_iterator aLastCIt =
225       aSplitCurves.end();
226     for (int iw=0; aCIt != aLastCIt; ++aCIt, iw++)
227     {
228       std::stringstream brepName;
229       brepName << "theSplitWire_";
230       brepName << iw;
231       brepName << ".brep";
232       BRepTools::Write(aCIt->Wire() , brepName.str().c_str() );
233       aResult.push_back(aCIt->Wire());
234     }
235   }
236
237   CreatePolylines( theDoc, thePolyline->GetName(), aResult, true, thePolyline->GetWireColor() );
238   //CreatePolylinesSplit( theDoc, thePolyline, aResult, true );
239   return true;
240 }
241
242 void HYDROData_PolylineOperator::GetWires(
243   const Handle( HYDROData_PolylineXY )& thePolyline,
244   std::vector<TopoDS_Wire>& theWires)
245 {
246   TopoDS_Shape aShape = thePolyline->GetShape();
247   if( aShape.ShapeType()==TopAbs_WIRE )
248   {
249     theWires.push_back( TopoDS::Wire( aShape ) );
250   }
251   else
252   {
253     TopExp_Explorer anExp( aShape, TopAbs_WIRE );
254     for( ; anExp.More(); anExp.Next() )
255     {
256       theWires.push_back( TopoDS::Wire( anExp.Current() ) );
257     }
258   }
259 }
260
261 void HYDROData_PolylineOperator::Split(
262   const TopoDS_Wire& theWire,
263   const gp_Pnt2d& thePoint,
264   double theTolerance,
265   std::vector<TopoDS_Shape>& theWires)
266 {
267   HYDROData_TopoCurve aCurve;
268   if (!aCurve.Initialize(theWire))
269   {
270     theWires.push_back(theWire);
271     return;
272   }
273
274   const gp_XYZ aP(thePoint.X(), thePoint.Y(), 0);
275   std::list<TopoDS_Edge>::const_iterator aEPos;
276   double aParam;
277   aCurve.Project(aP, aEPos, aParam);
278   HYDROData_TopoCurve aCurve1, aCurve2;
279   aCurve.Cut(aEPos, aParam, aCurve1, aCurve2);
280   theWires.push_back(aCurve1.Wire());
281   if (!aCurve2.IsEmpty())
282   {
283     theWires.push_back(aCurve2.Wire());
284   }
285 }
286
287 //bool HYDROData_PolylineOperator::CreatePolylinesSplit(const Handle( HYDROData_Document )& theDoc,
288 //                                                      const Handle( HYDROData_PolylineXY )& thePolyline,
289 //                                                      const std::vector<TopoDS_Shape>& theShapes, bool isUseIndices)
290 //{
291 //
292 //  if (theDoc.IsNull())
293 //    return false;
294 //
295 //  int nbSections = thePolyline->NbSections();
296 //  const QString& theNamePrefix = thePolyline->GetName();
297 //  const QColor& theColor = thePolyline->GetWireColor();
298 //
299 //  int n = theShapes.size();
300 //  DEBTRACE("theShapes.size() "<< n);
301 //  int anIndex = 1;
302 //  for (int i = 0; i < n; i++)
303 //    {
304 //      Handle( HYDROData_PolylineXY ) aPolyline =
305 //      Handle( HYDROData_PolylineXY )::DownCast(theDoc->CreateObject(KIND_POLYLINEXY));
306 //      if (aPolyline.IsNull())
307 //        return false;
308 //
309 //      for (int isec = 0; isec < nbSections; isec++)
310 //        {
311 //          gp_XY p = gp_XY(0, 0);
312 //          //double d = thePolyline->GetMinDistance(isec, p);
313 //        }
314 //
315 //      if (isUseIndices)
316 //        {
317 //          QString aNewName = theNamePrefix + "_" + QString::number(anIndex);
318 //          while (!theDoc->FindObjectByName(aNewName).IsNull())  // the object with such a name is not found
319 //            {
320 //              anIndex++;
321 //              aNewName = theNamePrefix + "_" + QString::number(anIndex);
322 //            }
323 //          aPolyline->SetName(aNewName);
324 //        }
325 //      else
326 //        {
327 //          aPolyline->SetName(theNamePrefix);
328 //        }
329 //
330 //      if (theColor.isValid())
331 //        aPolyline->SetWireColor(theColor);
332 //    }
333 //  return true;
334 //
335 //}
336
337 bool HYDROData_PolylineOperator::CreatePolylines( const Handle( HYDROData_Document )& theDoc,
338                                                   const QString& theNamePrefix,
339                                                   const std::vector<TopoDS_Shape>& theShapes,
340                                                   bool isUseIndices,
341                                                   const QColor& theColor )
342 {
343   if( theDoc.IsNull() )
344     return false;
345
346   int n = theShapes.size();
347   DEBTRACE("theShapes.size() "<< n);
348   int anIndex = 1;
349   for( int i=0; i<n; i++ )
350   {
351     Handle( HYDROData_PolylineXY ) aPolyline = 
352       Handle( HYDROData_PolylineXY )::DownCast( theDoc->CreateObject( KIND_POLYLINEXY ) );
353     if( aPolyline.IsNull() )
354       return false;
355
356     aPolyline->ImportShape(theShapes[i], false, false);
357     //aPolyline->SetShape( theShapes[i] );
358
359
360     if( isUseIndices )
361     {
362       QString aNewName = theNamePrefix + "_" + QString::number( anIndex );
363       while( !theDoc->FindObjectByName( aNewName ).IsNull() )  // the object with such a name is not found
364       {
365         anIndex++;
366         aNewName = theNamePrefix + "_" + QString::number( anIndex );
367       }
368       aPolyline->SetName( aNewName );
369     }
370     else
371     {
372       aPolyline->SetName( theNamePrefix );
373     }
374
375     if( theColor.isValid() )
376       aPolyline->SetWireColor( theColor );
377   }
378   return true;
379 }
380
381 double HYDROData_PolylineOperator::ReduceDeflection(
382   const double theDeflection,
383   HYDROData_TopoCurve& theCurve,
384   int& thePieceCount)
385 {
386   // Construct the approximating B-spline.
387   std::list<gp_XYZ> aPs;
388   if (!theCurve.ValuesInKnots(aPs))
389   {
390     return -1;
391   }
392
393   Handle(TColgp_HArray1OfPnt) aPs2 = new TColgp_HArray1OfPnt(1, aPs.size());
394   {
395     std::list<gp_XYZ>::const_iterator aLastPIt = aPs.end();
396     std::list<gp_XYZ>::const_iterator aPIt = aPs.begin();
397     for (int aPN = 1; aPIt != aLastPIt; ++aPN, ++aPIt)
398     {
399       aPs2->SetValue(aPN, *aPIt);
400     }
401   }
402   Handle(Geom_BSplineCurve) aBSpline2;
403   const bool isClosed = theCurve.IsClosed();
404 #ifndef LIGHT_MODE
405   if (!CurveCreator_Utils::constructBSpline(aPs2, isClosed, aBSpline2))
406 #endif
407   {
408     return -1;
409   }
410
411   // Calculate the piece deflections.
412   std::deque<double> aSqDefls;
413   double aMaxSqDefl = 0;
414   std::list<TopoDS_Edge>& aEdges = theCurve.Edges();
415   std::list<TopoDS_Edge>::const_iterator aLastEIt = aEdges.end();
416   {
417     std::list<TopoDS_Edge>::const_iterator aEIt = aEdges.begin();
418     for (int aPrevKCount = 0; aEIt != aLastEIt; ++aEIt)
419     {
420       TopLoc_Location aLoc;
421       double aParams[2];
422       Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
423         BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
424       const int aKCount = aBSpline->NbKnots();
425       for (int aKN = 1; aKN < aKCount; ++aKN)
426       {
427         const double aParam =
428           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5;
429         const double aParam2 = (aBSpline2->Knot(aPrevKCount + aKN) +
430           aBSpline2->Knot(aPrevKCount + aKN + 1)) * 0.5;
431         const double aSqDefl = Abs(aBSpline->Value(aParam).
432           SquareDistance(aBSpline2->Value(aParam2)));
433         aSqDefls.push_back(aSqDefl);
434         if (aMaxSqDefl < aSqDefl)
435         {
436           aMaxSqDefl = aSqDefl;
437         }
438       }
439       aPrevKCount += aKCount - 1;
440     }
441   }
442
443   // Check whether the reducing is necessary.
444   const double aMaxDefl = Sqrt(aMaxSqDefl);
445   if (aMaxDefl <= theDeflection)
446   {
447     return aMaxDefl;
448   }
449
450   // Reduce the deflections.
451   const double aThresSqDefl =
452     Max(aMaxSqDefl * 0.25, theDeflection * theDeflection);
453   std::list<TopoDS_Edge>::iterator aEIt = aEdges.begin();
454   std::deque<double>::const_iterator aSqDIt = aSqDefls.begin();
455   thePieceCount = 0;
456   for (; aEIt != aLastEIt; ++aEIt)
457   {
458     TopLoc_Location aLoc;
459     double aParams[2];
460     Handle(Geom_BSplineCurve) aBSpline = Handle(Geom_BSplineCurve)::DownCast(
461       BRep_Tool::Curve(*aEIt, aLoc, aParams[0], aParams[1]));
462     Handle(Geom_BSplineCurve) aBSpline2 =
463       Handle(Geom_BSplineCurve)::DownCast(aBSpline->Copy());
464     const int aKCount = aBSpline->NbKnots();
465     for (int aKN = 1; aKN < aKCount; ++aSqDIt, ++aKN)
466     {
467       if (*aSqDIt > aThresSqDefl)
468       {
469         aBSpline2->InsertKnot(
470           (aBSpline->Knot(aKN) + aBSpline->Knot(aKN + 1)) * 0.5);
471       }
472     }
473     TopoDS_Edge aEdge;
474     BRep_Builder().MakeEdge(aEdge, aBSpline2, Precision::Confusion());
475     BRep_Builder().Add(aEdge, TopExp::FirstVertex(*aEIt));
476     BRep_Builder().Add(aEdge, TopExp::LastVertex(*aEIt));
477     thePieceCount += aBSpline2->NbKnots() - 1;
478     *aEIt = aEdge;
479   }
480   return aMaxDefl;
481 }
482
483 bool HYDROData_PolylineOperator::Extract( const Handle(HYDROData_Document)& theDocument,
484                                           const Handle(HYDROData_Object)& theObject )
485 {
486   if( theObject.IsNull() || theDocument.IsNull() )
487     return false;
488
489   QList<TopoDS_Shape> aBoundShapes;
490   QStringList aBoundNames;
491
492   theObject->GetBoundaries( aBoundShapes, aBoundNames );
493
494   for( int i=0, n=aBoundShapes.size(); i<n; i++ )
495   {
496     TopoDS_Shape aShape = aBoundShapes[i];
497     if( aShape.IsNull() )
498       continue;
499
500     QString aBoundName = i<aBoundNames.size() ? aBoundNames[i] : "";
501
502     Handle( HYDROData_PolylineXY ) aPolyline = 
503       Handle( HYDROData_PolylineXY )::DownCast( theDocument->CreateObject( KIND_POLYLINEXY ) );
504     
505     if( aPolyline.IsNull() )
506       return false;
507
508     aPolyline->SetShape( aShape );
509
510     int anIndex = 0;
511     QString aName = aBoundName;
512     while( !theDocument->FindObjectByName( aName ).IsNull() )
513     {
514       anIndex++;
515       aName = aBoundName + "_" + QString::number( anIndex );
516     }
517     aPolyline->SetName( aName );
518   }
519
520   return true;
521 }