Skip to content

Instantly share code, notes, and snippets.

@nerdolo
Created April 20, 2020 19:46
Show Gist options
  • Save nerdolo/5117b2cc7f834b0d4d0db2c324172a6b to your computer and use it in GitHub Desktop.
Save nerdolo/5117b2cc7f834b0d4d0db2c324172a6b to your computer and use it in GitHub Desktop.
function for dividing quadrangle into two triangles that create it regardless of initial points order
import math
def matrix_det(mat): # mat - matrix
det, k_1, k_2 = 0, 1, 1
for i in range(3):
for j in range(3):
k_1 *= mat[(i + j) % 3][j % 3]
k_2 *= mat[-((i + j) % 3)][-(j % 3)]
det += k_1 - k_2
return det
def subtract_vectors(a,b):
return tuple([bi - ai for ai, bi in zip(a, b)])
def add_vectors(a,b):
return tuple([bi + ai for ai, bi in zip(a, b)])
def vector_len(vec):
return math.sqrt(sum(i**2 for i in vec))
def dot_product(v1,v2):
return sum(v1_i*v2_i for v1_i,v2_i in zip(v1,v2))
def vectors_angle(v1,v2):
return math.acos(dot_product(v1,v2)/(vector_len(v1)*vector_len(v2)))
def middle_vector(v):
angles, v = [], set(v)
for vector in v:
angles.append([vectors_angle(*v.difference({vector})), vector])
return max(angles)[1]
def coplanarity(v): # v - vectors
return matrix_det(v) == 0
def quad_to_triang(a,*points):
if len(points) != 3:
raise ValueError
v=[]
for point in points:
v.append(subtract_vectors(a,point))
if not coplanarity(v):
raise ValueError
c = add_vectors(middle_vector(v), a)
v.remove(middle_vector(v))
b = add_vectors(v[0], a)
d = add_vectors(v[1], a)
return (a, c, b,
a, c, d)
# test
# = [ x, y, z]
a = [ 1, 5, 0]
b = [ 5, 4, 0]
c = [ 1, 2, 0]
d = [ 4, 1, 0]
print(quad_to_triang(a,b,c,d))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment