5a925c96f71961d55bcaa1c2443bd79efe3fdda8
[occt.git] / src / IntTools / IntTools_BeanFaceIntersector.cxx
1 // Copyright (c) 1999-2014 OPEN CASCADE SAS
2 //
3 // This file is part of Open CASCADE Technology software library.
4 //
5 // This library is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU Lesser General Public License version 2.1 as published
7 // by the Free Software Foundation, with special exception defined in the file
8 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
9 // distribution for complete text of the license and disclaimer of any warranty.
10 //
11 // Alternatively, this file may be used under the terms of Open CASCADE
12 // commercial license or contractual agreement.
13
14
15 #include <Bnd_Box.hxx>
16 #include <BndLib_Add3dCurve.hxx>
17 #include <BndLib_AddSurface.hxx>
18 #include <BRep_Tool.hxx>
19 #include <BRepAdaptor_Curve.hxx>
20 #include <BRepAdaptor_HCurve.hxx>
21 #include <BRepAdaptor_HSurface.hxx>
22 #include <BRepAdaptor_Surface.hxx>
23 #include <ElCLib.hxx>
24 #include <ElSLib.hxx>
25 #include <Extrema_ExtCS.hxx>
26 #include <Extrema_ExtPS.hxx>
27 #include <Extrema_GenExtCS.hxx>
28 #include <Extrema_GenLocateExtPS.hxx>
29 #include <Extrema_POnCurv.hxx>
30 #include <Extrema_POnSurf.hxx>
31 #include <Geom_BSplineSurface.hxx>
32 #include <Geom_Curve.hxx>
33 #include <Geom_Surface.hxx>
34 #include <GeomAdaptor_Curve.hxx>
35 #include <GeomAdaptor_Surface.hxx>
36 #include <GeomAPI_ProjectPointOnCurve.hxx>
37 #include <GeomInt.hxx>
38 #include <IntAna_QuadQuadGeo.hxx>
39 #include <IntCurveSurface_HInter.hxx>
40 #include <IntCurveSurface_IntersectionPoint.hxx>
41 #include <IntCurveSurface_IntersectionSegment.hxx>
42 #include <IntTools.hxx>
43 #include <IntTools_BeanFaceIntersector.hxx>
44 #include <IntTools_Context.hxx>
45 #include <IntTools_CurveRangeLocalizeData.hxx>
46 #include <IntTools_CurveRangeSample.hxx>
47 #include <IntTools_EdgeFace.hxx>
48 #include <IntTools_ListIteratorOfListOfBox.hxx>
49 #include <IntTools_ListIteratorOfListOfCurveRangeSample.hxx>
50 #include <IntTools_ListIteratorOfListOfSurfaceRangeSample.hxx>
51 #include <IntTools_ListOfBox.hxx>
52 #include <IntTools_ListOfCurveRangeSample.hxx>
53 #include <IntTools_ListOfSurfaceRangeSample.hxx>
54 #include <IntTools_MapIteratorOfMapOfCurveSample.hxx>
55 #include <IntTools_Root.hxx>
56 #include <IntTools_SurfaceRangeLocalizeData.hxx>
57 #include <IntTools_SurfaceRangeSample.hxx>
58 #include <IntTools_Tools.hxx>
59 #include <Precision.hxx>
60 #include <TColgp_Array1OfPnt2d.hxx>
61 #include <TColStd_Array1OfBoolean.hxx>
62 #include <TColStd_Array1OfReal.hxx>
63 #include <TColStd_ListIteratorOfListOfInteger.hxx>
64 #include <TColStd_ListOfInteger.hxx>
65 #include <TopoDS_Edge.hxx>
66 #include <TopoDS_Face.hxx>
67
68 static Standard_Boolean SetEmptyResultRange(const Standard_Real      theParameter, 
69                                             IntTools_MarkedRangeSet& theMarkedRange);
70
71
72
73 static Bnd_Box GetSurfaceBox
74   (const Handle(Geom_BSplineSurface)        &theSurf,
75    const Standard_Real                       theFirstU,
76    const Standard_Real                       theLastU,
77    const Standard_Real                       theFirstV,
78    const Standard_Real                       theLastV,
79    const Standard_Real                       theTolerance,
80    IntTools_SurfaceRangeLocalizeData  &theSurfaceData);
81
82 static void ComputeGridPoints
83   (const Handle(Geom_BSplineSurface)       &theSurf,
84    const Standard_Real                      theFirstU,
85    const Standard_Real                      theLastU,
86    const Standard_Real                      theFirstV,
87    const Standard_Real                      theLastV,
88    const Standard_Real                      theTolerance,
89    IntTools_SurfaceRangeLocalizeData &theSurfaceData);
90
91 static void BuildBox(const Handle(Geom_BSplineSurface)       &theSurf,
92                      const Standard_Real                      theFirstU,
93                      const Standard_Real                      theLastU,
94                      const Standard_Real                      theFirstV,
95                      const Standard_Real                      theLastV,
96                      IntTools_SurfaceRangeLocalizeData &theSurfaceData,
97                      Bnd_Box                           &theBox);
98      
99 static void MergeSolutions(const IntTools_ListOfCurveRangeSample& theListCurveRange,
100                            const IntTools_ListOfSurfaceRangeSample& theListSurfaceRange,
101                            IntTools_ListOfCurveRangeSample& theListCurveRangeSort,
102                            IntTools_ListOfSurfaceRangeSample& theListSurfaceRangeSort);
103
104 static void CheckSampling(const IntTools_CurveRangeSample& theCurveRange,
105                           const IntTools_SurfaceRangeSample& theSurfaceRange,
106                           const IntTools_CurveRangeLocalizeData& theCurveData,
107                           const IntTools_SurfaceRangeLocalizeData& theSurfaceData,
108                           const Standard_Real DiffC,
109                           const Standard_Real DiffU,
110                           const Standard_Real DiffV,
111                           Standard_Boolean& bAllowSamplingC,
112                           Standard_Boolean& bAllowSamplingU,
113                           Standard_Boolean& bAllowSamplingV);
114
115 // ==================================================================================
116 // function: IntTools_BeanFaceIntersector
117 // purpose: 
118 // ==================================================================================
119 IntTools_BeanFaceIntersector::IntTools_BeanFaceIntersector() :
120 myFirstParameter(0.),
121 myLastParameter(0.),
122 myUMinParameter(0.),
123 myUMaxParameter(0.),
124 myVMinParameter(0.),
125 myVMaxParameter(0.),
126 myBeanTolerance(0.),
127 myFaceTolerance(0.),
128 myDeflection(0.01),
129 myIsDone(Standard_False)
130 {
131   myCriteria        = Precision::Confusion();
132   myCurveResolution = Precision::PConfusion();
133   
134 }
135
136 // ==================================================================================
137 // function: IntTools_BeanFaceIntersector
138 // purpose: 
139 // ==================================================================================
140 IntTools_BeanFaceIntersector::IntTools_BeanFaceIntersector(const TopoDS_Edge& theEdge,
141                                                            const TopoDS_Face& theFace) :
142        myFirstParameter(0.),
143        myLastParameter(0.),
144        myUMinParameter(0.),
145        myUMaxParameter(0.),
146        myVMinParameter(0.),
147        myVMaxParameter(0.),
148        myBeanTolerance(0.),
149        myFaceTolerance(0.),
150        myDeflection(0.01),
151        myIsDone(Standard_False)
152 {
153   Init(theEdge, theFace);
154 }
155
156 // ==================================================================================
157 // function: IntTools_BeanFaceIntersector
158 // purpose: 
159 // ==================================================================================
160 IntTools_BeanFaceIntersector::IntTools_BeanFaceIntersector(const BRepAdaptor_Curve&   theCurve,
161                                                            const BRepAdaptor_Surface& theSurface,
162                                                            const Standard_Real        theBeanTolerance,
163                                                            const Standard_Real        theFaceTolerance) :
164        myFirstParameter(0.),
165        myLastParameter(0.),
166        myUMinParameter(0.),
167        myUMaxParameter(0.),
168        myVMinParameter(0.),
169        myVMaxParameter(0.),
170        myDeflection(0.01),
171        myIsDone(Standard_False)
172 {
173   Init(theCurve, theSurface, theBeanTolerance, theFaceTolerance);
174 }
175
176 // ==================================================================================
177 // function: IntTools_BeanFaceIntersector
178 // purpose: 
179 // ==================================================================================
180 IntTools_BeanFaceIntersector::IntTools_BeanFaceIntersector(const BRepAdaptor_Curve&   theCurve,
181                                                            const BRepAdaptor_Surface& theSurface,
182                                                            const Standard_Real        theFirstParOnCurve,
183                                                            const Standard_Real        theLastParOnCurve,
184                                                            const Standard_Real        theUMinParameter,
185                                                            const Standard_Real        theUMaxParameter,
186                                                            const Standard_Real        theVMinParameter,
187                                                            const Standard_Real        theVMaxParameter,
188                                                            const Standard_Real        theBeanTolerance,
189                                                            const Standard_Real        theFaceTolerance) :
190        myFirstParameter(theFirstParOnCurve),
191        myLastParameter(theLastParOnCurve),
192        myUMinParameter(theUMinParameter),
193        myUMaxParameter(theUMaxParameter),
194        myVMinParameter(theVMinParameter),
195        myVMaxParameter(theVMaxParameter),
196        myBeanTolerance(theBeanTolerance),
197        myFaceTolerance(theFaceTolerance),
198        myDeflection(0.01),
199        myIsDone(Standard_False)
200 {
201   myCurve = theCurve;
202   
203   myCriteria = myBeanTolerance + myFaceTolerance;
204   myCurveResolution = myCurve.Resolution(myCriteria);
205
206   mySurface = theSurface;
207   myTrsfSurface = Handle(Geom_Surface)::DownCast(mySurface.Surface().Surface()->Transformed(mySurface.Trsf()));
208 }
209
210 // ==================================================================================
211 // function: Init
212 // purpose: 
213 // ==================================================================================
214 void IntTools_BeanFaceIntersector::Init(const TopoDS_Edge& theEdge,
215                                         const TopoDS_Face& theFace) 
216 {
217   myCurve.Initialize(theEdge);
218   mySurface.Initialize(theFace);
219   myTrsfSurface = Handle(Geom_Surface)::DownCast(mySurface.Surface().Surface()->Transformed(mySurface.Trsf()));
220   myBeanTolerance = BRep_Tool::Tolerance(theEdge);
221   myFaceTolerance = BRep_Tool::Tolerance(theFace);
222   
223   myCriteria = myBeanTolerance + myFaceTolerance;
224   myCurveResolution = myCurve.Resolution(myCriteria);
225
226   SetSurfaceParameters(mySurface.FirstUParameter(), mySurface.LastUParameter(), 
227                        mySurface.FirstVParameter(), mySurface.LastVParameter());
228   myResults.Clear();
229 }
230
231 // ==================================================================================
232 // function: Init
233 // purpose: 
234 // ==================================================================================
235 void IntTools_BeanFaceIntersector::Init(const BRepAdaptor_Curve&   theCurve,
236                                         const BRepAdaptor_Surface& theSurface,
237                                         const Standard_Real        theBeanTolerance,
238                                         const Standard_Real        theFaceTolerance) 
239 {
240   myCurve = theCurve;
241   mySurface = theSurface;
242   myTrsfSurface = Handle(Geom_Surface)::DownCast(mySurface.Surface().Surface()->Transformed(mySurface.Trsf()));
243   myBeanTolerance = theBeanTolerance;
244   myFaceTolerance = theFaceTolerance;
245   
246   myCriteria = myBeanTolerance + myFaceTolerance;
247   myCurveResolution = myCurve.Resolution(myCriteria);
248   
249   SetSurfaceParameters(mySurface.FirstUParameter(), mySurface.LastUParameter(), 
250                        mySurface.FirstVParameter(), mySurface.LastVParameter());
251   myResults.Clear();
252 }
253
254 // ==================================================================================
255 // function: Init
256 // purpose: 
257 // ==================================================================================
258 void IntTools_BeanFaceIntersector::Init(const BRepAdaptor_Curve&   theCurve,
259                                         const BRepAdaptor_Surface& theSurface,
260                                         const Standard_Real        theFirstParOnCurve,
261                                         const Standard_Real        theLastParOnCurve,
262                                         const Standard_Real        theUMinParameter,
263                                         const Standard_Real        theUMaxParameter,
264                                         const Standard_Real        theVMinParameter,
265                                         const Standard_Real        theVMaxParameter,
266                                         const Standard_Real        theBeanTolerance,
267                                         const Standard_Real        theFaceTolerance) 
268 {
269   Init(theCurve, theSurface, theBeanTolerance, theFaceTolerance);
270   SetBeanParameters(theFirstParOnCurve, theLastParOnCurve);
271   SetSurfaceParameters(theUMinParameter, theUMaxParameter, theVMinParameter, theVMaxParameter);
272 }
273
274 // ==================================================================================
275 // function: SetContext
276 // purpose: 
277 // ==================================================================================
278 void IntTools_BeanFaceIntersector::SetContext(const Handle(IntTools_Context)& theContext) 
279 {
280   myContext = theContext;
281 }
282 // ==================================================================================
283 // function: Context
284 // purpose: 
285 // ==================================================================================
286 const Handle(IntTools_Context)& IntTools_BeanFaceIntersector::Context()const
287 {
288   return myContext;
289 }
290
291 // ==================================================================================
292 // function: SetBeanParameters
293 // purpose: 
294 // ==================================================================================
295 void IntTools_BeanFaceIntersector::SetBeanParameters(const Standard_Real theFirstParOnCurve,
296                                                      const Standard_Real theLastParOnCurve) 
297 {
298   myFirstParameter = theFirstParOnCurve;
299   myLastParameter  = theLastParOnCurve;
300 }
301
302 // ==================================================================================
303 // function: SetSurfaceParameters
304 // purpose: 
305 // ==================================================================================
306 void IntTools_BeanFaceIntersector::SetSurfaceParameters(const Standard_Real theUMinParameter,
307                                                         const Standard_Real theUMaxParameter,
308                                                         const Standard_Real theVMinParameter,
309                                                         const Standard_Real theVMaxParameter) 
310 {
311   myUMinParameter  = theUMinParameter;
312   myUMaxParameter  = theUMaxParameter;
313   myVMinParameter  = theVMinParameter;
314   myVMaxParameter  = theVMaxParameter;
315 }
316
317 // ==================================================================================
318 // function: Perform
319 // purpose: 
320 // ==================================================================================
321 void IntTools_BeanFaceIntersector::Perform() 
322 {
323   myIsDone = Standard_False;
324   myResults.Clear();
325   Standard_Integer bRet; 
326   Standard_Integer aDiscretization = 30; 
327   Standard_Real aRelativeDeflection = 0.01;
328   myDeflection = aRelativeDeflection;
329   //
330   if (myContext.IsNull()) {
331     myContext=new IntTools_Context;
332   }
333   //
334   if(myCurve.GetType()==GeomAbs_Line && mySurface.GetType()==GeomAbs_Plane) {
335     ComputeLinePlane();
336     return;
337   }
338
339   if(myCurve.GetType()==GeomAbs_Line) {
340     aDiscretization = 3;
341     myDeflection = Precision::Confusion();
342   }
343   else {
344     if(myCurve.GetType()==GeomAbs_Circle) {
345       aDiscretization = 23;
346       Standard_Real R = myCurve.Circle().Radius();
347       myDeflection = aRelativeDeflection * R;
348     }
349     if(myCurve.GetType() == GeomAbs_Ellipse) {
350       aDiscretization = 23;
351       Standard_Real R = myCurve.Ellipse().MajorRadius();
352       myDeflection = 2 * aRelativeDeflection * R;
353     }
354   }
355 // modified by NIZHNY-MKK  Wed Oct 19 12:15:21 2005
356   Standard_Boolean bLocalize = Standard_False;
357
358   if(((mySurface.GetType() == GeomAbs_BSplineSurface) &&
359       ((mySurface.UDegree() > 2) || (mySurface.VDegree() > 2)) &&
360       //modified by NIZNHY-PKV Wed Feb 25 15:02:00 2009f
361       //((mySurface.NbUKnots() > 2) || (mySurface.NbVKnots() > 2))) ||
362       ((mySurface.NbUKnots() > 2) && (mySurface.NbVKnots() > 2))) ||
363      //modified by NIZNHY-PKV Wed Feb 25 15:02:13 2009t
364      (mySurface.GetType() == GeomAbs_BezierSurface) ||
365      (mySurface.GetType() == GeomAbs_OtherSurface)) {
366     bLocalize = Standard_True;
367   }
368
369   if(bLocalize) {
370     if(Precision::IsInfinite(myUMinParameter) ||
371        Precision::IsInfinite(myUMaxParameter) ||
372        Precision::IsInfinite(myVMinParameter) ||
373        Precision::IsInfinite(myVMaxParameter))
374       bLocalize = Standard_False;
375   }
376   Standard_Boolean bSuccessLocalize = Standard_False;
377
378   if( bLocalize) {
379     myRangeManager.SetBoundaries(myFirstParameter, myLastParameter, 0);
380     Standard_Boolean coinside = TestComputeCoinside();
381
382     if(!coinside)
383       bSuccessLocalize = ComputeLocalized();
384   }
385
386   if(!bLocalize || !bSuccessLocalize) {
387 // modified by NIZHNY-MKK  Wed Oct 19 12:15:26 2005.END
388
389     IntTools_CArray1OfReal aParams;
390     
391     if(IntTools::PrepareArgs(myCurve, 
392                              myLastParameter, 
393                              myFirstParameter, 
394                              aDiscretization, 
395                              aRelativeDeflection, 
396                              aParams)) {
397       return;
398     }
399
400     myRangeManager.SetRanges(aParams, 0);
401
402     if(myRangeManager.Length()==0) {
403       return;
404     }
405     //
406     bRet=FastComputeExactIntersection();
407     if(bRet == 1) {
408       IntTools_Range aRange(myFirstParameter, myLastParameter);
409       myResults.Append(aRange);
410       myIsDone = Standard_True;
411       return;
412     } 
413     //modified by NIZHNY-EMV Fri Apr 20 09:38:08 2012
414     else if (bRet == 2) {
415       myIsDone = Standard_True;
416       return;
417     }
418     //modified by NIZHNY-EMV Fri Apr 20 09:38:10 2012
419
420
421 //     Standard_Boolean coinside = TestCoinside(myCurve,mySurface);
422     Standard_Boolean coinside = TestComputeCoinside();
423 //     if(coinside) {
424 //       myRangeManager.InsertRange(myFirstParameter, myLastParameter, 2);
425 //     }
426 //     else {
427     if(!coinside) {
428       ComputeAroundExactIntersection();
429       
430       ComputeUsingExtremum();
431       
432       ComputeNearRangeBoundaries();
433     }
434   }
435
436   myIsDone = Standard_True;
437
438   for(Standard_Integer i = 1; i <= myRangeManager.Length(); i++) {
439
440     if(myRangeManager.Flag(i) == 2) {
441       IntTools_Range aRange = myRangeManager.Range(i);
442
443       if(myResults.Length() > 0) {
444         const IntTools_Range& aLastRange = myResults.Last();
445         
446         if(Abs(aRange.First() - aLastRange.Last()) > Precision::PConfusion()) {
447           myResults.Append(aRange);
448         }
449         else {
450           myResults.ChangeValue(myResults.Length()).SetLast(aRange.Last());
451         }
452       }
453       else {
454         myResults.Append(aRange);
455       }
456     }
457   }
458 }
459
460 // ==================================================================================
461 // function: Result
462 // purpose: 
463 // ==================================================================================
464 const IntTools_SequenceOfRanges& IntTools_BeanFaceIntersector::Result() const
465 {
466   return myResults;
467 }
468
469 // ==================================================================================
470 // function: Result
471 // purpose: 
472 // ==================================================================================
473 void IntTools_BeanFaceIntersector::Result(IntTools_SequenceOfRanges& theResults) const
474 {
475   theResults = myResults;
476 }
477
478 // ==================================================================================
479 // function: Distance
480 // purpose: 
481 // ==================================================================================
482 Standard_Real IntTools_BeanFaceIntersector::Distance(const Standard_Real theArg)
483 {
484   gp_Pnt aPoint = myCurve.Value(theArg);
485
486   GeomAPI_ProjectPointOnSurf& aProjector = myContext->ProjPS(mySurface.Face());
487   aProjector.Perform(aPoint);
488   
489   if(aProjector.IsDone() && aProjector.NbPoints() > 0) {
490     return aProjector.LowerDistance();
491   }
492   // 
493   Standard_Real aDistance = RealLast();
494     
495   for(Standard_Integer i=0; i < 4; i++) {
496     Standard_Real anIsoParameter = (i==0) ? myUMinParameter : ((i==1) ? myUMaxParameter : ((i==2) ? myVMinParameter : myVMaxParameter));
497     Standard_Real aMinParameter  = (i < 2) ? myVMinParameter : myUMinParameter;
498     Standard_Real aMaxParameter  = (i < 2) ? myVMaxParameter : myUMaxParameter;
499     Standard_Real aMidParameter = (aMinParameter + aMaxParameter) * 0.5;
500     gp_Pnt aPointMin = (i < 2) ? mySurface.Value(anIsoParameter, aMinParameter) : mySurface.Value(aMinParameter, anIsoParameter);
501     gp_Pnt aPointMax = (i < 2) ? mySurface.Value(anIsoParameter, aMaxParameter) : mySurface.Value(aMaxParameter, anIsoParameter);
502     gp_Pnt aPointMid = (i < 2) ? mySurface.Value(anIsoParameter, aMidParameter) : mySurface.Value(aMidParameter, anIsoParameter);
503
504     Standard_Boolean useMinMaxPoints = Standard_True;
505     Standard_Boolean computeisoline = Standard_True;
506
507     if(aPointMin.IsEqual(aPointMax, myCriteria) &&
508        aPointMin.IsEqual(aPointMid, myCriteria) &&
509        aPointMax.IsEqual(aPointMid, myCriteria)) {
510       computeisoline = Standard_False;
511     }
512    
513     if(computeisoline) {
514       Handle(Geom_Curve) aCurve = (i < 2) ? myTrsfSurface->UIso(anIsoParameter) : myTrsfSurface->VIso(anIsoParameter);
515       GeomAPI_ProjectPointOnCurve aProjectorOnCurve(aPoint, aCurve, aMinParameter, aMaxParameter);
516     
517       if(aProjectorOnCurve.NbPoints() > 0) {
518         useMinMaxPoints = Standard_False;
519         
520         if(aDistance > aProjectorOnCurve.LowerDistance())
521   aDistance = aProjectorOnCurve.LowerDistance();
522       }
523     }
524
525     if(useMinMaxPoints) {
526       Standard_Real aPPDistance = aPoint.Distance(aPointMin);
527       aDistance = (aPPDistance < aDistance) ? aPPDistance : aDistance;
528       aPPDistance = aPoint.Distance(aPointMax);
529       aDistance = (aPPDistance < aDistance) ? aPPDistance : aDistance;
530     }
531   }
532   return aDistance;
533 }
534
535
536 // ==================================================================================
537 // function: Distance
538 // purpose: 
539 // ==================================================================================
540 Standard_Real IntTools_BeanFaceIntersector::Distance(const Standard_Real theArg,
541                                                      Standard_Real&      theUParameter,
542                                                      Standard_Real&      theVParameter)  
543 {
544   gp_Pnt aPoint = myCurve.Value(theArg);
545   
546   theUParameter = myUMinParameter;
547   theVParameter = myVMinParameter;
548   // 
549   Standard_Real aDistance = RealLast();
550   Standard_Boolean projectionfound = Standard_False;
551
552   GeomAPI_ProjectPointOnSurf& aProjector = myContext->ProjPS(mySurface.Face());
553   aProjector.Perform(aPoint);
554   
555   if(aProjector.IsDone() && aProjector.NbPoints() > 0) {
556     aProjector.LowerDistanceParameters(theUParameter, theVParameter);
557     aDistance = aProjector.LowerDistance();
558     projectionfound = Standard_True;
559   }
560   
561   if(!projectionfound) {
562   //
563     for(Standard_Integer i = 0; i < 4; i++) {
564       Standard_Real anIsoParameter = (i==0) ? myUMinParameter : ((i==1) ? myUMaxParameter : ((i==2) ? myVMinParameter : myVMaxParameter));
565       Standard_Real aMinParameter = (i < 2) ? myVMinParameter : myUMinParameter;
566       Standard_Real aMaxParameter = (i < 2) ? myVMaxParameter : myUMaxParameter;
567       Standard_Real aMidParameter = (aMinParameter + aMaxParameter) * 0.5;
568       gp_Pnt aPointMin = (i < 2) ? mySurface.Value(anIsoParameter, aMinParameter) : mySurface.Value(aMinParameter, anIsoParameter);
569       gp_Pnt aPointMax = (i < 2) ? mySurface.Value(anIsoParameter, aMaxParameter) : mySurface.Value(aMaxParameter, anIsoParameter);
570       gp_Pnt aPointMid = (i < 2) ? mySurface.Value(anIsoParameter, aMidParameter) : mySurface.Value(aMidParameter, anIsoParameter);
571       
572       Standard_Boolean useMinMaxPoints = Standard_True;
573       Standard_Boolean computeisoline = Standard_True;
574       
575       if(aPointMin.IsEqual(aPointMax, myCriteria) &&
576          aPointMin.IsEqual(aPointMid, myCriteria) &&
577          aPointMax.IsEqual(aPointMid, myCriteria)) {
578         computeisoline = Standard_False;
579                                                            }
580       
581       if(computeisoline) {
582         Handle(Geom_Curve) aCurve = (i < 2) ? myTrsfSurface->UIso(anIsoParameter) : myTrsfSurface->VIso(anIsoParameter);
583         GeomAPI_ProjectPointOnCurve aProjectorOnCurve(aPoint, aCurve, aMinParameter, aMaxParameter);
584         
585         if(aProjectorOnCurve.NbPoints() > 0) {
586           useMinMaxPoints = Standard_False;
587           
588           if(aDistance > aProjectorOnCurve.LowerDistance()) {
589             theUParameter = (i<=1) ? anIsoParameter : aProjectorOnCurve.LowerDistanceParameter();
590             theVParameter = (i>=2) ? anIsoParameter : aProjectorOnCurve.LowerDistanceParameter();
591             aDistance = aProjectorOnCurve.LowerDistance();
592           }
593         }
594       }
595       
596       if(useMinMaxPoints) {
597         Standard_Real aPPDistance = aPoint.Distance(aPointMin);
598         
599         if(aPPDistance < aDistance) {
600           theUParameter = (i<=1) ? anIsoParameter : aMinParameter;
601           theVParameter = (i>=2) ? anIsoParameter : aMinParameter;
602           aDistance = aPPDistance;
603         }
604         aPPDistance = aPoint.Distance(aPointMax);
605         
606         if(aPPDistance < aDistance) {
607           theUParameter = (i<=1) ? anIsoParameter : aMaxParameter;
608           theVParameter = (i>=2) ? anIsoParameter : aMaxParameter;
609           aDistance = aPPDistance;
610         }
611       }
612     }
613   }
614   theUParameter = (myUMinParameter > theUParameter) ? myUMinParameter : theUParameter;
615   theUParameter = (myUMaxParameter < theUParameter) ? myUMaxParameter : theUParameter;
616   theVParameter = (myVMinParameter > theVParameter) ? myVMinParameter : theVParameter;
617   theVParameter = (myVMaxParameter < theVParameter) ? myVMaxParameter : theVParameter;
618   
619   return aDistance;
620 }
621
622 // ==================================================================================
623 // function: ComputeAroundExactIntersection
624 // purpose: 
625 // ==================================================================================
626 void IntTools_BeanFaceIntersector::ComputeAroundExactIntersection() 
627 {
628   IntCurveSurface_HInter anExactIntersector;
629   
630   Handle(BRepAdaptor_HCurve) aCurve     = new BRepAdaptor_HCurve(myCurve);
631   Handle(BRepAdaptor_HSurface) aSurface = new BRepAdaptor_HSurface(mySurface);
632   
633   anExactIntersector.Perform(aCurve, aSurface);
634   
635   if(anExactIntersector.IsDone()) {
636     Standard_Integer i = 0;
637     
638     for(i = 1; i <= anExactIntersector.NbPoints(); i++) {
639       const IntCurveSurface_IntersectionPoint& aPoint = anExactIntersector.Point(i);
640       
641       if((aPoint.W() >= myFirstParameter) && (aPoint.W() <= myLastParameter)) {
642         Standard_Boolean UIsNotValid = ((myUMinParameter > aPoint.U()) || (aPoint.U() > myUMaxParameter));
643         Standard_Boolean VIsNotValid = ((myVMinParameter > aPoint.V()) || (aPoint.V() > myVMaxParameter));
644         Standard_Boolean solutionIsValid = !UIsNotValid && !VIsNotValid;
645         Standard_Real U = aPoint.U();
646         Standard_Real V = aPoint.V();
647         
648         if(UIsNotValid || VIsNotValid) {
649           Standard_Boolean bUCorrected = Standard_True;
650           
651           if(UIsNotValid) {
652             bUCorrected = Standard_False;
653             solutionIsValid = Standard_False;
654             //
655             if(mySurface.IsUPeriodic()) {
656               Standard_Real aNewU, aUPeriod, aEps, du;
657               //
658               aUPeriod = mySurface.UPeriod();
659               aEps = Epsilon(aUPeriod);
660               //
661               GeomInt::AdjustPeriodic(U, myUMinParameter, myUMaxParameter, 
662                                              aUPeriod, aNewU, du, aEps);
663               solutionIsValid = Standard_True;
664               bUCorrected = Standard_True;
665               U = aNewU;
666             }
667           }
668           //   if(solutionIsValid && VIsNotValid) {
669           if(bUCorrected && VIsNotValid) {
670             solutionIsValid = Standard_False;
671             //
672             if(mySurface.IsVPeriodic()) {
673               Standard_Real aNewV, aVPeriod, aEps, dv;
674               //
675               aVPeriod = mySurface.VPeriod();
676               aEps = Epsilon(aVPeriod);
677               //
678               GeomInt::AdjustPeriodic(V, myVMinParameter, myVMaxParameter, 
679                                              aVPeriod, aNewV, dv, aEps);
680               solutionIsValid = Standard_True;
681               V = aNewV;
682             }
683           }
684         }
685         
686         if(!solutionIsValid)
687           continue;
688         
689         Standard_Integer aNbRanges = myRangeManager.Length();
690         
691         ComputeRangeFromStartPoint(Standard_False, aPoint.W(), U, V);
692         ComputeRangeFromStartPoint(Standard_True, aPoint.W(), U, V);
693         
694         if(aNbRanges == myRangeManager.Length()) {  
695           SetEmptyResultRange(aPoint.W(), myRangeManager);
696         } // end if(aNbRanges == myRangeManager.Length())
697       }
698     }
699     
700     for(i = 1; i <= anExactIntersector.NbSegments(); i++) {
701       const IntCurveSurface_IntersectionSegment& aSegment = anExactIntersector.Segment(i);
702       IntCurveSurface_IntersectionPoint aPoint1, aPoint2;
703       aSegment.Values(aPoint1, aPoint2);
704       
705       Standard_Real aFirstParameter = (aPoint1.W() < myFirstParameter) ? myFirstParameter : aPoint1.W();
706       Standard_Real aLastParameter = (myLastParameter < aPoint2.W())   ? myLastParameter  : aPoint2.W();
707
708       myRangeManager.InsertRange(aFirstParameter, aLastParameter, 2);
709
710       ComputeRangeFromStartPoint(Standard_False, aPoint1.W(), aPoint1.U(), aPoint1.V());
711       ComputeRangeFromStartPoint(Standard_True,  aPoint2.W(), aPoint2.U(), aPoint2.V());
712     }
713   }
714 }
715
716 // ==================================================================================
717 // function: FastComputeExactIntersection
718 // purpose: 
719 // ==================================================================================
720 Standard_Integer IntTools_BeanFaceIntersector::FastComputeExactIntersection() 
721 {
722   Standard_Integer aresult;
723   GeomAbs_CurveType aCT;
724   GeomAbs_SurfaceType aST;
725   //
726   aresult = 0;
727   aCT=myCurve.GetType();
728   aST=mySurface.GetType();
729   //
730   if((aCT==GeomAbs_BezierCurve) ||
731      (aCT==GeomAbs_BSplineCurve) ||
732      (aCT==GeomAbs_OtherCurve)) {
733     return aresult;
734   }
735
736   if(aST==GeomAbs_Plane) {
737     gp_Pln surfPlane = mySurface.Plane();
738
739     if(aCT==GeomAbs_Line) {
740       if((surfPlane.Distance(myCurve.Value(myFirstParameter)) < myCriteria) &&
741          (surfPlane.Distance(myCurve.Value(myLastParameter)) < myCriteria)) {
742         aresult = 1;
743       }
744     }
745     else { // else 1
746       gp_Dir aDir;
747
748       switch(aCT) {
749         case GeomAbs_Circle: {
750           aDir = myCurve.Circle().Axis().Direction();
751           break;
752         }
753         case GeomAbs_Ellipse: {
754           aDir = myCurve.Ellipse().Axis().Direction();
755           break;
756         }
757         case GeomAbs_Hyperbola: {
758           aDir = myCurve.Hyperbola().Axis().Direction();
759           break;
760         }
761         case GeomAbs_Parabola: {
762           aDir = myCurve.Parabola().Axis().Direction();
763           break;
764         }
765         default: {
766           return aresult;
767         }
768       }
769       //
770       Standard_Real anAngle = aDir.Angle(surfPlane.Axis().Direction());
771       
772       if(anAngle < Precision::Angular()) {
773         Standard_Boolean insertRange = Standard_False;
774         
775         switch(aCT) {
776           case GeomAbs_Circle: {
777             Standard_Real adist = 
778               surfPlane.Distance(myCurve.Circle().Location()) + 
779                 myCurve.Circle().Radius() * Precision::Angular();
780             
781             if(adist < myCriteria) {
782               insertRange = Standard_True;
783             }
784             break;
785           }
786           case GeomAbs_Ellipse: {
787             Standard_Real adist = 
788               surfPlane.Distance(myCurve.Ellipse().Location()) + 
789                 myCurve.Ellipse().MajorRadius() * Precision::Angular();
790             
791             if(adist < myCriteria) {
792               insertRange = Standard_True;
793             }
794             break;
795           }
796           case GeomAbs_Hyperbola:
797           case GeomAbs_Parabola: {
798             Standard_Real aMaxPar =
799               (Abs(myFirstParameter)  > Abs(myLastParameter)) ? 
800                 Abs(myFirstParameter) : Abs(myLastParameter);
801             
802             gp_Pnt aLoc = (aCT == GeomAbs_Parabola) ? 
803               myCurve.Parabola().Location() : 
804                 myCurve.Hyperbola().Location();
805             Standard_Real adist = aLoc.Distance(myCurve.Value(aMaxPar));
806             adist = surfPlane.Distance(aLoc) + adist * Precision::Angular();
807             
808             if(adist < myCriteria) {
809               insertRange = Standard_True;
810             }
811             break;
812           }
813           default: {
814             break;
815           }
816         }
817         //
818         if(insertRange) {
819           aresult = 1;
820         }
821       }//if(anAngle < Precision::Angular()) {
822     }//else { // else 1
823   }// if(aST==GeomAbs_Plane) {
824   
825   if(aCT==GeomAbs_Circle) {
826     gp_Circ aCircle = myCurve.Circle();
827
828     if(aST==GeomAbs_Cylinder) {
829       gp_Cylinder aCylinder = mySurface.Cylinder();
830       gp_Dir aDir1(aCylinder.Axis().Direction());
831       gp_Dir aDir2(aCircle.Axis().Direction());
832       Standard_Real anAngle = aDir1.Angle(aDir2);
833       
834       if(anAngle < Precision::Angular()) {
835         gp_Pnt aLoc = aCircle.Location();
836         gp_Lin anCylAxis(aCylinder.Axis());
837         Standard_Real alocdist = anCylAxis.Distance(aLoc);
838         Standard_Real adist = alocdist;
839         Standard_Real adiff = aCircle.Radius() - aCylinder.Radius();
840         adist += Abs(adiff);
841         
842         if(adist < myCriteria) {
843           Standard_Real acylradius = aCylinder.Radius();
844           Standard_Real atmpvalue = aCircle.Radius() * sin(Precision::Angular());
845           Standard_Real aprojectedradius = atmpvalue;
846           aprojectedradius = 
847             sqrt((aCircle.Radius() * aCircle.Radius())
848                  - (aprojectedradius * aprojectedradius));
849           adiff = aprojectedradius - acylradius;
850           adist = alocdist + Abs(adiff);
851           
852           if(adist < myCriteria) { // Abs is important function here
853             aresult = 1;
854           }
855         }
856       }
857     }// if(aST==GeomAbs_Cylinder)
858
859     if(aST==GeomAbs_Sphere) {
860       gp_Pln aCirclePln(aCircle.Location(), aCircle.Axis().Direction());
861       IntAna_QuadQuadGeo anInter(aCirclePln, mySurface.Sphere());
862       
863       if(anInter.IsDone()) {
864         if(anInter.TypeInter() == IntAna_Circle) {
865           gp_Circ aCircleToCompare = anInter.Circle(1);
866           Standard_Real adist = 
867             aCircleToCompare.Location().Distance(aCircle.Location());
868           Standard_Real adiff = aCircle.Radius() - aCircleToCompare.Radius();
869           adist += Abs(adiff);
870           
871           if(adist < myCriteria) {
872             aresult = 1;
873           }
874         }
875       }
876     }// if(aST==GeomAbs_Sphere) {
877   }// if(aCT==GeomAbs_Circle) {
878   //
879   //modified by NIZNHY-PKV Thu Mar 01 11:54:04 2012f
880   if(aST==GeomAbs_Cylinder) {
881     Standard_Real aRC;
882     gp_Cylinder aCyl;
883     //
884     aCyl=mySurface.Cylinder();
885     aRC=aCyl.Radius();
886     const gp_Ax1& aAx1C=aCyl.Axis();
887     const gp_Dir& aDirC=aAx1C.Direction();
888     //
889     if(aCT==GeomAbs_Line) {
890       Standard_Real aCos, aAng2, aTolang2;
891       gp_Lin aLin;
892       //
893       aTolang2=1.e-16;
894       aLin=myCurve.Line();
895       const gp_Dir& aDirL=aLin.Direction();
896       //
897       aCos=aDirC.Dot(aDirL);
898       if(aCos >= 0.) {
899         aAng2 = 2.*(1. - aCos);
900       }
901       else {
902         aAng2 = 2.*(1. + aCos);
903       }
904       //
905       if(aAng2<=aTolang2) {// IsParallel = Standard_True;
906         Standard_Boolean bFlag = Standard_False;
907         Standard_Integer i;
908         Standard_Real aD;
909         gp_Pnt aPL[2];
910         gp_Lin aLC(aAx1C);
911         //
912         aPL[0]=myCurve.Value(myFirstParameter);
913         aPL[1]=myCurve.Value(myLastParameter);
914         //
915         for (i=0; i<2; ++i) {
916           aD=aLC.Distance(aPL[i]);
917           aD=fabs(aD-aRC);
918           bFlag=(aD > myCriteria);
919           if (bFlag) {
920             break;
921           }
922         }
923         if (!bFlag){
924           aresult = 1;
925         } 
926       }
927       
928     }//if(aCT==GeomAbs_Line) {
929   }
930   //modified by NIZNHY-PKV Thu Mar 01 11:54:06 2012t
931   //
932   if (aresult==1) {
933     //check intermediate point
934     Standard_Real aTm;
935     Standard_Boolean bValid;
936     //
937     const TopoDS_Face& aF = mySurface.Face();
938     aTm = IntTools_Tools::IntermediatePoint(myFirstParameter, myLastParameter);
939     const gp_Pnt& aPm = myCurve.Value(aTm);
940     //
941     bValid = myContext->IsValidPointForFace(aPm, aF, myCriteria);
942     if (bValid) {
943       IntTools_Range aRange(myFirstParameter, myLastParameter);
944       myRangeManager.InsertRange(aRange, 2);
945     } else {
946       aresult=2;
947     }
948   }
949   //
950   return aresult;
951 }
952
953 // ==================================================================================
954 // function: ComputeLinePlane
955 // purpose: 
956 // ==================================================================================
957 void IntTools_BeanFaceIntersector::ComputeLinePlane() 
958 {
959   Standard_Real Tolang = 1.e-9;
960   gp_Pln P = mySurface.Plane();
961   gp_Lin L = myCurve.Line();
962
963   myIsDone = Standard_True;
964
965   Standard_Real A,B,C,D;
966   Standard_Real Al,Bl,Cl;
967   Standard_Real Dis,Direc;
968   
969   P.Coefficients(A,B,C,D);
970   gp_Pnt Orig(L.Location());
971   L.Direction().Coord(Al,Bl,Cl);
972
973   Direc=A*Al+B*Bl+C*Cl;
974   Dis = A*Orig.X() + B*Orig.Y() + C*Orig.Z() + D;
975
976   Standard_Boolean parallel = Standard_False, inplane = Standard_False;
977   if (Abs(Direc) < Tolang) {
978     parallel= Standard_True;
979     if (Abs(Dis) < myCriteria) {
980       inplane=Standard_True;
981     }
982     else {
983       inplane=Standard_False;
984     }
985   }
986   else {
987     gp_Pnt p1 = ElCLib::Value(myFirstParameter, L);
988     gp_Pnt p2 = ElCLib::Value(myLastParameter, L);
989     Standard_Real d1 = A*p1.X() + B*p1.Y() + C*p1.Z() + D;
990     if(d1 < 0) d1 = -d1;
991     Standard_Real d2 = A*p2.X() + B*p2.Y() + C*p2.Z() + D;
992     if(d2 < 0) d2 = -d2;
993     if(d1 <= myCriteria && d2 <= myCriteria) {
994       inplane=Standard_True;
995     }
996   }
997
998   if(inplane) {
999     IntTools_Range aRange(myFirstParameter, myLastParameter);
1000     myResults.Append(aRange);
1001     return;
1002   }
1003
1004   if(parallel) {
1005     return;
1006   }
1007
1008   Standard_Real t = - Dis/Direc;
1009   if(t < myFirstParameter || t > myLastParameter) {
1010     return;
1011   }
1012
1013   gp_Pnt pint(Orig.X()+t*Al, Orig.Y()+t*Bl, Orig.Z()+t*Cl);
1014
1015   Standard_Real u, v;
1016   ElSLib::Parameters(P, pint, u, v);
1017   if(myUMinParameter > u || u > myUMaxParameter || myVMinParameter > v || v > myVMaxParameter) {
1018     return;
1019   }
1020
1021   Standard_Real t1 = Max(myFirstParameter, t-myCriteria);
1022   Standard_Real t2 = Min(myLastParameter, t+myCriteria);
1023   IntTools_Range aRange(t1, t2);
1024   myResults.Append(aRange);
1025  
1026   return;
1027
1028 }
1029
1030
1031 // ==================================================================================
1032 // function: ComputeUsingExtremum
1033 // purpose: 
1034 // ==================================================================================
1035 void IntTools_BeanFaceIntersector::ComputeUsingExtremum() 
1036 {
1037   Standard_Real Tol, af, al;
1038   Tol = Precision::PConfusion();
1039   Handle(Geom_Curve) aCurve = BRep_Tool::Curve  (myCurve.Edge(), af, al);
1040   GeomAdaptor_Surface aGASurface (myTrsfSurface, 
1041                                   myUMinParameter, 
1042                                   myUMaxParameter, 
1043                                   myVMinParameter, 
1044                                   myVMaxParameter);
1045   
1046   Bnd_Box FBox;
1047   BndLib_AddSurface::Add(mySurface, 0., FBox);
1048   FBox.Enlarge(myFaceTolerance);
1049
1050   for(Standard_Integer i = 1; i <= myRangeManager.Length(); i++) {
1051
1052     if(myRangeManager.Flag(i) > 0)
1053       continue;
1054
1055     IntTools_Range aParamRange = myRangeManager.Range(i);
1056     Standard_Real anarg1 = aParamRange.First();
1057     Standard_Real anarg2 = aParamRange.Last();
1058
1059     if(anarg2 - anarg1 < Precision::PConfusion()) {
1060
1061       if(((i > 1) && (myRangeManager.Flag(i-1) == 2)) ||
1062  ((i <  myRangeManager.Length()) && (myRangeManager.Flag(i+1) == 2))) {
1063         myRangeManager.SetFlag(i, 1);
1064         continue;
1065       }
1066     }
1067
1068     // check bounding boxes
1069     Bnd_Box EBox;
1070     EBox.Add(myCurve.Value(anarg1));
1071     EBox.Add(myCurve.Value(anarg2));
1072     EBox.Enlarge(myBeanTolerance + myDeflection);
1073     
1074     if(EBox.IsOut(FBox)) {
1075       myRangeManager.SetFlag(i, 1);
1076       continue;
1077     }
1078     
1079     GeomAdaptor_Curve aGACurve(aCurve, anarg1, anarg2);
1080     Extrema_ExtCS theExtCS(aGACurve, aGASurface, Tol, Tol);
1081     myExtrema = theExtCS; 
1082     
1083     if(myExtrema.IsDone() && (myExtrema.NbExt() || myExtrema.IsParallel())) {
1084       Standard_Integer anOldNbRanges = myRangeManager.Length();
1085       
1086       if (myExtrema.IsParallel()) {
1087         
1088         if(myExtrema.SquareDistance(1) < myCriteria * myCriteria) {
1089           Standard_Real U1, V1, U2, V2;
1090           Standard_Real adistance1 = Distance(anarg1, U1, V1);
1091           Standard_Real adistance2 = Distance(anarg2, U2, V2);
1092           Standard_Boolean validdistance1 = (adistance1 < myCriteria);
1093           Standard_Boolean validdistance2 = (adistance2 < myCriteria);
1094           
1095           if (validdistance1 && validdistance2) {
1096             myRangeManager.InsertRange(anarg1, anarg2, 2);
1097             continue;
1098           }
1099           else {
1100             if(validdistance1) {
1101               ComputeRangeFromStartPoint(Standard_True, anarg1, U1, V1);
1102             }
1103             else {
1104               if(validdistance2) {
1105                 ComputeRangeFromStartPoint(Standard_False, anarg2, U2, V2);
1106               }
1107               else {
1108                 Standard_Real a  = anarg1;
1109                 Standard_Real b  = anarg2;
1110                 Standard_Real da = adistance1;
1111                 Standard_Real db = adistance2;
1112                 Standard_Real asolution = a;
1113                 Standard_Boolean found = Standard_False;
1114                 
1115                 while(((b - a) > myCurveResolution) && !found) {
1116                   asolution = (a+b)*0.5;
1117                   Standard_Real adist = Distance(asolution, U1, V1);
1118                   
1119                   if(adist < myCriteria) {
1120                     found = Standard_True;
1121                   }
1122                   else {
1123                     if(da < db) {
1124                       b = asolution;
1125                       db = adist;
1126                     }
1127                     else {
1128                       a = asolution;
1129                       da = adist;
1130                     }
1131                   }
1132                 } // end while
1133                 
1134                 if(found) {
1135                   ComputeRangeFromStartPoint(Standard_False, asolution, U1, V1);
1136                   ComputeRangeFromStartPoint(Standard_True, asolution, U1, V1);
1137                 }
1138                 else {
1139                   myRangeManager.SetFlag(i, 1);
1140                 }
1141               }
1142             }
1143           }
1144         }
1145         else {
1146           myRangeManager.SetFlag(i, 1);
1147         }
1148       }
1149       else {
1150         Standard_Boolean solutionfound = Standard_False;
1151         
1152         for(Standard_Integer j = 1 ; j <= myExtrema.NbExt(); j++) {
1153           
1154           if(myExtrema.SquareDistance(j) < myCriteria * myCriteria) {
1155             Extrema_POnCurv p1;
1156             Extrema_POnSurf p2;
1157             myExtrema.Points(j, p1, p2);
1158             Standard_Real U, V;
1159             p2.Parameter(U, V);
1160             
1161             Standard_Integer aNbRanges = myRangeManager.Length();
1162             ComputeRangeFromStartPoint(Standard_False, p1.Parameter(), U, V);
1163             ComputeRangeFromStartPoint(Standard_True, p1.Parameter(), U, V);
1164             solutionfound = Standard_True;
1165             
1166             if(aNbRanges == myRangeManager.Length()) {
1167               SetEmptyResultRange(p1.Parameter(), myRangeManager);
1168             }
1169           }
1170         } //end for
1171         
1172         if(!solutionfound) {
1173           myRangeManager.SetFlag(i, 1);
1174         }
1175       }
1176       Standard_Integer adifference = myRangeManager.Length() - anOldNbRanges;
1177       
1178       if(adifference > 0) {
1179         i+=adifference;
1180       }
1181     } // end if(myExtrema.IsDone() && (myExtrema.NbExt() || myExtrema.IsParallel()))
1182   }
1183 }
1184
1185 // ==================================================================================
1186 // function: ComputeNearRangeBoundaries
1187 // purpose: 
1188 // ==================================================================================
1189 void IntTools_BeanFaceIntersector::ComputeNearRangeBoundaries() 
1190 {
1191   Standard_Real U = myUMinParameter;
1192   Standard_Real V = myVMinParameter;
1193   
1194   for(Standard_Integer i = 1; i <= myRangeManager.Length(); i++) {
1195
1196     if(myRangeManager.Flag(i) > 0)
1197       continue;
1198     
1199     if((i > 1) && (myRangeManager.Flag(i-1) > 0))
1200       continue;
1201     
1202     IntTools_Range aParamRange = myRangeManager.Range(i);
1203     
1204     if(Distance(aParamRange.First(), U, V) < myCriteria) {
1205       Standard_Integer aNbRanges = myRangeManager.Length();
1206       
1207       if(i > 1) {
1208         ComputeRangeFromStartPoint(Standard_False, aParamRange.First(), U, V, i-1);
1209       }
1210       ComputeRangeFromStartPoint(Standard_True, aParamRange.First(), U, V, i + (myRangeManager.Length() - aNbRanges));
1211       
1212       if(aNbRanges == myRangeManager.Length()) {
1213         SetEmptyResultRange(aParamRange.First(), myRangeManager);
1214       }
1215     }
1216   }
1217   
1218   if(myRangeManager.Flag(myRangeManager.Length()) == 0) {
1219     IntTools_Range aParamRange = myRangeManager.Range(myRangeManager.Length());
1220     
1221     if(Distance(aParamRange.Last(), U, V) < myCriteria) {
1222       Standard_Integer aNbRanges = myRangeManager.Length();
1223       
1224       ComputeRangeFromStartPoint(Standard_False, aParamRange.Last(), U, V, myRangeManager.Length());
1225       
1226       if(aNbRanges == myRangeManager.Length()) {
1227         SetEmptyResultRange(aParamRange.Last(), myRangeManager);
1228       }
1229     }
1230   }
1231 }
1232
1233 // ==================================================================================
1234 // function: ComputeRangeFromStartPoint
1235 // purpose:  Compute range using start point according to parameter theParameter,
1236 //           increasing parameter on curve if ToIncreaseParameter == Standard_True or
1237 //           decreasing parameter on curve if ToIncreaseParameter == Standard_False
1238 // ==================================================================================
1239 void IntTools_BeanFaceIntersector::ComputeRangeFromStartPoint(const Standard_Boolean ToIncreaseParameter,
1240          const Standard_Real    theParameter,
1241          const Standard_Real    theUParameter,
1242          const Standard_Real    theVParameter) 
1243 {
1244   Standard_Integer aFoundIndex = myRangeManager.GetIndex(theParameter, ToIncreaseParameter);
1245   
1246   if(aFoundIndex == 0) {
1247     return;
1248   }
1249   
1250   ComputeRangeFromStartPoint(ToIncreaseParameter, theParameter, theUParameter, theVParameter, aFoundIndex);
1251 }
1252
1253 // ==================================================================================
1254 // function: ComputeRangeFromStartPoint
1255 // purpose:  Compute range using start point according to parameter theParameter,
1256 //           increasing parameter on curve if ToIncreaseParameter == Standard_True or
1257 //           decreasing parameter on curve if ToIncreaseParameter == Standard_False.
1258 //           theIndex indicate that theParameter belong the range number theIndex.
1259 // ==================================================================================
1260 void IntTools_BeanFaceIntersector::ComputeRangeFromStartPoint(const Standard_Boolean ToIncreaseParameter,
1261          const Standard_Real    theParameter,
1262          const Standard_Real    theUParameter,
1263          const Standard_Real    theVParameter,
1264          const Standard_Integer theIndex) 
1265 {
1266   if(myRangeManager.Flag(theIndex) > 0)
1267     return;
1268   
1269   Standard_Integer aValidIndex = theIndex;
1270   
1271   Standard_Real aMinDelta        = myCurveResolution * 0.5;
1272   Standard_Real aDeltaRestrictor = myLastParameter - myFirstParameter;
1273
1274   if(aMinDelta > aDeltaRestrictor)
1275     aMinDelta = aDeltaRestrictor * 0.5;
1276
1277   Standard_Real tenOfMinDelta    = aMinDelta * 10.;
1278   Standard_Real aDelta           = myCurveResolution;
1279
1280   Standard_Real aCurPar  = (ToIncreaseParameter) ? (theParameter + aDelta) : (theParameter - aDelta);
1281   Standard_Real aPrevPar = theParameter;
1282   IntTools_Range aCurrentRange = myRangeManager.Range(aValidIndex);
1283
1284   Standard_Boolean BoundaryCondition  = (ToIncreaseParameter) ? (aCurPar > aCurrentRange.Last()) : (aCurPar < aCurrentRange.First());
1285   
1286   if(BoundaryCondition) {
1287     aCurPar = (ToIncreaseParameter) ? aCurrentRange.Last() : aCurrentRange.First();
1288     BoundaryCondition = Standard_False;
1289   }
1290
1291   Standard_Integer loopcounter = 0; // neccesary as infinite loop restricter
1292   Standard_Real U = theUParameter;
1293   Standard_Real V = theVParameter;
1294   Standard_Boolean anotherSolutionFound = Standard_False;
1295
1296   Standard_Boolean isboundaryindex = Standard_False;
1297   Standard_Boolean isvalidindex = Standard_True;
1298   
1299   while((aDelta >= aMinDelta) && (loopcounter <= 10)) {
1300     Standard_Boolean pointfound = Standard_False;
1301
1302     // 
1303     gp_Pnt aPoint = myCurve.Value(aCurPar);
1304     Extrema_GenLocateExtPS anExtrema(aPoint, mySurface, U, V, 1.e-10, 1.e-10);
1305     
1306     if(anExtrema.IsDone()) {
1307       if(anExtrema.SquareDistance() < myCriteria * myCriteria) {
1308         Extrema_POnSurf aPOnSurf = anExtrema.Point();
1309         aPOnSurf.Parameter(U, V);
1310         pointfound = Standard_True;
1311       }
1312     }
1313     else {
1314       pointfound = (Distance(aCurPar) < myCriteria);
1315     }
1316     
1317     if(pointfound) {
1318       aPrevPar = aCurPar;
1319       anotherSolutionFound = Standard_True;
1320       
1321       if(BoundaryCondition && (isboundaryindex || !isvalidindex))
1322         break;
1323     }
1324     else {
1325       aDeltaRestrictor = aDelta;
1326     }
1327     
1328     // if point found decide to increase aDelta using derivative of distance function
1329     //
1330     
1331     aDelta = (pointfound) ? (aDelta * 2.) : (aDelta * 0.5);
1332     aDelta = (aDelta < aDeltaRestrictor) ? aDelta : aDeltaRestrictor;
1333     
1334     aCurPar = (ToIncreaseParameter) ? (aPrevPar + aDelta) : (aPrevPar - aDelta);
1335     
1336     
1337     // prevent infinite loop when (aPrevPar +/- aDelta) == aPrevPar == 0.
1338     //
1339     
1340     if( aCurPar == aPrevPar )
1341       break;
1342     
1343     BoundaryCondition  = (ToIncreaseParameter) ? (aCurPar > aCurrentRange.Last()) : (aCurPar < aCurrentRange.First());
1344     
1345     isboundaryindex = Standard_False;
1346     isvalidindex = Standard_True;
1347     
1348     if(BoundaryCondition) {
1349       isboundaryindex = ((!ToIncreaseParameter && (aValidIndex == 1)) ||
1350                          (ToIncreaseParameter && (aValidIndex == myRangeManager.Length())));
1351       
1352       if(!isboundaryindex) {
1353         
1354         if(pointfound) {
1355           Standard_Integer aFlag = (ToIncreaseParameter) ? myRangeManager.Flag(aValidIndex + 1) : myRangeManager.Flag(aValidIndex - 1);
1356           
1357           if(aFlag==0) {    
1358             aValidIndex = (ToIncreaseParameter) ? (aValidIndex + 1) : (aValidIndex - 1);
1359             aCurrentRange = myRangeManager.Range(aValidIndex);
1360             
1361             if((ToIncreaseParameter && (aCurPar > aCurrentRange.Last())) ||
1362                (!ToIncreaseParameter && (aCurPar < aCurrentRange.First()))) {
1363               aCurPar = (aCurrentRange.First() + aCurrentRange.Last()) * 0.5;
1364               aDelta*=0.5;
1365             }
1366           }
1367           else {
1368             isvalidindex = Standard_False;
1369             aCurPar = (ToIncreaseParameter) ? aCurrentRange.Last() : aCurrentRange.First();
1370           }
1371         }
1372       }
1373       else {
1374         aCurPar = (ToIncreaseParameter) ? aCurrentRange.Last() : aCurrentRange.First();
1375       }      
1376       
1377       if(aDelta < tenOfMinDelta) {
1378         loopcounter++;
1379       }
1380       else {
1381         loopcounter = 0;
1382       }
1383     } // if(BoundaryCondition)
1384   }
1385   
1386   if(anotherSolutionFound) {
1387     if(ToIncreaseParameter)
1388       myRangeManager.InsertRange(theParameter, aPrevPar, 2);
1389     else
1390       myRangeManager.InsertRange(aPrevPar, theParameter, 2);
1391   }
1392 }
1393
1394 // ---------------------------------------------------------------------------------
1395 // static function: SetEmptyResultRange
1396 // purpose:  
1397 // ---------------------------------------------------------------------------------
1398 static Standard_Boolean SetEmptyResultRange(const Standard_Real      theParameter, 
1399                                             IntTools_MarkedRangeSet& theMarkedRange) {
1400   
1401   const TColStd_SequenceOfInteger& anIndices = theMarkedRange.GetIndices(theParameter);
1402   Standard_Boolean add = (anIndices.Length() > 0);
1403   
1404   for(Standard_Integer k = 1; k <= anIndices.Length(); k++) {
1405     if(theMarkedRange.Flag(anIndices(k)) == 2) {
1406       add = Standard_False;
1407       break;
1408     }
1409   }
1410   
1411   if(add) {
1412     theMarkedRange.InsertRange(theParameter, theParameter, 2);
1413   }
1414   
1415   return add;
1416 }
1417
1418 // ---------------------------------------------------------------------------------
1419 // static function: TestCoinside
1420 // purpose:  
1421 // ---------------------------------------------------------------------------------
1422 // static Standard_Boolean TestClose(const Extrema_ExtPS & theExt,
1423 //                                   const Standard_Real   theDist)
1424 // {
1425 //   Standard_Boolean close = Standard_False;
1426 //   if(!theExt.IsDone() || theExt.NbExt() == 0)
1427 //     return close;
1428 //   else {
1429 //     Standard_Integer ie;
1430 //     for(ie = 1; ie <= theExt.NbExt(); ie++) {
1431 //       Standard_Real dist = theExt.Value(ie);
1432 //       if(dist <= theDist) {
1433 //         close = Standard_True;
1434 //         break;
1435 //       }
1436 //     }
1437 //   }
1438 //   return close;
1439 // }
1440
1441 // Standard_Boolean TestCoinside(const BRepAdaptor_Curve&   theCurve,
1442 //                               const BRepAdaptor_Surface& theSurface)
1443 // {
1444 //   Standard_Real cfp = theCurve.FirstParameter(), clp = theCurve.LastParameter();
1445 //   Standard_Real cdp = fabs(clp - cfp) / 23.;
1446
1447 //   Standard_Integer i = 0;
1448 //   Standard_Real tolE = theCurve.Tolerance(), tolF = theSurface.Tolerance();
1449 //   Standard_Real tolT = tolE + tolF, tolU = 1.e-9, tolV = 1.e-9;
1450 //   gp_Pnt aP;
1451
1452 //   theCurve.D0(cfp,aP);
1453 //   Extrema_ExtPS eps(aP,theSurface,tolU,tolV);
1454
1455 //   if(!TestClose(eps,tolT))
1456 //     return Standard_False;
1457
1458 //   theCurve.D0(clp,aP);
1459 //   eps.Perform(aP);
1460
1461 //   if(!TestClose(eps,tolT))
1462 //     return Standard_False;
1463
1464 //   Standard_Boolean close = Standard_True;
1465
1466 //   for(i = 1; i <= 22; i++) {
1467 //     theCurve.D0((cfp+((Standard_Real)i)*cdp),aP);
1468 //     eps.Perform(aP);
1469 //     if(!TestClose(eps,tolT)) {
1470 //       close = Standard_False;
1471 //       break;
1472 //     }
1473 //   }
1474 //   return close;
1475 // }
1476
1477 // ======================================================================================================================
1478 // function: LocalizeSolutions
1479 // purpose: 
1480 // ======================================================================================================================
1481 Standard_Boolean IntTools_BeanFaceIntersector::LocalizeSolutions(const IntTools_CurveRangeSample& theCurveRange,
1482             const Bnd_Box& theBoxCurve,
1483             const IntTools_SurfaceRangeSample& theSurfaceRange,
1484             const Bnd_Box& theBoxSurface,
1485             IntTools_CurveRangeLocalizeData& theCurveData,
1486             IntTools_SurfaceRangeLocalizeData& theSurfaceData,
1487             IntTools_ListOfCurveRangeSample& theListCurveRange,
1488             IntTools_ListOfSurfaceRangeSample& theListSurfaceRange) 
1489 {
1490   Standard_Integer tIt = 0, uIt = 0, vIt = 0;
1491   
1492   // 
1493   IntTools_CurveRangeSample aRootRangeC(0);
1494   aRootRangeC.SetDepth(0);
1495   IntTools_SurfaceRangeSample aRootRangeS(0, 0, 0, 0);
1496
1497   Bnd_Box aMainBoxC = theBoxCurve;
1498   Bnd_Box aMainBoxS = theBoxSurface;
1499   Standard_Boolean bMainBoxFoundS = Standard_False;
1500   Standard_Boolean bMainBoxFoundC = Standard_False;
1501   //
1502   IntTools_ListOfCurveRangeSample aListCurveRangeFound;
1503   IntTools_ListOfSurfaceRangeSample aListSurfaceRangeFound;
1504
1505
1506   IntTools_Range aRangeC = theCurveRange.GetRange(myFirstParameter, myLastParameter, theCurveData.GetNbSample());
1507   Standard_Real localdiffC = (aRangeC.Last() - aRangeC.First()) / theCurveData.GetNbSample();
1508
1509   Standard_Real aCurPar = aRangeC.First();
1510   Standard_Real aPrevPar = aRangeC.First();
1511   Standard_Integer aCurIndexInit = theCurveRange.GetRangeIndexDeeper(theCurveData.GetNbSample());
1512
1513
1514   TColStd_ListOfInteger aListCToAvoid;
1515   Standard_Boolean bGlobalCheckDone = Standard_False;
1516   //
1517
1518   //
1519
1520   Standard_Integer aCurIndexU = theSurfaceRange.GetRangeIndexUDeeper(theSurfaceData.GetNbSampleU());
1521
1522   Standard_Integer aCurIndexVInit = theSurfaceRange.GetRangeIndexVDeeper(theSurfaceData.GetNbSampleV());
1523   IntTools_Range aRangeV = theSurfaceRange.GetRangeV(myVMinParameter, myVMaxParameter, theSurfaceData.GetNbSampleV());
1524
1525   //
1526   IntTools_Range aRangeU = theSurfaceRange.GetRangeU(myUMinParameter, myUMaxParameter, theSurfaceData.GetNbSampleU());
1527   Standard_Real aCurParU = aRangeU.First();
1528   Standard_Real aLocalDiffU = (aRangeU.Last() - aRangeU.First()) / theSurfaceData.GetNbSampleU();
1529
1530   Standard_Real aPrevParU = aCurParU;
1531   Standard_Real aLocalDiffV = (aRangeV.Last() - aRangeV.First()) / theSurfaceData.GetNbSampleV();
1532
1533
1534   // ranges check.begin
1535   Standard_Boolean bAllowSamplingC = Standard_True;
1536   Standard_Boolean bAllowSamplingU = Standard_True;
1537   Standard_Boolean bAllowSamplingV = Standard_True;
1538
1539   // check
1540   CheckSampling(theCurveRange, theSurfaceRange, theCurveData, theSurfaceData,
1541                 localdiffC, aLocalDiffU, aLocalDiffV,
1542                 bAllowSamplingC, bAllowSamplingU, bAllowSamplingV);
1543   //
1544   
1545   if(!bAllowSamplingC && !bAllowSamplingU && !bAllowSamplingV) {
1546     theListCurveRange.Append(theCurveRange);
1547     theListSurfaceRange.Append(theSurfaceRange);
1548     return Standard_True;
1549   }
1550   // ranges check.end
1551   
1552   // init template. begin
1553   IntTools_CurveRangeSample aNewRangeCTemplate;
1554
1555   if(!bAllowSamplingC) {
1556     aNewRangeCTemplate = theCurveRange;
1557     aCurIndexInit = theCurveRange.GetRangeIndex();
1558     localdiffC = (aRangeC.Last() - aRangeC.First());
1559   }
1560   else {
1561     aNewRangeCTemplate.SetDepth(theCurveRange.GetDepth() + 1);
1562     aNewRangeCTemplate.SetRangeIndex(aCurIndexInit);
1563   }
1564
1565   IntTools_SurfaceRangeSample aNewRangeSTemplate = theSurfaceRange;
1566
1567   if(bAllowSamplingU) {
1568     aNewRangeSTemplate.SetDepthU(theSurfaceRange.GetDepthU() + 1);
1569   }
1570   else {
1571     aCurIndexU = aNewRangeSTemplate.GetIndexU();
1572     aLocalDiffU = aRangeU.Last() - aRangeU.First();
1573   }
1574
1575   if(bAllowSamplingV) {
1576     aNewRangeSTemplate.SetDepthV(theSurfaceRange.GetDepthV() + 1);
1577   }
1578   else {
1579     aCurIndexVInit = theSurfaceRange.GetIndexV();
1580     aLocalDiffV = aRangeV.Last() - aRangeV.First();
1581   }
1582   // init template. end  
1583
1584
1585   Standard_Boolean bHasOut = Standard_False;
1586   const Standard_Integer nbU = (bAllowSamplingU) ? theSurfaceData.GetNbSampleU() : 1;
1587   const Standard_Integer nbV = (bAllowSamplingV) ? theSurfaceData.GetNbSampleV() : 1;
1588   const Standard_Integer nbC = (bAllowSamplingC) ? theCurveData.GetNbSample() : 1;
1589
1590   for(uIt = 1; uIt <= nbU; uIt++, aCurIndexU++, aPrevParU = aCurParU) {
1591     aCurParU += aLocalDiffU;
1592     
1593
1594     Standard_Real aCurParV = aRangeV.First();
1595     Standard_Real aPrevParV = aCurParV;
1596     Standard_Integer aCurIndexV = aCurIndexVInit;
1597
1598     Standard_Boolean bHasOutV = Standard_False;
1599
1600     // ///////
1601     for(vIt = 1; vIt <= nbV; vIt++, aCurIndexV++, aPrevParV = aCurParV) {
1602
1603       aCurParV += aLocalDiffV;
1604
1605
1606       // //////////////
1607       //
1608       IntTools_SurfaceRangeSample aNewRangeS = aNewRangeSTemplate;
1609
1610       if(bAllowSamplingU) {
1611         aNewRangeS.SetIndexU(aCurIndexU);
1612       }
1613       
1614       if(bAllowSamplingV) {
1615         aNewRangeS.SetIndexV(aCurIndexV);
1616       }
1617       
1618       if(theSurfaceData.IsRangeOut(aNewRangeS)) {
1619         bHasOutV = Standard_True;
1620         continue;
1621       }
1622       
1623       // ///////
1624       
1625       Bnd_Box aBoxS;
1626       
1627       if(!theSurfaceData.FindBox(aNewRangeS, aBoxS)) {
1628         
1629         if(mySurface.GetType() == GeomAbs_BSplineSurface) {
1630           //    if(Standard_False ) {
1631           Handle(Geom_BSplineSurface) aSurfBspl = Handle(Geom_BSplineSurface)::DownCast(myTrsfSurface);
1632           aBoxS = GetSurfaceBox(aSurfBspl, aPrevParU, aCurParU, aPrevParV, aCurParV, myCriteria, theSurfaceData);
1633         }
1634         else {
1635           BndLib_AddSurface::Add(mySurface, aPrevParU, aCurParU, aPrevParV, aCurParV, myCriteria, aBoxS);
1636           }
1637         //      Bnd_Box aMainBoxC;
1638         
1639         if(!bMainBoxFoundC && theCurveData.FindBox(aRootRangeC, aMainBoxC)) {
1640           bMainBoxFoundC = Standard_True;
1641         }
1642         
1643         if(aBoxS.IsOut(aMainBoxC)) {
1644           theSurfaceData.AddOutRange(aNewRangeS);
1645           bHasOutV = Standard_True;
1646           continue;
1647         }
1648         //      }
1649         theSurfaceData.AddBox(aNewRangeS, aBoxS);
1650       }
1651       
1652       if(aBoxS.IsOut(theBoxCurve)) {
1653         bHasOutV = Standard_True;
1654         continue;
1655       }
1656       
1657       IntTools_ListOfBox aListOfBox;
1658       TColStd_ListOfInteger aListOfIndex;
1659       
1660       Standard_Boolean bHasOutC = Standard_False;
1661       Standard_Integer aCurIndex = aCurIndexInit;
1662       
1663       // ////////////////////////////
1664       aCurPar = aRangeC.First();
1665       aPrevPar = aRangeC.First();
1666       IntTools_CurveRangeSample aCurRangeC = aNewRangeCTemplate;
1667       
1668       for (tIt = 1; tIt <= nbC; tIt++, aCurIndex++, aPrevPar = aCurPar) {
1669         
1670         aCurPar += localdiffC;
1671         
1672         // ignore already computed. begin
1673         Standard_Boolean bFound = Standard_False;
1674         TColStd_ListIteratorOfListOfInteger anItToAvoid(aListCToAvoid);
1675
1676         for(; anItToAvoid.More(); anItToAvoid.Next()) {
1677           if(tIt == anItToAvoid.Value()) {
1678             bFound = Standard_True;
1679             break;
1680           }
1681         }
1682         
1683         if(!bFound) {
1684           if(bAllowSamplingC) {
1685             aCurRangeC.SetRangeIndex(aCurIndex);
1686           }
1687           bFound = theCurveData.IsRangeOut(aCurRangeC);
1688         }
1689         
1690         if(bFound) {
1691           bHasOutC = Standard_True;
1692           continue;
1693         }
1694         // ignore already computed. end
1695         
1696         // compute Box
1697         Bnd_Box aBoxC;
1698         
1699         if(!theCurveData.FindBox(aCurRangeC, aBoxC)) {
1700           BndLib_Add3dCurve::Add(myCurve, aPrevPar, aCurPar, myCriteria, aBoxC);
1701             
1702             //   Bnd_Box aMainBoxS;
1703             
1704             if(!bMainBoxFoundS && theSurfaceData.FindBox(aRootRangeS, aMainBoxS)) {
1705               bMainBoxFoundS = Standard_True;
1706             }
1707             if(aBoxC.IsOut(aMainBoxS)) {
1708               theCurveData.AddOutRange(aCurRangeC);
1709               bHasOutC = Standard_True;
1710               continue;
1711             }
1712             //   }
1713             theCurveData.AddBox(aCurRangeC, aBoxC);
1714           }
1715         
1716         if(!bGlobalCheckDone && aBoxC.IsOut(theBoxSurface)) {
1717           aListCToAvoid.Append(tIt);
1718           bHasOutC = Standard_True;
1719           continue;
1720         }
1721         
1722         if(aBoxC.IsOut(aBoxS)) {
1723           bHasOutV = Standard_True;
1724           bHasOutC = Standard_True;
1725           continue;
1726         }
1727         //
1728         
1729         aListOfIndex.Append(tIt);
1730         aListOfBox.Append(aBoxC);
1731       } // end for(tIt...)
1732       
1733       bGlobalCheckDone = Standard_True;
1734       
1735       if(bHasOutC) {
1736         bHasOutV = Standard_True;
1737       }
1738       
1739       // //////////////
1740       //
1741       
1742       IntTools_CurveRangeSample aNewRangeC = aNewRangeCTemplate;
1743       
1744       aCurIndex = aCurIndexInit;
1745       TColStd_ListIteratorOfListOfInteger anItI(aListOfIndex);
1746       IntTools_ListIteratorOfListOfBox anItBox(aListOfBox);
1747       Standard_Boolean bUseOldC = Standard_False;
1748       Standard_Boolean bUseOldS = Standard_False;
1749       Standard_Boolean bCheckSize = !bHasOutC;
1750       
1751       for(; anItI.More() && anItBox.More(); anItI.Next(), anItBox.Next()) {
1752         aCurIndex = aCurIndexInit + anItI.Value() - 1;
1753
1754         bUseOldS = Standard_False;
1755         
1756         if(bAllowSamplingC) {
1757           aNewRangeC.SetRangeIndex(aCurIndex);
1758         }
1759         
1760         
1761         if(bCheckSize) {
1762           
1763           if((theCurveRange.GetDepth() == 0) ||
1764              (theSurfaceRange.GetDepthU() == 0) ||
1765              (theSurfaceRange.GetDepthV() == 0)) {
1766             bHasOutC = Standard_True;
1767             bHasOutV = Standard_True;
1768           }
1769           else if((theCurveRange.GetDepth() < 4) &&
1770                   (theSurfaceRange.GetDepthU() < 4) &&
1771                   (theSurfaceRange.GetDepthV() < 4)) {
1772             Bnd_Box aBoxC = anItBox.Value();
1773             
1774             if(!aBoxC.IsWhole() && !aBoxS.IsWhole()) {
1775               Standard_Real aDiagC = aBoxC.SquareExtent();
1776               Standard_Real aDiagS = aBoxS.SquareExtent();
1777               
1778               if(aDiagC < aDiagS) {
1779                 if((aDiagC * 10.) < aDiagS) {
1780                   bUseOldC = Standard_True;
1781                   bHasOutC = Standard_True;
1782                   bHasOutV = Standard_True;
1783                   break;
1784                 }
1785               }
1786               else {
1787                 if((aDiagS * 10.) < aDiagC) {
1788                   bUseOldS = Standard_True;
1789                   bHasOutC = Standard_True;
1790                   bHasOutV = Standard_True;
1791                 }
1792               }
1793             }
1794           }
1795         }
1796         
1797         
1798         if(!bHasOutC) {
1799           aListCurveRangeFound.Append(aNewRangeC);
1800           aListSurfaceRangeFound.Append(aNewRangeS);
1801         }
1802         else {
1803           
1804           //   if(bUseOldS || bAllowSamplingU || bAllowSamplingV) {
1805           //     theSurfaceData.AddBox(aNewRangeS, aBoxS);
1806           //   }
1807           
1808           if(bUseOldS && aNewRangeC.IsEqual(theCurveRange)) {
1809             return Standard_False;
1810           }
1811           
1812           if(!LocalizeSolutions(aNewRangeC, anItBox.Value(), 
1813                                 ((bUseOldS) ? theSurfaceRange : aNewRangeS), 
1814                                 ((bUseOldS) ? theBoxSurface : aBoxS),
1815                                 theCurveData, theSurfaceData,
1816                                 theListCurveRange, theListSurfaceRange))
1817             return Standard_False;
1818         }
1819       }
1820       // end (tIt...)
1821       aListOfIndex.Clear();
1822       aListOfBox.Clear();
1823       
1824       if(bHasOutV) {
1825         //      theSurfaceData.AddBox(aNewRangeS, aBoxS);
1826         
1827         if(bUseOldC && bAllowSamplingC && (bAllowSamplingU || bAllowSamplingV)) {
1828           if(!LocalizeSolutions(theCurveRange, theBoxCurve,
1829                                 aNewRangeS, aBoxS, 
1830                                 theCurveData, theSurfaceData,
1831                                 theListCurveRange, theListSurfaceRange))
1832             return Standard_False;
1833         }
1834       }
1835     } // end for (vIt...)
1836     
1837     if(bHasOutV) {
1838       bHasOut = Standard_True;
1839     }
1840   }
1841
1842   if(!bHasOut) {
1843     theListCurveRange.Append(theCurveRange);
1844     theListSurfaceRange.Append(theSurfaceRange);    
1845   }
1846   else {
1847     IntTools_ListIteratorOfListOfCurveRangeSample anIt1(aListCurveRangeFound);
1848     IntTools_ListIteratorOfListOfSurfaceRangeSample anIt2(aListSurfaceRangeFound);
1849
1850     for(; anIt1.More() && anIt2.More(); anIt1.Next(), anIt2.Next()) {
1851       theListCurveRange.Append(anIt1.Value());
1852       theListSurfaceRange.Append(anIt2.Value());
1853     }
1854   }
1855   return Standard_True;
1856 }
1857
1858
1859 // ======================================================================================================================
1860 // function: ComputeLocalized
1861 // purpose: 
1862 // ======================================================================================================================
1863 Standard_Boolean IntTools_BeanFaceIntersector::ComputeLocalized() {
1864   Standard_Real Tol = Precision::PConfusion();
1865   
1866   IntTools_SurfaceRangeSample aSurfaceRange(0, 0, 0, 0);
1867   Standard_Real dMinU = 10. * Precision::PConfusion();
1868   Standard_Real dMinV = dMinU;
1869   IntTools_SurfaceRangeLocalizeData aSurfaceDataInit(3, 3, dMinU, dMinV);
1870   IntTools_SurfaceRangeLocalizeData& aSurfaceData = myContext->SurfaceData(mySurface.Face());
1871   aSurfaceData.RemoveRangeOutAll();
1872   aSurfaceData.ClearGrid();
1873   
1874   Bnd_Box FBox;
1875   Standard_Boolean bFBoxFound = aSurfaceData.FindBox(aSurfaceRange, FBox);
1876   
1877   if(mySurface.GetType() == GeomAbs_BSplineSurface) {
1878     Handle(Geom_BSplineSurface) aSurfBspl = Handle(Geom_BSplineSurface)::DownCast(myTrsfSurface);
1879     
1880     ComputeGridPoints(aSurfBspl, myUMinParameter, myUMaxParameter,
1881                       myVMinParameter, myVMaxParameter, myFaceTolerance,
1882                       aSurfaceData);
1883     
1884     if(!bFBoxFound) {
1885       FBox = GetSurfaceBox(aSurfBspl, myUMinParameter, myUMaxParameter,
1886                            myVMinParameter, myVMaxParameter, myCriteria,
1887                            aSurfaceData);
1888       aSurfaceData.AddBox(aSurfaceRange, FBox);
1889     }
1890     
1891   } else if(!bFBoxFound) {
1892     
1893     BndLib_AddSurface::Add(mySurface, myUMinParameter, myUMaxParameter, myVMinParameter, myVMaxParameter, myFaceTolerance, FBox);
1894       aSurfaceData.AddBox(aSurfaceRange, FBox);
1895     }
1896   
1897   Bnd_Box EBox;
1898   
1899   BndLib_Add3dCurve::Add(myCurve.Trim(myFirstParameter, myLastParameter, Precision::PConfusion())->Curve(), myBeanTolerance, EBox);
1900   
1901   if(EBox.IsOut(FBox)) {
1902     for(Standard_Integer i = 1; i <= myRangeManager.Length(); i++) {
1903       myRangeManager.SetFlag(i, 1);
1904     }
1905     aSurfaceData.ClearGrid();
1906
1907     return Standard_True;
1908   }
1909   
1910   IntTools_ListOfCurveRangeSample aListCurveRange;
1911   IntTools_ListOfSurfaceRangeSample aListSurfaceRange;
1912   
1913   IntTools_CurveRangeSample aCurveRange(0);
1914   aCurveRange.SetDepth(0);
1915   Standard_Integer nbSampleC = 3;
1916   Standard_Integer nbSampleU = aSurfaceData.GetNbSampleU();
1917   Standard_Integer nbSampleV = aSurfaceData.GetNbSampleV();
1918   Standard_Real dMinC = 10. * myCurveResolution;
1919   IntTools_ListOfCurveRangeSample aListOut;
1920   
1921   // check
1922   Standard_Boolean bAllowSamplingC = Standard_True;
1923   Standard_Boolean bAllowSamplingU = Standard_True;
1924   Standard_Boolean bAllowSamplingV = Standard_True;
1925   IntTools_CurveRangeLocalizeData aCurveDataTmp(nbSampleC, dMinC);
1926   IntTools_SurfaceRangeLocalizeData aSurfaceDataTmp(nbSampleU, nbSampleV, dMinU, dMinV);
1927   
1928   CheckSampling(aCurveRange, aSurfaceRange, aCurveDataTmp, aSurfaceDataTmp,
1929                 myLastParameter - myFirstParameter,
1930                 myUMaxParameter - myUMinParameter,
1931                 myVMaxParameter - myVMinParameter,
1932                 bAllowSamplingC, bAllowSamplingU, bAllowSamplingV);
1933   
1934   
1935   {
1936     IntTools_CurveRangeLocalizeData aCurveData(nbSampleC, dMinC);
1937     
1938     aCurveData.AddBox(aCurveRange, EBox);
1939     
1940     if(!LocalizeSolutions(aCurveRange, EBox, aSurfaceRange, FBox, 
1941                           aCurveData, aSurfaceData,
1942                           aListCurveRange, aListSurfaceRange)) {
1943       aSurfaceData.ClearGrid();
1944       
1945       return Standard_False;
1946     }
1947     
1948     IntTools_ListOfCurveRangeSample aListCurveRangeSort;
1949     IntTools_ListOfSurfaceRangeSample aListSurfaceRangeSort;
1950     
1951     MergeSolutions(aListCurveRange, aListSurfaceRange, aListCurveRangeSort, aListSurfaceRangeSort);
1952     
1953     IntTools_ListIteratorOfListOfCurveRangeSample anItC(aListCurveRangeSort);
1954     IntTools_ListIteratorOfListOfSurfaceRangeSample anItS(aListSurfaceRangeSort);
1955     IntTools_SurfaceRangeSample aRangeSPrev;
1956     
1957     Extrema_GenExtCS anExtremaGen;
1958     
1959     for(; anItC.More() && anItS.More(); anItC.Next(), anItS.Next()) {
1960       
1961       IntTools_Range aRangeC(myFirstParameter, myLastParameter);
1962
1963       if(bAllowSamplingC) 
1964         aRangeC = anItC.Value().GetRange(myFirstParameter, myLastParameter, nbSampleC);
1965       
1966       IntTools_Range aRangeU(myUMinParameter, myUMaxParameter);
1967
1968       if(bAllowSamplingU) 
1969         aRangeU = anItS.Value().GetRangeU(myUMinParameter, myUMaxParameter, nbSampleU);
1970       
1971       IntTools_Range aRangeV(myVMinParameter, myVMaxParameter);
1972       
1973       if(bAllowSamplingV) 
1974         aRangeV = anItS.Value().GetRangeV(myVMinParameter, myVMaxParameter, nbSampleV);
1975       
1976       Standard_Real anarg1 = aRangeC.First(), anarg2 = aRangeC.Last();
1977       
1978       Standard_Boolean bFound = Standard_False;
1979       
1980       Standard_Integer nMinIndex = myRangeManager.Length();
1981       Standard_Integer nMaxIndex = -1;
1982       const TColStd_SequenceOfInteger& anInds1 = myRangeManager.GetIndices(anarg1);
1983       Standard_Integer indIt = 1;
1984
1985       for(indIt = 1 ; indIt <= anInds1.Length(); indIt++) {
1986         Standard_Integer nIndex = anInds1.Value(indIt);
1987         nMinIndex = (nMinIndex > nIndex) ? nIndex : nMinIndex;
1988         nMaxIndex = (nMaxIndex < nIndex) ? nIndex : nMaxIndex;
1989       }
1990       
1991       for(indIt = nMinIndex ; indIt <= nMaxIndex; indIt++) {
1992         if(myRangeManager.Flag(indIt) == 2) {
1993           bFound = Standard_True;
1994   break;
1995         }
1996       }
1997       
1998       if(bFound)
1999         continue;
2000       nMinIndex = (nMaxIndex >= 0) ? nMaxIndex : nMinIndex;
2001       const TColStd_SequenceOfInteger& anInds2 = myRangeManager.GetIndices(anarg2);
2002       
2003       for(indIt = 1 ; indIt <= anInds2.Length(); indIt++) {
2004         Standard_Integer nIndex = anInds2.Value(indIt);
2005         nMinIndex = (nMinIndex > nIndex) ? nIndex : nMinIndex;
2006         nMaxIndex = (nMaxIndex < nIndex) ? nIndex : nMaxIndex;
2007       }
2008
2009       for(indIt = nMinIndex ; indIt <= nMaxIndex; indIt++) {
2010         if(myRangeManager.Flag(indIt) == 2) {
2011           bFound = Standard_True;
2012           break;
2013         }
2014       }
2015       
2016       if(bFound)
2017         continue;
2018       
2019       Standard_Real parUF = aRangeU.First(), parUL = aRangeU.Last();
2020       Standard_Real parVF = aRangeV.First(), parVL = aRangeV.Last();
2021       
2022       if(aRangeSPrev.IsEqual(anItS.Value())) {
2023         anExtremaGen.Perform(myCurve, 10, anarg1, anarg2, Tol);
2024       }
2025       else {
2026         anExtremaGen.Initialize(mySurface, 10, 10, parUF, parUL, parVF, parVL, Tol);
2027         anExtremaGen.Perform(myCurve, 10, anarg1, anarg2, Tol);
2028       }
2029       
2030       if(anExtremaGen.IsDone() && (anExtremaGen.NbExt() > 0)) {
2031         
2032         for(Standard_Integer j = 1 ; j <= anExtremaGen.NbExt(); j++) {
2033
2034           if(anExtremaGen.SquareDistance(j) < myCriteria * myCriteria) {
2035             
2036             Extrema_POnCurv p1;
2037             Extrema_POnSurf p2;
2038             p1 = anExtremaGen.PointOnCurve(j);
2039             p2 = anExtremaGen.PointOnSurface(j);
2040             Standard_Real U, V, T;
2041             T = p1.Parameter();
2042             p2.Parameter(U, V);
2043             
2044             if (myCurve.IsPeriodic())
2045               T = ElCLib::InPeriod(T, anarg1, anarg1 + myCurve.Period());
2046             if (mySurface.IsUPeriodic())
2047               U = ElCLib::InPeriod(U, parUF, parUF + mySurface.UPeriod());
2048             if (mySurface.IsVPeriodic())
2049               V = ElCLib::InPeriod(V, parVF, parVF + mySurface.VPeriod());
2050             
2051             //To avoid occasional going out of boundaries because of numerical
2052             //problem
2053             if(U < myUMinParameter) U = myUMinParameter;
2054             if(U > myUMaxParameter) U = myUMaxParameter;
2055             if(V < myVMinParameter) V = myVMinParameter;
2056             if(V > myVMaxParameter) V = myVMaxParameter;
2057             
2058             Standard_Integer aNbRanges = myRangeManager.Length();
2059             ComputeRangeFromStartPoint(Standard_False, T, U, V);
2060             ComputeRangeFromStartPoint(Standard_True, T, U, V);
2061             
2062             if(aNbRanges == myRangeManager.Length()) {
2063               SetEmptyResultRange(T, myRangeManager);
2064             }
2065           }
2066         } //end for
2067       }
2068       else {
2069         myRangeManager.InsertRange(anarg1, anarg2, 0);
2070       }
2071       
2072       aRangeSPrev = anItS.Value();
2073     }
2074     
2075     //
2076     aCurveData.ListRangeOut(aListOut);
2077   }
2078   
2079   //
2080   if(bAllowSamplingC) {
2081     IntTools_ListIteratorOfListOfCurveRangeSample anItC(aListOut);
2082     
2083     for(; anItC.More(); anItC.Next()) {
2084       IntTools_Range aRangeC =anItC.Value().GetRange(myFirstParameter, myLastParameter, nbSampleC);
2085       myRangeManager.InsertRange(aRangeC.First(), aRangeC.Last(), 1);
2086     }
2087   }
2088   ComputeNearRangeBoundaries();
2089   
2090   aSurfaceData.ClearGrid();
2091
2092   return Standard_True;
2093 }
2094
2095 // ======================================================================================================================
2096 // function: TestComputeCoinside
2097 // purpose: 
2098 // ======================================================================================================================
2099 Standard_Boolean IntTools_BeanFaceIntersector::TestComputeCoinside()
2100 {
2101   Standard_Real cfp = myFirstParameter, clp = myLastParameter;
2102   const Standard_Integer nbSeg = 23;
2103   Standard_Real cdp = (clp - cfp) / (Standard_Real )nbSeg;
2104
2105   Standard_Integer i = 0;
2106
2107   Standard_Real U, V;
2108
2109   if(Distance(cfp, U, V) > myCriteria)
2110     return Standard_False;
2111
2112   //
2113   ComputeRangeFromStartPoint(Standard_True, cfp, U, V);
2114   //
2115
2116   Standard_Integer aFoundIndex = myRangeManager.GetIndex(clp, Standard_False );
2117
2118   if(aFoundIndex != 0) {
2119     if(myRangeManager.Flag(aFoundIndex) == 2)
2120       return Standard_True;
2121   }
2122
2123   if(Distance(clp, U, V) > myCriteria)
2124     return Standard_False;
2125
2126   //
2127   ComputeRangeFromStartPoint(Standard_False, clp, U, V);
2128   //
2129
2130   for(i = 1; i < nbSeg; i++) {
2131     Standard_Real aPar = (cfp+((Standard_Real)i)*cdp);
2132
2133     if(Distance(aPar, U, V) > myCriteria) 
2134       return Standard_False;
2135
2136     Standard_Integer aNbRanges = myRangeManager.Length();
2137     ComputeRangeFromStartPoint(Standard_False, aPar, U, V);
2138     ComputeRangeFromStartPoint(Standard_True, aPar, U, V);
2139
2140     if(aNbRanges == myRangeManager.Length()) {
2141       SetEmptyResultRange(aPar, myRangeManager);
2142     }
2143   }
2144
2145   return Standard_True;
2146 }
2147
2148 //  Modified by skv - Wed Nov  2 15:21:11 2005 Optimization Begin
2149 // ---------------------------------------------------------------------------------
2150 // static function: GetSurfaceBox
2151 // purpose:  
2152 // ---------------------------------------------------------------------------------
2153 Bnd_Box GetSurfaceBox(const Handle(Geom_BSplineSurface)        &theSurf,
2154                       const Standard_Real                       theFirstU,
2155                       const Standard_Real                       theLastU,
2156                       const Standard_Real                       theFirstV,
2157                       const Standard_Real                       theLastV,
2158                       const Standard_Real                       theTolerance,
2159                       IntTools_SurfaceRangeLocalizeData  &theSurfaceData)
2160 {
2161   Bnd_Box              aTotalBox;
2162   
2163   BuildBox(theSurf, theFirstU, theLastU, theFirstV, theLastV,
2164            theSurfaceData, aTotalBox);
2165
2166   aTotalBox.Enlarge(theTolerance);
2167   return aTotalBox;
2168 }
2169
2170
2171 // ---------------------------------------------------------------------------------
2172 // static function: ComputeGridPoints
2173 // purpose:  
2174 // ---------------------------------------------------------------------------------
2175 void ComputeGridPoints
2176   (const Handle(Geom_BSplineSurface)       &theSurf,
2177    const Standard_Real                      theFirstU,
2178    const Standard_Real                      theLastU,
2179    const Standard_Real                      theFirstV,
2180    const Standard_Real                      theLastV,
2181    const Standard_Real                      theTolerance,
2182    IntTools_SurfaceRangeLocalizeData &theSurfaceData)
2183 {
2184   Standard_Integer     i;
2185   Standard_Integer     j;
2186   Standard_Integer     k;
2187   Standard_Integer     aNbSamples[2] = { theSurf->UDegree(),
2188                                          theSurf->VDegree() };
2189   Standard_Integer     aNbKnots[2]   = { theSurf->NbUKnots(),
2190                                          theSurf->NbVKnots() };
2191   TColStd_Array1OfReal aKnotsU(1, aNbKnots[0]);
2192   TColStd_Array1OfReal aKnotsV(1, aNbKnots[1]);
2193
2194   theSurf->UKnots(aKnotsU);
2195   theSurf->VKnots(aKnotsV);
2196
2197   Standard_Integer iLmI;
2198   Standard_Integer iMin[2]   = { -1, -1 };
2199   Standard_Integer iMax[2]   = { -1, -1 };
2200   Standard_Integer aNbGridPnts[2];
2201   Standard_Real    aFPar[2]  = { theFirstU, theFirstV};
2202   Standard_Real    aLPar[2]  = { theLastU,  theLastV};
2203   Standard_Real    aFpTol[2] = { aFPar[0] + theTolerance,
2204                                  aFPar[1] + theTolerance };
2205   Standard_Real    aFmTol[2] = { aFPar[0] - theTolerance,
2206                                  aFPar[1] - theTolerance };
2207   Standard_Real    aLpTol[2] = { aLPar[0] + theTolerance,
2208                                  aLPar[1] + theTolerance };
2209   Standard_Real    aLmTol[2] = { aLPar[0] - theTolerance,
2210                                  aLPar[1] - theTolerance };
2211   
2212
2213   // Compute number of U and V grid points.
2214   for (j = 0; j < 2; j++) {
2215     const TColStd_Array1OfReal &aKnots = (j == 0) ? aKnotsU : aKnotsV;
2216     
2217     for (i = 1; i <= aNbKnots[j] && (iMin[j] == -1 || iMax[j] == -1); i++) {
2218       if (iMin[j] == -1 && aFpTol[j] < aKnots.Value(i))
2219         iMin[j] = i - 1;
2220       
2221       iLmI = aNbKnots[j] - i + 1;
2222       
2223       if (iMax[j] == -1 && aLmTol[j] > aKnots.Value(iLmI))
2224         iMax[j] = iLmI + 1;
2225     }
2226     
2227     // If indices are not found, return.
2228     //if (iMin[j] == -1 || iMax[j] == -1)
2229       //return;
2230     if(iMin[j] == -1)
2231       iMin[j] = 1;
2232
2233     if (iMax[j] == -1)
2234       iMax[j] = aNbKnots[j];
2235
2236     if (iMin[j] == 0)
2237       iMin[j] = 1;
2238
2239     if (iMax[j] > aNbKnots[j])
2240       iMax[j] = aNbKnots[j];
2241
2242     if (iMax[j] < iMin[j])
2243       return;
2244
2245     if (iMax[j] == iMin[j]) {
2246       iMax[j]++;
2247       iMin[j]--;
2248       if (iMin[j] == 0)
2249         iMin[j] = 1;
2250       if (iMax[j] > aNbKnots[j])
2251         iMax[j] = aNbKnots[j];
2252
2253     }
2254
2255     aNbGridPnts[j] = (iMax[j] - iMin[j])*aNbSamples[j] + 1;
2256
2257   // Setting the number of grid points.
2258     if (j == 0)
2259       theSurfaceData.SetRangeUGrid(aNbGridPnts[j]);
2260     else // j == 1
2261       theSurfaceData.SetRangeVGrid(aNbGridPnts[j]);
2262     
2263     // Setting the first and last parameters.
2264     Standard_Integer iAbs    = 1;
2265     Standard_Real    aMinPar;
2266     Standard_Real    aMaxPar = (j == 0) ? theLastU : theLastV;
2267     
2268     for (i = iMin[j]; i < iMax[j]; i++) {
2269       // Get the first parameter.
2270       if (i == iMin[j]) {
2271         // The first knot.
2272         if (aFmTol[j] > aKnots.Value(iMin[j]))
2273           aMinPar = aFPar[j];
2274         else
2275           aMinPar = aKnots.Value(iMin[j]);
2276       } else {
2277         aMinPar = aKnots.Value(i);
2278       }
2279       
2280       // Get the last parameter.
2281       if (i == iMax[j] - 1) {
2282         // The last knot.
2283         if (aLpTol[j] < aKnots.Value(iMax[j]))
2284           aMaxPar = aLPar[j];
2285         else
2286           aMaxPar = aKnots.Value(iMax[j]);
2287       } else {
2288         aMaxPar = aKnots.Value(i + 1);
2289       }
2290       
2291       // Compute grid parameters.
2292       Standard_Real aDelta = (aMaxPar - aMinPar)/aNbSamples[j];
2293       
2294       for (k = 0; k < aNbSamples[j]; k++, aMinPar += aDelta) {
2295         if (j == 0)
2296           theSurfaceData.SetUParam(iAbs++, aMinPar);
2297         else
2298           theSurfaceData.SetVParam(iAbs++, aMinPar);
2299       }
2300     }
2301     
2302     // Add the last parameter
2303     if (j == 0)
2304       theSurfaceData.SetUParam(iAbs++, aMaxPar);
2305     else
2306       theSurfaceData.SetVParam(iAbs++, aMaxPar);
2307   }
2308   
2309   // Compute of grid points.
2310   gp_Pnt        aPnt;
2311   Standard_Real aParU;
2312   Standard_Real aParV;
2313   
2314   for (i = 1; i <= aNbGridPnts[0]; i++) {
2315     aParU = theSurfaceData.GetUParam(i);
2316     
2317     for (j = 1; j <= aNbGridPnts[1]; j++) {
2318       aParV = theSurfaceData.GetVParam(j);
2319       
2320       theSurf->D0(aParU, aParV, aPnt);
2321       theSurfaceData.SetGridPoint(i, j, aPnt);
2322     }
2323   }
2324
2325   // Compute deflection.
2326   Standard_Real aDef = 0.;
2327 //   Standard_Real aDefLin;
2328 //   Standard_Real aParMid;
2329 //   Standard_Real aParConst;
2330 //   Standard_Real aDistPP;
2331 //   gp_Pnt        aPntMid;
2332 //   gp_Vec        aVec;
2333 //   gp_XYZ        aCoord;
2334
2335 //   // Compute DU deflection.
2336 //   for (i = 1; i < aNbGridPnts[0]; i++) {
2337 //     aParMid = 0.5*(theSurfaceData.GetUParam(i + 1) +
2338 //         theSurfaceData.GetUParam(i));
2339
2340 //     for (j = 1; j <= aNbGridPnts[1]; j++) {
2341 //       const gp_Pnt &thePnt1 = theSurfaceData.GetGridPoint(i,     j);
2342 //       const gp_Pnt &thePnt2 = theSurfaceData.GetGridPoint(i + 1, j);
2343
2344 //       aVec.SetXYZ(thePnt2.XYZ().Subtracted(thePnt1.XYZ()));
2345 //       aDistPP = aVec.Magnitude();
2346
2347 //       if (aDistPP > theTolerance) {
2348 //      // Computation of a distance of a middle point from the line P1 - P2.
2349 //      aParConst = theSurfaceData.GetVParam(j);
2350 //      theSurf->D0(aParMid, aParConst, aPntMid);
2351 //      aCoord = aPntMid.XYZ();
2352 //      aCoord.Subtract(thePnt1.XYZ());
2353 //      aCoord.Cross (aVec.XYZ());
2354 //      aCoord.Divide(aDistPP);
2355 //      aDefLin = aCoord.Modulus();
2356
2357 //      if (aDefLin > aDef)
2358 //   aDef = aDefLin;
2359 //       }
2360 //     }
2361 //   }
2362
2363 //   // Compute DV deflection.
2364 //   for (j = 1; j < aNbGridPnts[1]; j++) {
2365 //     aParMid = 0.5*(theSurfaceData.GetVParam(j + 1) +
2366 //         theSurfaceData.GetVParam(j));
2367
2368 //     for (i = 1; i <= aNbGridPnts[0]; i++) {
2369 //       const gp_Pnt &thePnt1 = theSurfaceData.GetGridPoint(i, j);
2370 //       const gp_Pnt &thePnt2 = theSurfaceData.GetGridPoint(i, j + 1);
2371
2372 //       aVec.SetXYZ(thePnt2.XYZ().Subtracted(thePnt1.XYZ()));
2373 //       aDistPP = aVec.Magnitude();
2374
2375 //       if (aDistPP > theTolerance) {
2376 //      // Computation of a distance of a middle point from the line P1 - P2.
2377 //      aParConst = theSurfaceData.GetUParam(i);
2378 //      theSurf->D0(aParConst, aParMid, aPntMid);
2379 //      aCoord = aPntMid.XYZ();
2380 //      aCoord.Subtract(thePnt1.XYZ());
2381 //      aCoord.Cross (aVec.XYZ());
2382 //      aCoord.Divide(aDistPP);
2383 //      aDefLin = aCoord.Modulus();
2384
2385 //      if (aDefLin > aDef)
2386 //   aDef = aDefLin;
2387 //       }
2388 //     }
2389 //   }
2390
2391   if (theTolerance > aDef)
2392     aDef = theTolerance;
2393
2394   aDef *= 2.;
2395   theSurfaceData.SetGridDeflection(aDef);
2396 }
2397
2398 // ---------------------------------------------------------------------------------
2399 // static function: BuildBox
2400 // purpose:  Compute bounding box.
2401 // ---------------------------------------------------------------------------------
2402 void BuildBox(const Handle(Geom_BSplineSurface)       &theSurf,
2403       const Standard_Real                      theFirstU,
2404       const Standard_Real                      theLastU,
2405       const Standard_Real                      theFirstV,
2406       const Standard_Real                      theLastV,
2407             IntTools_SurfaceRangeLocalizeData &theSurfaceData,
2408               Bnd_Box                           &theBox)
2409 {
2410   Standard_Integer i;
2411   Standard_Integer j;
2412   Standard_Integer aNbUPnts;
2413   Standard_Integer aNbVPnts;
2414   Standard_Real    aParam;
2415   gp_Pnt           aPnt;
2416
2417   theSurfaceData.SetFrame(theFirstU, theLastU, theFirstV, theLastV);
2418   aNbUPnts = theSurfaceData.GetNBUPointsInFrame();
2419   aNbVPnts = theSurfaceData.GetNBVPointsInFrame();
2420
2421   // Add corner points.
2422   theSurf->D0(theFirstU, theFirstV, aPnt);
2423   theBox.Add(aPnt);
2424   theSurf->D0(theLastU,  theFirstV, aPnt);
2425   theBox.Add(aPnt);
2426   theSurf->D0(theFirstU, theLastV, aPnt);
2427   theBox.Add(aPnt);
2428   theSurf->D0(theLastU,  theLastV, aPnt);
2429   theBox.Add(aPnt);
2430
2431   for (i = 1; i <= aNbUPnts; i++) {
2432     // Add top and bottom points.
2433     aParam = theSurfaceData.GetUParamInFrame(i);
2434     theSurf->D0(aParam, theFirstV, aPnt);
2435     theBox.Add(aPnt);
2436     theSurf->D0(aParam, theLastV, aPnt);
2437     theBox.Add(aPnt);
2438
2439     // Add internal points.
2440     for (j = 1; j <= aNbVPnts; j++) {
2441       const gp_Pnt &aGridPnt = theSurfaceData.GetPointInFrame(i, j);
2442
2443       theBox.Add(aGridPnt);
2444     }
2445   }
2446
2447   // Add left and right points.
2448   for (j = 1; j <= aNbVPnts; j++) {
2449     aParam = theSurfaceData.GetVParamInFrame(j);
2450     theSurf->D0(theFirstU, aParam, aPnt);
2451     theBox.Add(aPnt);
2452     theSurf->D0(theLastU,  aParam, aPnt);
2453     theBox.Add(aPnt);
2454   }
2455
2456   theBox.Enlarge(theSurfaceData.GetGridDeflection());
2457 }
2458 //  Modified by skv - Wed Nov  2 15:21:11 2005 Optimization End
2459
2460
2461 // ---------------------------------------------------------------------------------
2462 // static function: MergeSolutions
2463 // purpose:  
2464 // ---------------------------------------------------------------------------------
2465 static void MergeSolutions(const IntTools_ListOfCurveRangeSample& theListCurveRange,
2466                            const IntTools_ListOfSurfaceRangeSample& theListSurfaceRange,
2467                            IntTools_ListOfCurveRangeSample& theListCurveRangeSort,
2468                            IntTools_ListOfSurfaceRangeSample& theListSurfaceRangeSort) {
2469   
2470   IntTools_ListIteratorOfListOfCurveRangeSample anItC2;
2471   IntTools_ListIteratorOfListOfSurfaceRangeSample anItS1(theListSurfaceRange), anItS2;
2472   IntTools_MapOfSurfaceSample aMapToAvoid;
2473
2474   for(; anItS1.More(); anItS1.Next()) {
2475     const IntTools_SurfaceRangeSample& aRangeS = anItS1.Value();
2476
2477     if(aMapToAvoid.Contains(aRangeS))
2478       continue;
2479     aMapToAvoid.Add(aRangeS);
2480
2481     anItC2.Initialize(theListCurveRange);
2482     anItS2.Initialize(theListSurfaceRange);
2483
2484     for(; anItS2.More() && anItC2.More(); anItS2.Next(), anItC2.Next()) {
2485       if(aRangeS.IsEqual(anItS2.Value())) {
2486         theListCurveRangeSort.Append(anItC2.Value());
2487         theListSurfaceRangeSort.Append(anItS2.Value());
2488       }
2489     }
2490   }
2491 }
2492
2493 // ---------------------------------------------------------------------------------
2494 // static function: CheckSampling
2495 // purpose:  
2496 // ---------------------------------------------------------------------------------
2497 static void CheckSampling(const IntTools_CurveRangeSample& theCurveRange,
2498                           const IntTools_SurfaceRangeSample& theSurfaceRange,
2499                           const IntTools_CurveRangeLocalizeData& theCurveData,
2500                           const IntTools_SurfaceRangeLocalizeData& theSurfaceData,
2501                           const Standard_Real DiffC,
2502                           const Standard_Real DiffU,
2503                           const Standard_Real DiffV,
2504                           Standard_Boolean& bAllowSamplingC,
2505                           Standard_Boolean& bAllowSamplingU,
2506                           Standard_Boolean& bAllowSamplingV) {
2507   
2508   const Standard_Real dLimit = 1000;
2509   bAllowSamplingC = Standard_True;
2510   bAllowSamplingU = Standard_True;
2511   bAllowSamplingV = Standard_True;
2512
2513   // check
2514   if((pow((Standard_Real)theCurveData.GetNbSample(), (Standard_Real )(theCurveRange.GetDepth() + 1)) > dLimit) ||
2515      ((DiffC / theCurveData.GetNbSample()) < theCurveData.GetMinRange())) {
2516     bAllowSamplingC = Standard_False;
2517   }
2518
2519   if((pow((Standard_Real )theSurfaceData.GetNbSampleU(), (Standard_Real )(theSurfaceRange.GetDepthU() + 1)) > dLimit) ||
2520      ((DiffU / theSurfaceData.GetNbSampleU()) < theSurfaceData.GetMinRangeU())) {
2521     bAllowSamplingU = Standard_False;
2522   }
2523   
2524
2525   if((pow((Standard_Real )theSurfaceData.GetNbSampleV(), (Standard_Real )(theSurfaceRange.GetDepthV() + 1)) > dLimit) ||
2526      ((DiffV / theSurfaceData.GetNbSampleV()) < theSurfaceData.GetMinRangeV())) {
2527     bAllowSamplingV = Standard_False;
2528   }
2529 }