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