surfaceCheck.C 18.3 KB
Newer Older
1
2
3
4
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
5
    \\  /    A nd           | Copyright (C) 1991-2010 OpenCFD Ltd.
6
7
8
9
10
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

11
12
13
14
    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.
15
16
17
18
19
20
21

    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
22
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.
23
24
25
26
27
28
29
30
31
32
33

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

#include "triangle.H"
#include "triSurface.H"
#include "triSurfaceTools.H"
#include "triSurfaceSearch.H"
#include "argList.H"
#include "OFstream.H"
#include "surfaceIntersection.H"
#include "SortableList.H"
mattijs's avatar
mattijs committed
34
#include "PatchTools.H"
35
36
37
38

using namespace Foam;

// Does face use valid vertices?
Mark Olesen's avatar
Mark Olesen committed
39
40
41
42
43
44
bool validTri
(
    const bool verbose,
    const triSurface& surf,
    const label faceI
)
45
46
47
48
49
50
51
52
53
54
55
56
{
    // Simple check on indices ok.

    const labelledTri& f = surf[faceI];

    if
    (
        (f[0] < 0) || (f[0] >= surf.points().size())
     || (f[1] < 0) || (f[1] >= surf.points().size())
     || (f[2] < 0) || (f[2] >= surf.points().size())
    )
    {
mattijs's avatar
mattijs committed
57
58
59
60
        WarningIn("validTri(const triSurface&, const label)")
            << "triangle " << faceI << " vertices " << f
            << " uses point indices outside point range 0.."
            << surf.points().size()-1 << endl;
61
62
63
64
65
66

        return false;
    }

    if ((f[0] == f[1]) || (f[0] == f[2]) || (f[1] == f[2]))
    {
mattijs's avatar
mattijs committed
67
68
69
70
71
        WarningIn("validTri(const triSurface&, const label)")
            << "triangle " << faceI
            << " uses non-unique vertices " << f
            << " coords:" << f.points(surf.points())
            << endl;
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
        return false;
    }

    // duplicate triangle check

    const labelList& fFaces = surf.faceFaces()[faceI];

    // Check if faceNeighbours use same points as this face.
    // Note: discards normal information - sides of baffle are merged.
    forAll(fFaces, i)
    {
        label nbrFaceI = fFaces[i];

        if (nbrFaceI <= faceI)
        {
            // lower numbered faces already checked
            continue;
        }

        const labelledTri& nbrF = surf[nbrFaceI];

        if
        (
            ((f[0] == nbrF[0]) || (f[0] == nbrF[1]) || (f[0] == nbrF[2]))
         && ((f[1] == nbrF[0]) || (f[1] == nbrF[1]) || (f[1] == nbrF[2]))
         && ((f[2] == nbrF[0]) || (f[2] == nbrF[1]) || (f[2] == nbrF[2]))
        )
        {
mattijs's avatar
mattijs committed
100
101
102
103
104
105
            WarningIn("validTri(const triSurface&, const label)")
                << "triangle " << faceI << " vertices " << f
                << " has the same vertices as triangle " << nbrFaceI
                << " vertices " << nbrF
                << " coords:" << f.points(surf.points())
                << endl;
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

            return false;
        }
    }
    return true;
}


labelList countBins
(
    const scalar min,
    const scalar max,
    const label nBins,
    const scalarField& vals
)
{
    scalar dist = nBins/(max - min);

    labelList binCount(nBins, 0);

    forAll(vals, i)
    {
        scalar val = vals[i];

        label index = -1;

        if (Foam::mag(val - min) < SMALL)
        {
            index = 0;
        }
        else if (val >= max - SMALL)
        {
            index = nBins - 1;
        }
        else
        {
            index = label((val - min)*dist);

            if ((index < 0) || (index >= nBins))
            {
                WarningIn
                (
                    "countBins(const scalar, const scalar, const label"
                    ", const scalarField&)"
                )   << "value " << val << " at index " << i
                    << " outside range " << min << " .. " << max << endl;

                if (index < 0)
                {
                    index = 0;
                }
                else
                {
                    index = nBins - 1;
                }
            }
        }
        binCount[index]++;
    }

    return binCount;
}


// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Main program:

int main(int argc, char *argv[])
{
    argList::noParallel();
176
177
178
179
180
181
182
183
184
185
186
    argList::validArgs.append("surfaceFile");
    argList::addBoolOption
    (
        "checkSelfIntersection",
        "also check for self-intersection"
    );
    argList::addBoolOption
    (
        "verbose",
        "verbose operation"
    );
Mark Olesen's avatar
Mark Olesen committed
187
188
189
190
191
    argList::addBoolOption
    (
        "blockMesh",
        "write vertices/blocks for blockMeshDict"
    );
192

193
194
    argList args(argc, argv);

195
196
197
    const fileName surfFileName = args[1];
    const bool checkSelfIntersect = args.optionFound("checkSelfIntersection");
    const bool verbose = args.optionFound("verbose");
198

Mark Olesen's avatar
Mark Olesen committed
199
    Info<< "Reading surface from " << surfFileName << " ..." << nl << endl;
200
201
202
203
204
205
206
207


    // Read
    // ~~~~

    triSurface surf(surfFileName);


Mark Olesen's avatar
Mark Olesen committed
208
209
210
211
212
213
214
    Info<< "Statistics:" << endl;
    surf.writeStats(Info);
    Info<< endl;

    // write bounding box corners
    if (args.optionFound("blockMesh"))
    {
215
        pointField cornerPts = boundBox(surf.points()).points();
Mark Olesen's avatar
Mark Olesen committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231

        Info<<"// blockMeshDict info" << nl;

        Info<<"vertices\n(" << nl;
        forAll(cornerPts, ptI)
        {
            Info << "    " << cornerPts[ptI] << nl;
        }

        // number of divisions needs adjustment later
        Info<<");\n" << nl
            <<"blocks\n"
            <<"(\n"
            <<"    hex (0 1 2 3 4 5 6 7) (10 10 10) simpleGrading (1 1 1)\n"
            <<");\n" << nl;

232
233
        Info<<"edges\n();" << nl
            <<"patches\n();" << endl;
Mark Olesen's avatar
Mark Olesen committed
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


    // Region sizes
    // ~~~~~~~~~~~~

    {
        labelList regionSize(surf.patches().size(), 0);

        forAll(surf, faceI)
        {
            label region = surf[faceI].region();

            if (region < 0 || region >= regionSize.size())
            {
                WarningIn(args.executable())
                    << "Triangle " << faceI << " vertices " << surf[faceI]
                    << " has region " << region << " which is outside the range"
                    << " of regions 0.." << surf.patches().size()-1
                    << endl;
            }
            else
            {
                regionSize[region]++;
            }
        }

Mark Olesen's avatar
Mark Olesen committed
261
        Info<< "Region\tSize" << nl
262
263
264
            << "------\t----" << nl;
        forAll(surf.patches(), patchI)
        {
Mark Olesen's avatar
Mark Olesen committed
265
            Info<< surf.patches()[patchI].name() << '\t'
266
267
                << regionSize[patchI] << nl;
        }
Mark Olesen's avatar
Mark Olesen committed
268
        Info<< nl << endl;
269
270
271
272
273
274
275
276
277
278
279
    }


    // Check triangles
    // ~~~~~~~~~~~~~~~

    {
        DynamicList<label> illegalFaces(surf.size()/100 + 1);

        forAll(surf, faceI)
        {
mattijs's avatar
mattijs committed
280
            if (!validTri(verbose, surf, faceI))
281
282
283
284
285
            {
                illegalFaces.append(faceI);
            }
        }

286
        if (illegalFaces.size())
287
        {
Mark Olesen's avatar
Mark Olesen committed
288
            Info<< "Surface has " << illegalFaces.size()
289
290
291
                << " illegal triangles." << endl;

            OFstream str("illegalFaces");
Mark Olesen's avatar
Mark Olesen committed
292
            Info<< "Dumping conflicting face labels to " << str.name() << endl
293
294
295
296
297
                << "Paste this into the input for surfaceSubset" << endl;
            str << illegalFaces;
        }
        else
        {
Mark Olesen's avatar
Mark Olesen committed
298
            Info<< "Surface has no illegal triangles." << endl;
299
        }
Mark Olesen's avatar
Mark Olesen committed
300
        Info<< endl;
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    }



    // Triangle quality
    // ~~~~~~~~~~~~~~~~

    {
        scalarField triQ(surf.size(), 0);
        forAll(surf, faceI)
        {
            const labelledTri& f = surf[faceI];

            if (f[0] == f[1] || f[0] == f[2] || f[1] == f[2])
            {
Mattijs Janssens's avatar
Mattijs Janssens committed
316
317
318
                //WarningIn(args.executable())
                //    << "Illegal triangle " << faceI << " vertices " << f
                //    << " coords " << f.points(surf.points()) << endl;
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
            }
            else
            {
                triPointRef tri
                (
                    surf.points()[f[0]],
                    surf.points()[f[1]],
                    surf.points()[f[2]]
                );

                vector ba(tri.b() - tri.a());
                ba /= mag(ba) + VSMALL;

                vector ca(tri.c() - tri.a());
                ca /= mag(ca) + VSMALL;

                if (mag(ba&ca) > 1-1E-3)
                {
                    triQ[faceI] = SMALL;
                }
                else
                {
                    triQ[faceI] = triPointRef
                    (
                        surf.points()[f[0]],
                        surf.points()[f[1]],
                        surf.points()[f[2]]
                    ).quality();
                }
            }
        }

        labelList binCount = countBins(0, 1, 20, triQ);

Mark Olesen's avatar
Mark Olesen committed
353
        Info<< "Triangle quality (equilateral=1, collapsed=0):"
354
355
356
            << endl;


Mark Olesen's avatar
Mark Olesen committed
357
        OSstream& os = Info;
358
359
360
361
362
363
        os.width(4);

        scalar dist = (1.0 - 0.0)/20.0;
        scalar min = 0;
        forAll(binCount, binI)
        {
Mark Olesen's avatar
Mark Olesen committed
364
            Info<< "    " << min << " .. " << min+dist << "  : "
365
366
                << 1.0/surf.size() * binCount[binI]
                << endl;
367
            min += dist;
368
        }
Mark Olesen's avatar
Mark Olesen committed
369
        Info<< endl;
370
371
372
373

        label minIndex = findMin(triQ);
        label maxIndex = findMax(triQ);

Mark Olesen's avatar
Mark Olesen committed
374
        Info<< "    min " << triQ[minIndex] << " for triangle " << minIndex
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
            << nl
            << "    max " << triQ[maxIndex] << " for triangle " << maxIndex
            << nl
            << endl;


        if (triQ[minIndex] < SMALL)
        {
            WarningIn(args.executable()) << "Minimum triangle quality is "
                << triQ[minIndex] << ". This might give problems in"
                << " self-intersection testing later on." << endl;
        }

        // Dump for subsetting
        {
            DynamicList<label> problemFaces(surf.size()/100+1);

            forAll(triQ, faceI)
            {
                if (triQ[faceI] < 1E-11)
                {
                    problemFaces.append(faceI);
                }
            }

400
401
402
403
404
405
406
            if (!problemFaces.empty())
            {
                OFstream str("badFaces");

                Info<< "Dumping bad quality faces to " << str.name() << endl
                    << "Paste this into the input for surfaceSubset" << nl
                    << nl << endl;
407

408
409
                str << problemFaces;
            }
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
        }
    }



    // Edges
    // ~~~~~
    {
        const edgeList& edges = surf.edges();
        const pointField& localPoints = surf.localPoints();

        scalarField edgeMag(edges.size());

        forAll(edges, edgeI)
        {
            edgeMag[edgeI] = edges[edgeI].mag(localPoints);
        }

        label minEdgeI = findMin(edgeMag);
        label maxEdgeI = findMax(edgeMag);

        const edge& minE = edges[minEdgeI];
        const edge& maxE = edges[maxEdgeI];


Mark Olesen's avatar
Mark Olesen committed
435
        Info<< "Edges:" << nl
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
            << "    min " << edgeMag[minEdgeI] << " for edge " << minEdgeI
            << " points " << localPoints[minE[0]] << localPoints[minE[1]]
            << nl
            << "    max " << edgeMag[maxEdgeI] << " for edge " << maxEdgeI
            << " points " << localPoints[maxE[0]] << localPoints[maxE[1]]
            << nl
            << endl;
    }



    // Close points
    // ~~~~~~~~~~~~
    {
        const edgeList& edges = surf.edges();
        const pointField& localPoints = surf.localPoints();

        const boundBox bb(localPoints);
454
        scalar smallDim = 1E-6 * bb.mag();
455

Mark Olesen's avatar
Mark Olesen committed
456
        Info<< "Checking for points less than 1E-6 of bounding box ("
457
            << bb.span() << " meter) apart."
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
            << endl;

        // Sort points
        SortableList<scalar> sortedMag(mag(localPoints));

        label nClose = 0;

        for (label i = 1; i < sortedMag.size(); i++)
        {
            label ptI = sortedMag.indices()[i];

            label prevPtI = sortedMag.indices()[i-1];

            if (mag(localPoints[ptI] - localPoints[prevPtI]) < smallDim)
            {
                // Check if neighbours.
                const labelList& pEdges = surf.pointEdges()[ptI];

                label edgeI = -1;

                forAll(pEdges, i)
                {
                    const edge& e = edges[pEdges[i]];

                    if (e[0] == prevPtI || e[1] == prevPtI)
                    {
                        // point1 and point0 are connected through edge.
                        edgeI = pEdges[i];

                        break;
                    }
                }

                nClose++;

                if (edgeI == -1)
                {
Mark Olesen's avatar
Mark Olesen committed
495
                    Info<< "    close unconnected points "
496
497
498
499
500
501
502
503
504
                        << ptI << ' ' << localPoints[ptI]
                        << " and " << prevPtI << ' '
                        << localPoints[prevPtI]
                        << " distance:"
                        << mag(localPoints[ptI] - localPoints[prevPtI])
                        << endl;
                }
                else
                {
Mark Olesen's avatar
Mark Olesen committed
505
                    Info<< "    small edge between points "
506
507
508
509
510
511
512
513
514
515
                        << ptI << ' ' << localPoints[ptI]
                        << " and " << prevPtI << ' '
                        << localPoints[prevPtI]
                        << " distance:"
                        << mag(localPoints[ptI] - localPoints[prevPtI])
                        << endl;
                }
            }
        }

Mark Olesen's avatar
Mark Olesen committed
516
        Info<< "Found " << nClose << " nearby points." << nl
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
            << endl;
    }



    // Check manifold
    // ~~~~~~~~~~~~~~

    DynamicList<label> problemFaces(surf.size()/100 + 1);

    const labelListList& eFaces = surf.edgeFaces();

    label nSingleEdges = 0;
    forAll(eFaces, edgeI)
    {
        const labelList& myFaces = eFaces[edgeI];

        if (myFaces.size() == 1)
        {
            problemFaces.append(myFaces[0]);

            nSingleEdges++;
        }
    }
541

542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
    label nMultEdges = 0;
    forAll(eFaces, edgeI)
    {
        const labelList& myFaces = eFaces[edgeI];

        if (myFaces.size() > 2)
        {
            forAll(myFaces, myFaceI)
            {
                problemFaces.append(myFaces[myFaceI]);
            }

            nMultEdges++;
        }
    }
    problemFaces.shrink();

    if ((nSingleEdges != 0) || (nMultEdges != 0))
    {
Mark Olesen's avatar
Mark Olesen committed
561
        Info<< "Surface is not closed since not all edges connected to "
562
563
564
565
            << "two faces:" << endl
            << "    connected to one face : " << nSingleEdges << endl
            << "    connected to >2 faces : " << nMultEdges << endl;

Mark Olesen's avatar
Mark Olesen committed
566
        Info<< "Conflicting face labels:" << problemFaces.size() << endl;
567
568
569

        OFstream str("problemFaces");

Mark Olesen's avatar
Mark Olesen committed
570
        Info<< "Dumping conflicting face labels to " << str.name() << endl
571
572
573
574
575
576
            << "Paste this into the input for surfaceSubset" << endl;

        str << problemFaces;
    }
    else
    {
Mark Olesen's avatar
Mark Olesen committed
577
        Info<< "Surface is closed. All edges connected to two faces." << endl;
578
    }
Mark Olesen's avatar
Mark Olesen committed
579
    Info<< endl;
580
581
582
583
584
585
586
587
588



    // Check singly connected domain
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    labelList faceZone;
    label numZones = surf.markZones(boolList(surf.nEdges(), false), faceZone);

Mark Olesen's avatar
Mark Olesen committed
589
    Info<< "Number of unconnected parts : " << numZones << endl;
590
591
592

    if (numZones > 1)
    {
Mark Olesen's avatar
Mark Olesen committed
593
        Info<< "Splitting surface into parts ..." << endl << endl;
594
595
596

        fileName surfFileNameBase(surfFileName.name());

597
        for (label zone = 0; zone < numZones; zone++)
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
        {
            boolList includeMap(surf.size(), false);

            forAll(faceZone, faceI)
            {
                if (faceZone[faceI] == zone)
                {
                    includeMap[faceI] = true;
                }
            }

            labelList pointMap;
            labelList faceMap;

            triSurface subSurf
            (
                surf.subsetMesh
                (
                    includeMap,
                    pointMap,
                    faceMap
                )
            );

            fileName subFileName
            (
                surfFileNameBase.lessExt()
              + "_"
              + name(zone)
627
              + ".obj"
628
629
            );

Mark Olesen's avatar
Mark Olesen committed
630
            Info<< "writing part " << zone << " size " << subSurf.size()
631
632
633
634
635
636
637
638
639
640
641
642
643
                << " to " << subFileName << endl;

            subSurf.write(subFileName);
        }

        return 0;
    }



    // Check orientation
    // ~~~~~~~~~~~~~~~~~

mattijs's avatar
mattijs committed
644
645
    labelHashSet borderEdge(surf.size()/1000);
    PatchTools::checkOrientation(surf, false, &borderEdge);
646
647
648
649
650

    //
    // Colour all faces into zones using borderEdge
    //
    labelList normalZone;
mattijs's avatar
mattijs committed
651
    label numNormalZones = PatchTools::markZones(surf, borderEdge, normalZone);
652

Mark Olesen's avatar
Mark Olesen committed
653
    Info<< endl
654
655
656
657
658
        << "Number of zones (connected area with consistent normal) : "
        << numNormalZones << endl;

    if (numNormalZones > 1)
    {
Mark Olesen's avatar
Mark Olesen committed
659
        Info<< "More than one normal orientation." << endl;
660
    }
Mark Olesen's avatar
Mark Olesen committed
661
    Info<< endl;
662
663
664
665
666
667



    // Check self-intersection
    // ~~~~~~~~~~~~~~~~~~~~~~~

668
    if (checkSelfIntersect)
669
    {
Mark Olesen's avatar
Mark Olesen committed
670
        Info<< "Checking self-intersection." << endl;
671
672
673
674

        triSurfaceSearch querySurf(surf);
        surfaceIntersection inter(querySurf);

675
        if (inter.cutEdges().empty() && inter.cutPoints().empty())
676
        {
Mark Olesen's avatar
Mark Olesen committed
677
            Info<< "Surface is not self-intersecting" << endl;
678
679
680
        }
        else
        {
Mark Olesen's avatar
Mark Olesen committed
681
682
            Info<< "Surface is self-intersecting" << endl;
            Info<< "Writing edges of intersection to selfInter.obj" << endl;
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698

            OFstream intStream("selfInter.obj");
            forAll(inter.cutPoints(), cutPointI)
            {
                const point& pt = inter.cutPoints()[cutPointI];

                intStream << "v " << pt.x() << ' ' << pt.y() << ' ' << pt.z()
                    << endl;
            }
            forAll(inter.cutEdges(), cutEdgeI)
            {
                const edge& e = inter.cutEdges()[cutEdgeI];

                intStream << "l " << e.start()+1 << ' ' << e.end()+1 << endl;
            }
        }
Mark Olesen's avatar
Mark Olesen committed
699
        Info<< endl;
700
    }
701

702

Mark Olesen's avatar
Mark Olesen committed
703
    Info<< "\nEnd\n" << endl;
704
705
706
707
708
709

    return 0;
}


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