r/blenderpython • • Sep 06 '14

Switching to 3D view with Python?

I'm writing a script that will generate some camera animation. I need to have the user select the area for the camera to focus on, and I thought select_border() would do the trick. However, I can't seem to be able to switch to the active 3D view. Any ideas?

import bpy
from math import floor,ceil
from random import uniform, randint
from time import sleep

MIN_SIZE = 1024
MAX_SIZE = 1200
MIN_FOCUS = 0.4
MAX_FOCUS = 0.9

def get_frame_size():
    rnd = bpy.data.scenes[0].render
    return (rnd.resolution_x, rnd.resolution_y)

def get_2D_cursor_position():
    curs = bpy.context.scene.cursor_location
    return (curs.x, curs.y)

def get_px_unit_ratio(cam_obj=bpy.context.scene.camera): # this can constantly change
    fs = get_frame_size()
    dim = max(fs[0], fs[1])
    return cam_obj.data.ortho_scale/dim

def get_random_pos_factors():
    values = ((2, 2),(2, -2), (-2, 2), (-2, -2))
    return values[randint(0,3)]

def do_selection():
    screen = bpy.context.window.screen
    for area in screen.areas:
        if area.type == 'VIEW_3D':
            for region in area.regions:
                if region.type == 'WINDOW':
                    region3d = area.spaces[0].region_3d
                    region3d.view_perspective = "CAMERA"

                    override = bpy.context.copy()
                    override["area"] = area
                    override["screen"] = screen
                    override["region"] = region
                    return bpy.ops.view3d.select_border(override, gesture_mode=3)

target = bpy.context.active_object
total_w = target.dimensions.x
total_h = target.dimensions.y
focal_d = target.location.x+(target.dimensions.z/2)

frame_x, frame_y = get_frame_size()
curs_x, curs_y = get_2D_cursor_position()

bpy.ops.object.camera_add()
cam = bpy.context.active_object
cam.data.type = "ORTHO"
cam.data.ortho_scale = min(total_w, total_h)
bpy.context.scene.camera = cam
cam.data.ortho_scale = cam.data.ortho_scale*uniform(MIN_FOCUS, MAX_FOCUS)
corner = get_random_pos_factors()
cam.location = ((total_w-(frame_x*get_px_unit_ratio(cam)))/corner[0], (total_h-(frame_y*get_px_unit_ratio(cam)))/corner[1], 2)
print(do_selection())
4 Upvotes

8 comments sorted by