CreateFaces.cxx 39.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
//=============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.  See the above copyright notice for more information.
//=============================================================================
#include "smtk/bridge/polygon/operators/CreateFaces.h"

#include "smtk/bridge/polygon/Session.h"
David Thompson's avatar
David Thompson committed
13
#include "smtk/bridge/polygon/internal/Config.h"
14
#include "smtk/bridge/polygon/internal/Model.h"
David Thompson's avatar
David Thompson committed
15
#include "smtk/bridge/polygon/internal/Edge.h"
16

17
18
#include "smtk/common/UnionFind.h"

19
20
21
22
23
24
25
26
27
28
#include "smtk/io/Logger.h"

#include "smtk/attribute/Attribute.h"
#include "smtk/attribute/DoubleItem.h"
#include "smtk/attribute/IntItem.h"
#include "smtk/attribute/ModelEntityItem.h"
#include "smtk/attribute/StringItem.h"

#include "smtk/bridge/polygon/CreateFaces_xml.h"

29
30
#include <deque>
#include <map>
David Thompson's avatar
David Thompson committed
31
#include <set>
32
#include <vector>
David Thompson's avatar
David Thompson committed
33

34
35
36
37
namespace smtk {
  namespace bridge {
    namespace polygon {

David Thompson's avatar
David Thompson committed
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
/// An internal structure used when discovering edge loops.
struct ModelEdgeInfo
{
  ModelEdgeInfo()
    : m_allowedOrientations(0)
    {
    this->m_visited[0] = this->m_visited[1] = false;
    }
  ModelEdgeInfo(int allowedOrientations)
    {
    this->m_allowedOrientations = allowedOrientations > 0 ? +1 : allowedOrientations < 0 ? -1 : 0;
    this->m_visited[0] = this->m_visited[1] = false;
    }
  ModelEdgeInfo(const ModelEdgeInfo& other)
    : m_allowedOrientations(other.m_allowedOrientations)
    {
    for (int i = 0; i < 2; ++i)
      m_visited[i] = other.m_visited[i];
    }

  int m_allowedOrientations; // 0: all, -1: only negative, +1: only positive
  bool m_visited[2]; // has the [0]: negative, [1]: positive orientation of the edge been visited already?
};

/// An internal structure used to map model edges to information about the space between them.
63
typedef std::map<smtk::model::Edge, ModelEdgeInfo> ModelEdgeMap;
David Thompson's avatar
David Thompson committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

/// An internal structure used to hold a sequence of model edges which form a loop.
struct LoopInfo
{
  internal::Id m_id;
  internal::Rect m_bounds;
  smtk::model::Edges m_edges;
  std::set<internal::Id> m_children; // first-level holes
  bool operator < (const LoopInfo& other)
    {
    return ll(this->m_bounds) < ur(other.m_bounds);
    }
};

/// An internal structure that holds all the loops discovered, sorted by their lower-left bounding box coordinates.
79
typedef std::map<internal::Id,LoopInfo> LoopsById;
David Thompson's avatar
David Thompson committed
80

81
82
83
84
/// Sweep events ordered by their left-, lower-most point coordinates.
typedef std::set<SweepEvent> SweepEventSet;

/// Structure to hold a sweepline event data (segment start, segment end, segment crossing).
85
86
87
88
struct SweepEvent
{
  enum SweepEventType {
    SEGMENT_START,
89
90
    SEGMENT_CROSS, // NB: CROSS must come before END so that RemoveCrossing can terminate early; want to handle crossings while edge is still active.
    SEGMENT_END
91
92
93
  };
  SweepEventType m_type;
  internal::Point m_posn;
94
95
96
  smtk::model::Edge m_edge; // only used by SEGMENT_START
  int m_indx; // only used by SEGMENT_START
  RegionIdSet::value_type m_frag[2]; // used by SEGMENT_END and SEGMENT_CROSS as frag ID, SEGMENT_START as sense (-1/+1)
97
98
99
100
101
102
103
104
105
106
107
108
109
110

  SweepEventType type() const { return this->m_type; }
  const internal::Point& point() const { return this->m_posn; }

  bool operator < (const SweepEvent& other) const
    {
    return
      (this->m_posn.x() < other.point().x() ||
       (this->m_posn.x() == other.point().x() &&
        (this->m_posn.y() < other.point().y() ||
         (this->m_posn.y() == other.point().y() &&
          (this->m_type < other.type() ||
           (this->m_type == other.type() &&
            ( // Types match, perform type-specific comparisons:
111
112
113
114
115
             (this->m_type == SEGMENT_START &&
              (this->m_edge < other.m_edge ||
               (this->m_edge == other.m_edge && this->m_indx < other.m_indx))) ||
             (this->m_type == SEGMENT_END &&
              (this->m_frag[0] < other.m_frag[0])) ||
116
             (this->m_type == SEGMENT_CROSS &&
117
118
119
120
              (this->m_frag[0] < other.m_frag[0] ||
               (this->m_frag[0] == other.m_frag[0] &&
                (this->m_frag[1] < other.m_frag[1]))))
            ))))))) ?
121
122
123
      true : false;
    }

124
125
126
127
128
  static SweepEvent SegmentStart(
    const internal::Point& p0,
    const internal::Point& p1,
    const smtk::model::Edge& edge,
    int segId)
129
130
131
    {
    SweepEvent event;
    event.m_type = SEGMENT_START;
132
133
134
135
136
137
138
139
140
141
142
143
    if (p0.x() < p1.x() || (p0.x() == p1.x() && p0.y() < p1.y()))
      {
      event.m_posn = p0;
      event.m_frag[0] = +1;
      }
    else
      {
      event.m_posn = p1;
      event.m_frag[0] = -1;
      }
    event.m_edge = edge;
    event.m_indx = segId;
144
145
    return event;
    }
146
147
148
  static SweepEvent SegmentEnd(
    const internal::Point& posn,
    RegionIdSet::value_type fragId)
149
150
151
152
    {
    SweepEvent event;
    event.m_type = SEGMENT_END;
    event.m_posn = posn;
153
    event.m_frag[0] = fragId;
154
155
    return event;
    }
156
157
158
159
  static SweepEvent SegmentCross(
    const internal::Point& crossPos,
    RegionIdSet::value_type fragId0,
    RegionIdSet::value_type fragId1)
160
161
162
163
    {
    SweepEvent event;
    event.m_type = SEGMENT_CROSS;
    event.m_posn = crossPos;
164
165
    event.m_frag[0] = fragId0;
    event.m_frag[1] = fragId1;
166
167
    return event;
    }
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

  static bool RemoveCrossing(
    SweepEventSet& queue,
    FragmentId fragId0,
    FragmentId fragId1)
    {
    for (SweepEventSet::iterator it = queue.begin(); it != queue.end(); ++it)
      {
      switch (it->m_type)
        {
      case SEGMENT_START:
        break;
      case SEGMENT_CROSS:
        if (
          it->m_frag[0] == fragId0 &&
          it->m_frag[1] == fragId1)
          {
          queue.erase(it);
          return true;
          }
        break;
      case SEGMENT_END:
        if (it->m_frag[0] == fragId0 || it->m_frag[0] == fragId1)
          { // Terminate early... crossing event must come before either edge ends.
          return false;
          }
        break;
        }
      }
    return false;
    }
};

/// Structure to hold information about a portion of an edge-segment forming part of an output loop.
struct EdgeFragment
{
  internal::Point m_lo; // Low is relative to the sweep direction (left to right, bottom to top).
  internal::Point m_hi; // High is relative to the sweep direction.
  smtk::model::Edge m_edge; // SMTK model information
  internal::EdgePtr m_edgeData; // Private edge data (sequence of points defining segments)
  int m_segment; // Offset into edge's point sequence defining the segment containing this fragment.
  bool m_sense; // True when fragment and model edge are codirectional; false when they are antidirectional.
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
  RegionIdSet::value_type m_regionId[2]; // Union-Find region to each side of edge; 0: region CCW of edge, 1: region CW of edge.

  internal::Point& lo() { return this->m_lo; }
  const internal::Point& lo() const { return this->m_lo; }

  internal::Point& hi() { return this->m_hi; }
  const internal::Point& hi() const { return this->m_hi; }

  /// Return the ID of the region above the fragment.
  RegionIdSet::value_type& upperRegion() { return this->m_regionId[1]; }
  /// Return the ID of the region below the fragment.
  RegionIdSet::value_type& lowerRegion() { return this->m_regionId[0]; }

  /**\brief Return the ID of the region just counter-clockwise (CCW) of the fragment...
    *
    * ... when winding around the lower (\a fromLowerEnd is true) or
    * upper (\a fromLowerEnd is false) endpoint of the fragment.
    */
  RegionIdSet::value_type& ccwRegion(bool fromLowerEnd) { return this->m_regionId[fromLowerEnd ? 1 : 0]; }
  /**\brief Return the ID of the region just clockwise (CW) of the fragment...
    *
    * ... when winding around the lower (\a fromLowerEnd is true) or
    * upper (\a fromLowerEnd is false) endpoint of the fragment.
    */
  RegionIdSet::value_type& cwRegion(bool fromLowerEnd) { return this->m_regionId[fromLowerEnd ? 0 : 1]; }
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
};

typedef std::vector<EdgeFragment> FragmentArray; // List of all output fragments forming loops.

struct SweeplinePosition
{
  internal::Point m_position;
  SweeplinePosition(const internal::Point& posn)
    : m_position(posn)
    {
    }
  SweeplinePosition(const SweeplinePosition& other)
    : m_position(other.m_position)
    {
    }
250
251
252
253
254
255
256

  /// Return the current sweepline position
  internal::Point& position() { return this->m_position; }

  /// Return the current sweepline position
  const internal::Point& position() const { return this->m_position; }

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
  /// Advance the sweepline to another position, ignoring invalid points to the left of the current position.
  void advance(const internal::Point& pt)
    {
    if (
      pt.x() > this->m_position.x() ||
      (pt.x() == this->m_position.x() && pt.y() > this->m_position.y()))
      {
      this->m_position = pt;
      }
    /*
    else
      {
      throw std::string("Can not sweep backwards!");
      }
      */
    }
  bool operator < (const internal::Point& other)
    {
    return this->m_position < other;
    }
  bool operator > (const internal::Point& other)
    {
    return this->m_position > other;
    }
  bool operator == (const internal::Point& other)
    {
    return this->m_position == other;
    }
  bool operator != (const internal::Point& other)
    {
    return this->m_position != other;
    }
};

/// Functor to compare indices into a vector of EdgeFragments based on which fragment is above the other.
struct EdgeFragmentComparator
{
  FragmentArray* m_sweptFragments;
  SweeplinePosition* m_sweepPosition;

  EdgeFragmentComparator(FragmentArray& frag, SweeplinePosition& startPoint)
    : m_sweptFragments(&frag), m_sweepPosition(&startPoint)
    {
    }

  EdgeFragmentComparator(const EdgeFragmentComparator& other)
    :
      m_sweptFragments(other.m_sweptFragments),
      m_sweepPosition(other.m_sweepPosition)
    {
    }

  /// Return the array of fragments the comparator indexes into.
  FragmentArray* fragments() const
    {
    return this->m_sweptFragments;
    }
  /**\brief Return the current sweep line location, which moves from left to right.
    *
    * Fragments are ordered bottom-to-top along the vertical line passing through this point.
    * It is possible for multiple sweep points to line on the same vertical line;
    * points directly beneath the sweepline position are considered
    * to be to the "left" of the current point.
    */
  internal::Point position() const
    {
    return this->m_sweepPosition->m_position;
    }
  /**\brief Return true when line a lies to the left of and/or below line b for the current sweepLocation.
    *
    * When the sweep position is at an intersection point of 2 or more lines, we order
    * the lines according to their behavior just to the left (or below, in the case of
    * vertical lines) of the sweep position.
    *
    * As noted by Boissonat and Preparata, predicates for testing relationships between
    * lines require increased-precision operations according to the degree of the
    * equations in the predicate.
    */
  bool operator() (FragmentId a, FragmentId b) const
    {
    FragmentId fsize = this->fragments()->size();
    // If a is invalid, it is "above" any valid segments:
    if (a >= fsize)
      return false;
    // Now we know a is valid (or we would have returned false).
    // Valid segments are always below invalid ones:
    if (b >= fsize)
      return true;

    // Both a and b are valid:
    EdgeFragment& lineA((*this->fragments())[a]);
    EdgeFragment& lineB((*this->fragments())[b]);

    // I. Compare their y-intercepts with the sweepline
    internal::Point p = this->position();
    internal::HighPrecisionCoord ya =
       lineA.m_lo.y() * (lineA.m_hi.x() - p.x()) +
       lineA.m_hi.y() * (p.x() - lineA.m_lo.x());
    internal::Coord denomA = lineA.m_hi.x() - lineA.m_lo.x();

    internal::HighPrecisionCoord yb =
       lineB.m_lo.y() * (lineB.m_hi.x() - p.x()) +
       lineB.m_hi.y() * (p.x() - lineB.m_lo.x());
    internal::Coord denomB = lineB.m_hi.x() - lineB.m_lo.x();

    if (denomA == 0) // Fragment a is vertical, so y_a is technically the sweep position.
      {
      if (denomB == 0) // Both fragments are vertical and intersect our vertical sweep line
        {
        return (
          // Order by the "lower" coordinates
          (lineA.m_lo.x() < lineB.m_lo.x() || // FIXME: Not necessary since lines are vertical?
           (lineA.m_lo.x() == lineB.m_lo.x() && // FIXME: Not necessary since lines are vertical?
            (lineA.m_lo.y() < lineB.m_lo.y() ||
             (lineA.m_lo.y() == lineB.m_lo.y() &&
              // Order so that "lower" segment is the one that will *exit* the active fragments first
              // (i.e., by smaller m_hi.y()) and then by edge Id and segment Id so that no segments are identical
              (lineA.m_hi.y() < lineB.m_hi.y() ||
               (lineA.m_hi.y() == lineB.m_hi.y() &&
                (lineA.m_edge.entity() < lineB.m_edge.entity() ||
                 (lineA.m_edge.entity() == lineB.m_edge.entity() &&
                  (lineA.m_segment < lineB.m_segment ||
                   (lineA.m_segment == lineB.m_segment &&
                    (lineA.m_sense < lineB.m_sense)))))))))))) ? true : false;
        }
      else
        { // A is vertical, B is not. A < B for all lines that could possibly be active.
        return true;
        }
      }
    else if (denomB == 0)
      { // A is not vertical, B is vertical. A > B for all lines that could possibly be active.
      return false;
      }
    else
      {
      return (ya * denomB < yb * denomA) ? true : false;
      }
    }
};

/// The sweepline Interval Tree (IT), of active edge segments, is a set of offsets into the array of fragments.
typedef std::set<FragmentId, EdgeFragmentComparator> ActiveSegmentTree;

/// The set of all regions is a UnionFind (UF) data structure.
typedef smtk::common::UnionFind<int> RegionIdSet;

/// A structure to hold chains of coedges bounding regions of space.
struct Region
{
  std::deque<std::pair<FragmentId,bool> > m_boundary; // size_t = fragment id, bool = sense rel to fragment
  std::set<int> m_innerLoops;
};

/// A map to hold each region's definition indexed by its UF region ID.
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
typedef std::map<RegionIdSet::value_type,smtk::shared_ptr<Region> > RegionDefinitions;

internal::HighPrecisionCoord dot2d(const internal::Coord oa[2], const internal::Coord oo[2])
{
  internal::HighPrecisionCoord result;
  result =
    static_cast<internal::HighPrecisionCoord>(oa[0]) * oo[0] +
    static_cast<internal::HighPrecisionCoord>(oa[1]) * oo[1];
  return result;
}

internal::HighPrecisionCoord cross2d(const internal::Coord oa[2], const internal::Coord oo[2])
{
  internal::HighPrecisionCoord result;
  result =
    static_cast<internal::HighPrecisionCoord>(oa[0]) * oo[1] -
    static_cast<internal::HighPrecisionCoord>(oa[1]) * oo[0];
  return result;
}
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450

/**\brief Represent the neighborhood of a sweepline point, x.
  *
  * This holds a CCW-ordered list of edges incident to x, plus an
  * array of fragments
  */
struct Neighborhood
{
  Neighborhood(SweeplinePosition& x, FragmentArray& fragments, SweepEventSet& eventQueue, ActiveSegmentTree& active)
    : m_point(&x), m_fragments(&fragments), m_eventQueue(&eventQueue), m_activeEdges(&active)
    {
    }

  SweeplinePosition* m_point;
  FragmentArray* m_fragments;
  SweepEventSet* m_eventQueue;
  ActiveSegmentTree* m_activeEdges;
  RegionIdSet m_regionIds;
  RegionDefinitions m_regions;
  std::vector<FragmentId> m_fragmentsToQueue;
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
  std::list<FragmentId> m_ring; // offsets into m_fragments that order a neighborhood CCW

  /// The space between \a ringA and \a ringB is not interrupted; mark coedges of A/B as same region.
  void assignAndMergeRegions(
    const std::list<FragmentId>::iterator& ringA,
    const std::list<FragmentId>::iterator& ringB)
    {
    EdgeFragment& fragA((*this->m_fragments)[*ringA]);
    EdgeFragment& fragB((*this->m_fragments)[*ringB]);
    bool orientA = this->fragmentOrientation(fragA); // true when m_point is coincident with fragA.lower
    bool orientB = this->fragmentOrientation(fragB);

    // TODO. Fix so that no regionId is ever < 0.
    //       Then this code becomes moot and we just:
    //         - insert fragment A to end of m_regions[find(fragA.regionIds[0])] if fragA's coedge 0 points "backwards"
    //         - insert fragment B to end of m_regions[find(fragB.regionIds[1])] if fragB's coedge 1 points "backwards"
    //         - winner = mergeSet(fragA.regionIds[0], fragB.regionIds[1])
    //         - pop loser (!= winner) from m_regions and hold onto it.
    //         - append/prepend m_regions[loser] to m_regions[winner] (append if winner = fragA, prepend if winner = fragB)
    //         - if m_regions[winner] is closed, output region and add it as an inner loop to the region containing the neighborhood (if any).
    RegionIdSet::value_type idA = this->m_regionIds.find(fragA.ccwRegion(orientA));
    RegionIdSet::value_type idB = this->m_regionIds.find(fragB.cwRegion(orientB));
    if (idA != idB)
      { // Merge regions on inside of A--B. Add coedges (of exiting edges on inside of A--B) to region.
      RegionIdSet::value_type winner = this->m_regionIds.mergeSets(idA, idB);
      }
    else
      { // Add coedges (of exiting edges on inside of A--B) to region.
      }
    //xxx
    if (this->m_point.position() > fragA.lo())
      {
      this->m_regions[winner].insert(fragA.xxx)
    this->m_regionIds.mergeSets(fragA.regionIds[0], fragB.regionIds[1]);
      // TODO. Pop m_regions[whichever fragX.regionId[z] is not returned by mergeSets] and append/prepend
      //       to m_regions[whichever fragX.regionId[z] *is* returned by mergeSets] depending on
      //       whether survivor X == A (prepend m_regions[m_regionIds->find(B)]) or X == b (append ...find(A)).
      }
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
    // TODO. Could also check whether fragments are both segment-end events;
    //       if so, see whether chain is complete and output a "create face
    //       from chain" event.
    }

  /// Insert \a fragId into \a m_ring if it is between \a ringA and \a ringB
  bool insertFragmentBetween(
    const std::list<FragmentId>::iterator& ringA,
    const std::list<FragmentId>::iterator& ringB,
    FragmentId fragId,
    EdgeFragment& frag,
    const internal::Point& other)
    {
    EdgeFragment& fragA((*this->m_fragments)[*ringA]);
    EdgeFragment& fragB((*this->m_fragments)[*ringB]);
    internal::Point otherA(fragA.lo() == this->m_point->position() ? fragA.hi() : fragA.lo());
    internal::Point otherB(fragB.lo() == this->m_point->position() ? fragB.hi() : fragB.lo());

    internal::Coord oa[2] = {
      otherA.x() - this->m_point->position().x(),
      otherA.y() - this->m_point->position().y()};
    internal::Coord ob[2] = {
      otherB.x() - this->m_point->position().x(),
      otherB.y() - this->m_point->position().y()};
    internal::Coord oo[2] = {
      other.x() - this->m_point->position().x(),
      other.y() - this->m_point->position().y()};
    internal::HighPrecisionCoord oaXoo = cross2d(oa, oo);
    internal::HighPrecisionCoord ooXob = cross2d(oo, ob);
    if (oaXoo > 0 && ooXob > 0)
      { // other is between ringA and ringB. Insert it just before ringB:
      this->m_ring.insert(ringB, fragId);
      return true;
      }
    else if (oaXoo == 0)
      { // Urk. other is collinear with ringA...
      if (dot2d(oa,oo) < 0 && ooXob > 0)
        {
        // ... but antidirectional with ringA; and properly oriented with ringB.
        this->m_ring.insert(ringB, fragId);
        return true;
        }
      else
        {
        // TODO. FIXME.
        // Replace ringA with fragId if frag is shorter (or barf if lengths identical? surgery to fix problems could be nasty);
        // queue new SegmentStart for remaining long fragment.
        }
      }
    else if (ooXob == 0)
      { // Urk. other is collinear with ringB...
      if (dot2d(oo,ob) < 0 && oaXoo > 0)
        {
        // ... but antidirectional with ringB; and properly oriented with ringA.
        this->m_ring.insert(ringB, fragId);
        return true;
        }
      else
        {
        // TODO. FIXME.
        // Replace ringB with fragId if frag is shorter (or barf if lengths identical? surgery to fix problems could be nasty);
        // queue new SegmentStart for remaining long fragment.
        }
      }
    return false; // other is not between ringA and ringB.
    }
  /**\brief Insert \a frag where it belongs in the ring of fragments incident to \a m_point.
    *
    * The \a other point is the end of \a frag which is not \a m_point.
    * This algorithm works by traversing pre-existing neighborhood fragments to identify when
    * dot(cross(fragIt-m_point x other-m_point),(0,0,1)) changes sign from - to +.
    * Or, identically, it inserts frag between a neighboring pair of points on the ring (a,b)
    * when dot(cross(a-m_point x other-m_point),(0,0,1)) > 0 && dot(cross(other-m_point x b-m_point),(0,0,1)) > 0.
    *
    * If either cross product has zero magnitude, the fragment is collinear with an existing segment.
    * In that case, (1) the shorter fragment is kept in the ring; (2) a new SegmentStart event is queued
    * for the uncovered portion of the longer fragment; (3) the longer fragment is discarded; and
    * (4?) a warning is logged.
    */
569
  void insertFragment(FragmentId fragId, EdgeFragment& frag, const internal::Point& other)
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
    {
    for (int i = 0; i < 2; ++i)
      if (frag.m_regionId[i] < 0)
        frag.m_regionId[i] = this->m_regionIds.createSet();

    if (this->m_ring.size() < 2)
      { // No matter where we insert, the order will be CCW. So insert at beginning:
      this->m_ring.insert(this->m_ring.begin(), fragId);
      return;
      }
    std::list<FragmentId>::iterator ringA = this->m_ring.end();
    --ringA; // "unadvance" before end() to the last ring entry.
    std::list<FragmentId>::iterator ringB = this->m_ring.begin();
    // Start by processing the implicit fragment-pair between m_ring.end() and m_ring.begin():
    if (this->insertFragmentBetween(ringA, ringB, fragId, frag, other))
      return;
    // Now proceed through the list until we find the right spot.
    ringA = ringB;
    for (++ringB; ringB != this->m_ring.end(); ++ringA, ++ringB /*, sao = -sbo??? */)
      {
      if (this->insertFragmentBetween(ringA, ringB, fragId, frag, other))
        return;
      }
    std::cerr << "Error. Unable to insert fragment into neighborhood!\n"; // FIXME. Add to log, not cerr/cout.
594
595
596
597
598
599
600
601
602
603
604
605
606
    }

  void queueActiveEdge(FragmentId fragId, EdgeFragment& frag)
    {
    this->m_fragmentsToQueue.push_back(fragId);
    }

  void removeActiveEdge(FragmentId fragId, EdgeFragment& frag)
    {
    }

  void processQueue()
    {
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
    // If we have any incident edges (and it is highly suspicious if we don't)
    // then loop over adjacent pairs assigning/merging region IDs.
    if (!this->m_ring.empty())
      { // Note that ringA == ringB is valid (both sides of fragment are the same regionId).
      std::list<FragmentId>::iterator ringA = this->m_ring.end();
      --ringA; // "unadvance" before end() to the last ring entry.
      std::list<FragmentId>::iterator ringB = this->m_ring.begin();
      // Start by processing the implicit fragment-pair between m_ring.end() and m_ring.begin():
      this->assignAndMergeRegions(ringA, ringB);
      // Now proceed through the list until we have visited them all.
      ringA = ringB;
      for (++ringB; ringB != this->m_ring.end(); ++ringA, ++ringB /*, sao = -sbo??? */)
        {
        this->assignAndMergeRegions(ringA, ringB);
        }
      }
    std::cout << "Neighborhood::processQueue()\n";
    std::list<FragmentId>::iterator rit;
    for (rit = this->m_ring.begin(); rit != this->m_ring.end(); ++rit)
      {
      EdgeFragment& frag((*this->m_fragments)[*rit]);
      std::cout
        << "  " << frag.lo().x()/1182720.0 << " " << frag.lo().y()/1182720.0
        << " -- " << frag.hi().x()/1182720.0 << " " << frag.hi().y()/1182720.0
        << "  " << frag.m_edge.name() << ", seg " << frag.m_segment
        << "\n";
      }
634
635
636
637
638
639
640
641
642
    std::vector<FragmentId>::iterator it;
    for (it = this->m_fragmentsToQueue.begin(); it != this->m_fragmentsToQueue.end(); ++it)
      {
      this->m_activeEdges->insert(*it);
      EdgeFragment& frag((*this->m_fragments)[*it]);
      this->m_eventQueue->insert(SweepEvent::SegmentEnd(frag.m_hi, *it));
      // TODO: Check for neighbor intersections; remove them then check for neighbor intersections with *it and add them.
      }
    this->m_fragmentsToQueue.clear();
643
    this->m_ring.clear();
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
    }

  /**\brief Advance the sweepline to the next event's point.
    *
    * This may do nothing if the next event is coincident with the current point.
    * This may advance to some position other than \a pt if any queued edge fragments
    * end or cross before \a pt.
    */
  void advanceSweeplineTo(const internal::Point& pt)
    {
    if (this->m_point->m_position != pt)
      {
      // Advance the sweepline the absolute minimum expressable amount.
      // This makes it possible to insert fragments that start at this->m_point->m_position:
      this->m_point->m_position.y(this->m_point->m_position.y()+1);
      // Now it is safe to add edges which crossed at the previous sweepline point.
      this->processQueue();

      internal::Point tmp = this->m_eventQueue->begin()->point();
      if (tmp.x() < pt.x() || (tmp.x() == pt.x() && tmp.y() < pt.y()))
        {
        this->m_point->advance(tmp);
        return;
        }

      // FIXME!!! Do not do this. Consider newly inserted end/crossing events created by processQueue!
      this->m_point->advance(pt);
      }
    }
673
674
675
};

#if 0
David Thompson's avatar
David Thompson committed
676
static void AddLoopsForEdge(
677
  CreateFaces* op,
678
679
  ModelEdgeMap& modelEdgeMap,
  ModelEdgeMap::iterator edgeInfo,
680
  LoopsById& loops,
David Thompson's avatar
David Thompson committed
681
682
683
684
  smtk::model::VertexSet& visitedVerts,
  std::map<internal::Point, int>& visitedPoints // number of times a point has been encountered (not counting periodic repeat at end of a single-edge loop); used to identify points that must be promoted to model vertices.
)
{
685
  if (!edgeInfo->first.isValid() || !op)
David Thompson's avatar
David Thompson committed
686
687
688
    {
    return; // garbage-in? garbage-out.
    }
689
  internal::EdgePtr edgeRec = op->findStorage<internal::edge>(edgeInfo->first.entity());
David Thompson's avatar
David Thompson committed
690
691
692
693
694
695
696
697
698
699

  smtk::model::Vertices endpts = edgeInfo->first.vertices();
  if (endpts.empty())
    { // Tessellation had better be a periodic loop. Traverse for bbox.
    //AddEdgePointsToBox(tess, box);
    }
  else
    { // Choose an endpoint and walk around the edge.
    }
}
700
701
702
703
704
705
706
707
#endif // 0

template<typename T>
void ConditionalErase(T& container, typename T::iterator item, bool shouldErase)
{
  if (shouldErase)
    container.erase(item);
}
David Thompson's avatar
David Thompson committed
708

709
void DumpEventQueue(const char* msg, SweepEventSet& eventQueue)
710
{
711
  std::cout << ">>>>>   " << msg << "\n";
712
713
714
715
716
717
718
719
720
  std::cout << ">>>>>   Event Queue:\n";
  SweepEventSet::iterator it;
  for (it = eventQueue.begin(); it != eventQueue.end(); ++it)
    {
    std::cout << "  " << it->type() << ": " << it->point().x() << ", " << it->point().y() << "\n";
    }
  std::cout << "<<<<<   Event Queue\n";
}

721
722
723
724
725
726
727
728
729
730
731
732
733
smtk::model::OperatorResult CreateFaces::operateInternal()
{
  // Discover how the user wants to specify scaling.
  smtk::attribute::IntItem::Ptr constructionMethodItem = this->findInt("construction method");
  int method = constructionMethodItem->discreteIndex(0);

  smtk::attribute::DoubleItem::Ptr pointsItem = this->findDouble("points");
  smtk::attribute::IntItem::Ptr coordinatesItem = this->findInt("coordinates");
  smtk::attribute::IntItem::Ptr offsetsItem = this->findInt("offsets");

  smtk::attribute::ModelEntityItem::Ptr edgesItem = this->findModelEntity("edges");

  smtk::attribute::ModelEntityItem::Ptr modelItem = this->specification()->associations();
734
  smtk::model::Model model;
735
736
737

  internal::pmodel::Ptr storage; // Look up from session = internal::pmodel::create();
  bool ok = true;
David Thompson's avatar
David Thompson committed
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759

  Session* sess = this->polygonSession();
  smtk::model::ManagerPtr mgr;
  if (!sess || !(mgr = sess->manager()))
    {
    // error logging requires mgr...
    return this->createResult(smtk::model::OPERATION_FAILED);
    }
  // Keep a set of model edges marked by the directions in which they
  // should be used to form faces. This will constrain what faces
  // may be created without requiring users to pick a point interior
  // to the face.
  //
  // This way, when users specify oriented (CCW) point sequences or
  // a preferred set of edges as outer loop + inner loops, we don't
  // create faces that fill the holes.
  // But when users specify that all possible faces should be created,
  // they don't have to pick interior points.
  //
  // -1 = use only negative orientation
  //  0 = no preferred direction: use in either or both directions
  // +1 = use only positive orientation
760
  ModelEdgeMap modelEdgeMap;
David Thompson's avatar
David Thompson committed
761
762

  // First, collect or create edges to process:
763
764
765
766
767
  // These case values match CreateFaces.sbt indices (and enum values):
  switch (method)
    {
  case 0: // points, coordinates, offsets
      {
David Thompson's avatar
David Thompson committed
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
      // identify pre-existing model vertices from points
      // verify that existing edges/faces incident to model vertices
      //        do not impinge on proposed edge/face
      // run edge-creation pre-processing on each point-sequence?
      // determine sub-sequences of points that will
      //   (a) form new edges
      //   (b) make use of existing edges (with orientation)
      // determine loop nesting and edge splits required by intersecting loops
      // report point sequences, model vertices (existing, imposed by intersections, non-manifold), loops w/ nesting
      // ---
      // create new vertices as required
      // create edges on point sequences
      // modify/create vertex uses
      // create chains
      // create edge uses
      // create loops
      // create faces
785
786
      }
    break;
David Thompson's avatar
David Thompson committed
787
  case 1: // edges, points, coordinates
788
      {
David Thompson's avatar
David Thompson committed
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
      // for each edge
      //   for each model vertex
      //     walk loops where vertices have no face, aborting walk if an unselected edge is found.
      //     mark traversed regions and do not re-traverse
      //   OR IF NO MODEL VERTICES
      //     edge must be periodic and oriented properly... treat it as a loop to bound a hole+/^face-filling-the-hole.
      //     mark traversed regions and do not re-traverse
      //   determine loop nesting and edge splits required by intersecting loops
      //   report model vertices (imposed by intersections, non-manifold), loops w/ nesting
      // ---
      // create new vertices as required
      // modify vertex uses
      // create edge uses
      // create loops
      // create faces
804
805
806
807
      }
    break;
  case 2: // all non-overlapping
      {
808
      model = modelItem->value(0);
David Thompson's avatar
David Thompson committed
809
      smtk::model::Edges allEdges =
810
        model.cellsAs<smtk::model::Edges>();
David Thompson's avatar
David Thompson committed
811
812
813
814
      for (smtk::model::Edges::const_iterator it = allEdges.begin(); it != allEdges.end(); ++it)
        {
        modelEdgeMap[*it] = 0;
        }
David Thompson's avatar
David Thompson committed
815
816
      // Same as case 1 but with the set of all edges in model.
      //
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
      // Create a union-find struct
      // for each "model" vertex
      //   for each edge attached to each vertex
      //     add 2 union-find entries (UFEs), 1 per co-edge
      //     merge adjacent pairs of UFEs
      //     store UFEs on edges
      // For each loop, discover nestings and merge UFEs
      // For each edge
      //   For each unprocessed (nesting-wise) UFE
      //     Discover nesting via ray test
      //     Merge parent and child UFEs (if applicable)
      //     Add an (edge, coedge sign) tuple to a "face" identified by the given UFE
      // FIXME: Test for self-intersections?
      // FIXME: Deal w/ pre-existing faces?
      }
    break;
  default:
    ok = false;
    smtkInfoMacro(log(), "Unhandled construction method " << method << ".");
    break;
    }

839
840
  // Create an event queue and populate it with events
  // for each segment of each edge in modelEdgeMap.
841
842
  ModelEdgeMap::iterator modelEdgeIt;
  SweepEventSet eventQueue; // (QE) sorted into a queue by point-x, point-y, event-type, and then event-specific data.
David Thompson's avatar
David Thompson committed
843
844
  for (modelEdgeIt = modelEdgeMap.begin(); modelEdgeIt != modelEdgeMap.end(); ++modelEdgeIt)
    {
845
846
847
848
    std::cout << "Consider " << modelEdgeIt->first.name() << "\n";
    internal::EdgePtr erec =
      this->findStorage<internal::edge>(
        modelEdgeIt->first.entity());
David Thompson's avatar
David Thompson committed
849

850
851
    if (erec->pointsSize() < 2)
      continue; // Do not handle edges with < 2 points.
David Thompson's avatar
David Thompson committed
852

853
854
855
856
857
    internal::PointSeq::const_iterator pit = erec->pointsBegin();
    int seg = 0;
    internal::Point last = *pit;
    for (++pit; pit != erec->pointsEnd(); ++pit, ++seg)
      {
858
859
860
      eventQueue.insert(SweepEvent::SegmentStart(last, *pit, modelEdgeIt->first, seg));
      //eventQueue.insert(SweepEvent::SegmentEnd(*pit, modelEdgeIt->first, seg - 1));
      last = *pit;
861
      }
David Thompson's avatar
David Thompson committed
862
    }
863
  DumpEventQueue( "Initial", eventQueue);
864
865
866
867
868
869

  // The first event in eventQueue had better be a segment-start event.
  // So the first thing this event-loop should do is start processing edges.
  // As other edges are added, they must intersect all active edges
  // and add split events as required.
  std::set<SweepEvent>::iterator event;
870
871
872
873
874
875
876
877
878
879
  std::vector<SweepEvent> edgesToInsertAfterAdvance; // FIXME. Needed?
  FragmentArray fragments; // (FR)
  fragments.reserve(static_cast<size_t>(eventQueue.size() * 1.125)); // pre-allocate some space for additional segments

  internal::Point startPoint = eventQueue.begin()->point();
  startPoint.x(startPoint.x() - 1);
  SweeplinePosition sweepPosn(startPoint);
  ActiveSegmentTree activeEdges(
    EdgeFragmentComparator(fragments, sweepPosn)); // (IT)
  Neighborhood neighborhood(sweepPosn, fragments, eventQueue, activeEdges); // N(x)
880
881
882
883
884
885
886

  // Set the initial sweepline to before the beginning of the queue.
  bool shouldErase;
  for (
    event = eventQueue.begin();
    (event = eventQueue.begin()) != eventQueue.end();
    ConditionalErase(eventQueue, event, shouldErase))
David Thompson's avatar
David Thompson committed
887
    {
888
    shouldErase = true;
889
890
    neighborhood.advanceSweeplineTo(event->point()); // XXX URHERE
    event = eventQueue.begin(); // Advancing the sweepline may have changed the eventQueue.
891
    /*
892
893
    std::cout
      << "Event " << event->type() << " posn " << event->point().x() << " " << event->point().y()
894
895
896
897
898
899
900
901
902
903
904
905
      ;
    if (event->type() == SweepEvent::SEGMENT_START)
      {
      std::cout << " edge " << event->m_edge.entity().toString() << " seg " << event->m_indx << "\n";
      }
    else
      {
      std::cout
        << " fragment " << event->m_frag[0]
        << " (edge " << fragments[event->m_frag[0]].m_edge.entity().toString() << " seg " << fragments[event->m_frag[0]].m_segment << ")"
        << "\n";
      }
906
      */
907
908
909
    switch (event->type())
      {
    case SweepEvent::SEGMENT_START:
910
      this->processSegmentStart(*event, fragments, sweepPosn, activeEdges, edgesToInsertAfterAdvance, neighborhood);
911
912
913
914
915
916
917
918
      // Add to active edges:
      //   Test for intersection with existing edges
      //     If any, add SEGMENT_CROSS events.
      //   Add to list in proper place
      // If the edge is neighbors others in the active list, either:
      //   a. Add
      break;
    case SweepEvent::SEGMENT_END:
919
      this->processSegmentEnd(*event, fragments, neighborhood);
920
921
      break;
    case SweepEvent::SEGMENT_CROSS:
922
      this->processSegmentCross(*event, fragments, sweepPosn, activeEdges, edgesToInsertAfterAdvance, neighborhood);
923
924
      break;
      }
David Thompson's avatar
David Thompson committed
925
926
927
    }

  // Create vertex-use, chain, edge-use, loop, and face records
928
929
930
  smtk::model::OperatorResult result;
  if (ok)
    {
David Thompson's avatar
David Thompson committed
931
932
    result = this->createResult(smtk::model::OPERATION_SUCCEEDED);
    //this->addEntityToResult(result, model, CREATED);
933
    }
David Thompson's avatar
David Thompson committed
934

935
936
937
938
939
940
941
942
  if (!result)
    {
    result = this->createResult(smtk::model::OPERATION_FAILED);
    }

  return result;
}

943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
void CreateFaces::processNeighborhood(
  Neighborhood& n,
  RegionDefinitions& regions,
  RegionIdSet& regionIds)
{
}

void CreateFaces::processSegmentStart(
  const SweepEvent& event,
  FragmentArray& fragments,
  SweeplinePosition& sweepPosn,
  ActiveSegmentTree& activeEdges,
  SweepEventArray& edgesToInsertAfterAdvance,
  Neighborhood& n)
{
958
959
960
961
  // Create output fragment for new segment.
  // The m_hi point is altered as segment crossing are processed but the
  // region IDs of this segment will not change. The regions will be
  // unioned with other regions depending on neighborhood adjacency.
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
  static EdgeFragment blank;
  FragmentArray::size_type fragId = fragments.size();
  FragmentArray::iterator it = fragments.insert(fragments.end(), blank);
  it->m_edge = event.m_edge;
  it->m_segment = event.m_indx;
  it->m_edgeData = this->findStorage<internal::edge>(it->m_edge.entity());
  it->m_edgeData->pointsOfSegment(event.m_indx, it->m_lo, it->m_hi);
  it->m_sense = event.m_frag[0] > 0 ? true : false;
  if (it->m_lo > it->m_hi)
    {
    if (it->m_sense) { std::cout << "\nOoops, reversed frag sense\n\n"; }
    std::swap(it->m_lo, it->m_hi);
    }
  else if (!it->m_sense) { std::cout << "\nOoops, non-reversed frag sense\n\n"; }
  it->m_regionId[0] = it->m_regionId[1] = -1; // Indicate regions are unassigned.

  // Tell neighborhood:
  //   to insert fragment into incident edge ring
  //   to insert SEGMENT_END into activeEdges after neighborhood processed
  //      this will also trigger insertion of SEGMENT_CROSS events
  n.insertFragment(fragId, *it, it->m_hi);
  n.queueActiveEdge(fragId, *it);

  // Locate insertion point in activeEdges
  // Insert end event
  //   eventQueue.insert(SweepEvent::SegmentEnd(*pit, modelEdgeIt->first, seg - 1));
  // Insert fragment into neighborhood (and tell neighborhood to add it to activeEdges at end of processing)
  // Determine if/where fragment intersects neighbors in activeEdges
  // Insert cross events
}

void CreateFaces::processSegmentEnd(
  const SweepEvent& event,
  FragmentArray& fragments,
  Neighborhood& n)
{
  FragmentId fragId = event.m_frag[0];
  EdgeFragment& frag(fragments[fragId]);