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