Python bpy_extras.view3d_utils.region_2d_to_location_3d() Examples

The following are 13 code examples of bpy_extras.view3d_utils.region_2d_to_location_3d(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bpy_extras.view3d_utils , or try the search function .
Example #1
Source File: space_view3d_paint_bprojection.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def move_bp(self, context, cm, fm):
    em = bpy.data.objects['Empty for BProjection']

    deltax = cm.x - round(fm.x)
    deltay = cm.y - round(fm.y)

    sd = context.space_data
    l = sd.region_3d
    vr = l.view_rotation.copy()
    vr.invert()

    v_init = Vector((0.0, 0.0, 1.0))

    pos = [-deltax, -deltay]
    v = view3d_utils.region_2d_to_location_3d(context.region, l, pos, v_init)
    pos = [0, 0]
    vbl = view3d_utils.region_2d_to_location_3d(context.region, l, pos, v_init)
    loc = vbl - v

    loc.rotate(vr)

    em.custom_location -= loc

    self.first_mouse = cm 
Example #2
Source File: image_background_transform.py    From image-background-transform with GNU General Public License v2.0 6 votes vote down vote up
def set_initial_view(self, context, event):
        rv3d = context.region_data
        region = context.region
        self.initial_mouse = Vector((
            event.mouse_region_x,
            event.mouse_region_y))
        self.initial_mouse_location_3d = (
            view3d_utils.region_2d_to_location_3d(
                region, rv3d, self.initial_mouse, Vector()))

        self.initial_mouse_location_2d = (
            space_to_view_vector(
                self.camera_orientation,
                self.initial_mouse_location_3d))

        self.draw_start = self.initial_mouse
        self.draw_end = self.initial_mouse 
Example #3
Source File: 3dmouse_plugin_alpha.py    From android3dblendermouse with Apache License 2.0 6 votes vote down vote up
def pan(ary):
        #get reference to all the areas
        area = bpy.context.window_manager.windows[0].screen.areas[1]
        viewport = area.regions[4]
        rv3d = area.spaces[0].region_3d
        
        #convert view location's 3D Cords to 2D Cords
        locCord = rv3d.view_location
        cord =  view3d_utils.location_3d_to_region_2d(viewport, rv3d, locCord)
        
        cord[0] += float(ary[1])
        cord[1] += float(ary[2])
        
        #convert 2d cords to 3d Cords and apply
        vec = view3d_utils.region_2d_to_vector_3d(viewport, rv3d, cord)
        loc = view3d_utils.region_2d_to_location_3d(viewport, rv3d, cord, vec)
        rv3d.view_location = loc 
Example #4
Source File: bp_draw_objects.py    From ProSidebar with GNU General Public License v3.0 6 votes vote down vote up
def get_point_under_mouse(context,event):
    viewport_region = context.region
    viewport_region_data = context.space_data.region_3d
    viewport_matrix = viewport_region_data.view_matrix.inverted()
    
    # Shooting a ray from the camera, through the mouse cursor towards the grid with a length of 100000
    # If the camera is more than 100000 units away from the grid it won't detect a point
    ray_start = viewport_matrix.to_translation()
    ray_depth = viewport_matrix @ Vector((0,0,-100000))
    
    # Get the 3D vector position of the mouse
    ray_end = view3d_utils.region_2d_to_location_3d(viewport_region,viewport_region_data, (event.mouse_region_x, event.mouse_region_y), ray_depth )
    
    # A triangle on the grid plane. We use these 3 points to define a plane on the grid
    point_1 = Vector((0,0,0))
    point_2 = Vector((0,1,0))
    point_3 = Vector((1,0,0))
    
    # Create a 3D position on the grid under the mouse cursor using the triangle as a grid plane
    # and the ray cast from the camera
    return mathutils.geometry.intersect_ray_tri(point_1,point_2,point_3,ray_end,ray_start,False ) 
Example #5
Source File: animation_motion_trail.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def screen_to_world(context, x, y):
    depth_vector = view3d_utils.region_2d_to_vector_3d(\
        context.region, context.region_data, [x,y])
    vector = view3d_utils.region_2d_to_location_3d(\
        context.region, context.region_data, [x,y], depth_vector)

    return(vector)


# turn 3d world coordinates vector into screen coordinate integers (x,y) 
Example #6
Source File: space_view3d_paint_bprojection.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def invoke(self, context, event):
        em = bpy.data.objects['Empty for BProjection']
        context.window_manager.modal_handler_add(self)
        self.first_mouse = Vector((event.mouse_region_x, event.mouse_region_y))

        sd = context.space_data
        l = sd.region_3d
        v_init = Vector((0.0, 0.0, 1.0))
        context.scene.cursor_location = view3d_utils.region_2d_to_location_3d(
                                                    context.region, l,
                                                    [event.mouse_region_x,
                                                     event.mouse_region_y], v_init
                                                    )

        self.first_location = em.custom_location.copy()

        self.v_offset = Vector((context.region.width, context.region.height)) - Vector((event.mouse_region_x,
                                                                                        event.mouse_region_y))
        move_bp(self, context, Vector((event.mouse_region_x, event.mouse_region_y)) - self.v_offset, self.first_mouse)

        em.custom_c3d = False
        self.alpha = bpy.data.materials['Material for BProjection'].alpha

        em.custom_location.z = -10

        bpy.data.materials['Material for BProjection'].alpha = 0

        bpy.ops.paint.image_paint(stroke=[{"name": "", "location": (0, 0, 0),
                                           "mouse": (event.mouse_region_x, event.mouse_region_y),
                                           "pressure": 1, "pen_flip": False,
                                           "time": 0, "size": 1,
                                           "is_start": False}])
        self.step_prev = Vector((event.mouse_region_x, event.mouse_region_y))
        return {'RUNNING_MODAL'}


# Operator Class toggle the alpha of the plane 
Example #7
Source File: space_view3d_paint_bprojection.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def modal(self, context, event):
        em = bpy.data.objects[BProjection_Empty]
        deltax = event.mouse_region_x - self.first_mouse.x
        deltay = event.mouse_region_y - self.first_mouse.y

        sd = context.space_data
        r3d = sd.region_3d
        vr = r3d.view_rotation.copy()
        vr.invert()

        v_init = Vector((0.0, 0.0, 1.0))

        pos = [deltax, deltay]
        v = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
        pos = [0, 0]
        vbl = view3d_utils.region_2d_to_location_3d(context.region, r3d, pos, v_init)
        loc = vbl - v
        sd.region_3d.view_location += loc
        loc.rotate(vr)
        if not em.custom_style_clone:
            em.custom_location += loc

        self.first_mouse.x = event.mouse_region_x
        self.first_mouse.y = event.mouse_region_y

        if event.type == 'MIDDLEMOUSE'and event.value == 'RELEASE':
            if self.tmp_level > -1:
                for sub in context.object.modifiers:
                    if sub.type in ['SUBSURF', 'MULTIRES']:
                        sub.levels = self.tmp_level
            return {'FINISHED'}

        return {'RUNNING_MODAL'} 
Example #8
Source File: mmvt_utils.py    From mmvt with GNU General Public License v3.0 5 votes vote down vote up
def mouse_coo_to_3d_loc(event, context):
    from bpy_extras.view3d_utils import region_2d_to_vector_3d, region_2d_to_location_3d
    coord = event.mouse_region_x, event.mouse_region_y
    region = context.region
    rv3d = context.space_data.region_3d
    vec = region_2d_to_vector_3d(region, rv3d, coord)
    loc = region_2d_to_location_3d(region, rv3d, coord, vec)
    return loc 
Example #9
Source File: bp_draw_objects.py    From ProSidebar with GNU General Public License v3.0 5 votes vote down vote up
def invoke (self, context, event):
        
        viewport_region = context.region
        viewport_region_data = context.space_data.region_3d
        viewport_matrix = viewport_region_data.view_matrix.inverted()
        
        # Shooting a ray from the camera, through the mouse cursor towards the grid with a length of 100000
        # If the camera is more than 100000 units away from the grid it won't detect a point
        ray_start = viewport_matrix.to_translation()
        ray_depth = viewport_matrix @ Vector((0,0,-100000))
        
        # Get the 3D vector position of the mouse
        ray_end = view3d_utils.region_2d_to_location_3d(viewport_region,viewport_region_data, (event.mouse_region_x, event.mouse_region_y), ray_depth )
        
        # A triangle on the grid plane. We use these 3 points to define a plane on the grid
        point_1 = Vector((0,0,0))
        point_2 = Vector((0,1,0))
        point_3 = Vector((1,0,0))
        
        # Create a 3D position on the grid under the mouse cursor using the triangle as a grid plane
        # and the ray cast from the camera
        position_on_grid = mathutils.geometry.intersect_ray_tri(point_1,point_2,point_3,ray_end,ray_start,False )
        
        # Create an empty for testing
        empty = self.create_test_empty(context)
        # Place the empty on the grid under the mouse cursor
        empty.location = position_on_grid
        
        return {'FINISHED'} 
Example #10
Source File: bgis_utils.py    From BlenderGIS with GNU General Public License v3.0 5 votes vote down vote up
def mouseTo3d(context, x, y):
	'''Convert event.mouse_region to world coordinates'''
	if context.area.type != 'VIEW_3D':
		raise Exception('Wrong context')
	coords = (x, y)
	reg = context.region
	reg3d = context.region_data
	vec = region_2d_to_vector_3d(reg, reg3d, coords)
	loc = region_2d_to_location_3d(reg, reg3d, coords, vec) #WARNING, this function return indeterminate value when view3d clip distance is too large
	return loc 
Example #11
Source File: mesh_pen_tool.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def modal(self, context, event):
        context.area.tag_redraw()

        if event.type =='LEFT_ALT' or event.type == 'RIGHT_ALT':
            if event.value == 'PRESS': pt_buf.alt = True
            if event.value == 'RELEASE': pt_buf.alt = False
            return {'RUNNING_MODAL'}

        elif event.type =='LEFT_SHIFT' or event.type == 'RIGHT_SHIFT':
            if event.value == 'PRESS': pt_buf.shift = True
            if event.value == 'RELEASE': pt_buf.shift = False
            return {'RUNNING_MODAL'}

        elif event.type == 'MOUSEMOVE':
            if pt_buf.list_m_loc_2d != []:
                pt_buf_list_m_loc_3d_last_2d = location_3d_to_region_2d(context.region, context.space_data.region_3d, pt_buf.list_m_loc_3d[-1])

                if pt_buf.alt == True:
                    pt_buf.x = pt_buf_list_m_loc_3d_last_2d[0]
                    pt_buf.y = event.mouse_region_y
                elif pt_buf.shift == True:
                    pt_buf.x = event.mouse_region_x
                    pt_buf.y = pt_buf_list_m_loc_3d_last_2d[1]
                else:
                    pt_buf.x = event.mouse_region_x
                    pt_buf.y = event.mouse_region_y
            else:
                pt_buf.x = event.mouse_region_x
                pt_buf.y = event.mouse_region_y

        elif event.type == 'LEFTMOUSE':
            if event.value == 'PRESS':
                mouse_loc_2d = Vector((pt_buf.x, pt_buf.y))
                pt_buf.list_m_loc_2d.append(mouse_loc_2d)

                mouse_loc_3d = region_2d_to_location_3d(context.region, context.space_data.region_3d, mouse_loc_2d, pt_buf.depth_location)
                pt_buf.list_m_loc_3d.append(mouse_loc_3d)

                pt_buf.depth_location = pt_buf.list_m_loc_3d[-1]      # <----- depth location
            elif event.value == 'RELEASE':
                pass
        elif event.type == 'RIGHTMOUSE':
            context.space_data.draw_handler_remove(self._handle_px, 'WINDOW')
            self.execute(context)
            pt_buf.sws = 'off'
            return {'FINISHED'}
        elif event.type == 'ESC':
            context.space_data.draw_handler_remove(self._handle_px, 'WINDOW')
            pt_buf.list_m_loc_2d[:] = []
            pt_buf.list_m_loc_3d[:] = []
            pt_buf.depth_location = Vector((0.0, 0.0, 0.0))
            pt_buf.sws = 'off'
            return {'CANCELLED'}
        return {"PASS_THROUGH"} 
Example #12
Source File: mesh_carver.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def Picking(context, event):
    # get the context arguments
    scene = context.scene
    region = context.region
    rv3d = context.region_data
    coord = event.mouse_region_x, event.mouse_region_y

    # get the ray from the viewport and mouse
    view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)
    ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coord)

    ray_target = ray_origin + view_vector

    def visible_objects_and_duplis():
        for obj in context.visible_objects:
            if obj.type == 'MESH':
                yield (obj, obj.matrix_world.copy())

            if obj.dupli_type != 'NONE':
                obj.dupli_list_create(scene)
                for dob in obj.dupli_list:
                    obj_dupli = dob.object
                    if obj_dupli.type == 'MESH':
                        yield (obj_dupli, dob.matrix.copy())

            obj.dupli_list_clear()

    def obj_ray_cast(obj, matrix):
        # get the ray relative to the object
        matrix_inv = matrix.inverted()
        ray_origin_obj = matrix_inv * ray_origin
        ray_target_obj = matrix_inv * ray_target
        ray_direction_obj = ray_target_obj - ray_origin_obj
        # cast the ray
        success, location, normal, face_index = obj.ray_cast(ray_origin_obj, ray_direction_obj)
        if success:
            return location, normal, face_index
        else:
            return None, None, None

    # cast rays and find the closest object
    best_length_squared = -1.0
    best_obj = None

    # cast rays and find the closest object
    for obj, matrix in visible_objects_and_duplis():
        if obj.type == 'MESH':
            hit, normal, face_index = obj_ray_cast(obj, matrix)
            if hit is not None:
                hit_world = matrix * hit
                length_squared = (hit_world - ray_origin).length_squared
                if best_obj is None or length_squared < best_length_squared:
                    scene.cursor_location = hit_world
                    best_length_squared = length_squared
                    best_obj = obj
            else:
                if best_obj is None:
                    depthLocation = region_2d_to_vector_3d(region, rv3d, coord)
                    loc = region_2d_to_location_3d(region, rv3d, coord, depthLocation)
                    scene.cursor_location = loc 
Example #13
Source File: mmvt_utils.py    From mmvt with GNU General Public License v3.0 4 votes vote down vote up
def is_point_inside_mesh(p, obj, mult_by_mat_world=False):
    from mathutils import Vector
    p = Vector(p)
    if mult_by_mat_world:
        p = p * get_matrix_world()
    res, point, normal, face = obj.closest_point_on_mesh(p)
    p2 = point-p
    v = p2.dot(normal)
    return not(v < 0.0)


# def mouse_coo_to_3d_loc(event, context):
#     from bpy_extras.view3d_utils import region_2d_to_vector_3d, region_2d_to_location_3d
#     try:
#         # coord = event.mouse_region_x, event.mouse_region_y
#         area, region = get_3d_area_region()
#         coord = (event.mouse_x - area.x, event.mouse_y - area.y)
#         # region = context.region
#         # rv3d = context.space_data.region_3d
#         rv3d = area.spaces.active.region_3d
#         vec = region_2d_to_vector_3d(region, rv3d, coord)
#         pos = region_2d_to_location_3d(region, rv3d, coord, vec)
#     except:
#         pos = None
#         print(traceback.format_exc())
#         print("Couldn't convert mouse coo to 3d loc!")
#     return pos
#

# def mouse_coo_to_3d_loc(event, context):
#     from bpy_extras.view3d_utils import region_2d_to_vector_3d, region_2d_to_location_3d
#
#     mouse_pos = [event.mouse_region_x, event.mouse_region_y]
#
#     # Contextual active object, 2D and 3D regions
#     object = bpy.data.objects['inflated_rh']
#     region = bpy.context.region
#     region3D = bpy.context.space_data.region_3d
#
#     # The direction indicated by the mouse position from the current view
#     view_vector = region_2d_to_vector_3d(region, region3D, mouse_pos)
#     # The 3D location in this direction
#     loc = region_2d_to_location_3d(region, region3D, mouse_pos, view_vector)
#     # The 3D location converted in object local coordinates
#     loc = object.matrix_world.inverted() * loc
#     return loc