conformalVoronoiMesh.C 48.2 KB
Newer Older
1 2 3 4
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
OpenFOAM bot's avatar
OpenFOAM bot committed
5
    \\  /    A nd           | www.openfoam.com
6
     \\/     M anipulation  |
OpenFOAM bot's avatar
OpenFOAM bot committed
7
-------------------------------------------------------------------------------
OpenFOAM bot's avatar
OpenFOAM bot committed
8
    Copyright (C) 2012-2016 OpenFOAM Foundation
9
    Copyright (C) 2020 OpenCFD Ltd.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "conformalVoronoiMesh.H"
#include "initialPointsMethod.H"
#include "relaxationModel.H"
#include "faceAreaWeightModel.H"
#include "meshSearch.H"
#include "vectorTools.H"
#include "IOmanip.H"
#include "indexedCellChecks.H"
37 38
#include "controlMeshRefinement.H"
#include "smoothAlignmentSolver.H"
laurence's avatar
laurence committed
39
#include "OBJstream.H"
40
#include "indexedVertexOps.H"
41
#include "DelaunayMeshTools.H"
42 43 44 45 46

// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

namespace Foam
{
47
    defineTypeNameAndDebug(conformalVoronoiMesh, 0);
48 49
}

50 51 52 53 54
const Foam::Enum
<
    Foam::conformalVoronoiMesh::dualMeshPointType
>
Foam::conformalVoronoiMesh::dualMeshPointTypeNames_
Mark Olesen's avatar
Mark Olesen committed
55
({
56 57 58 59 60
    { dualMeshPointType::internal, "internal" },
    { dualMeshPointType::surface, "surface" },
    { dualMeshPointType::featureEdge, "featureEdge" },
    { dualMeshPointType::featurePoint, "featurePoint" },
    { dualMeshPointType::constrained, "constrained" },
Mark Olesen's avatar
Mark Olesen committed
61
});
62

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

// * * * * * * * * * * * * Private Member Functions  * * * * * * * * * * * * //

void Foam::conformalVoronoiMesh::cellSizeMeshOverlapsBackground() const
{
    const cellShapeControlMesh& cellSizeMesh =
        cellShapeControl_.shapeControlMesh();

    DynamicList<Foam::point> pts(number_of_vertices());

    for
    (
        Delaunay::Finite_vertices_iterator vit = finite_vertices_begin();
        vit != finite_vertices_end();
        ++vit
    )
    {
80
        if (vit->internalOrBoundaryPoint() && !vit->referred())
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
        {
            pts.append(topoint(vit->point()));
        }
    }

    boundBox bb(pts);

    boundBox cellSizeMeshBb = cellSizeMesh.bounds();

    bool fullyContained = true;

    if (!cellSizeMeshBb.contains(bb))
    {
        Pout<< "Triangulation not fully contained in cell size mesh."
            << endl;

        Pout<< "Cell Size Mesh Bounds = " << cellSizeMesh.bounds() << endl;
98
        Pout<< "foamyHexMesh Bounds         = " << bb << endl;
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

        fullyContained = false;
    }

    reduce(fullyContained, andOp<unsigned int>());

    Info<< "Triangulation is "
        << (fullyContained ? "fully" : "not fully")
        << " contained in the cell size mesh"
        << endl;
}


void Foam::conformalVoronoiMesh::insertInternalPoints
(
    List<Point>& points,
    bool distribute
)
{
    label nPoints = points.size();

    if (Pstream::parRun())
    {
        reduce(nPoints, sumOp<label>());
    }

    Info<< "    " << nPoints << " points to insert..." << endl;

    if (Pstream::parRun() && distribute)
    {
        List<Foam::point> transferPoints(points.size());

        forAll(points, pI)
        {
            transferPoints[pI] = topoint(points[pI]);
        }

        // Send the points that are not on this processor to the appropriate
        // place
        Foam::autoPtr<Foam::mapDistribute> map
        (
            decomposition_().distributePoints(transferPoints)
        );

143 144
        transferPoints.clear();

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        map().distribute(points);
    }

    label nVert = number_of_vertices();

    insert(points.begin(), points.end());

    label nInserted(number_of_vertices() - nVert);

    if (Pstream::parRun())
    {
        reduce(nInserted, sumOp<label>());
    }

    Info<< "    " << nInserted << " points inserted"
        << ", failed to insert " << nPoints - nInserted
        << " ("
laurence's avatar
laurence committed
162
        << 100.0*(nPoints - nInserted)/(nInserted + SMALL)
163 164 165 166 167 168 169 170 171
        << " %)"<< endl;

    for
    (
        Delaunay::Finite_vertices_iterator vit = finite_vertices_begin();
        vit != finite_vertices_end();
        ++vit
    )
    {
172
        if (CGAL::indexedVertexOps::uninitialised(vit))
173 174 175 176 177 178 179 180
        {
            vit->index() = getNewVertexIndex();
            vit->type() = Vb::vtInternal;
        }
    }
}


181
Foam::Map<Foam::label> Foam::conformalVoronoiMesh::insertPointPairs
182 183
(
    List<Vb>& vertices,
184 185
    bool distribute,
    bool reIndex
186 187 188 189
)
{
    if (Pstream::parRun() && distribute)
    {
190 191 192 193 194 195 196 197
        autoPtr<mapDistribute> mapDist =
            decomposition_().distributePoints(vertices);

        // Re-index the point pairs if one or both have been distributed.
        // If both, remove

        // If added a point, then need to know its point pair
        // If one moved, then update procIndex locally
198 199 200 201 202 203 204

        forAll(vertices, vI)
        {
            vertices[vI].procIndex() = Pstream::myProcNo();
        }
    }

205 206
    label preReinsertionSize(number_of_vertices());

207 208
    Map<label> oldToNewIndices =
        this->DelaunayMesh<Delaunay>::insertPoints(vertices, reIndex);
209 210 211 212 213

    const label nReinserted = returnReduce
    (
        label(number_of_vertices()) - preReinsertionSize,
        sumOp<label>()
214
    );
215 216 217 218

    Info<< "    Reinserted " << nReinserted << " vertices out of "
        << returnReduce(vertices.size(), sumOp<label>())
        << endl;
219 220

    return oldToNewIndices;
221 222 223 224 225 226
}


void Foam::conformalVoronoiMesh::insertSurfacePointPairs
(
    const pointIndexHitAndFeatureList& surfaceHits,
227 228
    const fileName fName,
    DynamicList<Vb>& pts
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
)
{
    forAll(surfaceHits, i)
    {
        vectorField norm(1);

        const pointIndexHit surfaceHit = surfaceHits[i].first();
        const label featureIndex = surfaceHits[i].second();

        allGeometry_[featureIndex].getNormal
        (
            List<pointIndexHit>(1, surfaceHit),
            norm
        );

        const vector& normal = norm[0];

        const Foam::point& surfacePt(surfaceHit.hitPoint());

laurence's avatar
laurence committed
248 249 250 251
        extendedFeatureEdgeMesh::sideVolumeType meshableSide =
            geometryToConformTo_.meshableSide(featureIndex, surfaceHit);

        if (meshableSide == extendedFeatureEdgeMesh::BOTH)
252 253 254 255 256 257
        {
            createBafflePointPair
            (
                pointPairDistance(surfacePt),
                surfacePt,
                normal,
258
                true,
259 260 261
                pts
            );
        }
laurence's avatar
laurence committed
262
        else if (meshableSide == extendedFeatureEdgeMesh::INSIDE)
263 264 265 266 267 268
        {
            createPointPair
            (
                pointPairDistance(surfacePt),
                surfacePt,
                normal,
269
                true,
270 271 272
                pts
            );
        }
laurence's avatar
laurence committed
273 274 275 276 277 278 279
        else if (meshableSide == extendedFeatureEdgeMesh::OUTSIDE)
        {
            createPointPair
            (
                pointPairDistance(surfacePt),
                surfacePt,
                -normal,
280
                true,
laurence's avatar
laurence committed
281 282 283 284 285
                pts
            );
        }
        else
        {
286 287
            WarningInFunction
                << meshableSide << ", bad"
laurence's avatar
laurence committed
288 289
                << endl;
        }
290 291
    }

292
    if (foamyHexMeshControls().objOutput() && fName != fileName::null)
293
    {
294
        DelaunayMeshTools::writeOBJ(time().path()/fName, pts);
295 296 297 298 299 300 301
    }
}


void Foam::conformalVoronoiMesh::insertEdgePointGroups
(
    const pointIndexHitAndFeatureList& edgeHits,
302 303
    const fileName fName,
    DynamicList<Vb>& pts
304 305 306 307
)
{
    forAll(edgeHits, i)
    {
308 309 310 311 312 313
        if (edgeHits[i].first().hit())
        {
            const extendedFeatureEdgeMesh& feMesh
            (
                geometryToConformTo_.features()[edgeHits[i].second()]
            );
314

315 316 317 318 319 320 321 322 323 324
//            const bool isBaffle =
//                geometryToConformTo_.isBaffleFeature(edgeHits[i].second());

            createEdgePointGroup
            (
                feMesh,
                edgeHits[i].first(),
                pts
            );
        }
325 326
    }

327
    if (foamyHexMeshControls().objOutput() && fName != fileName::null)
328
    {
329
        DelaunayMeshTools::writeOBJ(time().path()/fName, pts);
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    }
}


bool Foam::conformalVoronoiMesh::nearFeaturePt(const Foam::point& pt) const
{
    scalar exclusionRangeSqr = featurePointExclusionDistanceSqr(pt);

    pointIndexHit info;
    label featureHit;

    geometryToConformTo_.findFeaturePointNearest
    (
        pt,
        exclusionRangeSqr,
        info,
        featureHit
    );

    return info.hit();
}


353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
bool Foam::conformalVoronoiMesh::surfacePtNearFeatureEdge
(
    const Foam::point& pt
) const
{
    scalar exclusionRangeSqr = surfacePtExclusionDistanceSqr(pt);

    pointIndexHit info;
    label featureHit;

    geometryToConformTo_.findEdgeNearest
    (
        pt,
        exclusionRangeSqr,
        info,
        featureHit
    );

    return info.hit();
}


375 376 377 378 379 380 381 382 383 384 385 386 387
void Foam::conformalVoronoiMesh::insertInitialPoints()
{
    Info<< nl << "Inserting initial points" << endl;

    timeCheck("Before initial points call");

    List<Point> initPts = initialPointsMethod_->initialPoints();

    timeCheck("After initial points call");

    // Assume that the initial points method made the correct decision for
    // which processor each point should be on, so give distribute = false
    insertInternalPoints(initPts);
laurence's avatar
laurence committed
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

    if (initialPointsMethod_->fixInitialPoints())
    {
        for
        (
            Finite_vertices_iterator vit = finite_vertices_begin();
            vit != finite_vertices_end();
            ++vit
        )
        {
            vit->fixed() = true;
        }
    }

    if (foamyHexMeshControls().objOutput())
    {
404
        DelaunayMeshTools::writeOBJ
laurence's avatar
laurence committed
405
        (
406 407
            time().path()/"initialPoints.obj",
            *this,
laurence's avatar
laurence committed
408 409 410
            Foam::indexedVertexEnum::vtInternal
        );
    }
411 412 413 414 415 416 417
}


void Foam::conformalVoronoiMesh::distribute()
{
    if (!Pstream::parRun())
    {
418
        return;
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
    }

    DynamicList<Foam::point> points(number_of_vertices());
    DynamicList<Foam::indexedVertexEnum::vertexType> types
    (
        number_of_vertices()
    );
    DynamicList<scalar> sizes(number_of_vertices());
    DynamicList<tensor> alignments(number_of_vertices());

    for
    (
        Finite_vertices_iterator vit = finite_vertices_begin();
        vit != finite_vertices_end();
        ++vit
    )
    {
        if (vit->real())
        {
            points.append(topoint(vit->point()));
            types.append(vit->type());
            sizes.append(vit->targetCellSize());
            alignments.append(vit->alignment());
        }
    }

445 446 447
    autoPtr<mapDistribute> mapDist =
        DistributedDelaunayMesh<Delaunay>::distribute(decomposition_(), points);

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    mapDist().distribute(types);
    mapDist().distribute(sizes);
    mapDist().distribute(alignments);

    // Reset the entire tessellation
    DelaunayMesh<Delaunay>::reset();

    Info<< nl << "    Inserting distributed tessellation" << endl;

    // Internal points have to be inserted first

    DynamicList<Vb> verticesToInsert(points.size());

    forAll(points, pI)
    {
        verticesToInsert.append
        (
            Vb
            (
467
                toPoint(points[pI]),
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
                -1,
                types[pI],
                Pstream::myProcNo()
            )
        );

        verticesToInsert.last().targetCellSize() = sizes[pI];
        verticesToInsert.last().alignment() = alignments[pI];
    }

    this->rangeInsertWithInfo
    (
        verticesToInsert.begin(),
        verticesToInsert.end(),
        true
    );

    Info<< "    Total number of vertices after redistribution "
        << returnReduce
           (
               label(number_of_vertices()), sumOp<label>()
           )
        << endl;
}


void Foam::conformalVoronoiMesh::buildCellSizeAndAlignmentMesh()
{
496 497 498 499 500 501 502 503 504 505 506
    controlMeshRefinement meshRefinement
    (
        cellShapeControl_
    );

    smoothAlignmentSolver meshAlignmentSmoother
    (
        cellShapeControl_.shapeControlMesh()
    );

    meshRefinement.initialMeshPopulation(decomposition_);
507 508 509 510 511

    cellShapeControlMesh& cellSizeMesh = cellShapeControl_.shapeControlMesh();

    if (Pstream::parRun())
    {
512 513 514
        if (!distributeBackground(cellSizeMesh))
        {
            // Synchronise the cell size mesh if it has not been distributed
515
            cellSizeMesh.distribute(decomposition_());
516
        }
517 518
    }

519 520 521
    const dictionary& motionControlDict
        = foamyHexMeshControls().foamyHexMeshDict().subDict("motionControl");

522 523
    const label nMaxIter =
        motionControlDict.get<label>("maxRefinementIterations");
524 525 526 527 528

    Info<< "Maximum number of refinement iterations : " << nMaxIter << endl;

    for (label i = 0; i < nMaxIter; ++i)
    {
529 530
        label nAdded = meshRefinement.refineMesh(decomposition_);
        //cellShapeControl_.refineMesh(decomposition_);
531 532 533 534
        reduce(nAdded, sumOp<label>());

        if (Pstream::parRun())
        {
535
            cellSizeMesh.distribute(decomposition_());
536 537 538 539 540
        }

        Info<< "    Iteration " << i
            << " Added = " << nAdded << " points"
            << endl;
541 542 543 544 545

        if (nAdded == 0)
        {
            break;
        }
546 547
    }

548 549 550 551 552
    if (Pstream::parRun())
    {
        // Need to distribute the cell size mesh to cover the background mesh
        if (!distributeBackground(cellSizeMesh))
        {
553
            cellSizeMesh.distribute(decomposition_());
554 555 556
        }
    }

557
    meshAlignmentSmoother.smoothAlignments
558
    (
559
        motionControlDict.get<label>("maxSmoothingIterations")
560
    );
561 562 563 564

    Info<< "Background cell size and alignment mesh:" << endl;
    cellSizeMesh.printInfo(Info);

565 566 567 568
    Info<< "Triangulation is "
        << (cellSizeMesh.is_valid() ? "valid" : "not valid!" )
        << endl;

laurence's avatar
laurence committed
569
    if (foamyHexMeshControls().writeCellShapeControlMesh())
570
    {
571
        //cellSizeMesh.writeTriangulation();
572 573
        cellSizeMesh.write();
    }
574

575
    if (foamyHexMeshControls().printVertexInfo())
576 577 578
    {
        cellSizeMesh.printVertexInfo(Info);
    }
579 580 581 582 583 584 585 586

//    Info<< "Estimated number of cells in final mesh = "
//        << returnReduce
//           (
//               cellSizeMesh.estimateCellCount(decomposition_),
//               sumOp<label>()
//           )
//        << endl;
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
}


void Foam::conformalVoronoiMesh::setVertexSizeAndAlignment()
{
    Info<< nl << "Calculating target cell alignment and size" << endl;

    for
    (
        Delaunay::Finite_vertices_iterator vit = finite_vertices_begin();
        vit != finite_vertices_end();
        vit++
    )
    {
        if (vit->internalOrBoundaryPoint())
        {
603
            pointFromPoint pt = topoint(vit->point());
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

            cellShapeControls().cellSizeAndAlignment
            (
                pt,
                vit->targetCellSize(),
                vit->alignment()
            );
        }
    }
}


Foam::face Foam::conformalVoronoiMesh::buildDualFace
(
    const Delaunay::Finite_edges_iterator& eit
) const
{
    Cell_circulator ccStart = incident_cells(*eit);
    Cell_circulator cc1 = ccStart;
    Cell_circulator cc2 = cc1;

    // Advance the second circulator so that it always stays on the next
    // cell around the edge;
    cc2++;

    DynamicList<label> verticesOnFace;

    label nUniqueVertices = 0;

    do
    {
        if
        (
            cc1->hasFarPoint() || cc2->hasFarPoint()
         || is_infinite(cc1) || is_infinite(cc2)
        )
        {
            Cell_handle c = eit->first;
            Vertex_handle vA = c->vertex(eit->second);
            Vertex_handle vB = c->vertex(eit->third);

645 646
//            DelaunayMeshTools::drawDelaunayCell(Pout, cc1);
//            DelaunayMeshTools::drawDelaunayCell(Pout, cc2);
647

648
            WarningInFunction
649 650 651
                << "Dual face uses circumcenter defined by a "
                << "Delaunay tetrahedron with no internal "
                << "or boundary points.  Defining Delaunay edge ends: "
652 653
                << vA->info() << " "
                << vB->info() << nl
654
                <<endl;//<< exit(FatalError);
655
        }
656
        else
657
        {
658 659 660 661
            label cc1I = cc1->cellIndex();
            label cc2I = cc2->cellIndex();

            if (cc1I != cc2I)
662
            {
663
                if (!verticesOnFace.found(cc1I))
664 665 666
                {
                    nUniqueVertices++;
                }
667

668 669
                verticesOnFace.append(cc1I);
            }
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
        }

        cc1++;
        cc2++;

    } while (cc1 != ccStart);

    verticesOnFace.shrink();

    if (verticesOnFace.size() >= 3 && nUniqueVertices < 3)
    {
        // There are not enough unique vertices on this face to
        // justify its size, it may have a form like:

        // Vertices:
        // A                                  B
        // A                                  B

        // Face:
        // ABAB

        // Setting the size to be below 3, so that it will not be
        // created

        verticesOnFace.setSize(nUniqueVertices);
    }

    return face(verticesOnFace);
}


Foam::label Foam::conformalVoronoiMesh::maxFilterCount
(
    const Delaunay::Finite_edges_iterator& eit
) const
{
    Cell_circulator ccStart = incident_cells(*eit);
    Cell_circulator cc = ccStart;

    label maxFC = 0;

    do
    {
        if (cc->hasFarPoint())
        {
            Cell_handle c = eit->first;
            Vertex_handle vA = c->vertex(eit->second);
            Vertex_handle vB = c->vertex(eit->third);

719
            FatalErrorInFunction
720 721 722 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
                << "Dual face uses circumcenter defined by a "
                << "Delaunay tetrahedron with no internal "
                << "or boundary points.  Defining Delaunay edge ends: "
                << topoint(vA->point()) << " "
                << topoint(vB->point()) << nl
                << exit(FatalError);
        }

        if (cc->filterCount() > maxFC)
        {
            maxFC = cc->filterCount();
        }

        cc++;

    } while (cc != ccStart);

    return maxFC;
}


bool Foam::conformalVoronoiMesh::ownerAndNeighbour
(
    Vertex_handle vA,
    Vertex_handle vB,
    label& owner,
    label& neighbour
) const
{
    bool reverse = false;

    owner = -1;
    neighbour = -1;

    label dualCellIndexA = vA->index();

    if (!vA->internalOrBoundaryPoint() || vA->referred())
    {
laurence's avatar
laurence committed
758 759 760 761
        if (!vA->constrained())
        {
            dualCellIndexA = -1;
        }
762 763 764 765 766 767
    }

    label dualCellIndexB = vB->index();

    if (!vB->internalOrBoundaryPoint() || vB->referred())
    {
laurence's avatar
laurence committed
768 769 770 771
        if (!vB->constrained())
        {
            dualCellIndexB = -1;
        }
772 773 774 775
    }

    if (dualCellIndexA == -1 && dualCellIndexB == -1)
    {
776
        FatalErrorInFunction
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
            << "Attempting to create a face joining "
            << "two unindexed dual cells "
            << exit(FatalError);
    }
    else if (dualCellIndexA == -1 || dualCellIndexB == -1)
    {
        // boundary face, find which is the owner

        if (dualCellIndexA == -1)
        {
            owner = dualCellIndexB;

            reverse = true;
        }
        else
        {
            owner = dualCellIndexA;
        }
    }
    else
    {
        // internal face, find the lower cell to be the owner

        if (dualCellIndexB > dualCellIndexA)
        {
            owner = dualCellIndexA;
            neighbour = dualCellIndexB;
        }
        else
        {
            owner = dualCellIndexB;
            neighbour = dualCellIndexA;

            // reverse face order to correctly orientate normal
            reverse = true;
        }
    }

    return reverse;
}


// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::conformalVoronoiMesh::conformalVoronoiMesh
(
    const Time& runTime,
824 825
    const dictionary& foamyHexMeshDict,
    const fileName& decompDictFile
826 827
)
:
828
    DistributedDelaunayMesh<Delaunay>(runTime),
829 830
    runTime_(runTime),
    rndGen_(64293*Pstream::myProcNo()),
831
    foamyHexMeshControls_(foamyHexMeshDict),
832 833 834 835 836 837 838 839 840 841 842
    allGeometry_
    (
        IOobject
        (
            "cvSearchableSurfaces",
            runTime_.constant(),
            "triSurface",
            runTime_,
            IOobject::MUST_READ,
            IOobject::NO_WRITE
        ),
843
        foamyHexMeshDict.subDict("geometry"),
844
        foamyHexMeshDict.getOrDefault("singleRegionName", true)
845 846 847 848 849 850
    ),
    geometryToConformTo_
    (
        runTime_,
        rndGen_,
        allGeometry_,
851
        foamyHexMeshDict.subDict("surfaceConformation")
852
    ),
853 854 855 856 857 858 859 860 861 862 863
    decomposition_
    (
        Pstream::parRun()
      ? new backgroundMeshDecomposition
        (
            runTime_,
            rndGen_,
            geometryToConformTo_,
            foamyHexMeshControls().foamyHexMeshDict().subDict
            (
                "backgroundMeshDecomposition"
864 865
            ),
            decompDictFile
866
        )
867
      : nullptr
868
    ),
869 870 871
    cellShapeControl_
    (
        runTime_,
872
        foamyHexMeshControls_,
873 874 875 876
        allGeometry_,
        geometryToConformTo_
    ),
    limitBounds_(),
877
    ptPairs_(*this),
878
    ftPtConformer_(*this),
879 880 881 882 883 884 885
    edgeLocationTreePtr_(),
    surfacePtLocationTreePtr_(),
    surfaceConformationVertices_(),
    initialPointsMethod_
    (
        initialPointsMethod::New
        (
886
            foamyHexMeshDict.subDict("initialPoints"),
887 888 889 890 891
            runTime_,
            rndGen_,
            geometryToConformTo_,
            cellShapeControl_,
            decomposition_
892 893 894 895 896 897
        )
    ),
    relaxationModel_
    (
        relaxationModel::New
        (
898
            foamyHexMeshDict.subDict("motionControl"),
899 900 901 902 903 904 905
            runTime_
        )
    ),
    faceAreaWeightModel_
    (
        faceAreaWeightModel::New
        (
906
            foamyHexMeshDict.subDict("motionControl")
907
        )
908
    )
909 910 911 912 913 914 915 916 917 918 919 920
{}


// * * * * * * * * * * * * * * * * Destructor  * * * * * * * * * * * * * * * //

Foam::conformalVoronoiMesh::~conformalVoronoiMesh()
{}


// * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * * //

void Foam::conformalVoronoiMesh::initialiseForMotion()
921
{
922
    if (foamyHexMeshControls().objOutput())
923
    {
924
        geometryToConformTo_.writeFeatureObj("foamyHexMesh");
925 926 927 928 929 930
    }

    buildCellSizeAndAlignmentMesh();

    insertInitialPoints();

931
    insertFeaturePoints(true);
932 933 934 935 936 937 938 939

    setVertexSizeAndAlignment();

    cellSizeMeshOverlapsBackground();

    // Improve the guess that the backgroundMeshDecomposition makes with the
    // initial positions.  Use before building the surface conformation to
    // better balance the surface conformation load.
940
    distributeBackground(*this);
941 942 943 944 945

    buildSurfaceConformation();

    // The introduction of the surface conformation may have distorted the
    // balance of vertices, distribute if necessary.
946
    distributeBackground(*this);
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962

    if (Pstream::parRun())
    {
        sync(decomposition_().procBounds());
    }

    // Do not store the surface conformation until after it has been
    // (potentially) redistributed.
    storeSurfaceConformation();

    // Report any Delaunay vertices that do not think that they are in the
    // domain the processor they are on.
    // reportProcessorOccupancy();

    cellSizeMeshOverlapsBackground();

963
    if (foamyHexMeshControls().printVertexInfo())
964 965 966
    {
        printVertexInfo(Info);
    }
967

968
    if (foamyHexMeshControls().objOutput())
969
    {
970
        DelaunayMeshTools::writeOBJ
971
        (
972 973
            time().path()/"internalPoints_" + time().timeName() + ".obj",
            *this,
974 975 976 977 978 979 980
            Foam::indexedVertexEnum::vtUnassigned,
            Foam::indexedVertexEnum::vtExternalFeaturePoint
        );
    }
}


981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
void Foam::conformalVoronoiMesh::initialiseForConformation()
{
    if (Pstream::parRun())
    {
        decomposition_.reset
        (
            new backgroundMeshDecomposition
            (
                runTime_,
                rndGen_,
                geometryToConformTo_,
                foamyHexMeshControls().foamyHexMeshDict().subDict
                (
                    "backgroundMeshDecomposition"
                )
            )
        );
    }
999

1000
    insertInitialPoints();
1001

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
    insertFeaturePoints();

    // Improve the guess that the backgroundMeshDecomposition makes with the
    // initial positions.  Use before building the surface conformation to
    // better balance the surface conformation load.
    distributeBackground(*this);

    buildSurfaceConformation();

    // The introduction of the surface conformation may have distorted the
    // balance of vertices, distribute if necessary.
    distributeBackground(*this);

    if (Pstream::parRun())
    {
        sync(decomposition_().procBounds());
    }

    cellSizeMeshOverlapsBackground();

    if (foamyHexMeshControls().printVertexInfo())
    {
        printVertexInfo(Info);
    }
}
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080


void Foam::conformalVoronoiMesh::move()
{
    timeCheck("Start of move");

    scalar relaxation = relaxationModel_->relaxation();

    Info<< nl << "Relaxation = " << relaxation << endl;

    pointField dualVertices(number_of_finite_cells());

    this->resetCellCount();

    // Find the dual point of each tetrahedron and assign it an index.
    for
    (
        Delaunay::Finite_cells_iterator cit = finite_cells_begin();
        cit != finite_cells_end();
        ++cit
    )
    {
        cit->cellIndex() = Cb::ctUnassigned;

        if (cit->anyInternalOrBoundaryDualVertex())
        {
            cit->cellIndex() = getNewCellIndex();

            dualVertices[cit->cellIndex()] = cit->dual();
        }

        if (cit->hasFarPoint())
        {
            cit->cellIndex() = Cb::ctFar;
        }
    }

    dualVertices.setSize(cellCount());

    setVertexSizeAndAlignment();

    timeCheck("Determined sizes and alignments");

    Info<< nl << "Determining vertex displacements" << endl;

    vectorField cartesianDirections(3);

    cartesianDirections[0] = vector(1, 0, 0);
    cartesianDirections[1] = vector(0, 1, 0);
    cartesianDirections[2] = vector(0, 0, 1);

    vectorField displacementAccumulator
    (
        number_of_vertices(),
Henry Weller's avatar
Henry Weller committed
1081
        Zero
1082 1083
    );

1084
    bitSet pointToBeRetained(number_of_vertices(), true);
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122

    DynamicList<Point> pointsToInsert(number_of_vertices());

    for
    (
        Delaunay::Finite_edges_iterator eit = finite_edges_begin();
        eit != finite_edges_end();
        ++eit
    )
    {
        Cell_handle c = eit->first;
        Vertex_handle vA = c->vertex(eit->second);
        Vertex_handle vB = c->vertex(eit->third);

        if
        (
            (
                vA->internalPoint() && !vA->referred()
             && vB->internalOrBoundaryPoint()
            )
         || (
                vB->internalPoint() && !vB->referred()
             && vA->internalOrBoundaryPoint()
            )
        )
        {
            pointFromPoint dVA = topoint(vA->point());
            pointFromPoint dVB = topoint(vB->point());

            Field<vector> alignmentDirsA
            (
                vA->alignment().T() & cartesianDirections
            );
            Field<vector> alignmentDirsB
            (
                vB->alignment().T() & cartesianDirections
            );

1123
            Field<vector> alignmentDirs(alignmentDirsA);
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

            forAll(alignmentDirsA, aA)
            {
                const vector& a = alignmentDirsA[aA];

                scalar maxDotProduct = 0.0;

                forAll(alignmentDirsB, aB)
                {
                    const vector& b = alignmentDirsB[aB];

                    const scalar dotProduct = a & b;

                    if (mag(dotProduct) > maxDotProduct)
                    {
                        maxDotProduct = mag(dotProduct);

                        alignmentDirs[aA] = a + sign(dotProduct)*b;

1143
                        alignmentDirs[aA].normalise();
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
                    }
                }
            }

            vector rAB = dVA - dVB;

            scalar rABMag = mag(rAB);

            if (rABMag < SMALL)
            {
                // Removal of close points

                if
                (
laurence's avatar
laurence committed
1158 1159
                    vA->internalPoint() && !vA->referred() && !vA->fixed()
                 && vB->internalPoint() && !vB->referred() && !vB->fixed()
1160 1161 1162 1163 1164 1165 1166 1167 1168
                )
                {
                    // Only insert a point at the midpoint of
                    // the short edge if neither attached
                    // point has already been identified to be
                    // removed.

                    if
                    (
1169 1170
                        pointToBeRetained.test(vA->index())
                     && pointToBeRetained.test(vB->index())
1171 1172
                    )
                    {
1173
                        const Foam::point pt(0.5*(dVA + dVB));
1174 1175 1176 1177 1178

                        if (internalPointIsInside(pt))
                        {
                            pointsToInsert.append(toPoint(pt));
                        }
1179 1180 1181
                    }
                }

laurence's avatar
laurence committed
1182
                if (vA->internalPoint() && !vA->referred() && !vA->fixed())
1183
                {
1184
                    pointToBeRetained.unset(vA->index());
1185 1186
                }

laurence's avatar
laurence committed
1187
                if (vB->internalPoint() && !vB->referred() && !vB->fixed())
1188
                {
1189
                    pointToBeRetained.unset(vB->index());
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
                }

                // Do not consider this Delaunay edge any further

                continue;
            }

            forAll(alignmentDirs, aD)
            {
                vector& alignmentDir = alignmentDirs[aD];

                scalar dotProd = rAB & alignmentDir;

                if (dotProd < 0)
                {
                    // swap the direction of the alignment so that has the
                    // same sense as rAB
                    alignmentDir *= -1;
                    dotProd *= -1;
                }

                const scalar alignmentDotProd = dotProd/rABMag;

                if
                (
                    alignmentDotProd
1216
                  > foamyHexMeshControls().cosAlignmentAcceptanceAngle()
1217 1218
                )
                {
1219 1220
                    scalar targetCellSize =
                        CGAL::indexedVertexOps::averageCellSize(vA, vB);
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

                    scalar targetFaceArea = sqr(targetCellSize);

                    const vector originalAlignmentDir = alignmentDir;

                    // Update cell size and face area
                    cellShapeControls().aspectRatio().updateCellSizeAndFaceArea
                    (
                        alignmentDir,
                        targetFaceArea,
                        targetCellSize
                    );

                    // Vector to move end points around middle of vector
                    // to align edge (i.e. dual face normal) with alignment
                    // directions.
                    vector delta = alignmentDir - 0.5*rAB;

                    face dualFace = buildDualFace(eit);

//                    Pout<< dualFace << endl;
//                    Pout<< "    " << vA->info() << endl;
//                    Pout<< "    " << vB->info() << endl;

                    const scalar faceArea = dualFace.mag(dualVertices);

                    // Update delta vector
                    cellShapeControls().aspectRatio().updateDeltaVector
                    (
                        originalAlignmentDir,
                        targetCellSize,
                        rABMag,
                        delta
                    );

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
//                    if (targetFaceArea == 0)
//                    {
//                        Pout<< vA->info() << vB->info();
//
//                        Cell_handle ch = locate(vA->point());
//                        if (is_infinite(ch))
//                        {
//                            Pout<< "vA " << vA->targetCellSize() << endl;
//                        }
//
//                        ch = locate(vB->point());
//                        if (is_infinite(ch))
//                        {
//                            Pout<< "vB " << vB->targetCellSize() << endl;
//                        }
//                    }
1272 1273 1274 1275 1276 1277 1278 1279 1280

                    delta *= faceAreaWeightModel_->faceAreaWeight
                    (
                        faceArea/targetFaceArea
                    );

                    if
                    (
                        (
1281
                            (vA->internalPoint() && vB->internalPoint())
1282 1283 1284 1285 1286 1287 1288 1289
                         && (!vA->referred() || !vB->referred())
//                         ||
//                            (
//                                vA->referredInternalPoint()
//                             && vB->referredInternalPoint()
//                            )
                        )
                     && rABMag
1290 1291
                      > foamyHexMeshControls().insertionDistCoeff()
                       *targetCellSize
1292
                     && faceArea
1293 1294
                      > foamyHexMeshControls().faceAreaRatioCoeff()
                       *targetFaceArea
1295
                     && alignmentDotProd
1296
                      > foamyHexMeshControls().cosInsertionAcceptanceAngle()
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
                    )
                    {
                        // Point insertion
                        if
                        (
                            !geometryToConformTo_.findSurfaceAnyIntersection
                            (
                                dVA,
                                dVB
                            )
                        )
                        {
1309
                            const Foam::point newPt(0.5*(dVA + dVB));
1310

1311 1312
                            // Prevent insertions spanning surfaces
                            if (internalPointIsInside(newPt))
1313
                            {
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
                                if (Pstream::parRun())
                                {
                                    if
                                    (
                                        decomposition().positionOnThisProcessor
                                        (
                                            newPt
                                        )
                                    )
                                    {
                                        pointsToInsert.append(toPoint(newPt));
                                    }
                                }
                                else
1328 1329 1330
                                {
                                    pointsToInsert.append(toPoint(newPt));
                                }
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
                            }
                        }
                    }
                    else if
                    (
                        (
                            (vA->internalPoint() && !vA->referred())
                         || (vB->internalPoint() && !vB->referred())
                        )
                     && rABMag
1341
                      < foamyHexMeshControls().removalDistCoeff()
1342 1343 1344 1345 1346 1347
                       *targetCellSize
                    )
                    {
                        // Point removal
                        if
                        (
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
                            (
                                vA->internalPoint()
                             && !vA->referred()
                             && !vA->fixed()
                            )
                         &&
                            (
                                vB->internalPoint()
                             && !vB->referred()
                             && !vB->fixed()
                            )
1359 1360 1361 1362 1363 1364 1365 1366
                        )
                        {
                            // Only insert a point at the midpoint of
                            // the short edge if neither attached
                            // point has already been identified to be
                            // removed.
                            if
                            (
1367 1368
                                pointToBeRetained.test(vA->index())
                             && pointToBeRetained.test(vB->index())
1369 1370
                            )
                            {
1371
                                const Foam::point pt(0.5*(dVA + dVB));
1372 1373 1374 1375 1376

                                if (internalPointIsInside(pt))
                                {<