在OpenGL中近似球体
我正在尝试按照这个链接的说明来近似一个球体:http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/sphere_cylinder/,但是效果看起来一点也不对。这是我的代码:
def draw_sphere(facets, radius=100):
"""approximate a sphere using a certain number of facets"""
dtheta = 180.0 / facets
dphi = 360.0 / facets
global sphere_list
sphere_list = glGenLists(2)
glNewList(sphere_list, GL_COMPILE)
glBegin(GL_QUADS)
for theta in range(-90, 90, int(dtheta)):
for phi in range(0, 360, int(dphi)):
print theta, phi
a1 = theta, phi
a2 = theta + dtheta, phi
a3 = theta + dtheta, phi + dphi
a4 = theta, phi + dphi
angles = [a1, a2, a3, a4]
print 'angles: %s' % (angles)
glColor4f(theta/360.,phi/360.,1,0.5)
for angle in angles:
x, y, z = angle_to_coords(angle[0], angle[1], radius)
print 'coords: %s,%s,%s' % (x, y, z)
glVertex3f(x, y, z)
glEnd()
glEndList()
def angle_to_coords(theta, phi, radius):
"""return coordinates of point on sphere given angles and radius"""
x = cos(theta) * cos(phi)
y = cos(theta) * sin(phi)
z = sin(theta)
return x * radius, y * radius, z * radius
看起来有些四边形(quads)并不简单,也就是说它们的边是交叉的,但我改变顶点的顺序似乎没有什么效果。
1 个回答
4
我这边没有可以同时运行Python和OpenGL的系统,但我还是能看到一些问题:
你在range
语句中对dphi
和dtheta
进行了四舍五入。这意味着每个面片的起始角度总是整度数,但当你加上没有四舍五入的增量值时,最后的边缘就不一定是整度数了。这很可能就是你出现重叠的原因。
更好的做法是让你的范围值从0 .. facets-1
开始,然后把这些索引乘以360 / facets
(或者纬线用180
)。这样可以避免四舍五入带来的错误,比如:
dtheta = 180.0 / facets
dphi = 360.0 / facets
for y in range(facets):
theta = y * dtheta - 90
for x in range(facets):
phi = x * dphi
...
另外,你在其他地方有没有转换成弧度?Python的默认三角函数是用弧度而不是度数的。