In python I want to rasterize a 2D triangle from a 3D triangle as fast as possible and clip the pixels that are out of the z bounds. I can convert 3D coordinates to 2D, I just can't seem to get the rasterizing working. I'm using a set pixel method that takes (x,y,colour) and (0,0) is at the top left.
Thanks for any help. This is the triangle code i used.
def triangle(self,v = vec2(0,0),v1 = vec2(0,0),v2 = vec2(0,0), colour = 0xFFFFFF):
sort = sortVecByY(v,v1,v2)
a = sort[0]
b = sort[1]
c = sort[2]
if b.y == c.y:
self.flatBottomTri(a,b,c,colour)
elif a.y == b.y:
self.flatTopTri(a,b,c,colour)
else:
d = vec2(int(a.x + (float((b.y-a.y)/(c.y-a.y))) * (c.x - a.x)),b.y)
self.flatBottomTri(a,b,d,colour)
self.flatTopTri(b,d,c,colour)
def flatBottomTri(self,v1,v2,v3,colour):
r1 = (v2.y - v1.y)
s1 = 0
if r1 != 0.0:
s1 = (v2.x - v1.x) / r1
r2 = (v3.y - v1.y)
s2 = 0
if r2 != 0.0:
s2 = (v3.x - v1.x) / (v3.y - v1.y)
x1 = v1.x
x2 = v1.x + 0.5
for sy in range(v1.y,v2.y):
for x in range(int(x1),int(x2)):
self.set(x,sy,colour)
x1 += s1
x2 += s2
def flatTopTri(self,v1,v2,v3,colour):
s1 = (v3.x - v1.x) / (v3.y - v1.y)
s2 = (v3.x - v2.x) / (v3.y - v2.y)
x1 = v3.x
x2 = v3.x + 0.5
for sy in range(v3.y,v1.y,-1):
x1 -= s1
x2 -= s2
for x in range(int(x1),int(x2)):
self.set(x,sy,colour)