Mesh.cpp 50.9 KB
Newer Older
1 2 3 4 5 6 7 8
#include "Mesh.hpp"

Mesh::Mesh(Sketch &sketch) {
    Boundary = sketch.boundary();

    for (size_t i = 0; i != sketch.size_curves(); ++i) {
        auto c = sketch.curve(i);
        if (!(c->for_construction())) {
9
            BoundaryConstraints.push_back(std::make_shared<BoundaryConstraint>(c));
10 11
        }
    }
12
    sort_constraints();
13 14 15 16 17

    for (size_t i = 0; i != sketch.size_contours(); ++i) {
        Contours.push_back(sketch.contour(i));
    }

18
    new_dart_constraint(0.0, 1.0, std::make_shared<BoundaryConstraint>(nullptr));
19 20 21 22
}

bool Mesh::are_intersecting(size_t ei, size_t ej) const {
    // TODO, Make more detailed return type enumeration
23
    if (is_constrained(ei) && curve_from_edge(ei) == curve_from_edge(ej)) {
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
        return false;
    }

    Point const v00 = base(ei);
    Point const v01 = tip(ei);
    Point const v10 = base(ej);
    Point const v11 = tip(ej);

    double xs0 = (v00.X + v01.X) / 2.0;
    double ys0 = (v00.Y + v01.Y) / 2.0;
    double xs1 = (v10.X + v11.X) / 2.0;
    double ys1 = (v10.Y + v11.Y) / 2.0;

    double xd0 = (v00.X - v01.X) / 2.0;
    double yd0 = (v00.Y - v01.Y) / 2.0;
    double xd1 = (v10.X - v11.X) / 2.0;
    double yd1 = (v10.Y - v11.Y) / 2.0;

    double d0 = xd0 * xd0 + yd0 * yd0;
    double d1 = xd1 * xd1 + yd1 * yd1;
    double cross = abs(xd0 * yd1 - xd1 * yd0);
    double tol = (d0 * d1) * FLT_EPSILON;

    if (cross < tol) {
        // Lines are nearly parallel
        // There are four possible minimum distance points between the lines

        double s, dx, dy, dmin = DBL_MAX;

        s = ((xd0 - xd1) * (xs0 - xs1) + (yd0 - yd1) * (ys0 - ys1)) /
            ((xd0 - xd1) * (xd0 - xd1) + (yd0 - yd1) * (yd0 - yd1));
        if (abs(s) < 1.0 - FLT_EPSILON) {
            dx = xs0 + xd0 * s - xs1 - xd1 * s;
            dy = ys0 + yd0 * s - ys1 - yd1 * s;
            dmin = std::fmin(dmin, dx * dx + dy * dy);

            dx = xs0 - xd0 * s - xs1 + xd1 * s;
            dy = ys0 - yd0 * s - ys1 + yd1 * s;
            dmin = std::fmin(dmin, dx * dx + dy * dy);
        }

        s = ((xd0 + xd1) * (xs0 - xs1) + (yd0 + yd1) * (ys0 - ys1)) /
            ((xd0 + xd1) * (xd0 + xd1) + (yd0 + yd1) * (yd0 + yd1));
        if (abs(s) < 1.0 - FLT_EPSILON) {
            dx = xs0 + xd0 * s - xs1 + xd1 * s;
            dy = ys0 + yd0 * s - ys1 + yd1 * s;
            dmin = std::fmin(dmin, dx * dx + dy * dy);

            dx = xs0 - xd0 * s - xs1 - xd1 * s;
            dy = ys0 - yd0 * s - ys1 - yd1 * s;
            dmin = std::fmin(dmin, dx * dx + dy * dy);
        }

        tol = (d0 + d1) * FLT_EPSILON;
        return (dmin < tol);
    } else { // Lines are not parallel
        double s0 = abs(xd1 * (ys0 - ys1) - yd1 * (xs0 - xs1));
        double s1 = abs(xd0 * (ys0 - ys1) - yd0 * (xs0 - xs1));
        tol = cross * (1.0 - FLT_EPSILON);

        return (s0 < tol && s1 < tol);
    }
}

88 89 90 91 92 93 94 95 96 97 98 99 100 101
bool Mesh::edges_are_optimal() const {
    /*
     * Returns true if all unconstrained edges satisfy the empty circumcircle property
     */

    for (size_t e = 0; e != Edges.size(); ++e) {
        if (!is_locally_optimal(e)) {
            return false;
        }
    }

    return true;
}

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
bool Mesh::edges_are_valid() const {
    bool result = true;

    for (size_t e = 0; e != Edges.size(); ++e) {
        if (e != prev(next(e))) {
            result = false;
            break;
        }
        if (e != next(prev(e))) {
            result = false;
            break;
        }
        if (e != twin(twin(e))) {
            result = false;
            break;
        }

        if ((e != twin(e))) {
            if (node(e) != node(next(twin(e)))) {
                result = false;
                break;
            }
124
            if (curve_from_edge(e) != curve_from_edge(twin(e))) {
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
                result = false;
                break;
            }
            if (is_constrained(e)) {
                if (orientation(e) == orientation(twin(e))) {
                    result = false;
                    break;
                }
            }

            if (node(e) == node(twin(e))) {
                result = false;
                break;
            }
        }

        if (is_constrained(e)) {
142
            DartConstraint dc = DartConstraints[Edges[e].Constraint];
143 144 145
            double tol = length(e) * FLT_EPSILON;
            if (orientation(e)) {
                Point p0 = base(e);
146
                Point p1 = dc.curve()->point(dc.S0);
147
                if (dist(p0, p1) > tol) {
148 149 150 151 152
                    result = false;
                    break;
                }

                p0 = tip(e);
153
                p1 = dc.curve()->point(dc.S1);
154
                if (dist(p0, p1) > tol) {
155 156 157 158 159
                    result = false;
                    break;
                }
            } else {
                Point p0 = base(e);
160
                Point p1 = dc.curve()->point(dc.S1);
161
                if (dist(p0, p1) > tol) {
162 163 164 165 166
                    result = false;
                    break;
                }

                p0 = tip(e);
167
                p1 = dc.curve()->point(dc.S0);
168
                if (dist(p0, p1) > tol) {
169 170 171 172 173 174 175 176 177 178 179 180 181
                    result = false;
                    break;
                }
            }
        }
    }

    return result;
}

bool Mesh::find_attached(Point const p, size_t &e_out) {
    double tol = length(e_out) * FLT_EPSILON;

182
    if (dist(tip(e_out), p) < tol) {
183 184 185 186 187 188 189 190
        return true;
    }

    size_t e_in = e_out;

    if (e_out != twin(e_out)) {
        e_out = next(twin(e_out));
        while (e_out != e_in) {
191
            if (dist(tip(e_out), p) < tol) {
192 193 194 195 196 197 198 199 200 201 202 203
                return true;
            } else if (e_out != twin(e_out)) {
                e_out = next(twin(e_out));
            } else {
                break;
            }
        }
    }

    if (e_out == twin(e_out)) {
        e_out = prev(e_in);
        while (e_out != twin(e_out)) {
204
            if (dist(base(e_out), p) < tol) {
205 206 207 208 209 210 211 212 213 214 215 216
                e_out = twin(e_out);
                return true;
            } else {
                e_out = prev(twin(e_out));
            }
        }
    }

    return false;
}

bool Mesh::refine() {
217 218 219 220 221 222 223 224 225 226 227 228 229
    /*
     * Iteratively refines the mesh based on user defined size and quality criteria
     *
     * TODO: Loop until quality is satisfied
     * TODO: Iteratively decrease the min and max element size until quality is satisfied
     * TODO: First: refine until maximum element size criteria is satisfied
     * TODO:        plan() out iterative maximum element size refinement
     * TODO: Then: refine until element quality criteria is satisfied
     * TODO:        ?somehow iterate?
     *
     * TODO: Implement sort permutation option
     */

230 231 232 233
    std::vector<double> radii;
    std::vector<double> quality;
    std::vector<size_t> index;

234 235 236 237
    size_t prev_points_size = 0;
    size_t smooth_threshold = Points.size() + Edges.size() / 3; // Heuristic, 3 Darts per triangle
    while (Points.size() > prev_points_size) {
        prev_points_size = Points.size();
238 239

        element_quality(radii, quality);
240 241
        // TODO: Implement sort permutation option
        //sort_permutation_ascending(quality, index);s
242
        sort_permutation_descending(radii, index);
243

244
        refine_once(index, radii, quality);
245 246 247 248 249 250 251
        if (Points.size() > smooth_threshold || Points.size() <= prev_points_size) { // if the loop will exit, performing a smoothing iteration
            enforce_boundary_mappings();
            smooth();
            smooth_threshold = Points.size() + Edges.size() / 3;
        }

        get_triangles();
252 253 254 255 256 257
    }

    return edges_are_valid(); // TODO: Instrument in tests
}

bool Mesh::refine_once() {
258 259 260 261
    /*
     * Performs one iteration of refinement without smoothing or enforcing boundary mapping constraints
     */

262 263 264 265 266 267 268 269
    std::vector<double> radii;
    std::vector<double> quality;
    std::vector<size_t> index;

    element_quality(radii, quality);
    //sort_permutation_ascending(quality, index);
    sort_permutation_descending(radii, index);
    refine_once(index, radii, quality);
270
    get_triangles();
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

    return edges_are_valid(); // TODO: Instrument in tests
}

bool Mesh::in_triangle(Point const p, size_t ei) const {
    double xp = p.X;
    double yp = p.Y;

    Point const p0 = base(ei);
    Point const p1 = base(next(ei));
    Point const p2 = base(prev(ei));

    double dx0p = p0.X - xp;
    double dy0p = p0.Y - yp;

    double dx1p = p1.X - xp;
    double dy1p = p1.Y - yp;

    double dx2p = p2.X - xp;
    double dy2p = p2.Y - yp;

    double dx01 = p0.X - p1.X;
    double dy01 = p0.Y - p1.Y;

    double dx12 = p1.X - p2.X;
    double dy12 = p1.Y - p2.Y;

    double dx20 = p2.X - p0.X;
    double dy20 = p2.Y - p0.Y;

    double area012 = dx01 * dy12 - dy01 * dx12;

    double tol = FLT_EPSILON * area012;

    double area01p = dx0p * dy1p - dx1p * dy0p;
    double area12p = dx1p * dy2p - dx2p * dy1p;
    double area20p = dx2p * dy0p - dx0p * dy2p;

    return (area01p > -tol && area12p > -tol && area20p > -tol);
}

bool Mesh::is_encroached(Point const p, size_t ei) const {
    /*
        A constrained edge is encroached if a triangle and it's circumcenter lie on opposite sides of the edge.
        This is equivalent to a node being in the diameteral ball of the edge?
        This only occurs if one of the triangles attached to the edge encroaches the edge?
        This only occurs if the angle of the triangles attached to the edge has an angle opposite the edge of greater than 90 degrees.
        Using the dot product, this requires that the normalized dot product < cos(90) = 0
    */

    if (!is_constrained(ei)) {
        return false;
    } else {
        Point const p0 = base(ei);
        Point const p1 = tip(ei);

        double dx0 = p0.X - p.X;
        double dy0 = p0.Y - p.Y;

        double dx1 = p1.X - p.X;
        double dy1 = p1.Y - p.Y;

        double dot = dx0 * dx1 + dy0 * dy1;
        double tol = std::sqrt(dx0 * dx0 + dy0 * dy0) * std::sqrt(dx1 * dx1 + dy1 * dy1) * FLT_EPSILON;

        return (dot < tol);
    }
}

bool Mesh::is_locally_optimal(size_t ei) const {
    /*
        See Chapter 3.7 of "Triangulations and Applications" by Øyvind Hjelle and Morten Dæhlen
    */

    if (is_constrained(ei)) {
        return true;
    } else {
        Point const p3 = base(ei);
        Point const p2 = base(prev(ei));
        Point const p1 = base(twin(ei));
        Point const p4 = base(prev(twin(ei)));

        double v1x = p3.X - p2.X;
        double v1y = p3.Y - p2.Y;
        double v2x = p1.X - p2.X;
        double v2y = p1.Y - p2.Y;
        double v3x = p1.X - p4.X;
        double v3y = p1.Y - p4.Y;
        double v4x = p3.X - p4.X;
        double v4y = p3.Y - p4.Y;

        double d1 = std::sqrt(v1x * v1x + v1y * v1y);
        double d2 = std::sqrt(v2x * v2x + v2y * v2y);
        double d3 = std::sqrt(v3x * v3x + v3y * v3y);
        double d4 = std::sqrt(v4x * v4x + v4y * v4y);
366
        double tol = -std::sqrt(d1 * d2 * d3 * d4) * FLT_EPSILON;
367 368 369 370 371 372 373

        double sina = v1x * v2y - v1y * v2x;
        double sinb = v3x * v4y - v3y * v4x;
        double cosa = v1x * v2x + v1y * v2y;
        double cosb = v3x * v4x + v3y * v4y;
        double cct = sina * cosb + cosa * sinb;

374
        return cct >= tol; // TODO: Optional tol for testing purposes
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
    }
}

bool Mesh::is_protruding(size_t ei) const {
    //
    //    See Chapter 1.4 of "Triangulations and Applications" by Øyvind Hjelle and Morten Dæhlen
    //

    Point const p0 = base(prev(ei));
    Point const p1 = base(ei);
    Point const p2 = base(next(ei));

    double v1x = p2.X - p1.X;
    double v1y = p2.Y - p1.Y;

    double v0x = p0.X - p1.X;
    double v0y = p0.Y - p1.Y;

    double area = v1x * v0y - v1y * v0x;

    if (area > 0.0) {
        // Make sure no boundary points interior to triangle
        // Calculate barrycentric coordinates of p

        size_t nxt = next(next(ei));
        while (nxt != prev(ei)) {
            Point const p4 = base(nxt);

            double v2x = p2.X - p4.X;
            double v2y = p2.Y - p4.Y;

            v1x = p1.X - p4.X;
            v1y = p1.Y - p4.Y;

            v0x = p0.X - p4.X;
            v0y = p0.Y - p4.Y;

            double b0 = (v0x * v1y - v0y * v1x);
            double b1 = (v1x * v2y - v1y * v2x);
            double b2 = (v2x * v0y - v2y * v0x);

            if (b0 >= 0.0 && b0 <= area && b1 >= 0.0 && b1 <= area && b2 >= 0.0 && b2 <= area) {
                return false;    // Point is interior to triangle
            } else {
                nxt = next(nxt);
            }
        }
        return true;
    } else {
        return false;
    }
}

bool Mesh::is_valid(size_t ei) const {
    bool value = true;

    value = value && (ei == prev(next(ei)));
    value = value && (ei == next(prev(ei)));
    value = value && (ei == twin(twin(ei)));

    return value;
}

bool Mesh::recursive_swap(size_t ei) {
    // TODO, May need to have two different recursive swap methods, one for midpoint insertion and one for circumcenter insertion
    if (!is_locally_optimal(ei) && swap(ei)) {
        size_t enext = next(ei);
        size_t eprev = prev(ei);
        size_t tnext = next(twin(ei));
        size_t tprev = prev(twin(ei));

        recursive_swap(enext);
        recursive_swap(eprev);
        recursive_swap(tnext);
        recursive_swap(tprev);

        return true;
    } else {
        return false;
    }
}

bool Mesh::swap(size_t ei) {
    if (!is_constrained(ei)) {
        Edge &e0 = Edges[ei];
        Edge &e1 = Edges[e0.Next];
        Edge &e2 = Edges[e0.Prev];
        Edge &e5 = Edges[e0.Twin];
        Edge &e3 = Edges[e5.Next];
        Edge &e4 = Edges[e5.Prev];

        e0.Node = e2.Node;
        e0.Next = e4.Self;
        e0.Prev = e1.Self;
        e0.Mark = false;

        e5.Node = e4.Node;
        e5.Next = e2.Self;
        e5.Prev = e3.Self;
        e5.Mark = false;

        e1.Next = e0.Self;
        e1.Prev = e4.Self;
        e1.Mark = false;

        e2.Next = e3.Self;
        e2.Prev = e0.Twin;
        e2.Mark = false;

        e3.Next = e0.Twin;
        e3.Prev = e2.Self;
        e3.Mark = false;

        e4.Next = e1.Self;
        e4.Prev = e0.Self;
        e4.Mark = false;

        return true;
    } else {
        Edges[ei].Mark = false;
        return false;
    }
}

double Mesh::circumradius(size_t ei) const {
    Point const slf = base(ei);
    Point const prv = base(prev(ei));
    Point const nxt = base(next(ei));

    double xa = slf.X;
    double ya = slf.Y;
    double xb = prv.X - xa;
    double yb = prv.Y - ya;
    double xc = nxt.X - xa;
    double yc = nxt.Y - ya;
    xa = xb - xc;
    ya = yb - yc;

    double den = 2.0 * abs(xb * yc - yb * xc);
    double num = std::sqrt(xa * xa + ya * ya) * std::sqrt(xb * xb + yb * yb) * std::sqrt(xc * xc + yc * yc);

    return num / den;
}

double Mesh::length(size_t ei) const {
    Point const p0 = base(ei);
    Point const p1 = tip(ei);

    double dx = p0.X - p1.X;
    double dy = p0.Y - p1.Y;

    return std::sqrt(dx * dx + dy * dy);
}

double Mesh::shortest_edge_length(size_t ei) const { // TODO: Rename Edge class to Dart
    Point const slf = base(ei);
    Point const prv = base(prev(ei));
    Point const nxt = base(next(ei));

    double x0 = slf.X;
    double y0 = slf.Y;
    double x1 = nxt.X;
    double y1 = nxt.Y;
    double x2 = prv.X;
    double y2 = prv.Y;

    double dx = x0 - x1;
    double dy = y0 - y1;
    double dl = dx * dx + dy * dy;

    dx = x1 - x2;
    dy = y1 - y2;
    dl = std::fmin(dl, dx * dx + dy * dy);

    dx = x2 - x0;
    dy = y2 - y0;
    dl = std::fmin(dl, dx * dx + dy * dy);

    return std::sqrt(dl);
}

size_t Mesh::num_edges() const {
    size_t count = 0;
    for (size_t e = 0; e != Edges.size(); ++e) {
        count += (e == twin(e) ? 2 : 1);
    }
    count /= 2;

    return count;
}

566 567 568 569 570 571 572 573 574 575 576
void Mesh::add_dart_to_queue(size_t d) {
    /*
     * Adds a Dart and all other darts encroached by its midpoint to the refinement queue
     */

    std::vector<size_t> encroached_darts = get_encroached_edges(midpoint(d), d);
    for (size_t ed : encroached_darts) {
        add_to_queue(std::make_unique<MidpointQueuer>(ed));
    }
}

577
void Mesh::create() {
578 579 580
    /*
     * Creates the initial mesh by inserting nodes only on the mesh constraint boundaries
     */
581
    create_boundary_polygon();
582

583 584 585
    triangulate_boundary_polygon();

    insert_internal_boundaries();
586 587 588

    enforce_boundary_mappings();

589 590 591 592 593 594 595 596 597 598
    get_triangles();
}

void Mesh::create_boundary_polygon() {
    // Create input edges
    Edges.reserve(Boundary->size());
    Points.reserve(Boundary->size());
    for (size_t i = 0; i != Boundary->size(); ++i) {
        std::shared_ptr<Curve const> cc = Boundary->curve(i);
        bool dir = Boundary->orientation(i);
599
        Edge &e = new_edge(Points.size(), DartConstraints.size(), dir); // TODO: change to new_edge(Edge)
600 601
        e.Twin = e.Self;

602
        DartConstraint &dc = new_dart_constraint(0.0, 1.0, boundary_constraint(cc));
603 604 605 606 607 608

        if (dir) {
            dc.forward_dart(e.self());
        } else {
            dc.reverse_dart(e.self());
        }
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
        Points.push_back(Point(dir ? cc->start() : cc->end()));
    }

    // Set Next/Prev edges from Boundary
    size_t Ne = 0;
    for (size_t i = 0; i != Edges.size(); ++i) {
        size_t j = (i + 1) % Edges.size();
        Edges[i].Next = Edges[j].Self;
        Edges[j].Prev = Edges[i].Self;
    }

    // Some edges may intersect due to discretization error
    // If two edges intersect, split the longest edge
    bool any_split = true;
    while (any_split) {
        any_split = false;
        for (size_t i = 0; i != Edges.size() - 1; ++i) {
            for (size_t j = i + 1; j != Edges.size(); ++j) {
                if (are_intersecting(i, j)) {
                    any_split = true;
                    if (length(i) > length(j)) {
                        split_edge(i);
                    } else {
                        split_edge(j);
                    }
                }
            }
        }
    }
}

void Mesh::element_quality(std::vector<double> &radii, std::vector<double> &quality) {
    radii.resize(0);
    quality.resize(0);

    radii.reserve(Triangles.size());
    quality.reserve(Triangles.size());
    for (size_t i = 0; i != Triangles.size(); ++i) {
648 649
        double r = circumradius(Triangles[i].Edge);
        double l = shortest_edge_length(Triangles[i].Edge);
650 651 652 653 654 655

        radii.push_back(r);
        quality.push_back(l / r / sqrt(3.0)); // sqrt(3.0) = (shortest edges length) / radius of equilateral triangle
    }
}

656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
void Mesh::enforce_boundary_mappings() {
    /*
     * Inserts nodes on boundaries until all boundary mapping constraints are satisfied
     *
     * TODO: Will this strategy converge for cyclical mappings?
     */

    bool all_enforced{false};
    while (!all_enforced) {
        all_enforced = true;
        for (auto &mb : MappedBoundaries) {
            all_enforced &= mb->enforce_mapping(*this);
        }
    }
}

672
void Mesh::get_triangles() {
673 674 675 676 677 678
    /*
     * Parses the mesh for darts representing unique triangles
     *
     * // TODO: Instead of starting from scratch for each iteration, sweep and mark existing triangles, then parse the remainder
     */

679 680 681 682
    Triangles.resize(0);
    Triangles.reserve(2 * num_points());

    for (auto &e : Edges) {
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
        e.Mark = true;
    }

    std::vector<size_t> edge_queue;
    std::vector<size_t> contours;
    edge_queue.reserve(2 * num_points());
    contours.reserve(2 * num_points());
    for (size_t contour_index = 0; contour_index != Contours.size(); ++contour_index) {
        edge_queue.resize(0);

        std::shared_ptr<Contour const> &contour = Contours[contour_index];
        std::shared_ptr<Curve const> c = contour->curve(0);
        std::shared_ptr<BoundaryConstraint> bc = boundary_constraint(c);
        DartConstraint const dc = dart_constraint(bc->dart(0));

        edge_queue.push_back(contour->orientation(0) ? dc.forward_dart() : dc.reverse_dart());
699
        while (edge_queue.size() > 0) {
700 701 702 703 704 705 706 707 708
            Edge &et = Edges[edge_queue.back()];
            Edge &en = Edges[et.next()];
            Edge &ep = Edges[et.prev()];

            edge_queue.pop_back();

            if (et.Mark) {
                Triangles.emplace_back(et.self(), contour_index);

709
                if (!en.is_constrained() && en.Mark) {
710 711 712 713
                    edge_queue.push_back(en.twin());
                    en.Mark = false;
                }

714
                if (!ep.is_constrained() && ep.Mark) {
715 716 717 718
                    edge_queue.push_back(ep.twin());
                    ep.Mark = false;
                }
            }
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
        }
    }
}

void Mesh::insert_internal_boundaries() {
    /*
        For each constraint curve :
            Add constraint curve to queue
            Insert endpoints if they do not exist.
                Will have to keep attempting insertion until no existing edge is encroached

            While the queue is not empty :
                Orbit the start point of the last curve in the queue :
                    If the end point is attached to the start point by some edge :
                        Set Edge->ConstraintCurve and->Orientation properties
                        Pop last curve from queue
                    Else
                        Split the last curve and add a new curve to the end of the queue

            Repeat until no edge is split :
                Orbit each edge, checking for encroachment by attached verticies
                If encroached, split edge
    */

743 744
    sort_constraints_by_length();

745
    // Find interior curves
746
    std::vector<size_t> interior_index;
747 748
    for (size_t i = 0; i != BoundaryConstraints.size(); ++i) {
        auto const &bc = BoundaryConstraints[i];
749 750
        bool on_exterior = false;
        for (size_t i = 0; i != Boundary->size(); ++i) {
751
            if (bc->curve() == Boundary->curve(i)) {
752 753 754 755 756 757
                on_exterior = true;
                break;
            }
        }

        if (!on_exterior) {
758
            interior_index.push_back(i);
759 760 761 762
        }
    }

    // Insert interior curve end points
763
    for (size_t i : interior_index) {
764
        // Insert start point
765
        Point p = BoundaryConstraints[i]->curve()->start();
766 767
        LocateTriangleResult result = locate_triangle(p);
        if (result == LocateTriangleResult::Interior) {
768 769 770 771
            while (add_point_to_queue(p) == AddToQueueResult::Midpoint) {
                insert_from_queue();
            }
            insert_from_queue();
772 773 774
        }

        // Insert end point
775
        p = BoundaryConstraints[i]->curve()->end();
776 777
        result = locate_triangle(p);
        if (result == LocateTriangleResult::Interior) {
778 779 780 781
            while (add_point_to_queue(p) == AddToQueueResult::Midpoint) {
                insert_from_queue();
            }
            insert_from_queue();
782 783 784
        }
    }

785 786
    // Attach edges to constraints by inserting interior curve midpoints until constraints are naturally satisfied
    std::vector<size_t> queue;
787
    for (size_t i : interior_index) {
788
        queue.push_back(DartConstraints.size());
789
        new_dart_constraint(0.0, 1.0, BoundaryConstraints[i]);
790
        while (queue.size() != 0) {
791
            DartConstraint &dc = DartConstraints[queue.back()];
792 793
            Point p0 = dc.curve()->point(dc.S0); // TODO: write Point Curve::point(double) and differentiate from Vertex Curve::vertex(double)
            Point p1 = dc.curve()->point(dc.S1);
794 795 796 797 798 799 800 801 802 803

            size_t ei = Edges.size() - 1;
            LocateTriangleResult result = locate_triangle(p0, ei);

            if (result != LocateTriangleResult::Point) {
                throw std::exception();
            }

            if (find_attached(p1, ei)) {
                Edge &e = Edges[ei];
804
                e.Constraint = dc.Self;
805
                e.Orientation = true;
806 807
                dc.forward_dart(e.self());

808
                Edge &et = Edges[e.Twin];
809
                et.Constraint = dc.Self;
810
                et.Orientation = false;
811
                dc.reverse_dart(et.self());
812 813 814 815 816 817

                queue.pop_back();
            } else {
                double s0 = dc.S0;
                double s1 = dc.S1;
                double sn = (s0 + s1) / 2.0;
818 819

                Point const p = dc.curve()->point(sn);
820 821 822

                dc.S1 = sn;

823 824 825 826 827 828 829
                queue.push_back(DartConstraints.size());
                new_dart_constraint(sn, s1, dc.boundary_constraint());

                while (add_point_to_queue(p) == AddToQueueResult::Midpoint) {
                    insert_from_queue();
                }
                insert_from_queue();
830 831 832 833
            }
        }
    }

834
    for (auto bc : BoundaryConstraints) { // Length based refinement
835
        bc->refine(*this, 0.01);
836 837
    }

838
    split_encroached_edges();
839

840 841 842 843 844 845
    for (auto bc: BoundaryConstraints) {
        if (bc->uniform_discretizaiton()) {
            bc->make_uniform(*this);
        }
    }

846
    sort_constraints();
847
    // TODO: Enforce BoundaryConstraint conditions (e.g. uniform discretization, boundary maps)
848 849
}

850 851 852 853 854 855 856 857 858 859
void Mesh::make_edges_optimal() {
    /*
     * Swaps edges in the triangulation until the circumcircle property is satisfied for all unconstrained edges
     */

    for (size_t i = 0; i != Edges.size(); ++i) {
        recursive_swap(i);
    }
}

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
void Mesh::mark_triangles() {
    for (size_t i = 0; i != Edges.size(); ++i) {
        Edges[i].Mark = true;
    }

    for (size_t i = 0; i != Edges.size(); ++i) {
        if (Edges[i].Mark && Edges[next(i)].Mark && Edges[prev(i)].Mark) {
            Edges[next(i)].Mark = false;
            Edges[prev(i)].Mark = false;
        }
    }
}

void Mesh::refine_once(std::vector<size_t> index, std::vector<double> radii, std::vector<double> quality) {
    for (size_t i = 0; i != Triangles.size(); ++i) {
        size_t j = index[i];
876
        if ((edge_from_triangle_index(j).Mark) && ((radii[j] > MaximumElementSize) || (radii[j] > MinimumElementSize && quality[j] < MinimumElementQuality))) {
877
            add_circumcenter_to_queue(Triangles[j].Edge);
878
            insert_from_queue();
879 880 881 882
        }
    }
}

883 884 885 886 887 888 889
void Mesh::insert_from_queue() {
    while (!Queue.empty()) {
        Queue.back()->insert(*this);
        Queue.pop_back();
    }
}

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
void Mesh::save_as(std::string path, std::string file_name) const {
    /*
        This is a stub for visualization
    */

    if (!boost::filesystem::exists(path)) {
        boost::filesystem::create_directories(path);
    }

    std::fstream fs;
    fs.open(path + file_name + ".oeme", std::fstream::out);

    for (size_t e = 0; e != Edges.size(); ++e) {
        Point const v0 = base(e);
        Point const v1 = base(next(e));
        Point const v2 = base(next(next(e)));
        fs << v0.X << ',' << v1.X << ',' << v2.X << ',' << v0.Y << ',' << v1.Y << ',' << v2.Y << '\n';
    }

909 910 911 912 913 914 915 916 917 918 919 920
    /*
    for (auto t : Triangles) {
        size_t e{t.edge()};

        Point const v0 = base(e);
        Point const v1 = base(next(e));
        Point const v2 = base(next(next(e)));

        fs << v0.X << ',' << v1.X << ',' << v2.X << ',' << v0.Y << ',' << v1.Y << ',' << v2.Y << '\n';
    }
    */

921 922 923
    fs.close();
}

924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 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 1001 1002 1003 1004 1005 1006
void Mesh::smooth() {
    /*
     * Moves unconstrained nodes in the triangulation so that the mesh satisfies a laplacian optimality condition
     *
     * TODO: Apply boundary conditions such that the A matrix is symmetric => can use Cholesky factorization
     * TODO: Could also use iterative method since current node locations give good initial guess
     * TODO: Could also think of this a discrete system, where the present implementation is an implicit time step
     * TODO:    The question then is, could we use an explicit time step and still have the smoothing converge?
     * TODO:    The question is equivalent to, what are the eigenvalues of the matrix?
     */

    size_t num_points = Points.size();

    std::vector<Eigen::Triplet<double_t>> triplets;
    Eigen::VectorXd b = Eigen::VectorXd::Zero(2 * num_points);
    Eigen::VectorXd q;

    for (auto &e_i : Edges) {
        bool node_is_constrained = e_i.is_constrained();
        auto e_j = e_i;
        while (!node_is_constrained) {
            e_j = next(twin(e_j));

            if (e_j == e_i) {
                break;
            }

            node_is_constrained = node_is_constrained || e_j.is_constrained();
        }

        if (node_is_constrained) {
            size_t n = node(e_i);
            Point p = Points[n];

            n *= 2;
            triplets.emplace_back(n + 0, n + 0, 1.0);
            triplets.emplace_back(n + 1, n + 1, 1.0);

            b(n + 0) += p.X;
            b(n + 1) += p.Y;
        } else {
            size_t n0 = 2 * node(e_i);
            size_t n1 = 2 * node(next(e_i));

            triplets.emplace_back(n0 + 0, n0 + 0, 1.0);
            triplets.emplace_back(n0 + 0, n1 + 0, -1.0);
            triplets.emplace_back(n0 + 1, n0 + 1, 1.0);
            triplets.emplace_back(n0 + 1, n1 + 1, -1.0);
        }
    }

    Eigen::SparseMatrix<double> A(2 * num_points, 2 * num_points);
    A.setFromTriplets(triplets.begin(), triplets.end());

    Eigen::SparseLU<Eigen::SparseMatrix<double>> LU;

    LU.compute(A);
    if(LU.info()!=Eigen::Success) {
        std::cerr << "Factorization of mesh smoothing matrix was not successful";
        return;
    }

    q = LU.solve(b);
    if(LU.info()!=Eigen::Success) {
        std::cerr << "Mesh smoothing equation could not be solved";
        return;
    }

    for (size_t i = 0; i != num_points; ++i) {
        size_t n = 2 * i;
        Points[i].X = q(n);
        Points[i].Y = q(n + 1);
    }

    make_edges_optimal();
    add_encroached_edges_to_queue_and_insert();

    if(!edges_are_optimal()) {
        std::cerr << "Edges are not optimal" << std::endl;
        throw;
    }
};

1007
void Mesh::sort_constraints() {
1008 1009 1010 1011 1012 1013 1014
    /*
     * Sorts BoundaryConstraints by pointer address for fast lookup
     */

    auto comp = [](std::shared_ptr<BoundaryConstraint> const &x, std::shared_ptr<BoundaryConstraint> const &y) {return (size_t) (x->curve().get()) < (size_t) (y->curve().get());};

    std::sort(BoundaryConstraints.begin(), BoundaryConstraints.end(), comp);
1015 1016
}

1017 1018 1019 1020 1021 1022 1023 1024 1025
void Mesh::sort_constraints_by_length() {
    /*
     * Sorts BoundaryConstraints by length for internal boundary insertion
     */
    auto comp = [](std::shared_ptr<BoundaryConstraint> const &x, std::shared_ptr<BoundaryConstraint> const &y) { return (x->curve()->length()) < (y->curve()->length()); };

    std::sort(BoundaryConstraints.begin(), BoundaryConstraints.end(), comp);
};

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
void Mesh::sort_permutation_ascending(std::vector<double> &values, std::vector<size_t> &index) const {
    index.resize(values.size());
    std::iota(index.begin(), index.end(), 0);
    std::sort(index.begin(), index.end(), [&](size_t i, size_t j) { return (values[i] < values[j]); });
}

void Mesh::sort_permutation_descending(std::vector<double> &values, std::vector<size_t> &index) const {
    index.resize(values.size());
    std::iota(index.begin(), index.end(), 0);
    std::sort(index.begin(), index.end(), [&](size_t i, size_t j) { return (values[i] > values[j]); });
}

void Mesh::split_edge(size_t ei) {
    /*
        Splits edge into two edges at the midpoint without creating any new triangles.
        Used for initial polygon refinement.

1043 1044
        // TODO: Rename to split_boundary_edge
    */
1045

1046 1047 1048
    if (!(is_constrained(ei) && ei == twin(ei))) { // TODO: write bool Edge::is_boundary()
        std::cerr << "Mesh::split_edge(size_t ei) should only be called on boundary edges" << std::endl;
        return;
1049 1050
    }

1051 1052 1053
    DartConstraint &dci = DartConstraints[Edges[ei].Constraint];
    double s0 = dci.S0;
    double s1 = dci.S1;
1054
    std::shared_ptr<Curve const> cc = dci.curve();
1055

1056 1057
    double sn = (s0 + s1) / 2.0;
    dci.S1 = sn;
1058

1059
    size_t c{DartConstraints.size()};
1060 1061
    new_dart_constraint(sn, s1, dci.boundary_constraint());
    Points.push_back(cc->point(sn));
1062

1063 1064 1065 1066 1067
    size_t itr = new_edges(1);
    Edge &newe = Edges[--itr];
    Edge &e = Edges[ei];
    Edge &nxt = Edges[e.Next];

1068 1069 1070
    DartConstraint &dcc = DartConstraints[c];
    DartConstraint &dce = DartConstraints[e.Constraint];

1071 1072 1073 1074
    // Constraint Curve
    newe.Orientation = e.Orientation;
    if (e.Orientation) {
        newe.Constraint = c;
1075 1076

        dcc.forward_dart(newe.self());
1077
    } else {
1078 1079
        newe.Constraint = e.Constraint;
        e.Constraint = c;
1080 1081 1082

        dce.reverse_dart(newe.self());
        dcc.reverse_dart(e.self());
1083
    }
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096

    // Connectivity
    newe.Node = Points.size() - 1;
    newe.Next = e.Next;
    newe.Prev = e.Self;
    newe.Twin = newe.Self;
    newe.Mark = false;

    nxt.Prev = newe.Self;
    nxt.Mark = false;

    e.Next = newe.Self;
    e.Mark = false;
1097 1098 1099
}

void Mesh::split_encroached_edges() {
1100 1101 1102 1103 1104 1105
    /*
     * Inserts the midpoints of all edges until they are no longer encroached
     *
     * // TODO: Review where this should be used versus add_encroached_edges_to_queue_and_insert
     */

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
    bool any_split = true;
    while (any_split) {
        any_split = false;
        for (size_t i = 0; i != Edges.size(); ++i) {
            if (is_constrained(i)) {
                if (is_encroached(base(prev(i)), i)) {
                    any_split = true;
                    insert_midpoint(i);
                }
            }
        }
    }
}

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
void Mesh::add_encroached_edges_to_queue_and_insert() {
    /*
     * Inserts the midpoints of all edges until they are no longer encroached
     */

    bool any_encroached = true;
    while (any_encroached) {
        any_encroached = false;
        size_t num_edges_at_start = Edges.size();
        for (size_t e = 0; e != num_edges_at_start; ++e) {
            if (is_constrained(e)) {
                if (is_encroached(base(prev(e)), e)) { // base(prev(e)) == node in triangle opposite of edge e
                    any_encroached = true;

                    std::vector<size_t> encroached_edges = get_encroached_edges(midpoint(e), e);
                    for (size_t ee : encroached_edges) {
                        Edges[ee].add_to_queue(*this);
                    }

                    insert_from_queue();
                }
            }
        }
        //insert_from_queue();
    }
}

1147
void Mesh::triangulate_boundary_polygon() {
1148 1149 1150 1151
    /*
     * Performs intial triangulation of the mesh boundary
     */

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
    Edges.reserve(3 * num_points());

    size_t i = 0;
    while (i != next(next(next(i)))) {
        if (is_protruding(i)) {
            size_t itr = new_edges(2);
            Edge &e1 = Edges[--itr];
            Edge &e0 = Edges[--itr];

            Edge &ei = Edges[i];
            Edge &nxt = Edges[ei.Next];
            Edge &prv = Edges[ei.Prev];

            Edge &prvprv = Edges[prv.Prev];

            // Edge of new triangle
            e0.Node = nxt.Node;
            e0.Prev = ei.Self;
            e0.Next = ei.Prev;
            e0.Twin = e1.Self;

            // Twin edge, part of new polygonal boundary
            e1.Node = prv.Node;
            e1.Next = ei.Next;
            e1.Prev = prv.Prev;
            e1.Twin = e0.Self;

            // Update polygonal boundary
            nxt.Prev = e1.Self;
            ei.Next = e0.Self;
            prvprv.Next = e1.Self;
            prv.Prev = e0.Self;

            // Next edge
            i = next(e1.Self);
        } else {
            i = next(i);
        }
    }

    // Edge swap to make triangulation Delaunay
1193
    make_edges_optimal();
1194 1195

    split_encroached_edges();
1196 1197 1198 1199 1200 1201 1202 1203 1204

    for (size_t i = 0; i != Boundary->size(); ++i) { // Length based-refinement of boundary curves
        std::shared_ptr<Curve const> cc = Boundary->curve(i);
        std::shared_ptr<BoundaryConstraint> bc = boundary_constraint(cc);
        bc->refine(*this, 0.01);
        if (bc->uniform_discretizaiton()) {
            bc->make_uniform(*this);
        }
    }
1205 1206 1207 1208 1209

    // Length based refinement
    for (auto bc : BoundaryConstraints) {
        bc->refine(*this, 0.01); // TODO: Tolerance must be chosen adaptively in order to account for local feature sizes, small gaps, etc.
    }
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
}

LocateTriangleResult Mesh::locate_triangle(Point const p, size_t &ei) const {
    double xp = p.X;
    double yp = p.Y;

    Point p0 = base(ei);
    Point p1 = base(next(ei));
    Point p2 = base(prev(ei));

    double dx0p = p0.X - xp;
    double dy0p = p0.Y - yp;

    double dx1p = p1.X - xp;
    double dy1p = p1.Y - yp;

    double dx2p = p2.X - xp;
    double dy2p = p2.Y - yp;

    double dx01 = p0.X - p1.X;
    double dy01 = p0.Y - p1.Y;

    double dx12 = p1.X - p2.X;
    double dy12 = p1.Y - p2.Y;

    double dx20 = p2.X - p0.X;
    double dy20 = p2.Y - p0.Y;

    double tol_a = FLT_EPSILON * (dx20 * dy01 - dy20 * dx01);
    double tol_l = FLT_EPSILON * sqrt(dx20 * dy01 - dy20 * dx01);

    double dist0 = sqrt(dx0p * dx0p + dy0p * dy0p);
    double dist1 = sqrt(dx1p * dx1p + dy1p * dy1p);
    double dist2 = sqrt(dx2p * dx2p + dy2p * dy2p);

    double area01 = dx0p * dy1p - dx1p * dy0p;
    double area12 = dx1p * dy2p - dx2p * dy1p;
    double area20 = dx2p * dy0p - dx0p * dy2p;

    if (dist0 < tol_l) {
        return LocateTriangleResult::Point;
    } else if (dist1 < tol_l) {
        ei = next(ei);
        return LocateTriangleResult::Point;
    } else if (dist2 < tol_l) {
        ei = prev(ei);
        return LocateTriangleResult::Point;
1257
    } else if (area01 > tol_a && area12 > tol_a && area20 > tol_a) {
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
        return LocateTriangleResult::Interior;
    } else if (area01 < -tol_a && ei != twin(ei)) {
        ei = twin(ei);
        p2 = p1;
        p1 = p0;
        p0 = p2;

        dx2p = dx1p;
        dx1p = dx0p;
        dx0p = dx2p;

        dy2p = dy1p;
        dy1p = dy0p;
        dy0p = dy2p;

        dx01 = -dx01;
        dy01 = -dy01;
    } else if (area12 < -tol_a && next(ei) != twin(next(ei))) {
        ei = twin(next(ei));
        p0 = p2;

        dx0p = dx2p;
        dy0p = dy2p;

        dx01 = -dx12;
        dy01 = -dy12;
    } else if (area20 < -tol_a && prev(ei) != twin(prev(ei))) {
        ei = twin(prev(ei));
        p1 = p2;

        dx1p = dx2p;
        dy1p = dy2p;

        dx01 = -dx20;
        dy01 = -dy20;
    } else if (area01 > -tol_a && area12 > tol_a && area20 > tol_a) {
        ei = twin(ei);
        return LocateTriangleResult::Interior;
    } else if (area01 > tol_a && area12 > -tol_a && area20 > tol_a) {
        ei = twin(next(ei));
        return LocateTriangleResult::Interior;
    } else if (area01 > tol_a && area12 > tol_a && area20 > -tol_a) {
        ei = twin(prev(ei));
        return LocateTriangleResult::Interior;
    } else if (area01 < -tol_a) {
        return LocateTriangleResult::Exterior;
    } else if (area12 < -tol_a) {
        ei = next(ei);
        return LocateTriangleResult::Exterior;
    } else if (area20 < -tol_a) {
        ei = prev(ei);
        return LocateTriangleResult::Exterior;
    } else {
        throw std::exception();
    }

    while (true) { // After first iteration, area01 > 0
        p2 = base(prev(ei));

        dx2p = p2.X - xp;
        dy2p = p2.Y - yp;

        dx12 = p1.X - p2.X;
        dy12 = p1.Y - p2.Y;

        dx20 = p2.X - p0.X;
        dy20 = p2.Y - p0.Y;

        tol_a = FLT_EPSILON * (dx20 * dy01 - dy20 * dx01);
        tol_l = FLT_EPSILON * sqrt(dx20 * dy01 - dy20 * dx01);

        dist2 = sqrt(dx2p * dx2p + dy2p * dy2p);

        area12 = dx1p * dy2p - dx2p * dy1p;
        area20 = dx2p * dy0p - dx0p * dy2p;

        if (dist2 < tol_l) {
            ei = prev(ei);
            return LocateTriangleResult::Point;
        } else if (area12 > tol_a && area20 > tol_a) {
            return LocateTriangleResult::Interior;
        } else if (area12 < -tol_a && next(ei) != twin(next(ei))) {
            ei = twin(next(ei));
            p0 = p2;

            dx0p = dx2p;
            dy0p = dy2p;

            dx01 = -dx12;
            dy01 = -dy12;
            continue;
        } else if (area20 < -tol_a && prev(ei) != twin(prev(ei))) {
            ei = twin(prev(ei));
            p1 = p2;

            dx1p = dx2p;
            dy1p = dy2p;

            dx01 = -dx20;
            dy01 = -dy20;
            continue;
        } else if (area12 > -tol_a && area20 > tol_a) {
            ei = twin(next(ei));
            return LocateTriangleResult::Interior;
        } else if (area12 > tol_a && area20 > -tol_a) {
            ei = twin(prev(ei));
            return LocateTriangleResult::Interior;
        } else if (area12 < -tol_a) {
            ei = next(ei);
            return LocateTriangleResult::Exterior;
        } else if (area20 < -tol_a) {
            ei = prev(ei);
            return LocateTriangleResult::Exterior;
        } else {
            throw std::exception();
        }
    }
}

1377 1378
AddToQueueResult Mesh::add_circumcenter_to_queue(size_t dart) {
    return add_point_to_queue(circumcenter(dart), dart);
1379 1380 1381 1382 1383 1384 1385 1386 1387
}

InsertPointResult Mesh::insert_midpoint(size_t ei) {
    /*
        Splits edge into two edges and creates two new triangles.
    */

    size_t c{0};
    if (is_constrained(ei)) { // Constrained Edge
1388
        c = DartConstraints.size();
1389

1390
        DartConstraint &dc = DartConstraints[Edges[ei].Constraint];
1391 1392
        double s0 = dc.S0;
        double s1 = dc.S1;
1393
        std::shared_ptr<Curve const> cc = dc.curve();
1394 1395 1396 1397

        double sn = (s0 + s1) / 2.0;
        dc.S1 = sn;

1398
        new_dart_constraint(sn, s1, dc.boundary_constraint());
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
        Points.push_back(cc->point(sn));
    } else { // Unconstrained Edge
        Point const p0 = base(ei);
        Point const p1 = tip(ei);
        Points.push_back(Point((p0.X + p1.X) / 2.0, (p0.Y + p1.Y) / 2.0));
    }

    if (ei == twin(ei)) { // Boundary Edge
        size_t itr = new_edges(3);
        Edge &e2 = Edges[--itr];
        Edge &e1 = Edges[--itr];
        Edge &e0 = Edges[--itr];

        Edge &e = Edges[ei];
        Edge &nxt = Edges[e.Next];
        Edge &prv = Edges[e.Prev];

1416 1417 1418
        DartConstraint &dcc = DartConstraints[c];
        DartConstraint &dce = DartConstraints[e.Constraint];