Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

June 27, 2011

randomly placing vertices around a spherical surface

import bpy
import time
from math import radians
from random import randint
from mathutils import Vector, Euler

# constants
SPHERE_RADIUS = 0.7
NUM_VERTS = 116
MIN_DISTANCE = 0.19

# ttime in seconds beyond which iteration will be cancelled.
MAX_TIME = 20 

# consumable
Verts = []

# get start time
a_time = time.time()


def make_vertgon(Verts, object_name):
    object_mesh = object_name + "_mesh"
    mesh = bpy.data.meshes.new(object_mesh)
    mesh.from_pydata(Verts, [], [])
    mesh.update()
    new_object = bpy.data.objects.new(object_name, mesh)
    new_object.data = mesh
    
    scene = bpy.context.scene
    scene.objects.link(new_object)
    return


# populate the Verts list with verts randomly positioned around the radius
while(len(Verts)<=NUM_VERTS):
            
    ax_x = radians(randint(0, 360))
    ax_y = radians(randint(0, 360))
    ax_z = radians(randint(0, 360))
    myEul = Euler((ax_x, ax_y, ax_z), 'XYZ')
    
    outVec = Vector((SPHERE_RADIUS, 0.0, 0.0))
    outVec.rotate(myEul)

    # get current time
    b_time = time.time()
    
    # check time difference between current and start.
    elapsed_time = abs(a_time - b_time)    
    if elapsed_time > MAX_TIME:
        # breaking instead of running something that might be shy of infinite.
        break

    myToken = False    
    for B in Verts:       
        if (outVec-B).length < MIN_DISTANCE:
            myToken = True
            break
        
    if myToken == True:
        continue    
   
    Verts.append(outVec)
    
        
# draw verts randomly around the radius
make_vertgon(Verts, "stix")


'''
code notes:
    
this approach makes it obvious that SPHERE_RADIUS, NUM_VERTS and MIN_DISTANCE 
will reach equilibrium if their ratio approaches the optimal spread that 
NUM_VERTS has on the surface of the sphere.

The random nature of establishing vertex coordinates will often make it 
unlikely that any precise geometric distribution can be achieved.
'''