CreateFaces.cxx 29.4 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
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

  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.
  int m_regionId[2]; // Union-Find region to each side of edge; 0: region CCW of edge, 1: region CW of edge.
};

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)
    {
    }
  /// 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.
typedef std::map<RegionIdSet::value_type,Region> RegionDefinitions;

/**\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;

  void insertFragment(FragmentId fragId, EdgeFragment& frag, const internal::Point& other)
    { // find where fragId belongs in ring
    }

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

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

  void processQueue()
    {
    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();
    }

  /**\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);
      }
    }
456
457
458
};

#if 0
David Thompson's avatar
David Thompson committed
459
static void AddLoopsForEdge(
460
  CreateFaces* op,
461
462
  ModelEdgeMap& modelEdgeMap,
  ModelEdgeMap::iterator edgeInfo,
463
  LoopsById& loops,
David Thompson's avatar
David Thompson committed
464
465
466
467
  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.
)
{
468
  if (!edgeInfo->first.isValid() || !op)
David Thompson's avatar
David Thompson committed
469
470
471
    {
    return; // garbage-in? garbage-out.
    }
472
  internal::EdgePtr edgeRec = op->findStorage<internal::edge>(edgeInfo->first.entity());
David Thompson's avatar
David Thompson committed
473
474
475
476
477
478
479
480
481
482

  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.
    }
}
483
484
485
486
487
488
489
490
#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
491

492
493
494
495
496
497
498
499
500
501
502
void DumpEventQueue(SweepEventSet& eventQueue)
{
  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";
}

503
504
505
506
507
508
509
510
511
512
513
514
515
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();
516
  smtk::model::Model model;
517
518
519

  internal::pmodel::Ptr storage; // Look up from session = internal::pmodel::create();
  bool ok = true;
David Thompson's avatar
David Thompson committed
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541

  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
542
  ModelEdgeMap modelEdgeMap;
David Thompson's avatar
David Thompson committed
543
544

  // First, collect or create edges to process:
545
546
547
548
549
  // These case values match CreateFaces.sbt indices (and enum values):
  switch (method)
    {
  case 0: // points, coordinates, offsets
      {
David Thompson's avatar
David Thompson committed
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
      // 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
567
568
      }
    break;
David Thompson's avatar
David Thompson committed
569
  case 1: // edges, points, coordinates
570
      {
David Thompson's avatar
David Thompson committed
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
      // 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
586
587
588
589
      }
    break;
  case 2: // all non-overlapping
      {
590
      model = modelItem->value(0);
David Thompson's avatar
David Thompson committed
591
      smtk::model::Edges allEdges =
592
        model.cellsAs<smtk::model::Edges>();
David Thompson's avatar
David Thompson committed
593
594
595
596
      for (smtk::model::Edges::const_iterator it = allEdges.begin(); it != allEdges.end(); ++it)
        {
        modelEdgeMap[*it] = 0;
        }
David Thompson's avatar
David Thompson committed
597
598
      // Same as case 1 but with the set of all edges in model.
      //
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
      // 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;
    }

621
622
  // Create an event queue and populate it with events
  // for each segment of each edge in modelEdgeMap.
623
624
  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
625
626
  for (modelEdgeIt = modelEdgeMap.begin(); modelEdgeIt != modelEdgeMap.end(); ++modelEdgeIt)
    {
627
628
629
630
    std::cout << "Consider " << modelEdgeIt->first.name() << "\n";
    internal::EdgePtr erec =
      this->findStorage<internal::edge>(
        modelEdgeIt->first.entity());
David Thompson's avatar
David Thompson committed
631

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

635
636
637
638
639
    internal::PointSeq::const_iterator pit = erec->pointsBegin();
    int seg = 0;
    internal::Point last = *pit;
    for (++pit; pit != erec->pointsEnd(); ++pit, ++seg)
      {
640
641
642
      eventQueue.insert(SweepEvent::SegmentStart(last, *pit, modelEdgeIt->first, seg));
      //eventQueue.insert(SweepEvent::SegmentEnd(*pit, modelEdgeIt->first, seg - 1));
      last = *pit;
643
      }
David Thompson's avatar
David Thompson committed
644
    }
645
  DumpEventQueue(eventQueue);
646
647
648
649
650
651

  // 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;
652
653
654
655
656
657
658
659
660
661
  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)
662
663
664
665
666
667
668

  // 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
669
    {
670
    shouldErase = true;
671
672
    neighborhood.advanceSweeplineTo(event->point()); // XXX URHERE
    event = eventQueue.begin(); // Advancing the sweepline may have changed the eventQueue.
673
674
    std::cout
      << "Event " << event->type() << " posn " << event->point().x() << " " << event->point().y()
675
676
677
678
679
680
681
682
683
684
685
686
      ;
    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";
      }
687
688
689
    switch (event->type())
      {
    case SweepEvent::SEGMENT_START:
690
      this->processSegmentStart(*event, fragments, sweepPosn, activeEdges, edgesToInsertAfterAdvance, neighborhood);
691
692
693
694
695
696
697
698
      // 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:
699
      this->processSegmentEnd(*event, fragments, neighborhood);
700
701
      break;
    case SweepEvent::SEGMENT_CROSS:
702
      this->processSegmentCross(*event, fragments, sweepPosn, activeEdges, edgesToInsertAfterAdvance, neighborhood);
703
704
      break;
      }
David Thompson's avatar
David Thompson committed
705
706
707
    }

  // Create vertex-use, chain, edge-use, loop, and face records
708
709
710
  smtk::model::OperatorResult result;
  if (ok)
    {
David Thompson's avatar
David Thompson committed
711
712
    result = this->createResult(smtk::model::OPERATION_SUCCEEDED);
    //this->addEntityToResult(result, model, CREATED);
713
    }
David Thompson's avatar
David Thompson committed
714

715
716
717
718
719
720
721
722
  if (!result)
    {
    result = this->createResult(smtk::model::OPERATION_FAILED);
    }

  return result;
}

723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
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)
{
  // Create fragment for new segment:
  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_lo = it->m_edgeData)[event.m_frag[0] > 0 ? event.m_indx : event.m_indx + 1];
  //it->m_hi = it->m_edgeData)[event.m_frag[0] > 0 ? event.m_indx + 1 : event.m_indx];
  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]);

  // Add fragment to neighborhood
  n.insertFragment(fragId, frag, frag.m_lo);

  // Find neighbors of fragment in activeEdges
  // Remove fragment from activeEdges
  // If neighbors intersect, add crossing to event queue
  n.removeActiveEdge(fragId, frag);
}

void CreateFaces::processSegmentCross(
  const SweepEvent& event,
  FragmentArray& fragments,
  SweeplinePosition& sweepPosn,
  ActiveSegmentTree& activeEdges,
  SweepEventArray& edgesToInsertAfterAdvance,
  Neighborhood& n)
{
  // Say fragment s and t intersect at x with s < t to the left of x.
  //
  // Be careful not to put activeEdges into an invalid state by either
  // + advancing the sweep position before removing fragments s and t.
  // + inserting new fragments before advancing sweep position.
  //
  // Advance sweepline before queueing new intersections...
  // except we can't guarantee that there aren't more events at
  // this sweep location.
  // So, we have the neighborhood add fragments to the "right" of x to activeEdges
  // during processNeighborhood.
  /*
  // If segment r exists and intersects s, remove r-s cross event
  if (edgeR.isValid())
    {
    SweepEvent::RemoveCrossing(queue, fragR, fragS);
    neighborhood.queueCrossing(edgeR, segR, edgeT, segT);
    }
  // If segment u exists and intersects t, remove t-u cross event
  if (edgeU.isValid())
    {
    SweepEvent::RemoveCrossing(queue, fragT, fragU);
    neighborhood.queueCrossing(edgeS, segS, edgeU, segU);
    }
  // If segment r exists and intersects t, add r-t cross event
  // If segment u exists and intersects s, add s-u cross event
  */
  for (int i = 0; i < 2; ++i)
    {
    }
  //---
  // For each intersecting fragment,
  //   If intersection is not at endpoint,
  //     Create new fragment (cross_pt to fragment_hi)
  //     Modify fragment_hi to be cross_pt
  //     Insert new fragment start event and end event
  //     Insert new fragment into activeEdges
  //     Insert new fragment into neighborhood
  //  Remove existing intersections of segment with existing neighbors
}

838
839
840
841
842
843
844
845
846
847
848
    } // namespace polygon
  } //namespace bridge
} // namespace smtk

smtkImplementsModelOperator(
  SMTKPOLYGONSESSION_EXPORT,
  smtk::bridge::polygon::CreateFaces,
  polygon_create_faces,
  "create faces",
  CreateFaces_xml,
  smtk::bridge::polygon::Session);