0030286: Cover polygonal HLR algorithm by regression tests
[occt.git] / src / BRepFill / BRepFill_OffsetWire.cxx
1 // Created on: 1995-04-20
2 // Created by: Bruno DUMORTIER
3 // Copyright (c) 1995-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 - Fri Jul  8 11:21:38 2005 OCC9145
18
19 #include <Adaptor3d_Curve.hxx>
20 #include <Adaptor2d_OffsetCurve.hxx>
21 #include <Bisector_Bisec.hxx>
22 #include <BRep_Builder.hxx>
23 #include <BRep_CurveRepresentation.hxx>
24 #include <BRep_GCurve.hxx>
25 #include <BRep_TEdge.hxx>
26 #include <BRep_Tool.hxx>
27 #include <BRep_TVertex.hxx>
28 #include <BRepAdaptor_Curve.hxx>
29 #include <BRepAdaptor_Surface.hxx>
30 #include <BRepFill_DataMapOfNodeShape.hxx>
31 #include <BRepFill_DataMapOfOrientedShapeListOfShape.hxx>
32 #include <BRepFill_DataMapOfShapeSequenceOfPnt.hxx>
33 #include <BRepFill_DataMapOfShapeSequenceOfReal.hxx>
34 #include <BRepFill_OffsetWire.hxx>
35 #include <BRepFill_TrimEdgeTool.hxx>
36 #include <BRepLib.hxx>
37 #include <BRepLib_MakeEdge.hxx>
38 #include <BRepLib_MakeFace.hxx>
39 #include <BRepLib_MakeVertex.hxx>
40 #include <BRepLib_MakeWire.hxx>
41 #include <BRepMAT2d_BisectingLocus.hxx>
42 #include <BRepMAT2d_Explorer.hxx>
43 #include <BRepMAT2d_LinkTopoBilo.hxx>
44 #include <BRepTools.hxx>
45 #include <BRepTools_Substitution.hxx>
46 #include <BRepTools_WireExplorer.hxx>
47 #include <Geom2d_BSplineCurve.hxx>
48 #include <Geom2d_Circle.hxx>
49 #include <Geom2d_Curve.hxx>
50 #include <Geom2d_Line.hxx>
51 #include <Geom2d_OffsetCurve.hxx>
52 #include <Geom2d_TrimmedCurve.hxx>
53 #include <Geom2dAdaptor_Curve.hxx>
54 #include <Geom2dAdaptor_HCurve.hxx>
55 #include <Geom2dConvert_CompCurveToBSplineCurve.hxx>
56 #include <Geom2dLProp_CLProps2d.hxx>
57 #include <Geom_Circle.hxx>
58 #include <Geom_Line.hxx>
59 #include <Geom_OffsetCurve.hxx>
60 #include <Geom_Plane.hxx>
61 #include <Geom_Surface.hxx>
62 #include <Geom_TrimmedCurve.hxx>
63 #include <GeomAPI.hxx>
64 #include <gp.hxx>
65 #include <gp_Ax2.hxx>
66 #include <gp_Dir2d.hxx>
67 #include <gp_Pln.hxx>
68 #include <gp_Vec.hxx>
69 #include <MAT2d_CutCurve.hxx>
70 #include <MAT_Arc.hxx>
71 #include <MAT_Graph.hxx>
72 #include <MAT_Node.hxx>
73 #include <Precision.hxx>
74 #include <Standard_ConstructionError.hxx>
75 #include <Standard_ErrorHandler.hxx>
76 #include <Standard_NoSuchObject.hxx>
77 #include <Standard_NotImplemented.hxx>
78 #include <TColgp_Array1OfPnt2d.hxx>
79 #include <TColgp_SequenceOfPnt.hxx>
80 #include <TColStd_Array1OfInteger.hxx>
81 #include <TColStd_Array1OfReal.hxx>
82 #include <TColStd_SequenceOfReal.hxx>
83 #include <TopAbs.hxx>
84 #include <TopExp.hxx>
85 #include <TopExp_Explorer.hxx>
86 #include <TopoDS.hxx>
87 #include <TopoDS_Compound.hxx>
88 #include <TopoDS_Face.hxx>
89 #include <TopoDS_Iterator.hxx>
90 #include <TopoDS_Shape.hxx>
91 #include <TopoDS_Wire.hxx>
92 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
93 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
94 #include <TopTools_DataMapOfShapeListOfShape.hxx>
95 #include <TopTools_DataMapOfShapeSequenceOfShape.hxx>
96 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
97 #include <TopTools_IndexedMapOfShape.hxx>
98 #include <TopTools_ListIteratorOfListOfShape.hxx>
99 #include <TopTools_ListOfShape.hxx>
100 #include <TopTools_MapIteratorOfMapOfShape.hxx>
101 #include <TopTools_MapOfShape.hxx>
102 #include <TopTools_SequenceOfShape.hxx>
103
104 #include <stdio.h>
105 #ifdef OCCT_DEBUG
106 //#define DRAW
107 #ifdef DRAW
108 #include <Draw.hxx>
109 #include <DrawTrSurf.hxx>
110 #include <DrawTrSurf_Curve2d.hxx>
111 #include <DBRep.hxx>
112 #include <Geom_Curve.hxx>
113 static Standard_Boolean AffichGeom  = Standard_False;
114 static Standard_Boolean Affich2d    = Standard_False;
115 static Standard_Boolean AffichEdge  = Standard_False;
116 static Standard_Integer NbTRIMEDGES = 0;
117 static Standard_Integer NbOFFSET    = 0;
118 static Standard_Integer NbEDGES     = 0;
119 static Standard_Integer NbBISSEC    = 0;
120 #endif
121 #endif
122
123 //  Modified by Sergey KHROMOV - Thu Nov 16 17:24:39 2000 Begin
124
125 static void QuasiFleche(const Adaptor3d_Curve& C,
126   const Standard_Real Deflection2, 
127   const Standard_Real Udeb,
128   const gp_Pnt& Pdeb,
129   const gp_Vec& Vdeb,
130   const Standard_Real Ufin,
131   const gp_Pnt& Pfin,
132   const gp_Vec& Vfin,
133   const Standard_Integer Nbmin,
134   const Standard_Real Eps,
135   TColStd_SequenceOfReal& Parameters,
136   TColgp_SequenceOfPnt& Points);
137
138 static Standard_Boolean PerformCurve (TColStd_SequenceOfReal& Parameters,
139   TColgp_SequenceOfPnt&   Points,
140   const Adaptor3d_Curve& C, 
141   const Standard_Real Deflection,
142   const Standard_Real U1,
143   const Standard_Real U2,
144   const Standard_Real EPSILON,
145   const Standard_Integer Nbmin);
146
147 static void CheckBadEdges(const TopoDS_Face& Spine, const Standard_Real Offset,
148   const BRepMAT2d_BisectingLocus& Locus, 
149   const BRepMAT2d_LinkTopoBilo&   Link,
150   TopTools_ListOfShape& BadEdges);
151
152 static Standard_Integer CutEdge (const TopoDS_Edge& E, 
153   const TopoDS_Face& F,
154   Standard_Integer ForceCut,
155   TopTools_ListOfShape& Cuts);
156
157
158 static void CutCurve (const Handle(Geom2d_TrimmedCurve)& C,
159   const Standard_Integer nbParts,
160   TColGeom2d_SequenceOfCurve& theCurves);
161 //  Modified by Sergey KHROMOV - Thu Nov 16 17:24:47 2000 End
162
163
164 static void EdgeVertices (const TopoDS_Edge&   E,
165   TopoDS_Vertex& V1, 
166   TopoDS_Vertex& V2)
167 {
168   if (E.Orientation() == TopAbs_REVERSED) {
169     TopExp::Vertices(E,V2,V1);
170   }
171   else {
172     TopExp::Vertices(E,V1,V2);
173   }
174 }
175 static Standard_Boolean VertexFromNode
176   (const Handle(MAT_Node)&      aNode, 
177   const Standard_Real          Offset,
178   gp_Pnt2d&                    PN,
179   BRepFill_DataMapOfNodeShape& MapNodeVertex,
180   TopoDS_Vertex&               VN);
181
182 static void StoreInMap (const TopoDS_Shape& V1,
183   const TopoDS_Shape& V2,
184   TopTools_IndexedDataMapOfShapeShape& MapVV);
185
186 static void TrimEdge (const TopoDS_Edge&              CurrentEdge,
187                       const TopoDS_Shape&             CurrentSpine,
188                       const TopoDS_Face&              AllSpine,
189                       const TopTools_ListOfShape&     D,
190                       TopTools_SequenceOfShape& Sv,  
191                       TColStd_SequenceOfReal&   MapverPar,
192                       TopTools_SequenceOfShape& S,
193                       TopTools_IndexedDataMapOfShapeShape& MapVV,
194                       const Standard_Integer IndOfE);
195
196 static Standard_Boolean IsInnerEdge(const TopoDS_Shape& ProE,
197                                     const TopoDS_Face&  AllSpine,
198                                     Standard_Real& TrPar1,
199                                     Standard_Real& TrPar2);
200
201 static Standard_Boolean DoubleOrNotInside (const TopTools_ListOfShape& EC,
202   const TopoDS_Vertex&        V);
203
204 static Standard_Boolean IsSmallClosedEdge(const TopoDS_Edge& anEdge,
205   const TopoDS_Vertex& aVertex);
206
207 static void MakeCircle 
208   (const TopoDS_Edge&                          E, 
209   const TopoDS_Vertex&                        V, 
210   const TopoDS_Face&                          F,
211   const Standard_Real                         Offset, 
212   BRepFill_IndexedDataMapOfOrientedShapeListOfShape& Map,
213   const Handle(Geom_Plane)&                   RefPlane);
214
215 static void MakeOffset 
216   (const TopoDS_Edge&                          E,
217   const TopoDS_Face&                          F,
218   const Standard_Real                         Offset, 
219   BRepFill_IndexedDataMapOfOrientedShapeListOfShape& Map,
220   const Handle(Geom_Plane)&                   RefPlane,
221   const Standard_Boolean                      IsOpenResult,
222  const GeomAbs_JoinType                      theJoinType,
223   const TopoDS_Vertex *                       Ends);
224
225 Standard_Boolean CheckSmallParamOnEdge(const TopoDS_Edge& anEdge);
226
227 //=======================================================================
228 //function : KPartCircle
229 //purpose  : 
230 //=======================================================================
231
232 static Standard_Boolean KPartCircle
233   (const TopoDS_Face&  mySpine,
234   const Standard_Real myOffset,
235   const Standard_Boolean IsOpenResult,
236   const Standard_Real Alt,
237   TopoDS_Shape&       myShape, 
238   BRepFill_IndexedDataMapOfOrientedShapeListOfShape& myMap,
239   Standard_Boolean&    myIsDone)
240 {
241   TopoDS_Edge E;
242   for (TopExp_Explorer anEdgeIter (mySpine, TopAbs_EDGE); anEdgeIter.More(); anEdgeIter.Next())
243   {
244     if (!E.IsNull())
245     {
246       return Standard_False;
247     }
248     E = TopoDS::Edge (anEdgeIter.Current());
249   }
250   if (E.IsNull())
251   {
252     return Standard_False;
253   }
254
255   Standard_Real      f,l;
256   TopLoc_Location    L;
257   Handle(Geom_Curve) C =  BRep_Tool::Curve(E,L,f,l);
258   if (C.IsNull())
259   {
260     return Standard_False;
261   }
262
263   if (C->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
264     Handle(Geom_TrimmedCurve) Ct = Handle(Geom_TrimmedCurve)::DownCast(C);
265     C = Ct->BasisCurve();
266   }
267
268   if ((C->IsKind(STANDARD_TYPE(Geom_Circle)) && BRep_Tool::IsClosed(E)) || //closed circle
269       IsOpenResult)
270   {
271     Standard_Real anOffset = myOffset;
272     
273     Handle(Geom2d_Curve) aPCurve = BRep_Tool::CurveOnSurface(E, mySpine, f, l);
274     Handle(Geom2dAdaptor_HCurve) AHC = new Geom2dAdaptor_HCurve(aPCurve, f, l);
275     Handle(Geom2d_Curve) OC;
276     if (AHC->GetType() == GeomAbs_Line)
277     {
278       if (E.Orientation() == TopAbs_REVERSED)
279         anOffset *= -1;
280       Adaptor2d_OffsetCurve Off(AHC,anOffset);
281       OC = new Geom2d_Line(Off.Line());
282     }
283     else if (AHC->GetType() == GeomAbs_Circle)
284     {
285       if (E.Orientation() == TopAbs_FORWARD)
286         anOffset *= -1;
287       gp_Circ2d theCirc = AHC->Circle();
288       if (anOffset > 0. || Abs(anOffset) < theCirc.Radius())
289         OC = new Geom2d_Circle (theCirc.Position(), theCirc.Radius() + anOffset);
290       else
291       {
292         myIsDone = Standard_False;
293         return Standard_False;
294     }
295     }
296     else
297     {
298       if (E.Orientation() == TopAbs_FORWARD)
299         anOffset *= -1;
300       Handle(Geom2d_TrimmedCurve) G2dT = new Geom2d_TrimmedCurve(aPCurve, f, l);
301       OC = new Geom2d_OffsetCurve( G2dT, anOffset);
302     }
303     Handle(Geom_Surface) aSurf = BRep_Tool::Surface(mySpine);
304     Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(aSurf);
305     myShape = BRepLib_MakeEdge(OC, aPlane, f, l);
306     BRepLib::BuildCurve3d(TopoDS::Edge(myShape));
307     
308     myShape.Orientation(E.Orientation());
309     myShape.Location(L);
310     if (fabs(Alt) > gp::Resolution()) {
311       BRepAdaptor_Surface S(mySpine,0);
312       gp_Ax1 Nor = S.Plane().Axis();
313       gp_Trsf T;
314       gp_Vec Trans(Nor.Direction());
315       Trans = Alt*Trans;
316       T.SetTranslation(Trans);
317       myShape.Move(TopLoc_Location(T));
318     }
319       
320     TopTools_ListOfShape LL;
321     LL.Append(myShape);
322     myMap.Add(E,LL);
323     
324     TopoDS_Edge myEdge = TopoDS::Edge(myShape);
325     myShape = BRepLib_MakeWire(myEdge);
326     
327     myIsDone = Standard_True;
328     return Standard_True;
329   }
330
331   return Standard_False;
332 }
333
334 //=======================================================================
335 //function : BRepFill_OffsetWire
336 //purpose  : 
337 //=======================================================================
338
339 BRepFill_OffsetWire::BRepFill_OffsetWire() 
340   : myIsOpenResult(Standard_False),
341     myIsDone(Standard_False)
342 {
343 }
344
345
346 //=======================================================================
347 //function : BRepFill_OffsetWire
348 //purpose  : 
349 //=======================================================================
350
351 BRepFill_OffsetWire::BRepFill_OffsetWire(const TopoDS_Face&     Spine,
352   const GeomAbs_JoinType Join,
353   const Standard_Boolean IsOpenResult)
354 {
355   Init(Spine,Join,IsOpenResult);
356 }
357
358 //=======================================================================
359 //function : Init
360 //purpose  : 
361 //=======================================================================
362
363 void BRepFill_OffsetWire::Init(const TopoDS_Face&     Spine,
364   const GeomAbs_JoinType Join,
365   const Standard_Boolean IsOpenResult)
366 {
367   myIsDone   = Standard_False;
368   TopoDS_Shape aLocalShape = Spine.Oriented(TopAbs_FORWARD);
369   mySpine    = TopoDS::Face(aLocalShape);
370   //  mySpine    = TopoDS::Face(Spine.Oriented(TopAbs_FORWARD));
371   myJoinType = Join;
372   myIsOpenResult = IsOpenResult;
373   
374   myMap.Clear();
375   myMapSpine.Clear();
376   //------------------------------------------------------------------
377   // cut the spine for bissectors.
378   //------------------------------------------------------------------
379   //  Modified by Sergey KHROMOV - Tue Nov 26 17:39:03 2002 Begin
380   static BRepMAT2d_Explorer Exp;
381
382   Exp.Perform(mySpine);
383
384   //  TopoDS_Face anOldSpine = mySpine;
385
386   mySpine = TopoDS::Face(Exp.ModifiedShape(mySpine));
387   PrepareSpine  ();
388
389   //  Modified by Sergey KHROMOV - Tue Nov 26 17:39:03 2002 End
390   TopoDS_Shape aShape;
391   BRepFill_IndexedDataMapOfOrientedShapeListOfShape aMap;
392   Standard_Boolean Done;
393   if (KPartCircle(myWorkSpine,1.,myIsOpenResult,0.,aShape,aMap,Done)) return;
394
395
396   //-----------------------------------------------------
397   // Calculate the map of bissectors to the left.  
398   // and Links Topology -> base elements of the map.
399   //-----------------------------------------------------
400   
401   //  Modified by Sergey KHROMOV - Tue Nov 26 17:39:03 2002 Begin
402   //   static BRepMAT2d_Explorer Exp;
403   //  Modified by Sergey KHROMOV - Tue Nov 26 17:39:03 2002 End
404   Exp.Perform(myWorkSpine);
405   myBilo.Compute(Exp, 1 ,MAT_Left, myJoinType, myIsOpenResult);
406   myLink.Perform(Exp,myBilo);
407 }
408
409
410 //=======================================================================
411 //function : IsDone
412 //purpose  : 
413 //=======================================================================
414
415 Standard_Boolean BRepFill_OffsetWire::IsDone() const 
416 {
417   return myIsDone;
418 }
419
420
421 //=======================================================================
422 //function : Spine
423 //purpose  : 
424 //=======================================================================
425
426 const TopoDS_Face& BRepFill_OffsetWire::Spine() const 
427 {
428   return mySpine;
429 }
430
431
432 //=======================================================================
433 //function : Shape
434 //purpose  : 
435 //=======================================================================
436
437 const TopoDS_Shape& BRepFill_OffsetWire::Shape() const 
438 {
439   return myShape;
440 }
441
442
443 //=======================================================================
444 //function : GeneratedShapes
445 //purpose  : 
446 //=======================================================================
447
448 const TopTools_ListOfShape& BRepFill_OffsetWire::GeneratedShapes
449   (const TopoDS_Shape& SpineShape)
450 {  
451   if (!myCallGen) {
452     if (!myMapSpine.IsEmpty()) {
453       // myMapSpine can be empty if passed by PerformWithBilo.
454       TopTools_DataMapIteratorOfDataMapOfShapeShape it(myMapSpine);
455       for (; it.More(); it.Next()) {
456         if (myMap.Contains(it.Key())) {
457           if (!myMap.Contains(it.Value())) {
458             TopTools_ListOfShape L;
459             myMap.Add(it.Value(),L);
460           }
461           if ( !it.Value().IsSame(it.Key())) {
462             myMap.ChangeFromKey(it.Value()).Append(myMap.ChangeFromKey(it.Key()));
463             myMap.RemoveKey(it.Key());
464           }
465         }
466         if (myMap.Contains(it.Key().Reversed())) {
467           if (!myMap.Contains(it.Value().Reversed())) {
468             TopTools_ListOfShape L;
469             myMap.Add(it.Value().Reversed(),L);
470           }
471           if ( !it.Value().IsSame(it.Key())) {
472             myMap.ChangeFromKey(it.Value().Reversed()).Append(myMap.ChangeFromKey(it.Key().Reversed()));
473             myMap.RemoveKey(it.Key().Reversed());
474           }
475         }
476       }
477     }
478     myCallGen = Standard_True;
479   }
480
481   if (myMap.Contains(SpineShape)) {
482     return myMap.FindFromKey(SpineShape);
483   }
484   else {
485     static TopTools_ListOfShape Empty;
486     return Empty;
487   }
488 }
489
490
491 //=======================================================================
492 //function : JoinType
493 //purpose  : 
494 //=======================================================================
495
496 GeomAbs_JoinType BRepFill_OffsetWire::JoinType() const 
497 {
498   return myJoinType;
499 }
500
501 //=======================================================================
502 //function : Perform
503 //purpose  : 
504 //=======================================================================
505
506 void BRepFill_OffsetWire::Perform (const Standard_Real Offset,
507   const Standard_Real Alt)
508 {
509   //  Modified by skv - Fri Jul  8 11:21:38 2005 OCC9145 Begin
510   try
511   {
512     OCC_CATCH_SIGNALS
513       myCallGen = Standard_False;
514     if (KPartCircle(myWorkSpine,Offset,myIsOpenResult,Alt,myShape,myMap,myIsDone)) return;
515
516     TopoDS_Face oldWorkSpain = myWorkSpine;
517
518     TopTools_ListOfShape BadEdges;
519     CheckBadEdges(myWorkSpine,Offset,myBilo,myLink,BadEdges);
520
521     if(!BadEdges.IsEmpty())
522     {
523       // Modification of myWorkSpine;
524       //cout << "Modification of myWorkSpine : " << BadEdges.Extent() << endl;
525       BRepTools_Substitution aSubst;
526       TopTools_ListIteratorOfListOfShape it(BadEdges);
527       TopTools_ListOfShape aL;
528       Standard_Real aDefl = .01 * Abs(Offset);
529       TColStd_SequenceOfReal Parameters;
530       TColgp_SequenceOfPnt Points;
531
532       for(; it.More(); it.Next()) {
533         aL.Clear();
534         Parameters.Clear();
535         Points.Clear();
536         const TopoDS_Shape& anE = it.Value();
537
538         TopoDS_Vertex Vf, Vl;
539         TopExp::Vertices(TopoDS::Edge(anE), Vf, Vl);
540
541         Standard_Real f, l;
542         Handle(Geom_Curve) G3d = BRep_Tool::Curve(TopoDS::Edge(anE),f,l);
543         GeomAdaptor_Curve  AC(G3d,f,l);
544
545         PerformCurve(Parameters, Points, AC, aDefl, f, 
546           l, Precision::Confusion(), 2);
547
548         Standard_Integer NPnts = Points.Length();
549         if(NPnts > 2)
550         {
551           //cout << NPnts << " points " << endl;
552           TopoDS_Vertex FV = Vf;
553           TopoDS_Vertex LV;
554           TopoDS_Edge newE;
555           Standard_Integer np;
556           for(np = 2; np < NPnts; np++) {
557             gp_Pnt LP = Points(np);
558             LV = BRepLib_MakeVertex(LP);
559             newE = BRepLib_MakeEdge(FV, LV);
560             aL.Append(newE);
561             FV = LV;
562           }
563           LV = Vl;
564           newE = BRepLib_MakeEdge(FV, LV);
565           aL.Append(newE);
566         }
567         else
568         {
569           //cout << " 2 points " << endl;
570           TopoDS_Edge newE = BRepLib_MakeEdge(Vf, Vl);
571           aL.Append(newE);
572         }
573         //Update myMapSpine
574         if (myMapSpine.IsBound( anE ))
575         {
576           TopTools_ListIteratorOfListOfShape newit( aL );
577           for (; newit.More(); newit.Next())
578           {
579             TopoDS_Edge NewEdge = TopoDS::Edge( newit.Value() );
580             myMapSpine.Bind( NewEdge, myMapSpine(anE) );
581             TopoDS_Vertex NewV1, NewV2;
582             EdgeVertices( NewEdge, NewV1, NewV2 );
583             if (!myMapSpine.IsBound(NewV1)) myMapSpine.Bind( NewV1, myMapSpine(anE) );
584             if (!myMapSpine.IsBound(NewV2)) myMapSpine.Bind( NewV2, myMapSpine(anE) );
585           }
586           myMapSpine.UnBind( anE );
587         }
588         ///////////////////
589         aSubst.Substitute(anE, aL);
590       }
591
592       TopTools_DataMapOfShapeListOfShape wwmap;
593       TopoDS_Iterator itws( myWorkSpine );
594       for (; itws.More(); itws.Next())
595       {
596         TopoDS_Shape aWire = itws.Value();
597         aSubst.Build( aWire );
598         if (aSubst.IsCopied(aWire))
599         {
600           TopoDS_Wire NewWire = TopoDS::Wire( aSubst.Copy(aWire).First() );
601           NewWire.Closed( aWire.Closed() );
602           TopTools_ListOfShape Lw;
603           Lw.Append( NewWire );
604           wwmap.Bind( aWire, Lw );
605         }
606       }
607       aSubst.Clear();
608       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itmap( wwmap );
609       for (; itmap.More(); itmap.Next())
610         aSubst.Substitute( itmap.Key(), itmap.Value() );
611
612       aSubst.Build(myWorkSpine);
613
614       if(aSubst.IsCopied(myWorkSpine)) {
615         myWorkSpine = TopoDS::Face(aSubst.Copy(myWorkSpine).First());
616
617         BRepMAT2d_Explorer newExp;
618         newExp.Perform(myWorkSpine);
619         BRepMAT2d_BisectingLocus newBilo;
620         BRepMAT2d_LinkTopoBilo newLink;
621         newBilo.Compute(newExp, 1, MAT_Left, myJoinType, myIsOpenResult);
622
623         if(!newBilo.IsDone())
624         {
625           myShape.Nullify();
626           myIsDone = Standard_False;
627           return;
628         }
629
630         newLink.Perform(newExp,newBilo);
631         PerformWithBiLo(myWorkSpine,Offset,newBilo,newLink,myJoinType,Alt);
632         myWorkSpine = oldWorkSpain;
633       }
634       else {
635         PerformWithBiLo(myWorkSpine,Offset,myBilo,myLink,myJoinType,Alt);
636       }
637     }
638     else
639     {
640       PerformWithBiLo(myWorkSpine,Offset,myBilo,myLink,myJoinType,Alt);
641     }
642   }
643   catch (Standard_Failure const& anException) {
644 #ifdef OCCT_DEBUG
645     cout<<"An exception was caught in BRepFill_OffsetWire::Perform : ";
646     anException.Print(cout);
647     cout<<endl;
648 #endif
649     (void)anException;
650     myShape.Nullify();
651     myIsDone = Standard_False;
652
653     return;
654   }
655
656   //  Modified by skv - Fri Jul  8 11:21:38 2005 OCC9145 End
657   //  Modified by Sergey KHROMOV - Thu Mar 14 10:48:15 2002 Begin
658   if (!myIsOpenResult)
659   {
660     TopExp_Explorer anExp(myShape, TopAbs_WIRE);
661
662     for (; anExp.More(); anExp.Next()) {
663       const TopoDS_Shape &aWire = anExp.Current();
664
665       if (!aWire.Closed()) {
666         myShape.Nullify();
667         myIsDone = Standard_False;
668         throw Standard_ConstructionError("Offset wire is not closed.");
669       }
670     }
671   }
672   //  Modified by Sergey KHROMOV - Thu Mar 14 10:48:16 2002 End
673 }
674
675 //=======================================================================
676 //function : Compute
677 //purpose  : 
678 //=======================================================================
679
680 void Compute (const TopoDS_Face&  Spine,
681   TopoDS_Shape& aShape,
682   BRepFill_IndexedDataMapOfOrientedShapeListOfShape& Map,
683   const Standard_Real Alt)
684 {
685   BRep_Builder B;
686   B.MakeCompound(TopoDS::Compound(aShape));
687   Standard_Real ALT = Alt;
688   if ( Spine.Orientation() == TopAbs_REVERSED) ALT = -Alt;
689   gp_Trsf T;
690   T.SetTranslation(gp_Vec(0.,0.,ALT));
691   TopLoc_Location L(T);
692
693   for ( TopExp_Explorer exp(Spine,TopAbs_WIRE); exp.More(); exp.Next()) {
694     const TopoDS_Wire& CurW = TopoDS::Wire(exp.Current());
695     TopoDS_Shape aLocalShape = CurW.Moved(L);
696     TopoDS_Wire        NewW = TopoDS::Wire(aLocalShape);
697     //    TopoDS_Wire        NewW = TopoDS::Wire(CurW.Moved(L));
698     B.Add(aShape,NewW);
699     // update Map.
700     TopoDS_Iterator it1( CurW);
701     TopoDS_Iterator it2( NewW);
702     for ( ; it1.More(); it1.Next(), it2.Next()) {
703       TopTools_ListOfShape List;
704       List.Append(it2.Value());
705       Map.Add(it1.Value(), List);
706     }
707   }
708 }
709
710 //=======================================================================
711 //function : PerformWithBiLo
712 //purpose  : 
713 //=======================================================================
714
715 void BRepFill_OffsetWire::PerformWithBiLo
716   (const TopoDS_Face&              Spine,
717   const Standard_Real             Offset,
718   const BRepMAT2d_BisectingLocus& Locus, 
719   BRepMAT2d_LinkTopoBilo&   Link,
720   const GeomAbs_JoinType          Join,
721   const Standard_Real             Alt)
722 {
723   myIsDone     = Standard_False;
724   TopoDS_Shape aLocalShapeWork = Spine.Oriented(TopAbs_FORWARD);
725   myWorkSpine  = TopoDS::Face(aLocalShapeWork);
726   //  myWorkSpine  = TopoDS::Face(Spine.Oriented(TopAbs_FORWARD));
727   myJoinType   = Join;
728   myOffset     = Offset ;
729   myShape.Nullify();
730
731
732   if (mySpine.IsNull()) {
733     TopoDS_Shape aLocalShape = Spine.Oriented(TopAbs_FORWARD);
734     mySpine = TopoDS::Face(aLocalShape);
735     //    mySpine = TopoDS::Face(Spine.Oriented(TopAbs_FORWARD));
736   }
737   myMap.Clear();
738
739   if ( Abs(myOffset) < Precision::Confusion()) {
740     Compute(mySpine,myShape,myMap,Alt);
741     myIsDone = Standard_True;
742     return;
743   }
744
745   //********************************
746   // Calculate for a non null offset 
747   //********************************
748   if (KPartCircle(myWorkSpine,Offset,myIsOpenResult,Alt,myShape,myMap,myIsDone))
749     return;
750
751   BRep_Builder myBuilder;
752
753   //---------------------------------------------------------------------
754   // MapNodeVertex : associate to each node of the map (key1) and to
755   //                 each element of the profile (key2) a vertex (item).
756   // MapBis        : all edges or vertices (item) generated by 
757   //                 a bisectrice on a face or an edge (key) of revolution tubes.
758   // MapVerPar     : Map of parameters of vertices on parallel edges 
759   //                 the list contained in MapVerPar (E) corresponds to 
760   //                 parameters on E of vertices contained in MapBis(E);
761   //---------------------------------------------------------------------
762
763
764   BRepFill_DataMapOfNodeShape               MapNodeVertex; 
765   TopTools_DataMapOfShapeSequenceOfShape    MapBis;  
766   BRepFill_DataMapOfShapeSequenceOfReal     MapVerPar;
767
768   TopTools_DataMapOfShapeShape              EmptyMap;
769   TopTools_SequenceOfShape                  EmptySeq;
770   TopTools_ListOfShape                      EmptyList;
771   TColStd_SequenceOfReal                    EmptySeqOfReal;
772
773   Handle(Geom_Plane) RefPlane = 
774     Handle(Geom_Plane)::DownCast(BRep_Tool::Surface(myWorkSpine));
775   if (fabs(Alt) > gp::Resolution()) {
776     Standard_Real anAlt = Alt;
777     if ( myWorkSpine.Orientation() == TopAbs_REVERSED) anAlt = -Alt;
778     RefPlane = Handle(Geom_Plane)::DownCast
779       (RefPlane->Translated( anAlt * gp_Vec(RefPlane->Axis().Direction() )));
780   }
781
782   //---------------------------------------------------------------
783   // Construction of Circles and OffsetCurves
784   //---------------------------------------------------------------
785
786   TopoDS_Vertex Ends [2];
787   if (myIsOpenResult)
788   {
789     TopoDS_Wire theWire;
790     TopoDS_Iterator iter(mySpine);
791     theWire = TopoDS::Wire(iter.Value());
792     TopExp::Vertices(theWire, Ends[0], Ends[1]);
793   }
794
795   if (Locus.NumberOfContours() == 0)
796   {
797     return;
798   }
799
800   for (Standard_Integer ic = 1; ic <= Locus.NumberOfContours(); ic++) {
801     TopoDS_Shape PEE = Link.GeneratingShape(Locus.BasicElt(ic,Locus.NumberOfElts(ic)));
802     TopoDS_Shape& PE = PEE ;      
803     for (Standard_Integer ie = 1; ie <= Locus.NumberOfElts(ic); ie++) {
804       const TopoDS_Shape& SE = Link.GeneratingShape(Locus.BasicElt(ic,ie));
805       if (SE.ShapeType() == TopAbs_VERTEX) {
806         if (!SE.IsSame(Ends[0]) && !SE.IsSame(Ends[1]))
807           MakeCircle (TopoDS::Edge(PE),TopoDS::Vertex(SE),
808                       myWorkSpine,myOffset,myMap,RefPlane);
809       }
810       else {
811         MakeOffset (TopoDS::Edge(SE),myWorkSpine,myOffset,myMap,RefPlane,
812                     myIsOpenResult, myJoinType, Ends);
813         PE = SE;
814       }
815     }
816   }
817
818   //Remove possible hanging arcs on vertices
819   if (myIsOpenResult && myJoinType == GeomAbs_Arc)
820   {
821     if (!myMap.IsEmpty() &&
822         myMap.FindKey(1).ShapeType() == TopAbs_VERTEX)
823     {
824       myMap.RemoveFromIndex(1);
825     }
826     if (!myMap.IsEmpty() &&
827         myMap.FindKey(myMap.Extent()).ShapeType() == TopAbs_VERTEX)
828       myMap.RemoveLast();
829   }
830
831 #ifdef OCCT_DEBUG
832 #ifdef DRAW
833   if (AffichEdge) {
834     cout << " End Construction of geometric primitives "<<endl;
835   }
836 #endif
837 #endif
838
839
840   //---------------------------------------------------
841   // Construction of offset vertices.
842   //---------------------------------------------------
843   BRepFill_DataMapOfOrientedShapeListOfShape Detromp;
844   Handle(MAT_Arc)        CurrentArc;
845   Handle(Geom2d_Curve)   Bis, PCurve1, PCurve2 ;
846   Handle(Geom_Curve)     CBis;
847   Standard_Boolean       Reverse;
848   TopoDS_Edge            CurrentEdge;
849   TopoDS_Shape           S       [2];
850   TopoDS_Edge            E       [2];
851   TopLoc_Location        L;
852   Standard_Integer       j, k;
853
854   for (Standard_Integer i = 1; i <= Locus.Graph()->NumberOfArcs(); i++) {
855
856     CurrentArc           = Locus.Graph()->Arc(i);
857     Bisector_Bisec Bisec = Locus.GeomBis(CurrentArc,Reverse);
858 #ifdef OCCT_DEBUG
859 #ifdef DRAW
860
861     if ( AffichGeom) {
862       char name[256];
863       sprintf(name,"BISSEC_%d",NbBISSEC++);
864       DrawTrSurf::Set(name,Bisec.Value());
865     }
866 #endif
867 #endif
868
869     //-------------------------------------------------------------------
870     // Return elements of the spine corresponding to separate basicElts.
871     //-------------------------------------------------------------------
872     S [0] = Link.GeneratingShape(CurrentArc->FirstElement());
873     S [1] = Link.GeneratingShape(CurrentArc->SecondElement());
874
875     TopTools_SequenceOfShape Vertices;
876     TColgp_SequenceOfPnt     Params;
877
878     TopTools_DataMapOfShapeSequenceOfShape MapSeqVer;
879     BRepFill_DataMapOfShapeSequenceOfPnt   MapSeqPar;
880
881     //-----------------------------------------------------------
882     // Return parallel edges on each face.
883     // If no offset generated => move to the next bissectrice. 
884     //--------------------------------------------------------------
885     if (myMap.Contains(S[0]) && myMap.Contains(S[1])) {
886       E [0] = TopoDS::Edge(myMap.FindFromKey(S[0]).First());
887       E [1] = TopoDS::Edge(myMap.FindFromKey(S[1]).First());
888     }
889     else continue;
890
891     //-----------------------------------------------------------
892     // Construction of vertices corresponding to the node of the map.
893     // if they are on the offset.
894     //-----------------------------------------------------------
895     TopoDS_Vertex VS,VE;
896     Handle(MAT_Node) Node1, Node2;
897
898     if (Reverse) {
899       Node1 = CurrentArc->SecondNode();
900       Node2 = CurrentArc->FirstNode();
901     }
902     else  {
903       Node1 = CurrentArc->FirstNode();
904       Node2 = CurrentArc->SecondNode();
905     }
906
907     Standard_Boolean StartOnEdge = 0, EndOnEdge = 0;
908
909     if (!Node1->Infinite()) {
910       gp_Pnt2d aLocalPnt2d = Locus.GeomElt(Node1);
911       StartOnEdge = VertexFromNode(Node1, myOffset, aLocalPnt2d ,MapNodeVertex,VS);
912       //      StartOnEdge = VertexFromNode(Node1, myOffset, Locus.GeomElt(Node1),
913       //                                   MapNodeVertex,VS);
914     }
915     if (!Node2->Infinite()) {
916       gp_Pnt2d aLocalPnt2d = Locus.GeomElt(Node2) ;
917       EndOnEdge   = VertexFromNode(Node2, myOffset, aLocalPnt2d ,MapNodeVertex,VE);
918       //      EndOnEdge   = VertexFromNode(Node2, myOffset, Locus.GeomElt(Node2),
919       //                                   MapNodeVertex,VE);
920     }
921
922     if (myJoinType == GeomAbs_Intersection)
923       StartOnEdge = EndOnEdge = 0;
924
925     //---------------------------------------------
926     // Construction of geometries.
927     //---------------------------------------------
928     BRepFill_TrimEdgeTool Trim (Bisec, 
929       Locus.GeomElt(CurrentArc->FirstElement()),
930       Locus.GeomElt(CurrentArc->SecondElement()),
931       myOffset);
932
933     //-----------------------------------------------------------
934     // Construction of vertices on edges parallel to the spine.
935     //-----------------------------------------------------------
936
937     Trim.IntersectWith(E[0], E[1], S[0], S[1], Ends[0], Ends[1],
938                        myJoinType, myIsOpenResult, Params);
939
940     for (Standard_Integer s = 1; s <= Params.Length(); s++) {
941       TopoDS_Vertex VC;
942       myBuilder.MakeVertex (VC);
943       gp_Pnt2d P2  = Bisec.Value()->Value(Params.Value(s).X());
944       gp_Pnt   PVC(P2.X(),P2.Y(),0.);
945
946       myBuilder.UpdateVertex(VC,PVC,Precision::Confusion());
947       Vertices.Append(VC);
948     }
949     if (StartOnEdge) {
950       Standard_Boolean Start = 1;
951       Trim.AddOrConfuse(Start, E[0], E[1], Params);
952       if (Params.Length() == Vertices.Length()) 
953         Vertices.SetValue(1,VS);
954       
955       else
956         // the point was not found by IntersectWith
957         Vertices.Prepend(VS);
958     }
959     if (EndOnEdge) {      
960       Standard_Boolean Start = 0;
961       Trim.AddOrConfuse(Start, E[0], E[1], Params);
962       if (Params.Length() == Vertices.Length()) 
963         Vertices.SetValue(Params.Length(),VE);
964       
965       else
966         // the point was not found by IntersectWith
967         Vertices.Append(VE);
968     }
969
970     //------------------------------------------------------------
971     // Update Detromp.
972     // Detromp allows to remove vertices on the offset 
973     // corresponding to tangency zones
974     // Detromp ranks the vertices that limit
975     // the parts of the bissectrices located between the spine and the 
976     // offset.
977     //------------------------------------------------------------
978     if (!Detromp.IsBound(S[0])) Detromp.Bind(S[0],EmptyList);
979     if (!Detromp.IsBound(S[1])) Detromp.Bind(S[1],EmptyList);
980
981     
982     UpdateDetromp (Detromp, S[0], S[1], Vertices, Params, 
983       Bisec, StartOnEdge, EndOnEdge, Trim);
984     //----------------------------------------------
985     // Storage of vertices on parallel edges.
986     // fill MapBis and MapVerPar.
987     //----------------------------------------------
988     if (!Vertices.IsEmpty()) {
989       for (k = 0; k <= 1; k++) {
990         if (!MapBis.IsBound(E[k])) {
991           MapBis   .Bind(E[k],EmptySeq);
992           MapVerPar.Bind(E[k],EmptySeqOfReal);
993         } 
994         for (Standard_Integer ii = 1; ii <= Vertices.Length(); ii++) {
995           MapBis (E[k]).Append(Vertices.Value(ii));
996           if (k == 0) MapVerPar (E[k]).Append(Params.Value(ii).Y());
997           else        MapVerPar (E[k]).Append(Params.Value(ii).Z());
998         }
999       }
1000     }
1001     else {
1002       //------------------------------------------------------------
1003       // FOR COMPLETE CIRCLES. the parallel line can be contained
1004       // in the zone without intersection with the border
1005       // no intersection 
1006       // if myoffset is < distance of nodes the parallel can be valid.
1007       //-------------------------------------------------------------
1008       for (k = 0; k <= 1; k++) {
1009         if (!MapBis.IsBound(E[k])) {
1010           if (Node1->Distance() > myOffset && Node2->Distance() > myOffset) {
1011             MapBis   .Bind(E[k],EmptySeq); 
1012             MapVerPar.Bind(E[k],EmptySeqOfReal);
1013           }
1014         }
1015       }
1016     }
1017   }
1018
1019 #ifdef OCCT_DEBUG
1020 #ifdef DRAW
1021   if (AffichEdge) {
1022     cout << " End Construction of vertices on offsets"<<endl;
1023   }
1024 #endif
1025 #endif
1026
1027   //----------------------------------
1028   // Construction of parallel edges.
1029   //----------------------------------
1030   TopTools_IndexedDataMapOfShapeShape MapVV;
1031
1032   TopoDS_Shape CurrentSpine;
1033
1034   //BRepFill_DataMapIteratorOfDataMapOfOrientedShapeListOfShape ite1;  
1035
1036   for (j = 1; j <= myMap.Extent(); j++) {
1037     CurrentSpine = myMap.FindKey(j);
1038     CurrentEdge  = TopoDS::Edge(myMap(j).First());
1039
1040     myMap(j).Clear();
1041     if (MapBis.IsBound(CurrentEdge)) {
1042       TopTools_SequenceOfShape aSeqOfShape;
1043       if (!MapBis(CurrentEdge).IsEmpty()) {
1044         Standard_Integer IndOfE = 0;
1045         if (myIsOpenResult)
1046         {
1047           if (j == 1)
1048             IndOfE = 1;
1049           else if (j == myMap.Extent())
1050             IndOfE = -1;
1051         }
1052         TrimEdge (CurrentEdge,
1053           CurrentSpine,
1054           mySpine,
1055           Detromp  (CurrentSpine),
1056           MapBis   (CurrentEdge) ,  
1057           MapVerPar(CurrentEdge) ,
1058           aSeqOfShape, MapVV, IndOfE);
1059         for ( k = 1; k <= aSeqOfShape.Length(); k++) {
1060           myMap(j).Append(aSeqOfShape.Value(k));
1061         }
1062       }
1063       else {
1064         //-----------------
1065         // Complete circles
1066         //-----------------
1067         myMap(j).Append(CurrentEdge);
1068       }
1069     }
1070   }
1071
1072   Standard_Integer ind;
1073   for (ind = 1; ind <= MapVV.Extent(); ind++)
1074   {
1075     TopoDS_Vertex OldV = TopoDS::Vertex(MapVV.FindKey(ind));
1076     TopoDS_Vertex NewV = TopoDS::Vertex(MapVV(ind));
1077     gp_Pnt P1 = BRep_Tool::Pnt(OldV);
1078     gp_Pnt P2 = BRep_Tool::Pnt(NewV);
1079     myBuilder.UpdateVertex(NewV, P1.Distance(P2));
1080     TopTools_ListOfShape LV;
1081     LV.Append( NewV.Oriented(TopAbs_FORWARD) );
1082     BRepTools_Substitution aSubst;
1083     aSubst.Substitute( OldV, LV );
1084     for (j = 1; j <= myMap.Extent(); j++)
1085     {
1086       TopTools_ListIteratorOfListOfShape itl(myMap(j));
1087       for (; itl.More(); itl.Next())
1088       {
1089         aSubst.Build(itl.Value());
1090         if (aSubst.IsCopied(itl.Value()))
1091         {
1092           const TopTools_ListOfShape& listSh = aSubst.Copy(itl.Value());
1093           TopAbs_Orientation SaveOr = itl.Value().Orientation();
1094           itl.Value() = listSh.First();
1095           itl.Value().Orientation(SaveOr);
1096         }
1097       }
1098     }
1099   }
1100       
1101   //----------------------------------
1102   // Construction of offset wires.
1103   //----------------------------------
1104   MakeWires ();
1105
1106   // Update vertices ( Constructed in the plane Z = 0) !!!
1107   TopTools_MapOfShape MapVertex;
1108   for ( TopExp_Explorer exp(myShape,TopAbs_VERTEX); exp.More(); exp.Next()) {
1109     TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
1110     if ( MapVertex.Add(V)) {
1111       gp_Pnt        P = BRep_Tool::Pnt(V);
1112       P = RefPlane->Value(P.X(),P.Y());
1113       myBuilder.UpdateVertex(V,P, Precision::Confusion());
1114     }
1115   }
1116
1117   // Construction of curves 3d.
1118   BRepLib::BuildCurves3d(myShape);
1119   MapVertex.Clear();
1120   TopExp_Explorer Explo( myShape, TopAbs_EDGE );
1121   for (; Explo.More(); Explo.Next())
1122   {
1123     TopoDS_Edge anEdge = TopoDS::Edge( Explo.Current() );
1124     TopoDS_Vertex V1, V2;
1125     TopExp::Vertices(anEdge, V1, V2 );
1126     Handle(BRep_TVertex)& TV1 = *((Handle(BRep_TVertex)*) &(V1).TShape());
1127     Handle(BRep_TVertex)& TV2 = *((Handle(BRep_TVertex)*) &(V2).TShape());
1128
1129     TopLoc_Location loc;
1130     Standard_Real f, l;
1131     Handle( Geom_Curve ) theCurve = BRep_Tool::Curve(anEdge, loc, f, l );
1132     theCurve = Handle( Geom_Curve )::DownCast( theCurve->Copy() );
1133     theCurve->Transform( loc.Transformation() );
1134     gp_Pnt f3d = theCurve->Value( f );
1135     gp_Pnt l3d = theCurve->Value( l );
1136
1137     Standard_Real dist1, dist2;
1138     dist1 = f3d.Distance( TV1->Pnt() );
1139     dist2 = l3d.Distance( TV2->Pnt() );
1140     if (! MapVertex.Contains( V1 ))
1141     {
1142       
1143       TV1->Pnt( f3d );
1144       MapVertex.Add( V1 );
1145     }
1146     else
1147       TV1->UpdateTolerance( 1.5*dist1 );
1148     if (! MapVertex.Contains( V2 ))
1149     {
1150       TV2->Pnt( l3d );
1151       MapVertex.Add( V2 );
1152     }
1153     else
1154       TV2->UpdateTolerance( 1.5*dist2 );
1155   }
1156
1157   if (!myIsOpenResult)
1158     FixHoles();
1159
1160   myIsDone = Standard_True;
1161 }
1162
1163
1164 //=======================================================================
1165 //function : Generated
1166 //purpose  : 
1167 //=======================================================================
1168
1169 BRepFill_IndexedDataMapOfOrientedShapeListOfShape& 
1170   BRepFill_OffsetWire::Generated() 
1171 {
1172   return myMap;
1173 }
1174
1175
1176 //=======================================================================
1177 //function : PrepareSpine
1178 //purpose  : 
1179 //=======================================================================
1180
1181 void BRepFill_OffsetWire::PrepareSpine()
1182 {
1183   BRep_Builder      B;
1184   TopTools_ListOfShape Cuts;
1185   TopTools_ListIteratorOfListOfShape IteCuts;
1186   TopoDS_Vertex V1,V2;
1187
1188   myWorkSpine.Nullify();
1189   myMapSpine.Clear();
1190
1191   TopLoc_Location L;
1192   const Handle(Geom_Surface)& S    = BRep_Tool::Surface  (mySpine,L);
1193   Standard_Real               TolF = BRep_Tool::Tolerance(mySpine);
1194   B.MakeFace(myWorkSpine,S,L,TolF);
1195   
1196   for (TopoDS_Iterator IteF(mySpine) ; IteF.More(); IteF.Next()) {
1197
1198     TopoDS_Wire NW;
1199     B.MakeWire (NW);
1200
1201     //  Modified by Sergey KHROMOV - Thu Nov 16 17:29:55 2000 Begin
1202     Standard_Integer ForcedCut = 0;
1203     Standard_Integer nbResEdges = -1;
1204     TopTools_IndexedMapOfShape EdgeMap;
1205
1206     TopExp::MapShapes(IteF.Value(), TopAbs_EDGE, EdgeMap);
1207     Standard_Integer nbEdges = EdgeMap.Extent();
1208     
1209     if (nbEdges == 1 && !myIsOpenResult) //in case of open wire there's no need to do it
1210       ForcedCut = 2;
1211     //  Modified by Sergey KHROMOV - Thu Nov 16 17:29:48 2000 End
1212
1213     for (TopoDS_Iterator IteW(IteF.Value()); IteW.More(); IteW.Next()) {
1214       
1215       const TopoDS_Edge& E = TopoDS::Edge(IteW.Value());
1216       EdgeVertices(E,V1,V2);
1217       myMapSpine.Bind(V1,V1);
1218       myMapSpine.Bind(V2,V2);
1219       Cuts.Clear();
1220
1221       // Cut
1222       TopoDS_Shape aLocalShape = E.Oriented(TopAbs_FORWARD);
1223       //  Modified by Sergey KHROMOV - Thu Nov 16 17:29:29 2000 Begin
1224       if (nbEdges == 2 && nbResEdges == 0)
1225         ForcedCut = 1;
1226       //  Modified by Sergey KHROMOV - Thu Nov 16 17:29:33 2000 End
1227       nbResEdges = CutEdge (TopoDS::Edge(aLocalShape), mySpine, ForcedCut, Cuts);
1228       
1229       if (Cuts.IsEmpty()) {
1230         B.Add(NW,E);
1231         myMapSpine.Bind(E,E);
1232       }
1233       else {    
1234         for (IteCuts.Initialize(Cuts); IteCuts.More(); IteCuts.Next()) {
1235           TopoDS_Edge NE = TopoDS::Edge(IteCuts.Value());
1236           NE.Orientation(E.Orientation());
1237           B.Add(NW,NE);
1238           myMapSpine.Bind(NE,E);
1239           EdgeVertices(NE,V1,V2);
1240           if (!myMapSpine.IsBound(V1)) myMapSpine.Bind(V1,E);
1241           if (!myMapSpine.IsBound(V2)) myMapSpine.Bind(V2,E);
1242         }
1243       }
1244     }
1245     //  Modified by Sergey KHROMOV - Thu Mar  7 09:17:41 2002 Begin
1246     TopoDS_Vertex aV1;
1247     TopoDS_Vertex aV2;
1248
1249     TopExp::Vertices(NW, aV1, aV2);
1250
1251     NW.Closed(aV1.IsSame(aV2));
1252
1253     //  Modified by Sergey KHROMOV - Thu Mar  7 09:17:43 2002 End
1254     B.Add(myWorkSpine, NW);
1255   }
1256
1257 #ifdef OCCT_DEBUG
1258 #ifdef DRAW
1259   if ( AffichEdge) {
1260     DBRep::Set("WS",myWorkSpine);
1261     DBRep::Set("MS",mySpine);
1262     BRepTools::Write(myWorkSpine, "WS");
1263     BRepTools::Write(mySpine, "MS");
1264   }
1265 #endif
1266 #endif
1267
1268 }
1269
1270 //=======================================================================
1271 //function : UpdateDetromp
1272 //purpose  : For each interval on bissectrice defined by parameters
1273 //           test if the medium point is at a distance > offset 
1274 //           in this case vertices corresponding to the extremities of the interval
1275 //           are ranked in the proofing.
1276 //           => If the same vertex appears in the proofing, the 
1277 //           border of the zone of proximity is tangent to the offset .
1278 //=======================================================================
1279
1280 void BRepFill_OffsetWire::UpdateDetromp (BRepFill_DataMapOfOrientedShapeListOfShape& Detromp,
1281                                          const TopoDS_Shape& Shape1,
1282                                          const TopoDS_Shape& Shape2,
1283                                          const TopTools_SequenceOfShape& Vertices, 
1284                                          const TColgp_SequenceOfPnt&     Params, 
1285                                          const Bisector_Bisec&           Bisec,
1286                                          const Standard_Boolean          SOnE,
1287                                          const Standard_Boolean          EOnE,
1288                                          const BRepFill_TrimEdgeTool&    Trim) const
1289 {
1290   Standard_Integer ii = 1;
1291
1292   if (myJoinType == GeomAbs_Intersection)
1293   {
1294     for (; ii <= Vertices.Length(); ii++)
1295     {
1296       const TopoDS_Vertex& aVertex = TopoDS::Vertex(Vertices.Value(ii));
1297       Detromp(Shape1).Append(aVertex);
1298       Detromp(Shape2).Append(aVertex);
1299     }
1300   }
1301   else //myJoinType == GeomAbs_Arc
1302   {
1303     Standard_Real    U1,U2;
1304     TopoDS_Vertex    V1,V2;
1305     
1306     const Handle(Geom2d_Curve)& Bis = Bisec.Value();
1307     Standard_Boolean ForceAdd = Standard_False;
1308     Handle(Geom2d_TrimmedCurve) aTC = Handle(Geom2d_TrimmedCurve)::DownCast(Bis);
1309     if(!aTC.IsNull() && aTC->BasisCurve()->IsPeriodic())
1310     {
1311       gp_Pnt2d Pf = Bis->Value(Bis->FirstParameter());
1312       gp_Pnt2d Pl = Bis->Value(Bis->LastParameter());
1313       ForceAdd = Pf.Distance(Pl) <= Precision::Confusion();
1314     }
1315
1316     U1 = Bis->FirstParameter();
1317     
1318     if (SOnE) { 
1319       // the first point of the bissectrice is on the offset
1320       V1 = TopoDS::Vertex(Vertices.Value(ii));
1321       ii++; 
1322     }
1323     
1324     while (ii <= Vertices.Length()) {
1325       U2 = Params.Value(ii).X();
1326       V2 = TopoDS::Vertex(Vertices.Value(ii));
1327       
1328       gp_Pnt2d P = Bis->Value((U2 + U1)*0.5);
1329       if (!Trim.IsInside(P) || ForceAdd) {
1330         if (!V1.IsNull()) {
1331           Detromp(Shape1).Append(V1);
1332           Detromp(Shape2).Append(V1);
1333         }
1334         Detromp(Shape1).Append(V2);
1335         Detromp(Shape2).Append(V2);
1336       }
1337       U1 = U2;
1338       V1 = V2;
1339       ii ++;
1340     }
1341     
1342     // test medium point between the last parameter and the end of the bissectrice.
1343     U2 = Bis->LastParameter();
1344     if (!EOnE) {
1345       if (!Precision::IsInfinite(U2)) {
1346         gp_Pnt2d P = Bis->Value((U2 + U1)*0.5);
1347         if (!Trim.IsInside(P) || ForceAdd) {
1348           if (!V1.IsNull()) {
1349             Detromp(Shape1).Append(V1);
1350             Detromp(Shape2).Append(V1);
1351           }
1352         }
1353       }
1354       else {
1355         if (!V1.IsNull()) {
1356           Detromp(Shape1).Append(V1);
1357           Detromp(Shape2).Append(V1);
1358         }
1359       }
1360     }    
1361     //else if(myJoinType != GeomAbs_Arc)
1362     //{
1363     //  if (!V1.IsNull()) {
1364     //    Detromp(Shape1).Append(V1);
1365     //    Detromp(Shape2).Append(V1);
1366     //  }
1367     //}
1368   } //end of else (myJoinType==GeomAbs_Arc)
1369 }
1370
1371 //=======================================================================
1372 //function : MakeWires
1373 //purpose  : 
1374 //=======================================================================
1375
1376 void BRepFill_OffsetWire::MakeWires()
1377 {
1378   //--------------------------------------------------------
1379   // creation of a single list of created parallel edges.
1380   //--------------------------------------------------------
1381   TopTools_SequenceOfShape TheEdges;
1382   TopTools_ListOfShape     TheWires;
1383   TopTools_ListIteratorOfListOfShape                          itl;
1384   //BRepFill_DataMapIteratorOfDataMapOfOrientedShapeListOfShape ite;  
1385   TopTools_IndexedDataMapOfShapeListOfShape                   MVE;
1386   //TopTools_DataMapIteratorOfDataMapOfShapeListOfShape         MVEit;
1387   TopoDS_Vertex V1,V2,VF,CV;
1388   Standard_Integer i;
1389
1390   for (i = 1; i <= myMap.Extent(); i++) {    
1391     for (itl.Initialize(myMap(i)); itl.More(); itl.Next()) {
1392       const TopoDS_Edge& E = TopoDS::Edge(itl.Value());
1393       TopExp::Vertices (E,V1,V2);
1394       if (V1.IsSame(V2) && IsSmallClosedEdge(E, V1))
1395         continue; //remove small closed edges
1396       if (!CheckSmallParamOnEdge(E))
1397         continue;
1398       if (!MVE.Contains(V1)) {
1399         TopTools_ListOfShape empty;
1400         MVE.Add(V1,empty);
1401       }
1402       MVE.ChangeFromKey(V1).Append(E);
1403       if (!MVE.Contains(V2)) {
1404         TopTools_ListOfShape empty;
1405         MVE.Add(V2,empty);
1406       }
1407       MVE.ChangeFromKey(V2).Append(E);
1408     }
1409   }
1410
1411   //--------------------------------------
1412   // Creation of parallel wires.
1413   //--------------------------------------
1414   BRep_Builder B;
1415
1416
1417   //  Standard_Integer NbEdges;
1418   //  Standard_Boolean NewWire  = Standard_True;
1419   //  Standard_Boolean AddEdge  = Standard_False;
1420
1421   TopoDS_Wire      NW;
1422   Standard_Boolean End;
1423   TopoDS_Edge CE;
1424
1425   while (!MVE.IsEmpty()) {
1426     B.MakeWire(NW);
1427
1428     //MVEit.Initialize(MVE);
1429     for (i = 1; i <= MVE.Extent(); i++)
1430       if(MVE(i).Extent() == 1)
1431         break;
1432
1433     //if(!MVEit.More()) MVEit.Initialize(MVE);
1434     if (i > MVE.Extent())
1435       i = 1;
1436     
1437     CV  = VF = TopoDS::Vertex(MVE.FindKey(i));
1438     CE  = TopoDS::Edge(MVE(i).First());
1439     End = Standard_False;
1440     MVE.ChangeFromKey(CV).RemoveFirst();
1441
1442     if (myIsOpenResult && MVE.FindFromKey(CV).IsEmpty())
1443     {
1444       MVE.RemoveKey(CV);
1445     }
1446       
1447
1448     //  Modified by Sergey KHROMOV - Thu Mar 14 11:29:59 2002 Begin
1449     Standard_Boolean isClosed = Standard_False;
1450
1451     //  Modified by Sergey KHROMOV - Thu Mar 14 11:30:00 2002 End
1452
1453     while(!End) {      
1454       //-------------------------------
1455       // Construction of a wire.
1456       //-------------------------------
1457       TopExp::Vertices(CE,V1,V2);
1458       if (!CV.IsSame(V1)) CV = V1; else CV = V2;
1459
1460       B.Add (NW,CE);
1461
1462       if (VF.IsSame(CV) || !MVE.Contains(CV)) {
1463         //  Modified by Sergey KHROMOV - Thu Mar 14 11:30:14 2002 Begin
1464         isClosed = VF.IsSame(CV);
1465         //  Modified by Sergey KHROMOV - Thu Mar 14 11:30:15 2002 End
1466         End = Standard_True;
1467         MVE.RemoveKey(VF);
1468       }
1469
1470       if (!End) {
1471         if (MVE.FindFromKey(CV).Extent() > 2) {
1472           //cout <<"vertex on more that 2 edges in a face."<<endl;
1473         }
1474         for ( itl.Initialize(MVE.FindFromKey(CV)); itl.More(); itl.Next()) {
1475           if (itl.Value().IsSame(CE)) {
1476             MVE.ChangeFromKey(CV).Remove(itl);
1477             break;
1478           }
1479         }
1480         if (!MVE.FindFromKey(CV).IsEmpty()) {
1481           CE = TopoDS::Edge(MVE.FindFromKey(CV).First());
1482           MVE.ChangeFromKey(CV).RemoveFirst();
1483         }
1484         else if (myIsOpenResult)//CV was a vertex with one edge
1485           End = Standard_True;
1486         
1487         if (MVE.FindFromKey(CV).IsEmpty())
1488         {
1489           MVE.RemoveKey(CV);
1490         }
1491       }
1492     }
1493     //  Modified by Sergey KHROMOV - Thu Mar 14 11:29:31 2002 Begin
1494     //     NW.Closed(Standard_True);
1495     NW.Closed(isClosed);
1496     //  Modified by Sergey KHROMOV - Thu Mar 14 11:29:37 2002 End
1497     TheWires.Append(NW);
1498   }
1499
1500   // update myShape :
1501   //      -- if only one wire : myShape is a Wire
1502   //      -- if several wires : myShape is a Compound.
1503   if ( TheWires.Extent() == 1) {
1504     myShape = TheWires.First();
1505   }
1506   else {
1507     TopoDS_Compound R;
1508     B.MakeCompound(R);
1509     TopTools_ListIteratorOfListOfShape it(TheWires);
1510     for ( ; it.More(); it.Next()) {
1511       B.Add(R, it.Value());
1512     }
1513     myShape = R;
1514   }
1515   
1516 }
1517
1518 //=======================================================================
1519 //function : FixHoles
1520 //purpose  : 
1521 //=======================================================================
1522
1523 void BRepFill_OffsetWire::FixHoles()
1524 {
1525   TopTools_SequenceOfShape ClosedWires, UnclosedWires, IsolatedWires;
1526
1527   Standard_Real MaxTol = 0.;
1528   BRep_Builder BB;
1529
1530   TopExp_Explorer Explo( mySpine, TopAbs_VERTEX );
1531   for (; Explo.More(); Explo.Next())
1532   {
1533     const TopoDS_Vertex& aVertex = TopoDS::Vertex( Explo.Current() );
1534     Standard_Real Tol = BRep_Tool::Tolerance(aVertex);
1535     if (Tol > MaxTol)
1536       MaxTol = Tol;
1537   }
1538   MaxTol *= 100.;
1539
1540   Explo.Init( myShape, TopAbs_WIRE );
1541   for (; Explo.More(); Explo.Next())
1542   {
1543     TopoDS_Shape aWire = Explo.Current();
1544     // Remove duplicated edges
1545     TopTools_DataMapOfShapeListOfShape EEmap;
1546     TopoDS_Iterator it( aWire );
1547     for (; it.More(); it.Next())
1548     {
1549       const TopoDS_Shape& anEdge = it.Value();
1550       if (! EEmap.IsBound( anEdge ))
1551       {
1552         TopTools_ListOfShape LE;
1553         EEmap.Bind( anEdge, LE );
1554       }
1555       else
1556         EEmap(anEdge).Append( anEdge );
1557     }
1558     aWire.Free( Standard_True );
1559     TopTools_DataMapIteratorOfDataMapOfShapeListOfShape mapit( EEmap );
1560     for (; mapit.More(); mapit.Next())
1561     {
1562       const TopTools_ListOfShape& LE = mapit.Value();
1563       TopTools_ListIteratorOfListOfShape itl( LE );
1564       for (; itl.More(); itl.Next())
1565         BB.Remove( aWire, itl.Value() );
1566     }
1567     // Sorting
1568     if (aWire.Closed())
1569       ClosedWires.Append( aWire );
1570     else
1571       UnclosedWires.Append( aWire );
1572   }
1573
1574   while (!UnclosedWires.IsEmpty())
1575   {
1576     TopoDS_Wire& Base = TopoDS::Wire( UnclosedWires(1) );
1577     TopoDS_Vertex Vf, Vl;
1578     TopExp::Vertices( Base, Vf, Vl );
1579     if(Vf.IsNull() || Vl.IsNull())
1580     {
1581       throw Standard_Failure("BRepFill_OffsetWire::FixHoles(): Wrong wire.");
1582     }
1583     gp_Pnt Pf, Pl;
1584     Pf = BRep_Tool::Pnt(Vf);
1585     Pl = BRep_Tool::Pnt(Vl);
1586     Standard_Real DistF = RealLast(), DistL = RealLast();
1587     Standard_Integer IndexF = 0, IndexL = 0;
1588     Standard_Boolean IsFirstF = Standard_False, IsFirstL = Standard_False;
1589     for (Standard_Integer i = 2; i <= UnclosedWires.Length(); i++)
1590     {
1591       TopoDS_Wire aWire = TopoDS::Wire( UnclosedWires(i) );
1592       TopoDS_Vertex V1, V2;
1593       TopExp::Vertices( aWire, V1, V2 );
1594
1595       if(V1.IsNull() || V2.IsNull())
1596       {
1597         throw Standard_Failure("BRepFill_OffsetWire::FixHoles(): Wrong wire.");
1598       }
1599
1600       gp_Pnt P1, P2;
1601       P1 = BRep_Tool::Pnt(V1);
1602       P2 = BRep_Tool::Pnt(V2);
1603       Standard_Real dist = Pf.Distance( P1 );
1604       if (dist < DistF)
1605       {
1606         DistF = dist;
1607         IndexF = i;
1608         IsFirstF = Standard_True;
1609       }
1610       dist = Pf.Distance( P2 );
1611       if (dist < DistF)
1612       {
1613         DistF = dist;
1614         IndexF = i;
1615         IsFirstF = Standard_False;
1616       }
1617       dist = Pl.Distance( P1 );
1618       if (dist < DistL)
1619       {
1620         DistL = dist;
1621         IndexL = i;
1622         IsFirstL = Standard_True;
1623       }
1624       dist = Pl.Distance( P2 );
1625       if (dist < DistL)
1626       {
1627         DistL = dist;
1628         IndexL = i;
1629         IsFirstL = Standard_False;
1630       }
1631     }
1632     if (DistF > MaxTol)
1633       IndexF = 0;
1634     if (DistL > MaxTol)
1635       IndexL = 0;
1636     TopoDS_Wire theWire;
1637     TopoDS_Edge theEdge;
1638     TopoDS_Vertex theVertex;
1639     Standard_Real CommonTol;
1640     Standard_Boolean TryToClose = Standard_True;
1641     if (DistF <= MaxTol && DistL <= MaxTol && IndexF == IndexL && IsFirstF == IsFirstL)
1642     {
1643       if (DistF < DistL)
1644       {
1645         DistL = RealLast();
1646         IndexL++;
1647       }
1648       else
1649       {
1650         DistF = RealLast();
1651         IndexF++;
1652       }
1653       TryToClose = Standard_False;
1654     }
1655     if (DistF <= MaxTol)
1656     {
1657       theWire = TopoDS::Wire( UnclosedWires(IndexF) );
1658       TopoDS_Vertex V1, V2;
1659       TopExp::Vertices( theWire, V1, V2 );
1660       TopTools_IndexedDataMapOfShapeListOfShape VEmap;
1661       TopExp::MapShapesAndAncestors( theWire, TopAbs_VERTEX, TopAbs_EDGE, VEmap );
1662       theEdge = (IsFirstF)? TopoDS::Edge(VEmap.FindFromKey( V1 ).First()) :
1663         TopoDS::Edge(VEmap.FindFromKey( V2 ).First());
1664       TopoDS_Iterator it( theWire );
1665       for (; it.More(); it.Next())
1666       {
1667         TopoDS_Edge anEdge = TopoDS::Edge( it.Value() );
1668         if (IsFirstF) anEdge.Reverse();
1669         if (!anEdge.IsSame( theEdge ))
1670           BB.Add( Base, anEdge );
1671       }
1672       theVertex = (IsFirstF)? V1 : V2;
1673       CommonTol = Max( BRep_Tool::Tolerance(Vf), BRep_Tool::Tolerance(theVertex) );
1674       if (DistF <= CommonTol)
1675       {
1676         theEdge.Free( Standard_True );
1677         Vf.Orientation( theVertex.Orientation() );
1678         BB.Remove( theEdge, theVertex );
1679         BB.Add( theEdge, Vf );
1680         BB.UpdateVertex( Vf, CommonTol );
1681         if (IsFirstF) theEdge.Reverse();
1682         BB.Add( Base, theEdge );
1683       }
1684       else
1685       {
1686         if (IsFirstF) theEdge.Reverse();
1687         BB.Add( Base, theEdge );
1688         // Creating new edge from theVertex to Vf
1689         TopoDS_Edge NewEdge = BRepLib_MakeEdge( theVertex, Vf );
1690         BB.Add( Base, NewEdge );
1691       }
1692     }
1693     if (DistL <= MaxTol && IndexL != IndexF)
1694     {
1695       theWire = TopoDS::Wire( UnclosedWires(IndexL) );
1696       TopoDS_Vertex V1, V2;
1697       TopExp::Vertices( theWire, V1, V2 );
1698       TopTools_IndexedDataMapOfShapeListOfShape VEmap;
1699       TopExp::MapShapesAndAncestors( theWire, TopAbs_VERTEX, TopAbs_EDGE, VEmap );
1700       theEdge = (IsFirstL)? TopoDS::Edge(VEmap.FindFromKey( V1 ).First()) :
1701         TopoDS::Edge(VEmap.FindFromKey( V2 ).First());
1702       TopoDS_Iterator it( theWire );
1703       for (; it.More(); it.Next())
1704       {
1705         TopoDS_Edge anEdge = TopoDS::Edge( it.Value() );
1706         if (!IsFirstL) anEdge.Reverse();
1707         if (!anEdge.IsSame( theEdge ))
1708           BB.Add( Base, anEdge );
1709       }
1710       theVertex = (IsFirstL)? V1 : V2;
1711       CommonTol = Max( BRep_Tool::Tolerance(Vl), BRep_Tool::Tolerance(theVertex) );
1712       if (DistL <= CommonTol)
1713       {
1714         theEdge.Free( Standard_True );
1715         Vl.Orientation( theVertex.Orientation() );
1716         BB.Remove( theEdge, theVertex );
1717         BB.Add( theEdge, Vl );
1718         BB.UpdateVertex( Vl, CommonTol );
1719         if (!IsFirstL) theEdge.Reverse();
1720         BB.Add( Base, theEdge );
1721       }
1722       else
1723       {
1724         if (!IsFirstL) theEdge.Reverse();
1725         BB.Add( Base, theEdge );
1726         // Creating new edge from Vl to theVertex
1727         TopoDS_Edge NewEdge = BRepLib_MakeEdge( Vl, theVertex );
1728         BB.Add( Base, NewEdge );
1729       }
1730     }
1731     // Check if it is possible to close resulting wire
1732     if (TryToClose)
1733     {
1734       TopExp::Vertices( Base, Vf, Vl );
1735       CommonTol = Max( BRep_Tool::Tolerance(Vf), BRep_Tool::Tolerance(Vl) );
1736       TopTools_IndexedDataMapOfShapeListOfShape VEmap;
1737       TopExp::MapShapesAndAncestors( Base, TopAbs_VERTEX, TopAbs_EDGE, VEmap );
1738       TopoDS_Edge Efirst, Elast;
1739       Efirst = TopoDS::Edge(VEmap.FindFromKey( Vf ).First());
1740       Elast  = TopoDS::Edge(VEmap.FindFromKey( Vl ).First());
1741       Pf = BRep_Tool::Pnt(Vf);
1742       Pl = BRep_Tool::Pnt(Vl);
1743       Standard_Real Dist = Pf.Distance(Pl);
1744       if (Dist <= CommonTol)
1745       {
1746         Elast.Free( Standard_True );
1747         Vf.Orientation( Vl.Orientation() );
1748         BB.Remove( Elast, Vl );
1749         BB.Add( Elast, Vf );
1750         BB.UpdateVertex( Vf, CommonTol );
1751         Base.Closed( Standard_True );
1752       }
1753       else if (Dist <= MaxTol)
1754       {
1755         // Creating new edge from Vl to Vf
1756         TopoDS_Edge NewEdge = BRepLib_MakeEdge( Vf, Vl );
1757         BB.Add( Base, NewEdge );
1758         Base.Closed( Standard_True );
1759       }
1760     }
1761     // Updating sequences ClosedWires and UnclosedWires
1762     if (DistF <= MaxTol)
1763       UnclosedWires.Remove( IndexF );
1764     if (DistL <= MaxTol && IndexL != IndexF)
1765     {
1766       if (DistF <= MaxTol && IndexL > IndexF)
1767         IndexL--;
1768       UnclosedWires.Remove( IndexL );
1769     }
1770     if (Base.Closed())
1771     {
1772       ClosedWires.Append( Base );
1773       UnclosedWires.Remove( 1 );
1774     }
1775     else if (DistF > MaxTol && DistL > MaxTol)
1776     {
1777       IsolatedWires.Append( Base );
1778       UnclosedWires.Remove( 1 );
1779     }
1780   }
1781
1782   // Updating myShape
1783   if (ClosedWires.Length() + IsolatedWires.Length() == 1)
1784   {
1785     if (!ClosedWires.IsEmpty())
1786       myShape = ClosedWires.First();
1787     else
1788       myShape = IsolatedWires.First();
1789   }
1790   else
1791   {
1792     TopoDS_Compound R;
1793     BB.MakeCompound( R );
1794     Standard_Integer i;
1795     for (i = 1; i <= ClosedWires.Length(); i++)
1796       BB.Add( R, ClosedWires(i) );
1797     for (i = 1; i <= IsolatedWires.Length(); i++)
1798       BB.Add( R, IsolatedWires(i) );
1799     myShape = R;
1800   }
1801 }
1802
1803 //=======================================================================
1804 //function : CutEdge
1805 //purpose  : Cut edge at the extrema of curvatures and points of inflexion.
1806 //           So, closed circles are cut in two.
1807 //           If <Cuts> is empty, the edge is not modified.
1808 //           The first and the last vertex of the initial edge 
1809 //           belong to the first and the last parts respectively.
1810 //=======================================================================
1811 Standard_Integer CutEdge (const TopoDS_Edge& E, 
1812   const TopoDS_Face& F,
1813   Standard_Integer ForceCut,
1814   TopTools_ListOfShape& Cuts)
1815 {
1816   Cuts.Clear();
1817   MAT2d_CutCurve              Cuter;
1818   TColGeom2d_SequenceOfCurve  theCurves;
1819   Standard_Real               f,l;
1820   Handle(Geom2d_Curve)        C2d;
1821   Handle(Geom2d_TrimmedCurve) CT2d;
1822   //  Modified by Sergey KHROMOV - Wed Mar  6 17:36:25 2002 Begin
1823   Standard_Real               aTol = BRep_Tool::Tolerance(E);
1824   Handle(Geom_Curve)          aC;
1825   //  Modified by Sergey KHROMOV - Wed Mar  6 17:36:25 2002 End
1826   
1827   TopoDS_Vertex V1,V2,VF,VL;
1828   TopExp::Vertices (E,V1,V2);
1829   BRep_Builder B;
1830   
1831   C2d  = BRep_Tool::CurveOnSurface (E,F,f,l);
1832   //  Modified by Sergey KHROMOV - Wed Mar  6 17:36:54 2002 Begin
1833   aC   = BRep_Tool::Curve(E,f,l);
1834   //  Modified by Sergey KHROMOV - Wed Mar  6 17:36:54 2002 End
1835   CT2d = new Geom2d_TrimmedCurve(C2d,f,l);
1836   //if (E.Orientation() == TopAbs_REVERSED) CT2d->Reverse();
1837
1838   if (CT2d->BasisCurve()->IsKind(STANDARD_TYPE(Geom2d_Circle)) &&
1839     ( Abs(f-l) >= M_PI) ) {
1840       return 0;
1841   }
1842
1843   //-------------------------
1844   // Cut curve.
1845   //-------------------------
1846   Cuter.Perform(CT2d);
1847
1848   //  Modified by Sergey KHROMOV - Thu Nov 16 17:28:29 2000 Begin
1849   if (ForceCut == 0) {
1850     if (Cuter.UnModified()) {
1851       //-----------------------------
1852       // edge not modified => return.
1853       //-----------------------------
1854       return 0;
1855     } else {
1856       for (Standard_Integer k = 1; k <= Cuter.NbCurves(); k++)
1857         theCurves.Append(Cuter.Value(k));
1858     }
1859   } else if (ForceCut == 1) {
1860     if (Cuter.UnModified()) {
1861       CutCurve (CT2d, 2, theCurves);
1862     } else {
1863       for (Standard_Integer k = 1; k <= Cuter.NbCurves(); k++)
1864
1865        theCurves.Append(Cuter.Value(k));
1866     }
1867   } else if (ForceCut == 2) {
1868     if (Cuter.UnModified()) {
1869       CutCurve (CT2d, 3, theCurves);
1870     } else {
1871       if (Cuter.NbCurves() == 2) {
1872
1873         Handle(Geom2d_TrimmedCurve)CC = Cuter.Value(1);
1874
1875         if (CC->LastParameter() > (l+f)/2.) {
1876           CutCurve (CC, 2, theCurves);
1877           theCurves.Append(Cuter.Value(2));
1878         } else {
1879           theCurves.Append(CC);
1880           CutCurve (Cuter.Value(2), 2, theCurves);
1881         }
1882       } else {
1883         for (Standard_Integer k = 1; k <= Cuter.NbCurves(); k++)
1884           theCurves.Append(Cuter.Value(k));
1885       }
1886     }
1887   }
1888
1889   //  Modified by Sergey KHROMOV - Thu Nov 16 17:28:37 2000 End
1890
1891   //--------------------------------------
1892   // Creation of cut edges.
1893   //--------------------------------------
1894   VF = V1;
1895
1896   for (Standard_Integer k = 1; k <= theCurves.Length(); k++) {
1897
1898     Handle(Geom2d_TrimmedCurve)CC = Handle(Geom2d_TrimmedCurve)::DownCast(theCurves.Value(k));
1899
1900     if (k == theCurves.Length()) {VL = V2;}
1901     else { 
1902       //  Modified by Sergey KHROMOV - Wed Mar  6 17:38:02 2002 Begin
1903       gp_Pnt        P = aC->Value(CC->LastParameter());
1904
1905       VL = BRepLib_MakeVertex(P);
1906       B.UpdateVertex(VL, aTol);
1907       //  Modified by Sergey KHROMOV - Wed Mar  6 17:38:05 2002 End
1908     }
1909     TopoDS_Shape aLocalShape = E.EmptyCopied();
1910     TopoDS_Edge NE = TopoDS::Edge(aLocalShape);
1911     //      TopoDS_Edge NE = TopoDS::Edge(E.EmptyCopied());
1912     NE.Orientation(TopAbs_FORWARD);
1913     B.Add  (NE,VF.Oriented(TopAbs_FORWARD));
1914     B.Add  (NE,VL.Oriented(TopAbs_REVERSED));      
1915     B.Range(NE,CC->FirstParameter(),CC->LastParameter());
1916     Cuts.Append(NE.Oriented(E.Orientation()));
1917     VF = VL;
1918   }
1919
1920   return theCurves.Length();
1921 }
1922
1923 //  Modified by Sergey KHROMOV - Thu Nov 16 17:27:56 2000 Begin
1924 //=======================================================================
1925 //function : CutCurve
1926 //purpose  : 
1927 //=======================================================================
1928
1929 void CutCurve (const Handle(Geom2d_TrimmedCurve)& C,
1930   const Standard_Integer nbParts,
1931   TColGeom2d_SequenceOfCurve& theCurves)
1932 {
1933   Handle(Geom2d_TrimmedCurve) TrimC;
1934   Standard_Real               UF,UL,UC;
1935   Standard_Real               Step;
1936   gp_Pnt2d                    PF,PL,PC;
1937   Standard_Real               PTol  = Precision::PConfusion()*10;
1938   Standard_Real               Tol   = Precision::Confusion()*10;
1939   Standard_Boolean            YaCut = Standard_False;
1940
1941   UF = C->FirstParameter();
1942   UL = C->LastParameter ();
1943   PF = C->Value(UF);
1944   PL = C->Value(UL);
1945
1946   Step = (UL - UF)/nbParts;
1947
1948   for (Standard_Integer i = 1; i < nbParts; i++) {
1949
1950     UC = UF + i*Step;
1951     PC = C->Value(UC);
1952
1953     if (UC - UF > PTol && PC.Distance(PF) > Tol) {
1954       if ( UL - UC < PTol || PL.Distance(PC) < Tol)
1955         continue;
1956
1957       TrimC = new Geom2d_TrimmedCurve(C,UF,UC);
1958       theCurves.Append(TrimC);
1959       UF = UC;
1960       PF = PC;
1961       YaCut = Standard_True;
1962     }
1963   }
1964   if (YaCut) {
1965     TrimC = new Geom2d_TrimmedCurve(C,UF,UL);
1966     theCurves.Append(TrimC);
1967   } else
1968     theCurves.Append(C);
1969 }
1970 //  Modified by Sergey KHROMOV - Thu Nov 16 17:28:13 2000 End
1971
1972 //=======================================================================
1973 //function : MakeCircle
1974 //purpose  : 
1975 //=======================================================================
1976
1977 void MakeCircle (const TopoDS_Edge&          E,
1978   const TopoDS_Vertex&        V,
1979   const TopoDS_Face&          F,
1980   const Standard_Real         Offset, 
1981   BRepFill_IndexedDataMapOfOrientedShapeListOfShape& Map,
1982   const Handle(Geom_Plane)&   RefPlane)
1983 {
1984   // evaluate the Axis of the Circle.
1985   Standard_Real f,l;
1986   Handle(Geom2d_Curve) GC = BRep_Tool::CurveOnSurface(E,F,f,l);
1987   gp_Vec2d DX;
1988   gp_Pnt2d P;
1989
1990   if (E.Orientation() == TopAbs_FORWARD) {
1991     GC->D1(l,P,DX);
1992     DX.Reverse();
1993   }
1994   else GC->D1(f,P,DX);
1995
1996   gp_Ax2d Axis(P,gp_Dir2d(DX));
1997   Handle(Geom2d_Circle) Circ 
1998     = new  Geom2d_Circle(Axis, Abs(Offset), Offset < 0.);
1999
2000   // Bind the edges in my Map.
2001   TopoDS_Edge OE = BRepLib_MakeEdge(Circ, RefPlane);
2002   TopTools_ListOfShape LL;
2003
2004   LL.Append(OE);
2005   Map.Add(V,LL);
2006
2007 #ifdef OCCT_DEBUG
2008 #ifdef DRAW
2009   if ( AffichGeom && !OE.IsNull()) {
2010     char name[256];
2011     sprintf(name,"OFFSET_%d",++NbOFFSET);
2012     DBRep::Set(name,OE);
2013   }
2014 #endif
2015 #endif
2016 }
2017
2018 //=======================================================================
2019 //function : MakeOffset
2020 //purpose  : 
2021 //=======================================================================
2022
2023 void MakeOffset (const TopoDS_Edge&        E, 
2024   const TopoDS_Face&        F,
2025   const Standard_Real       Offset, 
2026   BRepFill_IndexedDataMapOfOrientedShapeListOfShape& Map,
2027   const Handle(Geom_Plane)& RefPlane,
2028   const Standard_Boolean    IsOpenResult,
2029                  const GeomAbs_JoinType    theJoinType,
2030   const TopoDS_Vertex *     Ends)
2031 {
2032   Standard_Real f,l;
2033   Standard_Real anOffset = Offset;
2034
2035   if (E.Orientation() == TopAbs_REVERSED) anOffset *= -1;
2036
2037   Handle(Geom2d_Curve) G2d = BRep_Tool::CurveOnSurface(E,F,f,l);
2038   Handle(Geom2d_Curve) G2dOC;
2039
2040   Standard_Boolean ToExtendFirstPar = Standard_True;
2041   Standard_Boolean ToExtendLastPar  = Standard_True;
2042   if (IsOpenResult)
2043   {
2044     TopoDS_Vertex V1, V2;
2045     TopExp::Vertices(E, V1, V2);
2046     if (V1.IsSame(Ends[0]) ||
2047       V1.IsSame(Ends[1]))
2048       ToExtendFirstPar = Standard_False;
2049     if (V2.IsSame(Ends[0]) ||
2050       V2.IsSame(Ends[1]))
2051       ToExtendLastPar  = Standard_False;
2052   }
2053
2054   Geom2dAdaptor_Curve  AC(G2d,f,l);
2055   if ( AC.GetType() == GeomAbs_Circle) {
2056     // if the offset is greater otr equal to the radius and the side of the  
2057     // concavity of the circle => edge null.
2058     gp_Circ2d C1(AC.Circle());
2059     gp_Ax22d axes( C1.Axis());
2060     gp_Dir2d Xd = axes.XDirection();
2061     gp_Dir2d Yd = axes.YDirection();
2062     Standard_Real Crossed = Xd.X()*Yd.Y()-Xd.Y()*Yd.X();
2063     Standard_Real Signe = ( Crossed > 0.) ? 1. : -1.;
2064
2065     if (anOffset*Signe < AC.Circle().Radius() - Precision::Confusion()) {
2066
2067       Handle(Geom2dAdaptor_HCurve) AHC = 
2068         new Geom2dAdaptor_HCurve(G2d);
2069       Adaptor2d_OffsetCurve   Off(AHC,-anOffset);
2070       Handle(Geom2d_Circle) CC = new Geom2d_Circle(Off.Circle());      
2071
2072       Standard_Real Delta = 2*M_PI - l + f;
2073       if (theJoinType == GeomAbs_Arc)
2074       {
2075       if (ToExtendFirstPar)
2076         f -= 0.2*Delta;
2077       if (ToExtendLastPar)
2078         l += 0.2*Delta;
2079       }
2080       else //GeomAbs_Intersection
2081       {
2082         if (ToExtendFirstPar && ToExtendLastPar)
2083         {
2084           Standard_Real old_l = l;
2085           f = old_l + Delta/2.;
2086           l = f + 2*M_PI;
2087         }
2088         else if (ToExtendFirstPar)
2089         {
2090           f = l;
2091           l = f + 2*M_PI;
2092         }
2093         else if (ToExtendLastPar)
2094         {
2095           l = f + 2*M_PI;
2096         }
2097       }
2098       G2dOC = new Geom2d_TrimmedCurve(CC,f,l);
2099     }
2100   }
2101   else if (AC.GetType() == GeomAbs_Line) {
2102     Handle(Geom2dAdaptor_HCurve) AHC = 
2103       new Geom2dAdaptor_HCurve(G2d);
2104     Adaptor2d_OffsetCurve Off(AHC,anOffset);
2105     Handle(Geom2d_Line)       CC = new Geom2d_Line(Off.Line());
2106     Standard_Real Delta = (l - f);
2107     if (ToExtendFirstPar)
2108     {
2109       if (theJoinType == GeomAbs_Arc)
2110       f -= Delta;
2111       else //GeomAbs_Intersection
2112         f = -Precision::Infinite();
2113     }
2114     if (ToExtendLastPar)
2115     {
2116       if (theJoinType == GeomAbs_Arc)
2117       l += Delta;
2118       else //GeomAbs_Intersection
2119         l = Precision::Infinite();
2120     }
2121     G2dOC = new Geom2d_TrimmedCurve(CC,f,l);
2122   }
2123   else {
2124
2125     anOffset = -anOffset;
2126     Handle(Geom2d_TrimmedCurve) G2dT = new Geom2d_TrimmedCurve(G2d,f,l);
2127     G2dOC = new Geom2d_OffsetCurve( G2dT, anOffset);
2128
2129   }
2130
2131   // Bind the edges in my Map.
2132   if (!G2dOC.IsNull()) {
2133     TopoDS_Edge OE = BRepLib_MakeEdge(G2dOC, RefPlane);
2134     OE.Orientation(E.Orientation());
2135     TopTools_ListOfShape LL;
2136     LL.Append(OE);
2137     Map.Add(E,LL);
2138
2139 #ifdef OCCT_DEBUG
2140 #ifdef DRAW  
2141     if (AffichGeom && !OE.IsNull()) {
2142       char name[256];
2143       sprintf(name,"OFFSET_%d",++NbOFFSET);
2144       DBRep::Set(name,OE);
2145       //Standard_Real ii = 0;
2146     }
2147 #endif
2148 #endif
2149
2150   }
2151 }  
2152
2153
2154 //=======================================================================
2155 //function : VertexFromNode
2156 //purpose  : 
2157 //=======================================================================
2158
2159 Standard_Boolean VertexFromNode (const Handle(MAT_Node)&      aNode, 
2160   const Standard_Real          Offset,
2161   gp_Pnt2d&                   PN,
2162   BRepFill_DataMapOfNodeShape& MapNodeVertex,
2163   TopoDS_Vertex&               VN)
2164 {  
2165   Standard_Boolean Status;
2166   Standard_Real    Tol = Precision::Confusion();
2167   BRep_Builder     B;
2168
2169   if (!aNode->Infinite() && Abs(aNode->Distance()-Offset) < Tol) {
2170     //------------------------------------------------
2171     // the Node gives a vertex on the offset
2172     //------------------------------------------------
2173     if (MapNodeVertex.IsBound(aNode)) {
2174       VN = TopoDS::Vertex(MapNodeVertex(aNode));
2175     }
2176     else { 
2177       gp_Pnt P(PN.X(),PN.Y(),0.);
2178       B.MakeVertex (VN);
2179       B.UpdateVertex(VN,P, Precision::Confusion());
2180       MapNodeVertex.Bind(aNode,VN);
2181     }
2182     Status = Standard_True;
2183   }
2184   else Status = Standard_False;
2185
2186   return Status;
2187 }
2188
2189
2190 //=======================================================================
2191 //function : StoreInMap
2192 //purpose  : 
2193 //=======================================================================
2194
2195 void StoreInMap (const TopoDS_Shape& V1,
2196   const TopoDS_Shape& V2,
2197   TopTools_IndexedDataMapOfShapeShape& MapVV)
2198 {
2199   TopoDS_Shape OldV = V1, NewV = V2;
2200   Standard_Integer i;
2201
2202   if (MapVV.Contains(V2))
2203     NewV = MapVV.FindFromKey(V2);
2204
2205   if (MapVV.Contains(V1))
2206     MapVV.ChangeFromKey(V1) = NewV;
2207
2208   for (i = 1; i <= MapVV.Extent(); i++)
2209     if (MapVV(i).IsSame(V1))
2210       MapVV(i) = NewV;
2211
2212   MapVV.Add(V1, NewV);
2213 }
2214
2215 //=======================================================================
2216 //function : TrimEdge
2217 //purpose  : 
2218 //=======================================================================
2219
2220 void TrimEdge (const TopoDS_Edge&              E,
2221                const TopoDS_Shape&             ProE,
2222                const TopoDS_Face&              AllSpine,
2223                const TopTools_ListOfShape&     Detromp,
2224                TopTools_SequenceOfShape& TheVer,
2225                TColStd_SequenceOfReal&   ThePar,
2226                TopTools_SequenceOfShape& S,
2227                TopTools_IndexedDataMapOfShapeShape& MapVV,
2228                const Standard_Integer IndOfE)
2229 {
2230   Standard_Boolean         Change = Standard_True;
2231   BRep_Builder             TheBuilder;
2232   S.Clear();
2233
2234   //-----------------------------------------------------------
2235   // Parse two sequences depending on the parameter on the edge.
2236   //-----------------------------------------------------------
2237   while (Change) {
2238     Change = Standard_False;
2239     for (Standard_Integer i = 1; i < ThePar.Length(); i++) {
2240       if (ThePar.Value(i) > ThePar.Value(i+1)) {
2241         ThePar.Exchange(i,i+1);
2242         TheVer.Exchange(i,i+1);
2243         Change = Standard_True;
2244       }
2245     }
2246   }
2247
2248   //----------------------------------------------------------
2249   // If a vertex is not in the proofing, it is eliminated.
2250   //----------------------------------------------------------
2251   if (!BRep_Tool::Degenerated(E)) {
2252     for (Standard_Integer k = 1; k <= TheVer.Length(); k ++) {
2253       if ( DoubleOrNotInside (Detromp,
2254         TopoDS::Vertex(TheVer.Value(k)))) {
2255           TheVer.Remove(k);
2256           ThePar.Remove(k);
2257           k--;
2258       }
2259     }
2260   }
2261
2262   //----------------------------------------------------------
2263   // If a vertex_double appears twice in the proofing 
2264   // the vertex is removed.
2265   // otherwise preserve only one of its representations.
2266   //----------------------------------------------------------
2267   if (!BRep_Tool::Degenerated(E)) {
2268     Standard_Real aParTol = 2.0 * Precision::PConfusion();
2269     for (Standard_Integer k = 1; k < TheVer.Length(); k ++) {
2270       if (TheVer.Value(k).IsSame(TheVer.Value(k+1)) || 
2271           Abs(ThePar.Value(k)-ThePar.Value(k+1)) <= aParTol) {
2272
2273           if(k+1 == TheVer.Length()) {
2274             StoreInMap(TheVer(k), TheVer(k+1), MapVV);
2275             TheVer.Remove(k);
2276             ThePar.Remove(k);
2277           }
2278           else {
2279             StoreInMap(TheVer(k+1), TheVer(k), MapVV);
2280             TheVer.Remove(k+1);
2281             ThePar.Remove(k+1);
2282           }
2283           /*
2284           if ( DoubleOrNotInside (Detromp,
2285           TopoDS::Vertex(TheVer.Value(k)))) {
2286           TheVer.Remove(k);
2287           ThePar.Remove(k);
2288           k--;
2289           }
2290           */
2291           k--;
2292       }
2293     }
2294   }
2295   //-----------------------------------------------------------
2296   // Creation of edges.
2297   // the number of vertices should be even. The created edges  
2298   // go from a vertex with uneven index i to vertex i+1;
2299   //-----------------------------------------------------------
2300   if (IndOfE == 1 || IndOfE == -1) //open result and extreme edges of result
2301   {
2302     TopoDS_Shape aLocalShape = E.EmptyCopied();
2303     TopoDS_Edge NewEdge = TopoDS::Edge(aLocalShape);
2304     TopoDS_Vertex V1, V2;
2305     TopExp::Vertices(E, V1, V2);
2306     Standard_Real fpar, lpar;
2307     Handle(Geom_Surface) aPlane;
2308     TopLoc_Location aLoc;
2309     Handle(Geom2d_Curve) PCurve;
2310     BRep_Tool::CurveOnSurface(E, PCurve, aPlane, aLoc, fpar, lpar);
2311     //BRep_Tool::Range(E, fpar, lpar);
2312
2313     Standard_Real TrPar1, TrPar2;
2314     Standard_Boolean ToTrimAsOrigin = IsInnerEdge(ProE, AllSpine, TrPar1, TrPar2);
2315     
2316     if (IndOfE == 1) //first edge of open wire
2317     {
2318       if (NewEdge.Orientation() == TopAbs_FORWARD)
2319       {
2320         if (ToTrimAsOrigin)
2321         {
2322           fpar = TrPar1;
2323           gp_Pnt2d TrPnt2d = PCurve->Value(fpar);
2324           gp_Pnt TrPnt(TrPnt2d.X(), TrPnt2d.Y(), 0.);
2325           V1 = BRepLib_MakeVertex(TrPnt);
2326         }
2327         TheBuilder.Add(NewEdge, V1.Oriented(TopAbs_FORWARD));
2328         TheBuilder.Add(NewEdge, TheVer.First().Oriented(TopAbs_REVERSED));
2329         TheBuilder.Range(NewEdge, fpar, ThePar.First());
2330       }
2331       else
2332       {
2333         if (ToTrimAsOrigin)
2334         {
2335           lpar = TrPar2;
2336           gp_Pnt2d TrPnt2d = PCurve->Value(lpar);
2337           gp_Pnt TrPnt(TrPnt2d.X(), TrPnt2d.Y(), 0.);
2338           V2 = BRepLib_MakeVertex(TrPnt);
2339         }
2340         TheBuilder.Add(NewEdge, TheVer.First().Oriented(TopAbs_REVERSED));
2341         TheBuilder.Add(NewEdge, V2.Oriented(TopAbs_FORWARD));
2342         TheBuilder.Range(NewEdge, ThePar.First(), lpar);
2343       }
2344     }
2345     else //last edge of open wire
2346     {
2347       if (NewEdge.Orientation() == TopAbs_FORWARD)
2348       {
2349         if (ToTrimAsOrigin)
2350         {
2351           lpar = TrPar2;
2352           gp_Pnt2d TrPnt2d = PCurve->Value(lpar);
2353           gp_Pnt TrPnt(TrPnt2d.X(), TrPnt2d.Y(), 0.);
2354           V2 = BRepLib_MakeVertex(TrPnt);
2355         }
2356         TheBuilder.Add(NewEdge, TheVer.First().Oriented(TopAbs_FORWARD));
2357         TheBuilder.Add(NewEdge, V2.Oriented(TopAbs_REVERSED));
2358         TheBuilder.Range(NewEdge, ThePar.First(), lpar);
2359       }
2360       else
2361       {
2362         if (ToTrimAsOrigin)
2363         {
2364           fpar = TrPar1;
2365           gp_Pnt2d TrPnt2d = PCurve->Value(fpar);
2366           gp_Pnt TrPnt(TrPnt2d.X(), TrPnt2d.Y(), 0.);
2367           V1 = BRepLib_MakeVertex(TrPnt);
2368         }
2369         TheBuilder.Add(NewEdge, V1.Oriented(TopAbs_REVERSED));
2370         TheBuilder.Add(NewEdge, TheVer.First().Oriented(TopAbs_FORWARD));
2371         TheBuilder.Range(NewEdge, fpar, ThePar.First());
2372       }
2373     }
2374     S.Append(NewEdge);
2375   }
2376   else
2377   {
2378     for (Standard_Integer k = 1; k < TheVer.Length(); k = k+2) {
2379       TopoDS_Shape aLocalShape = E.EmptyCopied();
2380       TopoDS_Edge NewEdge = TopoDS::Edge(aLocalShape);
2381       //    TopoDS_Edge NewEdge = TopoDS::Edge(E.EmptyCopied());
2382       
2383       if (NewEdge.Orientation() == TopAbs_REVERSED) {
2384         TheBuilder.Add  (NewEdge,TheVer.Value(k)  .Oriented(TopAbs_REVERSED));
2385         TheBuilder.Add  (NewEdge,TheVer.Value(k+1).Oriented(TopAbs_FORWARD));
2386       }
2387       else {      
2388         TheBuilder.Add  (NewEdge,TheVer.Value(k)  .Oriented(TopAbs_FORWARD));
2389         TheBuilder.Add  (NewEdge,TheVer.Value(k+1).Oriented(TopAbs_REVERSED));
2390       }
2391       
2392       
2393       TheBuilder.Range(NewEdge,ThePar.Value(k),ThePar.Value(k+1));
2394       
2395 #ifdef OCCT_DEBUG
2396 #ifdef DRAW
2397       if ( AffichEdge) {
2398         char name[256];
2399         sprintf(name,"TRIMEDGE_%d",NbTRIMEDGES);
2400         DBRep::Set(name,NewEdge);  
2401       }
2402       if (Affich2d) {
2403         TopLoc_Location L;
2404         Standard_Real f,l;
2405         Handle(Geom_Surface) Surf;  
2406         Handle(Geom2d_Curve) C;
2407         BRep_Tool::CurveOnSurface(NewEdge,C,Surf,L,f,l);
2408         char name[256];
2409         sprintf(name,"OFFSET2d_%d",NbTRIMEDGES++);
2410         Handle(Geom2d_TrimmedCurve) C2d = new Geom2d_TrimmedCurve(C,f,l);
2411         Handle(DrawTrSurf_Curve2d) dr =
2412           new DrawTrSurf_Curve2d(C2d,Standard_False);
2413         dr->SetColor(Draw_bleu);
2414         Draw::Set(name,dr);
2415       }
2416 #endif
2417 #endif
2418       S.Append(NewEdge);
2419     }
2420   }
2421 }
2422
2423 //=======================================================================
2424 //function : IsInnerEdge
2425 //purpose  :
2426 //=======================================================================
2427
2428 static Standard_Boolean IsInnerEdge(const TopoDS_Shape& ProE,
2429                                     const TopoDS_Face&  AllSpine,
2430                                     Standard_Real& TrPar1,
2431                                     Standard_Real& TrPar2)
2432 {
2433   if (ProE.ShapeType() != TopAbs_EDGE)
2434     return Standard_False;
2435
2436   TopoDS_Edge anEdge = TopoDS::Edge(ProE);
2437
2438   TopTools_IndexedDataMapOfShapeListOfShape VEmap;
2439   TopExp::MapShapesAndAncestors(AllSpine, TopAbs_VERTEX, TopAbs_EDGE, VEmap);
2440   for (Standard_Integer i = 1; i <= VEmap.Extent(); i++)
2441   {
2442     const TopTools_ListOfShape& LE = VEmap(i);
2443     if (LE.Extent() == 1 && anEdge.IsSame(LE.First()))
2444       return Standard_False;
2445   }
2446
2447   BRep_Tool::Range(anEdge, TrPar1, TrPar2);
2448   return Standard_True;
2449 }
2450
2451
2452
2453 //=======================================================================
2454 //function : DoubleOrNotInside
2455 //purpose  : return True if V appears twice in LV or is not inside.
2456 //=======================================================================
2457
2458 Standard_Boolean DoubleOrNotInside (const TopTools_ListOfShape& LV,
2459   const TopoDS_Vertex&        V)
2460 {  
2461   Standard_Boolean Vu = Standard_False;
2462   TopTools_ListIteratorOfListOfShape it(LV);
2463
2464   for ( ; it.More(); it.Next()) {
2465     if (V.IsSame(it.Value())) {
2466       if  (Vu) return Standard_True;
2467       else       Vu = Standard_True;
2468     }
2469   }
2470   if (Vu) return Standard_False;
2471   else    return Standard_True;   
2472 }
2473
2474 Standard_Boolean IsSmallClosedEdge(const TopoDS_Edge& anEdge,
2475   const TopoDS_Vertex& aVertex)
2476 {
2477   gp_Pnt PV = BRep_Tool::Pnt(aVertex);
2478   gp_Pnt2d PV2d, Pfirst, Plast, Pmid;
2479   PV2d.SetCoord( PV.X(), PV.Y() );
2480
2481   Handle(Geom2d_Curve) PCurve;
2482   Handle( BRep_CurveRepresentation ) CurveRep =
2483     ((Handle(BRep_TEdge)::DownCast(anEdge.TShape()))->Curves()).First();
2484   PCurve = CurveRep->PCurve();
2485
2486   Standard_Real fpar = (Handle(BRep_GCurve)::DownCast(CurveRep))->First();
2487   Standard_Real lpar = (Handle(BRep_GCurve)::DownCast(CurveRep))->Last();
2488   Pfirst = PCurve->Value(fpar);
2489   Plast  = PCurve->Value(lpar);
2490   Pmid   = PCurve->Value((fpar + lpar)*0.5);
2491
2492   Standard_Real theTol = BRep_Tool::Tolerance(aVertex);
2493   theTol *= 1.5;
2494
2495   Standard_Real dist1 = Pfirst.Distance(PV2d);
2496   Standard_Real dist2 = Plast.Distance(PV2d);
2497   Standard_Real dist3 = Pmid.Distance(PV2d);
2498
2499   if (dist1 <= theTol && dist2 <= theTol && dist3 <= theTol)
2500     return Standard_True;
2501
2502   return Standard_False;
2503 }
2504
2505 static void CheckBadEdges(const TopoDS_Face& Spine, const Standard_Real Offset,
2506   const BRepMAT2d_BisectingLocus& Locus, 
2507   const BRepMAT2d_LinkTopoBilo&   Link,
2508   TopTools_ListOfShape& BadEdges)
2509 {
2510
2511   TopoDS_Face F = TopoDS::Face(Spine.Oriented(TopAbs_FORWARD));
2512   Standard_Real eps = Precision::Confusion(); 
2513   Standard_Real LimCurv = 1./Offset;
2514
2515   TopTools_MapOfShape aMap;
2516
2517   for (Standard_Integer ic = 1; ic <= Locus.NumberOfContours(); ic++) {
2518     for (Standard_Integer ie = 1; ie <= Locus.NumberOfElts(ic); ie++) {
2519       const TopoDS_Shape& SE = Link.GeneratingShape(Locus.BasicElt(ic,ie));
2520       if (SE.ShapeType() == TopAbs_EDGE) {
2521
2522
2523         if (aMap.Contains(SE)) {
2524           //cout << "Edge is treated second time" << endl;
2525           continue;
2526         }
2527
2528
2529         TopoDS_Edge E = TopoDS::Edge(SE);
2530
2531
2532         Standard_Real f,l;
2533
2534
2535         Handle(Geom2d_Curve) G2d = BRep_Tool::CurveOnSurface(E,F,f,l);
2536
2537
2538         Geom2dAdaptor_Curve  AC(G2d,f,l);
2539         GeomAbs_CurveType aCType = AC.GetType();
2540
2541
2542         if(aCType != GeomAbs_Line && aCType != GeomAbs_Circle) {
2543
2544
2545           Standard_Boolean reverse = Standard_False;
2546           if (E.Orientation() == TopAbs_FORWARD) reverse = Standard_True;
2547
2548
2549           gp_Pnt2d P, Pc;
2550           gp_Dir2d N;
2551
2552
2553           Geom2dLProp_CLProps2d aCLProps(G2d, 2, eps);
2554
2555
2556           aCLProps.SetParameter(f);
2557           if(!aCLProps.IsTangentDefined()) {
2558             BadEdges.Append(SE);
2559             aMap.Add(SE);
2560             continue;
2561           }
2562
2563
2564           P = aCLProps.Value();
2565           Standard_Real Crv = aCLProps.Curvature();
2566
2567
2568           if(Crv >= eps) {
2569             aCLProps.Tangent(N);
2570             Standard_Real x = N.Y(), y = -N.X();
2571             N.SetCoord(x, y);
2572             if (reverse) N.Reverse();
2573             aCLProps.CentreOfCurvature(Pc);
2574             gp_Vec2d Dir( P, Pc );
2575             if (N.Dot(Dir) > 0.) {
2576               if (LimCurv <= Crv + eps) {
2577                 BadEdges.Append(SE);
2578                 aMap.Add(SE);
2579                 continue;
2580               }
2581             }
2582           }  
2583
2584
2585           aCLProps.SetParameter(l);
2586           if(!aCLProps.IsTangentDefined()) {
2587             BadEdges.Append(SE);
2588             aMap.Add(SE);
2589             continue;
2590           }
2591
2592
2593           P = aCLProps.Value();
2594           Crv = aCLProps.Curvature();
2595
2596
2597           if(Crv >= eps) {
2598             aCLProps.Tangent(N);
2599             Standard_Real x = N.Y(), y = -N.X();
2600             N.SetCoord(x, y);
2601             if (reverse) N.Reverse();
2602             aCLProps.CentreOfCurvature(Pc);
2603             gp_Vec2d Dir( P, Pc );
2604             if (N.Dot(Dir) > 0.) {
2605               if (LimCurv <= Crv + eps) {
2606                 BadEdges.Append(SE);
2607                 aMap.Add(SE);
2608                 continue;
2609               }
2610             }
2611           }  
2612         }
2613       }
2614     }
2615   }
2616 }
2617
2618
2619 //=======================================================================
2620 //function : PerformCurve
2621 //purpose  : 
2622 //=======================================================================
2623
2624 static Standard_Boolean PerformCurve (TColStd_SequenceOfReal& Parameters,
2625
2626   TColgp_SequenceOfPnt&   Points,
2627   const Adaptor3d_Curve& C, 
2628   const Standard_Real Deflection,
2629   const Standard_Real U1,
2630   const Standard_Real U2,
2631   const Standard_Real EPSILON,
2632   const Standard_Integer Nbmin)
2633 {
2634   Standard_Real UU1 = Min(U1, U2);
2635   Standard_Real UU2 = Max(U1, U2);
2636
2637   gp_Pnt Pdeb, Pfin;
2638   gp_Vec Ddeb,Dfin;
2639   C.D1(UU1,Pdeb,Ddeb);
2640   Parameters.Append(UU1);
2641   Points.Append(Pdeb);
2642
2643   C.D1(UU2,Pfin,Dfin);
2644
2645   const Standard_Real aDelta = UU2 - UU1;
2646   const Standard_Real aDist = Pdeb.Distance(Pfin);
2647
2648   if((aDelta/aDist) > 5.0e-14)
2649   {
2650     QuasiFleche(C,Deflection*Deflection,
2651
2652       UU1,Pdeb,
2653       Ddeb,
2654       UU2,Pfin,
2655       Dfin,
2656       Nbmin,
2657       EPSILON*EPSILON,
2658       Parameters,Points);
2659   }
2660
2661   return Standard_True;
2662 }
2663 //=======================================================================
2664 //function : QuasiFleche
2665 //purpose  : 
2666 //=======================================================================
2667
2668 static void QuasiFleche(const Adaptor3d_Curve& C,
2669
2670   const Standard_Real Deflection2, 
2671   const Standard_Real Udeb,
2672   const gp_Pnt& Pdeb,
2673   const gp_Vec& Vdeb,
2674   const Standard_Real Ufin,
2675   const gp_Pnt& Pfin,
2676   const gp_Vec& Vfin,
2677   const Standard_Integer Nbmin,
2678   const Standard_Real Eps,
2679   TColStd_SequenceOfReal& Parameters,
2680   TColgp_SequenceOfPnt& Points)
2681 {
2682   Standard_Integer Ptslength = Points.Length();
2683   Standard_Real Udelta = Ufin-Udeb;
2684   gp_Pnt Pdelta;
2685   gp_Vec Vdelta;
2686   if (Nbmin > 2) {
2687     Udelta /=(Nbmin-1);
2688     C.D1(Udeb+Udelta,Pdelta,Vdelta);
2689   }
2690   else {
2691     Pdelta = Pfin;
2692     Vdelta = Vfin;
2693   }
2694
2695
2696   Standard_Real Norme = gp_Vec(Pdeb,Pdelta).SquareMagnitude();
2697   Standard_Real theFleche=0;
2698   Standard_Boolean flecheok = Standard_False;
2699   if (Norme > Eps) { 
2700     // Evaluation of the arrow by interpolation. See IntWalk_IWalking_5.gxx
2701     Standard_Real N1 = Vdeb.SquareMagnitude();
2702     Standard_Real N2 = Vdelta.SquareMagnitude();
2703     if (N1 > Eps && N2 > Eps) {
2704       Standard_Real Normediff = 
2705
2706         (Vdeb.Normalized().XYZ()-Vdelta.Normalized().XYZ()).SquareModulus();
2707       if (Normediff > Eps) {
2708
2709         theFleche = Normediff*Norme/64.;
2710         flecheok = Standard_True;
2711       }
2712     }
2713   }
2714   if (!flecheok) {
2715     gp_Pnt Pmid((Pdeb.XYZ()+Pdelta.XYZ())/2.);
2716     gp_Pnt Pverif(C.Value(Udeb+Udelta/2.));
2717     theFleche = Pmid.SquareDistance(Pverif);
2718   }
2719
2720   if (theFleche < Deflection2) {
2721     Parameters.Append(Udeb+Udelta);
2722     Points.Append(Pdelta);
2723   }
2724   else {
2725     QuasiFleche(C,Deflection2,Udeb,Pdeb,
2726
2727       Vdeb,
2728       Udeb+Udelta,Pdelta,
2729       Vdelta,
2730       3,
2731       Eps,
2732       Parameters,Points);
2733
2734   }
2735
2736   if (Nbmin > 2) {
2737     QuasiFleche(C,Deflection2,Udeb+Udelta,Pdelta,
2738
2739       Vdelta,
2740       Ufin,Pfin,
2741       Vfin,
2742       Nbmin-(Points.Length()-Ptslength),
2743       Eps,
2744       Parameters,Points);
2745   }
2746 }
2747
2748 Standard_Boolean CheckSmallParamOnEdge(const TopoDS_Edge& anEdge)
2749 {  
2750   const BRep_ListOfCurveRepresentation& aList = ((Handle(BRep_TEdge)::DownCast(anEdge.TShape()))->Curves());
2751   if (!aList.IsEmpty())
2752   {
2753     Handle( BRep_CurveRepresentation ) CRep = ((Handle(BRep_TEdge)::DownCast(anEdge.TShape()))->Curves()).First();
2754     Standard_Real f = (Handle(BRep_GCurve)::DownCast(CRep))->First();
2755     Standard_Real l = (Handle(BRep_GCurve)::DownCast(CRep))->Last();
2756     if (Abs (l - f) < Precision::PConfusion())
2757       return Standard_False;
2758   }
2759   return Standard_True;
2760 }
2761
2762