iain
iain

Reputation: 33

Find if 2 triangles are perpendicular in 3D space

I have 2 triangles in 3D space made of 3 points.

I assume I need to use the dot product but how do I arrange the matrix?

I think I have the pieces but need help to arrange it :)

Thank you.

Current code included below, not convinced it is correct.

vx1 = self.vertices[f[1]].x-self.vertices[f[0]].x
vy1 = self.vertices[f[1]].y-self.vertices[f[0]].y
vz1 = self.vertices[f[1]].z-self.vertices[f[0]].z

vx2 = self.vertices[f[2]].x-self.vertices[f[0]].x
vy2 = self.vertices[f[2]].y-self.vertices[f[0]].y
vz2 = self.vertices[f[2]].z-self.vertices[f[0]].z

plane1 = np.cross([vx1,vy1,vz1],[vx2, vy2, vz2])

vx3 = self.vertices[ff[1]].x-self.vertices[ff[0]].x
vy3 = self.vertices[ff[1]].y-self.vertices[ff[0]].y
vz3 = self.vertices[ff[1]].z-self.vertices[ff[0]].z

vx4 = self.vertices[ff[2]].x-self.vertices[ff[0]].x
vy4 = self.vertices[ff[2]].y-self.vertices[ff[0]].y
vz4 = self.vertices[ff[2]].z-self.vertices[ff[0]].z

plane2 = np.cross([vx3,vy3,vz3],[vx4, vy4, vz4])

print("p1",plane1)
print("p2",plane2)
print("dot",np.dot(plane1,plane2))

if np.dot(plane1,plane2) == 0:
    print("perpendictular")

Upvotes: 1

Views: 193

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53079

@Rory Daulton's answer is intuitive and perfectly fine. I'd just add that you can use Binet-Cauchy formula for a ten-fold speedup:

import numpy as np

TR1, TR2 = np.random.random((2,3,3))

def xprod():
    return np.cross(*(TR1[:2]-TR1[2]))@np.cross(*(TR2[:2]-TR2[2]))

def bincau():
    aux = ((TR1[:2]-TR1[2])@(TR2[:2]-TR2[2]).T).ravel()
    return aux[0]*aux[3] - aux[1]*aux[2]

xprod()
# -0.04300263623056995
bincau()
# -0.043002636230569956

from timeit import timeit

timeit(xprod, number=100000)
# 7.751510428992333
timeit(bincau, number=100000)
# 0.620043026006897

Upvotes: 0

Rory Daulton
Rory Daulton

Reputation: 22564

I'll assume here that the triangles do not need to actually intersect to be considered "perpendicular".

In that case, the triangles are perpendicular if and only if their normal vectors are perpendicular. To find the normal vector of Triangle 1, take the cross-product of the vectors making the sides. I.e. if Triangle 1 is defined by the points t1p1, t1p2, and t1p3, calculate the cross product of t1p2-t1p1 and t1p3-t1p1. (Use numpy.cross to do that.) Do the same for Triangle 2.

Now use the dot product to see of those normal vectors are perpendicular to each other. (Use numpy.dot to do that.) Those vectors are perpendicular if their dot product is zero.

If your points have floating-point coordinates, you should check "close to zero" rather than "equal to zero" to handle slight calculation errors. I'll leave the actual Python/numpy code to you. If you need more help, show some more effort on your part.

Upvotes: 1

Related Questions