I was trying to track down the code that Blender uses to generate the sphere primitive but I can not seem to find it. It must be hard coded in C. I am looking for a python solution.
But I was able to almost approximate that using the Torus code with a major radius of 0.0. Then the minor radius takes over and forms a sphere. But there are extra little vertical and horizontal faces in the mesh using this technique. I would like the cleanest sphere possible.
It does takes a bit of juggling with the indices near the poles. It produces 1 single vertex at each pole. It produces triangular faces near the poles, and quads elsewhere.
Had a quick go at this too, changing the face vert order gives some weird results.
Done with the equation of a sphere
assumed center was 0, 0, 0. Also creates poles with segment x verts in single loc.
import bpy
from math import radians, sin, cos
#create a sphere
verts = []
edges =[]
faces = []
mesh = bpy.data.meshes.new("Sphere")
segments = 16
rings = 32
phi = 0
r = 5.0
for ring in range(rings+1):
phi = ring * radians(180) / rings
for segment in range(segments + 1):
theta = segment * radians(360) / segments
x = r * cos(theta) * sin(phi)
y = r * sin(theta) * sin(phi)
z = r * cos(phi)
verts.append((x, y, z))
if ring:
for segment in range(segments):
s = segments + 1
faces.append([(ring - 1) * s + segment,
(ring - 1) * s + segment + 1,
(ring) * s + segment + 1,
(ring) * s + segment])
mesh.from_pydata(verts, edges, faces)
obj = bpy.data.objects.new("Sphere", mesh)
bpy.context.scene.objects.link(obj)