Skip to content

Instantly share code, notes, and snippets.

@calebrob6
Created November 13, 2013 18:25
Show Gist options
  • Save calebrob6/7453843 to your computer and use it in GitHub Desktop.
Save calebrob6/7453843 to your computer and use it in GitHub Desktop.
Python script that renders a triangle by testing to see if a point is inside the triangle.
import sys,os,math
def distance(p1,p2):
return abs(math.sqrt( (p2[0]-p1[0])**2 + (p2[1]-p1[1])**2 ))
def getAngle(s1,s2,s3):
try:
return math.acos( round((s1**2 + s2**2 - s3**2)/(2*s1*s2),3) ) * (180 / math.pi)
except:
return 2
def isInside(triangle,p):
AB = distance(triangle[0],triangle[1])
BC = distance(triangle[1],triangle[2])
CA = distance(triangle[2],triangle[0])
c = getAngle(AB,BC,CA)
b = getAngle(CA,AB,BC)
a = getAngle(BC,CA,AB)
AP = distance(triangle[0],p)
BP = distance(triangle[1],p)
CP = distance(triangle[2],p)
pa = getAngle(AP,AB,BP)
pb = getAngle(BC,BP,CP)
pc = getAngle(CP,CA,AP)
#print("%f %f %f" % (pa,pb,pc))
if pa > 90 or pa < 0:
return False
if pb > 90 or pb < 0:
return False
if pc > 90 or pc < 0:
return False
return True
def main():
WIDTH = 200
HEIGHT = 200
a = (0,0)
b = (10,10)
c = (15,0)
inside_point = (5,2)
outside_point = (-10,0)
triangle = (a,b,c);
f=open("out.pgm","w")
f.write("P2\n")
f.write("# out.pgm\n")
f.write(str(WIDTH*2)+ " " + str(HEIGHT*2) + "\n")
f.write("15\n")
for h in range(-HEIGHT,HEIGHT):
for w in range(-WIDTH,WIDTH):
color = None
if isInside(triangle,(h,w)):
color = 9
else:
color = 1
f.write(str(color))
if w!=WIDTH-1:
f.write(" ")
f.write("\n")
print("Done")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment