0031307: Modeling Algorithms - Offset algorithm produces incorrect result in mode...
[occt.git] / src / BRepOffset / BRepOffset_Inter2d.cxx
1 // Created on: 1996-09-03
2 // Created by: Yves FRICAUD
3 // Copyright (c) 1996-1999 Matra Datavision
4 // Copyright (c) 1999-2014 OPEN CASCADE SAS
5 //
6 // This file is part of Open CASCADE Technology software library.
7 //
8 // This library is free software; you can redistribute it and/or modify it under
9 // the terms of the GNU Lesser General Public License version 2.1 as published
10 // by the Free Software Foundation, with special exception defined in the file
11 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
12 // distribution for complete text of the license and disclaimer of any warranty.
13 //
14 // Alternatively, this file may be used under the terms of Open CASCADE
15 // commercial license or contractual agreement.
16
17 //  Modified by skv - Wed Dec 24 18:08:39 2003 OCC4455
18
19 #include <Adaptor2d_HCurve2d.hxx>
20 #include <Adaptor3d_CurveOnSurface.hxx>
21 #include <Adaptor3d_HSurface.hxx>
22 #include <Bnd_Box.hxx>
23 #include <BndLib_Add3dCurve.hxx>
24 #include <BOPTools_AlgoTools.hxx>
25 #include <BRep_Builder.hxx>
26 #include <BRep_CurveRepresentation.hxx>
27 #include <BRep_GCurve.hxx>
28 #include <BRep_ListIteratorOfListOfCurveRepresentation.hxx>
29 #include <BRep_TEdge.hxx>
30 #include <BRep_Tool.hxx>
31 #include <BRepAdaptor_Curve.hxx>
32 #include <BRepAdaptor_Curve2d.hxx>
33 #include <BRepAdaptor_Surface.hxx>
34 #include <BRepAlgo_AsDes.hxx>
35 #include <BRepLib.hxx>
36 #include <BRepLib_MakeVertex.hxx>
37 #include <BRepOffset_Analyse.hxx>
38 #include <BRepOffset_Inter2d.hxx>
39 #include <BRepOffset_Offset.hxx>
40 #include <BRepOffset_Tool.hxx>
41 #include <BRepTools.hxx>
42 #include <BRepTools_WireExplorer.hxx>
43 #include <Geom2d_BezierCurve.hxx>
44 #include <Geom2d_BSplineCurve.hxx>
45 #include <Geom2d_Line.hxx>
46 #include <Geom2d_TrimmedCurve.hxx>
47 #include <Geom2dAdaptor_HCurve.hxx>
48 #include <Geom2dConvert_CompCurveToBSplineCurve.hxx>
49 #include <Geom2dInt_GInter.hxx>
50 #include <Geom_BSplineCurve.hxx>
51 #include <Geom_BSplineSurface.hxx>
52 #include <Geom_ConicalSurface.hxx>
53 #include <Geom_CylindricalSurface.hxx>
54 #include <Geom_Line.hxx>
55 #include <Geom_Plane.hxx>
56 #include <Geom_TrimmedCurve.hxx>
57 #include <GeomAdaptor_HSurface.hxx>
58 #include <GeomAdaptor_Surface.hxx>
59 #include <GeomAPI_ProjectPointOnCurve.hxx>
60 #include <GeomConvert_CompCurveToBSplineCurve.hxx>
61 #include <GeomLib.hxx>
62 #include <GeomProjLib.hxx>
63 #include <gp_Pnt.hxx>
64 #include <IntRes2d_IntersectionPoint.hxx>
65 #include <IntRes2d_IntersectionSegment.hxx>
66 #include <Precision.hxx>
67 #include <TColGeom2d_SequenceOfCurve.hxx>
68 #include <TColgp_Array1OfPnt2d.hxx>
69 #include <TColgp_SequenceOfPnt.hxx>
70 #include <TopExp.hxx>
71 #include <TopExp_Explorer.hxx>
72 #include <TopoDS.hxx>
73 #include <TopoDS_Edge.hxx>
74 #include <TopoDS_Face.hxx>
75 #include <TopoDS_Iterator.hxx>
76 #include <TopoDS_Vertex.hxx>
77 #include <TopoDS_Wire.hxx>
78 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
79 #include <TopTools_ListIteratorOfListOfShape.hxx>
80 #include <TopTools_ListOfShape.hxx>
81
82 #include <stdio.h>
83 #ifdef DRAW 
84 #include <DBRep.hxx>
85 #include <Geom2d_BoundedCurve.hxx>
86 #include <Geom_BoundedSurface.hxx>
87 #include <Geom_BoundedCurve.hxx>
88 #include <BRep_CurveOnSurface.hxx>
89 #include <Geom_Surface.hxx>
90 Standard_Boolean Inter2dAffichInt2d;
91 static Standard_Integer NbF2d = 0;
92 static Standard_Integer NbE2d = 0;
93 static Standard_Integer NbNewVertices  = 0;
94 #endif
95
96 //=======================================================================
97 //function : CommonVertex
98 //purpose  : 
99 //=======================================================================
100
101 static TopoDS_Vertex CommonVertex(TopoDS_Edge& E1,
102                                   TopoDS_Edge& E2)
103 {
104   TopoDS_Vertex V1[2],V2[2],V;
105   //
106   TopExp::Vertices(E1,V1[0],V1[1], Standard_True);
107   TopExp::Vertices(E2,V2[0],V2[1], Standard_True);
108   // The first edge is the current one, the second edge is the next one.
109   // We check last vertex of the first edge first.
110   if (V1[1].IsSame(V2[0]) || V1[1].IsSame(V2[1])) return V1[1];
111   if (V1[0].IsSame(V2[0]) || V1[0].IsSame(V2[1])) return V1[0];
112   //
113   return V;
114 }
115
116 static Standard_Boolean IsOrientationChanged(TopTools_IndexedMapOfShape& theMap,
117                                              const TopoDS_Edge& theEdge)
118 {
119   Standard_Boolean IsOrChanged = Standard_False;
120   
121   if (!theMap.Contains(theEdge))
122     theMap.Add(theEdge);
123   else
124   {
125     Standard_Integer anInd = theMap.FindIndex(theEdge);
126     const TopoDS_Shape& anEdge = theMap(anInd);
127     if (theEdge.Orientation() != anEdge.Orientation())
128     {
129       theMap.Substitute( anInd, theEdge );
130       IsOrChanged = Standard_True;
131     }
132   }
133
134   return IsOrChanged;
135 }
136
137
138 //=======================================================================
139 //function : Store
140 //purpose  : Store the vertices <theLV> into AsDes for the edge <theEdge>.
141 //           The vertices are added despite of the coincidence with
142 //           already added vertices. When all vertices for all edges
143 //           are added the coinciding chains of vertices should be fused
144 //           using FuseVertices() method.
145 //=======================================================================
146 static void Store(const TopoDS_Edge& theEdge,
147                   const TopTools_ListOfShape& theLV,
148                   const Standard_Real theTol,
149                   const Standard_Boolean IsToUpdate,
150                   Handle(BRepAlgo_AsDes) theAsDes2d,
151                   TopTools_IndexedDataMapOfShapeListOfShape& theDMVV)
152 {
153   const TopTools_ListOfShape& aLVEx = theAsDes2d->Descendant(theEdge);
154   if (!IsToUpdate && aLVEx.IsEmpty()) {
155     if (theLV.Extent()) theAsDes2d->Add(theEdge, theLV);
156     return;
157   }
158   //
159   GeomAPI_ProjectPointOnCurve aProjPC;
160   if (IsToUpdate) {
161     Standard_Real aT1, aT2;
162     const Handle(Geom_Curve)& aC = BRep_Tool::Curve(theEdge, aT1, aT2);
163     aProjPC.Init(aC, aT1, aT2);
164   }
165   //
166   TopTools_MapOfShape aMV;
167   TopTools_ListIteratorOfListOfShape aIt(theLV);
168   for (; aIt.More(); aIt.Next()) {
169     const TopoDS_Vertex& aV = TopoDS::Vertex(aIt.Value());
170     if (!aMV.Add(aV)) {
171       continue;
172     }
173     //
174     const gp_Pnt& aP = BRep_Tool::Pnt(aV);
175     //
176     TopTools_ListOfShape aLVC;
177     TopTools_ListIteratorOfListOfShape aItEx(aLVEx);
178     for (; aItEx.More(); aItEx.Next()) {
179       const TopoDS_Vertex& aVEx = TopoDS::Vertex(aItEx.Value());
180       if (aV.IsSame(aVEx)) {
181         break;
182       }
183       const gp_Pnt& aPEx = BRep_Tool::Pnt(aVEx);
184       if (aP.IsEqual(aPEx, theTol)) {
185         aLVC.Append(aVEx);
186       }
187     }
188     //
189     if (aItEx.More()) {
190       continue;
191     }
192     //
193     if (IsToUpdate) {
194       // get parameter of the vertex on the edge
195       aProjPC.Perform(aP);
196       if (!aProjPC.NbPoints()) {
197         continue;
198       }
199       //
200       if (aProjPC.LowerDistance() > theTol) {
201         continue;
202       }
203       //
204       Standard_Real aT = aProjPC.LowerDistanceParameter();
205       TopoDS_Shape aLocalShape = aV.Oriented(TopAbs_INTERNAL);
206       BRep_Builder().UpdateVertex(TopoDS::Vertex(aLocalShape), aT, theEdge, theTol);
207     }
208     else {
209       BRep_Builder().UpdateVertex(aV, theTol);
210     }
211     //
212     if (aLVC.Extent()) {
213       TopTools_ListIteratorOfListOfShape aItLV(aLVC);
214       for (; aItLV.More(); aItLV.Next()) {
215         const TopoDS_Shape& aVC = aItLV.Value();
216         TopTools_ListOfShape* pLV = theDMVV.ChangeSeek(aVC);
217         if (!pLV) {
218           pLV = &theDMVV(theDMVV.Add(aVC, TopTools_ListOfShape()));
219         }
220         pLV->Append(aV);
221       }
222       //
223       TopTools_ListOfShape* pLV = theDMVV.ChangeSeek(aV);
224       if (!pLV) {
225         pLV = &theDMVV(theDMVV.Add(aV, TopTools_ListOfShape()));
226       }
227       pLV->Append(aLVC);
228     }
229     theAsDes2d->Add(theEdge, aV);
230   }
231 }
232
233 //=======================================================================
234 //function : Store
235 //purpose  : Store the intersection vertices between two edges into AsDes
236 //=======================================================================
237 static void  Store (const TopoDS_Edge& theE1,
238                     const TopoDS_Edge& theE2,
239                     const TopTools_ListOfShape& theLV1,
240                     const TopTools_ListOfShape& theLV2,
241                     const Standard_Real theTol,
242                     Handle(BRepAlgo_AsDes) theAsDes2d,
243                     TopTools_IndexedDataMapOfShapeListOfShape& theDMVV)
244 {
245   for (Standard_Integer i = 0; i < 2; ++i) {
246     const TopoDS_Edge& aE = !i ? theE1 : theE2;
247     const TopTools_ListOfShape& aLV = !i ? theLV1 : theLV2;
248     Store(aE, aLV, theTol, Standard_False, theAsDes2d, theDMVV);
249   }
250 }
251
252 //=======================================================================
253 //function : EdgeInter
254 //purpose  : 
255 //=======================================================================
256
257 static void EdgeInter(const TopoDS_Face&              F,
258                       const BRepAdaptor_Surface&      BAsurf,
259                       const TopoDS_Edge&              E1,
260                       const TopoDS_Edge&              E2,
261                       const Handle(BRepAlgo_AsDes)&   AsDes,
262                       Standard_Real                   Tol,
263                       Standard_Boolean                WithOri,
264                       TopTools_IndexedDataMapOfShapeListOfShape& aDMVV)
265 {
266 #ifdef DRAW
267   if (Inter2dAffichInt2d) {
268     char name[256];
269     sprintf(name,"E2d_%d_%d",NbF2d,NbE2d++);
270     DBRep::Set(name,E1);
271     sprintf(name,"E2d_%d_%d",NbF2d,NbE2d++);
272     DBRep::Set(name,E2);
273   }
274 #endif
275
276   if (E1.IsSame(E2))
277     return;
278
279   Standard_Real f[3],l[3];
280   Standard_Real TolDub = 1.e-7;
281   Standard_Integer i;
282
283   BRep_Tool::Range(E1, f[1], l[1]);
284   BRep_Tool::Range(E2, f[2], l[2]);
285
286   BRepAdaptor_Curve CE1(E1,F);
287   BRepAdaptor_Curve CE2(E2,F);
288
289   TopoDS_Edge                 EI[3]; EI[1] = E1; EI[2] = E2;
290   TopTools_ListOfShape        LV1;   
291   TopTools_ListOfShape        LV2; 
292   BRep_Builder                B;
293
294   TopoDS_Vertex CV;
295   if (!TopExp::CommonVertex( E1, E2, CV ))
296     {
297       BRepLib::BuildCurve3d(E1);
298       BRepLib::BuildCurve3d(E2);
299       
300       Standard_Real TolSum = BRep_Tool::Tolerance(E1) + BRep_Tool::Tolerance(E2);
301       TolSum = Max( TolSum, 1.e-5 );
302
303       TColgp_SequenceOfPnt   ResPoints;
304       TColStd_SequenceOfReal ResParamsOnE1, ResParamsOnE2;
305       gp_Pnt DegPoint;
306       Standard_Boolean WithDegen = BRep_Tool::Degenerated(E1) || BRep_Tool::Degenerated(E2);
307       
308       if (WithDegen)
309         {
310           Standard_Integer ideg = (BRep_Tool::Degenerated(E1))? 1 : 2;
311           TopoDS_Iterator iter( EI[ideg] );
312           if (iter.More())
313             {
314               const TopoDS_Vertex& vdeg = TopoDS::Vertex(iter.Value());
315               DegPoint = BRep_Tool::Pnt(vdeg);
316             }
317           else
318             {
319               BRepAdaptor_Curve CEdeg( EI[ideg], F );
320               DegPoint = CEdeg.Value( CEdeg.FirstParameter() );
321             }
322         }
323         //
324       Handle(Geom2d_Curve) pcurve1 = BRep_Tool::CurveOnSurface(E1, F, f[1], l[1]);
325       Handle(Geom2d_Curve) pcurve2 = BRep_Tool::CurveOnSurface(E2, F, f[2], l[2]);
326       Geom2dAdaptor_Curve GAC1(pcurve1, f[1], l[1]);
327       Geom2dAdaptor_Curve GAC2(pcurve2, f[2], l[2]);
328       Geom2dInt_GInter Inter2d( GAC1, GAC2, TolDub, TolDub );
329       for (i = 1; i <= Inter2d.NbPoints(); i++)
330         {
331           gp_Pnt P3d;
332           if (WithDegen)
333             P3d = DegPoint;
334           else
335             {
336               gp_Pnt2d P2d = Inter2d.Point(i).Value();
337               P3d = BAsurf.Value( P2d.X(), P2d.Y() );
338             }
339           ResPoints.Append( P3d );
340           ResParamsOnE1.Append( Inter2d.Point(i).ParamOnFirst() );
341           ResParamsOnE2.Append( Inter2d.Point(i).ParamOnSecond() );
342         }
343
344       for (i = 1; i <= ResPoints.Length(); i++)
345         {
346           Standard_Real aT1 = ResParamsOnE1(i); //ponc1.Parameter();
347           Standard_Real aT2 = ResParamsOnE2(i); //ponc2.Parameter();
348           if (Precision::IsInfinite(aT1) || Precision::IsInfinite(aT2))
349             {
350 #ifdef OCCT_DEBUG
351               std::cout << "Inter2d : Solution rejected due to infinite parameter"<<std::endl;
352 #endif
353               continue;
354             }
355           
356           gp_Pnt P = ResPoints(i); //ponc1.Value();
357           TopoDS_Vertex aNewVertex = BRepLib_MakeVertex(P);
358           aNewVertex.Orientation(TopAbs_INTERNAL);
359           B.UpdateVertex( aNewVertex, aT1, E1, Tol );
360           B.UpdateVertex( aNewVertex, aT2, E2, Tol );
361           gp_Pnt P1 = CE1.Value(aT1);
362           gp_Pnt P2 = CE2.Value(aT2);
363           Standard_Real dist1, dist2, dist3;
364           dist1 = P1.Distance(P);
365           dist2 = P2.Distance(P);
366           dist3 = P1.Distance(P2);
367           dist1 = Max( dist1, dist2 );
368           dist1 = Max( dist1, dist3 );
369           B.UpdateVertex( aNewVertex, dist1 );
370           
371 #ifdef OCCT_DEBUG
372           if (aT1 < f[1]-Tol  || aT1 > l[1]+Tol)
373             {
374               std::cout << "out of limit"<<std::endl;
375               std::cout<<"aT1 = "<<aT1<<", f[1] = "<<f[1]<<", l[1] = "<<l[1]<<std::endl;
376             }
377           if (aT2 < f[2]-Tol  || aT2 > l[2]+Tol)
378             {
379               std::cout << "out of limit"<<std::endl;
380               std::cout<<"aT2 = "<<aT2<<", f[2] = "<<f[2]<<", l[2] = "<<l[2]<<std::endl;
381             }
382           Standard_Real MilTol2 = 1000*Tol*Tol;
383           if (P1.SquareDistance(P) >  MilTol2 || P2.SquareDistance(P) > MilTol2 || P1.Distance(P2) > 2.*Tol)
384             {
385               std::cout << "Inter2d : Solution rejected "<<std::endl;
386               std::cout<<"P  = "<<P.X()<<" "<<P.Y()<<" "<<P.Z()<<std::endl;
387               std::cout<<"P1 = "<<P1.X()<<" "<<P1.Y()<<" "<<P1.Z()<<std::endl;
388               std::cout<<"P2 = "<<P2.X()<<" "<<P2.Y()<<" "<<P2.Z()<<std::endl;
389               std::cout<<"MaxDist = "<<dist1<<std::endl;
390             }
391 #endif
392           //define the orientation of a new vertex
393           TopAbs_Orientation OO1 = TopAbs_REVERSED;
394           TopAbs_Orientation OO2 = TopAbs_REVERSED;
395           if (WithOri)
396             {
397               BRepAdaptor_Curve2d PCE1( E1, F );
398               BRepAdaptor_Curve2d PCE2( E2, F );
399               gp_Pnt2d P2d1, P2d2;
400               gp_Vec2d V1, V2, V1or, V2or;
401               PCE1.D1( aT1, P2d1, V1 );
402               PCE2.D1( aT2, P2d2, V2 );
403               V1or = V1; V2or = V2;
404               if (E1.Orientation() == TopAbs_REVERSED) V1or.Reverse();
405               if (E2.Orientation() == TopAbs_REVERSED) V2or.Reverse();
406               Standard_Real CrossProd = V2or ^ V1;
407 #ifdef OCCT_DEBUG
408               if (Abs(CrossProd) <= gp::Resolution())
409                 std::cout<<std::endl<<"CrossProd = "<<CrossProd<<std::endl;
410 #endif
411               if (CrossProd > 0.)
412                 OO1 = TopAbs_FORWARD;
413               CrossProd = V1or ^ V2;
414               if (CrossProd > 0.)
415                 OO2 = TopAbs_FORWARD;
416             }
417           LV1.Append( aNewVertex.Oriented(OO1) );
418           LV2.Append( aNewVertex.Oriented(OO2) );
419         }
420     }
421   
422   //----------------------------------
423   // Test at end.
424   //---------------------------------
425   Standard_Real U1,U2;
426   Standard_Real TolConf = Tol;
427   TopoDS_Vertex V1[2],V2[2];
428   TopExp::Vertices(E1,V1[0],V1[1]);
429   TopExp::Vertices(E2,V2[0],V2[1]);
430
431   Standard_Integer j;
432   for (j = 0; j < 2; j++) {
433     if (V1[j].IsNull()) continue;
434     for (Standard_Integer k = 0; k < 2; k++) {
435       if (V2[k].IsNull()) continue;
436       if (V1[j].IsSame(V2[k])) {
437         if (AsDes->HasAscendant(V1[j])) {
438           continue;
439         }
440       }
441       //
442       gp_Pnt P1 = BRep_Tool::Pnt(V1[j]);
443       gp_Pnt P2 = BRep_Tool::Pnt(V2[k]);
444       Standard_Real Dist = P1.Distance(P2); 
445       if (Dist < TolConf) {
446         Standard_Real aTol = 
447           Max(BRep_Tool::Tolerance(V1[j]), BRep_Tool::Tolerance(V2[k]));
448         TopoDS_Vertex V = BRepLib_MakeVertex(P1);
449         U1 = (j == 0) ? f[1] : l[1];
450         U2 = (k == 0) ? f[2] : l[2];
451         //
452         TopoDS_Shape aLocalShape = V.Oriented(TopAbs_INTERNAL);
453         B.UpdateVertex(TopoDS::Vertex(aLocalShape),U1,E1,aTol);
454         B.UpdateVertex(TopoDS::Vertex(aLocalShape),U2,E2,aTol);
455         //
456         LV1.Prepend(V.Oriented(V1[j].Orientation()));
457         LV2.Prepend(V.Oriented(V2[k].Orientation()));
458       }
459     }
460   }
461
462   Standard_Boolean AffichPurge = Standard_False;
463
464   if ( !LV1.IsEmpty()) {
465     //----------------------------------
466     // Remove all vertices.
467     // There can be doubles
468     //----------------------------------
469     TopTools_ListIteratorOfListOfShape it1LV1,it1LV2,it2LV1;
470     gp_Pnt P1,P2;
471     Standard_Boolean Purge = Standard_True;
472
473     while (Purge) {
474       i = 1;
475       Purge = Standard_False;
476       for (it1LV1.Initialize(LV1),it1LV2.Initialize(LV2); 
477            it1LV1.More(); it1LV1.Next(),it1LV2.Next()) {
478         j = 1;
479         it2LV1.Initialize(LV1);
480         while (j < i) {      
481           P1 = BRep_Tool::Pnt(TopoDS::Vertex(it1LV1.Value()));
482           P2 = BRep_Tool::Pnt(TopoDS::Vertex(it2LV1.Value()));
483 //  Modified by skv - Thu Jan 22 18:19:04 2004 OCC4455 Begin
484 //           if (P1.IsEqual(P2,10*Tol)) {
485           Standard_Real aTol;
486
487           aTol = Max(BRep_Tool::Tolerance(TopoDS::Vertex(it1LV1.Value())),
488                      BRep_Tool::Tolerance(TopoDS::Vertex(it2LV1.Value())));
489           if (P1.IsEqual(P2,aTol)) {
490 //  Modified by skv - Thu Jan 22 18:19:05 2004 OCC4455 End
491             LV1.Remove(it1LV1);
492             LV2.Remove(it1LV2);
493             if (AffichPurge) std::cout <<"Doubles removed in EdgeInter."<<std::endl;
494             Purge = Standard_True;
495             break;
496           }
497           j++;
498           it2LV1.Next();
499         }
500         if (Purge) break;
501         i++;
502       }
503     }
504     //---------------------------------
505     // Vertex storage in DS.
506     //---------------------------------
507     Standard_Real TolStore = BRep_Tool::Tolerance(E1) + BRep_Tool::Tolerance(E2);
508     TolStore = Max(TolStore, 10.*Tol);
509     Store (E1,E2,LV1,LV2,TolStore,AsDes, aDMVV);
510   }
511 }
512 //=======================================================================
513 //function : EdgeInter
514 //purpose  : 
515 //=======================================================================
516
517 static void RefEdgeInter(const TopoDS_Face&              F,
518                          const BRepAdaptor_Surface&      BAsurf,
519                          const TopoDS_Edge&              E1,
520                          const TopoDS_Edge&              E2,
521                          const Handle(BRepAlgo_AsDes)&   AsDes,
522                          Standard_Real                   Tol,
523                          Standard_Boolean                WithOri,
524                          gp_Pnt&                         Pref,
525                          TopTools_IndexedDataMapOfShapeListOfShape& aDMVV,
526                          Standard_Boolean&               theCoincide)
527 {
528 #ifdef DRAW
529   if (Inter2dAffichInt2d) {
530     char name[256];
531     sprintf(name,"E2d_%d_%d",NbF2d,NbE2d++);
532     DBRep::Set(name,E1);
533     sprintf(name,"E2d_%d_%d",NbF2d,NbE2d++);
534     DBRep::Set(name,E2);
535   }
536 #endif
537   //
538   theCoincide = Standard_False;
539   //
540   if (E1.IsSame(E2))
541     return;
542
543   Standard_Real f[3],l[3];
544   Standard_Real TolDub = 1.e-7;
545   Standard_Integer i;
546
547   //BRep_Tool::Range(E1, f[1], l[1]);
548   //BRep_Tool::Range(E2, f[2], l[2]);
549
550   BRepAdaptor_Curve CE1(E1,F);
551   BRepAdaptor_Curve CE2(E2,F);
552
553   TopoDS_Edge                 EI[3]; EI[1] = E1; EI[2] = E2;
554   TopTools_ListOfShape        LV1;   
555   TopTools_ListOfShape        LV2; 
556   BRep_Builder                B;
557
558   BRepLib::BuildCurve3d(E1);
559   BRepLib::BuildCurve3d(E2);
560
561   Standard_Real TolSum = BRep_Tool::Tolerance(E1) + BRep_Tool::Tolerance(E2);
562   TolSum = Max( TolSum, 1.e-5 );
563
564   TColgp_SequenceOfPnt   ResPoints;
565   TColStd_SequenceOfReal ResParamsOnE1, ResParamsOnE2;
566   gp_Pnt DegPoint;
567   Standard_Boolean WithDegen = BRep_Tool::Degenerated(E1) || BRep_Tool::Degenerated(E2);
568   
569   if (WithDegen)
570     {
571       Standard_Integer ideg = (BRep_Tool::Degenerated(E1))? 1 : 2;
572       TopoDS_Iterator iter( EI[ideg] );
573       if (iter.More())
574         {
575           const TopoDS_Vertex& vdeg = TopoDS::Vertex(iter.Value());
576           DegPoint = BRep_Tool::Pnt(vdeg);
577         }
578       else
579         {
580           BRepAdaptor_Curve CEdeg( EI[ideg], F );
581           DegPoint = CEdeg.Value( CEdeg.FirstParameter() );
582         }
583     }
584   //
585   Handle(Geom2d_Curve) pcurve1 = BRep_Tool::CurveOnSurface(E1, F, f[1], l[1]);
586   Handle(Geom2d_Curve) pcurve2 = BRep_Tool::CurveOnSurface(E2, F, f[2], l[2]);
587   Geom2dAdaptor_Curve GAC1(pcurve1, f[1], l[1]);
588   Geom2dAdaptor_Curve GAC2(pcurve2, f[2], l[2]);
589   if ((GAC1.GetType() == GeomAbs_Line) &&
590       (GAC2.GetType() == GeomAbs_Line))
591   {
592     // Just quickly check if lines coincide
593     if (GAC1.Line().Direction().IsParallel (GAC2.Line().Direction(), 1.e-8))
594     {
595       theCoincide = Standard_True;
596       return;
597     }
598   }
599
600   Geom2dInt_GInter Inter2d( GAC1, GAC2, TolDub, TolDub );
601   //
602   if (!Inter2d.IsDone() || !Inter2d.NbPoints()) {
603     theCoincide = (Inter2d.NbSegments() &&
604                   (GAC1.GetType() == GeomAbs_Line) &&
605                   (GAC2.GetType() == GeomAbs_Line));
606     return;
607   }
608   //
609   for (i = 1; i <= Inter2d.NbPoints(); i++)
610     {
611       gp_Pnt P3d;
612       if (WithDegen)
613         P3d = DegPoint;
614       else
615         {
616           gp_Pnt2d P2d = Inter2d.Point(i).Value();
617           P3d = BAsurf.Value( P2d.X(), P2d.Y() );
618         }
619       ResPoints.Append( P3d );
620       ResParamsOnE1.Append( Inter2d.Point(i).ParamOnFirst() );
621       ResParamsOnE2.Append( Inter2d.Point(i).ParamOnSecond() );
622     }
623   
624   for (i = 1; i <= ResPoints.Length(); i++)
625     {
626       Standard_Real aT1 = ResParamsOnE1(i); //ponc1.Parameter();
627       Standard_Real aT2 = ResParamsOnE2(i); //ponc2.Parameter();
628       if (Precision::IsInfinite(aT1) || Precision::IsInfinite(aT2))
629         {
630 #ifdef OCCT_DEBUG
631           std::cout << "Inter2d : Solution rejected due to infinite parameter"<<std::endl;
632 #endif
633           continue;
634         }
635       
636       gp_Pnt P = ResPoints(i); //ponc1.Value();
637       TopoDS_Vertex aNewVertex = BRepLib_MakeVertex(P);
638       aNewVertex.Orientation(TopAbs_INTERNAL);
639       B.UpdateVertex( aNewVertex, aT1, E1, Tol );
640       B.UpdateVertex( aNewVertex, aT2, E2, Tol );
641       gp_Pnt P1 = CE1.Value(aT1);
642       gp_Pnt P2 = CE2.Value(aT2);
643       Standard_Real dist1, dist2, dist3;
644       dist1 = P1.Distance(P);
645       dist2 = P2.Distance(P);
646       dist3 = P1.Distance(P2);
647       dist1 = Max( dist1, dist2 );
648       dist1 = Max( dist1, dist3 );
649       B.UpdateVertex( aNewVertex, dist1 );
650       
651 #ifdef OCCT_DEBUG
652       if (aT1 < f[1]-Tol  || aT1 > l[1]+Tol)
653         {
654           std::cout << "out of limit"<<std::endl;
655           std::cout<<"aT1 = "<<aT1<<", f[1] = "<<f[1]<<", l[1] = "<<l[1]<<std::endl;
656         }
657       if (aT2 < f[2]-Tol  || aT2 > l[2]+Tol)
658         {
659           std::cout << "out of limit"<<std::endl;
660           std::cout<<"aT2 = "<<aT2<<", f[2] = "<<f[2]<<", l[2] = "<<l[2]<<std::endl;
661         }
662       Standard_Real MilTol2 = 1000*Tol*Tol;
663       if (P1.SquareDistance(P) >  MilTol2 || P2.SquareDistance(P) > MilTol2 || P1.Distance(P2) > 2.*Tol)
664         {
665           std::cout << "Inter2d : Solution rejected"<<std::endl;
666           std::cout<<"P  = "<<P.X()<<" "<<P.Y()<<" "<<P.Z()<<std::endl;
667           std::cout<<"P1 = "<<P1.X()<<" "<<P1.Y()<<" "<<P1.Z()<<std::endl;
668           std::cout<<"P2 = "<<P2.X()<<" "<<P2.Y()<<" "<<P2.Z()<<std::endl;
669           std::cout<<"MaxDist = "<<dist1<<std::endl;
670         }
671 #endif
672       //define the orientation of a new vertex
673       TopAbs_Orientation OO1 = TopAbs_REVERSED;
674       TopAbs_Orientation OO2 = TopAbs_REVERSED;
675       if (WithOri)
676         {
677           BRepAdaptor_Curve2d PCE1( E1, F );
678           BRepAdaptor_Curve2d PCE2( E2, F );
679           gp_Pnt2d P2d1, P2d2;
680           gp_Vec2d V1, V2, V1or, V2or;
681           PCE1.D1( aT1, P2d1, V1 );
682           PCE2.D1( aT2, P2d2, V2 );
683           V1or = V1; V2or = V2;
684           if (E1.Orientation() == TopAbs_REVERSED) V1or.Reverse();
685           if (E2.Orientation() == TopAbs_REVERSED) V2or.Reverse();
686           Standard_Real CrossProd = V2or ^ V1;
687 #ifdef OCCT_DEBUG
688           if (Abs(CrossProd) <= gp::Resolution())
689             std::cout<<std::endl<<"CrossProd = "<<CrossProd<<std::endl;
690 #endif
691           if (CrossProd > 0.)
692             OO1 = TopAbs_FORWARD;
693           CrossProd = V1or ^ V2;
694           if (CrossProd > 0.)
695             OO2 = TopAbs_FORWARD;
696         }
697       LV1.Append( aNewVertex.Oriented(OO1) );
698       LV2.Append( aNewVertex.Oriented(OO2) );
699     }
700   
701   //----------------------------------
702   // Test at end.
703   //---------------------------------
704   Standard_Real U1,U2;
705   Standard_Real TolConf = Tol;
706   TopoDS_Vertex V1[2],V2[2];
707   TopExp::Vertices(E1,V1[0],V1[1]);
708   TopExp::Vertices(E2,V2[0],V2[1]);
709
710   Standard_Integer j;
711   for (j = 0; j < 2; j++) {
712     if (V1[j].IsNull()) continue;
713     for (Standard_Integer k = 0; k < 2; k++) {
714       if (V2[k].IsNull()) continue;
715       if (V1[j].IsSame(V2[k])) {
716         if (AsDes->HasAscendant(V1[j])) {
717           continue;
718         }
719       }
720       //
721       gp_Pnt P1 = BRep_Tool::Pnt(V1[j]);
722       gp_Pnt P2 = BRep_Tool::Pnt(V2[k]);
723       Standard_Real Dist = P1.Distance(P2); 
724       if (Dist < TolConf) {
725         TopoDS_Vertex V = BRepLib_MakeVertex(P1);
726         U1 = (j == 0) ? f[1] : l[1];
727         U2 = (k == 0) ? f[2] : l[2];
728         TopoDS_Shape aLocalShape = V.Oriented(TopAbs_INTERNAL);
729         B.UpdateVertex(TopoDS::Vertex(aLocalShape),U1,E1,Tol);
730         B.UpdateVertex(TopoDS::Vertex(aLocalShape),U2,E2,Tol);
731         LV1.Prepend(V.Oriented(V1[j].Orientation()));
732         LV2.Prepend(V.Oriented(V2[k].Orientation()));
733       }
734     }
735   }
736
737   Standard_Boolean AffichPurge = Standard_False;
738
739   if ( !LV1.IsEmpty()) {
740     //----------------------------------
741     // Remove all vertices.
742     // there can be doubles
743     //----------------------------------
744     TopTools_ListIteratorOfListOfShape it1LV1,it1LV2,it2LV1;
745     gp_Pnt P1,P2;
746     Standard_Boolean Purge = Standard_True;
747
748     while (Purge) {
749       i = 1;
750       Purge = Standard_False;
751       for (it1LV1.Initialize(LV1),it1LV2.Initialize(LV2); 
752            it1LV1.More(); it1LV1.Next(),it1LV2.Next()) {
753         j = 1;
754         it2LV1.Initialize(LV1);
755         while (j < i) {      
756           P1 = BRep_Tool::Pnt(TopoDS::Vertex(it1LV1.Value()));
757           P2 = BRep_Tool::Pnt(TopoDS::Vertex(it2LV1.Value()));
758           if (P1.IsEqual(P2,10*Tol)) {
759             LV1.Remove(it1LV1);
760             LV2.Remove(it1LV2);
761             if (AffichPurge) std::cout <<"Doubles removed in EdgeInter."<<std::endl;
762             Purge = Standard_True;
763             break;
764           }
765           j++;
766           it2LV1.Next();
767         }
768         if (Purge) break;
769         i++;
770       }
771     }
772     //---------------------------------
773     // Vertex storage in SD.
774     //---------------------------------
775 ////-----------------------------------------------------
776     if(LV1.Extent() > 1) {
777       //std::cout << "IFV - RefEdgeInter: remove vertex" << std::endl;
778       Standard_Real dmin = RealLast();
779       TopoDS_Vertex Vmin;
780       for (it1LV1.Initialize(LV1); it1LV1.More(); it1LV1.Next()) {
781         gp_Pnt P = BRep_Tool::Pnt(TopoDS::Vertex(it1LV1.Value()));
782         Standard_Real d = P.SquareDistance(Pref);
783         if(d < dmin) {
784           dmin = d;
785           Vmin = TopoDS::Vertex(it1LV1.Value());
786         }
787       }
788       for (it1LV1.Initialize(LV1),it1LV2.Initialize(LV2); 
789            it1LV1.More(); it1LV1.Next(),it1LV2.Next()) {
790         if(!Vmin.IsSame(it1LV1.Value())) {
791           LV1.Remove(it1LV1);
792           LV2.Remove(it1LV2);
793           if(!it1LV1.More()) break;
794         }
795       }
796     }
797       
798 ////-----------------------------------------------------
799     Standard_Real TolStore = BRep_Tool::Tolerance(E1) + BRep_Tool::Tolerance(E2);
800     TolStore = Max(TolStore, 10.*Tol);
801     Store (E1,E2,LV1,LV2,TolStore,AsDes, aDMVV);
802   }
803 }
804
805
806 //======================================================================
807 //function : EvaluateMaxSegment
808 //purpose  : return MaxSegment to pass in approximation
809 //======================================================================
810
811 static Standard_Integer evaluateMaxSegment(const Adaptor3d_CurveOnSurface& aCurveOnSurface)
812 {
813   Handle(Adaptor3d_HSurface) aSurf   = aCurveOnSurface.GetSurface();
814   Handle(Adaptor2d_HCurve2d) aCurv2d = aCurveOnSurface.GetCurve();
815
816   Standard_Real aNbSKnots = 0, aNbC2dKnots = 0;
817   
818   if (aSurf->GetType() == GeomAbs_BSplineSurface) {
819     Handle(Geom_BSplineSurface) aBSpline = aSurf->BSpline();
820     aNbSKnots = Max(aBSpline->NbUKnots(), aBSpline->NbVKnots());
821   }
822   if (aCurv2d->GetType() == GeomAbs_BSplineCurve) {
823     aNbC2dKnots = aCurv2d->NbKnots();
824   }
825   Standard_Integer aReturn = (Standard_Integer) (  30 + Max(aNbSKnots, aNbC2dKnots) ) ;
826   return aReturn;
827 }
828
829
830 //=======================================================================
831 //function : ExtendPCurve
832 //purpose  : 
833 //=======================================================================
834
835 static Standard_Boolean ExtendPCurve(const Handle(Geom2d_Curve)& aPCurve,
836                                      const Standard_Real anEf,
837                                      const Standard_Real anEl,
838                                      const Standard_Real a2Offset,
839                                      Handle(Geom2d_Curve)& NewPCurve)
840 {
841   NewPCurve = aPCurve;
842   if (NewPCurve->IsInstance(STANDARD_TYPE(Geom2d_TrimmedCurve)))
843     NewPCurve = Handle(Geom2d_TrimmedCurve)::DownCast (NewPCurve)->BasisCurve();
844   
845   Standard_Real FirstPar = NewPCurve->FirstParameter();
846   Standard_Real LastPar  = NewPCurve->LastParameter();
847
848   if (NewPCurve->IsKind(STANDARD_TYPE(Geom2d_BoundedCurve)) &&
849       (FirstPar > anEf - a2Offset || LastPar < anEl + a2Offset))
850     {
851       if (NewPCurve->IsInstance(STANDARD_TYPE(Geom2d_BezierCurve)))
852         {
853           Handle(Geom2d_BezierCurve) aBezier = Handle(Geom2d_BezierCurve)::DownCast (NewPCurve);
854           if (aBezier->NbPoles() == 2)
855             {
856               TColgp_Array1OfPnt2d thePoles(1,2);
857               aBezier->Poles(thePoles);
858               gp_Vec2d aVec(thePoles(1), thePoles(2));
859               NewPCurve = new Geom2d_Line(thePoles(1), aVec);
860               return Standard_True;
861             }
862         }
863       else if (NewPCurve->IsInstance(STANDARD_TYPE(Geom2d_BSplineCurve)))
864         {
865           Handle(Geom2d_BSplineCurve) aBSpline = Handle(Geom2d_BSplineCurve)::DownCast (NewPCurve);
866           if (aBSpline->NbKnots() == 2 && aBSpline->NbPoles() == 2)
867             {
868               TColgp_Array1OfPnt2d thePoles(1,2);
869               aBSpline->Poles(thePoles);
870               gp_Vec2d aVec(thePoles(1), thePoles(2));
871               NewPCurve = new Geom2d_Line(thePoles(1), aVec);
872               return Standard_True;
873             }
874         }
875     }
876
877   FirstPar = aPCurve->FirstParameter();
878   LastPar  = aPCurve->LastParameter();
879   Handle(Geom2d_TrimmedCurve) aTrCurve = 
880     new Geom2d_TrimmedCurve(aPCurve, FirstPar, LastPar);
881   
882   // The curve is not prolonged on begin or end.
883   // Trying to prolong it adding a segment to its bound.
884   gp_Pnt2d                              aPBnd;
885   gp_Vec2d                              aVBnd;
886   gp_Pnt2d                              aPBeg;
887   gp_Dir2d                              aDBnd;
888   Handle(Geom2d_Line)                   aLin;
889   Handle(Geom2d_TrimmedCurve)           aSegment;
890   Geom2dConvert_CompCurveToBSplineCurve aCompCurve(aTrCurve, Convert_RationalC1);
891   Standard_Real                         aTol = Precision::Confusion();
892   Standard_Real                         aDelta = Max(a2Offset, 1.);
893   
894   if (FirstPar > anEf - a2Offset) {
895     aPCurve->D1(FirstPar, aPBnd, aVBnd);
896     aDBnd.SetXY(aVBnd.XY());
897     aPBeg    = aPBnd.Translated(gp_Vec2d(-aDelta*aDBnd.XY()));
898     aLin     = new Geom2d_Line(aPBeg, aDBnd);
899     aSegment = new Geom2d_TrimmedCurve(aLin, 0, aDelta);
900     
901     if (!aCompCurve.Add(aSegment, aTol))
902       return Standard_False;
903   }
904   
905   if (LastPar < anEl + a2Offset) {
906     aPCurve->D1(LastPar, aPBeg, aVBnd);
907     aDBnd.SetXY(aVBnd.XY());
908     aLin     = new Geom2d_Line(aPBeg, aDBnd);
909     aSegment = new Geom2d_TrimmedCurve(aLin, 0, aDelta);
910     
911     if (!aCompCurve.Add(aSegment, aTol))
912       return Standard_False;
913   }
914   
915   NewPCurve  = aCompCurve.BSplineCurve();
916   return Standard_True;
917 }
918
919 //=======================================================================
920 //function : ExtentEdge
921 //purpose  : 
922 //=======================================================================
923
924 //  Modified by skv - Fri Dec 26 17:00:55 2003 OCC4455 Begin
925 //static void ExtentEdge(const TopoDS_Edge& E,TopoDS_Edge& NE) 
926 void BRepOffset_Inter2d::ExtentEdge(const TopoDS_Edge& E,TopoDS_Edge& NE, const Standard_Real theOffset)
927 {
928   //BRepLib::BuildCurve3d(E);
929
930   TopoDS_Shape  aLocalShape = E.EmptyCopied();
931   Standard_Real anEf;
932   Standard_Real anEl;
933   Standard_Real a2Offset = 2.*Abs(theOffset);
934   BRep_Builder BB;
935   Standard_Integer i, j;
936
937   BRep_Tool::Range(E, anEf, anEl);
938   NE = TopoDS::Edge(aLocalShape); 
939 //  NE = TopoDS::Edge(E.EmptyCopied()); 
940   // Enough for analytic edges, for general case reconstruct the
941   // geometry of the edge recalculating the intersection of surfaces.
942
943   //BRepLib::BuildCurve3d(E);
944
945   Standard_Integer NbPCurves = 0;
946   Standard_Real FirstParOnPC = RealFirst(), LastParOnPC = RealLast();
947   Handle(Geom2d_Curve) MinPC;
948   Handle(Geom_Surface) MinSurf;
949   TopLoc_Location      MinLoc;
950
951   BRep_ListIteratorOfListOfCurveRepresentation itr( (Handle(BRep_TEdge)::DownCast(NE.TShape()))->ChangeCurves() );
952   for (; itr.More(); itr.Next())
953     {
954       Handle( BRep_CurveRepresentation ) CurveRep = itr.Value();
955       Standard_Real FirstPar, LastPar;
956       if (CurveRep->IsCurveOnSurface())
957         {
958           NbPCurves++;
959           Handle(Geom2d_Curve) theCurve = CurveRep->PCurve();
960           FirstPar = theCurve->FirstParameter();
961           LastPar  = theCurve->LastParameter();
962
963           if (theCurve->IsKind(STANDARD_TYPE(Geom2d_BoundedCurve)) &&
964               (FirstPar > anEf - a2Offset || LastPar < anEl + a2Offset))
965             {
966               Handle(Geom2d_Curve) NewPCurve;
967               if (ExtendPCurve(theCurve, anEf, anEl, a2Offset, NewPCurve))
968                 {
969                   CurveRep->PCurve(NewPCurve);
970                   FirstPar = NewPCurve->FirstParameter();
971                   LastPar  = NewPCurve->LastParameter();
972                   if (CurveRep->IsCurveOnClosedSurface())
973                     {
974                       Handle(Geom2d_Curve) PCurve2 = CurveRep->PCurve2();
975                       if (ExtendPCurve(PCurve2, anEf, anEl, a2Offset, NewPCurve))
976                         CurveRep->PCurve2(NewPCurve);
977                     }
978                 }
979             }
980           else if (theCurve->IsPeriodic())
981             {
982               Standard_Real delta = (theCurve->Period() - (anEl - anEf))*0.5;
983               delta *= 0.95;
984               FirstPar = anEf - delta;
985               LastPar  = anEl + delta;
986             }
987           else if (theCurve->IsClosed())
988             LastPar -= 0.05*(LastPar - FirstPar);
989
990           //check FirstPar and LastPar: the pcurve should be in its surface
991           theCurve = CurveRep->PCurve();
992           Handle(Geom_Surface) theSurf = CurveRep->Surface();
993           Standard_Real Umin, Umax, Vmin, Vmax;
994           theSurf->Bounds(Umin, Umax, Vmin, Vmax);
995           TColGeom2d_SequenceOfCurve BoundLines;
996           if (!Precision::IsInfinite(Vmin))
997             {
998               Handle(Geom2d_Line) aLine = new Geom2d_Line(gp_Pnt2d( 0., Vmin ),
999                                                           gp_Dir2d( 1., 0. ));
1000               BoundLines.Append(aLine);
1001             }
1002           if (!Precision::IsInfinite(Umin))
1003             {
1004               Handle(Geom2d_Line) aLine = new Geom2d_Line(gp_Pnt2d( Umin, 0. ),
1005                                                           gp_Dir2d( 0., 1. ));
1006               BoundLines.Append(aLine);
1007             }
1008           if (!Precision::IsInfinite(Vmax))
1009             {
1010               Handle(Geom2d_Line) aLine = new Geom2d_Line(gp_Pnt2d( 0., Vmax ),
1011                                                           gp_Dir2d( 1., 0. ));
1012               BoundLines.Append(aLine);
1013             }
1014           if (!Precision::IsInfinite(Umax))
1015             {
1016               Handle(Geom2d_Line) aLine = new Geom2d_Line(gp_Pnt2d( Umax, 0. ),
1017                                                           gp_Dir2d( 0., 1. ));
1018               BoundLines.Append(aLine);
1019             }
1020
1021           TColStd_SequenceOfReal params;
1022           Geom2dInt_GInter IntCC;
1023           Geom2dAdaptor_Curve GAcurve(theCurve);
1024           for (i = 1; i <= BoundLines.Length(); i++)
1025             {
1026               Geom2dAdaptor_Curve GAline( BoundLines(i) );
1027               IntCC.Perform( GAcurve, GAline, Precision::PConfusion(), Precision::PConfusion());
1028               if (IntCC.IsDone())
1029                 {
1030                   for (j = 1; j <= IntCC.NbPoints(); j++)
1031                     {
1032                       const IntRes2d_IntersectionPoint& ip = IntCC.Point(j);
1033                       gp_Pnt2d aPoint = ip.Value();
1034                       if (aPoint.X() >= Umin && aPoint.X() <= Umax &&
1035                           aPoint.Y() >= Vmin && aPoint.Y() <= Vmax)
1036                         params.Append( ip.ParamOnFirst() );
1037                     }
1038                   for (j = 1; j <= IntCC.NbSegments(); j++)
1039                     {
1040                       const IntRes2d_IntersectionSegment& is = IntCC.Segment(j);
1041                       if (is.HasFirstPoint())
1042                         {
1043                           const IntRes2d_IntersectionPoint& ip = is.FirstPoint();
1044                           gp_Pnt2d aPoint = ip.Value();
1045                           if (aPoint.X() >= Umin && aPoint.X() <= Umax &&
1046                               aPoint.Y() >= Vmin && aPoint.Y() <= Vmax)
1047                             params.Append( ip.ParamOnFirst() );
1048                         }
1049                       if (is.HasLastPoint())
1050                         {
1051                           const IntRes2d_IntersectionPoint& ip = is.LastPoint();
1052                           gp_Pnt2d aPoint = ip.Value();
1053                           if (aPoint.X() >= Umin && aPoint.X() <= Umax &&
1054                               aPoint.Y() >= Vmin && aPoint.Y() <= Vmax)
1055                             params.Append( ip.ParamOnFirst() );
1056                         }
1057                     }
1058                 }
1059             }
1060           if (!params.IsEmpty())
1061             {
1062               if (params.Length() == 1)
1063                 {
1064                   gp_Pnt2d PntFirst = theCurve->Value(FirstPar);
1065                   if (PntFirst.X() >= Umin && PntFirst.X() <= Umax &&
1066                       PntFirst.Y() >= Vmin && PntFirst.Y() <= Vmax)
1067                     {
1068                       if (LastPar > params(1))
1069                         LastPar = params(1);
1070                     }
1071                   else if (FirstPar < params(1))
1072                     FirstPar = params(1);
1073                 }
1074               else
1075                 {
1076                   Standard_Real fpar = RealLast(), lpar = RealFirst();
1077                   for (i = 1; i <= params.Length(); i++)
1078                     {
1079                       if (params(i) < fpar)
1080                         fpar = params(i);
1081                       if (params(i) > lpar)
1082                         lpar = params(i);
1083                     }
1084                   if (FirstPar < fpar)
1085                     FirstPar = fpar;
1086                   if (LastPar > lpar)
1087                     LastPar = lpar;
1088                 }
1089             }
1090           //// end of check ////
1091           (Handle(BRep_GCurve)::DownCast(CurveRep))->SetRange( FirstPar, LastPar );
1092           //gp_Pnt2d Pfirst = theCurve->Value(FirstPar);
1093           //gp_Pnt2d Plast  = theCurve->Value(LastPar);
1094           //(Handle(BRep_CurveOnSurface)::DownCast(CurveRep))->SetUVPoints( Pfirst, Plast );
1095
1096           //update FirstParOnPC and LastParOnPC
1097           if (FirstPar > FirstParOnPC)
1098             {
1099               FirstParOnPC = FirstPar;
1100               MinPC   = theCurve;
1101               MinSurf = theSurf;
1102               MinLoc  = CurveRep->Location();
1103             }
1104           if (LastPar  < LastParOnPC)
1105             {
1106               LastParOnPC  = LastPar;
1107               MinPC   = theCurve;
1108               MinSurf = theSurf;
1109               MinLoc  = CurveRep->Location();
1110             }
1111         }
1112     }
1113
1114   Standard_Real f, l;
1115   Handle(Geom_Curve) C3d = BRep_Tool::Curve( NE, f, l );
1116   if (NbPCurves)
1117     {
1118       MinLoc = E.Location() * MinLoc;
1119       if (!C3d.IsNull())
1120         {
1121           if (MinPC->IsClosed())
1122             {
1123               f = FirstParOnPC;
1124               l = LastParOnPC;
1125             }
1126           else if (C3d->IsPeriodic())
1127             {
1128               Standard_Real delta = (C3d->Period() - (l - f))*0.5;
1129               delta *= 0.95;
1130               f -= delta;
1131               l += delta;
1132             }
1133           else if (C3d->IsClosed())
1134             l -= 0.05*(l - f);
1135           else
1136             {
1137               f = FirstParOnPC;
1138               l = LastParOnPC;
1139               GeomAPI_ProjectPointOnCurve Projector;
1140               if (!Precision::IsInfinite(FirstParOnPC))
1141                 {
1142                   gp_Pnt2d P2d1 = MinPC->Value(FirstParOnPC);
1143                   gp_Pnt P1 = MinSurf->Value( P2d1.X(), P2d1.Y() );
1144                   P1.Transform(MinLoc.Transformation());
1145                   Projector.Init( P1, C3d );
1146                   if (Projector.NbPoints() > 0)
1147                     f = Projector.LowerDistanceParameter();
1148 #ifdef OCCT_DEBUG
1149                   else
1150                     std::cout<<"ProjectPointOnCurve not done"<<std::endl;
1151 #endif
1152                 }
1153               if (!Precision::IsInfinite(LastParOnPC))
1154                 {
1155                   gp_Pnt2d P2d2 = MinPC->Value(LastParOnPC);
1156                   gp_Pnt P2 = MinSurf->Value( P2d2.X(), P2d2.Y() );
1157                   P2.Transform(MinLoc.Transformation());
1158                   Projector.Init( P2, C3d );
1159                   if (Projector.NbPoints() > 0)
1160                     l = Projector.LowerDistanceParameter();
1161 #ifdef OCCT_DEBUG
1162                   else
1163                     std::cout<<"ProjectPointOnCurve not done"<<std::endl;
1164 #endif
1165                 }
1166             }
1167           BB.Range( NE, f, l );
1168           if (!Precision::IsInfinite(f) && !Precision::IsInfinite(l))
1169             BRepLib::SameParameter( NE, Precision::Confusion(), Standard_True );
1170         }
1171       else if (!BRep_Tool::Degenerated(E)) //no 3d curve
1172         {
1173           MinSurf = Handle(Geom_Surface)::DownCast
1174             (MinSurf->Transformed(MinLoc.Transformation()));
1175           Standard_Real max_deviation = 0.;
1176           if (Precision::IsInfinite(FirstParOnPC) || Precision::IsInfinite(LastParOnPC))
1177             {
1178               if (MinPC->IsInstance(STANDARD_TYPE(Geom2d_Line)))
1179                 {
1180                   Standard_Boolean IsLine = Standard_False;
1181                   if (MinSurf->IsInstance(STANDARD_TYPE(Geom_Plane)))
1182                     IsLine = Standard_True;
1183                   else if (MinSurf->IsInstance(STANDARD_TYPE(Geom_CylindricalSurface)) ||
1184                            MinSurf->IsInstance(STANDARD_TYPE(Geom_ConicalSurface)))
1185                     {
1186                       Handle(Geom2d_Line) theLine = Handle(Geom2d_Line)::DownCast (MinPC);
1187                       gp_Dir2d LineDir = theLine->Direction();
1188                       if (LineDir.IsParallel( gp::DY2d(), Precision::Angular() ))
1189                         IsLine = Standard_True;
1190                     }
1191                   if (IsLine)
1192                     {
1193                       gp_Pnt2d P2d1 = MinPC->Value(0.), P2d2 = MinPC->Value(1.);
1194                       gp_Pnt P1 = MinSurf->Value(P2d1.X(), P2d1.Y());
1195                       gp_Pnt P2 = MinSurf->Value(P2d2.X(), P2d2.Y());
1196                       gp_Vec aVec(P1, P2);
1197                       C3d = new Geom_Line( P1, aVec );
1198                     }
1199                 }
1200             }
1201           else
1202             {
1203               Geom2dAdaptor_Curve AC2d( MinPC, FirstParOnPC, LastParOnPC );
1204               GeomAdaptor_Surface GAsurf( MinSurf );
1205               Handle(Geom2dAdaptor_HCurve) HC2d  = new Geom2dAdaptor_HCurve( AC2d );
1206               Handle(GeomAdaptor_HSurface) HSurf = new GeomAdaptor_HSurface( GAsurf );
1207               Adaptor3d_CurveOnSurface ConS( HC2d, HSurf );
1208               Standard_Real /*max_deviation,*/ average_deviation;
1209               GeomAbs_Shape Continuity = GeomAbs_C1;
1210               Standard_Integer MaxDegree = 14;
1211               Standard_Integer MaxSegment = evaluateMaxSegment(ConS);
1212               GeomLib::BuildCurve3d(Precision::Confusion(),
1213                                     ConS, FirstParOnPC, LastParOnPC,
1214                                     C3d, max_deviation, average_deviation,
1215                                     Continuity, MaxDegree, MaxSegment);
1216             }
1217           BB.UpdateEdge( NE, C3d, max_deviation );
1218           //BB.Range( NE, FirstParOnPC, LastParOnPC );
1219           Standard_Boolean ProjectionSuccess = Standard_True;
1220           if (NbPCurves > 1)
1221             //BRepLib::SameParameter( NE, Precision::Confusion(), Standard_True );
1222             for (itr.Initialize((Handle(BRep_TEdge)::DownCast(NE.TShape()))->ChangeCurves());
1223                  itr.More();
1224                  itr.Next())
1225               {
1226                 Handle( BRep_CurveRepresentation ) CurveRep = itr.Value();
1227                 Standard_Real FirstPar, LastPar;
1228                 if (CurveRep->IsCurveOnSurface())
1229                   {
1230                     Handle(Geom2d_Curve) theCurve = CurveRep->PCurve();
1231                     Handle(Geom_Surface) theSurf  = CurveRep->Surface();
1232                     TopLoc_Location      theLoc   = CurveRep->Location();
1233                     if (theCurve == MinPC && theSurf == MinSurf && theLoc == MinLoc)
1234                       continue;
1235                     FirstPar = (Handle(BRep_GCurve)::DownCast(CurveRep))->First();
1236                     LastPar  = (Handle(BRep_GCurve)::DownCast(CurveRep))->Last();
1237                     if (Abs(FirstPar - FirstParOnPC) > Precision::PConfusion() ||
1238                         Abs(LastPar  - LastParOnPC)  > Precision::PConfusion())
1239                       {
1240                         theLoc = E.Location() * theLoc;
1241                         theSurf = Handle(Geom_Surface)::DownCast
1242                           (theSurf->Transformed(theLoc.Transformation()));
1243
1244                         if (theCurve->IsInstance(STANDARD_TYPE(Geom2d_Line)) &&
1245                             theSurf->IsKind(STANDARD_TYPE(Geom_BoundedSurface)))
1246                           {
1247                             gp_Dir2d theDir = Handle(Geom2d_Line)::DownCast (theCurve)->Direction();
1248                             if (theDir.IsParallel(gp::DX2d(), Precision::Angular()) ||
1249                                 theDir.IsParallel(gp::DY2d(), Precision::Angular()))
1250                               {
1251                                 Standard_Real U1, U2, V1, V2;
1252                                 theSurf->Bounds(U1, U2, V1, V2);
1253                                 gp_Pnt2d Origin = Handle(Geom2d_Line)::DownCast (theCurve)->Location();
1254                                 if (Abs(Origin.X()-U1) <= Precision::Confusion() ||
1255                                     Abs(Origin.X()-U2) <= Precision::Confusion() ||
1256                                     Abs(Origin.Y()-V1) <= Precision::Confusion() ||
1257                                     Abs(Origin.Y()-V2) <= Precision::Confusion())
1258                                   {
1259                                     BRepLib::SameParameter( NE, Precision::Confusion(), Standard_True );
1260                                     break;
1261                                   }
1262                               }
1263                           }
1264
1265                         Handle(Geom2d_Curve) ProjPCurve =
1266                           GeomProjLib::Curve2d( C3d, FirstParOnPC, LastParOnPC, theSurf );
1267                         if (ProjPCurve.IsNull())
1268                           ProjectionSuccess = Standard_False;
1269                         else
1270                           CurveRep->PCurve( ProjPCurve );
1271                       }
1272                   }
1273               }
1274           if (ProjectionSuccess)
1275             BB.Range( NE, FirstParOnPC, LastParOnPC );
1276           else
1277             {
1278               BB.Range( NE, FirstParOnPC, LastParOnPC, Standard_True );
1279               BRepLib::SameParameter( NE, Precision::Confusion(), Standard_True );
1280             }
1281         }
1282     }
1283   else //no pcurves
1284     {
1285       Standard_Real FirstPar = C3d->FirstParameter();
1286       Standard_Real LastPar  = C3d->LastParameter();
1287       
1288       if (C3d->IsKind(STANDARD_TYPE(Geom_BoundedCurve)) &&
1289           (FirstPar > anEf - a2Offset || LastPar < anEl + a2Offset))
1290         {
1291           Handle(Geom_TrimmedCurve) aTrCurve = 
1292             new Geom_TrimmedCurve(C3d, FirstPar, LastPar);
1293           
1294           // The curve is not prolonged on begin or end.
1295           // Trying to prolong it adding a segment to its bound.
1296           gp_Pnt                              aPBnd;
1297           gp_Vec                              aVBnd;
1298           gp_Pnt                              aPBeg;
1299           gp_Dir                              aDBnd;
1300           Handle(Geom_Line)                   aLin;
1301           Handle(Geom_TrimmedCurve)           aSegment;
1302           GeomConvert_CompCurveToBSplineCurve aCompCurve(aTrCurve, Convert_RationalC1);
1303           Standard_Real                       aTol = Precision::Confusion();
1304           Standard_Real                       aDelta = Max(a2Offset, 1.);
1305           
1306           if (FirstPar > anEf - a2Offset) {
1307             C3d->D1(FirstPar, aPBnd, aVBnd);
1308             aDBnd.SetXYZ(aVBnd.XYZ());
1309             aPBeg    = aPBnd.Translated(gp_Vec(-aDelta*aDBnd.XYZ()));
1310             aLin     = new Geom_Line(aPBeg, aDBnd);
1311             aSegment = new Geom_TrimmedCurve(aLin, 0, aDelta);
1312             
1313             if (!aCompCurve.Add(aSegment, aTol))
1314               return;
1315           }
1316           
1317           if (LastPar < anEl + a2Offset) {
1318             C3d->D1(LastPar, aPBeg, aVBnd);
1319             aDBnd.SetXYZ(aVBnd.XYZ());
1320             aLin     = new Geom_Line(aPBeg, aDBnd);
1321             aSegment = new Geom_TrimmedCurve(aLin, 0, aDelta);
1322             
1323             if (!aCompCurve.Add(aSegment, aTol))
1324               return;
1325           }
1326           
1327           C3d = aCompCurve.BSplineCurve();
1328           FirstPar = C3d->FirstParameter();
1329           LastPar  = C3d->LastParameter();
1330           BB.UpdateEdge(NE, C3d, Precision::Confusion());
1331         }
1332       else if (C3d->IsPeriodic())
1333         {
1334           Standard_Real delta = (C3d->Period() - (anEl - anEf))*0.5;
1335           delta *= 0.95;
1336           FirstPar = anEf - delta;
1337           LastPar  = anEl + delta;
1338         }
1339       else if (C3d->IsClosed())
1340         LastPar -= 0.05*(LastPar - FirstPar);
1341       
1342       BB.Range( NE, FirstPar, LastPar );
1343     }
1344 }
1345 //  Modified by skv - Fri Dec 26 17:00:57 2003 OCC4455 End
1346
1347
1348 //=======================================================================
1349 //function : UpdateVertex
1350 //purpose  : 
1351 //=======================================================================
1352
1353 static Standard_Boolean  UpdateVertex(TopoDS_Vertex V,
1354                                       TopoDS_Edge&  OE,
1355                                       TopoDS_Edge&  NE,
1356                                       Standard_Real TolConf)
1357 {
1358   BRepAdaptor_Curve OC(OE);
1359   BRepAdaptor_Curve NC(NE);
1360   Standard_Real Of = OC.FirstParameter(); Standard_Real Ol = OC.LastParameter();
1361   Standard_Real Nf = NC.FirstParameter(); Standard_Real Nl = NC.LastParameter();
1362   Standard_Real U = 0.;
1363   Standard_Real ParTol = Precision::PConfusion();
1364   gp_Pnt           P  = BRep_Tool::Pnt(V);
1365   Standard_Boolean OK = Standard_False;
1366
1367   if (P.Distance(OC.Value(Of)) < TolConf) {
1368     if (Of >= Nf + ParTol && Of <= Nl + ParTol  && P.Distance(NC.Value(Of)) < TolConf) {
1369       OK = Standard_True;
1370       U    = Of;
1371     }
1372   }
1373   if (P.Distance(OC.Value(Ol)) < TolConf) {
1374     if (Ol >= Nf + ParTol && Ol <= Nl + ParTol  && P.Distance(NC.Value(Ol)) < TolConf) {
1375       OK = Standard_True;
1376       U    = Ol;
1377     }
1378   }
1379   if (OK) {
1380     BRep_Builder B;
1381     TopoDS_Shape aLocalShape = NE.Oriented(TopAbs_FORWARD);
1382     TopoDS_Edge EE = TopoDS::Edge(aLocalShape);
1383 //    TopoDS_Edge EE = TopoDS::Edge(NE.Oriented(TopAbs_FORWARD));
1384     aLocalShape = V.Oriented(TopAbs_INTERNAL);
1385     B.UpdateVertex(TopoDS::Vertex(aLocalShape),
1386                    U,NE,BRep_Tool::Tolerance(NE));
1387 //    B.UpdateVertex(TopoDS::Vertex(V.Oriented(TopAbs_INTERNAL)),
1388 //                   U,NE,BRep_Tool::Tolerance(NE));
1389   }
1390   return OK;  
1391 }
1392
1393 //=======================================================================
1394 //function : Compute
1395 //purpose  : 
1396 //=======================================================================
1397
1398 void BRepOffset_Inter2d::Compute (const Handle(BRepAlgo_AsDes)&     AsDes,
1399                                   const TopoDS_Face&                F,
1400                                   const TopTools_IndexedMapOfShape& NewEdges,
1401                                   const Standard_Real               Tol,
1402                                   TopTools_IndexedDataMapOfShapeListOfShape& theDMVV)
1403 {
1404 #ifdef DRAW
1405   NbF2d++;
1406   NbE2d = 0;
1407 #endif 
1408
1409   //Do not intersect the edges of face
1410   TopTools_MapOfShape EdgesOfFace;
1411   TopExp_Explorer Explo( F, TopAbs_EDGE );
1412   for (; Explo.More(); Explo.Next())
1413     EdgesOfFace.Add( Explo.Current() );
1414
1415   //-----------------------------------------------------------
1416   // calculate intersections2d on faces touched by  
1417   // intersection3d
1418   //---------------------------------------------------------
1419   TopTools_ListIteratorOfListOfShape it1LE ;    
1420   TopTools_ListIteratorOfListOfShape it2LE ;  
1421
1422   //-----------------------------------------------
1423   // Intersection of edges 2*2.
1424   //-----------------------------------------------
1425   const TopTools_ListOfShape&        LE = AsDes->Descendant(F);
1426   TopoDS_Vertex                      V1,V2;
1427   Standard_Integer                   j, i = 1;
1428   BRepAdaptor_Surface BAsurf(F);
1429   //
1430   for ( it1LE.Initialize(LE) ; it1LE.More(); it1LE.Next()) {
1431     const TopoDS_Edge& E1 = TopoDS::Edge(it1LE.Value());        
1432     j = 1;
1433     it2LE.Initialize(LE);
1434     
1435     while (j < i && it2LE.More()) {
1436       const TopoDS_Edge& E2 = TopoDS::Edge(it2LE.Value());
1437       //--------------------------------------------------------------
1438       // Intersections of New edges obtained by intersection
1439       // between them and with edges of restrictions
1440       //------------------------------------------------------
1441       if ( (!EdgesOfFace.Contains(E1) || !EdgesOfFace.Contains(E2)) &&
1442            (NewEdges.Contains(E1) || NewEdges.Contains(E2)) ) {
1443         TopoDS_Shape aLocalShape = F.Oriented(TopAbs_FORWARD);
1444         EdgeInter(TopoDS::Face(aLocalShape),BAsurf,E1,E2,AsDes,Tol,Standard_True, theDMVV);
1445 //          EdgeInter(TopoDS::Face(F.Oriented(TopAbs_FORWARD)),E1,E2,AsDes,Tol,Standard_True);
1446       }
1447       it2LE.Next();
1448       j++;
1449     }
1450     i++;
1451   }
1452 }
1453
1454 //=======================================================================
1455 //function : ConnexIntByInt
1456 //purpose  : 
1457 //=======================================================================
1458 void BRepOffset_Inter2d::ConnexIntByInt
1459  (const TopoDS_Face&            FI,
1460   BRepOffset_Offset&            OFI,
1461   TopTools_DataMapOfShapeShape& MES,
1462   const TopTools_DataMapOfShapeShape& Build,
1463   const Handle(BRepAlgo_AsDes)& AsDes2d,
1464   const Standard_Real           Offset,
1465   const Standard_Real           Tol,
1466   const BRepOffset_Analyse&     Analyse,
1467   TopTools_IndexedMapOfShape&   FacesWithVerts,
1468   TopTools_IndexedDataMapOfShapeListOfShape& theDMVV)
1469 {  
1470
1471   TopTools_DataMapOfShapeListOfShape MVE;
1472   BRepOffset_Tool::MapVertexEdges(FI,MVE);
1473
1474   //---------------------
1475   // Extension of edges.
1476   //---------------------
1477   TopoDS_Edge  NE;
1478   TopTools_DataMapIteratorOfDataMapOfShapeListOfShape it(MVE);
1479   for  ( ; it.More(); it.Next()) {
1480     const TopTools_ListOfShape&  L = it.Value();
1481     Standard_Boolean   YaBuild = 0;
1482     TopTools_ListIteratorOfListOfShape itL(L);
1483     for (; itL.More(); itL.Next()) {
1484       YaBuild = Build.IsBound(itL.Value());
1485       if (YaBuild) break;
1486     }
1487     if (YaBuild) {
1488       for (itL.Initialize(L); itL.More(); itL.Next()) {
1489         const TopoDS_Edge& EI = TopoDS::Edge(itL.Value());
1490         if (EI.Orientation() != TopAbs_FORWARD &&
1491             EI.Orientation() != TopAbs_REVERSED)
1492           continue;
1493         TopoDS_Shape aLocalShape = OFI.Generated(EI);
1494         const TopoDS_Edge& OE = TopoDS::Edge(aLocalShape);
1495         if (!MES.IsBound(OE) && !Build.IsBound(EI)) {
1496           ExtentEdge(OE,NE, Offset);
1497           MES.Bind  (OE,NE);
1498         }
1499       }
1500     } 
1501   }
1502   
1503   TopoDS_Face           FIO = TopoDS::Face(OFI.Face());
1504   if (MES.IsBound(FIO)) FIO = TopoDS::Face(MES(FIO));
1505   //
1506   BRepAdaptor_Surface BAsurf(FIO);
1507   
1508   TopExp_Explorer exp(FI.Oriented(TopAbs_FORWARD),TopAbs_WIRE);
1509   for (; exp.More(); exp.Next()) {
1510     const TopoDS_Wire&     W = TopoDS::Wire(exp.Current());
1511     BRepTools_WireExplorer wexp;
1512     Standard_Boolean       end = Standard_False ;
1513     TopoDS_Edge            FirstE,CurE,NextE;
1514
1515     TopoDS_Shape aLocalWire = W .Oriented(TopAbs_FORWARD);
1516     TopoDS_Shape aLocalFace = FI.Oriented(TopAbs_FORWARD);
1517     wexp.Init(TopoDS::Wire(aLocalWire),TopoDS::Face(aLocalFace));
1518     if (!wexp.More())
1519       continue; // Protection from case when explorer does not contain edges.
1520     CurE = FirstE  = wexp.Current();
1521     TopTools_IndexedMapOfShape Edges;
1522     Standard_Boolean ToReverse1, ToReverse2;
1523     ToReverse1 = IsOrientationChanged(Edges, CurE);
1524     while (!end) {
1525       wexp.Next();
1526       if (wexp.More()) {
1527         NextE = wexp.Current();
1528       } 
1529       else {
1530         NextE = FirstE; end = Standard_True;
1531       }
1532       if (CurE.IsSame(NextE)) continue;
1533
1534       ToReverse2 = IsOrientationChanged(Edges, NextE);
1535
1536       TopoDS_Vertex Vref = CommonVertex(CurE, NextE); 
1537       gp_Pnt Pref = BRep_Tool::Pnt(Vref);
1538
1539       CurE = Analyse.EdgeReplacement (FI, CurE);
1540       NextE = Analyse.EdgeReplacement (FI, NextE);
1541
1542       TopoDS_Shape aLocalShape = OFI.Generated(CurE);
1543       TopoDS_Edge CEO = TopoDS::Edge(aLocalShape);
1544       aLocalShape = OFI.Generated(NextE);
1545       TopoDS_Edge NEO = TopoDS::Edge(aLocalShape);
1546       //------------------------------------------
1547       // Inter processing of images of CurE NextE.
1548       //------------------------------------------
1549       TopTools_ListOfShape LV1,LV2;
1550       Standard_Boolean     DoInter = 1;
1551       TopoDS_Shape         NE1,NE2;
1552       
1553       if (Build.IsBound(CurE) && Build.IsBound(NextE)) {
1554         NE1 = Build(CurE );
1555         NE2 = Build(NextE);
1556       }
1557       else if (Build.IsBound(CurE) && MES.IsBound(NEO)) {
1558         NE1 = Build(CurE);
1559         NE2 = MES  (NEO);
1560       }
1561       else if (Build.IsBound(NextE) && MES.IsBound(CEO)) {
1562         NE1 = Build(NextE);
1563         NE2 = MES(CEO);
1564         Standard_Boolean Tmp = ToReverse1;
1565         ToReverse1 = ToReverse2;
1566         ToReverse2 = Tmp;
1567       }
1568       else {
1569         DoInter = 0;
1570       }
1571       if (DoInter) {
1572         //------------------------------------
1573         // NE1,NE2 can be a compound of Edges.
1574         //------------------------------------
1575         Standard_Boolean bCoincide;
1576         TopExp_Explorer Exp1, Exp2;
1577         for (Exp1.Init(NE1, TopAbs_EDGE); Exp1.More(); Exp1.Next()) {
1578           TopoDS_Edge aE1 = TopoDS::Edge(Exp1.Current());
1579           for (Exp2.Init(NE2, TopAbs_EDGE); Exp2.More(); Exp2.Next()) {
1580             TopoDS_Edge aE2 = TopoDS::Edge(Exp2.Current());
1581
1582             //Correct orientation of edges
1583             if (ToReverse1)
1584               aE1.Reverse();
1585             if (ToReverse2)
1586               aE2.Reverse();
1587             //////////////////////////////
1588             
1589             RefEdgeInter(FIO, BAsurf, aE1, aE2, AsDes2d,
1590                          Tol, Standard_True, Pref, theDMVV, bCoincide);
1591           }
1592         }
1593         //
1594         // check if some of the offset edges have been
1595         // generated out of the common vertex
1596         if (Build.IsBound(Vref)) {
1597           FacesWithVerts.Add(FI);
1598         }
1599       }
1600       else {
1601         TopoDS_Vertex  V = CommonVertex(CEO,NEO);
1602         if (!V.IsNull())
1603         {
1604           if (MES.IsBound(CEO)) {
1605             UpdateVertex  (V,CEO,TopoDS::Edge(MES(CEO)),Tol);
1606             AsDes2d->Add     (MES(CEO),V);
1607           }
1608           if (MES.IsBound(NEO)) {
1609             UpdateVertex (V,NEO,TopoDS::Edge(MES(NEO)),Tol);
1610             AsDes2d->Add    (MES(NEO),V);
1611           }
1612         }
1613       }
1614       CurE = wexp.Current();
1615       ToReverse1 = ToReverse2;
1616     }
1617   }
1618 }
1619
1620 //=======================================================================
1621 //function : ConnexIntByIntInVert
1622 //purpose  : Intersection of the edges generated out of vertices
1623 //=======================================================================
1624 void BRepOffset_Inter2d::ConnexIntByIntInVert
1625  (const TopoDS_Face&            FI,
1626   BRepOffset_Offset&            OFI,
1627   TopTools_DataMapOfShapeShape& MES,
1628   const TopTools_DataMapOfShapeShape& Build,
1629   const Handle(BRepAlgo_AsDes)& AsDes,
1630   const Handle(BRepAlgo_AsDes)& AsDes2d,
1631   const Standard_Real           Tol,
1632   const BRepOffset_Analyse&     Analyse,
1633   TopTools_IndexedDataMapOfShapeListOfShape& theDMVV)
1634 {
1635   TopoDS_Face           FIO = TopoDS::Face(OFI.Face());
1636   if (MES.IsBound(FIO)) FIO = TopoDS::Face(MES(FIO));
1637   //
1638   TopTools_MapOfShape aME;
1639   const TopTools_ListOfShape& aLE = AsDes->Descendant(FIO);
1640   TopTools_ListIteratorOfListOfShape aItLE(aLE);
1641   for (; aItLE.More(); aItLE.Next()) {
1642     const TopoDS_Shape& aE = aItLE.Value();
1643     aME.Add(aE);
1644   }
1645   //
1646   BRepAdaptor_Surface BAsurf(FIO);
1647   //
1648   TopExp_Explorer exp(FI.Oriented(TopAbs_FORWARD),TopAbs_WIRE);
1649   for (; exp.More(); exp.Next()) {
1650     const TopoDS_Wire&     W = TopoDS::Wire(exp.Current());
1651     //
1652     BRepTools_WireExplorer wexp;
1653     Standard_Boolean       end = Standard_False ;
1654     TopoDS_Edge            FirstE,CurE,NextE;
1655     //
1656     TopoDS_Shape aLocalWire = W .Oriented(TopAbs_FORWARD);
1657     TopoDS_Shape aLocalFace = FI.Oriented(TopAbs_FORWARD);
1658     wexp.Init(TopoDS::Wire(aLocalWire),TopoDS::Face(aLocalFace));
1659     if (!wexp.More())
1660       continue; // Protection from case when explorer does not contain edges.
1661     //
1662     CurE = FirstE  = wexp.Current(); 
1663     while (!end) {
1664       wexp.Next();
1665       if (wexp.More()) {
1666         NextE = wexp.Current();
1667       } 
1668       else {
1669         NextE = FirstE; end = Standard_True;
1670       }
1671       if (CurE.IsSame(NextE)) continue;
1672       //
1673       TopoDS_Vertex Vref = CommonVertex(CurE, NextE); 
1674       gp_Pnt Pref = BRep_Tool::Pnt(Vref);
1675       if (!Build.IsBound(Vref)) {
1676         CurE = NextE;
1677         continue;
1678       }
1679
1680       CurE = Analyse.EdgeReplacement (FI, CurE);
1681       NextE = Analyse.EdgeReplacement (FI, NextE);
1682
1683       TopoDS_Shape aLocalShape = OFI.Generated(CurE);
1684       TopoDS_Edge CEO = TopoDS::Edge(aLocalShape);
1685       aLocalShape = OFI.Generated(NextE);
1686       TopoDS_Edge NEO = TopoDS::Edge(aLocalShape);
1687       //
1688       TopoDS_Shape         NE1,NE2;
1689       
1690       if (Build.IsBound(CurE) && Build.IsBound(NextE)) {
1691         NE1 = Build(CurE );
1692         NE2 = Build(NextE);
1693       }
1694       else if (Build.IsBound(CurE) && MES.IsBound(NEO)) {
1695         NE1 = Build(CurE);
1696         NE2 = MES  (NEO);
1697       }
1698       else if (Build.IsBound(NextE) && MES.IsBound(CEO)) {
1699         NE1 = Build(NextE);
1700         NE2 = MES(CEO);
1701       }
1702       else {
1703         CurE = wexp.Current();
1704         continue;
1705       }
1706       //
1707       TopExp_Explorer Exp1, Exp2;
1708       Standard_Boolean bCoincide;
1709       // intersect edges generated from vertex with the edges of the face
1710       TopoDS_Shape NE3 = Build(Vref);
1711       //
1712       for (Exp2.Init(NE3, TopAbs_EDGE); Exp2.More(); Exp2.Next()) {
1713         const TopoDS_Edge& aE3 = *(TopoDS_Edge*)&Exp2.Current();
1714         if (!aME.Contains(aE3)) {
1715           continue;
1716         }
1717         //
1718         // intersection with first edge
1719         for (Exp1.Init(NE1, TopAbs_EDGE); Exp1.More(); Exp1.Next()) {
1720           const TopoDS_Edge& aE1 = TopoDS::Edge(Exp1.Current());
1721           RefEdgeInter(FIO, BAsurf, aE1, aE3, AsDes2d,
1722             Tol, Standard_True, Pref, theDMVV, bCoincide);
1723           if (bCoincide) {
1724             // in case of coincidence trim the edge E3 the same way as E1
1725             Store(aE3, AsDes2d->Descendant(aE1), Tol, Standard_True, AsDes2d, theDMVV);
1726           }
1727         }
1728         //
1729         // intersection with second edge
1730         for (Exp1.Init(NE2, TopAbs_EDGE); Exp1.More(); Exp1.Next()) {
1731           const TopoDS_Edge& aE2 = TopoDS::Edge(Exp1.Current());
1732           RefEdgeInter(FIO, BAsurf, aE2, aE3, AsDes2d,
1733             Tol, Standard_True, Pref, theDMVV, bCoincide);
1734           if (bCoincide) {
1735             // in case of coincidence trim the edge E3 the same way as E2
1736             Store(aE3, AsDes2d->Descendant(aE2), Tol, Standard_True, AsDes2d, theDMVV);
1737           }
1738         }
1739         //
1740         // intersection of the edges generated from vertex
1741         // among themselves
1742         for (Exp1.Init(NE3, TopAbs_EDGE); Exp1.More(); Exp1.Next()) {
1743           if (aE3.IsSame(Exp1.Current())) {
1744             break;
1745           }
1746         }
1747         //
1748         for (Exp1.Next(); Exp1.More(); Exp1.Next()) {
1749           const TopoDS_Edge& aE3Next = TopoDS::Edge(Exp1.Current());
1750           if (aME.Contains(aE3Next)) {
1751             RefEdgeInter(FIO, BAsurf, aE3Next, aE3, AsDes2d,
1752               Tol, Standard_True, Pref, theDMVV, bCoincide);
1753           }
1754         }
1755       }
1756       CurE = wexp.Current();
1757     }
1758   }
1759 }
1760
1761 //=======================================================================
1762 //function : MakeChain
1763 //purpose  : 
1764 //=======================================================================
1765 static void MakeChain(const TopoDS_Shape& theV,
1766                       const TopTools_IndexedDataMapOfShapeListOfShape& theDMVV,
1767                       TopTools_MapOfShape& theMDone,
1768                       TopTools_ListOfShape& theChain)
1769 {
1770   if (theMDone.Add(theV)) {
1771     theChain.Append(theV);
1772     const TopTools_ListOfShape* pLV = theDMVV.Seek(theV);
1773     if (pLV) {
1774       TopTools_ListIteratorOfListOfShape aIt(*pLV);
1775       for (; aIt.More(); aIt.Next()) {
1776         MakeChain(aIt.Value(), theDMVV, theMDone, theChain);
1777       }
1778     }
1779   }
1780 }
1781
1782 //=======================================================================
1783 //function : FuseVertices
1784 //purpose  : 
1785 //=======================================================================
1786 void BRepOffset_Inter2d::FuseVertices(const TopTools_IndexedDataMapOfShapeListOfShape& theDMVV,
1787                                       const Handle(BRepAlgo_AsDes)& theAsDes)
1788 {
1789   BRep_Builder aBB;
1790   TopTools_MapOfShape aMVDone;
1791   Standard_Integer i, aNb = theDMVV.Extent();
1792   for (i = 1; i <= aNb; ++i) {
1793     const TopoDS_Vertex& aV = TopoDS::Vertex(theDMVV.FindKey(i));
1794     //
1795     // find chain of vertices
1796     TopTools_ListOfShape aLVChain;
1797     MakeChain(aV, theDMVV, aMVDone, aLVChain);
1798     //
1799     if (aLVChain.Extent() < 2) {
1800       continue;
1801     }
1802     //
1803     // make new vertex
1804     TopoDS_Vertex aVNew;
1805     BOPTools_AlgoTools::MakeVertex(aLVChain, aVNew);
1806     //
1807     TopoDS_Vertex aVNewInt = TopoDS::Vertex(aVNew.Oriented(TopAbs_INTERNAL));
1808     //
1809     TopTools_ListIteratorOfListOfShape aIt(aLVChain);
1810     for (; aIt.More(); aIt.Next()) {
1811       const TopoDS_Shape& aVOld = aIt.Value();
1812       // update the parameters on edges
1813       TopoDS_Vertex aVOldInt = TopoDS::Vertex(aVOld.Oriented(TopAbs_INTERNAL));
1814       const TopTools_ListOfShape& aLE = theAsDes->Ascendant(aVOld);
1815       //
1816       TopTools_ListIteratorOfListOfShape aItLE(aLE);
1817       for (; aItLE.More(); aItLE.Next()) {
1818         const TopoDS_Edge& aE = TopoDS::Edge(aItLE.Value());
1819         Standard_Real aTolE = BRep_Tool::Tolerance(aE);
1820         Standard_Real aT = BRep_Tool::Parameter(aVOldInt, aE);
1821         aBB.UpdateVertex(aVNewInt, aT, aE, aTolE);
1822       }
1823       // and replace the vertex
1824       theAsDes->Replace(aVOld, aVNew);
1825     }
1826   }
1827 }