2
$\begingroup$

I try to import an obj file and make a rendered image, by a python script. How to center the view to the mesh?

I've tried bpy.ops.view3d.view_selected() but i get this error:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "<string>", line 43, in <module>
  File "J:\Programmi\blender-2.75a-windows32\2.75\scripts\modules\bpy\ops.py", l
ine 189, in __call__
    ret = op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.action.view_selected.poll() failed, context is in
correct
$\endgroup$
7
$\begingroup$

If you don't have a reference to a specific window, you can iterate over all screen areas, and call the operator on all VIEW_3D area types.

for area in bpy.context.screen.areas:
    if area.type == 'VIEW_3D':
        ctx = bpy.context.copy()
        ctx['area'] = area
        ctx['region'] = area.regions[-1]
        bpy.ops.view3d.view_selected(ctx)            # points view
        # bpy.ops.view3d.camera_to_view_selected(ctx)   # points camera

I think the topic and resolutions to context is incorrect have been covered exhaustively .

If you use camera_to_view_selected(ctx) you can break the loop early if you only have one camera to point, else it will point the camera at the same thing for every 3dview opened.

$\endgroup$
  • $\begingroup$ Thanks @zeffii, no exception now, but the command seems not to work. Here a rendered output example: 156.54.99.175/3d/preview.jpg I want to call Numpad Period from script. $\endgroup$ – sborfedor Aug 25 '15 at 8:06
  • $\begingroup$ I see.. what you're doing there is using a Camera to render. This (although seemingly related) has nothing to do with view32.view_selected() -- which only controls the viewing angle of the viewport, in much the same way as you would use your mouse to position the view so you could see stuff better. ---- That being said you can allign the active camera to the view using another command.bpy.ops.view3d.camera_to_view_selected() $\endgroup$ – zeffii Aug 25 '15 at 8:14
  • $\begingroup$ i'll update my answer so this isn't lost $\endgroup$ – zeffii Aug 25 '15 at 8:14
  • $\begingroup$ Thanks again @zeffii ! Now I get: 156.54.99.175/3d/preview2.jpg how about light? How to get better light in scene? I have to act on the context? $\endgroup$ – sborfedor Aug 25 '15 at 8:36
  • $\begingroup$ you should ask a separate question about lights.. and scripting of light positions. $\endgroup$ – zeffii Aug 25 '15 at 8:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.