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