Sub topic 15
Setting and reading the view from Python
This chapter shows how to read and change a 3D viewport from a script. You can then reproduce a view exactly instead of orbiting by hand each time.
It assumes you know basic Python, can run a script from the Text Editor or the Python Console, and have read the earlier chapters on orbit, pan, zoom, standard views, projection, framing, and clipping. Examples need Blender 3.2 or later because they use temp_override.
Two ways to control a view
A viewport has two Python interfaces. Each suits a different job.
- Operators such as
bpy.ops.view3d.view_axis()do what the keyboard shortcut does. They are good for named actions: snap to top view, frame the selection, enter local view. They need the right context, meaning a 3D viewport area and its window region. - Properties on the viewport data let you read and write exact numbers. They are good for repeatable setups: a given angle, distance, or lens.
The data lives in two places. The SpaceView3D object (area.spaces.active) holds settings that belong to the editor, such as clip_start, clip_end, lens, and shading. The RegionView3D object (space.region_3d) holds the current view itself: projection, rotation, pivot, and distance.
Finding the viewport
A script does not run "in" a viewport. If you run it from the Text Editor, bpy.context.area is the Text Editor, so you must search for a viewport yourself.
import bpy
area = next(a for a in bpy.context.screen.areas if a.type == 'VIEW_3D')
space = area.spaces.active
r3d = space.region_3d
print(r3d.view_perspective) # 'PERSP', 'ORTHO', or 'CAMERA'
print(r3d.view_distance) # distance from the view to its orbit pivot
print(r3d.view_location) # the orbit pivot point
print(r3d.view_rotation) # quaternion
print(space.clip_start, space.clip_end, space.lens)next(...) raises StopIteration if the current workspace has no 3D viewport. If you have several windows, loop over bpy.context.window_manager.windows and read window.screen.areas.
bpy.context.screen is None when Blender runs in background mode (blender -b). There are no viewports to control there, so view scripts only make sense in an interactive session.
Reading the view in detail
RegionView3D exposes these properties.
| Property | Meaning | Writable |
|---|---|---|
| `view_perspective` | `'PERSP'`, `'ORTHO'`, or `'CAMERA'` | Yes |
| `is_perspective` | `True` for perspective and for camera views using a perspective camera | No |
| `view_location` | The orbit pivot, as a `Vector` in world space | Yes |
| `view_rotation` | Orientation as a `Quaternion` | Yes |
| `view_distance` | Distance from the eye to the pivot | Yes |
| `view_matrix` | World-to-view matrix | No |
| `perspective_matrix` | Projection multiplied by view matrix | No |
| `view_camera_zoom`, `view_camera_offset` | Zoom and shift of the camera-view frame | Yes |
The eye position is not stored directly. It follows from the others:
import bpy
area = next(a for a in bpy.context.screen.areas if a.type == 'VIEW_3D')
r3d = area.spaces.active.region_3d
eye = r3d.view_location + r3d.view_rotation @ __import__("mathutils").Vector((0, 0, r3d.view_distance))
print("Eye position:", eye)The view looks down its local negative Z axis, so the eye sits view_distance units back along local +Z from the pivot. That is why orbiting moves the eye but leaves view_location fixed, and why panning moves view_location itself.
Setting an exact view
To define a view, set the pivot, the rotation, and the distance. Build rotations from Euler angles with mathutils, and call tag_redraw() so the change shows immediately.
import math
import bpy
from mathutils import Euler, Vector
area = next(a for a in bpy.context.screen.areas if a.type == 'VIEW_3D')
space = area.spaces.active
r3d = space.region_3d
r3d.view_perspective = 'PERSP'
r3d.view_location = Vector((0.0, 0.0, 1.0))
r3d.view_rotation = Euler((math.radians(65), 0.0, math.radians(45))).to_quaternion()
r3d.view_distance = 12.0
space.lens = 50.0
area.tag_redraw()The Euler angles here follow the same convention as a default camera: 65 degrees about X tilts the view down toward the ground, and 45 degrees about Z turns it to a corner.
In orthographic mode view_distance still controls how large things appear, but it no longer creates foreshortening. Changing view_perspective to 'ORTHO' keeps the current rotation and pivot.
Using operators with a context override
Operators check their context in a poll step. Called from the Text Editor, bpy.ops.view3d.view_axis() fails with RuntimeError: Operator bpy.ops.view3d.view_axis.poll() failed, context is incorrect. bpy.context.temp_override() fixes this by supplying a viewport temporarily.
import bpy
area = next(a for a in bpy.context.screen.areas if a.type == 'VIEW_3D')
region = next(r for r in area.regions if r.type == 'WINDOW')
with bpy.context.temp_override(area=area, region=region):
bpy.ops.view3d.view_axis(type='TOP') # like Numpad 7
bpy.ops.view3d.view_all() # like Home
bpy.ops.view3d.view_selected() # like Numpad PeriodThe WINDOW region is the main drawing region. Other regions of the area, such as the header and toolbar, are not valid for view operators.
Common view operators:
| Operator | Shortcut equivalent | Notes |
|---|---|---|
| `view3d.view_axis(type=...)` | Numpad 1, 3, 7 | `type` is `'FRONT'`, `'BACK'`, `'LEFT'`, `'RIGHT'`, `'TOP'`, or `'BOTTOM'` |
| `view3d.view_all()` | Home | Frames every object in the scene |
| `view3d.view_selected()` | Numpad Period | Frames the selection |
| `view3d.view_persportho()` | Numpad 5 | Toggles perspective and orthographic |
| `view3d.view_camera()` | Numpad 0 | Enters or leaves camera view |
| `view3d.localview()` | Numpad Slash | Toggles local view |
| `view3d.camera_to_view()` | Ctrl+Alt+Numpad 0 | Moves the scene camera to match the viewport |
view_selected() with nothing selected does nothing useful, so select something first or call view_all().
Matching the camera to the viewport
You can also do the camera-to-view step with data, which avoids a context override. The view matrix maps world space to view space, so its inverse is exactly the transform a camera needs.
import bpy
area = next(a for a in bpy.context.screen.areas if a.type == 'VIEW_3D')
r3d = area.spaces.active.region_3d
cam = bpy.context.scene.camera
if cam is None:
print("The scene has no active camera.")
elif r3d.view_perspective == 'CAMERA':
print("Leave camera view first, or the view matrix is the camera's own.")
else:
cam.matrix_world = r3d.view_matrix.inverted()This copies position and rotation only. It does not copy the viewport's lens, so set cam.data.lens = space.lens if you want the same field of view.
Quad View
With Quad View on, the area has four views. space.region_3d refers to the active region only. The other views are in space.region_quadviews, a collection of RegionView3D objects, which is empty when Quad View is off. Check its length before indexing.
import bpy
area = next(a for a in bpy.context.screen.areas if a.type == 'VIEW_3D')
space = area.spaces.active
print(len(space.region_quadviews))
for r3d in space.region_quadviews:
print(r3d.view_perspective, r3d.view_distance)Common errors
- Poll failed, context is incorrect. An operator ran without a viewport context. Wrap the call in
temp_override. AttributeError: 'NoneType' object has no attribute 'areas'.bpy.context.screenisNone, usually because Blender is running in background mode.- The property changed but the screen did not. Call
area.tag_redraw(). - Setting
view_rotationhas no visible effect in camera view. In camera view the camera controls the image. Changeview_perspectiveaway from'CAMERA'first. - Objects disappear after a distance change. The view may now sit outside
clip_startandclip_end. Adjust them as described in the clipping chapter.
Exercise
Write a script that saves the current view, switches to top orthographic view, and then restores the original view. Which properties do you need to save, and why must you copy them?
Show answer
Save view_perspective, view_location, view_rotation, and view_distance. Copy the location and rotation with .copy(), since they are live values that would otherwise change when the view changes. Example:
import bpy
area = next(a for a in bpy.context.screen.areas if a.type == 'VIEW3D')
region = next(r for r in area.regions if r.type == 'WINDOW')
r3d = area.spaces.active.region3d
saved = (r3d.viewperspective, r3d.viewlocation.copy(),
r3d.viewrotation.copy(), r3d.viewdistance)
with bpy.context.tempoverride(area=area, region=region):
bpy.ops.view3d.viewaxis(type='TOP')
r3d.viewperspective = 'ORTHO'
r3d.viewperspective, r3d.viewlocation, r3d.viewrotation, r3d.viewdistance = saved
area.tagredraw()
Exercise
A script calls bpy.ops.view3d.view_all() from the Text Editor and fails with a poll error. What is the cause, and what is the fix?
Show answer
The operator needs a 3D viewport area and its WINDOW region in the context, but the script's context is the Text Editor. Find the VIEW3D area, pick its region of type 'WINDOW', and call the operator inside `with bpy.context.tempoverride(area=area, region=region):`.