Salome HOME
91301c61b7517359ec8d9cb3b24012f76d7a4d1c
[modules/geom.git] / src / GEOMImpl / GEOMImpl_HealingDriver.cxx
1 // Copyright (C) 2007-2023  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 #include <GEOMImpl_HealingDriver.hxx>
24 #include <GEOMImpl_Types.hxx>
25 #include <GEOMImpl_IHealing.hxx>
26 #include <GEOM_Function.hxx>
27
28 #include <GEOMImpl_GlueDriver.hxx>
29 #include <GEOMImpl_ShapeDriver.hxx>
30
31 #include <GEOMUtils.hxx>
32 #include <GEOMAlgo_RemoverWebs.hxx>
33
34 #include <ShHealOper_ShapeProcess.hxx>
35 #include <ShHealOper_RemoveFace.hxx>
36 #include <ShHealOper_CloseContour.hxx>
37 #include <ShHealOper_RemoveInternalWires.hxx>
38 #include <ShHealOper_FillHoles.hxx>
39 #include <ShHealOper_Sewing.hxx>
40 #include <ShHealOper_EdgeDivide.hxx>
41 #include <ShHealOper_ChangeOrientation.hxx>
42
43 #include <TNaming_CopyShape.hxx>
44
45 #include <BRep_Builder.hxx>
46 #include <BRepAdaptor_Curve.hxx>
47 #include <BRepBuilderAPI_Copy.hxx>
48 #include <BRepTools_WireExplorer.hxx>
49
50 #include <TopExp.hxx>
51 #include <TopExp_Explorer.hxx>
52 #include <TopoDS.hxx>
53 #include <TopoDS_Iterator.hxx>
54 #include <TopTools_IndexedMapOfShape.hxx>
55 #include <TopTools_ListOfShape.hxx>
56 #include <TopTools_ListIteratorOfListOfShape.hxx>
57
58 #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
59
60 #include <Precision.hxx>
61
62 #include <StdFail_NotDone.hxx>
63 #include <Standard_NullObject.hxx>
64
65 //=======================================================================
66 //function :  raiseNotDoneExeption
67 //purpose  :  global function: forms error message and raises exception
68 //=======================================================================
69 void raiseNotDoneExeption( const int theErrorStatus )
70 {
71   switch ( theErrorStatus )
72   {
73   case ShHealOper_NotError:           StdFail_NotDone::Raise( "ShHealOper_NotError_msg" ); break;
74   case ShHealOper_InvalidParameters:  StdFail_NotDone::Raise( "ShHealOper_InvalidParameters_msg" ); break;
75   case ShHealOper_ErrorExecution:
76   default:                            StdFail_NotDone::Raise( "ShHealOper_ErrorExecution_msg" ); break;
77   }
78 }
79
80 //=======================================================================
81 //function : GetID
82 //purpose  :
83 //=======================================================================
84 const Standard_GUID& GEOMImpl_HealingDriver::GetID()
85 {
86   static Standard_GUID aHealingDriver("FF1BBB61-5D14-4df2-980B-3A668264EA16");
87   return aHealingDriver;
88 }
89
90 //=======================================================================
91 //function : GEOMImpl_HealingDriver
92 //purpose  :
93 //=======================================================================
94 GEOMImpl_HealingDriver::GEOMImpl_HealingDriver()
95 {
96 }
97
98 //=======================================================================
99 //function : Execute
100 //purpose  :
101 //=======================================================================
102 Standard_Integer GEOMImpl_HealingDriver::Execute(Handle(TFunction_Logbook)& log) const
103 {
104   if (Label().IsNull()) return 0;
105   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
106
107   if (aFunction.IsNull()) return 0;
108
109   GEOMImpl_IHealing HI (aFunction);
110   Standard_Integer aType = aFunction->GetType();
111   Handle(GEOM_Function) anOriginalFunction = HI.GetOriginal();
112   if (anOriginalFunction.IsNull()) return 0;
113   TopoDS_Shape aShape, anOriginalShape = anOriginalFunction->GetValue();
114   if (anOriginalShape.IsNull()) return 0;
115
116   switch (aType)
117   {
118   case SHAPE_PROCESS:
119     ShapeProcess(&HI, anOriginalShape, aShape);
120     break;
121   case SUPPRESS_FACES:
122     SuppressFaces(&HI, anOriginalShape, aShape);
123     break;
124   case CLOSE_CONTOUR:
125     CloseContour(&HI, anOriginalShape, aShape);
126     break;
127   case REMOVE_INT_WIRES:
128     RemoveIntWires(&HI, anOriginalShape, aShape);
129     break;
130   case FILL_HOLES:
131     RemoveHoles(&HI, anOriginalShape, aShape);
132     break;
133   case SEWING:
134     Sew(&HI, anOriginalShape, aShape, false);
135     break;
136   case SEWING_NON_MANIFOLD:
137     Sew(&HI, anOriginalShape, aShape, true);
138     break;
139   case REMOVE_INTERNAL_FACES:
140     RemoveInternalFaces(&HI, anOriginalShape, aShape);
141     break;
142   case DIVIDE_EDGE:
143   case DIVIDE_EDGE_BY_POINT:
144     AddPointOnEdge(&HI, anOriginalShape, aShape);
145     break;
146   case CHANGE_ORIENTATION:
147     ChangeOrientation(&HI, anOriginalShape, aShape);
148     break;
149   case LIMIT_TOLERANCE:
150     LimitTolerance(&HI, anOriginalShape, aShape);
151     break;
152   case FUSE_COLLINEAR_EDGES:
153     {
154       Handle(TColStd_HSequenceOfTransient) aVerts = HI.GetShapes();
155       FuseCollinearEdges(anOriginalShape, aVerts, aShape);
156     }
157     break;
158   default:
159     return 0;
160   }
161
162   if (aShape.IsNull())
163     raiseNotDoneExeption( ShHealOper_ErrorExecution );
164
165   aFunction->SetValue(aShape);
166
167   log->SetTouched(Label());
168   return 1;
169 }
170
171 //=======================================================================
172 //function :  ShapeProcess
173 //purpose  :
174 //=======================================================================
175 Standard_Boolean GEOMImpl_HealingDriver::ShapeProcess (GEOMImpl_IHealing* theHI,
176                                                        const TopoDS_Shape& theOriginalShape,
177                                                        TopoDS_Shape& theOutShape) const
178 {
179   Handle(TColStd_HArray1OfExtendedString) anOperators = theHI->GetOperators();
180   Handle(TColStd_HArray1OfExtendedString) aParams = theHI->GetParameters();
181   Handle(TColStd_HArray1OfExtendedString) aValues = theHI->GetValues();
182
183   if (anOperators.IsNull() || anOperators->Length() <= 0)
184     return Standard_False;
185
186   Standard_Integer nbParams = 0, nbValues = 0;
187   if (!aParams.IsNull()) {
188     nbParams = aParams->Length();
189   }
190   if (!aValues.IsNull()) {
191     nbValues = aValues->Length();
192   }
193   if (nbParams != nbValues)
194     return Standard_False;
195
196   ShHealOper_ShapeProcess aHealer;
197   TColStd_SequenceOfAsciiString anOperatorsAS, aParamsAS, aValuesAS;
198   int i;
199   for (i = 1; i <= anOperators->Length(); i++)
200     anOperatorsAS.Append(TCollection_AsciiString(anOperators->Value(i)));
201
202   aHealer.SetOperators(anOperatorsAS);
203
204   for (i = 1; i <= nbParams; i++) {
205     aHealer.SetParameter(TCollection_AsciiString(aParams->Value(i)),
206                          TCollection_AsciiString(aValues->Value(i)));
207   }
208
209   aHealer.Perform(theOriginalShape, theOutShape);
210
211   if (!aHealer.isDone())
212     raiseNotDoneExeption( ShHealOper_NotError );
213
214   SaveStatistics( aHealer );
215
216   return Standard_True;
217 }
218
219 //=======================================================================
220 //function :  SupressFaces
221 //purpose  :
222 //=======================================================================
223 void GEOMImpl_HealingDriver::SuppressFacesRec (const TopTools_SequenceOfShape& theShapesFaces,
224                                                const TopoDS_Shape&             theOriginalShape,
225                                                TopoDS_Shape&                   theOutShape) const
226 {
227   if ((theOriginalShape.ShapeType() != TopAbs_COMPOUND &&
228        theOriginalShape.ShapeType() != TopAbs_COMPSOLID))
229   {
230     ShHealOper_RemoveFace aHealer (theOriginalShape);
231     Standard_Boolean aResult = aHealer.Perform(theShapesFaces);
232
233     if (aResult)
234       theOutShape = aHealer.GetResultShape();
235     else
236       raiseNotDoneExeption(aHealer.GetErrorStatus());
237   }
238   else
239   {
240     BRep_Builder BB;
241     TopoDS_Compound CC;
242     BB.MakeCompound(CC);
243
244     TopTools_MapOfShape mapShape;
245     TopoDS_Iterator It (theOriginalShape, Standard_True, Standard_True);
246
247     for (; It.More(); It.Next()) {
248       TopoDS_Shape aShape_i = It.Value();
249       if (mapShape.Add(aShape_i)) {
250         // check, if current shape contains at least one of faces to be removed
251         bool isFound = false;
252         TopTools_IndexedMapOfShape aShapes_i;
253         TopExp::MapShapes(aShape_i, aShapes_i);
254         for (int i = 1; i <= theShapesFaces.Length() && !isFound; i++) {
255           const TopoDS_Shape& aFace_i = theShapesFaces.Value(i);
256           if (aShapes_i.Contains(aFace_i)) isFound = true;
257         }
258         if (isFound) {
259           TopoDS_Shape anOutSh_i;
260           SuppressFacesRec(theShapesFaces, aShape_i, anOutSh_i);
261           if ( !anOutSh_i.IsNull() )
262             BB.Add(CC, anOutSh_i);
263         }
264         else {
265           // nothing to do
266           BB.Add(CC, aShape_i);
267         }
268       }
269     }
270     theOutShape = CC;
271   }
272 }
273
274 Standard_Boolean GEOMImpl_HealingDriver::SuppressFaces (GEOMImpl_IHealing* theHI,
275                                                         const TopoDS_Shape& theOriginalShape,
276                                                         TopoDS_Shape& theOutShape) const
277 {
278   Handle(TColStd_HArray1OfInteger) aFaces = theHI->GetFaces();
279
280   Standard_Boolean aResult = Standard_False;
281
282   if (aFaces.IsNull()) {
283     ShHealOper_RemoveFace aHealer (theOriginalShape);
284     aResult = aHealer.Perform();
285
286     if (aResult)
287       theOutShape = aHealer.GetResultShape();
288     else
289       raiseNotDoneExeption(aHealer.GetErrorStatus());
290   }
291   else {
292     TopTools_SequenceOfShape aShapesFaces;
293     TopTools_IndexedMapOfShape aShapes;
294     TopExp::MapShapes(theOriginalShape, aShapes);
295     for (int i = 1; i <= aFaces->Length(); i++) {
296       int indexOfFace = aFaces->Value(i);
297       TopoDS_Shape aFace = aShapes.FindKey(indexOfFace);
298       aShapesFaces.Append(aFace);
299     }
300     SuppressFacesRec(aShapesFaces, theOriginalShape, theOutShape);
301     if ((theOriginalShape.ShapeType() == TopAbs_COMPOUND ||
302          theOriginalShape.ShapeType() == TopAbs_COMPSOLID)) {
303       TopoDS_Shape aSh = theOutShape;
304       theOutShape = GEOMImpl_GlueDriver::GlueFaces(aSh, Precision::Confusion(), Standard_True);
305     }
306   }
307   // count removed faces
308   TopTools_IndexedMapOfShape faces;
309   TopExp::MapShapes(theOriginalShape, TopAbs_FACE, faces);
310   int nbBefore = faces.Extent();
311   faces.Clear();
312   TopExp::MapShapes(theOutShape, TopAbs_FACE, faces);
313   int nbAfter = faces.Extent();
314
315   if ( nbAfter < nbBefore )
316   {
317     ShHealOper_Tool tool;
318     ShHealOper_ModifStats& stats = tool.GetStatistics();
319     stats.AddModif( "Face removed", nbBefore - nbAfter );
320     SaveStatistics( tool );
321   }
322
323   return Standard_True;
324 }
325
326 //=======================================================================
327 //function :  CloseContour
328 //purpose  :
329 //=======================================================================
330 Standard_Boolean GEOMImpl_HealingDriver::CloseContour (GEOMImpl_IHealing* theHI,
331                                                        const TopoDS_Shape& theOriginalShape,
332                                                        TopoDS_Shape& theOutShape) const
333 {
334   Standard_Boolean isByVertex = theHI->GetIsCommonVertex();
335   Handle(TColStd_HArray1OfInteger) aWires = theHI->GetWires();
336
337   ShHealOper_CloseContour aHealer (theOriginalShape);
338
339   Standard_Boolean aResult = Standard_False;
340   if ( aWires.IsNull() ) {
341     if ( theOriginalShape.ShapeType() == TopAbs_WIRE )
342       aResult = aHealer.Perform(TopoDS::Wire(theOriginalShape), isByVertex, !isByVertex);
343   }
344   else {
345     TopTools_SequenceOfShape aShapesWires;
346     TopTools_IndexedMapOfShape aShapes;
347     TopExp::MapShapes(theOriginalShape, aShapes);
348     for (int i = 1; i <= aWires->Length(); i++) {
349       int indexOfWire = aWires->Value(i);
350       TopoDS_Shape aWire = aShapes.FindKey(indexOfWire);
351       aShapesWires.Append(aWire);
352     }
353
354     aResult = aHealer.Perform( aShapesWires, isByVertex, !isByVertex );
355   }
356
357   if (aResult)
358     theOutShape = aHealer.GetResultShape();
359   else
360     raiseNotDoneExeption( aHealer.GetErrorStatus() );
361
362   SaveStatistics( aHealer );
363
364   return aResult;
365 }
366
367 //=======================================================================
368 //function :  RemoveIntWires
369 //purpose  :
370 //=======================================================================
371 Standard_Boolean GEOMImpl_HealingDriver::RemoveIntWires (GEOMImpl_IHealing* theHI,
372                                                          const TopoDS_Shape& theOriginalShape,
373                                                          TopoDS_Shape& theOutShape) const
374 {
375   Handle(TColStd_HArray1OfInteger) aWires = theHI->GetWires();
376
377   ShHealOper_RemoveInternalWires aHealer(theOriginalShape);
378
379   Standard_Boolean aResult = Standard_False;
380   if (aWires.IsNull()) { // remove all faces
381     aResult = aHealer.Remove();
382   } else {
383     TopTools_SequenceOfShape aShapesWires;
384     TopTools_IndexedMapOfShape aShapes;
385     TopExp::MapShapes(theOriginalShape, aShapes);
386     for (int i = 1; i <= aWires->Length(); i++) {
387       int indexOfWire = aWires->Value(i);
388       TopoDS_Shape aWire = aShapes.FindKey(indexOfWire);
389       aShapesWires.Append(aWire);
390     }
391
392     aResult = aHealer.Remove(aShapesWires);
393   }
394
395   if (aResult)
396     theOutShape = aHealer.GetResultShape();
397   else
398     raiseNotDoneExeption( aHealer.GetErrorStatus() );
399
400   SaveStatistics( aHealer );
401
402   return aResult;
403 }
404
405 //=======================================================================
406 //function :  RemoveHoles
407 //purpose  :
408 //=======================================================================
409 Standard_Boolean GEOMImpl_HealingDriver::RemoveHoles (GEOMImpl_IHealing* theHI,
410                                                       const TopoDS_Shape& theOriginalShape,
411                                                       TopoDS_Shape& theOutShape) const
412 {
413   Handle(TColStd_HArray1OfInteger) aWires = theHI->GetWires();
414
415   ShHealOper_FillHoles aHealer (theOriginalShape);
416
417   Standard_Boolean aResult = Standard_False;
418   if (aWires.IsNull()) { // remove all faces
419     aResult = aHealer.Fill();
420   } else {
421     TopTools_SequenceOfShape aShapesWires;
422     TopTools_IndexedMapOfShape aShapes;
423     TopExp::MapShapes(theOriginalShape, aShapes);
424     for (int i = 1; i <= aWires->Length(); i++) {
425       int indexOfWire = aWires->Value(i);
426       TopoDS_Shape aWire = aShapes.FindKey(indexOfWire);
427       aShapesWires.Append(aWire);
428     }
429
430     aResult = aHealer.Fill(aShapesWires);
431   }
432
433   if (aResult)
434     theOutShape = aHealer.GetResultShape();
435   else
436     raiseNotDoneExeption( aHealer.GetErrorStatus() );
437
438   SaveStatistics( aHealer );
439
440   return aResult;
441 }
442
443 //=======================================================================
444 //function :  Sew
445 //purpose  :
446 //=======================================================================
447 Standard_Boolean GEOMImpl_HealingDriver::Sew (GEOMImpl_IHealing*  theHI,
448                                               const TopoDS_Shape& theOriginalShape,
449                                               TopoDS_Shape&       theOutShape,
450                                               Standard_Boolean    isAllowNonManifold) const
451 {
452   Standard_Real aTol = theHI->GetTolerance();
453
454   TopoDS_Compound aCompound;
455   BRep_Builder builder;
456   builder.MakeCompound( aCompound );
457
458   builder.Add( aCompound, theOriginalShape );
459   Handle(TColStd_HSequenceOfTransient) otherObjs = theHI->GetShapes();
460   for ( int ind = 1; ind <= otherObjs->Length(); ind++)
461   {
462     Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(otherObjs->Value(ind));
463     builder.Add( aCompound, aRefShape->GetValue() );
464   }
465
466   ShHealOper_Sewing aHealer (aCompound, aTol);
467
468   // Set non-manifold mode.
469   aHealer.SetNonManifoldMode(isAllowNonManifold);
470
471   Standard_Boolean aResult = aHealer.Perform();
472
473   if (aResult)
474     theOutShape = aHealer.GetResultShape();
475   else
476     raiseNotDoneExeption( aHealer.GetErrorStatus() );
477
478   SaveStatistics( aHealer );
479
480   return aResult;
481 }
482
483 //=======================================================================
484 //function : RemoveInternalFaces
485 //purpose  :
486 //=======================================================================
487 Standard_Boolean
488 GEOMImpl_HealingDriver::RemoveInternalFaces (GEOMImpl_IHealing*  theHI,
489                                              const TopoDS_Shape& theOriginalShape,
490                                              TopoDS_Shape&       theOutShape) const
491 {
492   // get all input shapes
493   TopTools_SequenceOfShape shapeSeq;
494   shapeSeq.Append( theOriginalShape );
495   Handle(TColStd_HSequenceOfTransient) otherObjs = theHI->GetShapes();
496   if ( !otherObjs.IsNull() )
497     for ( int ind = 1; ind <= otherObjs->Length(); ind++)
498     {
499       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(otherObjs->Value(ind));
500       TopoDS_Shape aShape = aRefShape->GetValue();
501       if (aShape.IsNull())
502         Standard_NullObject::Raise("Null object given");
503       shapeSeq.Append( aShape );
504     }
505
506   // pass input shapes to the algorithm
507   GEOMAlgo_RemoverWebs aTool;
508   if ( shapeSeq.Length() == 1 )
509   {
510     aTool.SetShape( shapeSeq.First() );
511   }
512   else
513   {
514     TopoDS_Compound solidCompound;
515     BRep_Builder builder;
516     builder.MakeCompound( solidCompound );
517     for ( int ind = 1; ind <= shapeSeq.Length(); ++ind )
518       for ( TopExp_Explorer so( shapeSeq( ind ), TopAbs_SOLID ); so.More(); so.Next() )
519         builder.Add( solidCompound, so.Current() );
520
521     aTool.SetShape( solidCompound );
522   }
523
524   // run the algorithm
525   aTool.Perform();
526
527   if (aTool.ErrorStatus() == 0) { // OK
528     theOutShape = aTool.Result();
529
530     // as GEOMAlgo_RemoverWebs always produces compound, lets simplify it
531     // for the case, if it contains only one sub-shape
532     TopTools_ListOfShape listShapeRes;
533     GEOMUtils::AddSimpleShapes(theOutShape, listShapeRes);
534     if (listShapeRes.Extent() == 1) {
535       theOutShape = listShapeRes.First();
536     }
537   }
538   else if (aTool.ErrorStatus() == 11) // invalid argument (contains non-solids), do nothing
539     theOutShape = theOriginalShape;
540   else // error
541     StdFail_NotDone::Raise("GEOMAlgo_RemoverWebs failed!");
542
543   return Standard_True;
544 }
545
546 //=======================================================================
547 //function :  AddPointOnEdge
548 //purpose  :
549 //=======================================================================
550 Standard_Boolean GEOMImpl_HealingDriver::AddPointOnEdge (GEOMImpl_IHealing*  theHI,
551                                                          const TopoDS_Shape& theOriginalShape,
552                                                          TopoDS_Shape&       theOutShape) const
553 {
554   Standard_Boolean isByParameter = theHI->GetIsByParameter();
555   Standard_Integer       anIndex = theHI->GetIndex();
556   Standard_Real           aValue = theHI->GetDevideEdgeValue();
557
558   TopoDS_Shape pointToProject;
559   {
560     Handle(TColStd_HSequenceOfTransient) funs = theHI->GetShapes();
561     if ( !funs.IsNull() && funs->Length() > 0 ) {
562       TopoDS_Compound vCompound;
563       BRep_Builder builder;
564       builder.MakeCompound( vCompound );
565       pointToProject = vCompound;
566       for ( int ind = 1; ind <= funs->Length(); ind++)
567       {
568         Handle(GEOM_Function) vFun = Handle(GEOM_Function)::DownCast(funs->Value(ind));
569         TopoDS_Shape vertex = vFun->GetValue();
570         if ( vertex.IsNull() )
571           Standard_NullObject::Raise("Null vertex given");
572         builder.Add( vCompound, vertex );
573       }
574     }
575   }
576
577   ShHealOper_EdgeDivide aHealer (theOriginalShape);
578
579   Standard_Boolean aResult = Standard_False;
580   if (anIndex == -1) { // apply algorithm for the whole shape which is EDGE
581     if (theOriginalShape.ShapeType() == TopAbs_EDGE) {
582       if ( pointToProject.IsNull() )
583         aResult = aHealer.Perform(TopoDS::Edge(theOriginalShape), aValue, isByParameter);
584       else
585         aResult = aHealer.Perform(TopoDS::Edge(theOriginalShape), pointToProject);
586     }
587   } else {
588     TopTools_IndexedMapOfShape aShapes;
589     TopExp::MapShapes(theOriginalShape, aShapes);
590     TopoDS_Shape aEdgeShape = aShapes.FindKey(anIndex);
591     if (aEdgeShape.ShapeType() == TopAbs_EDGE) {
592       if ( pointToProject.IsNull() )
593         aResult = aHealer.Perform(TopoDS::Edge(aEdgeShape), aValue, isByParameter);
594       else
595         aResult = aHealer.Perform(TopoDS::Edge(aEdgeShape), pointToProject);
596     }
597   }
598
599   if (aResult)
600     theOutShape = aHealer.GetResultShape();
601   else
602     raiseNotDoneExeption( aHealer.GetErrorStatus() );
603
604   SaveStatistics( aHealer );
605
606   return aResult;
607 }
608
609
610 //=======================================================================
611 //function :  ChangeOrientation
612 //purpose  :
613 //=======================================================================
614 Standard_Boolean GEOMImpl_HealingDriver::ChangeOrientation (GEOMImpl_IHealing* /*theHI*/,
615                                                             const TopoDS_Shape& theOriginalShape,
616                                                             TopoDS_Shape& theOutShape) const
617 {
618   ShHealOper_ChangeOrientation aHealer (theOriginalShape);
619
620   Standard_Boolean aResult = aHealer.Perform();
621
622   if (aResult)
623     theOutShape = aHealer.GetResultShape();
624   else
625     raiseNotDoneExeption( aHealer.GetErrorStatus() );
626
627   SaveStatistics( aHealer );
628
629   return aResult;
630 }
631
632 //=======================================================================
633 //function : LimitTolerance
634 //purpose  :
635 //=======================================================================
636 void GEOMImpl_HealingDriver::LimitTolerance (GEOMImpl_IHealing* theHI,
637                                              const TopoDS_Shape& theOriginalShape,
638                                              TopoDS_Shape& theOutShape) const
639 {
640   Standard_Real aTol = theHI->GetTolerance();
641   TopAbs_ShapeEnum aType = theHI->GetType();
642
643   if (aTol < Precision::Confusion())
644     aTol = Precision::Confusion();
645
646   // 1. Make a copy to prevent the original shape changes.
647   TopoDS_Shape aShapeCopy;
648   {
649     BRepBuilderAPI_Copy aMC (theOriginalShape);
650     if (aMC.IsDone()) {
651       aShapeCopy = aMC.Shape();
652     }
653     else {
654       TColStd_IndexedDataMapOfTransientTransient aMapTShapes;
655       TNaming_CopyShape::CopyTool(theOriginalShape, aMapTShapes, aShapeCopy);
656     }
657   }
658
659   // 2. Limit tolerance.
660   if (!GEOMUtils::FixShapeTolerance(aShapeCopy, aType, aTol))
661     StdFail_NotDone::Raise("Non valid shape result");
662
663   // 3. Set the result
664   theOutShape = aShapeCopy;
665
666   // 4. Collect statistics
667   {
668     ShHealOper_Tool tool;
669     ShHealOper_ModifStats& stats = tool.GetStatistics();
670
671     int nb[3] = { 0,0,0 };
672     TopTools_IndexedMapOfShape aShapes;
673     TopExp::MapShapes( theOutShape, TopAbs_VERTEX, aShapes);
674     for ( int i = 1; i <= aShapes.Extent(); ++i )
675     {
676       const TopoDS_Vertex& v = TopoDS::Vertex( aShapes( i ));
677       double tol = BRep_Tool::Tolerance( v );
678       if      ( tol < aTol ) nb[0]++;
679       else if ( tol > aTol ) nb[2]++;
680       else                   nb[1]++;
681     }
682     if ( nb[0] > 0 )
683       stats.AddModif( "Tolerance of vertex decreased for shape validity", nb[0] );
684     if ( nb[1] > 0 )
685       stats.AddModif( "Tolerance of vertex limited as requested", nb[1] );
686     if ( nb[2] > 0 )
687       stats.AddModif( "Tolerance of vertex increased for shape validity", nb[2] );
688
689     nb[0] = nb[1] = nb[2] = 0;
690     aShapes.Clear();
691     TopExp::MapShapes( theOutShape, TopAbs_EDGE, aShapes);
692     for ( int i = 1; i <= aShapes.Extent(); ++i )
693     {
694       const TopoDS_Edge& e = TopoDS::Edge( aShapes( i ));
695       double tol = BRep_Tool::Tolerance( e );
696       if      ( tol < aTol ) nb[0]++;
697       else if ( tol > aTol ) nb[2]++;
698       else                   nb[1]++;
699     }
700     if ( nb[0] > 0 )
701       stats.AddModif( "Tolerance of edge decreased for shape validity", nb[0] );
702     if ( nb[1] > 0 )
703       stats.AddModif( "Tolerance of edge limited as requested", nb[1] );
704     if ( nb[2] > 0 )
705       stats.AddModif( "Tolerance of edge increased for shape validity", nb[2] );
706
707     nb[0] = nb[1] = nb[2] = 0;
708     aShapes.Clear();
709     TopExp::MapShapes( theOutShape, TopAbs_FACE, aShapes);
710     for ( int i = 1; i <= aShapes.Extent(); ++i )
711     {
712       const TopoDS_Face& f = TopoDS::Face( aShapes( i ));
713       double tol = BRep_Tool::Tolerance( f );
714       if      ( tol < aTol ) nb[0]++;
715       else if ( tol > aTol ) nb[2]++;
716       else                   nb[1]++;
717     }
718     if ( nb[0] > 0 )
719       stats.AddModif( "Tolerance of face decreased for shape validity", nb[0] );
720     if ( nb[1] > 0 )
721       stats.AddModif( "Tolerance of face limited as requested", nb[1] );
722     if ( nb[2] > 0 )
723       stats.AddModif( "Tolerance of face increased for shape validity", nb[2] );
724
725     SaveStatistics( tool );
726   }
727 }
728
729 //=======================================================================
730 //function : FuseCollinearEdges
731 //purpose  :
732 //=======================================================================
733 void GEOMImpl_HealingDriver::FuseCollinearEdges (const TopoDS_Shape& theOriginalShape,
734                                                  const Handle(TColStd_HSequenceOfTransient)& aVerts,
735                                                  TopoDS_Shape& theOutShape)
736 {
737   if (theOriginalShape.ShapeType() != TopAbs_WIRE)
738     Standard_TypeMismatch::Raise("Not a wire is given");
739
740   // Tolerances
741   Standard_Real AngTol = Precision::Angular();
742   Standard_Real LinTol = Precision::Confusion();
743   Standard_Real tol;
744   for (TopExp_Explorer ExV (theOriginalShape, TopAbs_VERTEX); ExV.More(); ExV.Next()) {
745     TopoDS_Vertex Vertex = TopoDS::Vertex(ExV.Current());
746     tol = BRep_Tool::Tolerance(Vertex);
747     if (tol > LinTol)
748       LinTol = tol;
749   }
750
751   // 1. Make a copy to prevent the original shape changes.
752   TopoDS_Shape aWire;
753   TColStd_IndexedDataMapOfTransientTransient aMapTShapes;
754   TNaming_CopyShape::CopyTool(theOriginalShape, aMapTShapes, aWire);
755   TopoDS_Wire theWire = TopoDS::Wire(aWire);
756
757   // 2. Sub-shapes of the wire
758   TopTools_MapOfShape aMapToRemove;
759
760   TopTools_IndexedMapOfShape anOldIndices;
761   TopExp::MapShapes(theOriginalShape, anOldIndices);
762
763   TopTools_IndexedMapOfShape aNewIndices;
764   TopExp::MapShapes(theWire, aNewIndices);
765
766   // 3. Collect vertices of the wire, same or equal to the given vertices
767   bool removeAll = false;
768   if (aVerts.IsNull() || aVerts->Length() < 1)
769     removeAll = true;
770
771   if (!removeAll) {
772     for ( int ind = 1; ind <= aVerts->Length(); ind++) {
773       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aVerts->Value(ind));
774       TopoDS_Shape aShape_i = aRefShape->GetValue();
775       if (aShape_i.IsNull())
776         Standard_NullObject::Raise("Null vertex given");
777       if (aShape_i.ShapeType() != TopAbs_VERTEX)
778         Standard_TypeMismatch::Raise("Shape to suppress is not a vertex");
779
780       // find vertices shared with the initial wire
781       if (anOldIndices.Contains(aShape_i)) {
782         aMapToRemove.Add(aNewIndices.FindKey(anOldIndices.FindIndex(aShape_i)));
783       } else {
784         // try to find by coords in the new wire
785         TopoDS_Vertex aVert = TopoDS::Vertex(aShape_i);
786         gp_Pnt aP = BRep_Tool::Pnt(aVert);
787
788         bool isFound = false;
789         TopTools_MapOfShape mapShape;
790         TopExp_Explorer exp (theWire, TopAbs_VERTEX);
791         for (; exp.More() && !isFound; exp.Next()) {
792           if (mapShape.Add(exp.Current())) {
793             TopoDS_Vertex aVi = TopoDS::Vertex(exp.Current());
794             gp_Pnt aPi = BRep_Tool::Pnt(aVi);
795             if (aPi.Distance(aP) < LinTol) {
796               aMapToRemove.Add(aVi);
797               isFound = true;
798             }
799           }
800         }
801       }
802     }
803   }
804
805   /*
806   BRepLib::BuildCurves3d(theWire);
807   Handle(ShapeFix_Shape) Fixer = new ShapeFix_Shape(theWire);
808   Fixer->SetPrecision(LinTol);
809   Fixer->SetMaxTolerance(LinTol);
810   Fixer->Perform();
811   theWire = TopoDS::Wire(Fixer->Shape());
812   */
813
814   // Get the ordered list of edges.
815   TopTools_ListOfShape   anEdges;
816   TopTools_ListOfShape   aCurVertices;
817   BRepTools_WireExplorer aWExp (theWire);
818
819   for (; aWExp.More(); aWExp.Next()) {
820     anEdges.Append(aWExp.Current());
821     aCurVertices.Append(aWExp.CurrentVertex());
822   }
823
824   if (anEdges.IsEmpty()) {
825     Standard_NullObject::Raise("Empty wire given");
826   }
827
828   // Treat the case if the wire is closed and first and last edges are C1.
829   Standard_Boolean isShift = Standard_False;
830
831   if (BRep_Tool::IsClosed(theWire)) {
832     // Wire is closed. Check if there are more than 2 edges in the wire.
833     if (!anEdges.First().IsSame(anEdges.Last())) {
834       isShift = Standard_True;
835     }
836   }
837
838   if (isShift) {
839     // Put first edge to the end of the list while the chain break is reached.
840     TopoDS_Shape aFirstEdge = anEdges.First();
841
842     while (isShift) {
843       isShift = Standard_False;
844
845       // Check if the first vertex should be kept
846       if (aMapToRemove.Contains(aCurVertices.First()) || removeAll) {
847         // Check if first and last edges are C1.
848         TopoDS_Edge anEdge1 = TopoDS::Edge(anEdges.Last());
849         TopoDS_Edge anEdge2 = TopoDS::Edge(anEdges.First());
850
851         if (AreEdgesC1(anEdge1, anEdge2)) {
852           // Make the first edge last.
853           anEdges.Append(anEdge2);
854           anEdges.RemoveFirst();
855           aCurVertices.Append(aCurVertices.First());
856           aCurVertices.RemoveFirst();
857
858           // Check if we reached the first edge again.
859           // Break the loop in this case.
860           isShift = !aFirstEdge.IsSame(anEdges.First());
861         }
862       }
863     }
864   }
865
866   TopTools_ListOfShape finalList, currChain;
867   TopTools_ListIteratorOfListOfShape anEIter(anEdges);
868   TopTools_ListIteratorOfListOfShape aVIter(aCurVertices);
869   TopoDS_Edge                        prevEdge = TopoDS::Edge(anEIter.Value());
870
871   currChain.Append(prevEdge);
872   anEIter.Next();
873   aVIter.Next();
874
875   for (; anEIter.More(); anEIter.Next(), aVIter.Next()) {
876     TopoDS_Edge         anEdge     = TopoDS::Edge(anEIter.Value());
877     const TopoDS_Shape &aCurVertex = aVIter.Value();
878
879     bool continueChain = false;
880     if (aMapToRemove.Contains(aCurVertex) || removeAll) {
881       // if C1 -> continue chain
882       if (AreEdgesC1(prevEdge, anEdge)) {
883         continueChain = true;
884       }
885     }
886
887     if (!continueChain) {
888       if (currChain.Extent() == 1) {
889         // add one edge to the final list
890         finalList.Append(currChain.First());
891       }
892       else {
893         // make wire from the list of edges
894         BRep_Builder B;
895         TopoDS_Wire aCurrWire;
896         B.MakeWire(aCurrWire);
897         TopTools_ListIteratorOfListOfShape itEdges (currChain);
898         for (; itEdges.More(); itEdges.Next()) {
899           TopoDS_Shape aValue = itEdges.Value();
900           B.Add(aCurrWire, TopoDS::Edge(aValue));
901         }
902
903         // make edge from the wire
904         TopoDS_Edge anEdge = GEOMImpl_ShapeDriver::MakeEdgeFromWire(aCurrWire, LinTol, AngTol);
905
906         // add this new edge to the final list
907         finalList.Append(anEdge);
908       }
909       currChain.Clear();
910     }
911
912     // add one edge to the chain
913     currChain.Append(anEdge);
914     prevEdge = anEdge;
915   }
916
917   if (currChain.Extent() == 1) {
918     // add one edge to the final list
919     finalList.Append(currChain.First());
920   }
921   else {
922     // make wire from the list of edges
923     BRep_Builder B;
924     TopoDS_Wire aCurrWire;
925     B.MakeWire(aCurrWire);
926     TopTools_ListIteratorOfListOfShape itEdges (currChain);
927     for (; itEdges.More(); itEdges.Next()) {
928       TopoDS_Shape aValue = itEdges.Value();
929       B.Add(aCurrWire, TopoDS::Edge(aValue));
930     }
931
932     // make edge from the wire
933     TopoDS_Edge anEdge = GEOMImpl_ShapeDriver::MakeEdgeFromWire(aCurrWire, LinTol, AngTol);
934
935     // add this new edge to the final list
936     finalList.Append(anEdge);
937   }
938
939   BRep_Builder B;
940   TopoDS_Wire aFinalWire;
941   B.MakeWire(aFinalWire);
942   TopTools_ListIteratorOfListOfShape itEdges (finalList);
943   for (; itEdges.More(); itEdges.Next()) {
944     TopoDS_Shape aValue = itEdges.Value();
945     B.Add(aFinalWire, TopoDS::Edge(aValue));
946   }
947   theOutShape = aFinalWire;
948
949   if (!GEOMUtils::CheckShape(theOutShape, true))
950     StdFail_NotDone::Raise("Non valid shape result");
951 }
952
953 //=======================================================================
954 //function : AreEdgesC1
955 //purpose  :
956 //=======================================================================
957 Standard_Boolean GEOMImpl_HealingDriver::AreEdgesC1 (const TopoDS_Edge& E1, const TopoDS_Edge& E2)
958 {
959   BRepAdaptor_Curve aCurve1 (E1);
960   BRepAdaptor_Curve aCurve2 (E2);
961
962   if (aCurve1.Continuity() == GeomAbs_C0 || aCurve2.Continuity() == GeomAbs_C0)
963     return Standard_False;
964
965   Standard_Real tol, tolMax = Precision::Confusion();
966   for (TopExp_Explorer ExV1 (E1, TopAbs_VERTEX); ExV1.More(); ExV1.Next()) {
967     TopoDS_Vertex Vertex = TopoDS::Vertex(ExV1.Current());
968     tol = BRep_Tool::Tolerance(Vertex);
969       if (tol > tolMax)
970         tolMax = tol;
971   }
972   for (TopExp_Explorer ExV2 (E2, TopAbs_VERTEX); ExV2.More(); ExV2.Next()) {
973     TopoDS_Vertex Vertex = TopoDS::Vertex(ExV2.Current());
974     tol = BRep_Tool::Tolerance(Vertex);
975       if (tol > tolMax)
976         tolMax = tol;
977   }
978
979   Standard_Real f1, l1, f2, l2;
980   f1 = aCurve1.FirstParameter();
981   l1 = aCurve1.LastParameter();
982   f2 = aCurve2.FirstParameter();
983   l2 = aCurve2.LastParameter();
984
985   if (f1 > l1) {
986     Standard_Real tmp = f1;
987     f1 = l1;
988     l1 = tmp;
989   }
990
991   if (f2 > l2) {
992     Standard_Real tmp = f2;
993     f2 = l2;
994     l2 = tmp;
995   }
996
997   gp_Pnt pf1, pl1, pf2, pl2;
998   gp_Vec vf1, vl1, vf2, vl2;
999   aCurve1.D1(f1, pf1, vf1);
1000   aCurve1.D1(l1, pl1, vl1);
1001   aCurve2.D1(f2, pf2, vf2);
1002   aCurve2.D1(l2, pl2, vl2);
1003
1004   // pf1--->---pl1.pf2--->---pl2
1005   if (pl1.SquareDistance(pf2) < tolMax*tolMax) {
1006     if (vl1.Angle(vf2) < Precision::Angular())
1007       return Standard_True;
1008   }
1009   // pl1---<---pf1.pf2--->---pl2
1010   else if (pf1.SquareDistance(pf2) < tolMax*tolMax) {
1011     if (vf1.Angle(-vf2) < Precision::Angular())
1012       return Standard_True;
1013   }
1014   // pf1--->---pl1.pl2---<---pf2
1015   else if (pl1.SquareDistance(pl2) < tolMax*tolMax) {
1016     if (vl1.Angle(-vl2) < Precision::Angular())
1017       return Standard_True;
1018   }
1019   // pl1---<---pf1.pl2---<---pf2
1020   else {
1021     if (vf1.Angle(vl2) < Precision::Angular())
1022       return Standard_True;
1023   }
1024
1025   return Standard_False;
1026 }
1027
1028 //================================================================================
1029 /*!
1030  * \brief Returns a name of creation operation and names and values of creation parameters
1031  */
1032 //================================================================================
1033
1034 bool GEOMImpl_HealingDriver::
1035 GetCreationInformation(std::string&             theOperationName,
1036                        std::vector<GEOM_Param>& theParams)
1037 {
1038   if (Label().IsNull()) return 0;
1039   Handle(GEOM_Function) function = GEOM_Function::GetFunction(Label());
1040
1041   GEOMImpl_IHealing aCI( function );
1042   Standard_Integer aType = function->GetType();
1043
1044   switch ( aType ) {
1045   case SHAPE_PROCESS:
1046   {
1047     theOperationName = "SHAPE_PROCESS";
1048     AddParam( theParams, "Object", aCI.GetOriginal() );
1049     Handle(TColStd_HArray1OfExtendedString) anOperators = aCI.GetOperators();
1050     Handle(TColStd_HArray1OfExtendedString) aParams     = aCI.GetParameters();
1051     Handle(TColStd_HArray1OfExtendedString) aValues     = aCI.GetValues();
1052     for ( int i = anOperators->Lower(), nb = anOperators->Upper(); i <= nb; ++i )
1053     {
1054       const TCollection_ExtendedString& op = anOperators->Value(i);
1055       AddParam( theParams, "Operation", op );
1056       for ( int iP = aParams->Lower(), nbP = aParams->Upper(); iP <= nbP; ++iP )
1057       {
1058         const TCollection_ExtendedString& par = aParams->Value(iP);
1059         TCollection_AsciiString parAscii( par );
1060         if ( par.Search( op ) == 1 && parAscii.Value( op.Length() + 1 ) == '.' )
1061         {
1062           GEOM_Param& p = AddParam( theParams, parAscii.ToCString() );
1063           if ( iP <= aValues->Upper() )
1064             p << aValues->Value( iP );
1065         }
1066       }
1067     }
1068     break;
1069   }
1070   case SUPPRESS_FACES:
1071     theOperationName = "SUPPRESS_FACES";
1072     AddParam( theParams, "Selected Shape", aCI.GetOriginal() );
1073     AddParam( theParams, "Faces to remove", aCI.GetFaces() );
1074     break;
1075   case CLOSE_CONTOUR:
1076     theOperationName = "CLOSE_CONTOUR";
1077     AddParam( theParams, "Selected Shape", aCI.GetOriginal() );
1078     AddParam( theParams, "Contour to close", aCI.GetWires() );
1079     AddParam( theParams, "Close by common vertex", aCI.GetIsCommonVertex() );
1080     break;
1081   case REMOVE_INT_WIRES:
1082     theOperationName = "SUPPRESS_INT_WIRES";
1083     AddParam( theParams, "Selected face", aCI.GetOriginal() );
1084     AddParam( theParams, "Wires to remove", aCI.GetWires(), "all" );
1085     break;
1086   case FILL_HOLES:
1087     theOperationName = "SUPPERSS_HOLES";
1088     AddParam( theParams, "Selected shape", aCI.GetOriginal() );
1089     AddParam( theParams, "Wires to remove", aCI.GetWires(), "all" );
1090     break;
1091   case SEWING:
1092   case SEWING_NON_MANIFOLD:
1093     theOperationName = "SEWING";
1094     AddParam( theParams, "Selected shapes", aCI.GetOriginalAndShapes() );
1095     AddParam( theParams, "Allow Non Manifold", ( aType == SEWING_NON_MANIFOLD ));
1096     AddParam( theParams, "Tolerance", aCI.GetTolerance() );
1097     break;
1098   case DIVIDE_EDGE:
1099     theOperationName = "POINT_ON_EDGE";
1100     if ( aCI.GetIndex() > 0 )
1101       AddParam( theParams, "Edge", "#" ) << aCI.GetIndex() << " of " << aCI.GetOriginal();
1102     else
1103       AddParam( theParams, "Edge", aCI.GetOriginal() );
1104     AddParam( theParams, "By parameter", aCI.GetIsByParameter() );
1105     AddParam( theParams, "Value", aCI.GetDevideEdgeValue() );
1106     break;
1107   case DIVIDE_EDGE_BY_POINT:
1108     theOperationName = "POINT_ON_EDGE";
1109     if ( aCI.GetIndex() > 0 )
1110       AddParam( theParams, "Edge", "#" ) << aCI.GetIndex() << " of " << aCI.GetOriginal();
1111     else
1112       AddParam( theParams, "Edge", aCI.GetOriginal() );
1113     AddParam( theParams, "Points", aCI.GetShapes() );
1114     break;
1115   case CHANGE_ORIENTATION:
1116     theOperationName = "CHANGE_ORIENTATION";
1117     AddParam( theParams, "Selected shape", aCI.GetOriginal() );
1118     break;
1119   case LIMIT_TOLERANCE:
1120     theOperationName = "LIMIT_TOLERANCE";
1121     AddParam( theParams, "Selected shape", aCI.GetOriginal() );
1122     AddParam( theParams, "Tolerance", aCI.GetTolerance() );
1123     AddParam( theParams, "Type", aCI.GetType() );
1124     break;
1125   case FUSE_COLLINEAR_EDGES:
1126     theOperationName = "FUSE_EDGES";
1127     AddParam( theParams, "Wire", aCI.GetOriginal() );
1128     AddParam( theParams, "Vertexes", aCI.GetShapes() );
1129     break;
1130   case REMOVE_INTERNAL_FACES:
1131     theOperationName = "REMOVE_WEBS";
1132     AddParam( theParams, "Selected shapes", aCI.GetOriginalAndShapes() );
1133     break;
1134   default:
1135     return false;
1136   }
1137   
1138   return true;
1139 }
1140
1141 //================================================================================
1142 /*!
1143  * \brief Pass a record of what is done to the operation
1144  */
1145 //================================================================================
1146
1147 void GEOMImpl_HealingDriver::SaveStatistics( const ShHealOper_Tool& healer, bool add ) const
1148 {
1149   if ( healer.GetStatistics().GetData().empty() )
1150     return;
1151
1152   if (Label().IsNull()) return;
1153
1154   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
1155   if (aFunction.IsNull()) return;
1156
1157   GEOMImpl_IHealing HI (aFunction);
1158   ShHealOper_ModifStats * stats = HI.GetStatistics();
1159   if ( !stats ) return;
1160
1161   if ( add )
1162     stats->Add( healer.GetStatistics() );
1163   else
1164     *stats = healer.GetStatistics();
1165 }
1166
1167 IMPLEMENT_STANDARD_RTTIEXT (GEOMImpl_HealingDriver,GEOM_BaseDriver)