imstkCollisionUtils.h 28.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
/*=========================================================================

   Library: iMSTK

   Copyright (c) Kitware, Inc. & Center for Modeling, Simulation,
   & Imaging in Medicine, Rensselaer Polytechnic Institute.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

Andrew Wilson's avatar
Andrew Wilson committed
12
	  http://www.apache.org/licenses/LICENSE-2.0.txt
13
14
15
16
17
18
19
20
21
22
23
24

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

=========================================================================*/

#pragma once

#include "imstkMath.h"
Andrew Wilson's avatar
Andrew Wilson committed
25
#include "imstkTypes.h"
26

27
#include <algorithm>
Andrew Wilson's avatar
Andrew Wilson committed
28
#include <array>
29
30
31
32
33
34

namespace imstk
{
namespace CollisionUtils
{
///
35
/// \brief Do ranges [\p a,\p b] and [\p c,\p d] intersect?
Andrew Wilson's avatar
Andrew Wilson committed
36
/// inclusive
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
///
inline bool
isIntersect(const double a, const double b, const double c, const double d)
{
    return ((a <= d && a >= c) || (c <= b && c >= a)) ? true : false;
}

///
/// \brief Check if two AABBs are intersecting
///
inline bool
testAABBToAABB(const double min1_x, const double max1_x,
               const double min1_y, const double max1_y,
               const double min1_z, const double max1_z,
               const double min2_x, const double max2_x,
               const double min2_y, const double max2_y,
               const double min2_z, const double max2_z)
{
    return (isIntersect(min1_x, max1_x, min2_x, max2_x)
            && isIntersect(min1_y, max1_y, min2_y, max2_y)
            && isIntersect(min1_z, max1_z, min2_z, max2_z));
}

///
/// \brief Check if triangle and point are intersecting with AABB test
///
inline bool
testPointToTriAABB(const double x1, const double y1, const double z1,
                   const double x2, const double y2, const double z2,
                   const double x3, const double y3, const double z3,
                   const double x4, const double y4, const double z4,
                   const double prox1, const double prox2)
{
    const auto min_x = std::min({ x2, x3, x4 });
    const auto max_x = std::max({ x2, x3, x4 });
    const auto min_y = std::min({ y2, y3, y4 });
    const auto max_y = std::max({ y2, y3, y4 });
    const auto min_z = std::min({ z2, z3, z4 });
    const auto max_z = std::max({ z2, z3, z4 });

    return testAABBToAABB(x1 - prox1, x1 + prox1, y1 - prox1, y1 + prox1,
Andrew Wilson's avatar
Andrew Wilson committed
78
79
                z1 - prox1, z1 + prox1, min_x - prox2, max_x + prox2,
                min_y - prox2, max_y + prox2, min_z - prox2, max_z + prox2);
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
}

///
/// \brief Check if two lines are intersecting with AABB intersection test
/// \param x1/y1/z1 Coordinates of the first end-point of the first line
/// \param x2/y2/z2 Coordinates of the second end-point of the first line
/// \param x3/y3/z3 Coordinates of the first end-point of the second line
/// \param x4/y4/z4 Coordinates of the second end-point of the second line
/// \param prox1 Round-off precision for the test
/// \param prox2 Round-off precision for the test
///
bool testLineToLineAABB(const double x1, const double y1, const double z1,
                        const double x2, const double y2, const double z2,
                        const double x3, const double y3, const double z3,
                        const double x4, const double y4, const double z4,
                        const double prox1 = VERY_SMALL_EPSILON_D, const double prox2 = VERY_SMALL_EPSILON_D);

///
/// \brief Check if two lines are intersecting with AABB intersection test
/// \param p1A The first end-point of the first line
/// \param p1B The second end-point of the first line
/// \param p2A The first end-point of the second line
/// \param p2B The second end-point of the second line
/// \param prox1 Round-off precision for the test
/// \param prox2 Round-off precision for the test
///
inline bool
testLineToLineAABB(const Vec3r& p1A, const Vec3r& p1B,
                   const Vec3r& p2A, const Vec3r& p2B,
                   const double prox1 = VERY_SMALL_EPSILON_D, const double prox2 = VERY_SMALL_EPSILON_D)
{
    const Real* p1Aptr = &p1A[0];
    const Real* p1Bptr = &p1B[0];
    const Real* p2Aptr = &p2A[0];
    const Real* p2Bptr = &p2B[0];
    return testLineToLineAABB(p1Aptr[0], p1Aptr[1], p1Aptr[2],
Andrew Wilson's avatar
Andrew Wilson committed
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
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
                p1Bptr[0], p1Bptr[1], p1Bptr[2],
                p2Aptr[0], p2Aptr[1], p2Aptr[2],
                p2Bptr[0], p2Bptr[1], p2Bptr[2],
                prox1, prox2);
}

///
/// \brief Check if an OBB and point intersect, no contact info
/// \param center of box
/// \param rotation matrix of box
/// \param x, y, z scalar extents
/// \param point to test
/// \return true if intersecting, false if not
///
inline bool
testOBBToPoint(
    const Vec3d& cubePos, const Mat3d& rot, const Vec3d extents,
    const Vec3d& pt)
{
    // We assume rot is an orthonormal rotation matrix (no shear or scale/normalized)
    // We then take the diff from the center of the cube and project onto each axes
    const Vec3d diff = (pt - cubePos);
    const Vec3d proj = rot.transpose() * diff; // dot product on each axes

    return
        (std::abs(proj[0]) < extents[0])
        && (std::abs(proj[1]) < extents[1])
        && (std::abs(proj[2]) < extents[2]);
}

///
/// \brief Check if an oriented cube and point intersect, with contact info (normal and surface contact point)
/// \return true if intersecting, false if not
///
inline bool
testOBBToPoint(
    const Vec3d& cubePos, const Mat3d& rot, const Vec3d extents,
    const Vec3d& pt,
    Vec3d& ptContactNormal, Vec3d& cubeContactPt, double& penetrationDepth)
{
    const Vec3d diff   = (pt - cubePos);
    const Mat3d rotInv = rot.transpose();
    const Vec3d proj   = rotInv * diff; // dot product on each axes

    bool inside[3] =
    {
        (std::abs(proj[0]) < extents[0]),
        (std::abs(proj[1]) < extents[1]),
        (std::abs(proj[2]) < extents[2])
    };
    bool isInsideCube = inside[0] && inside[1] && inside[2];

    if (isInsideCube)
    {
        // If inside, find closest face, use that distance
        penetrationDepth = std::numeric_limits<double>::max();
        for (int i = 0; i < 3; i++)
        {
            double       dist = proj[i];
            const Vec3d& axes = rotInv.col(i);

            if (dist < extents[i] && dist > 0.0)
            {
                const double unsignedDistToSide = (extents[i] - dist);
                if (unsignedDistToSide < penetrationDepth)
                {
                    cubeContactPt    = pt + unsignedDistToSide * axes;
                    penetrationDepth = unsignedDistToSide;
                    ptContactNormal  = axes;
                }
            }
            else if (dist > -extents[i] && dist < 0.0)
            {
                const double unsignedDistToSide = (extents[i] + dist);
                if (unsignedDistToSide < penetrationDepth)
                {
                    cubeContactPt    = pt - unsignedDistToSide * axes;
                    penetrationDepth = unsignedDistToSide;
                    ptContactNormal  = -axes;
                }
            }
        }
    }
    else
    {
        // If outside we need to also consider diagonal distance to corners and edges
        // Compute nearest point
        cubeContactPt   = cubePos;
        ptContactNormal = Vec3d::Zero();
        for (int i = 0; i < 3; i++)
        {
            double       dist = proj[i];
            const Vec3d& axes = rotInv.col(i);

            // If distance farther than the box extents, clamp to the box
            if (dist >= extents[i])
            {
                cubeContactPt   += extents[i] * axes;
                ptContactNormal += axes;
            }
            else if (dist <= -extents[i])
            {
                cubeContactPt   -= extents[i] * axes;
                ptContactNormal -= axes;
            }
        }
        ptContactNormal.normalize();
    }

    return isInsideCube;
}

///
/// \brief Check if plane and sphere intersect, no contact info
/// \return true if intersecting, false if not
///
inline bool
testPlaneToSphere(
    const Vec3d& planePt, const Vec3d& planeNormal,
    const Vec3d& spherePos, const double r)
{
    return (spherePos - planePt).dot(planeNormal) < r;
}

///
/// \brief Check if plane and sphere intersect, with contact info (normal and surface contact point)
/// \return true if intersecting, false if not
///
inline bool
testPlaneToSphere(
    const Vec3d& planePt, const Vec3d& planeNormal,
    const Vec3d& spherePos, const double r,
    Vec3d& planeContactPt, Vec3d& planeContactNormal,
    Vec3d& sphereContactPt, Vec3d& sphereContactNormal, double& penetrationDepth)
{
    const double d = (spherePos - planePt).dot(planeNormal);

    planeContactNormal  = -planeNormal;
    sphereContactNormal = planeNormal;
    planeContactPt      = spherePos - d * planeNormal;
    sphereContactPt     = spherePos - r * planeNormal;

    penetrationDepth = r + std::abs(d);
    return d < r;
}

///
/// \brief Check if bidirectional plane and sphere intersect, with contact info
/// \return true if intersecting, false if not
///
inline bool
testBidirectionalPlaneToSphere(
    const Vec3d& planePt, const Vec3d& planeNormal,
    const Vec3d& spherePos, const double r,
    Vec3d& planeContactPt, Vec3d& planeContactNormal,
    Vec3d& sphereContactPt, Vec3d& sphereContactNormal, double& pentrationDepth)
{
    const double d = (spherePos - planePt).dot(planeNormal);

    planeContactPt = spherePos - d * planeNormal;

    if (d < 0.0)
    {
        planeContactNormal  = planeNormal;
        sphereContactNormal = -planeNormal;
        sphereContactPt     = spherePos + r * planeNormal;
    }
    else
    {
        planeContactNormal  = -planeNormal;
        sphereContactNormal = planeNormal;
        sphereContactPt     = spherePos - r * planeNormal;
    }

    pentrationDepth = r - std::abs(d);
291
    return pentrationDepth > 0.0;
Andrew Wilson's avatar
Andrew Wilson committed
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
}

///
/// \brief Check if sphere and sphere intersect, no contact info
/// \return true if intersecting, false if not
///
inline bool
testSphereToSphere(
    const Vec3d& sphereAPos, const double rA,
    const Vec3d& sphereBPos, const double rB)
{
    const double rSum = rA + rB;
    return (sphereBPos - sphereAPos).squaredNorm() < (rSum * rSum);
}

///
/// \brief Check if sphere and sphere intersect, with contact info (normal and surface contact point)
/// \return true if intersecting, false if not
///
inline bool
testSphereToSphere(
    const Vec3d& sphereAPos, const double rA,
    const Vec3d& sphereBPos, const double rB,
    Vec3d& sphereAContactPt, Vec3d& sphereAContactNormal,
    Vec3d& sphereBContactPt, Vec3d& sphereBContactNormal,
    double& depth)
{
    Vec3d dirAtoB = sphereBPos - sphereAPos;

    const double d = dirAtoB.norm();
    dirAtoB = dirAtoB / d;

    sphereAContactPt     = sphereAPos + dirAtoB * rA;
    sphereAContactNormal = -dirAtoB;
    sphereBContactPt     = sphereBPos - dirAtoB * rB;
    sphereBContactNormal = dirAtoB;
    depth = (rA + rB) - d;

330
    return depth > 0.0;
Andrew Wilson's avatar
Andrew Wilson committed
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
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
}

///
/// \brief Check if sphere and cylinder intersect, with contact info (normal and surface contact point)
/// \return true if intersecting, false if not
///
inline bool
testSphereToCylinder(
    const Vec3d& spherePos, const double rSphere,
    const Vec3d& cylinderPos, const Vec3d& cylinderAxis, const double rCylinder, const double cylinderLength,
    Vec3d& sphereContactPt, Vec3d& sphereContactNormal,
    Vec3d& cylinderContactPt, Vec3d& cylinderContactNormal,
    double& depth)
{
    const double cylHalfLength = cylinderLength * 0.5;

    // Compute distance
    const Vec3d cylToSphere = (spherePos - cylinderPos);
    const Vec3d n = cylinderAxis;

    // Get normal distance (along axes)
    const double distN    = n.dot(cylToSphere);
    const Vec3d  distNVec = distN * n;

    // Get perp distance (orthogonal to axes)
    const Vec3d  distPerpVec = cylToSphere - distNVec;    // Remove N component to get perp
    const double distPerp    = distPerpVec.norm();
    const Vec3d  perp = distPerpVec.normalized();

    // If the center of the sphere is within the length of the cylinder
    if (std::abs(distN) < cylHalfLength)
    {
        //  ______
        // |      |_
        // |     (__)
        // |      |
        //

        sphereContactPt   = spherePos - perp * rSphere;
        cylinderContactPt = cylinderPos + distNVec + perp * rCylinder;

        sphereContactNormal   = perp;
        cylinderContactNormal = -perp;
        depth = (rSphere + rCylinder) - distPerp;

        return depth < 0.0;
    }
    else
    {
        // \todo: Does not return closest points, returns no points when no collision
        // slight math change needed (also add SDF function to cylinder)
        //    __           __
        //  _(__)_    ____(__)
        // |      |  |     |
        // |      |  |     |
        //

        // If any portion of the sphere is within the length of the cylinder
        if (std::abs(distN) < (cylHalfLength + rSphere))
        {
            // If the center of the sphere is within the circle of the caps
            //    __
            //  _(__)_
            // |      |
            // |      |
            //
            if (distPerp < rCylinder)
            {
                sphereContactPt   = spherePos - n * rSphere;
                cylinderContactPt = cylinderPos + n * cylHalfLength + distPerpVec;

                sphereContactNormal   = n;
                cylinderContactNormal = -n;
                depth = (rSphere + cylHalfLength) - std::abs(distN);

                return true;
            }
            // Finally the sphere vs circular cap edge/rim
            //       __
            //  ____(__)
            // |     |
            // |     |
            //
            else if (distPerp < (rCylinder + rSphere))
            {
                cylinderContactPt = cylinderPos + n * cylHalfLength + perp * rCylinder;
                const Vec3d  diagDiff = spherePos - cylinderContactPt;
                const double diagDist = diagDiff.norm();

                sphereContactNormal   = diagDiff / diagDist;
                cylinderContactNormal = -sphereContactNormal;

                sphereContactPt = spherePos + cylinderContactNormal * rSphere;
                depth = rSphere - diagDist;
                return true;
            }
        }
    }
    return false;
}

///
/// \brief Check if point and capsule intersect, no contact info
/// \return true if intersecting, false if not
///
inline bool
testCapsuleToPoint(
    const Vec3d& capsulePos, const Vec3d& capsuleAxis, const double capsuleLength, const double rCapsule,
    const Vec3d& point)
{
    // Two lines points
    const Vec3d a = capsulePos + 0.5 * capsuleAxis * capsuleLength;
    const Vec3d b = 2.0 * capsulePos - a;

    const Vec3d  pa = point - a;
    const Vec3d  ba = b - a;
    const double h  = std::min(std::max(pa.dot(ba) / ba.dot(ba), 0.0), 1.0);
    const double signedDist = ((pa - ba * h).norm() - rCapsule);
    return signedDist < 0.0;
}

///
/// \brief Check if point and capsule intersect, with contact info (normal and surface contact point)
/// \return true if intersecting, false if not
///
inline bool
testCapsuleToPoint(
    const Vec3d& capsulePos, const Vec3d& capsuleAxis, const double capsuleLength, const double rCapsule,
    const Vec3d& point,
    Vec3d& capsuleContactPt, Vec3d& capsuleContactNormal, Vec3d& pointContactNormal, double& depth)
{
    // Get position of end points of the capsule
    // TODO: Fix this issue of extra computation in future
    const Vec3d  mid   = capsulePos;
    const Vec3d  p1    = mid + 0.5 * capsuleAxis * capsuleLength;
    const Vec3d  p0    = 2.0 * mid - p1;
    const Vec3d  pDiff = p1 - p0;
    const double pDiffSqrLength = pDiff.dot(pDiff);
    const double pDotp0 = pDiff.dot(p0);

    // First, check collision with bounding sphere
    if ((mid - point).norm() > (rCapsule + capsuleLength * 0.5))
    {
        return false;
    }

    // Do the actual check
    const double alpha = (point.dot(pDiff) - pDotp0) / pDiffSqrLength;
    Vec3d        closestPoint;
    if (alpha > 1.0)
    {
        closestPoint = p1;
    }
    else if (alpha < 0.0)
    {
        closestPoint = p0;
    }
    else
    {
        closestPoint = p0 + alpha * pDiff;
    }

    // If the point is inside the bounding sphere then the closest point
    // should be inside the capsule
    const Vec3d  diff = (point - closestPoint);
    const double dist = diff.norm();
    if (dist < rCapsule)
    {
        depth = rCapsule - dist;
        pointContactNormal   = diff.normalized();
        capsuleContactNormal = -pointContactNormal;
        capsuleContactPt     = closestPoint + pointContactNormal * rCapsule;
        return true;
    }
    return false;
}

///
/// \brief Check if sphere and point intersect, no contact info
/// \return true if intersecting, false if not
///
inline bool
testSphereToPoint(
    const Vec3d& spherePos, const double rSqr, const Vec3d& point)
{
    return (spherePos - point).squaredNorm() < rSqr;
}

///
/// \brief Check if sphere and point intersect, with contact info
/// \return true if intersecting, false if not
///
inline bool
testSphereToPoint(
    const Vec3d& spherePos, const double r, const Vec3d& point,
    Vec3d& sphereContactPt, Vec3d& sphereContactNormal, double& penetrationDepth)
{
    const Vec3d diff = point - spherePos;
    penetrationDepth    = diff.norm();
    sphereContactNormal = diff / penetrationDepth;
    sphereContactPt     = spherePos + sphereContactNormal * r;
    const double signedDist = penetrationDepth - r;
    penetrationDepth = std::abs(signedDist);
    return signedDist < 0.0;
}

///
/// \brief Check if plane and point intersect, no contact info
/// \return true if intersecting, false if not
///
inline bool
testPlaneToPoint(
    const Vec3d& planePt, const Vec3d& planeNormal,
    const Vec3d& point)
{
    return (point - planePt).dot(planeNormal) < 0.0;
}

///
/// \brief Check if plane and point intersect, with contact info
/// \return true if intersecting, false if not
///
inline bool
testPlaneToPoint(
    const Vec3d& planePt, const Vec3d& planeNormal,
    const Vec3d& point,
    Vec3d& planeContactPt, Vec3d& contactNormal, double& pointPenetrationDepth)
{
    contactNormal = planeNormal;
    const double d = (point - planePt).dot(planeNormal);
    planeContactPt = point - pointPenetrationDepth * contactNormal;
    pointPenetrationDepth = std::abs(d);
    return d < 0.0;
}

///
/// \brief Compute intersection point of plane and infinite line
///
inline bool
testPlaneLine(const Vec3d& p, const Vec3d& q,
              const Vec3d& planePt, const Vec3d& planeNormal, Vec3d& iPt)
{
    const Vec3d  n     = q - p;
    const double denom = n.dot(planeNormal);
    // Plane and line are parallel
    if (std::abs(denom) < IMSTK_DOUBLE_EPS)
    {
        return false;
    }
    // const Vec3d  dir = n.normalized();
    const double t = (planePt - p).dot(planeNormal) / denom;
    iPt = p + t * n;
    return true;
}

static double
scalarTriple(const Vec3d& u, const Vec3d& v, const Vec3d& w)
{
    return u.cross(v).dot(w);
}

static bool
testSegmentTriangle(
    const Vec3d& p, const Vec3d& q,
    const Vec3d& a, const Vec3d& b, const Vec3d& c,
    Vec3d& uvw)
{
    const Vec3d  pq  = q - p;
    const double pqL = pq.norm();
    if (pqL < IMSTK_DOUBLE_EPS)
    {
        return false;
    }
    const Vec3d pa = a - p;
    const Vec3d pb = b - p;
    const Vec3d pc = c - p;
    // Test if pq is inside the edges bc, ca and ab. Done by testing
    // that the signed tetrahedral volumes, computed using scalar triple
    // products, are all positive
    uvw[0] = scalarTriple(pq, pc, pb);
    if (uvw[0] < 0.0)
    {
        return false;
    }
    uvw[1] = scalarTriple(pq, pa, pc);
    if (uvw[1] < 0.0)
    {
        return false;
    }
    uvw[2] = scalarTriple(pq, pb, pa);
    if (uvw[2] < 0.0)
    {
        return false;
    }
    // Compute the barycentric coordinates (u, v, w) determining the
    // intersection point r, r = u*a + v*b + w*c
    double denom = 1.0 / (uvw[0] + uvw[1] + uvw[2]);
    uvw[0] *= denom;
    uvw[1] *= denom;
    uvw[2] *= denom; // w = 1.0f - u - v;

    const Vec3d  iPt  = uvw[0] * a + uvw[1] * b + uvw[2] * c;
    const double dist = (pq / pqL).dot(iPt - p);

    return (dist >= 0.0 && dist <= pqL);
636
637
638
639
640
}

///
/// \brief Test if the segment define by points pA-pB intersects with triangle using Moller–Trumbore algorithm
///
Andrew Wilson's avatar
Andrew Wilson committed
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
static bool
testSegmentTriangle(
    const Vec3d& pA, const Vec3d& pB,
    const Vec3d& v0, const Vec3d& v1, const Vec3d& v2)
{
    static const double EPSILON = 1e-8;
    Vec3d               dirAB   = pB - pA;
    const double        lAB     = dirAB.norm();
    if (lAB < 1e-8)
    {
        return false;
    }
    dirAB /= lAB;

    const Vec3d  edge1 = v1 - v0;
    const Vec3d  edge2 = v2 - v0;
    const Vec3d  h     = dirAB.cross(edge2);
    const double a     = edge1.dot(h);
    if (a > -EPSILON && a < EPSILON)
    {
        return false;    // This ray is parallel to this triangle.
    }
    const double f = 1.0 / a;
    const Vec3d  s = pA - v0;
    const double u = f * s.dot(h);
    if (u < 0.0 || u > 1.0)
    {
        return false;
    }
    const Vec3d  q = s.cross(edge1);
    const double v = f * dirAB.dot(q);
    if (v < 0.0 || u + v > 1.0)
    {
        return false;
    }
    // At this stage we can compute t to find out where the intersection point is on the line.
    const double t = f * edge2.dot(q);

    // ray - triangle intersection
    return (t > EPSILON && t + EPSILON < lAB);
}

///
/// \brief Returns the position closest to triangle a-b-c and the case
/// type=0: a is the closest point
/// type=1: b is the closest point
/// type=2: c is the closest point
/// type=3: closest point on ab
/// type=4: closest point on bc
/// type=5: closest point on ca
/// type=6: closest point on face
///
Vec3d closestPointOnTriangle(const Vec3d& p, const Vec3d& a, const Vec3d& b, const Vec3d& c, int& caseType);

///
/// \brief Check if sphere and triangle intersect, with point direction contact info
/// \return true if intersecting, false if not
///
inline bool
testSphereToTriangle(const Vec3d& spherePt, const double sphereRadius,
                     const Vec3d& a, const Vec3d& b, const Vec3d& c,
                     Vec3d& sphereContactPt, Vec3d& sphereContactNormal, double& penetrationDepth)
{
    int         type = 0;
    const Vec3d closestPtOnTriangle = closestPointOnTriangle(spherePt, a, b, c, type);

    sphereContactNormal = (spherePt - closestPtOnTriangle);
    const double dist = sphereContactNormal.norm();
    penetrationDepth     = sphereRadius - dist;
    sphereContactNormal /= dist;
    sphereContactPt      = spherePt - sphereContactNormal * sphereRadius;
    return dist < sphereRadius;
}

///
/// \brief Check if sphere and triangle intersect, with contact info
/// If edge contact, edgeContact gives the indices of the two vertices in contact,
/// If point contact, pointContact gives the index of the vertex in contact
/// \return contact type, 0-no intersection, 1-edge contact, 2-face contact, 3-point contact
///
inline int
testSphereToTriangle(const Vec3d& spherePt, const double sphereRadius,
                     const Vec3i& tri, const Vec3d& a, const Vec3d& b, const Vec3d& c,
                     Vec3d& triangleContactPt,
                     Vec2i& edgeContact,
                     int& pointContact)
{
    int caseType = 0;
    triangleContactPt = closestPointOnTriangle(spherePt, a, b, c, caseType);
    const Vec3d  diff = spherePt - triangleContactPt;
    const double dist = diff.norm();

    // If intersecting
    if (dist < sphereRadius)
    {
        switch (caseType)
        {
        case 0:
            pointContact = tri[0];
            return 3;
        case 1:
            pointContact = tri[1];
            return 3;
        case 2:
            pointContact = tri[2];
            return 3;
        case 3:
            edgeContact = { tri[0], tri[1] };
            return 1;
        case 4:
            edgeContact = { tri[1], tri[2] };
            return 1;
        case 5:
            edgeContact = { tri[2], tri[0] };
            return 1;
        case 6:
            return 2;
        default:
            return 0;
            break;
        }
        ;
    }
    else
    {
        return 0;
    }
}

///
/// \brief Tests if the segment intersects any of the triangle faces of the tet
/// does not cover line completely inside tet case
/// \todo: Could be faster with SAT directly applied here
///
inline bool
testTetToSegment(
    const std::array<Vec3d, 4>& inputTetVerts,
    const Vec3d& x1, const Vec3d& x2)
{
    static int faces[4][3] = { { 0, 1, 2 }, { 1, 2, 3 }, { 0, 2, 3 }, { 0, 1, 3 } };
    for (int i = 0; i < 4; i++)
    {
        if (testSegmentTriangle(x1, x2, inputTetVerts[faces[i][0]], inputTetVerts[faces[i][1]], inputTetVerts[faces[i][2]]))
        {
            return true;
        }
    }
    return false;
}

///
/// \brief Tests if the segment intersects any of the triangle faces of the tet
/// Returns -1 when intersection face not present
/// Also returns intersection points
///
inline bool
testTetToSegment(
    const std::array<Vec3d, 4>& inputTetVerts,
    const Vec3d& x1, const Vec3d& x2,
    int& intersectionFace0, int& intersectionFace1,
    Vec3d& iPt0, Vec3d& iPt1)
{
    static int faces[4][3] = { { 0, 1, 2 }, { 1, 2, 3 }, { 0, 2, 3 }, { 0, 1, 3 } };
    bool       firstFound  = false;
    for (int i = 0; i < 4; i++)
    {
        const Vec3d& a = inputTetVerts[faces[i][0]];
        const Vec3d& b = inputTetVerts[faces[i][1]];
        const Vec3d& c = inputTetVerts[faces[i][2]];
        Vec3d        uvw;
        if (testSegmentTriangle(x1, x2, a, b, c, uvw))
        {
            if (firstFound)
            {
                intersectionFace1 = i;
                iPt1 = uvw[0] * a + uvw[1] * b + uvw[2] * c;
                return true;
            }
            else
            {
                intersectionFace0 = i;
                iPt0 = uvw[0] * a + uvw[1] * b + uvw[2] * c;

                // There could still be one intersection face, keep searching
                firstFound = true;
            }
        }
    }
    return firstFound;
}
831
832
833
834

///
/// \brief Compute closest distance from a point to a segment x1-x2
///
Andrew Wilson's avatar
Andrew Wilson committed
835
Real pointSegmentClosestDistance(const Vec3d& point, const Vec3d& x1, const Vec3d& x2);
836
837
838
839

///
/// \brief Compute closest distance from a point to a triangle x1-x2-x3
///
Andrew Wilson's avatar
Andrew Wilson committed
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
Real pointTriangleClosestDistance(const Vec3d& point, const Vec3d& x1, const Vec3d& x2, const Vec3d& x3);

///
/// \brief Given two triangles and their ids produce the vertex ids for edge-edge and
/// vertex-triangle contacts. eeContact data is always a-b ordered, vt data is a-b, but tv data is b-a.
/// \todo: There is one edge case where the point of a triangle lies incident on the plane, ee should be
/// produced but fails. This may be too expensive to resolve?
/// \return int denoting which contact type it is -1=none, 0=ee, 1=vt, 2=tv
///
int triangleToTriangle(
    const Vec3i& tri_a, const Vec3i& tri_b,
    const Vec3d& p0_a, const Vec3d& p1_a, const Vec3d& p2_a,
    const Vec3d& p0_b, const Vec3d& p1_b, const Vec3d& p2_b,
    std::pair<Vec2i, Vec2i>& edgeContact,
    std::pair<int, Vec3i>& vertexTriangleContact,
    std::pair<Vec3i, int>& triangleVertexContact);

///
/// \brief Computes the closest point on two edges, reports midpoint
/// when colinear
/// \param first vertex of edge A
/// \param second vertex of edge A
/// \param first vertex of edge B
/// \param second vertex of edge B
/// \param closest point on edge A
/// \param closest point on edge B
/// \return case, 0 - closest point on edge, 1 - closest point on point of edge
///
inline int
edgeToEdgeClosestPoints(
    const Vec3d& a0, const Vec3d& a1,
    const Vec3d& b0, const Vec3d& b1,
    Vec3d& ptA, Vec3d& ptB)
{
    const Vec3d aDiff   = a1 - a0;
    const Vec3d bDiff   = b1 - b0;
    const Vec3d srcDiff = a0 - b0;

    const double a  = bDiff.dot(aDiff);
    const double b  = aDiff.dot(aDiff);
    const double cc = srcDiff.dot(aDiff);
    const double d  = bDiff.dot(bDiff);
    const double e  = a;
    const double f  = srcDiff.dot(bDiff);

    const double det      = a * e - d * b;
    double       s        = 0.5;
    double       t        = 0.5;
    int          caseType = 0;
    if (fabs(det) > 1e-12)
    {
        s = (cc * e - b * f) / det;
        t = (cc * d - a * f) / det;

        if (s < 0 || s > 1.0 || t < 0 || t > 1.0)
        {
            s = std::max(std::min(s, 1.0), 0.0);
            t = std::max(std::min(t, 1.0), 0.0);
            caseType = 1;
        }
    }
    else
    {
        //LOG(WARNING) << "det is null";
    }

    // Two closest points on the line segments
    ptA = a0 + t * aDiff;
    ptB = b0 + s * bDiff;
    return caseType;
}
}
}