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