summaryrefslogtreecommitdiff
path: root/src/Poly/Poly_MakeLoops.cxx
blob: 44c379df681f80d94d35784af5139cbae3e4645b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
// File:        Poly_MakeLoops.cxx
// Created:     22.10.2009
// Author:      Mikhail SAZONOV
// Copyright:   Open Cascade 2009

#include <Poly_MakeLoops.hxx>
#include <NCollection_IncAllocator.hxx>
#include <NCollection_DataMap.hxx>
#include <gp_Dir.hxx>
#include <gp_Dir2d.hxx>

#ifdef _DEBUG
static Standard_Integer doDebug = 0;
#endif

//=======================================================================
//function : Poly_MakeLoops
//purpose  : 
//=======================================================================

Poly_MakeLoops::Poly_MakeLoops(const Helper* theHelper,
                                     const Handle_NCollection_BaseAllocator& theAlloc)
: myHelper (theHelper),
  myAlloc (theAlloc),
  myMapLink (4000, myAlloc),
  myLoops (myAlloc),
  myStartIndices (4000)
{
}

//=======================================================================
//function : Reset
//purpose  : 
//=======================================================================

void Poly_MakeLoops::Reset
                   (const Helper* theHelper,
                    const Handle_NCollection_BaseAllocator& theAlloc)
{
  myHelper = theHelper;
  myMapLink.Clear();
  myLoops.Clear(theAlloc);
  myStartIndices.Clear();
  myAlloc = theAlloc;
}

//=======================================================================
//function : AddLink
//purpose  : 
//=======================================================================

void Poly_MakeLoops::AddLink(const Link& theLink)
{
  if (theLink.node1 == theLink.node2)
    return;
  Standard_Integer aInd = myMapLink.Add(theLink);
  Link& aLink = const_cast<Link&>(myMapLink(aInd));
  aLink.flags |= theLink.flags;
#ifdef _DEBUG
  myHelper->OnAddLink (aInd, aLink);
#endif
}

//=======================================================================
//function : ReplaceLink
//purpose  : 
//=======================================================================

void Poly_MakeLoops::ReplaceLink(const Link& theLink, const Link& theNewLink)
{
  if (theNewLink.node1 == theNewLink.node2)
    return;
  Standard_Integer aInd = myMapLink.Add(theLink);
  if (aInd > 0)
  {
    Link aLink;
    // replace with a null link first (workaround exception)
    myMapLink.Substitute(aInd, aLink);
    aLink = theNewLink;
    // and now put there the final value of link
    myMapLink.Substitute(aInd, aLink);
#ifdef _DEBUG
    myHelper->OnAddLink (aInd, aLink);
#endif
  }
}

//=======================================================================
//function : SetLinkOrientation
//purpose  : 
//=======================================================================

Poly_MakeLoops::LinkFlag Poly_MakeLoops::SetLinkOrientation
                   (const Link& theLink,
                    const LinkFlag theOrient)
{
  Standard_Integer aInd = myMapLink.FindIndex(theLink);
  LinkFlag aOri = LF_None;
  if (aInd > 0)
  {
    Link& aLink = const_cast<Link&>(myMapLink(aInd));
    aOri = (LinkFlag) (aLink.flags & LF_Both);
    aLink.flags = theOrient;
#ifdef _DEBUG
    myHelper->OnAddLink (aInd, aLink);
#endif
  }
  return aOri;
}

//=======================================================================
//function : FindLink
//purpose  : 
//=======================================================================

Poly_MakeLoops::Link Poly_MakeLoops::FindLink(const Link& theLink) const
{
  Standard_Integer aInd = myMapLink.FindIndex(theLink);
  Poly_MakeLoops::Link aLink;
  if (aInd > 0)
    aLink = myMapLink(aInd);
  return aLink;
}

//=======================================================================
//function : Perform
//purpose  : 
//=======================================================================

Standard_Integer Poly_MakeLoops::Perform()
{
  // prepare the set of start indices
  myStartIndices.Clear();
  Standard_Integer i;
  for (i = 1; i <= myMapLink.Extent(); i++)
  {
    const Link& aLink = myMapLink(i);
    if (aLink.flags & LF_Fwd)
      myStartIndices.Add(i);
    if (aLink.flags & LF_Rev)
      myStartIndices.Add(-i);
  }

#ifdef _DEBUG
  if (doDebug)
    showBoundaryBreaks();
#endif

  Standard_Integer aResult = 0;

  Handle(NCollection_IncAllocator) aTempAlloc = new NCollection_IncAllocator(4000);
  Handle(NCollection_IncAllocator) aTempAlloc1 = new NCollection_IncAllocator(4000);

  // two pass loop
  Standard_Integer aPassNum, nbLoopsOnPass2 = 0;
  for (aPassNum=0; aPassNum < 2; aPassNum++)
  {
    myHangIndices.Clear();
    // main loop
    while (!myStartIndices.IsEmpty())
    {
      Standard_Integer aIndexS = myStartIndices.Top();

      aTempAlloc->Reset();
      NCollection_IndexedMap<Standard_Integer> aContour (100, aTempAlloc);
      Standard_Integer aStartNumber = findContour (aIndexS, aContour, aTempAlloc, aTempAlloc1);
#ifdef _DEBUG
      if (aStartNumber > 1)
        if (doDebug)
        {
          cout << "--- found contour with hanging links:" << endl;
          for (i = 1; i <= aContour.Extent(); i++)
            cout << " " << aContour(i);
          cout << endl;
        }
#endif
      if (aStartNumber == 0)
      {      // error
        aResult |= RC_Failure;
        return aResult;
      }
      if (aStartNumber <= aContour.Extent())
      {
        // there is a closed loop in the contour
        if (aPassNum == 1)
          nbLoopsOnPass2++;
        acceptContour (aContour, aStartNumber);
      }
      if (aStartNumber > 1)
      {
        // it is required to mark hanging edges
        Standard_Integer aNode;
        if (aStartNumber <= aContour.Extent())
          // mark hanging edges starting from the first one till a bifurcation
          aNode = getFirstNode(aIndexS);
        else
        {
          // open contour - mark from the end back till a bifurcation
          aIndexS = aContour(aStartNumber - 1);
          aNode = getLastNode(aIndexS);
        }
        markHangChain(aNode, aIndexS);
      }
    }

    if (aPassNum == 0)
    {
      // move hanging links to start indices to make the second pass
      TColStd_MapIteratorOfPackedMapOfInteger it(myHangIndices);
      for (; it.More(); it.Next())
        myStartIndices.Add(it.Key());
    }
  }
#ifdef _DEBUG
  if (doDebug && nbLoopsOnPass2)
    cout << "MakeLoops: " << nbLoopsOnPass2
      << " contours accepted on the second pass" << endl;
#endif

  if (!myLoops.IsEmpty())
    aResult |= RC_LoopsDone;
  if (!myHangIndices.IsEmpty())
    aResult |= RC_HangingLinks;
  return aResult;
}

//=======================================================================
//function : findContour
//purpose  : Collects edges in chain until they form a closed contour.
// Returns the index in the map theContour where the loop starts.
// It may return the number greater than the extent of the map by 1,
// what means that the contour is open
//=======================================================================

Standard_Integer Poly_MakeLoops::findContour
                   (Standard_Integer theIndexS,
                    NCollection_IndexedMap<Standard_Integer> &theContour,
                    const Handle_NCollection_BaseAllocator& theTempAlloc,
                    const Handle_NCollection_IncAllocator& theTempAlloc1) const
{
  theContour.Clear();
  Standard_Integer aStartIndex = 0;
  Standard_Integer aIndexS = theIndexS;
  NCollection_DataMap<Standard_Integer,Standard_Integer> aNodeLink(100, theTempAlloc);
  Standard_Integer aLastNode  = getLastNode (aIndexS);

  for (;;) {
    theContour.Add(aIndexS);
    aNodeLink.Bind(getFirstNode(aIndexS), aIndexS);

    Standard_Integer aIndex = Abs (aIndexS);

    // collect the list of links from this node able to participate
    // in this contour
    theTempAlloc1->Reset();
    NCollection_List<Standard_Integer> aLstIndS (theTempAlloc1);
    const ListOfLink& aLinks = myHelper->GetAdjacentLinks (aLastNode);
    Poly_MakeLoops::ListOfLink::Iterator itLinks (aLinks);
    for (; itLinks.More(); itLinks.Next()) {
      Standard_Integer aInd = myMapLink.FindIndex(itLinks.Value());
      if (aInd == 0 || aInd == aIndex)
        continue;
      // determine the orientation in which the link is to be taken
      Standard_Integer aIndS = aInd;
      Standard_Integer aNode1 = getFirstNode(aInd);
      if (aNode1 != aLastNode)
        aIndS = -aIndS;

      if (canLinkBeTaken(aIndS))
        aLstIndS.Append(aIndS);
    }

    if (aLstIndS.IsEmpty()) {
      // no more ways: open contour
      aStartIndex = theContour.Extent() + 1;
      break;
    }

    Standard_Integer aIndexSNext = 0;
    if (aLstIndS.First() == aLstIndS.Last())
      // only one possible way
      aIndexSNext = aLstIndS.First();
    else
      // find the most left way
      aIndexSNext = chooseLeftWay (aLastNode, aIndexS, aLstIndS);

    aIndexS = aIndexSNext;

    if (aIndexS == 0)
    {
      // no more ways: open contour
      aStartIndex = theContour.Extent() + 1;
      break;
    }
    if (theContour.Contains(aIndexS))
    {
      // entering the loop second time, stop search
      aStartIndex = theContour.FindIndex (aIndexS);
      break;
    }
    if (theContour.Contains (-aIndexS))
    {
      // leaving the loop, stop search
      aStartIndex = theContour.FindIndex (-aIndexS) + 1;
      break;
    }

    aLastNode  = getLastNode (aIndexS);

    if (aNodeLink.IsBound(aLastNode))
    {
      // closing the loop, stop search
      theContour.Add(aIndexS);
      aStartIndex = theContour.FindIndex(aNodeLink.Find(aLastNode));
      break;
    }
  }

  return aStartIndex;
}

//=======================================================================
//function : acceptContour
//purpose  : Builds a wire from a given set of edge indices (starting with
// theStartNumber) and appends it to the result list. 
// Also updates the start indices.
//=======================================================================

void Poly_MakeLoops::acceptContour
                   (const NCollection_IndexedMap<Standard_Integer>& theContour,
                    Standard_Integer theStartNumber)
{
  // append a new loop to the result
  Loop anEmptyLoop(myAlloc);
  myLoops.Append(anEmptyLoop);
  Loop& aLoop = myLoops.ChangeValue(myLoops.Length());

  // build a loop, mark links as taken,
  // remove them from the set of start indices
  Standard_Integer i;
  for (i = theStartNumber; i <= theContour.Extent(); i++)
  {
    Standard_Integer aIndexS = theContour(i);   // index with sign
    Standard_Integer aIndex = Abs (aIndexS);
    const Link& aLink = myMapLink(aIndex);
    Link aOrientedLink = aLink;
    if (aIndexS < 0)
      aOrientedLink.Reverse();
    aLoop.Append(aOrientedLink);
    // remove from start set
    myStartIndices.Remove(aIndexS);
  }
}

//=======================================================================
//function : getFirstNode
//purpose  : Returns the first node of the given link
// taking into account its orientation (the sign of index)
//=======================================================================

Standard_Integer Poly_MakeLoops::getFirstNode(Standard_Integer theIndexS) const
{
  Standard_Integer aIndex = Abs(theIndexS);
  const Link& aLink = myMapLink(aIndex);
  if (theIndexS > 0)
    return aLink.node1;
  return aLink.node2;
}

//=======================================================================
//function : getLastNode
//purpose  : Returns the last node of the given link
// taking into account its orientation (the sign of index)
//=======================================================================

Standard_Integer Poly_MakeLoops::getLastNode(int theIndexS) const
{
  Standard_Integer aIndex = Abs(theIndexS);
  const Link& aLink = myMapLink(aIndex);
  if (theIndexS > 0)
    return aLink.node2;
  return aLink.node1;
}

//=======================================================================
//function : markHangChain
//purpose  : Marks hanging links starting from the given node.
// Also removes such links from the start indices.
//=======================================================================

void Poly_MakeLoops::markHangChain(Standard_Integer theNode, Standard_Integer theIndexS)
{
  Standard_Integer aNode1 = theNode;
  Standard_Integer aIndexS = theIndexS;
  Standard_Integer aIndex = Abs(aIndexS);
  Standard_Boolean isOut = (aNode1 == getFirstNode(aIndexS));
  for (;;)
  {
    // check if the current link is hanging:
    // if it is outcoming from aNode1 then count the number of
    // other incoming links and vise versa;
    // if the number is zero than it is hanging
    const ListOfLink& aLinks = myHelper->GetAdjacentLinks (aNode1);
    Standard_Integer nEdges = 0;
    Poly_MakeLoops::ListOfLink::Iterator itLinks (aLinks);
    for (; itLinks.More() && nEdges == 0; itLinks.Next())
    {
      const Link &aL = itLinks.Value();
      Standard_Integer aInd = myMapLink.FindIndex(aL);
      if (aInd == 0 || aInd == aIndex)
        continue;
      if ((isOut && aNode1 == aL.node1) ||
          (!isOut && aNode1 == aL.node2))
        aInd = -aInd;
      if (canLinkBeTaken(aInd))
        nEdges++;
    }
    if (nEdges > 0)
      // leave this chain
      break;

    // mark the current link as hanging
    myStartIndices.Remove(aIndexS);
    myHangIndices.Add(aIndexS);

    // get other node of the link and the next link
    if (isOut)
      aNode1 = getLastNode(aIndexS);
    else
      aNode1 = getFirstNode(aIndexS);
    const ListOfLink& aNextLinks = myHelper->GetAdjacentLinks (aNode1);
    Standard_Integer aNextIndexS = 0;
    for (itLinks.Init(aNextLinks); itLinks.More(); itLinks.Next())
    {
      const Link &aL = itLinks.Value();
      Standard_Integer aInd = myMapLink.FindIndex(aL);
      if (aInd == 0 || aInd == aIndex)
        continue;
      if ((isOut && aNode1 == aL.node2) ||
          (!isOut && aNode1 == aL.node1))
        aInd = -aInd;
      if (canLinkBeTaken(aInd))
      {
        if (aNextIndexS == 0)
          aNextIndexS = aInd;
        else
        {
          // more than 1 ways, stop the chain
          aNextIndexS = 0;
          break;
        }
      }
    }
    if (aNextIndexS == 0)
      break;
    aIndexS = aNextIndexS;
    aIndex = Abs(aIndexS);
  }
}

//=======================================================================
//function : canLinkBeTaken
//purpose  : Returns True if the link appointed by the index can participate
// in a loop in given orientation (it is the sign of index).
// Remark: A boundary edge can be taken only once
//=======================================================================

Standard_Boolean Poly_MakeLoops::canLinkBeTaken(Standard_Integer theIndexS) const
{
  return myStartIndices.Contains(theIndexS);
}

//=======================================================================
//function : showBoundaryBreaks
//purpose  : 
//=======================================================================

#ifdef _DEBUG
void Poly_MakeLoops::showBoundaryBreaks() const
{
  // collect nodes of boundary links
  TColStd_PackedMapOfInteger aNodesMap;
  Standard_Integer i;
  for (i = 1; i <= myMapLink.Extent(); i++)
  {
    const Link& aLink = myMapLink(i);
    Standard_Integer aFlags = aLink.flags & LF_Both;
    if (aFlags && aFlags != LF_Both)
    {
      // take only oriented links
      aNodesMap.Add(aLink.node1);
      aNodesMap.Add(aLink.node2);
    }
  }

  // check each node if the number of input and output links are equal
  Standard_Boolean isFirst = Standard_True;
  TColStd_MapIteratorOfPackedMapOfInteger it(aNodesMap);
  for (; it.More(); it.Next())
  {
    Standard_Integer aNode = it.Key();
    Standard_Integer nb = 0;
    const ListOfLink& aLinks = myHelper->GetAdjacentLinks(aNode);
    Poly_MakeLoops::ListOfLink::Iterator itLinks (aLinks);
    for (; itLinks.More(); itLinks.Next())
    {
      const Poly_MakeLoops::Link& aLink = itLinks.Value();
      if (myMapLink.FindIndex(aLink) == 0)
        continue;
      Standard_Integer aFlags = aLink.flags & LF_Both;
      if (aFlags && aFlags != LF_Both)
      {
        if (aNode == aLink.node1) // output?
        {
          if (aFlags & LF_Fwd)
            nb++;  // yes, output
          else
            nb--;  // reversed, so input
        }
        else if (aNode == aLink.node2) // input?
        {
          if (aFlags & LF_Fwd)
            nb--;  // yes, input
          else
            nb++;  // reversed, so output
        }
        else
          // inconsistent
          nb += 100;
      }
    }
    if (nb != 0)
    {
      // indicate this node
      if (isFirst)
      {
        isFirst = Standard_False;
        cout << "boundary breaks are found in the following nodes:" << endl;
      }
      cout << aNode << " ";
    }
  }
  if (!isFirst)
    cout << endl;
}
#endif

//=======================================================================
//function : GetHangingLinks
//purpose  : 
//=======================================================================

void Poly_MakeLoops::GetHangingLinks(ListOfLink& theLinks) const
{
  TColStd_MapIteratorOfPackedMapOfInteger it(myHangIndices);
  for (; it.More(); it.Next())
  {
    Standard_Integer aIndexS = it.Key();
    Link aLink = myMapLink(Abs(aIndexS));
    if (aIndexS < 0)
      aLink.Reverse();
    theLinks.Append(aLink);
  }
}

//=======================================================================
//function : Poly_MakeLoops3D
//purpose  : 
//=======================================================================

Poly_MakeLoops3D::Poly_MakeLoops3D(const Helper* theHelper,
                                         const Handle_NCollection_BaseAllocator& theAlloc)
: Poly_MakeLoops (theHelper, theAlloc)
{
}

//=======================================================================
//function : Poly_MakeLoops3D::chooseLeftWay
//purpose  : 
//=======================================================================

Standard_Integer Poly_MakeLoops3D::chooseLeftWay
                   (const Standard_Integer theNode,
                    const Standard_Integer theSegIndex,
                    const NCollection_List<Standard_Integer>& theLstIndS) const
{
  Standard_Real aAngleMin = ::PI * 2;
  gp_Dir aNormal;
  const Helper* aHelper = getHelper();
  if (!aHelper->GetNormal (theNode, aNormal))
    return theLstIndS.First();

  Link aLink = getLink(theSegIndex);
  gp_Dir aTgtRef;
  if (!aHelper->GetLastTangent (aLink, aTgtRef))
    return theLstIndS.First();

  // project tangent vector to the plane orthogonal to normal
  // to get the reference direction
  gp_XYZ aTgtRefXYZ = aNormal.XYZ().CrossCrossed (aTgtRef.XYZ(), aNormal.XYZ());
  if (aTgtRefXYZ.SquareModulus() < 1e-14)
    // a problem with defining reference direction, take first way
    return theLstIndS.First();
  aTgtRef = aTgtRefXYZ;

  // find the way with minimal angle to the reference direction
  // (the angle is in range ]-PI;PI])
  Standard_Integer aResIndex = 0;
  NCollection_List<Standard_Integer>::Iterator aItI (theLstIndS);
  for (; aItI.More(); aItI.Next())
  {
    Standard_Integer aIndS = aItI.Value();

    aLink = getLink(aIndS);
    gp_Dir aTgt;
    if (!aHelper->GetFirstTangent (aLink, aTgt))
      continue;

    gp_XYZ aTgtXYZ = aNormal.XYZ().CrossCrossed (aTgt.XYZ(), aNormal.XYZ());
    if (aTgtXYZ.SquareModulus() < 1e-14)
      // skip a problem way
      continue;
    aTgt = aTgtXYZ;

    Standard_Real aAngle = aTgt.AngleWithRef(aTgtRef, aNormal);
    if (aAngle < 1e-4 - ::PI)
      aAngle = ::PI;
    if (aAngle < aAngleMin)
    {
      aAngleMin = aAngle;
      aResIndex = aIndS;
    }
  }
  return aResIndex == 0 ? theLstIndS.First() : aResIndex;
}

//=======================================================================
//function : Poly_MakeLoops2D
//purpose  : 
//=======================================================================

Poly_MakeLoops2D::Poly_MakeLoops2D(const Standard_Boolean theLeftWay,
                                         const Helper* theHelper,
                                         const Handle_NCollection_BaseAllocator& theAlloc)
: Poly_MakeLoops (theHelper, theAlloc),
  myRightWay(!theLeftWay)
{
}

//=======================================================================
//function : Poly_MakeLoops2D::chooseLeftWay
//purpose  : 
//=======================================================================

Standard_Integer Poly_MakeLoops2D::chooseLeftWay
                   (const Standard_Integer /*theNode*/,
                    const Standard_Integer theSegIndex,
                    const NCollection_List<Standard_Integer>& theLstIndS) const
{
  Standard_Real aAngleMin = ::PI * 2;
  const Helper* aHelper = getHelper();
  Link aLink = getLink(theSegIndex);
  gp_Dir2d aTgtRef;
  if (!aHelper->GetLastTangent (aLink, aTgtRef))
    // a problem with defining reference direction, take first way
    return theLstIndS.First();

  // find the way with minimal angle to the reference direction
  // (the angle is in range ]-PI;PI])
  Standard_Integer aResIndex = 0;
  NCollection_List<Standard_Integer>::Iterator aItI (theLstIndS);
  for (; aItI.More(); aItI.Next())
  {
    Standard_Integer aIndS = aItI.Value();

    aLink = getLink(aIndS);
    gp_Dir2d aTgt;
    if (!aHelper->GetFirstTangent (aLink, aTgt))
      // skip a problem way
      continue;

    Standard_Real aAngle = aTgt.Angle(aTgtRef);
    if (myRightWay)
      aAngle = -aAngle;
    if (aAngle < 1e-4 - ::PI)
      aAngle = ::PI;
    if (aAngle < aAngleMin)
    {
      aAngleMin = aAngle;
      aResIndex = aIndS;
    }
  }
  return aResIndex == 0 ? theLstIndS.First() : aResIndex;
}