3

I'm new to Blender Python and writing a start-up script that imports mesh from another application to Blender for rendering.

I have a small problem however - imported mesh objects are too large for default Blender view-port, so I wanted to somehow make the script correct this issue.

I tried something with bpy.ops.view3d.view_all() but I can't get it work. I read the execution-context docs, but I always get this error:

RuntimeError: Operator bpy.ops.view3d.view_all.poll() expected a view3d region

Any suggestions?

iKlsR
  • 43,379
  • 12
  • 156
  • 189
zetah
  • 133
  • 4
  • why not scale the object down instead? – Vader Feb 28 '14 at 22:59
  • 1
    @Vader: meshes are from CAD application so units should be preserved – zetah Feb 28 '14 at 23:01
  • @iKlsR: I tried the snippet just below you suggested topic, which I guess cycles through windows and if editor type is "3D view" then it overrides the active object. But issuing bpy.ops.view3d.view_all() raises same error, and I guess I have to access this command from some other path. – zetah Feb 28 '14 at 23:07
  • 2
    Word of warning - even if you scale the view, clipping start/end may not be set to a very good range (for any existing cameras in the scene and for the viewports). In this situation you could have an option for the importer to clamp the imported model to fit within a bounding box (OBJ importer for eg optionally scaled down by 10 until it fits within a bounding box, see the Clamp Size option) – ideasman42 Mar 01 '14 at 04:03

1 Answers1

8

Operators need a certain context to run from, so you can override this so it can be run from the text editor or wherever depending on the area you need it executed from:

import bpy

for area in bpy.context.screen.areas:
    if area.type == 'VIEW_3D':
        for region in area.regions:
            if region.type == 'WINDOW':
                override = {'area': area, 'region': region, 'edit_object': bpy.context.edit_object}
                bpy.ops.view3d.view_all(override)

Read more in the docs and see this related question for more info.

iKlsR
  • 43,379
  • 12
  • 156
  • 189
  • This was taken from an old script I had lying around, not too sure exactly why the edit_object is/was needed on line 7 so might have to lookup that. – iKlsR Feb 28 '14 at 23:13
  • It works perfectly even w/o edit_object. Thanks for your answer :) – zetah Feb 28 '14 at 23:15
  • You can also use view_selected when needed instead of view_all. – ofekp Apr 12 '22 at 13:59