Question

I am basically building a 3D scatter plot using primitive UV spheres and am running into memory issues when attempting to create more than a couple hundred points at one time. I am limited on my laptop with a 2.1Ghz processor but wanted to know if there is a better way to write this:

import bpy
import random 

while count < 5:
    bpy.ops.mesh.primitive_uv_sphere_add(size=.3,\
    location=(random.randint(-9,9), random.randint(-9,9),\
    random.randint(-9,9)), rotation=(0,0,0))

    count += 1 

I realize that with such a simple script any performance increase is likely negligible but wanted to give it a shot anyway.

Was it helpful?

Solution

Some possible suggestions

  • I would pre-calculate the x,y,z values, store them in a mathutil vector and add it to a dict to be iterated over.
  • Duplication should provide a smaller memory footprint than instantiating new objects. bpy.ops.object.duplicate_move(OBJECT_OT_duplicate=(linked:false, TRANSFORM_OT_translate=(transform)

Edit:

Doing further research it appears each time a bpy.ops.* is called the redraw function . One user documentented exponential increase in time taken to genenerate UV sphere.

CoDEmanX provided the following code snippet to another user.

import bpy

bpy.ops.object.select_all(action='DESELECT')
bpy.ops.mesh.primitive_uv_sphere_add()
sphere = bpy.context.object


for i in range(-1000, 1000, 2):
    ob = sphere.copy()
    ob.location.y = i
    #ob.data = sphere.data.copy() # uncomment this, if you want full copies and no linked duplicates
    bpy.context.scene.objects.link(ob)
bpy.context.scene.update()

Then it is just a case of adapting the code to set the object locations

obj.location = location_dict[i]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top