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