在 python 中,我想尽快从 3D 三角形中光栅化 2D 三角形,并裁剪超出 z 边界的像素。我可以将 3D 坐标转换为 2D,但我似乎无法让光栅化工作。我正在使用一种设置像素方法,它采用 (x,y,color) 并且 (0,0) 位于左上角。
谢谢你的帮助。这是我使用的三角码。
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)