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