1
$\begingroup$

I am new to scripting in Python and so this is probably a very dumb mistake from my side.

I am just trying to arrange some cubes in a basic grid using three for-loops:

import bpy

for i in range(0, 10):
    for j in range(0, 10):
        for k in range(0, 10):
            bpy.ops.mesh.primitive_cube_add(size=0.5, location=(i, j, k))

I have read somewhere that Blender has to update the whole scene after each cube, but why is this a) so slow and b) how do I prevent that?

This code takes approx. 20 seconds with an GTX 1060 / Ryzen 5 1600X and the newest Blender Version 3.1.2.

Thanks in advance! :)

$\endgroup$
4

1 Answer 1

0
$\begingroup$

A: It's so slow because scene update synchronizes to the refresh rate of your monitor. You need to do 1000 scene updates. On a 60hz monitor that would take 1000 / 60 or a bit less than 17 seconds minimum. The additional 3 seconds is probably spent on creating the primitives and updating the relevant data structures plus a bit of bad luck when your operation takes slightly too long and you miss a refresh synchronization.

B: Find a way that uses fewer calls to bpy.ops but rather uses calls to functions that don't require screen updates. One possibility is to use the bmesh module to create the cubes and then only do one screen update when you copy the bemsh to an object's mesh data. As mentioned in the comments on your question, this answer shows an example of using bmesh.

Since you want to create 1000 identical objects but at different locations, I can't provide you with exact code because you need to see which of several approaches is fastest. You can, for example, only create one cube, but duplicate and move it, or you can use numpy to create the data structure and then convert it to a mesh.

One question you've left open is whether or not you want all 1000 cubes to each be separate objects, or you could work with all of the cubes in one object. The later approach is much faster, if it allows you to do what you want with the resulting mesh.

$\endgroup$
3
  • $\begingroup$ "scene update synchronizes to the refresh rate of your monitor" It does? Source? $\endgroup$
    – scurest
    May 27, 2022 at 16:53
  • $\begingroup$ Source: me. I've written drivers for both Windows and Linux, and even when the application doesn't explicitly synchronize the display driver does, at least for full redraws. $\endgroup$ May 27, 2022 at 17:47
  • $\begingroup$ How do you know it does anything involving the display at all? It has the same timings in background mode. $\endgroup$
    – scurest
    May 27, 2022 at 18:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .