EDIT: found the true improvement thanks to @batFINGER
After using the tip from @batFINGER and some other minor modification (I was initially editing gen_co_list...), the method can become a still comprehensible one-liner:
def zoom_to_g5(scene, camera, object):
depsgraph = bpy.context.evaluated_depsgraph_get()
camera.location, foo = camera.camera_fit_coords(depsgraph, [co for corner in object.bound_box for co in corner])
I wanted a faster method, so I'm using list comprehension instead of a generator. There shouldn't be a memory problem since there are only ever 8 corners in the bounding box.
The method is ~25% faster, clocking in at:
>>>print(min(timeit.Timer('cam.location=0.0,0.0,7.0; zoom_to_g5(scn, cam, obj)', setup=setup).repeat(7, 1000)))
0.007111115999578033
OLD
It seems it was a mistake in my comprehension of generators, and the code should have been:
def gen_co_list(object):
for point_co in [point[:] for point in object.bound_box]:
for co in point_co:
yield co
def zoom_to_g(scene, camera, object):
depsgraph = bpy.context.evaluated_depsgraph_get()
loc_new_for_cam, foo = camera.camera_fit_coords(depsgraph, [co for co in gen_co_list(object)])
camera.location = loc_new_for_cam
That said, trying to time the code yields different results than what I expected:
setup = """
import bpy
scn = bpy.context.scene
cam = bpy.data.objects['Camera']
obj = bpy.data.objects['Cube']
def zoom_to(scene, camera, object):
co_list = []
for point_co in [point[:] for point in object.bound_box]:
for co in point_co:
co_list.append(co)
depsgraph = bpy.context.evaluated_depsgraph_get()
loc_new_for_cam, foo = camera.camera_fit_coords(depsgraph, co_list)
camera.location = loc_new_for_cam
def gen_co_list(object):
for point_co in [point[:] for point in object.bound_box]:
for co in point_co:
yield co
def zoom_to_g(scene, camera, object):
depsgraph = bpy.context.evaluated_depsgraph_get()
loc_new_for_cam, foo = camera.camera_fit_coords(depsgraph, [co for co in gen_co_list(object)])
camera.location = loc_new_for_cam
"""
>>>print(min(timeit.Timer('cam.location=0.0,0.0,7.0; zoom_to(scn, cam, obj)', setup=setup).repeat(7, 1000)))
0.009414574999937031
>>>print(min(timeit.Timer('cam.location=0.0,0.0,7.0; zoom_to_g(scn, cam, obj)', setup=setup).repeat(7, 1000)))
0.00963822900030209
run on blender's classic cube.
I will therefore stick with the first zoom_to version, even though I thought the contrary would happen.