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