0027015: Sewing returns invalid shape if some faces are nearly plane cones
[occt.git] / src / BRepLib / BRepLib.cxx
1 // Created on: 1993-12-15
2 // Created by: Remi LEQUETTE
3 // Copyright (c) 1993-1999 Matra Datavision
4 // Copyright (c) 1999-2014 OPEN CASCADE SAS
5 //
6 // This file is part of Open CASCADE Technology software library.
7 //
8 // This library is free software; you can redistribute it and/or modify it under
9 // the terms of the GNU Lesser General Public License version 2.1 as published
10 // by the Free Software Foundation, with special exception defined in the file
11 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
12 // distribution for complete text of the license and disclaimer of any warranty.
13 //
14 // Alternatively, this file may be used under the terms of Open CASCADE
15 // commercial license or contractual agreement.
16
17 //pmn 26/09/97 Add parameters of approximation in BuildCurve3d
18 //  Modified by skv - Thu Jun  3 12:39:19 2004 OCC5898
19
20 #include <Adaptor3d_CurveOnSurface.hxx>
21 #include <AdvApprox_ApproxAFunction.hxx>
22 #include <AppParCurves_MultiBSpCurve.hxx>
23 #include <AppParCurves_MultiCurve.hxx>
24 #include <Approx_CurvilinearParameter.hxx>
25 #include <Approx_SameParameter.hxx>
26 #include <Bnd_Box.hxx>
27 #include <BRep_Builder.hxx>
28 #include <BRep_CurveRepresentation.hxx>
29 #include <BRep_GCurve.hxx>
30 #include <BRep_ListIteratorOfListOfCurveRepresentation.hxx>
31 #include <BRep_ListOfCurveRepresentation.hxx>
32 #include <BRep_TEdge.hxx>
33 #include <BRep_TFace.hxx>
34 #include <BRep_Tool.hxx>
35 #include <BRep_TVertex.hxx>
36 #include <BRepAdaptor_HCurve.hxx>
37 #include <BRepAdaptor_HCurve2d.hxx>
38 #include <BRepAdaptor_HSurface.hxx>
39 #include <BRepAdaptor_Surface.hxx>
40 #include <BRepBndLib.hxx>
41 #include <BRepClass3d_SolidClassifier.hxx>
42 #include <BRepLib.hxx>
43 #include <BSplCLib.hxx>
44 #include <ElSLib.hxx>
45 #include <Extrema_LocateExtPC.hxx>
46 #include <GCPnts_QuasiUniformDeflection.hxx>
47 #include <Geom2d_BSplineCurve.hxx>
48 #include <Geom2d_Curve.hxx>
49 #include <Geom2d_TrimmedCurve.hxx>
50 #include <Geom2dAdaptor.hxx>
51 #include <Geom2dAdaptor_Curve.hxx>
52 #include <Geom2dAdaptor_HCurve.hxx>
53 #include <Geom2dConvert.hxx>
54 #include <Geom_BSplineCurve.hxx>
55 #include <Geom_BSplineSurface.hxx>
56 #include <Geom_Curve.hxx>
57 #include <Geom_Plane.hxx>
58 #include <Geom_RectangularTrimmedSurface.hxx>
59 #include <Geom_Surface.hxx>
60 #include <Geom_TrimmedCurve.hxx>
61 #include <GeomAdaptor_Curve.hxx>
62 #include <GeomAdaptor_HCurve.hxx>
63 #include <GeomAdaptor_HSurface.hxx>
64 #include <GeomAdaptor_Surface.hxx>
65 #include <GeomLib.hxx>
66 #include <GeomLProp_SLProps.hxx>
67 #include <gp.hxx>
68 #include <gp_Ax2.hxx>
69 #include <gp_Pln.hxx>
70 #include <Poly_PolygonOnTriangulation.hxx>
71 #include <Poly_Triangulation.hxx>
72 #include <Precision.hxx>
73 #include <ProjLib_ProjectedCurve.hxx>
74 #include <Standard_Real.hxx>
75 #include <TColgp_Array1OfPnt.hxx>
76 #include <TColgp_Array1OfPnt2d.hxx>
77 #include <TColStd_Array1OfReal.hxx>
78 #include <TColStd_MapOfTransient.hxx>
79 #include <TopExp.hxx>
80 #include <TopExp_Explorer.hxx>
81 #include <TopoDS.hxx>
82 #include <TopoDS_Edge.hxx>
83 #include <TopoDS_Face.hxx>
84 #include <TopoDS_Shape.hxx>
85 #include <TopoDS_Solid.hxx>
86 #include <TopoDS_Vertex.hxx>
87 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
88 #include <TopTools_ListIteratorOfListOfShape.hxx>
89 #include <TopTools_MapOfShape.hxx>
90 #include <TShort_HArray1OfShortReal.hxx>
91 #include <TColgp_Array1OfXY.hxx>
92
93 // TODO - not thread-safe static variables
94 static Standard_Real thePrecision = Precision::Confusion();     
95 static Handle(Geom_Plane) thePlane;
96
97 //=======================================================================
98 //function : Precision
99 //purpose  : 
100 //=======================================================================
101
102 void BRepLib::Precision(const Standard_Real P)
103 {
104   thePrecision = P;
105 }
106
107 //=======================================================================
108 //function : Precision
109 //purpose  : 
110 //=======================================================================
111
112 Standard_Real  BRepLib::Precision()
113 {
114   return thePrecision;
115 }
116
117 //=======================================================================
118 //function : Plane
119 //purpose  : 
120 //=======================================================================
121
122 void  BRepLib::Plane(const Handle(Geom_Plane)& P)
123 {
124   thePlane = P;
125 }
126
127
128 //=======================================================================
129 //function : Plane
130 //purpose  : 
131 //=======================================================================
132
133 const Handle(Geom_Plane)&  BRepLib::Plane()
134 {
135   if (thePlane.IsNull()) thePlane = new Geom_Plane(gp::XOY());
136   return thePlane;
137 }
138 //=======================================================================
139 //function : CheckSameRange
140 //purpose  : 
141 //=======================================================================
142
143 Standard_Boolean  BRepLib::CheckSameRange(const TopoDS_Edge& AnEdge,
144   const Standard_Real Tolerance) 
145 {
146   Standard_Boolean  IsSameRange = Standard_True,
147     first_time_in = Standard_True ;
148
149   BRep_ListIteratorOfListOfCurveRepresentation an_Iterator
150     ((*((Handle(BRep_TEdge)*)&AnEdge.TShape()))->ChangeCurves());
151
152   Standard_Real first, last;
153   Standard_Real current_first =0., current_last =0. ;
154   Handle(BRep_GCurve) geometric_representation_ptr ;
155
156   while (IsSameRange && an_Iterator.More()) {
157     geometric_representation_ptr =
158       Handle(BRep_GCurve)::DownCast(an_Iterator.Value());
159     if (!geometric_representation_ptr.IsNull()) {
160
161       first = geometric_representation_ptr->First();
162       last =  geometric_representation_ptr->Last();
163       if (first_time_in ) {
164         current_first = first ;
165         current_last = last   ;
166         first_time_in = Standard_False ;
167       }
168       else {
169         IsSameRange = (Abs(current_first - first) <= Tolerance) 
170           && (Abs(current_last -last) <= Tolerance ) ;
171       }
172     }
173     an_Iterator.Next() ;
174   }
175   return IsSameRange ;
176 }
177
178 //=======================================================================
179 //function : SameRange
180 //purpose  : 
181 //=======================================================================
182
183 void BRepLib::SameRange(const TopoDS_Edge& AnEdge,
184   const Standard_Real Tolerance) 
185 {
186   BRep_ListIteratorOfListOfCurveRepresentation an_Iterator
187     ((*((Handle(BRep_TEdge)*)&AnEdge.TShape()))->ChangeCurves());
188
189   Handle(Geom2d_Curve) Curve2dPtr, Curve2dPtr2, NewCurve2dPtr, NewCurve2dPtr2;
190   TopLoc_Location LocalLoc ;
191
192   Standard_Boolean first_time_in = Standard_True,
193     has_curve,
194     has_closed_curve ;
195   Handle(BRep_GCurve) geometric_representation_ptr ;
196   Standard_Real first,
197     current_first,
198     last,
199     current_last ;
200
201   const Handle(Geom_Curve) C = BRep_Tool::Curve(AnEdge,
202     LocalLoc,
203     current_first,
204     current_last);
205   if (!C.IsNull()) {
206     first_time_in = Standard_False ;
207   }
208
209   while (an_Iterator.More()) {
210     geometric_representation_ptr =
211       Handle(BRep_GCurve)::DownCast(an_Iterator.Value());
212     if (! geometric_representation_ptr.IsNull()) {
213       has_closed_curve =
214         has_curve = Standard_False ;
215       first = geometric_representation_ptr->First();
216       last =  geometric_representation_ptr->Last();
217       if (geometric_representation_ptr->IsCurveOnSurface()) {
218         Curve2dPtr = geometric_representation_ptr->PCurve() ; 
219         has_curve = Standard_True ;
220       }
221       if (geometric_representation_ptr->IsCurveOnClosedSurface()) {
222         Curve2dPtr2 = geometric_representation_ptr->PCurve2() ;
223         has_closed_curve = Standard_True ;
224       }
225       if (has_curve || has_closed_curve) {
226         if (first_time_in) {
227           current_first = first ;
228           current_last = last ;
229           first_time_in = Standard_False ;
230         }
231
232         if (Abs(first - current_first) > Precision::Confusion() ||
233           Abs(last - current_last) > Precision::Confusion() )
234         {
235           if (has_curve)
236           {
237             GeomLib::SameRange(Tolerance,
238               Curve2dPtr,
239               geometric_representation_ptr->First(),
240               geometric_representation_ptr->Last(),
241               current_first,
242               current_last,
243               NewCurve2dPtr);
244             geometric_representation_ptr->PCurve(NewCurve2dPtr) ;
245           }
246           if (has_closed_curve)
247           {
248             GeomLib::SameRange(Tolerance,
249               Curve2dPtr2,
250               geometric_representation_ptr->First(),
251               geometric_representation_ptr->Last(),
252               current_first,
253               current_last,
254               NewCurve2dPtr2);
255             geometric_representation_ptr->PCurve2(NewCurve2dPtr2) ;
256           }
257         }
258       }
259     }
260     an_Iterator.Next() ;
261   }
262   BRep_Builder B;
263   B.Range(TopoDS::Edge(AnEdge),
264     current_first,
265     current_last) ;
266
267   B.SameRange(AnEdge,
268     Standard_True) ;
269 }
270
271 //=======================================================================
272 //function : EvaluateMaxSegment
273 //purpose  : return MaxSegment to pass in approximation, if MaxSegment==0 provided
274 //=======================================================================
275
276 static Standard_Integer evaluateMaxSegment(const Standard_Integer aMaxSegment,
277   const Adaptor3d_CurveOnSurface& aCurveOnSurface)
278 {
279   if (aMaxSegment != 0) return aMaxSegment;
280
281   Handle(Adaptor3d_HSurface) aSurf   = aCurveOnSurface.GetSurface();
282   Handle(Adaptor2d_HCurve2d) aCurv2d = aCurveOnSurface.GetCurve();
283
284   Standard_Real aNbSKnots = 0, aNbC2dKnots = 0;
285
286   if (aSurf->GetType() == GeomAbs_BSplineSurface) {
287     Handle(Geom_BSplineSurface) aBSpline = aSurf->BSpline();
288     aNbSKnots = Max(aBSpline->NbUKnots(), aBSpline->NbVKnots());
289   }
290   if (aCurv2d->GetType() == GeomAbs_BSplineCurve) {
291     aNbC2dKnots = aCurv2d->NbKnots();
292   }
293   Standard_Integer aReturn = (Standard_Integer) (  30 + Max(aNbSKnots, aNbC2dKnots) ) ;
294   return aReturn;
295 }
296
297 //=======================================================================
298 //function : BuildCurve3d
299 //purpose  : 
300 //=======================================================================
301
302 Standard_Boolean  BRepLib::BuildCurve3d(const TopoDS_Edge& AnEdge,
303   const Standard_Real Tolerance,
304   const GeomAbs_Shape Continuity,
305   const Standard_Integer MaxDegree,
306   const Standard_Integer MaxSegment)
307 {
308   Standard_Integer //ErrorCode,
309     //                   ReturnCode = 0,
310     ii,
311     //                   num_knots,
312     jj;
313
314   TopLoc_Location LocalLoc,L[2],LC;
315   Standard_Real f,l,fc,lc, first[2], last[2],
316     tolerance,
317     max_deviation,
318     average_deviation ;
319   Handle(Geom2d_Curve) Curve2dPtr, Curve2dArray[2]  ;
320   Handle(Geom_Surface) SurfacePtr, SurfaceArray[2]  ;
321
322   Standard_Integer not_done ;
323   // if the edge has a 3d curve returns true
324
325
326   const Handle(Geom_Curve) C = BRep_Tool::Curve(AnEdge,LocalLoc,f,l);
327   if (!C.IsNull()) 
328     return Standard_True;
329   //
330   // this should not exists but UpdateEdge makes funny things 
331   // if the edge is not same range 
332   //
333   if (! CheckSameRange(AnEdge,
334     Precision::Confusion())) {
335       SameRange(AnEdge,
336         Tolerance) ;
337   }
338
339
340
341   // search a curve on a plane
342   Handle(Geom_Surface) S;
343   Handle(Geom2d_Curve) PC;
344   Standard_Integer i = 0;
345   Handle(Geom_Plane) P;
346   not_done = 1 ;
347
348   while (not_done) {
349     i++;
350     BRep_Tool::CurveOnSurface(AnEdge,PC,S,LocalLoc,f,l,i);
351     Handle(Geom_RectangularTrimmedSurface) RT = 
352       Handle(Geom_RectangularTrimmedSurface)::DownCast(S);
353     if ( RT.IsNull()) {
354       P = Handle(Geom_Plane)::DownCast(S);
355     }
356     else {
357       P = Handle(Geom_Plane)::DownCast(RT->BasisSurface());
358     }
359     not_done = ! (S.IsNull() || !P.IsNull()) ;
360   }
361   if (! P.IsNull()) {
362     // compute the 3d curve
363     gp_Ax2 axes = P->Position().Ax2();
364     Handle(Geom_Curve) C3d = GeomLib::To3d(axes,PC);
365     if (C3d.IsNull())
366       return Standard_False;
367     // update the edge
368     Standard_Real First, Last;
369
370     BRep_Builder B;
371     B.UpdateEdge(AnEdge,C3d,LocalLoc,0.0e0);
372     BRep_Tool::Range(AnEdge, S, LC, First, Last);
373     B.Range(AnEdge, First, Last); //Do not forget 3D range.(PRO6412)
374   }
375   else {
376     //
377     // compute the 3d curve using existing surface
378     //
379     fc = f ;
380     lc = l ;
381     if (!BRep_Tool::Degenerated(AnEdge)) {
382       jj = 0 ;
383       for (ii = 0 ; ii < 3 ; ii++ ) {
384         BRep_Tool::CurveOnSurface(TopoDS::Edge(AnEdge),
385           Curve2dPtr,
386           SurfacePtr,
387           LocalLoc,
388           fc,
389           lc,
390           ii) ;
391
392         if (!Curve2dPtr.IsNull() && jj < 2){
393           Curve2dArray[jj] = Curve2dPtr ;
394           SurfaceArray[jj] = SurfacePtr ;
395           L[jj] = LocalLoc ;
396           first[jj] = fc ;
397           last[jj] = lc ;
398           jj += 1 ;
399         }
400       }
401       f = first[0] ;
402       l = last[0] ;
403       Curve2dPtr = Curve2dArray[0] ;
404       SurfacePtr = SurfaceArray[0] ;
405
406       Geom2dAdaptor_Curve     AnAdaptor3dCurve2d (Curve2dPtr, f, l) ;
407       GeomAdaptor_Surface     AnAdaptor3dSurface (SurfacePtr) ;
408       Handle(Geom2dAdaptor_HCurve) AnAdaptor3dCurve2dPtr =
409         new Geom2dAdaptor_HCurve(AnAdaptor3dCurve2d) ;
410       Handle(GeomAdaptor_HSurface) AnAdaptor3dSurfacePtr =
411         new GeomAdaptor_HSurface (AnAdaptor3dSurface) ;
412       Adaptor3d_CurveOnSurface  CurveOnSurface( AnAdaptor3dCurve2dPtr,
413         AnAdaptor3dSurfacePtr) ;
414
415       Handle(Geom_Curve) NewCurvePtr ;
416
417       GeomLib::BuildCurve3d(Tolerance,
418         CurveOnSurface,
419         f,
420         l,
421         NewCurvePtr,
422         max_deviation,
423         average_deviation,
424         Continuity,
425         MaxDegree,
426         evaluateMaxSegment(MaxSegment,CurveOnSurface)) ;
427       BRep_Builder B;   
428       tolerance = BRep_Tool::Tolerance(AnEdge) ;
429       //Patch
430       //max_deviation = Max(tolerance, max_deviation) ;
431       max_deviation = Max( tolerance, Tolerance );
432       if (NewCurvePtr.IsNull())
433         return Standard_False;
434       B.UpdateEdge(TopoDS::Edge(AnEdge),
435         NewCurvePtr,
436         L[0],
437         max_deviation) ;
438       if (jj == 1 ) {
439         //
440         // if there is only one curve on surface attached to the edge
441         // than it can be qualified sameparameter
442         //
443         B.SameParameter(TopoDS::Edge(AnEdge),
444           Standard_True) ;
445       }
446     }
447     else {
448       return Standard_False ;
449     }
450
451   }         
452   return Standard_True;
453 }
454 //=======================================================================
455 //function : BuildCurves3d
456 //purpose  : 
457 //=======================================================================
458
459 Standard_Boolean  BRepLib::BuildCurves3d(const TopoDS_Shape& S) 
460
461 {
462   return BRepLib::BuildCurves3d(S,
463     1.0e-5) ;
464 }
465
466 //=======================================================================
467 //function : BuildCurves3d
468 //purpose  : 
469 //=======================================================================
470
471 Standard_Boolean  BRepLib::BuildCurves3d(const TopoDS_Shape& S,
472   const Standard_Real Tolerance,
473   const GeomAbs_Shape Continuity,
474   const Standard_Integer MaxDegree,
475   const Standard_Integer MaxSegment)
476 {
477   Standard_Boolean boolean_value,
478     ok = Standard_True;
479   TopTools_MapOfShape a_counter ;
480   TopExp_Explorer ex(S,TopAbs_EDGE);
481
482   while (ex.More()) {
483     if (a_counter.Add(ex.Current())) {
484       boolean_value = 
485         BuildCurve3d(TopoDS::Edge(ex.Current()),
486         Tolerance, Continuity,
487         MaxDegree, MaxSegment);
488       ok = ok && boolean_value ;
489     }
490     ex.Next();
491   }
492   return ok;
493 }
494 //=======================================================================
495 //function : UpdateEdgeTolerance
496 //purpose  : 
497 //=======================================================================
498
499 Standard_Boolean  BRepLib::UpdateEdgeTol(const TopoDS_Edge& AnEdge,
500   const Standard_Real MinToleranceRequested,
501   const Standard_Real MaxToleranceToCheck)
502 {
503
504   Standard_Integer curve_on_surface_index,
505     curve_index,
506     not_done,
507     has_closed_curve,
508     has_curve,
509     jj,
510     ii,
511     geom_reference_curve_flag = 0,
512     max_sampling_points = 90,
513     min_sampling_points = 30 ;
514
515   Standard_Real factor = 100.0e0,
516     //     sampling_array[2],
517     safe_factor = 1.4e0,
518     current_last,
519     current_first,
520     max_distance,
521     coded_edge_tolerance,
522     edge_tolerance = 0.0e0 ;
523   Handle(TColStd_HArray1OfReal) parameters_ptr ;
524   Handle(BRep_GCurve) geometric_representation_ptr ;
525
526   if (BRep_Tool::Degenerated(AnEdge)) return Standard_False ;
527   coded_edge_tolerance = BRep_Tool::Tolerance(AnEdge) ;
528   if (coded_edge_tolerance > MaxToleranceToCheck) return Standard_False ;
529
530   const Handle(BRep_TEdge)& TE = *((Handle(BRep_TEdge)*)&AnEdge.TShape());
531   BRep_ListOfCurveRepresentation& list_curve_rep = TE->ChangeCurves() ;
532   BRep_ListIteratorOfListOfCurveRepresentation an_iterator(list_curve_rep),
533     second_iterator(list_curve_rep) ;
534   Handle(Geom2d_Curve) curve2d_ptr, new_curve2d_ptr;
535   Handle(Geom_Surface) surface_ptr ;
536   TopLoc_Location local_location ;
537   GCPnts_QuasiUniformDeflection  a_sampler ;
538   GeomAdaptor_Curve  geom_reference_curve ;
539   Adaptor3d_CurveOnSurface  curve_on_surface_reference ; 
540   Handle(Geom_Curve) C = BRep_Tool::Curve(AnEdge,
541     local_location,
542     current_first,
543     current_last);
544   curve_on_surface_index = -1 ;
545   if (!C.IsNull()) {
546     if (! local_location.IsIdentity()) {
547       C = Handle(Geom_Curve)::
548         DownCast(C-> Transformed(local_location.Transformation()) ) ;
549     }
550     geom_reference_curve.Load(C) ;
551     geom_reference_curve_flag = 1 ;
552     a_sampler.Initialize(geom_reference_curve,
553       MinToleranceRequested * factor,
554       current_first,
555       current_last) ;
556   }
557   else {
558     not_done = 1 ;
559     curve_on_surface_index = 0 ;  
560
561     while (not_done && an_iterator.More()) {
562       geometric_representation_ptr =
563         Handle(BRep_GCurve)::DownCast(second_iterator.Value());
564       if (!geometric_representation_ptr.IsNull() 
565         && geometric_representation_ptr->IsCurveOnSurface()) {
566           curve2d_ptr = geometric_representation_ptr->PCurve() ;
567           local_location = geometric_representation_ptr->Location() ;
568           current_first = geometric_representation_ptr->First();
569           //first = geometric_representation_ptr->First();
570           current_last =  geometric_representation_ptr->Last();
571           // must be inverted 
572           //
573           if (! local_location.IsIdentity() ) {
574             surface_ptr = Handle(Geom_Surface)::
575               DownCast( geometric_representation_ptr->Surface()->
576               Transformed(local_location.Transformation()) ) ;
577           }
578           else {
579             surface_ptr = 
580               geometric_representation_ptr->Surface() ;
581           }
582           not_done = 0 ;
583       }
584       curve_on_surface_index += 1 ;
585     }
586     Geom2dAdaptor_Curve     AnAdaptor3dCurve2d (curve2d_ptr) ;
587     GeomAdaptor_Surface     AnAdaptor3dSurface (surface_ptr) ;
588     Handle(Geom2dAdaptor_HCurve) AnAdaptor3dCurve2dPtr =
589       new Geom2dAdaptor_HCurve(AnAdaptor3dCurve2d) ;
590     Handle(GeomAdaptor_HSurface) AnAdaptor3dSurfacePtr =
591       new GeomAdaptor_HSurface (AnAdaptor3dSurface) ;
592     curve_on_surface_reference.Load (AnAdaptor3dCurve2dPtr, AnAdaptor3dSurfacePtr);
593     a_sampler.Initialize(curve_on_surface_reference,
594       MinToleranceRequested * factor,
595       current_first,
596       current_last) ;
597   }
598   TColStd_Array1OfReal   sampling_parameters(1,a_sampler.NbPoints()) ;
599   for (ii = 1 ; ii <= a_sampler.NbPoints() ; ii++) {
600     sampling_parameters(ii) = a_sampler.Parameter(ii) ;
601   }
602   if (a_sampler.NbPoints() < min_sampling_points) {
603     GeomLib::DensifyArray1OfReal(min_sampling_points,
604       sampling_parameters,
605       parameters_ptr) ;
606   }
607   else if (a_sampler.NbPoints() > max_sampling_points) {
608     GeomLib::RemovePointsFromArray(max_sampling_points,
609       sampling_parameters,
610       parameters_ptr) ; 
611   }
612   else {
613     jj = 1 ;
614     parameters_ptr =
615       new TColStd_HArray1OfReal(1,sampling_parameters.Length()) ;
616     for (ii = sampling_parameters.Lower() ; ii <= sampling_parameters.Upper() ; ii++) {
617       parameters_ptr->ChangeArray1()(jj) =
618         sampling_parameters(ii) ;
619       jj +=1 ;
620     }
621   }
622
623   curve_index = 0 ;
624
625   while (second_iterator.More()) {
626     geometric_representation_ptr =
627       Handle(BRep_GCurve)::DownCast(second_iterator.Value());
628     if (! geometric_representation_ptr.IsNull() && 
629       curve_index != curve_on_surface_index) {
630         has_closed_curve =
631           has_curve = Standard_False ;
632         //      first = geometric_representation_ptr->First();
633         //      last =  geometric_representation_ptr->Last();
634         local_location = geometric_representation_ptr->Location() ;
635         if (geometric_representation_ptr->IsCurveOnSurface()) {
636           curve2d_ptr = geometric_representation_ptr->PCurve() ; 
637           has_curve = Standard_True ;
638         }
639         if (geometric_representation_ptr->IsCurveOnClosedSurface()) {
640           curve2d_ptr = geometric_representation_ptr->PCurve2() ;
641           has_closed_curve = Standard_True ;
642         }
643
644         if (has_curve ||
645           has_closed_curve) {
646             if (! local_location.IsIdentity() ) {
647               surface_ptr = Handle(Geom_Surface)::
648                 DownCast( geometric_representation_ptr->Surface()->
649                 Transformed(local_location.Transformation()) ) ;
650             }
651             else {
652               surface_ptr = 
653                 geometric_representation_ptr->Surface() ;
654             }
655             Geom2dAdaptor_Curve     an_adaptor_curve2d (curve2d_ptr) ;
656             GeomAdaptor_Surface     an_adaptor_surface(surface_ptr) ;
657             Handle(Geom2dAdaptor_HCurve) an_adaptor_curve2d_ptr =
658               new Geom2dAdaptor_HCurve(an_adaptor_curve2d) ;
659             Handle(GeomAdaptor_HSurface) an_adaptor_surface_ptr =
660               new GeomAdaptor_HSurface (an_adaptor_surface) ;
661             Adaptor3d_CurveOnSurface a_curve_on_surface(an_adaptor_curve2d_ptr,
662               an_adaptor_surface_ptr) ;
663
664             if (BRep_Tool::SameParameter(AnEdge)) {
665
666               GeomLib::EvalMaxParametricDistance(a_curve_on_surface,
667                 geom_reference_curve,
668                 MinToleranceRequested,
669                 parameters_ptr->Array1(),
670                 max_distance) ;
671             }
672             else if (geom_reference_curve_flag) {
673               GeomLib::EvalMaxDistanceAlongParameter(a_curve_on_surface,
674                 geom_reference_curve,
675                 MinToleranceRequested,
676                 parameters_ptr->Array1(),
677                 max_distance) ;
678             }
679             else {
680
681               GeomLib::EvalMaxDistanceAlongParameter(a_curve_on_surface,
682                 curve_on_surface_reference,
683                 MinToleranceRequested,
684                 parameters_ptr->Array1(),
685                 max_distance) ;
686             }
687             max_distance *= safe_factor ;
688             edge_tolerance = Max(max_distance, edge_tolerance) ;
689         }
690
691
692     }
693     curve_index += 1 ;
694     second_iterator.Next() ; 
695   }
696
697   TE->Tolerance(edge_tolerance);
698   return Standard_True ;
699
700 }
701 //=======================================================================
702 //function : UpdateEdgeTolerance
703 //purpose  : 
704 //=======================================================================
705
706 Standard_Boolean BRepLib::UpdateEdgeTolerance(const TopoDS_Shape& S,
707   const Standard_Real MinToleranceRequested,
708   const Standard_Real MaxToleranceToCheck) 
709 {
710   TopExp_Explorer ex(S,TopAbs_EDGE);
711   TopTools_MapOfShape  a_counter ;
712
713   Standard_Boolean     return_status = Standard_False,
714     local_flag ;
715
716   while (ex.More()) {
717     if (a_counter.Add(ex.Current())) {
718       local_flag =
719         BRepLib::UpdateEdgeTol(TopoDS::Edge(ex.Current()),
720         MinToleranceRequested,
721         MaxToleranceToCheck) ;
722       if (local_flag && ! return_status) {
723         return_status = Standard_True ;
724       }
725     }
726     ex.Next();
727   }
728   return return_status ;
729 }
730
731 //=======================================================================
732 //function : SetEdgeTol
733 //purpose  : 
734 //=======================================================================
735
736 static void SetEdgeTol(const TopoDS_Edge& E,
737   const TopoDS_Face& F)
738 {
739   TopLoc_Location L;
740   const Handle(Geom_Surface)& S = BRep_Tool::Surface(F,L);
741   TopLoc_Location l = L.Predivided(E.Location());
742
743   const Handle(BRep_TEdge)& TE = *((Handle(BRep_TEdge)*)&E.TShape());
744   BRep_ListIteratorOfListOfCurveRepresentation itcr(TE->ChangeCurves());
745
746   while (itcr.More()) {
747     const Handle(BRep_CurveRepresentation)& cr = itcr.Value();
748     if(cr->IsCurveOnSurface(S,l)) return;
749     itcr.Next();
750   }
751
752   Handle(Geom_Plane) GP;
753   Handle(Geom_RectangularTrimmedSurface) GRTS;
754   GRTS = Handle(Geom_RectangularTrimmedSurface)::DownCast(S);
755   if(!GRTS.IsNull())
756     GP = Handle(Geom_Plane)::DownCast(GRTS->BasisSurface());
757   else
758     GP = Handle(Geom_Plane)::DownCast(S);
759
760   Handle(GeomAdaptor_HCurve) HC = new GeomAdaptor_HCurve();
761   Handle(GeomAdaptor_HSurface) HS = new GeomAdaptor_HSurface();
762
763   TopLoc_Location LC;
764   Standard_Real First, Last;
765   GeomAdaptor_Curve& GAC = HC->ChangeCurve();
766   GAC.Load(BRep_Tool::Curve(E,LC,First,Last));
767   LC = L.Predivided(LC);
768
769   if (!LC.IsIdentity()) {
770     GP = Handle(Geom_Plane)::DownCast(
771       GP->Transformed(LC.Transformation()));
772   }
773   GeomAdaptor_Surface& GAS = HS->ChangeSurface();
774   GAS.Load(GP);
775
776   ProjLib_ProjectedCurve Proj(HS,HC);
777   Handle(Geom2d_Curve) pc = Geom2dAdaptor::MakeCurve(Proj);
778
779   gp_Pln pln = GAS.Plane();
780   Standard_Real d2 = 0.;
781   Standard_Integer nn = 23;
782   Standard_Real unsurnn = 1./nn;
783   for(Standard_Integer i = 0; i <= nn; i++){
784     Standard_Real t = unsurnn*i;
785     Standard_Real u = First*(1.-t) + Last*t;
786     gp_Pnt Pc3d = HC->Value(u);
787     gp_Pnt2d p2d = pc->Value(u);
788     gp_Pnt Pcons = ElSLib::Value(p2d.X(),p2d.Y(),pln);
789     Standard_Real eps = Max(Pc3d.XYZ().SquareModulus(), Pcons.XYZ().SquareModulus());
790     eps = Epsilon(eps);
791     Standard_Real temp = Pc3d.SquareDistance(Pcons);
792     if(temp <= eps)
793     {
794       temp = 0.;
795     }
796     if(temp > d2) d2 = temp;
797   }
798   d2 = 1.5*sqrt(d2);
799   TE->UpdateTolerance(d2);
800 }
801
802 //=======================================================================
803 //function : SameParameter
804 //purpose  : 
805 //=======================================================================
806 void  BRepLib::SameParameter(const TopoDS_Shape& S,
807   const Standard_Real Tolerance,
808   const Standard_Boolean forced) 
809 {
810   TopExp_Explorer ex(S,TopAbs_EDGE);
811   TopTools_MapOfShape  Done;
812   BRep_Builder brB;
813
814   while (ex.More()) {
815     if (Done.Add(ex.Current())) {
816       if (forced) {
817         brB.SameRange(TopoDS::Edge(ex.Current()), Standard_False);
818         brB.SameParameter(TopoDS::Edge(ex.Current()), Standard_False);
819       }
820       BRepLib::SameParameter(TopoDS::Edge(ex.Current()),Tolerance);
821     }
822     ex.Next();
823   }
824
825   Done.Clear();
826   BRepAdaptor_Surface BS;
827   for(ex.Init(S,TopAbs_FACE); ex.More(); ex.Next()){
828     const TopoDS_Face& curface = TopoDS::Face(ex.Current());
829     if(!Done.Add(curface)) continue;
830     BS.Initialize(curface);
831     if(BS.GetType() != GeomAbs_Plane) continue;
832     TopExp_Explorer ex2;
833     for(ex2.Init(curface,TopAbs_EDGE); ex2.More(); ex2.Next()){
834       const TopoDS_Edge& E = TopoDS::Edge(ex2.Current());
835       SetEdgeTol(E,curface);
836     }
837   }
838   BRepLib::UpdateTolerances(S);
839 }
840
841 //================================================================
842 //function : SameParameter
843 //WARNING  : New spec DUB LBO 9/9/97.
844 //  Recode in the edge the best tolerance found, 
845 //  for vertex extremities it is required to find something else
846 //================================================================
847 static Standard_Boolean EvalTol(const Handle(Geom2d_Curve)& pc,
848   const Handle(Geom_Surface)& s,
849   const GeomAdaptor_Curve&    gac,
850   const Standard_Real         tol,
851   Standard_Real&              tolbail)
852 {
853   Standard_Integer ok = 0;
854   Standard_Real f = gac.FirstParameter();
855   Standard_Real l = gac.LastParameter();
856   Extrema_LocateExtPC Projector;
857   Projector.Initialize(gac,f,l,tol);
858   Standard_Real u,v;
859   gp_Pnt p;
860   tolbail = tol;
861   for(Standard_Integer i = 1; i <= 5; i++){
862     Standard_Real t = i/6.;
863     t = (1.-t) * f + t * l;
864     pc->Value(t).Coord(u,v);
865     p = s->Value(u,v);
866     Projector.Perform(p,t);
867     if (Projector.IsDone()) {
868       Standard_Real dist2 = Projector.SquareDistance();
869       if(dist2 > tolbail * tolbail) tolbail = sqrt (dist2);
870       ok++;
871     }
872   }
873   return (ok > 2);
874 }
875
876 static Standard_Real ComputeTol(const Handle(Adaptor3d_HCurve)& c3d,
877   const Handle(Adaptor2d_HCurve2d)& c2d,
878   const Handle(Adaptor3d_HSurface)& surf,
879   const Standard_Integer        nbp)
880
881 {
882
883   TColStd_Array1OfReal dist(1,nbp+10);
884   dist.Init(-1.);
885
886   Adaptor3d_CurveOnSurface  cons(c2d,surf);
887   Standard_Real d2 = 0.;
888   Standard_Real first = c3d->FirstParameter();
889   Standard_Real last  = c3d->LastParameter();
890   Standard_Integer i = 0;
891   for(i = 0; i <= nbp; i++){
892     const Standard_Real t = IntToReal(i)/IntToReal(nbp);
893     const Standard_Real u = first*(1.-t) + last*t;
894     gp_Pnt Pc3d = c3d->Value(u);
895     gp_Pnt Pcons = cons.Value(u);
896     if (Precision::IsInfinite(Pcons.X()) ||
897       Precision::IsInfinite(Pcons.Y()) ||
898       Precision::IsInfinite(Pcons.Z())) {
899         d2=Precision::Infinite();
900         break;
901     }
902     Standard_Real temp = Pc3d.SquareDistance(Pcons);
903
904
905     dist(i+1) = temp;
906
907
908     if(temp > d2) d2 = temp;
909   }
910
911
912   Standard_Boolean ana = Standard_False;
913   Standard_Real D2 = 0;
914   Standard_Integer N1 = 0;
915   Standard_Integer N2 = 0;
916   Standard_Integer N3 = 0;
917
918   for( i = 1; i<= nbp+10; i++)
919     if( dist(i) > 0 ) {
920       if( dist(i) < 1.0 ) N1++;
921       else N2++;
922     }
923
924     if( N1 > N2 && N2 != 0 ) N3 = 100*N2/(N1+N2);
925     if( N3 < 10 && N3 != 0 ) {
926       ana = Standard_True;
927       for( i = 1; i<= nbp+10; i++)
928         if( dist(i) > 0 && dist(i) < 1.0 )
929           if( dist(i) > D2 ) D2 = dist(i);
930     }
931
932     //d2 = 1.5*sqrt(d2);
933     d2 = (!ana) ? 1.5*sqrt(d2) : 1.5*sqrt(D2);
934     if(d2<1.e-7) d2 = 1.e-7;
935
936     return d2;
937 }
938
939 void BRepLib::SameParameter(const TopoDS_Edge&  AnEdge,
940   const Standard_Real Tolerance)
941 {
942   if (BRep_Tool::SameParameter(AnEdge)) return;
943
944   const Standard_Integer NCONTROL = 22;
945
946   Handle(GeomAdaptor_HCurve) HC = new GeomAdaptor_HCurve();
947   Handle(Geom2dAdaptor_HCurve) HC2d = new Geom2dAdaptor_HCurve();
948   Handle(GeomAdaptor_HSurface) HS = new GeomAdaptor_HSurface();
949   GeomAdaptor_Curve& GAC = HC->ChangeCurve();
950   Geom2dAdaptor_Curve& GAC2d = HC2d->ChangeCurve2d();
951   GeomAdaptor_Surface& GAS = HS->ChangeSurface();
952   Standard_Real f3d =0.,l3d =0.;
953   TopLoc_Location L3d;
954   Handle(Geom_Curve) C3d;
955
956   const Handle(BRep_TEdge)& TE = *((Handle(BRep_TEdge)*) &AnEdge.TShape());
957   BRep_ListOfCurveRepresentation& CList = TE->ChangeCurves();
958   BRep_ListIteratorOfListOfCurveRepresentation It(CList);
959
960   Standard_Boolean NotDone = Standard_True;
961
962   while (NotDone && It.More()) {
963     Handle(BRep_GCurve) GCurve = Handle(BRep_GCurve)::DownCast(It.Value());
964     if (!GCurve.IsNull() && GCurve->IsCurve3D()) {
965       C3d = GCurve->Curve3D() ;
966       f3d = GCurve->First();
967       l3d = GCurve->Last();
968       L3d = GCurve->Location() ;
969       NotDone = Standard_False;
970     } 
971     It.Next() ;
972   }
973
974   if(C3d.IsNull()) return;
975
976   // modified by NIZHNY-OCC486  Tue Aug 27 17:15:13 2002 :
977   Standard_Boolean m_TrimmedPeriodical = Standard_False;
978   Handle(Standard_Type) TheType = C3d->DynamicType();
979   if( TheType == STANDARD_TYPE(Geom_TrimmedCurve))
980   {
981     Handle(Geom_Curve) gtC (Handle(Geom_TrimmedCurve)::DownCast (C3d)->BasisCurve());
982     m_TrimmedPeriodical = gtC->IsPeriodic();
983   }
984   // modified by NIZHNY-OCC486  Tue Aug 27 17:15:17 2002 .
985
986   BRep_Builder B;
987   if(!C3d->IsPeriodic()) {
988     Standard_Real Udeb = C3d->FirstParameter();
989     Standard_Real Ufin = C3d->LastParameter();
990     // modified by NIZHNY-OCC486  Tue Aug 27 17:17:14 2002 :
991     //if (Udeb > f3d) f3d = Udeb;
992     //if (l3d > Ufin) l3d = Ufin;
993     if(!m_TrimmedPeriodical)
994     {
995       if (Udeb > f3d) f3d = Udeb;
996       if (l3d > Ufin) l3d = Ufin;
997     }
998     // modified by NIZHNY-OCC486  Tue Aug 27 17:17:55 2002 .
999   }
1000   if(!L3d.IsIdentity()){
1001     C3d = Handle(Geom_Curve)::DownCast(C3d->Transformed(L3d.Transformation()));
1002   }
1003   GAC.Load(C3d,f3d,l3d);
1004
1005   Standard_Boolean IsSameP = 1;
1006   Standard_Real maxdist = 0.;
1007
1008   //  Modified by skv - Thu Jun  3 12:39:19 2004 OCC5898 Begin
1009   Standard_Real anEdgeTol = BRep_Tool::Tolerance(AnEdge);
1010   //  Modified by skv - Thu Jun  3 12:39:20 2004 OCC5898 End
1011   Standard_Boolean SameRange = BRep_Tool::SameRange(AnEdge);
1012   Standard_Boolean YaPCu = Standard_False;
1013   It.Initialize(CList);
1014
1015   while (It.More()) {
1016     Standard_Boolean isANA = Standard_False;
1017     Standard_Boolean isBSP = Standard_False;
1018     Handle(BRep_GCurve) GCurve = Handle(BRep_GCurve)::DownCast(It.Value());
1019     Handle(Geom2d_Curve) PC[2];
1020     Handle(Geom_Surface) S;
1021     if (!GCurve.IsNull() && GCurve->IsCurveOnSurface()) {
1022       YaPCu = Standard_True;
1023       PC[0] = GCurve->PCurve();
1024       TopLoc_Location PCLoc = GCurve->Location();
1025       S = GCurve->Surface();
1026       if (!PCLoc.IsIdentity() ) {
1027         S = Handle(Geom_Surface)::DownCast(S->Transformed(PCLoc.Transformation()));
1028       }
1029
1030       GAS.Load(S);
1031       if (GCurve->IsCurveOnClosedSurface()) {
1032         PC[1] = GCurve->PCurve2();
1033       }
1034
1035       // Eval tol2d to compute SameRange
1036       Standard_Real UResol = Max(GAS.UResolution(Tolerance), Precision::PConfusion());
1037       Standard_Real VResol = Max(GAS.VResolution(Tolerance), Precision::PConfusion());
1038       Standard_Real Tol2d  = Min(UResol, VResol);
1039       for(Standard_Integer i = 0; i < 2; i++){
1040         Handle(Geom2d_Curve) curPC = PC[i];
1041         Standard_Boolean updatepc = 0;
1042         if(curPC.IsNull()) break;
1043         if(!SameRange){
1044           GeomLib::SameRange(Tol2d,
1045             PC[i],GCurve->First(),GCurve->Last(),
1046             f3d,l3d,curPC);
1047
1048           updatepc = (curPC != PC[i]);
1049
1050         }
1051         Standard_Boolean goodpc = 1;
1052         GAC2d.Load(curPC,f3d,l3d);
1053
1054         Standard_Real error = ComputeTol(HC, HC2d, HS, NCONTROL);
1055
1056         if(GAC2d.GetType() == GeomAbs_BSplineCurve && 
1057           GAC2d.Continuity() == GeomAbs_C0) {
1058             Handle(Geom2d_BSplineCurve) bs2d = GAC2d.BSpline();
1059             Handle(Geom2d_BSplineCurve) bs2dsov = bs2d;
1060             Standard_Real fC0 = bs2d->FirstParameter(), lC0 = bs2d->LastParameter();
1061             Standard_Boolean repar = Standard_True;
1062             gp_Pnt2d OriginPoint;
1063             bs2d->D0(fC0, OriginPoint);
1064             Geom2dConvert::C0BSplineToC1BSplineCurve(bs2d, Tol2d);
1065             isBSP = Standard_True; 
1066
1067             if(bs2d->IsPeriodic()) { // -------- IFV, Jan 2000
1068               gp_Pnt2d NewOriginPoint;
1069               bs2d->D0(bs2d->FirstParameter(), NewOriginPoint);
1070               if(Abs(OriginPoint.X() - NewOriginPoint.X()) > Precision::PConfusion() ||
1071                 Abs(OriginPoint.Y() - NewOriginPoint.Y()) > Precision::PConfusion()    ) {
1072
1073                   TColStd_Array1OfReal Knotbs2d (1, bs2d->NbKnots());
1074                   bs2d->Knots(Knotbs2d);
1075
1076                   for(Standard_Integer Index = 1; Index <= bs2d->NbKnots(); Index++) {
1077                     bs2d->D0(Knotbs2d(Index), NewOriginPoint);
1078                     if(Abs(OriginPoint.X() - NewOriginPoint.X()) > Precision::PConfusion() ||
1079                       Abs(OriginPoint.Y() - NewOriginPoint.Y()) > Precision::PConfusion()    ) continue;
1080
1081                     bs2d->SetOrigin(Index);
1082                     break;
1083                   }
1084               }
1085             }
1086
1087             if(bs2d->Continuity() == GeomAbs_C0) {
1088               Standard_Real tolbail;
1089               if(EvalTol(curPC,S,GAC,Tolerance,tolbail)){
1090                 bs2d = bs2dsov;
1091                 Standard_Real UResbail = GAS.UResolution(tolbail);
1092                 Standard_Real VResbail = GAS.VResolution(tolbail);
1093                 Standard_Real Tol2dbail  = Min(UResbail,VResbail);
1094                 bs2d->D0(bs2d->FirstParameter(), OriginPoint); 
1095
1096                 Standard_Integer nbp = bs2d->NbPoles();
1097                 TColgp_Array1OfPnt2d poles(1,nbp);
1098                 bs2d->Poles(poles);
1099                 gp_Pnt2d p = poles(1), p1;
1100                 Standard_Real d = Precision::Infinite();
1101                 for(Standard_Integer ip = 2; ip <= nbp; ip++) {
1102                   p1 = poles(ip);
1103                   d = Min(d,p.SquareDistance(p1));
1104                   p = p1;
1105                 }
1106                 d = sqrt(d)*.1;
1107
1108                 Tol2dbail = Max(Min(Tol2dbail,d),Tol2d);
1109
1110                 Geom2dConvert::C0BSplineToC1BSplineCurve(bs2d,Tol2dbail);
1111
1112                 if(bs2d->IsPeriodic()) { // -------- IFV, Jan 2000
1113                   gp_Pnt2d NewOriginPoint;
1114                   bs2d->D0(bs2d->FirstParameter(), NewOriginPoint);
1115                   if(Abs(OriginPoint.X() - NewOriginPoint.X()) > Precision::PConfusion() ||
1116                     Abs(OriginPoint.Y() - NewOriginPoint.Y()) > Precision::PConfusion()    ) {
1117
1118                       TColStd_Array1OfReal Knotbs2d (1, bs2d->NbKnots());
1119                       bs2d->Knots(Knotbs2d);
1120
1121                       for(Standard_Integer Index = 1; Index <= bs2d->NbKnots(); Index++) {
1122                         bs2d->D0(Knotbs2d(Index), NewOriginPoint);
1123                         if(Abs(OriginPoint.X() - NewOriginPoint.X()) > Precision::PConfusion() ||
1124                           Abs(OriginPoint.Y() - NewOriginPoint.Y()) > Precision::PConfusion()    ) continue;
1125
1126                         bs2d->SetOrigin(Index);
1127                         break;
1128                       }
1129                   }
1130                 }
1131
1132
1133                 if(bs2d->Continuity() == GeomAbs_C0) {
1134                   goodpc = 1;
1135                   bs2d = bs2dsov;
1136                   repar = Standard_False;
1137                 }
1138               }
1139               else goodpc = 0;
1140             }
1141
1142             if(goodpc){
1143               if(repar) {
1144                 Standard_Integer NbKnots = bs2d->NbKnots();
1145                 TColStd_Array1OfReal Knots(1,NbKnots);
1146                 bs2d->Knots(Knots);
1147                 //          BSplCLib::Reparametrize(f3d,l3d,Knots);
1148                 BSplCLib::Reparametrize(fC0,lC0,Knots);
1149                 bs2d->SetKnots(Knots);
1150                 GAC2d.Load(bs2d,f3d,l3d);
1151                 curPC = bs2d;
1152                 Standard_Boolean updatepcsov = updatepc;
1153                 updatepc = Standard_True;
1154
1155                 Standard_Real error1 = ComputeTol(HC, HC2d, HS, NCONTROL);
1156                 if(error1 > error) {
1157                   bs2d = bs2dsov;
1158                   GAC2d.Load(bs2d,f3d,l3d);
1159                   curPC = bs2d;
1160                   updatepc = updatepcsov;
1161                   isANA = Standard_True;
1162                 }
1163                 else {
1164                   error = error1;
1165                 }
1166               }
1167
1168               //check, if new BSpline "good" or not --------- IFV, Jan of 2000
1169               GeomAbs_Shape cont = bs2d->Continuity();
1170               Standard_Boolean IsBad = Standard_False;
1171
1172               if(cont > GeomAbs_C0 && error > Max(1.e-3,Tolerance)) {
1173                 Standard_Integer NbKnots = bs2d->NbKnots();
1174                 TColStd_Array1OfReal Knots(1,NbKnots);
1175                 bs2d->Knots(Knots);
1176                 Standard_Real critratio = 10.; 
1177                 Standard_Real dtprev = Knots(2) - Knots(1), dtratio = 1.;
1178                 Standard_Real dtmin = dtprev;
1179                 Standard_Real dtcur;
1180                 for(Standard_Integer j = 2; j < NbKnots; j++) {
1181                   dtcur = Knots(j+1) - Knots(j);
1182                   dtmin = Min(dtmin, dtcur);
1183
1184                   if(IsBad) continue;
1185
1186                   if(dtcur > dtprev) dtratio = dtcur/dtprev;
1187                   else dtratio = dtprev/dtcur;
1188                   if(dtratio > critratio) {IsBad = Standard_True;}
1189                   dtprev = dtcur;
1190
1191                 }
1192                 if(IsBad) {
1193                   // To avoid failures in Approx_CurvilinearParameter 
1194                   bs2d->Resolution(Max(1.e-3,Tolerance), dtcur);
1195                   if(dtmin < dtcur) IsBad = Standard_False;
1196                 }
1197               }
1198
1199
1200               if(IsBad ) { //if BSpline "bad", try to reparametrize it
1201                 // by its curve length
1202
1203                 //            GeomAbs_Shape cont = bs2d->Continuity();
1204                 if(cont > GeomAbs_C2) cont = GeomAbs_C2;
1205                 Standard_Integer maxdeg = bs2d->Degree();
1206                 if(maxdeg == 1) maxdeg = 14;
1207                 Approx_CurvilinearParameter AppCurPar(HC2d, HS, Max(1.e-3,Tolerance),
1208                   cont, maxdeg, 10);
1209                 if(AppCurPar.IsDone() || AppCurPar.HasResult()) {
1210                   bs2d = AppCurPar.Curve2d1();
1211                   GAC2d.Load(bs2d,f3d,l3d);
1212                   curPC = bs2d;
1213
1214                   if(Abs(bs2d->FirstParameter() - fC0) > Tol2d ||
1215                     Abs(bs2d->LastParameter() - lC0) > Tol2d    ) {
1216                       Standard_Integer NbKnots = bs2d->NbKnots();
1217                       TColStd_Array1OfReal Knots(1,NbKnots);
1218                       bs2d->Knots(Knots);
1219                       //                  BSplCLib::Reparametrize(f3d,l3d,Knots);
1220                       BSplCLib::Reparametrize(fC0,lC0,Knots);
1221                       bs2d->SetKnots(Knots);
1222                       GAC2d.Load(bs2d,f3d,l3d);
1223                       curPC = bs2d;
1224
1225                   }
1226                 }
1227               }
1228
1229
1230             }
1231         }
1232
1233
1234         if(goodpc){
1235           //      Approx_SameParameter SameP(HC,HC2d,HS,Tolerance);
1236           Standard_Real aTol = (isANA && isBSP) ? 1.e-7 : Tolerance;
1237           const Handle(Adaptor3d_HCurve)& aHCurv = HC; // to avoid ambiguity
1238           const Handle(Adaptor2d_HCurve2d)& aHCurv2d = HC2d; // to avoid ambiguity
1239           Approx_SameParameter SameP(aHCurv,aHCurv2d,HS,aTol);
1240
1241           if (SameP.IsSameParameter()) {
1242             maxdist = Max(maxdist,SameP.TolReached());
1243             if(updatepc){
1244               if (i == 0) GCurve->PCurve(curPC);
1245               else GCurve->PCurve2(curPC);
1246             }
1247           }
1248           else if (SameP.IsDone()) {
1249             Standard_Real tolreached = SameP.TolReached();
1250             if(tolreached <= error) {
1251               curPC = SameP.Curve2d();
1252               updatepc = Standard_True;
1253               maxdist = Max(maxdist,tolreached);
1254             }
1255             else {
1256               maxdist = Max(maxdist, error);
1257             }
1258             if(updatepc){
1259               if (i == 0) GCurve->PCurve(curPC);
1260               else GCurve->PCurve2(curPC);
1261             }
1262           }
1263           else
1264           {
1265             //Approx_SameParameter has failed.
1266             //Consequently, the situation might be,
1267             //when 3D and 2D-curve do not have same-range.
1268             GeomLib::SameRange( Tol2d, PC[i], 
1269                                 GCurve->First(), GCurve->Last(),
1270                                 f3d,l3d,curPC);
1271
1272             if (i == 0) GCurve->PCurve(curPC);
1273             else GCurve->PCurve2(curPC);
1274
1275             IsSameP = 0;
1276           }
1277
1278         }
1279         else IsSameP = 0;
1280
1281         //  Modified by skv - Thu Jun  3 12:39:19 2004 OCC5898 Begin
1282         if (!IsSameP) {
1283           if (anEdgeTol >= error) {
1284             maxdist = Max(maxdist, anEdgeTol);
1285             IsSameP = Standard_True;
1286           }
1287         }
1288         //  Modified by skv - Thu Jun  3 12:39:20 2004 OCC5898 End
1289       }
1290     }
1291     It.Next() ;
1292   }
1293   B.Range(AnEdge,f3d,l3d);
1294   B.SameRange(AnEdge,Standard_True);
1295   if ( IsSameP) {
1296     // Reduce eventually the tolerance of the edge, as
1297     // all its representations are processed (except for some associated
1298     // to planes and not stored in the edge !) 
1299     // The same cannot be done with vertices that cannot be enlarged 
1300     // or left as is.
1301     if (YaPCu) {
1302       // Avoid setting too small tolerances.
1303       maxdist = Max(maxdist,Precision::Confusion());
1304       TopoDS_Vertex V1,V2;
1305       TopExp::Vertices(AnEdge,V1,V2);
1306       if (!V1.IsNull())
1307         B.UpdateVertex(V1,maxdist);
1308       if (!V2.IsNull())
1309         B.UpdateVertex(V2,maxdist);
1310       TE->Modified(Standard_True);
1311       TE->Tolerance(maxdist);
1312     }
1313     B.SameParameter(AnEdge,Standard_True);
1314   }
1315 }
1316
1317 //=======================================================================
1318 //function : UpdateTolerances
1319 //purpose  : 
1320 //=======================================================================
1321 void  BRepLib::UpdateTolerances(const TopoDS_Shape& aShape,
1322   const Standard_Boolean verifyTolerance) 
1323 {
1324
1325   // Harmonize tolerances
1326   // with rule Tolerance(VERTEX)>=Tolerance(EDGE)>=Tolerance(FACE)
1327   BRep_Builder B;
1328   Standard_Real tol=0;
1329   if (verifyTolerance) {
1330     // Set tolerance to its minimum value
1331     Handle(Geom_Surface) S;
1332     TopLoc_Location l;
1333     TopExp_Explorer ex;
1334     Bnd_Box aB;
1335     Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax, dMax;
1336     for (ex.Init(aShape, TopAbs_FACE); ex.More(); ex.Next()) {
1337       const TopoDS_Face& curf=TopoDS::Face(ex.Current());
1338       S = BRep_Tool::Surface(curf, l);
1339       if (!S.IsNull()) {
1340         aB.SetVoid();
1341         BRepBndLib::Add(curf,aB);
1342         if (S->DynamicType() == STANDARD_TYPE(Geom_RectangularTrimmedSurface)) {
1343           S = Handle(Geom_RectangularTrimmedSurface)::DownCast (S)->BasisSurface();
1344         }
1345         GeomAdaptor_Surface AS(S);
1346         switch (AS.GetType()) {
1347         case GeomAbs_Plane: 
1348         case GeomAbs_Cylinder: 
1349         case GeomAbs_Cone: 
1350           {
1351             tol=Precision::Confusion();
1352             break;
1353           }
1354         case GeomAbs_Sphere: 
1355         case GeomAbs_Torus: 
1356           {
1357             tol=Precision::Confusion()*2;
1358             break;
1359           }
1360         default:
1361           tol=Precision::Confusion()*4;
1362         }
1363         if (!aB.IsWhole()) {
1364           aB.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
1365           dMax=1.;
1366           if (!aB.IsOpenXmin() && !aB.IsOpenXmax()) dMax=aXmax-aXmin;
1367           if (!aB.IsOpenYmin() && !aB.IsOpenYmax()) aYmin=aYmax-aYmin;
1368           if (!aB.IsOpenZmin() && !aB.IsOpenZmax()) aZmin=aZmax-aZmin;
1369           if (aYmin>dMax) dMax=aYmin;
1370           if (aZmin>dMax) dMax=aZmin;
1371           tol=tol*dMax;
1372           // Do not process tolerances > 1.
1373           if (tol>1.) tol=0.99;
1374         }
1375         const Handle(BRep_TFace)& Tf = *((Handle(BRep_TFace)*)&curf.TShape());
1376         Tf->Tolerance(tol);
1377       }
1378     }
1379   }
1380
1381   //Process edges
1382   TopTools_IndexedDataMapOfShapeListOfShape parents;
1383   TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, parents);
1384   TopTools_ListIteratorOfListOfShape lConx;
1385   Standard_Integer iCur;
1386   for (iCur=1; iCur<=parents.Extent(); iCur++) {
1387     tol=0;
1388     for (lConx.Initialize(parents(iCur)); lConx.More(); lConx.Next()) {
1389       tol=Max(tol, BRep_Tool::Tolerance(TopoDS::Face(lConx.Value())));
1390     }
1391     // Update can only increase tolerance, so if the edge has a greater
1392     //  tolerance than its faces it is not concerned
1393     B.UpdateEdge(TopoDS::Edge(parents.FindKey(iCur)), tol);
1394   }
1395
1396   //Vertices are processed
1397   parents.Clear();
1398   TopExp::MapShapesAndAncestors(aShape, TopAbs_VERTEX, TopAbs_EDGE, parents);
1399   TColStd_MapOfTransient Initialized;
1400   TopTools_MapOfShape Done;
1401   Standard_Integer nbV = parents.Extent();
1402   for (iCur=1; iCur<=nbV; iCur++) {
1403     tol=0;
1404     Done.Clear();
1405     const TopoDS_Vertex& V = TopoDS::Vertex(parents.FindKey(iCur));
1406     Bnd_Box box;
1407     box.Add(BRep_Tool::Pnt(V));
1408     gp_Pnt p3d;
1409     for (lConx.Initialize(parents(iCur)); lConx.More(); lConx.Next()) {
1410       const TopoDS_Edge& E = TopoDS::Edge(lConx.Value());
1411       if(!Done.Add(E)) continue;
1412       tol=Max(tol, BRep_Tool::Tolerance(E));
1413       if(!BRep_Tool::SameRange(E)) continue;
1414       Standard_Real par = BRep_Tool::Parameter(V,E);
1415       Handle(BRep_TEdge)& TE = *((Handle(BRep_TEdge)*)&E.TShape());
1416       BRep_ListIteratorOfListOfCurveRepresentation itcr(TE->Curves());
1417       const TopLoc_Location& Eloc = E.Location();
1418       while (itcr.More()) {
1419         // For each CurveRepresentation, check the provided parameter
1420         const Handle(BRep_CurveRepresentation)& cr = itcr.Value();
1421         const TopLoc_Location& loc = cr->Location();
1422         TopLoc_Location L = (Eloc * loc);
1423         if (cr->IsCurve3D()) {
1424           const Handle(Geom_Curve)& C = cr->Curve3D();
1425           if (!C.IsNull()) { // edge non degenerated
1426             p3d = C->Value(par);
1427             p3d.Transform(L.Transformation());
1428             box.Add(p3d);
1429           }
1430         }
1431         else if (cr->IsCurveOnSurface()) {
1432           const Handle(Geom_Surface)& Su = cr->Surface();
1433           const Handle(Geom2d_Curve)& PC = cr->PCurve();
1434           Handle(Geom2d_Curve) PC2;
1435           if (cr->IsCurveOnClosedSurface()) {
1436             PC2 = cr->PCurve2();
1437           }
1438           gp_Pnt2d p2d = PC->Value(par);
1439           p3d = Su->Value(p2d.X(),p2d.Y());
1440           p3d.Transform(L.Transformation());
1441           box.Add(p3d);
1442           if (!PC2.IsNull()) {
1443             p2d = PC2->Value(par);
1444             p3d = Su->Value(p2d.X(),p2d.Y());
1445             p3d.Transform(L.Transformation());
1446             box.Add(p3d);
1447           }
1448         }
1449         itcr.Next();
1450       }
1451     }
1452     Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
1453     box.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
1454     aXmax -= aXmin; aYmax -= aYmin; aZmax -= aZmin;
1455     tol = Max(tol,sqrt(aXmax*aXmax+aYmax*aYmax+aZmax*aZmax));
1456     tol += 2.*Epsilon(tol);
1457     if (verifyTolerance) {
1458       // ASet minimum value of the tolerance 
1459       // Attention to sharing of the vertex by other shapes
1460       const Handle(BRep_TVertex)& TV = *((Handle(BRep_TVertex)*)&V.TShape());
1461       if (Initialized.Add(TV)) 
1462         TV->Tolerance(tol);
1463       else 
1464         B.UpdateVertex(V, tol);
1465     }
1466     else {
1467       // Update can only increase tolerance, so if the edge has a greater
1468       //  tolerance than its faces it is not concerned
1469       B.UpdateVertex(V, tol);
1470     }
1471   }
1472 }
1473
1474 //=======================================================================
1475 //function : UpdateInnerTolerances
1476 //purpose  : 
1477 //=======================================================================
1478 void  BRepLib::UpdateInnerTolerances(const TopoDS_Shape& aShape)
1479 {
1480   TopTools_IndexedDataMapOfShapeListOfShape EFmap;
1481   TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, EFmap);
1482   BRep_Builder BB;
1483   for (Standard_Integer i = 1; i <= EFmap.Extent(); i++)
1484   {
1485     TopoDS_Edge anEdge = TopoDS::Edge(EFmap.FindKey(i));
1486     TopoDS_Vertex V1, V2;
1487     TopExp::Vertices(anEdge, V1, V2);
1488     Standard_Real fpar, lpar;
1489     BRep_Tool::Range(anEdge, fpar, lpar);
1490     Standard_Real TolEdge = BRep_Tool::Tolerance(anEdge);
1491     gp_Pnt Pnt1, Pnt2;
1492     Handle(BRepAdaptor_HCurve) anHCurve = new BRepAdaptor_HCurve();
1493     anHCurve->ChangeCurve().Initialize(anEdge);
1494     if (!V1.IsNull())
1495       Pnt1 = BRep_Tool::Pnt(V1);
1496     if (!V2.IsNull())
1497       Pnt2 = BRep_Tool::Pnt(V2);
1498     
1499     if (!BRep_Tool::Degenerated(anEdge) &&
1500         EFmap(i).Extent() > 0)
1501     {
1502       NCollection_Sequence<Handle(Adaptor3d_HCurve)> theRep;
1503       theRep.Append(anHCurve);
1504       TopTools_ListIteratorOfListOfShape itl(EFmap(i));
1505       for (; itl.More(); itl.Next())
1506       {
1507         const TopoDS_Face& aFace = TopoDS::Face(itl.Value());
1508         Handle(BRepAdaptor_HCurve) anHCurvOnSurf = new BRepAdaptor_HCurve();
1509         anHCurvOnSurf->ChangeCurve().Initialize(anEdge, aFace);
1510         theRep.Append(anHCurvOnSurf);
1511       }
1512       
1513       const Standard_Integer NbSamples = (BRep_Tool::SameParameter(anEdge))? 23 : 2;
1514       Standard_Real delta = (lpar - fpar)/(NbSamples-1);
1515       Standard_Real MaxDist = 0.;
1516       for (Standard_Integer j = 2; j <= theRep.Length(); j++)
1517       {
1518         for (Standard_Integer k = 0; k <= NbSamples; k++)
1519         {
1520           Standard_Real ParamOnCenter = (k == NbSamples)? lpar :
1521             fpar + k*delta;
1522           gp_Pnt Center = theRep(1)->Value(ParamOnCenter);
1523           Standard_Real ParamOnCurve = (BRep_Tool::SameParameter(anEdge))? ParamOnCenter
1524             : ((k == 0)? theRep(j)->FirstParameter() : theRep(j)->LastParameter());
1525           gp_Pnt aPoint = theRep(j)->Value(ParamOnCurve);
1526           Standard_Real aDist = Center.Distance(aPoint);
1527           //aDist *= 1.1;
1528           aDist += 2.*Epsilon(aDist);
1529           if (aDist > MaxDist)
1530             MaxDist = aDist;
1531
1532           //Update tolerances of vertices
1533           if (k == 0 && !V1.IsNull())
1534           {
1535             Standard_Real aDist1 = Pnt1.Distance(aPoint);
1536             aDist1 += 2.*Epsilon(aDist1);
1537             BB.UpdateVertex(V1, aDist1);
1538           }
1539           if (k == NbSamples && !V2.IsNull())
1540           {
1541             Standard_Real aDist2 = Pnt2.Distance(aPoint);
1542             aDist2 += 2.*Epsilon(aDist2);
1543             BB.UpdateVertex(V2, aDist2);
1544           }
1545         }
1546       }
1547       BB.UpdateEdge(anEdge, MaxDist);
1548     }
1549     TolEdge = BRep_Tool::Tolerance(anEdge);
1550     if (!V1.IsNull())
1551     {
1552       gp_Pnt End1 = anHCurve->Value(fpar);
1553       Standard_Real dist1 = Pnt1.Distance(End1);
1554       dist1 += 2.*Epsilon(dist1);
1555       BB.UpdateVertex(V1, Max(dist1, TolEdge));
1556     }
1557     if (!V2.IsNull())
1558     {
1559       gp_Pnt End2 = anHCurve->Value(lpar);
1560       Standard_Real dist2 = Pnt2.Distance(End2);
1561       dist2 += 2.*Epsilon(dist2);
1562       BB.UpdateVertex(V2, Max(dist2, TolEdge));
1563     }
1564   }
1565 }
1566
1567 //=======================================================================
1568 //function : OrientClosedSolid
1569 //purpose  : 
1570 //=======================================================================
1571 Standard_Boolean BRepLib::OrientClosedSolid(TopoDS_Solid& solid) 
1572 {
1573   // Set material inside the solid
1574   BRepClass3d_SolidClassifier where(solid);
1575   where.PerformInfinitePoint(Precision::Confusion());
1576   if (where.State()==TopAbs_IN) {
1577     solid.Reverse();
1578   }
1579   else if (where.State()==TopAbs_ON || where.State()==TopAbs_UNKNOWN) 
1580     return Standard_False;
1581
1582   return Standard_True;
1583 }
1584 //=======================================================================
1585 //function : tgtfaces
1586 //purpose  : check the angle at the border between two squares.
1587 //           Two shares should have a shared front edge.
1588 //=======================================================================
1589 static GeomAbs_Shape tgtfaces(const TopoDS_Edge& Ed,
1590   const TopoDS_Face& F1,
1591   const TopoDS_Face& F2,
1592   const Standard_Real theAngleTol,
1593   const Standard_Boolean couture)
1594 {
1595   // Check if pcurves exist on both faces of edge
1596   Standard_Real aFirst,aLast;
1597   Handle(Geom2d_Curve) aCurve;
1598   aCurve = BRep_Tool::CurveOnSurface(Ed,F1,aFirst,aLast);
1599   if(aCurve.IsNull())
1600     return GeomAbs_C0;
1601   aCurve = BRep_Tool::CurveOnSurface(Ed,F2,aFirst,aLast);
1602   if(aCurve.IsNull())
1603     return GeomAbs_C0;
1604   
1605   Standard_Real u;
1606   TopoDS_Edge E = Ed;
1607   BRepAdaptor_Surface aBAS1(F1,Standard_False);
1608   BRepAdaptor_Surface aBAS2(F2,Standard_False);
1609   
1610   // seam edge on elementary surface is always CN
1611   Standard_Boolean isElementary =
1612     (aBAS1.Surface().Surface()->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
1613      aBAS1.Surface().Surface()->IsKind(STANDARD_TYPE(Geom_ElementarySurface)));
1614   if (couture && isElementary)
1615   {
1616     return GeomAbs_CN;
1617   }
1618   
1619   Handle(BRepAdaptor_HSurface) HS1 = new BRepAdaptor_HSurface (aBAS1);
1620   Handle(BRepAdaptor_HSurface) HS2;
1621   if(couture) HS2 = HS1;
1622   else HS2 = new BRepAdaptor_HSurface(aBAS2);
1623   //case when edge lies on the one face
1624   
1625   E.Orientation(TopAbs_FORWARD);
1626   Handle(BRepAdaptor_HCurve2d) HC2d1 = new BRepAdaptor_HCurve2d();
1627   HC2d1->ChangeCurve2d().Initialize(E,F1);
1628   if(couture) E.Orientation(TopAbs_REVERSED);
1629   Handle(BRepAdaptor_HCurve2d) HC2d2 = new BRepAdaptor_HCurve2d();
1630   HC2d2->ChangeCurve2d().Initialize(E,F2);
1631   Adaptor3d_CurveOnSurface C1(HC2d1,HS1);
1632   Adaptor3d_CurveOnSurface C2(HC2d2,HS2);
1633
1634   Standard_Boolean rev1 = (F1.Orientation() == TopAbs_REVERSED);
1635   Standard_Boolean rev2 = (F2.Orientation() == TopAbs_REVERSED);
1636   Standard_Real f,l,eps;
1637   BRep_Tool::Range(E,f,l);
1638   Extrema_LocateExtPC ext;
1639   Standard_Boolean IsInitialized = Standard_False;
1640
1641   eps = (l - f)/100.;
1642   f += eps; // to avoid calculations on  
1643   l -= eps; // points of pointed squares.
1644   gp_Pnt2d p;
1645   gp_Pnt pp1,pp2;//,PP;
1646   gp_Vec du1, dv1, d2u1, d2v1, d2uv1;
1647   gp_Vec du2, dv2, d2u2, d2v2, d2uv2;
1648   gp_Vec d1,d2;
1649   Standard_Real uu, vv, norm;
1650
1651   Standard_Integer i;
1652   GeomAbs_Shape aCont = (isElementary ? GeomAbs_CN : GeomAbs_C2);
1653   for(i = 0; i<= 20 && aCont > GeomAbs_C0; i++)
1654   {
1655     // First suppose that this is sameParameter
1656     u = f + (l-f)*i/20;
1657
1658     // take derivatives of surfaces at the same u, and compute normals
1659     HC2d1->D0(u,p);
1660     HS1->D2 (p.X(), p.Y(), pp1, du1, dv1, d2u1, d2v1, d2uv1);
1661     d1 = (du1.Crossed(dv1));
1662     norm = d1.Magnitude(); 
1663     if (norm > 1.e-12) d1 /= norm;
1664     else continue; // skip degenerated point
1665     if(rev1) d1.Reverse();
1666
1667     HC2d2->D0(u,p);
1668     HS2->D2 (p.X(), p.Y(), pp2, du2, dv2, d2u2, d2v2, d2uv2);
1669     d2 = (du2.Crossed(dv2));
1670     norm = d2.Magnitude();
1671     if (norm > 1.e-12) d2 /= norm;
1672     else continue; // skip degenerated point
1673     if(rev2) d2.Reverse();
1674
1675     // check 
1676     Standard_Real ang = d1.Angle(d2);
1677
1678     // check special case of precise equality of derivatives,
1679     // occurring when edge connects two faces built on equally 
1680     // defined surfaces (e.g. seam-like edges on periodic surfaces, 
1681     // or planar faces on the same plane)
1682     if (aCont >= GeomAbs_C2 && ang < Precision::Angular() &&
1683         d2u1 .IsEqual (d2u2,  Precision::PConfusion(), Precision::Angular()) &&
1684         d2v1 .IsEqual (d2v2,  Precision::PConfusion(), Precision::Angular()) &&
1685         d2uv1.IsEqual (d2uv2, Precision::PConfusion(), Precision::Angular()))
1686     {
1687       continue;
1688     }
1689
1690     aCont = GeomAbs_G1;
1691
1692     // Refine by projection
1693     if (ang > theAngleTol)
1694     {
1695       if (! IsInitialized ) {
1696         ext.Initialize(C2,f,l,Precision::PConfusion());
1697         IsInitialized = Standard_True;
1698       }      
1699       ext.Perform(pp1,u);
1700       if(ext.IsDone() && ext.IsMin()){
1701         Extrema_POnCurv poc = ext.Point();
1702         Standard_Real v = poc.Parameter();
1703
1704         HC2d2->D0(v,p);
1705         p.Coord(uu,vv);
1706         HS2->D1(p.X(), p.Y(), pp2, du2, dv2);
1707         d2 = (du2.Crossed(dv2));
1708         norm = d2.Magnitude();
1709         if (norm> 1.e-12) d2 /= norm;
1710         else continue; // degenerated point
1711         if(rev2) d2.Reverse();
1712         ang = d1.Angle(d2);
1713       }
1714       if (ang > theAngleTol)
1715         return GeomAbs_C0;
1716     }
1717   }     
1718
1719   return aCont;
1720 }
1721
1722
1723 //=======================================================================
1724 // function : EncodeRegularity
1725 // purpose  : code the regularities on all edges of the shape, boundary of 
1726 //            two faces that do not have it.
1727 //=======================================================================
1728
1729 void BRepLib::EncodeRegularity(const TopoDS_Shape& S,
1730   const Standard_Real TolAng)
1731 {
1732   BRep_Builder B;
1733   TopTools_IndexedDataMapOfShapeListOfShape M;
1734   TopExp::MapShapesAndAncestors(S,TopAbs_EDGE,TopAbs_FACE,M);
1735   TopTools_ListIteratorOfListOfShape It;
1736   TopExp_Explorer Ex;
1737   TopoDS_Face F1,F2;
1738   Standard_Boolean found, couture;
1739   for(Standard_Integer i = 1; i <= M.Extent(); i++){
1740     TopoDS_Edge E = TopoDS::Edge(M.FindKey(i));
1741     found = Standard_False; couture = Standard_False;
1742     F1.Nullify();
1743     for(It.Initialize(M.FindFromIndex(i));It.More() && !found;It.Next()){
1744       if(F1.IsNull()) { F1 = TopoDS::Face(It.Value()); }
1745       else {
1746         if(!F1.IsSame(TopoDS::Face(It.Value()))){
1747           found = Standard_True;
1748           F2 = TopoDS::Face(It.Value());
1749         }
1750       }
1751     }
1752     if (!found && !F1.IsNull()){//is it a sewing edge?
1753       TopAbs_Orientation orE = E.Orientation();
1754       TopoDS_Edge curE;
1755       for(Ex.Init(F1,TopAbs_EDGE);Ex.More() && !found;Ex.Next()){
1756         curE= TopoDS::Edge(Ex.Current());
1757         if(E.IsSame(curE) && orE != curE.Orientation()) {
1758           found = Standard_True;
1759           couture = Standard_True;
1760           F2 = F1;
1761         }
1762       }
1763     }
1764     if(found){
1765       if(BRep_Tool::Continuity(E,F1,F2)<=GeomAbs_C0){
1766
1767         try {
1768           GeomAbs_Shape aCont = tgtfaces(E, F1, F2, TolAng, couture);
1769           B.Continuity(E,F1,F2,aCont);
1770         }
1771         catch(Standard_Failure)
1772         {
1773         }
1774       }
1775     }
1776   }
1777 }
1778
1779 //=======================================================================
1780 // function : EncodeRegularity
1781 // purpose  : code the regularity between 2 faces on an edge 
1782 //=======================================================================
1783
1784 void BRepLib::EncodeRegularity(TopoDS_Edge& E,
1785   const TopoDS_Face& F1,
1786   const TopoDS_Face& F2,
1787   const Standard_Real TolAng)
1788 {
1789   BRep_Builder B;
1790   if(BRep_Tool::Continuity(E,F1,F2)<=GeomAbs_C0){
1791     try {
1792       GeomAbs_Shape aCont = tgtfaces(E, F1, F2, TolAng, F1.IsEqual(F2));
1793       B.Continuity(E,F1,F2,aCont);
1794       
1795     }
1796     catch(Standard_Failure)
1797     {
1798     }
1799   }
1800 }
1801
1802 //=======================================================================
1803 // function : EnsureNormalConsistency
1804 // purpose  : Corrects the normals in Poly_Triangulation of faces.
1805 //              Returns TRUE if any correction is done.
1806 //=======================================================================
1807 Standard_Boolean BRepLib::
1808             EnsureNormalConsistency(const TopoDS_Shape& theShape,
1809                                     const Standard_Real theAngTol,
1810                                     const Standard_Boolean theForceComputeNormals)
1811 {
1812   const Standard_Real aThresDot = cos(theAngTol);
1813
1814   Standard_Boolean aRetVal = Standard_False, isNormalsFound = Standard_False;
1815
1816   // compute normals if they are absent
1817   TopExp_Explorer anExpFace(theShape,TopAbs_FACE);
1818   for (; anExpFace.More(); anExpFace.Next())
1819   {
1820     const TopoDS_Face& aFace = TopoDS::Face(anExpFace.Current());
1821     const Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
1822     if(aSurf.IsNull())
1823       continue;
1824     TopLoc_Location aLoc;
1825     const Handle(Poly_Triangulation)& aPT = BRep_Tool::Triangulation(aFace, aLoc);
1826     if(aPT.IsNull())
1827       continue;
1828     if (!theForceComputeNormals && aPT->HasNormals())
1829     {
1830       isNormalsFound = Standard_True;
1831       continue;
1832     }
1833
1834     GeomLProp_SLProps aSLP(aSurf, 2, Precision::Confusion());
1835     const Standard_Integer anArrDim = 3*aPT->NbNodes();
1836     Handle(TShort_HArray1OfShortReal) aNormArr = new TShort_HArray1OfShortReal(1, anArrDim);
1837     Standard_Integer anNormInd = aNormArr->Lower();
1838     for(Standard_Integer i = aPT->UVNodes().Lower(); i <= aPT->UVNodes().Upper(); i++)
1839     {
1840       const gp_Pnt2d &aP2d = aPT->UVNodes().Value(i);
1841       aSLP.SetParameters(aP2d.X(), aP2d.Y());
1842
1843       gp_XYZ aNorm(0.,0.,0.);
1844       if(!aSLP.IsNormalDefined())
1845       {
1846 #ifdef OCCT_DEBUG
1847         cout << "BRepLib::EnsureNormalConsistency(): Cannot find normal!" << endl;
1848 #endif
1849       }
1850       else
1851       {
1852         aNorm = aSLP.Normal().XYZ();
1853         if (aFace.Orientation() == TopAbs_REVERSED)
1854           aNorm.Reverse();
1855       }
1856       aNormArr->ChangeValue(anNormInd++) = static_cast<Standard_ShortReal>(aNorm.X());
1857       aNormArr->ChangeValue(anNormInd++) = static_cast<Standard_ShortReal>(aNorm.Y());
1858       aNormArr->ChangeValue(anNormInd++) = static_cast<Standard_ShortReal>(aNorm.Z());
1859     }
1860
1861     aRetVal = Standard_True;
1862     isNormalsFound = Standard_True;
1863     aPT->SetNormals(aNormArr);
1864   }
1865
1866   if(!isNormalsFound)
1867   {
1868     return aRetVal;
1869   }
1870
1871   // loop by edges
1872   TopTools_IndexedDataMapOfShapeListOfShape aMapEF;
1873   TopExp::MapShapesAndAncestors(theShape,TopAbs_EDGE,TopAbs_FACE,aMapEF);
1874   for(Standard_Integer anInd = 1; anInd <= aMapEF.Extent(); anInd++)
1875   {
1876     const TopoDS_Edge& anEdg = TopoDS::Edge(aMapEF.FindKey(anInd));
1877     const TopTools_ListOfShape& anEdgList = aMapEF.FindFromIndex(anInd);
1878     if (anEdgList.Extent() != 2)
1879       continue;
1880     TopTools_ListIteratorOfListOfShape anItF(anEdgList);
1881     const TopoDS_Face aFace1 = TopoDS::Face(anItF.Value());
1882     anItF.Next();
1883     const TopoDS_Face aFace2 = TopoDS::Face(anItF.Value());
1884     TopLoc_Location aLoc1, aLoc2;
1885     const Handle(Poly_Triangulation)& aPT1 = BRep_Tool::Triangulation(aFace1, aLoc1);
1886     const Handle(Poly_Triangulation)& aPT2 = BRep_Tool::Triangulation(aFace2, aLoc2);
1887
1888     if(aPT1.IsNull() || aPT2.IsNull())
1889       continue;
1890
1891     if(!aPT1->HasNormals() || !aPT2->HasNormals())
1892       continue;
1893
1894     const Handle(Poly_PolygonOnTriangulation)& aPTEF1 = 
1895                                 BRep_Tool::PolygonOnTriangulation(anEdg, aPT1, aLoc1);
1896     const Handle(Poly_PolygonOnTriangulation)& aPTEF2 = 
1897                                 BRep_Tool::PolygonOnTriangulation(anEdg, aPT2, aLoc2);
1898
1899     TShort_Array1OfShortReal& aNormArr1 = aPT1->ChangeNormals();
1900     TShort_Array1OfShortReal& aNormArr2 = aPT2->ChangeNormals();
1901
1902     for(Standard_Integer anEdgNode = aPTEF1->Nodes().Lower();
1903                          anEdgNode <= aPTEF1->Nodes().Upper(); anEdgNode++)
1904     {
1905       //Number of node
1906       const Standard_Integer aFNodF1 = aPTEF1->Nodes().Value(anEdgNode);
1907       const Standard_Integer aFNodF2 = aPTEF2->Nodes().Value(anEdgNode);
1908
1909       const Standard_Integer aFNorm1FirstIndex = aNormArr1.Lower() + 3*
1910                                                     (aFNodF1 - aPT1->Nodes().Lower());
1911       const Standard_Integer aFNorm2FirstIndex = aNormArr2.Lower() + 3*
1912                                                     (aFNodF2 - aPT2->Nodes().Lower());
1913
1914       gp_XYZ aNorm1(aNormArr1.Value(aFNorm1FirstIndex),
1915                     aNormArr1.Value(aFNorm1FirstIndex+1),
1916                     aNormArr1.Value(aFNorm1FirstIndex+2));
1917       gp_XYZ aNorm2(aNormArr2.Value(aFNorm2FirstIndex),
1918                     aNormArr2.Value(aFNorm2FirstIndex+1),
1919                     aNormArr2.Value(aFNorm2FirstIndex+2));
1920       const Standard_Real aDot = aNorm1 * aNorm2;
1921
1922       if(aDot > aThresDot)
1923       {
1924         gp_XYZ aNewNorm = (aNorm1 + aNorm2).Normalized();
1925         aNormArr1.ChangeValue(aFNorm1FirstIndex) =
1926           aNormArr2.ChangeValue(aFNorm2FirstIndex) =
1927           static_cast<Standard_ShortReal>(aNewNorm.X());
1928         aNormArr1.ChangeValue(aFNorm1FirstIndex+1) =
1929           aNormArr2.ChangeValue(aFNorm2FirstIndex+1) =
1930           static_cast<Standard_ShortReal>(aNewNorm.Y());
1931         aNormArr1.ChangeValue(aFNorm1FirstIndex+2) =
1932           aNormArr2.ChangeValue(aFNorm2FirstIndex+2) =
1933           static_cast<Standard_ShortReal>(aNewNorm.Z());
1934         aRetVal = Standard_True;
1935       }
1936     }
1937   }
1938
1939   return aRetVal;
1940 }
1941
1942 //=======================================================================
1943 //function : SortFaces
1944 //purpose  : 
1945 //=======================================================================
1946
1947 void  BRepLib::SortFaces (const TopoDS_Shape& Sh,
1948   TopTools_ListOfShape& LF)
1949 {
1950   LF.Clear();
1951   TopTools_ListOfShape LTri,LPlan,LCyl,LCon,LSphere,LTor,LOther;
1952   TopExp_Explorer exp(Sh,TopAbs_FACE);
1953   TopLoc_Location l;
1954   Handle(Geom_Surface) S;
1955
1956   for (; exp.More(); exp.Next()) {
1957     const TopoDS_Face&   F = TopoDS::Face(exp.Current());
1958     S = BRep_Tool::Surface(F, l);
1959     if (!S.IsNull()) {
1960       if (S->DynamicType() == STANDARD_TYPE(Geom_RectangularTrimmedSurface)) {
1961         S = Handle(Geom_RectangularTrimmedSurface)::DownCast (S)->BasisSurface();
1962       }
1963       GeomAdaptor_Surface AS(S);
1964       switch (AS.GetType()) {
1965       case GeomAbs_Plane: 
1966         {
1967           LPlan.Append(F);
1968           break;
1969         }
1970       case GeomAbs_Cylinder: 
1971         {
1972           LCyl.Append(F);
1973           break;
1974         }
1975       case GeomAbs_Cone: 
1976         {
1977           LCon.Append(F);
1978           break;
1979         }
1980       case GeomAbs_Sphere: 
1981         {
1982           LSphere.Append(F);
1983           break;
1984         }
1985       case GeomAbs_Torus: 
1986         {
1987           LTor.Append(F);
1988           break;
1989         }
1990       default:
1991         LOther.Append(F);
1992       }
1993     }
1994     else LTri.Append(F);
1995   }
1996   LF.Append(LPlan); LF.Append(LCyl  ); LF.Append(LCon); LF.Append(LSphere);
1997   LF.Append(LTor ); LF.Append(LOther); LF.Append(LTri); 
1998 }
1999
2000 //=======================================================================
2001 //function : ReverseSortFaces
2002 //purpose  : 
2003 //=======================================================================
2004
2005 void  BRepLib::ReverseSortFaces (const TopoDS_Shape& Sh,
2006   TopTools_ListOfShape& LF)
2007 {
2008   LF.Clear();
2009   // Use the allocator of the result LF for intermediate results
2010   TopTools_ListOfShape LTri(LF.Allocator()), LPlan(LF.Allocator()),
2011     LCyl(LF.Allocator()), LCon(LF.Allocator()), LSphere(LF.Allocator()),
2012     LTor(LF.Allocator()), LOther(LF.Allocator());
2013   TopExp_Explorer exp(Sh,TopAbs_FACE);
2014   TopLoc_Location l;
2015
2016   for (; exp.More(); exp.Next()) {
2017     const TopoDS_Face&   F = TopoDS::Face(exp.Current());
2018     const Handle(Geom_Surface)& S = BRep_Tool::Surface(F, l);
2019     if (!S.IsNull()) {
2020       GeomAdaptor_Surface AS(S);
2021       switch (AS.GetType()) {
2022       case GeomAbs_Plane: 
2023         {
2024           LPlan.Append(F);
2025           break;
2026         }
2027       case GeomAbs_Cylinder: 
2028         {
2029           LCyl.Append(F);
2030           break;
2031         }
2032       case GeomAbs_Cone: 
2033         {
2034           LCon.Append(F);
2035           break;
2036         }
2037       case GeomAbs_Sphere: 
2038         {
2039           LSphere.Append(F);
2040           break;
2041         }
2042       case GeomAbs_Torus: 
2043         {
2044           LTor.Append(F);
2045           break;
2046         }
2047       default:
2048         LOther.Append(F);
2049       }
2050     }
2051     else LTri.Append(F);
2052   }
2053   LF.Append(LTri); LF.Append(LOther); LF.Append(LTor ); LF.Append(LSphere);
2054   LF.Append(LCon); LF.Append(LCyl  ); LF.Append(LPlan);
2055
2056 }
2057