Skip to content

Instantly share code, notes, and snippets.

@NatKarmios
Created January 20, 2021 22:06
Show Gist options
  • Save NatKarmios/36d0a3a3c9e1bd75e04830192c5e6c26 to your computer and use it in GitHub Desktop.
Save NatKarmios/36d0a3a3c9e1bd75e04830192c5e6c26 to your computer and use it in GitHub Desktop.
Graphics tutorial solution
from itertools import permutations
P1 = (10, 20, 5)
P2 = (15, 10, 10)
P3 = (25, 20, 10)
def crossProduct(v1, v2):
x = v1[1]*v2[2] - v1[2]*v2[1]
y = v1[2]*v2[0] - v1[0]*v2[2]
z = v1[0]*v2[1] - v1[1]*v2[0]
return x, y, z
def normalise(v):
min_val = min(map(abs, v))
return tuple(map(lambda x: x/min_val, v))
def getNormal(p1, p2, p3):
v1 = tuple(map(lambda i: p2[i]-p1[i], range(3)))
v2 = tuple(map(lambda i: p3[i]-p1[i], range(3)))
n_ = crossProduct(v1, v2)
n = normalise(n_)
return n
def dotProduct(v1, v2):
return sum(map(lambda x: x[0]*x[1], zip(v1, v2)))
def getCartesianCoeffs(ps):
p1, p2, p3 = ps
n = getNormal(p1, p2, p3)
a, b, c = n
d = -dotProduct(n, p1)
coeffs = a, b, c, d
if (a < 0):
return tuple(map(lambda x: -x, coeffs))
return coeffs
# Check all permutations of P1, P2 and P3 give the same result
tests = list(map(getCartesianCoeffs, permutations((P1, P2, P3))))
assert all(test == tests[0] for test in tests)
print(tests[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment