conformalVoronoiMeshIO.C 58.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | Copyright (C) 2012-2013 OpenFOAM Foundation
     \\/     M anipulation  |
-------------------------------------------------------------------------------
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 "IOstreams.H"
#include "OFstream.H"
#include "pointMesh.H"
#include "pointFields.H"
#include "ListOps.H"
#include "polyMeshFilter.H"
#include "polyTopoChange.H"
#include "PrintTable.H"
#include "pointMesh.H"
36
#include "indexedVertexOps.H"
37
#include "DelaunayMeshTools.H"
38
39
40
41
42
#include "surfaceZonesInfo.H"
#include "polyModifyCell.H"
#include "polyModifyFace.H"
#include "syncTools.H"
#include "regionSplit.H"
43
#include "OBJstream.H"
44
45
46
47
48
49
50
51

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

void Foam::conformalVoronoiMesh::timeCheck
(
    const string& description
) const
{
52
    timeCheck(time(), description, foamyHexMeshControls().timeChecks());
53
54
55
56
57
58
59
60
61
62
63
}


void Foam::conformalVoronoiMesh::timeCheck
(
    const Time& runTime,
    const string& description,
    const bool check
)
{
    if (check)
64
65
    {
        Info<< nl << "--- [ cpuTime "
66
67
            << runTime.elapsedCpuTime() << " s, "
            << "delta " << runTime.cpuTimeIncrement()<< " s";
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

        if (description != word::null)
        {
            Info<< ", " << description << " ";
        }
        else
        {
            Info<< " ";
        }

        Info<< "] --- " << endl;

        memInfo m;

        if (m.valid())
        {
84
85
86
87
88
            PrintTable<word, label> memoryTable
            (
                "Memory Usage (kB): "
              + description
            );
89
90
91
92
93
94

            memoryTable.add("mSize", m.size());
            memoryTable.add("mPeak", m.peak());
            memoryTable.add("mRss", m.rss());

            Info<< incrIndent;
95
            memoryTable.print(Info, true, true);
96
97
98
99
100
101
102
103
            Info<< decrIndent;
        }
    }
}


void Foam::conformalVoronoiMesh::writeMesh(const fileName& instance)
{
104
    DelaunayMeshTools::writeInternalDelaunayVertices(instance, *this);
105
106
107
108
109

    // Per cell the Delaunay vertex
    labelList cellToDelaunayVertex;
    // Per patch, per face the Delaunay vertex
    labelListList patchToDelaunayVertex;
110

111
112
113
114
    labelList dualPatchStarts;

    {
        pointField points;
115
        labelList boundaryPts;
116
117
118
119
        faceList faces;
        labelList owner;
        labelList neighbour;
        wordList patchNames;
120
        PtrList<dictionary> patchDicts;
121
122
123
124
125
126
127
128
129
130
131
132
        pointField cellCentres;

        PackedBoolList boundaryFacesToRemove;

        calcDualMesh
        (
            points,
            boundaryPts,
            faces,
            owner,
            neighbour,
            patchNames,
133
            patchDicts,
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
            cellCentres,
            cellToDelaunayVertex,
            patchToDelaunayVertex,
            boundaryFacesToRemove
        );

        Info<< nl << "Writing polyMesh to " << instance << endl;

        writeMesh
        (
            Foam::polyMesh::defaultRegion,
            instance,
            points,
            boundaryPts,
            faces,
            owner,
            neighbour,
            patchNames,
152
            patchDicts,
153
154
155
            cellCentres,
            boundaryFacesToRemove
        );
156
157
158
159
160
161
162
163

        dualPatchStarts.setSize(patchDicts.size());

        forAll(dualPatchStarts, patchI)
        {
            dualPatchStarts[patchI] =
                readLabel(patchDicts[patchI].lookup("startFace"));
        }
164
165
    }

166
    if (foamyHexMeshControls().writeCellShapeControlMesh())
167
    {
168
169
        cellShapeControls().shapeControlMesh().write();
    }
170

171
172
173
    if (foamyHexMeshControls().writeBackgroundMeshDecomposition())
    {
        Info<< nl << "Writing " << "backgroundMeshDecomposition" << endl;
174

175
176
177
178
179
180
        // Have to explicitly update the mesh instance.
        const_cast<fvMesh&>(decomposition_().mesh()).setInstance
        (
            time().timeName()
        );

181
182
        decomposition_().mesh().write();
    }
183

184
185
186
187
    if (foamyHexMeshControls().writeTetDualMesh())
    {
        label cellI = 0;
        for
188
        (
189
190
191
192
            Finite_cells_iterator cit = finite_cells_begin();
            cit != finite_cells_end();
            ++cit
        )
193
        {
194
            if
195
            (
196
197
198
                !cit->hasFarPoint()
             && !is_infinite(cit)
            )
199
            {
200
                cit->cellIndex() = cellI++;
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
        Info<< nl << "Writing " << "tetDualMesh" << endl;

        DistributedDelaunayMesh<Delaunay>::labelTolabelPairHashTable vertexMap;
        labelList cellMap;
        autoPtr<polyMesh> tetMesh =
            createMesh("tetDualMesh", vertexMap, cellMap);

        tetMesh().write();

//        // Determine map from Delaunay vertex to Dual mesh
//        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//        // From all Delaunay vertices to cell (positive index)
//        // or patch face (negative index)
//        labelList vertexToDualAddressing(number_of_vertices(), 0);
//
//        forAll(cellToDelaunayVertex, cellI)
//        {
//            label vertI = cellToDelaunayVertex[cellI];
//
//            if (vertexToDualAddressing[vertI] != 0)
//            {
//                FatalErrorIn("conformalVoronoiMesh::writeMesh(..)")
//                    << "Delaunay vertex " << vertI
//                    << " from cell " << cellI
//                    << " is already mapped to "
//                    << vertexToDualAddressing[vertI]
//                    << exit(FatalError);
//            }
//            vertexToDualAddressing[vertI] = cellI+1;
//        }
//
//        forAll(patchToDelaunayVertex, patchI)
//        {
//            const labelList& patchVertices = patchToDelaunayVertex[patchI];
//
//            forAll(patchVertices, i)
//            {
//                label vertI = patchVertices[i];
//
//                if (vertexToDualAddressing[vertI] > 0)
//                {
//                    FatalErrorIn("conformalVoronoiMesh::writeMesh(..)")
//                        << "Delaunay vertex " << vertI
//                        << " from patch " << patchI
//                        << " local index " << i
//                        << " is already mapped to cell "
//                        << vertexToDualAddressing[vertI]-1
//                        << exit(FatalError);
//                }
//
//                // Vertex might be used by multiple faces. Which one to
//                // use? For now last one wins.
//                label dualFaceI = dualPatchStarts[patchI]+i;
//                vertexToDualAddressing[vertI] = -dualFaceI-1;
//            }
//        }
//
//
//        // Calculate tet mesh addressing
//        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//        pointField points;
//        labelList boundaryPts(number_of_finite_cells(), -1);
//        // From tet point back to Delaunay vertex index
//        labelList pointToDelaunayVertex;
//        faceList faces;
//        labelList owner;
//        labelList neighbour;
//        wordList patchTypes;
//        wordList patchNames;
//        PtrList<dictionary> patchDicts;
//        pointField cellCentres;
//
//        calcTetMesh
//        (
//            points,
//            pointToDelaunayVertex,
//            faces,
//            owner,
//            neighbour,
//            patchTypes,
//            patchNames,
//            patchDicts
//        );
//
//
//
//        // Calculate map from tet points to dual mesh cells/patch faces
//        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//        labelIOList pointDualAddressing
//        (
//            IOobject
//            (
//                "pointDualAddressing",
//                instance,
//                "tetDualMesh"/polyMesh::meshSubDir,
//                runTime_,
//                IOobject::NO_READ,
//                IOobject::AUTO_WRITE,
//                false
//            ),
//            UIndirectList<label>
//            (
//                vertexToDualAddressing,
//                pointToDelaunayVertex
//            )()
//        );
//
//        label pointI = findIndex(pointDualAddressing, -1);
//        if (pointI != -1)
//        {
//            WarningIn
//            (
//                "conformalVoronoiMesh::writeMesh\n"
//                "(\n"
//                "    const fileName& instance,\n"
//                "    bool filterFaces\n"
//                ")\n"
//            )   << "Delaunay vertex " << pointI
//                << " does not have a corresponding dual cell." << endl;
//        }
//
//        Info<< "Writing map from tetDualMesh points to Voronoi mesh to "
//            << pointDualAddressing.objectPath() << endl;
//        pointDualAddressing.write();
//
//
//
//        // Write tet points corresponding to the Voronoi cell/face centre
//        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//        {
//            // Read Voronoi mesh
//            fvMesh mesh
//            (
//                IOobject
//                (
//                    Foam::polyMesh::defaultRegion,
//                    instance,
//                    runTime_,
//                    IOobject::MUST_READ
//                )
//            );
//            pointIOField dualPoints
//            (
//                IOobject
//                (
//                    "dualPoints",
//                    instance,
//                    "tetDualMesh"/polyMesh::meshSubDir,
//                    runTime_,
//                    IOobject::NO_READ,
//                    IOobject::AUTO_WRITE,
//                    false
//                ),
//                points
//            );
//
//            forAll(pointDualAddressing, pointI)
//            {
//                label index = pointDualAddressing[pointI];
//
//                if (index > 0)
//                {
//                    label cellI = index-1;
//                    dualPoints[pointI] = mesh.cellCentres()[cellI];
//                }
//                else if (index < 0)
//                {
//                    label faceI = -index-1;
//                    if (faceI >= mesh.nInternalFaces())
//                    {
//                        dualPoints[pointI] = mesh.faceCentres()[faceI];
//                    }
//                }
//            }
//
//            Info<< "Writing tetDualMesh points mapped onto Voronoi mesh to "
//                << dualPoints.objectPath() << endl
//                << "Replace the polyMesh/points with these." << endl;
//            dualPoints.write();
//        }
//
//
//        Info<< nl << "Writing tetDualMesh to " << instance << endl;
//
//        PackedBoolList boundaryFacesToRemove;
//        writeMesh
//        (
//            "tetDualMesh",
//            instance,
//            points,
//            boundaryPts,
//            faces,
//            owner,
//            neighbour,
//            patchTypes,
//            patchNames,
//            patchDicts,
//            cellCentres,
//            boundaryFacesToRemove
//        );
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
void Foam::conformalVoronoiMesh::calcNeighbourCellCentres
(
    const polyMesh& mesh,
    const pointField& cellCentres,
    pointField& neiCc
) const
{
    label nBoundaryFaces = mesh.nFaces() - mesh.nInternalFaces();

    if (neiCc.size() != nBoundaryFaces)
    {
        FatalErrorIn("conformalVoronoiMesh::calcNeighbourCellCentres(..)")
            << "nBoundaries:" << nBoundaryFaces
            << " neiCc:" << neiCc.size()
            << abort(FatalError);
    }

    const polyBoundaryMesh& patches = mesh.boundaryMesh();

    forAll(patches, patchI)
    {
        const polyPatch& pp = patches[patchI];

        const labelUList& faceCells = pp.faceCells();

        label bFaceI = pp.start() - mesh.nInternalFaces();

        if (pp.coupled())
        {
            forAll(faceCells, i)
            {
                neiCc[bFaceI] = cellCentres[faceCells[i]];
                bFaceI++;
            }
        }
    }

    // Swap coupled boundaries. Apply separation to cc since is coordinate.
    syncTools::swapBoundaryFacePositions(mesh, neiCc);
}


void Foam::conformalVoronoiMesh::selectSeparatedCoupledFaces
(
    const polyMesh& mesh,
    boolList& selected
) const
{
    const polyBoundaryMesh& patches = mesh.boundaryMesh();

    forAll(patches, patchI)
    {
        // Check all coupled. Avoid using .coupled() so we also pick up AMI.
        if (isA<coupledPolyPatch>(patches[patchI]))
        {
            const coupledPolyPatch& cpp = refCast<const coupledPolyPatch>
            (
                patches[patchI]
            );

            if (cpp.separated() || !cpp.parallel())
            {
                forAll(cpp, i)
                {
                    selected[cpp.start()+i] = true;
                }
            }
        }
    }
}


483
484
485
486
487
488
489
490
491
492
void Foam::conformalVoronoiMesh::findCellZoneInsideWalk
(
    const polyMesh& mesh,
    const labelList& locationSurfaces,  // indices of surfaces with inside point
    const labelList& faceToSurface, // per face index of named surface
    labelList& cellToSurface
) const
{
    // Analyse regions. Reuse regionsplit
    boolList blockedFace(mesh.nFaces());
493
    selectSeparatedCoupledFaces(mesh, blockedFace);
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705

    forAll(faceToSurface, faceI)
    {
        if (faceToSurface[faceI] == -1)
        {
            blockedFace[faceI] = false;
        }
        else
        {
            blockedFace[faceI] = true;
        }
    }
    // No need to sync since namedSurfaceIndex already is synced

    // Set region per cell based on walking
    regionSplit cellRegion(mesh, blockedFace);
    blockedFace.clear();


    // Force calculation of face decomposition (used in findCell)
    (void)mesh.tetBasePtIs();

    const PtrList<surfaceZonesInfo>& surfZones =
        geometryToConformTo().surfZones();

    // For all locationSurface find the cell
    forAll(locationSurfaces, i)
    {
        label surfI = locationSurfaces[i];

        const Foam::point& insidePoint = surfZones[surfI].zoneInsidePoint();

        const word& surfName = geometryToConformTo().geometry().names()[surfI];

        Info<< "    For surface " << surfName
            << " finding inside point " << insidePoint
            << endl;

        // Find the region containing the insidePoint
        label keepRegionI = -1;

        label cellI = mesh.findCell(insidePoint);

        if (cellI != -1)
        {
            keepRegionI = cellRegion[cellI];
        }
        reduce(keepRegionI, maxOp<label>());

        Info<< "    For surface " << surfName
            << " found point " << insidePoint << " in cell " << cellI
            << " in global region " << keepRegionI
            << " out of " << cellRegion.nRegions() << " regions." << endl;

        if (keepRegionI == -1)
        {
            FatalErrorIn
            (
                "conformalVoronoiMesh::findCellZoneInsideWalk"
                "(const polyMesh&, const labelList&"
                ", const labelList&, labelList&)"
            )   << "Point " << insidePoint
                << " is not inside the mesh." << nl
                << "Bounding box of the mesh:" << mesh.bounds()
                << exit(FatalError);
        }

        // Set all cells with this region
        forAll(cellRegion, cellI)
        {
            if (cellRegion[cellI] == keepRegionI)
            {
                if (cellToSurface[cellI] == -2)
                {
                    cellToSurface[cellI] = surfI;
                }
                else if (cellToSurface[cellI] != surfI)
                {
                    WarningIn
                    (
                        "conformalVoronoiMesh::findCellZoneInsideWalk"
                        "(const labelList&, const labelList&"
                        ", const labelList&, const labelList&)"
                    )   << "Cell " << cellI
                        << " at " << mesh.cellCentres()[cellI]
                        << " is inside surface " << surfName
                        << " but already marked as being in zone "
                        << cellToSurface[cellI] << endl
                        << "This can happen if your surfaces are not"
                        << " (sufficiently) closed."
                        << endl;
                }
            }
        }
    }
}


Foam::labelList Foam::conformalVoronoiMesh::calcCellZones
(
    const pointField& cellCentres
) const
{
    labelList cellToSurface(cellCentres.size(), -1);

    const PtrList<surfaceZonesInfo>& surfZones =
        geometryToConformTo().surfZones();

    // Get list of closed surfaces
    labelList closedNamedSurfaces
    (
        surfaceZonesInfo::getAllClosedNamedSurfaces
        (
            surfZones,
            geometryToConformTo().geometry(),
            geometryToConformTo().surfaces()
        )
    );

    forAll(closedNamedSurfaces, i)
    {
        label surfI = closedNamedSurfaces[i];

        const searchableSurface& surface =
            allGeometry()[geometryToConformTo().surfaces()[surfI]];

        const surfaceZonesInfo::areaSelectionAlgo selectionMethod =
            surfZones[surfI].zoneInside();

        if
        (
            selectionMethod != surfaceZonesInfo::INSIDE
         && selectionMethod != surfaceZonesInfo::OUTSIDE
         && selectionMethod != surfaceZonesInfo::INSIDEPOINT
        )
        {
            FatalErrorIn("conformalVoronoiMesh::calcCellZones(..)")
                << "Trying to use surface "
                << surface.name()
                << " which has non-geometric inside selection method "
                << surfaceZonesInfo::areaSelectionAlgoNames[selectionMethod]
                << exit(FatalError);
        }

        if (surface.hasVolumeType())
        {
            List<volumeType> volType;
            surface.getVolumeType(cellCentres, volType);

            bool selectInside = true;
            if (selectionMethod == surfaceZonesInfo::INSIDEPOINT)
            {
                List<volumeType> volTypeInsidePoint;
                surface.getVolumeType
                (
                    pointField(1, surfZones[surfI].zoneInsidePoint()),
                    volTypeInsidePoint
                );

                if (volTypeInsidePoint[0] == volumeType::OUTSIDE)
                {
                    selectInside = false;
                }
            }
            else if (selectionMethod == surfaceZonesInfo::OUTSIDE)
            {
                selectInside = false;
            }

            forAll(volType, pointI)
            {
                if (cellToSurface[pointI] == -1)
                {
                    if
                    (
                        (
                            volType[pointI] == volumeType::INSIDE
                         && selectInside
                        )
                     || (
                            volType[pointI] == volumeType::OUTSIDE
                         && !selectInside
                        )
                    )
                    {
                        cellToSurface[pointI] = surfI;
                    }
                }
            }
        }
    }

    return cellToSurface;
}


void Foam::conformalVoronoiMesh::calcFaceZones
(
    const polyMesh& mesh,
    const pointField& cellCentres,
    const labelList& cellToSurface,
    labelList& faceToSurface,
    boolList& flipMap
) const
{
    faceToSurface.setSize(mesh.nFaces(), -1);
    flipMap.setSize(mesh.nFaces(), false);

    const faceList& faces = mesh.faces();
    const labelList& faceOwner = mesh.faceOwner();
    const labelList& faceNeighbour = mesh.faceNeighbour();

706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
    labelList neiFaceOwner(mesh.nFaces() - mesh.nInternalFaces(), -1);

    const polyBoundaryMesh& patches = mesh.boundaryMesh();

    forAll(patches, patchI)
    {
        const polyPatch& pp = patches[patchI];

        const labelUList& faceCells = pp.faceCells();

        label bFaceI = pp.start() - mesh.nInternalFaces();

        if (pp.coupled())
        {
            forAll(faceCells, i)
            {
                neiFaceOwner[bFaceI] = cellToSurface[faceCells[i]];
                bFaceI++;
            }
        }
    }

    syncTools::swapBoundaryFaceList(mesh, neiFaceOwner);

730
731
732
733
    forAll(faces, faceI)
    {
        const label ownerSurfaceI = cellToSurface[faceOwner[faceI]];

734
735
736
737
738
        if (faceToSurface[faceI] >= 0)
        {
            continue;
        }

739
740
741
742
743
744
745
746
747
748
        if (mesh.isInternalFace(faceI))
        {
            const label neiSurfaceI = cellToSurface[faceNeighbour[faceI]];

            if
            (
                (ownerSurfaceI >= 0 || neiSurfaceI >= 0)
             && ownerSurfaceI != neiSurfaceI
            )
            {
749
750
751
752
753
754
755
756
                flipMap[faceI] =
                    (
                        ownerSurfaceI == max(ownerSurfaceI, neiSurfaceI)
                      ? false
                      : true
                    );

                faceToSurface[faceI] = max(ownerSurfaceI, neiSurfaceI);
757
758
759
760
            }
        }
        else
        {
761
762
763
            label patchID = mesh.boundaryMesh().whichPatch(faceI);

            if (mesh.boundaryMesh()[patchID].coupled())
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
                const label neiSurfaceI =
                    neiFaceOwner[faceI - mesh.nInternalFaces()];

                if
                (
                    (ownerSurfaceI >= 0 || neiSurfaceI >= 0)
                 && ownerSurfaceI != neiSurfaceI
                )
                {
                    flipMap[faceI] =
                        (
                            ownerSurfaceI == max(ownerSurfaceI, neiSurfaceI)
                          ? false
                          : true
                        );

                    faceToSurface[faceI] = max(ownerSurfaceI, neiSurfaceI);
                }
            }
            else
            {
                if (ownerSurfaceI >= 0)
                {
                    faceToSurface[faceI] = ownerSurfaceI;
                }
790
791
792
793
794
795
796
797
            }
        }
    }


    const PtrList<surfaceZonesInfo>& surfZones =
        geometryToConformTo().surfZones();

798
799
800
801
802
803
804
805
806
807
808
809
    labelList unclosedSurfaces
    (
        surfaceZonesInfo::getUnclosedNamedSurfaces
        (
            surfZones,
            geometryToConformTo().geometry(),
            geometryToConformTo().surfaces()
        )
    );

    pointField neiCc(mesh.nFaces() - mesh.nInternalFaces());
    calcNeighbourCellCentres
810
    (
811
812
813
        mesh,
        cellCentres,
        neiCc
814
815
    );

816
817
818
    OBJstream intersections(time().path()/"ints.obj");
    OBJstream intersectionFaces(time().path()/"intFaces.obj");

819
820
821
    // Use intersection of cellCentre connections
    forAll(faces, faceI)
    {
822
        if (faceToSurface[faceI] >= 0)
823
        {
824
825
            continue;
        }
826

827
        label patchID = mesh.boundaryMesh().whichPatch(faceI);
828

829
830
831
832
833
834
835
836
837
838
        const label own = faceOwner[faceI];

        List<pointIndexHit> surfHit;
        labelList hitSurface;

        if (mesh.isInternalFace(faceI))
        {
            const label nei = faceNeighbour[faceI];

            geometryToConformTo().findSurfaceAllIntersections
839
840
841
842
843
844
            (
                cellCentres[own],
                cellCentres[nei],
                surfHit,
                hitSurface
            );
845
846
847
848
849
850
851
852
853
854
        }
        else if (patchID != -1 && mesh.boundaryMesh()[patchID].coupled())
        {
            geometryToConformTo().findSurfaceAllIntersections
            (
                cellCentres[own],
                neiCc[faceI - mesh.nInternalFaces()],
                surfHit,
                hitSurface
            );
855

856
            if (surfHit.size() == 1 && surfHit[0].hit())
857
            {
858
859
860
                intersections.write
                (
                    linePointRef
861
                    (
862
863
864
865
                        cellCentres[own],
                        neiCc[faceI - mesh.nInternalFaces()]
                    )
                );
866
867
868
            }
        }

869
870
871
        // If there are multiple intersections then do not add to
        // a faceZone
        if (surfHit.size() == 1 && surfHit[0].hit())
872
        {
873
            if (findIndex(unclosedSurfaces, hitSurface[0]) != -1)
874
            {
875
876
877
878
879
880
881
                vectorField norm;
                geometryToConformTo().getNormal
                (
                    hitSurface[0],
                    List<pointIndexHit>(1, surfHit[0]),
                    norm
                );
882

883
884
                vector fN = faces[faceI].normal(mesh.points());
                fN /= mag(fN) + SMALL;
885

886
                if ((norm[0] & fN) < 0)
887
                {
888
                    flipMap[faceI] = true;
889
                }
890
891
892
893
894
895
896
897
                else
                {
                    flipMap[faceI] = false;
                }

                faceToSurface[faceI] = hitSurface[0];

                intersectionFaces.write(faces[faceI], mesh.points());
898
899
900
901
            }
        }
    }

902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941

//    labelList neiCellSurface(mesh.nFaces()-mesh.nInternalFaces());
//
//    forAll(patches, patchI)
//    {
//        const polyPatch& pp = patches[patchI];
//
//        if (pp.coupled())
//        {
//            forAll(pp, i)
//            {
//                label faceI = pp.start()+i;
//                label ownSurface = cellToSurface[faceOwner[faceI]];
//                neiCellSurface[faceI - mesh.nInternalFaces()] = ownSurface;
//            }
//        }
//    }
//    syncTools::swapBoundaryFaceList(mesh, neiCellSurface);
//
//    forAll(patches, patchI)
//    {
//        const polyPatch& pp = patches[patchI];
//
//        if (pp.coupled())
//        {
//            forAll(pp, i)
//            {
//                label faceI = pp.start()+i;
//                label ownSurface = cellToSurface[faceOwner[faceI]];
//                label neiSurface = neiCellSurface[faceI-mesh.nInternalFaces()];
//
//                if (faceToSurface[faceI] == -1 && (ownSurface != neiSurface))
//                {
//                    // Give face the max cell zone
//                    faceToSurface[faceI] =  max(ownSurface, neiSurface);
//                }
//            }
//        }
//    }
//
942
943
944
945
946
    // Sync
    syncTools::syncFaceList(mesh, faceToSurface, maxEqOp<label>());
}


947
948
949
950
Foam::autoPtr<Foam::fvMesh> Foam::conformalVoronoiMesh::createDummyMesh
(
    const IOobject& io,
    const wordList& patchNames,
951
    const PtrList<dictionary>& patchDicts
952
953
954
955
956
957
958
959
960
961
962
963
964
965
) const
{
    autoPtr<fvMesh> meshPtr
    (
        new fvMesh
        (
            io,
            xferCopy(pointField()),
            xferCopy(faceList()),
            xferCopy(cellList())
        )
    );
    fvMesh& mesh = meshPtr();

966
    List<polyPatch*> patches(patchDicts.size());
967
968
969

    forAll(patches, patchI)
    {
970
971
972
973
974
975
976
977
        if
        (
            patchDicts.set(patchI)
         && (
                word(patchDicts[patchI].lookup("type"))
             == processorPolyPatch::typeName
            )
        )
978
979
980
981
982
983
984
985
        {
            patches[patchI] = new processorPolyPatch
            (
                patchNames[patchI],
                0,          //patchSizes[p],
                0,          //patchStarts[p],
                patchI,
                mesh.boundaryMesh(),
986
987
                readLabel(patchDicts[patchI].lookup("myProcNo")),
                readLabel(patchDicts[patchI].lookup("neighbProcNo")),
988
989
990
991
992
993
994
                coupledPolyPatch::COINCIDENTFULLMATCH
            );
        }
        else
        {
            patches[patchI] = polyPatch::New
            (
995
                patchDicts[patchI].lookup("type"),
996
997
998
999
1000
1001
1002
1003
                patchNames[patchI],
                0,          //patchSizes[p],
                0,          //patchStarts[p],
                patchI,
                mesh.boundaryMesh()
            ).ptr();
        }
    }
1004

1005
1006
1007
1008
1009
1010
1011
1012
    mesh.addFvPatches(patches);

    return meshPtr;
}


void Foam::conformalVoronoiMesh::checkProcessorPatchesMatch
(
1013
    const PtrList<dictionary>& patchDicts
1014
1015
1016
1017
1018
1019
1020
1021
1022
) const
{
    // Check patch sizes
    labelListList procPatchSizes
    (
        Pstream::nProcs(),
        labelList(Pstream::nProcs(), -1)
    );

1023
    forAll(patchDicts, patchI)
1024
    {
1025
1026
1027
1028
1029
1030
1031
1032
        if
        (
            patchDicts.set(patchI)
         && (
                word(patchDicts[patchI].lookup("type"))
             == processorPolyPatch::typeName
            )
        )
1033
        {
1034
1035
1036
1037
1038
            const label procNeighb =
                readLabel(patchDicts[patchI].lookup("neighbProcNo"));

            procPatchSizes[Pstream::myProcNo()][procNeighb]
                = readLabel(patchDicts[patchI].lookup("nFaces"));
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
1081
1082
1083
1084
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
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
        }
    }

    Pstream::gatherList(procPatchSizes);

    if (Pstream::master())
    {
        bool allMatch = true;

        forAll(procPatchSizes, procI)
        {
            const labelList& patchSizes = procPatchSizes[procI];

            forAll(patchSizes, patchI)
            {
                if (patchSizes[patchI] != procPatchSizes[patchI][procI])
                {
                    allMatch = false;

                    Info<< indent << "Patches " << procI << " and " << patchI
                        << " have different sizes: " << patchSizes[patchI]
                        << " and " << procPatchSizes[patchI][procI] << endl;
                }
            }
        }

        if (allMatch)
        {
            Info<< indent << "All processor patches have matching numbers of "
                << "faces" << endl;
        }
    }
}


void Foam::conformalVoronoiMesh::reorderPoints
(
    pointField& points,
    labelList& boundaryPts,
    faceList& faces,
    const label nInternalFaces
) const
{
    Info<< incrIndent << indent << "Reordering points into internal/external"
        << endl;

    labelList oldToNew(points.size(), 0);

    // Find points that are internal
    for (label fI = nInternalFaces; fI < faces.size(); ++fI)
    {
        const face& f = faces[fI];

        forAll(f, fpI)
        {
            oldToNew[f[fpI]] = 1;
        }
    }

    const label nInternalPoints = points.size() - sum(oldToNew);

    label countInternal = 0;
    label countExternal = nInternalPoints;

    forAll(points, pI)
    {
        if (oldToNew[pI] == 0)
        {
            oldToNew[pI] = countInternal++;
        }
        else
        {
            oldToNew[pI] = countExternal++;
        }
    }

    Info<< indent
        << "Number of internal points: " << countInternal << nl
        << indent << "Number of external points: " << countExternal
        << decrIndent << endl;

    inplaceReorder(oldToNew, points);
    inplaceReorder(oldToNew, boundaryPts);

    forAll(faces, fI)
    {
        face& f = faces[fI];

        forAll(f, fpI)
        {
            f[fpI] = oldToNew[f[fpI]];
        }
    }
}


void Foam::conformalVoronoiMesh::reorderProcessorPatches
(
    const word& meshName,
    const fileName& instance,
    const pointField& points,
    faceList& faces,
    const wordList& patchNames,
1142
    const PtrList<dictionary>& patchDicts
1143
1144
1145
1146
1147
) const
{
    Info<< incrIndent << indent << "Reordering processor patches" << endl;

    Info<< incrIndent;
1148
    checkProcessorPatchesMatch(patchDicts);
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164

    // Create dummy mesh with correct proc boundaries to do sorting
    autoPtr<fvMesh> sortMeshPtr
    (
        createDummyMesh
        (
            IOobject
            (
                meshName,
                instance,
                runTime_,
                IOobject::NO_READ,
                IOobject::NO_WRITE,
                false
            ),
            patchNames,
1165
            patchDicts
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
        )
    );
    const fvMesh& sortMesh = sortMeshPtr();

    // Change the transform type on processors to coincident full match.
//    forAll(sortMesh.boundaryMesh(), patchI)
//    {
//        const polyPatch& patch = sortMesh.boundaryMesh()[patchI];
//
//        if (isA<processorPolyPatch>(patch))
//        {
//            const processorPolyPatch& cpPatch
//                = refCast<const processorPolyPatch>(patch);
//
//            processorPolyPatch& pPatch
//                = const_cast<processorPolyPatch&>(cpPatch);
//
//            pPatch.transform() = coupledPolyPatch::COINCIDENTFULLMATCH;
//        }
//    }

    // Rotation on new faces.
1188
    labelList rotation(faces.size(), 0);
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
    labelList faceMap(faces.size(), -1);

    PstreamBuffers pBufs(Pstream::nonBlocking);

    // Send ordering
    forAll(sortMesh.boundaryMesh(), patchI)
    {
        const polyPatch& pp = sortMesh.boundaryMesh()[patchI];

        if (isA<processorPolyPatch>(pp))
        {
            refCast<const processorPolyPatch>(pp).initOrder
            (
                pBufs,
                primitivePatch
                (
                    SubList<face>
                    (
                        faces,
1208
1209
                        readLabel(patchDicts[patchI].lookup("nFaces")),
                        readLabel(patchDicts[patchI].lookup("startFace"))
1210
1211
1212
1213
1214
1215
1216
1217
1218
                    ),
                    points
                )
            );
        }
    }

    pBufs.finishedSends();

1219
    Info<< incrIndent << indent << "Face ordering initialised..." << endl;
1220

1221
1222
1223
1224
1225
1226
1227
1228
1229
    // Receive and calculate ordering
    bool anyChanged = false;

    forAll(sortMesh.boundaryMesh(), patchI)
    {
        const polyPatch& pp = sortMesh.boundaryMesh()[patchI];

        if (isA<processorPolyPatch>(pp))
        {
1230
1231
1232
1233
1234
1235
1236
            const label nPatchFaces =
                readLabel(patchDicts[patchI].lookup("nFaces"));
            const label patchStartFace =
                readLabel(patchDicts[patchI].lookup("startFace"));

            labelList patchFaceMap(nPatchFaces, -1);
            labelList patchFaceRotation(nPatchFaces, 0);
1237
1238
1239
1240
1241
1242
1243
1244
1245

            bool changed = refCast<const processorPolyPatch>(pp).order
            (
                pBufs,
                primitivePatch
                (
                    SubList<face>
                    (
                        faces,
1246
1247
                        nPatchFaces,
                        patchStartFace
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
                    ),
                    points
                ),
                patchFaceMap,
                patchFaceRotation
            );

            if (changed)
            {
                // Merge patch face reordering into mesh face reordering table
                forAll(patchFaceRotation, patchFaceI)
                {
1260
                    rotation[patchFaceI + patchStartFace]
1261
1262
1263
1264
1265
1266
1267
                        = patchFaceRotation[patchFaceI];
                }

                forAll(patchFaceMap, patchFaceI)
                {
                    if (patchFaceMap[patchFaceI] != patchFaceI)
                    {
1268
1269
                        faceMap[patchFaceI + patchStartFace]
                            = patchFaceMap[patchFaceI] + patchStartFace;
1270
1271
1272
1273
1274
1275
1276
1277
                    }
                }

                anyChanged = true;
            }
        }
    }

1278
    Info<< incrIndent << indent << "Faces matched." << endl;
1279

1280
1281
1282
1283
    reduce(anyChanged, orOp<bool>());

    if (anyChanged)
    {
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
        label nReorderedFaces = 0;

        forAll(faceMap, faceI)
        {
           if (faceMap[faceI] != -1)
           {
               nReorderedFaces++;
           }
        }

        if (nReorderedFaces > 0)
        {
            inplaceReorder(faceMap, faces);
        }
1298

1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
        // Rotate faces (rotation is already in new face indices).
        label nRotated = 0;

        forAll(rotation, faceI)
        {
            if (rotation[faceI] != 0)
            {
                inplaceRotateList<List, label>(faces[faceI], rotation[faceI]);
                nRotated++;
            }
        }

1311
1312
1313
1314
        Info<< indent << returnReduce(nReorderedFaces, sumOp<label>())
            << " faces have been reordered" << nl
            << indent << returnReduce(nRotated, sumOp<label>())
            << " faces have been rotated"
1315
            << decrIndent << decrIndent
1316
            << decrIndent << decrIndent << endl;
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
    }
}


void Foam::conformalVoronoiMesh::writeMesh
(
    const word& meshName,
    const fileName& instance,
    pointField& points,
    labelList& boundaryPts,
    faceList& faces,
    labelList& owner,
    labelList& neighbour,
    const wordList& patchNames,
1331
    const PtrList<dictionary>& patchDicts,
1332
1333
1334
1335
    const pointField& cellCentres,
    const PackedBoolList& boundaryFacesToRemove
) const
{
1336
    if (foamyHexMeshControls().objOutput())
1337
    {
1338
1339
1340
1341
1342
1343
        DelaunayMeshTools::writeObjMesh
        (
            time().path()/word(meshName + ".obj"),
            points,
            faces
        );
1344
1345
    }

1346
1347
1348
    const label nInternalFaces = readLabel(patchDicts[0].lookup("startFace"));

    reorderPoints(points, boundaryPts, faces, nInternalFaces);
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358

    if (Pstream::parRun())
    {
        reorderProcessorPatches
        (
            meshName,
            instance,
            points,
            faces,
            patchNames,
1359
            patchDicts
1360
1361
1362
        );
    }

1363
1364
    Info<< incrIndent;
    Info<< indent << "Constructing mesh" << endl;
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383

    timeCheck("Before fvMesh construction");

    fvMesh mesh
    (
        IOobject
        (
            meshName,
            instance,
            runTime_,
            IOobject::NO_READ,
            IOobject::AUTO_WRITE
        ),
        xferMove(points),
        xferMove(faces),
        xferMove(owner),
        xferMove(neighbour)
    );

1384
    Info<< indent << "Adding patches to mesh" << endl;
1385

1386
    List<polyPatch*> patches(patchNames.size());
1387
1388
1389
1390
1391

    label nValidPatches = 0;

    forAll(patches, p)
    {
1392
1393
        label totalPatchSize = readLabel(patchDicts[p].lookup("nFaces"));

1394
1395
1396
1397
1398
1399
1400
1401
        if
        (
            patchDicts.set(p)
         && (
                word(patchDicts[p].lookup("type"))
             == processorPolyPatch::typeName
            )
        )
1402
        {
1403
1404
1405
1406
1407
1408
1409
            const_cast<dictionary&>(patchDicts[p]).set
            (
                "transform",
                "noOrdering"
                //"coincidentFullMatch"
            );

1410
            // Do not create empty processor patches
1411
            if (totalPatchSize > 0)
1412
1413
1414
1415
            {
                patches[nValidPatches] = new processorPolyPatch
                (
                    patchNames[p],
1416
                    patchDicts[p],
1417
1418
                    nValidPatches,
                    mesh.boundaryMesh(),
1419
                    processorPolyPatch::typeName
1420
1421
1422
1423
1424
1425
1426
                );

                nValidPatches++;
            }
        }
        else
        {
1427
1428
1429
            // Check that the patch is not empty on every processor
            reduce(totalPatchSize, sumOp<label>());

1430
            if (totalPatchSize > 0)
1431
1432
1433
1434
            {
                patches[nValidPatches] = polyPatch::New
                (
                    patchNames[p],
1435
                    patchDicts[p],
1436
1437
1438
                    nValidPatches,
                    mesh.boundaryMesh()
                ).ptr();
1439

1440
1441
                nValidPatches++;
            }
1442
1443
1444
        }
    }

1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
    patches.setSize(nValidPatches);

    mesh.addFvPatches(patches);


    // Add zones to mesh
    {
        Info<< "    Adding zones to mesh" << endl;

        const PtrList<surfaceZonesInfo>& surfZones =
            geometryToConformTo().surfZones();

        labelList cellToSurface(calcCellZones(cellCentres));

        labelList faceToSurface;
        boolList flipMap;

        calcFaceZones
        (
            mesh,
            cellCentres,
            cellToSurface,
            faceToSurface,
            flipMap
        );

        labelList insidePointNamedSurfaces
        (
            surfaceZonesInfo::getInsidePointNamedSurfaces(surfZones)
        );

        findCellZoneInsideWalk
        (
            mesh,
            insidePointNamedSurfaces,
            faceToSurface,
            cellToSurface
        );

        labelList namedSurfaces(surfaceZonesInfo::getNamedSurfaces(surfZones));

        forAll(namedSurfaces, i)
        {
            label surfI = namedSurfaces[i];

            Info<< incrIndent << indent << "Surface : "
                << geometryToConformTo().geometry().names()[surfI] << nl
                << indent << "    faceZone : "
                << surfZones[surfI].faceZoneName() << nl
                << indent << "    cellZone : "
                << surfZones[surfI].cellZoneName()
                << decrIndent << endl;
        }

        // Add zones to mesh
        labelList surfaceToFaceZone =
            surfaceZonesInfo::addFaceZonesToMesh
            (
                surfZones,
                namedSurfaces,
                mesh
            );

        labelList surfaceToCellZone =
            surfaceZonesInfo::addCellZonesToMesh
            (
                surfZones,
                namedSurfaces,
                mesh
            );

        // Topochange container
        polyTopoChange meshMod(mesh);

        forAll(cellToSurface, cellI)
        {
            label surfaceI = cellToSurface[cellI];

            if (surfaceI >= 0)
            {
                label zoneI = surfaceToCellZone[surfaceI];

                if (zoneI >= 0)
                {
                    meshMod.setAction
                    (
                        polyModifyCell
                        (
                            cellI,
                            false,          // removeFromZone
                            zoneI
                        )
                    );
                }
            }
        }

        const labelList& faceOwner = mesh.faceOwner();
        const labelList& faceNeighbour = mesh.faceNeighbour();

1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
//        // Get coupled neighbour cellZone. Set to -1 on non-coupled patches.
//        labelList neiCellZone(mesh.nFaces() - mesh.nInternalFaces(), -1);
//
//        const polyBoundaryMesh& patches = mesh.boundaryMesh();
//
//        forAll(patches, patchI)
//        {
//            const polyPatch& pp = patches[patchI];
//
//            if (pp.coupled())
//            {
//                forAll(pp, i)
//                {
//                    label faceI = pp.start()+i;
//                    neiCellZone[faceI - mesh.nInternalFaces()] =
//                        surfaceToCellZone[cellToSurface[faceOwner[faceI]]];
//                }
//            }
//        }
//
//        syncTools::swapBoundaryFaceList(mesh, neiCellZone);

1567
1568
        forAll(faceToSurface, faceI)
        {
1569
1570
1571
            label surfaceI = faceToSurface[faceI];

            if (surfaceI < 0)
1572
1573
1574
1575
            {
                continue;
            }

1576
            label patchID = mesh.boundaryMesh().whichPatch(faceI);
1577

1578
            if (mesh.isInternalFace(faceI))
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
            {
                label own = faceOwner[faceI];
                label nei = faceNeighbour[faceI];

                meshMod.setAction
                (
                    polyModifyFace
                    (
                        mesh.faces()[faceI],            // modified face
                        faceI,                          // label of face
                        own,                            // owner
                        nei,                            // neighbour
                        false,                          // face flip
                        -1,                             // patch for face
                        false,                          // remove from zone
                        surfaceToFaceZone[surfaceI],    // zone for face
                        flipMap[faceI]                  // face flip in zone
                    )
                );
            }
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
            else if (patchID != -1 && mesh.boundaryMesh()[patchID].coupled())
            {
                label own = faceOwner[faceI];

                meshMod.setAction
                (
                    polyModifyFace
                    (
                        mesh.faces()[faceI],           // modified face
                        faceI,                          // label of face
                        own,               // owner
                        -1,                             // neighbour
                        false,                          // face flip
                        patchID,                         // patch for face
                        false,                          // remove from zone
                        surfaceToFaceZone[surfaceI],       // zone for face
                        flipMap[faceI]                            // face flip in zone
                    )
                );
            }
1619
1620
1621
1622
1623
1624
1625
1626
1627
        }

        // Change the mesh (no inflation, parallel sync)
        autoPtr<mapPolyMesh> map = meshMod.changeMesh(mesh, false, true);
    }




1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
    // Add indirectPatchFaces to a face zone
    {
        labelList addr(boundaryFacesToRemove.count());
        label count = 0;

        forAll(boundaryFacesToRemove, faceI)
        {
            if (boundaryFacesToRemove[faceI])
            {
                addr[count++] = faceI;
            }
        }

        label sz = mesh.faceZones().size();
        boolList flip(addr.size(), false);
        mesh.faceZones().setSize(sz + 1);
        mesh.faceZones().set
        (
            sz,
            new faceZone
            (
                "indirectPatchFaces",
                addr,
                flip,
                sz,
                mesh.faceZones()
            )
        );
    }

    timeCheck("Before fvMesh filtering");

    autoPtr<polyMeshFilter> meshFilter;

    label nInitialBadFaces = 0;

1664
    if (foamyHexMeshControls().filterEdges())
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
    {
        Info<< nl << "Filtering edges on polyMesh" << nl << endl;

        meshFilter.reset(new polyMeshFilter(mesh));

        // Filter small edges only. This reduces the number of faces so that
        // the face filtering is sped up.
        nInitialBadFaces = meshFilter().filterEdges(0);
        {
            const autoPtr<fvMesh>& newMesh = meshFilter().filteredMesh();

            polyTopoChange meshMod(newMesh);

            meshMod.changeMesh(mesh, false);
        }
    }

1682
    if (foamyHexMeshControls().filterFaces())
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
    {
        Info<< nl << "Filtering faces on polyMesh" << nl << endl;

        meshFilter.reset(new polyMeshFilter(mesh));

        meshFilter().filter(nInitialBadFaces);
        {
            const autoPtr<fvMesh>& newMesh = meshFilter().filteredMesh();

            polyTopoChange meshMod(newMesh);

            meshMod.changeMesh(mesh, false);
        }
    }

    timeCheck("After fvMesh filtering");

    mesh.setInstance(instance);

    if (!mesh.write())
    {
        FatalErrorIn("Foam::conformalVoronoiMesh::writeMesh(..)")
            << "Failed writing polyMesh."
            << exit(FatalError);
    }
    else
    {
        Info<< nl << "Written filtered mesh to "
            << mesh.polyMesh::instance() << nl
            << endl;
    }


laurence's avatar
laurence committed
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
//    volTensorField alignments
//    (
//        IOobject
//        (
//            "alignmentsField",
//            runTime_.timeName(),
//            runTime_,
//            IOobject::NO_READ,
//            IOobject::AUTO_WRITE
//        ),
//        mesh,
//        tensor::zero
//    );
//
//    forAll(mesh.cellCentres(), pI)
//    {
//        Vertex_handle nearV =
//            nearest_vertex
//            (
//                toPoint<Point>(mesh.cellCentres()[pI])
//            );
//        alignments[pI] = nearV->alignment();
//    }
//    alignments.write();
//
//    {
//        volVectorField alignmentx
//        (
//            IOobject
//            (
//                "alignmentsx",
//                runTime_.timeName(),
//                runTime_,
//                IOobject::NO_READ,
//                IOobject::AUTO_WRITE
//            ),
//            mesh,
//            vector::zero
//        );
//        forAll(alignmentx, aI)
//        {
//            alignmentx[aI] = alignments[aI].x();
//        }
//        alignmentx.write();
//    }
//    {
//        volVectorField alignmenty
//        (
//            IOobject
//            (
//                "alignmentsy",
//                runTime_.timeName(),
//                runTime_,
//                IOobject::NO_READ,
//                IOobject::AUTO_WRITE
//            ),
//            mesh,
//            vector::zero
//        );
//        forAll(alignmenty, aI)
//        {
//            alignmenty[aI] = alignments[aI].y();
//        }
//        alignmenty.write();
//    }
//    {
//        volVectorField alignmentz
//        (
//            IOobject
//            (
//                "alignmentsz",
//                runTime_.timeName(),
//                runTime_,
//                IOobject::NO_READ,
//                IOobject::AUTO_WRITE
//            ),
//            mesh,
//            vector::zero
//        );
//        forAll(alignmentz, aI)
//        {
//            alignmentz[aI] = alignments[aI].z();
//        }
//        alignmentz.write();
//    }
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147


    labelIOList boundaryIOPts
    (
        IOobject
        (
            "boundaryPoints",
            instance,
            runTime_,
            IOobject::NO_READ,
            IOobject::AUTO_WRITE
        ),
        boundaryPts
    );

    // Dump list of boundary points
    forAll(mesh.boundaryMesh(), patchI)
    {
        const polyPatch& pp = mesh.boundaryMesh()[patchI];

        if (!isA<coupledPolyPatch>(pp))
        {
            forAll(pp, fI)
            {
                const face& boundaryFace = pp[fI];

                forAll(boundaryFace, pI)
                {
                    const label boundaryPointI = boundaryFace[pI];

                    boundaryIOPts[boundaryPointI] = boundaryPts[boundaryPointI];
                }
            }
        }
    }

    boundaryIOPts.write();

//    forAllConstIter(labelHashSet, pointsInPatch, pI)
//    {
//        const Foam::point& ptMaster = mesh.points()[pI.key()];
//
//        forAllConstIter(labelHashSet, pointsInPatch, ptI)
//        {
//            if (ptI.key() != pI.key())
//            {
//                const Foam::point& ptSlave = mesh.points()[ptI.key()];
//
//                const scalar dist = mag(ptMaster - ptSlave);
//                if (ptMaster == ptSlave)
//                {
//                    Pout<< "Point(" << pI.key() << ") " << ptMaster
//                        << " == "
//                        << "(" << ptI.key() << ") " << ptSlave
//                        << endl;
//                }
//                else if (dist == 0)
//                {
//                    Pout<< "Point(" << pI.key() << ") " << ptMaster
//                        << " ~= "
//                        << "(" << ptI.key() << ") " << ptSlave
//                        << endl;
//                }
//            }
//        }
//    }

//    writeCellSizes(mesh);

//    writeCellAlignments(mesh);

//    writeCellCentres(mesh);

//    findRemainingProtrusionSet(mesh);
}


void Foam::conformalVoronoiMesh::writeCellSizes
(
    const fvMesh& mesh
) const
{
    {
        timeCheck("Start writeCellSizes");

        Info<< nl << "Create targetCellSize volScalarField" << endl;

        volScalarField targetCellSize
        (
            IOobject
            (
                "targetCellSize",
                mesh.polyMesh::instance(),
                mesh,
                IOobject::NO_READ,
                IOobject::AUTO_WRITE
            ),
            mesh,
            dimensionedScalar("cellSize", dimLength, 0),
            zeroGradientFvPatchScalarField::typeName
        );

        scalarField& cellSize = targetCellSize.internalField();

        const vectorField& C = mesh.cellCentres();

        forAll(cellSize, i)
        {
            cellSize[i] = cellShapeControls().cellSize(C[i]);
        }

        // Info<< nl << "Create targetCellVolume volScalarField" << endl;

        // volScalarField targetCellVolume
        // (
        //     IOobject
        //     (
        //         "targetCellVolume",
        //         mesh.polyMesh::instance(),
        //         mesh,
        //         IOobject::NO_READ,
        //         IOobject::AUTO_WRITE
        //     ),
        //     mesh,
        //     dimensionedScalar("cellVolume", dimLength, 0),
        //     zeroGradientFvPatchScalarField::typeName
        // );

        // targetCellVolume.internalField() = pow3(cellSize);

        // Info<< nl << "Create actualCellVolume volScalarField" << endl;

        // volScalarField actualCellVolume
        // (
        //     IOobject
        //     (
        //         "actualCellVolume",
        //         mesh.polyMesh::instance(),
        //         mesh,
        //         IOobject::NO_READ,
        //         IOobject::AUTO_WRITE
        //     ),
        //     mesh,
        //     dimensionedScalar("cellVolume", dimVolume, 0),
        //     zeroGradientFvPatchScalarField::typeName
        // );

        // actualCellVolume.internalField() = mesh.cellVolumes();

        // Info<< nl << "Create equivalentCellSize volScalarField" << endl;

        // volScalarField equivalentCellSize
        // (
        //     IOobject
        //     (
        //         "equivalentCellSize",
        //         mesh.polyMesh::instance(),
        //         mesh,
        //         IOobject::NO_READ,
        //         IOobject::AUTO_WRITE
        //     ),
        //     mesh,
        //     dimensionedScalar("cellSize", dimLength, 0),
        //     zeroGradientFvPatchScalarField::typeName
        // );

        // equivalentCellSize.internalField() = pow
        // (
        //     actualCellVolume.internalField(),
        //     1.0/3.0
        // );

        targetCellSize.correctBoundaryConditions();
        // targetCellVolume.correctBoundaryConditions();
        // actualCellVolume.correctBoundaryConditions();
        // equivalentCellSize.correctBoundaryConditions();

        targetCellSize.write();
        // targetCellVolume.write();
        // actualCellVolume.write();
        // equivalentCellSize.write();
    }

    // {
    //     polyMesh tetMesh
    //     (
    //         IOobject
    //         (
    //             "tetDualMesh",
    //             runTime_.constant(),
    //             runTime_,
    //             IOobject::MUST_READ
    //         )
    //     );

    //     pointMesh ptMesh(tetMesh);

    //     pointScalarField ptTargetCellSize
    //     (
    //         IOobject
    //         (
    //             "ptTargetCellSize",
    //             runTime_.timeName(),
    //             tetMesh,
    //             IOobject::NO_READ,
    //             IOobject::AUTO_WRITE
    //         ),
    //         ptMesh,
    //         dimensionedScalar("ptTargetCellSize", dimLength, 0),
    //         pointPatchVectorField::calculatedType()
    //     );

    //     scalarField& cellSize = ptTargetCellSize.internalField();

    //     const vectorField& P = tetMesh.points();

    //     forAll(cellSize, i)
    //     {
    //         cellSize[i] = cellShapeControls().cellSize(P[i]);
    //     }

    //     ptTargetCellSize.write();
    // }
}


void Foam::conformalVoronoiMesh::writeCellAlignments
(
    const fvMesh& mesh
) const
{
//    Info<< nl << "Create cellAlignments volTensorField" << endl;
//
//    volTensorField cellAlignments
//    (
//        IOobject
//        (
//            "cellAlignments",
//            mesh.polyMesh::instance(),
//            mesh,
//            IOobject::NO_READ,
//            IOobject::AUTO_WRITE
//        ),
//        mesh,
//        tensor::I,
//        zeroGradientFvPatchTensorField::typeName
//    );
//
//    tensorField& cellAlignment = cellAlignments.internalField();
//
//    const vectorField& C = mesh.cellCentres();
//
//    vectorField xDir(cellAlignment.size());
//    vectorField yDir(cellAlignment.size());
//    vectorField zDir(cellAlignment.size());
//
//    forAll(cellAlignment, i)
//    {
//        cellAlignment[i] = cellShapeControls().cellAlignment(C[i]);
//        xDir[i] = cellAlignment[i] & vector(1, 0, 0);
//        yDir[i] = cellAlignment[i] & vector(0, 1, 0);
//        zDir[i] = cellAlignment[i] & vector(0, 0, 1);
//    }
//
//    OFstream xStr("xDir.obj");
//    OFstream yStr("yDir.obj");
//    OFstream zStr("zDir.obj");
//
//    forAll(xDir, i)
//    {
//        meshTools::writeOBJ(xStr, C[i], C[i] + xDir[i]);
//        meshTools::writeOBJ(yStr, C[i], C[i] + yDir[i]);
//        meshTools::writeOBJ(zStr, C[i], C[i] + zDir[i]);
//    }
//
//    cellAlignments.correctBoundaryConditions();
//
//    cellAlignments.write();
}


void Foam::conformalVoronoiMesh::writeCellCentres
(
    const fvMesh& mesh
) const
{
    Info<< "Writing components of cellCentre positions to volScalarFields"
        << " ccx, ccy, ccz in " <<  runTime_.timeName() << endl;

    for (direction i=0; i<vector::nComponents; i++)
    {
        volScalarField cci
        (
            IOobject
            (
                "cc" + word(vector::componentNames[i]),
                runTime_.timeName(),
                mesh,
                IOobject::NO_READ,
                IOobject::AUTO_WRITE
            ),
            mesh.C().component(i)
        );

        cci.write();
    }
}


Foam::labelHashSet Foam::conformalVoronoiMesh::findRemainingProtrusionSet
(
    const polyMesh& mesh
) const
{
    timeCheck("Start findRemainingProtrusionSet");

    const polyBoundaryMesh& patches = mesh.boundaryMesh();

    labelHashSet protrudingBoundaryPoints;

    forAll(patches, patchI)
    {
        const polyPatch& patch = patches[patchI];

        forAll(patch.localPoints(), pLPI)
        {
            label meshPtI = patch.meshPoints()[pLPI];

            const Foam::point& pt = patch.localPoints()[pLPI];

            if
            (
                geometryToConformTo_.wellOutside
                (
                    pt,
                    sqr(targetCellSize(pt))
                )
            )
            {
                protrudingBoundaryPoints.insert(meshPtI);
            }
        }
    }

    cellSet protrudingCells
    (
        mesh,
2148
        "foamyHexMesh_remainingProtrusions",
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
        mesh.nCells()/1000
    );

    forAllConstIter(labelHashSet, protrudingBoundaryPoints, iter)
    {
        const label pointI = iter.key();
        const labelList& pCells = mesh.pointCells()[pointI];

        forAll(pCells, pCI)
        {
            protrudingCells.insert(pCells[pCI]);
        }
    }

    label protrudingCellsSize = protrudingCells.size();

    reduce(protrudingCellsSize, sumOp<label>());

2167
    if (foamyHexMeshControls().objOutput() && protrudingCellsSize > 0)
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
    {
        Info<< nl << "Found " << protrudingCellsSize
            << " cells protruding from the surface, writing cellSet "
            << protrudingCells.name()
            << endl;

        protrudingCells.write();
    }

    return protrudingCells;
}


// ************************************************************************* //