triSurfaceMesh.C 16.5 KB
Newer Older
1
2
3
4
/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
Mark Olesen's avatar
Mark Olesen committed
5
    \\  /    A nd           | Copyright (C) 1991-2009 OpenCFD Ltd.
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
     \\/     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 2 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, write to the Free Software Foundation,
    Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

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

#include "triSurfaceMesh.H"
#include "Random.H"
#include "addToRunTimeSelectionTable.H"
#include "EdgeMap.H"
mattijs's avatar
mattijs committed
31
32
#include "triSurfaceFields.H"
#include "Time.H"
33
34
35
36
37
38
39
40
41
42
43
44
45

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

namespace Foam
{

defineTypeNameAndDebug(triSurfaceMesh, 0);
addToRunTimeSelectionTable(searchableSurface, triSurfaceMesh, dict);

}

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

mattijs's avatar
mattijs committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//// Special version of Time::findInstance that does not check headerOk
//// to search for instances of raw files
//Foam::word Foam::triSurfaceMesh::findRawInstance
//(
//    const Time& runTime,
//    const fileName& dir,
//    const word& name
//)
//{
//    // Check current time first
//    if (isFile(runTime.path()/runTime.timeName()/dir/name))
//    {
//        return runTime.timeName();
//    }
//    instantList ts = runTime.times();
//    label instanceI;
//
//    for (instanceI = ts.size()-1; instanceI >= 0; --instanceI)
//    {
//        if (ts[instanceI].value() <= runTime.timeOutputValue())
//        {
//            break;
//        }
//    }
//
//    // continue searching from here
//    for (; instanceI >= 0; --instanceI)
//    {
//        if (isFile(runTime.path()/ts[instanceI].name()/dir/name))
//        {
//            return ts[instanceI].name();
//        }
//    }
//
//
//    // not in any of the time directories, try constant
//
//    // Note. This needs to be a hard-coded constant, rather than the
//    // constant function of the time, because the latter points to
//    // the case constant directory in parallel cases
//
//    if (isFile(runTime.path()/runTime.constant()/dir/name))
//    {
//        return runTime.constant();
//    }
//
//    FatalErrorIn
//    (
//        "searchableSurfaces::findRawInstance"
//        "(const Time&, const fileName&, const word&)"
//    )   << "Cannot find file \"" << name << "\" in directory "
//        << runTime.constant()/dir
//        << exit(FatalError);
//
//    return runTime.constant();
//}


104
105
106
107
108
109
110
//- Check file existence
const Foam::fileName& Foam::triSurfaceMesh::checkFile
(
    const fileName& fName,
    const fileName& objectName
)
{
Mark Olesen's avatar
Mark Olesen committed
111
    if (fName.empty())
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    {
        FatalErrorIn
        (
            "triSurfaceMesh::checkFile(const fileName&, const fileName&)"
        )   << "Cannot find triSurfaceMesh starting from "
            << objectName << exit(FatalError);
    }
    return fName;
}


bool Foam::triSurfaceMesh::isSurfaceClosed() const
{
    // Construct pointFaces. Let's hope surface has compact point
    // numbering ...
    labelListList pointFaces;
    invertManyToMany(points().size(), *this, pointFaces);

    // Loop over all faces surrounding point. Count edges emanating from point.
    // Every edge should be used by two faces exactly.
    // To prevent doing work twice per edge only look at edges to higher
    // point
    EdgeMap<label> facesPerEdge(100);
    forAll(pointFaces, pointI)
    {
        const labelList& pFaces = pointFaces[pointI];

        facesPerEdge.clear();
        forAll(pFaces, i)
        {
            const labelledTri& f = triSurface::operator[](pFaces[i]);
            label fp = findIndex(f, pointI);

            // Forward edge
            {
                label p1 = f[f.fcIndex(fp)];

                if (p1 > pointI)
                {
                    const edge e(pointI, p1);
                    EdgeMap<label>::iterator eFnd = facesPerEdge.find(e);
                    if (eFnd != facesPerEdge.end())
                    {
                        if (eFnd() == 2)
                        {
                            return false;
                        }
                        eFnd()++;
                    }
                    else
                    {
                        facesPerEdge.insert(e, 1);
                    }
                }
            }
            // Reverse edge
            {
                label p1 = f[f.rcIndex(fp)];

                if (p1 > pointI)
                {
                    const edge e(pointI, p1);
                    EdgeMap<label>::iterator eFnd = facesPerEdge.find(e);
                    if (eFnd != facesPerEdge.end())
                    {
                        if (eFnd() == 2)
                        {
                            return false;
                        }
                        eFnd()++;
                    }
                    else
                    {
                        facesPerEdge.insert(e, 1);
                    }
                }
            }
        }

        // Check for any edges used only once.
        forAllConstIter(EdgeMap<label>, facesPerEdge, iter)
        {
            if (iter() != 2)
            {
                return false;
            }
        }
    }

    return true;
}


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

Foam::triSurfaceMesh::triSurfaceMesh(const IOobject& io, const triSurface& s)
:
    searchableSurface(io),
mattijs's avatar
mattijs committed
210
211
212
213
214
215
216
217
218
219
220
221
222
    objectRegistry
    (
        IOobject
        (
            io.name(),
            io.instance(),
            io.local(),
            io.db(),
            io.readOpt(),
            io.writeOpt(),
            false       // searchableSurface already registered under name
        )
    ),
223
224
225
226
227
228
229
    triSurface(s),
    surfaceClosed_(-1)
{}


Foam::triSurfaceMesh::triSurfaceMesh(const IOobject& io)
:
mattijs's avatar
mattijs committed
230
    // Find instance for triSurfaceMesh
mattijs's avatar
mattijs committed
231
232
233
234
235
236
237
238
239
240
241
242
243
    searchableSurface(io),
    //(
    //    IOobject
    //    (
    //        io.name(),
    //        io.time().findInstance(io.local(), word::null),
    //        io.local(),
    //        io.db(),
    //        io.readOpt(),
    //        io.writeOpt(),
    //        io.registerObject()
    //    )
    //),
mattijs's avatar
mattijs committed
244
245
246
247
248
249
250
251
252
253
254
255
256
257
    // Reused found instance in objectRegistry
    objectRegistry
    (
        IOobject
        (
            io.name(),
            static_cast<const searchableSurface&>(*this).instance(),
            io.local(),
            io.db(),
            io.readOpt(),
            io.writeOpt(),
            false       // searchableSurface already registered under name
        )
    ),
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
    triSurface
    (
        checkFile
        (
            searchableSurface::filePath(),
            searchableSurface::objectPath()
        )
    ),
    surfaceClosed_(-1)
{}


Foam::triSurfaceMesh::triSurfaceMesh
(
    const IOobject& io,
    const dictionary& dict
)
:
mattijs's avatar
mattijs committed
276
277
278
279
280
281
282
283
284
285
286
287
288
    searchableSurface(io),
    //(
    //    IOobject
    //    (
    //        io.name(),
    //        io.time().findInstance(io.local(), word::null),
    //        io.local(),
    //        io.db(),
    //        io.readOpt(),
    //        io.writeOpt(),
    //        io.registerObject()
    //    )
    //),
mattijs's avatar
mattijs committed
289
290
291
292
293
294
295
296
297
298
299
300
301
302
    // Reused found instance in objectRegistry
    objectRegistry
    (
        IOobject
        (
            io.name(),
            static_cast<const searchableSurface&>(*this).instance(),
            io.local(),
            io.db(),
            io.readOpt(),
            io.writeOpt(),
            false       // searchableSurface already registered under name
        )
    ),
303
304
305
306
307
308
309
310
311
    triSurface
    (
        checkFile
        (
            searchableSurface::filePath(),
            searchableSurface::objectPath()
        )
    ),
    surfaceClosed_(-1)
312
313
314
315
316
317
318
319
320
321
{
    scalar scaleFactor = 0;

    // allow rescaling of the surface points
    // eg, CAD geometries are often done in millimeters
    if (dict.readIfPresent("scale", scaleFactor) && scaleFactor > 0)
    {
        triSurface::scalePoints(scaleFactor);
    }
}
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


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

Foam::triSurfaceMesh::~triSurfaceMesh()
{
    clearOut();
}


void Foam::triSurfaceMesh::clearOut()
{
    tree_.clear();
    edgeTree_.clear();
    triSurface::clearOut();
}


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

void Foam::triSurfaceMesh::movePoints(const pointField& newPoints)
{
    tree_.clear();
    edgeTree_.clear();
    triSurface::movePoints(newPoints);
}


const Foam::indexedOctree<Foam::treeDataTriSurface>&
    Foam::triSurfaceMesh::tree() const
{
353
    if (tree_.empty())
354
355
356
357
358
359
360
361
362
363
364
    {
        treeBoundBox bb(points(), meshPoints());

        // Random number generator. Bit dodgy since not exactly random ;-)
        Random rndGen(65431);

        tree_.reset
        (
            new indexedOctree<treeDataTriSurface>
            (
                treeDataTriSurface(*this),
mattijs's avatar
mattijs committed
365
                bb.extend(rndGen, 1E-4),    // slightly randomize bb
366
367
368
369
370
371
372
373
374
375
376
377
378
379
                10,     // maxLevel
                10,     // leafsize
                3.0     // duplicity
            )
        );
    }

    return tree_();
}


const Foam::indexedOctree<Foam::treeDataEdge>&
    Foam::triSurfaceMesh::edgeTree() const
{
380
    if (edgeTree_.empty())
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
    {
        treeBoundBox bb(localPoints());

        // Boundary edges
        labelList bEdges
        (
            identity
            (
                nEdges()
               -nInternalEdges()
            )
          + nInternalEdges()
        );

        // Random number generator. Bit dodgy since not exactly random ;-)
        Random rndGen(65431);

        edgeTree_.reset
        (
            new indexedOctree<treeDataEdge>
            (
                treeDataEdge
                (
                    false,          // cachebb
                    edges(),        // edges
                    localPoints(),  // points
                    bEdges          // selected edges
                ),
mattijs's avatar
mattijs committed
409
                bb.extend(rndGen, 1E-4),    // slightly randomize bb
410
411
412
413
414
415
416
417
418
419
420
421
                8,      // maxLevel
                10,     // leafsize
                3.0     // duplicity
            )
        );
    }
    return edgeTree_();
}


const Foam::wordList& Foam::triSurfaceMesh::regions() const
{
422
    if (regions_.empty())
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
    {
        regions_.setSize(patches().size());
        forAll(regions_, regionI)
        {
            regions_[regionI] = patches()[regionI].name();
        }
    }
    return regions_;
}


// Find out if surface is closed.
bool Foam::triSurfaceMesh::hasVolumeType() const
{
    if (surfaceClosed_ == -1)
    {
        if (isSurfaceClosed())
        {
            surfaceClosed_ = 1;
        }
        else
        {
            surfaceClosed_ = 0;
        }
    }

    return surfaceClosed_ == 1;
}


void Foam::triSurfaceMesh::findNearest
(
    const pointField& samples,
    const scalarField& nearestDistSqr,
    List<pointIndexHit>& info
) const
{
    const indexedOctree<treeDataTriSurface>& octree = tree();

    info.setSize(samples.size());

    forAll(samples, i)
    {
        static_cast<pointIndexHit&>(info[i]) =
            octree.findNearest(samples[i], nearestDistSqr[i]);
    }
}


void Foam::triSurfaceMesh::findLine
(
    const pointField& start,
    const pointField& end,
    List<pointIndexHit>& info
) const
{
    const indexedOctree<treeDataTriSurface>& octree = tree();

    info.setSize(start.size());

    forAll(start, i)
    {
        static_cast<pointIndexHit&>(info[i]) = octree.findLine
        (
            start[i],
            end[i]
        );
    }
}


void Foam::triSurfaceMesh::findLineAny
(
    const pointField& start,
    const pointField& end,
    List<pointIndexHit>& info
) const
{
    const indexedOctree<treeDataTriSurface>& octree = tree();

    info.setSize(start.size());

    forAll(start, i)
    {
        static_cast<pointIndexHit&>(info[i]) =
            octree.findLineAny(start[i], end[i]);
    }
}


void Foam::triSurfaceMesh::findLineAll
(
    const pointField& start,
    const pointField& end,
    List<List<pointIndexHit> >& info
) const
{
    const indexedOctree<treeDataTriSurface>& octree = tree();

    info.setSize(start.size());

    // Work array
    DynamicList<pointIndexHit, 1, 1> hits;

527
528
529
530
531
532
    // Tolerances:
    // To find all intersections we add a small vector to the last intersection
    // This is chosen such that
    // - it is significant (SMALL is smallest representative relative tolerance;
    //   we need something bigger since we're doing calculations)
    // - if the start-end vector is zero we still progress
533
534
535
536
537
538
539
540
541
542
    const vectorField dirVec(end-start);
    const scalarField magSqrDirVec(magSqr(dirVec));
    const vectorField smallVec
    (
        Foam::sqrt(SMALL)*dirVec
      + vector(ROOTVSMALL,ROOTVSMALL,ROOTVSMALL)
    );

    forAll(start, pointI)
    {
543
544
        // See if any intersection between pt and end
        pointIndexHit inter = octree.findLine(start[pointI], end[pointI]);
545

546
        if (inter.hit())
547
        {
548
            hits.clear();
549
550
            hits.append(inter);

551
            point pt = inter.hitPoint() + smallVec[pointI];
552

553
            while (((pt-start[pointI])&dirVec[pointI]) <= magSqrDirVec[pointI])
554
            {
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
                // See if any intersection between pt and end
                pointIndexHit inter = octree.findLine(pt, end[pointI]);

                // Check for not hit or hit same triangle as before (can happen
                // if vector along surface of triangle)
                if
                (
                    !inter.hit()
                 || (inter.index() == hits[hits.size()-1].index())
                )
                {
                    break;
                }
                hits.append(inter);

                pt = inter.hitPoint() + smallVec[pointI];
571
572
            }

573
574
575
576
577
578
            info[pointI].transfer(hits);
        }
        else
        {
            info[pointI].clear();
        }
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
    }
}


void Foam::triSurfaceMesh::getRegion
(
    const List<pointIndexHit>& info,
    labelList& region
) const
{
    region.setSize(info.size());
    forAll(info, i)
    {
        if (info[i].hit())
        {
            region[i] = triSurface::operator[](info[i].index()).region();
        }
        else
        {
            region[i] = -1;
        }
    }
}


void Foam::triSurfaceMesh::getNormal
(
    const List<pointIndexHit>& info,
    vectorField& normal
) const
{
    normal.setSize(info.size());

    forAll(info, i)
    {
        if (info[i].hit())
        {
            normal[i] = faceNormals()[info[i].index()];
        }
        else
        {
            // Set to what?
            normal[i] = vector::zero;
        }
    }
}


mattijs's avatar
mattijs committed
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
void Foam::triSurfaceMesh::getField
(
    const word& fieldName,
    const List<pointIndexHit>& info,
    labelList& values
) const
{
    const triSurfaceLabelField& fld = lookupObject<triSurfaceLabelField>
    (
        fieldName
    );

    values.setSize(info.size());
    forAll(info, i)
    {
        if (info[i].hit())
        {
            values[i] = fld[info[i].index()];
        }
    }
}


650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
void Foam::triSurfaceMesh::getVolumeType
(
    const pointField& points,
    List<volumeType>& volType
) const
{
    volType.setSize(points.size());

    forAll(points, pointI)
    {
        const point& pt = points[pointI];

        // - use cached volume type per each tree node
        // - cheat conversion since same values
        volType[pointI] = static_cast<volumeType>(tree().getVolumeType(pt));
    }
}


mattijs's avatar
mattijs committed
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//- Write using given format, version and compression
bool Foam::triSurfaceMesh::writeObject
(
    IOstream::streamFormat fmt,
    IOstream::versionNumber ver,
    IOstream::compressionType cmp
) const
{
    fileName fullPath(searchableSurface::objectPath());

    if (!mkDir(fullPath.path()))
    {
        return false;
    }

    triSurface::write(fullPath);

686
    if (!isFile(fullPath))
mattijs's avatar
mattijs committed
687
688
689
690
691
692
693
694
695
    {
        return false;
    }

    //return objectRegistry::writeObject(fmt, ver, cmp);
    return true;
}


696
// ************************************************************************* //