If you use 'PRE_VIEW'
or 'POST_VIEW'
as draw handler type, you will be in world space and can draw straight ahead. If you want to draw on top of everything ("X-Ray"), then calculate the 2d region coordinates and use 'POST_PIXEL'
- there is a utility function for the conversion:
from bpy_extras.view3d_utils import location_3d_to_region_2d
Here is a quick example that draws a line between 3D cursor and active object origin, using 'POST_VIEW'
, which will consider depth of other objects ('PRE_VIEW'
would draw under everything else):
import bpy
import bgl
import blf
def draw_callback_px(self, context):
ob = context.object
if ob is None:
return
font_id = 0 # XXX, need to find out how best to get this.
# draw some text
blf.position(font_id, 15, 30, 0)
blf.size(font_id, 20, 72)
blf.draw(font_id, ob.name)
# 50% alpha, 2 pixel width line
bgl.glEnable(bgl.GL_BLEND)
bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
bgl.glLineWidth(2)
bgl.glBegin(bgl.GL_LINE_STRIP)
bgl.glVertex3f(*ob.matrix_world.translation)
bgl.glVertex3f(*context.scene.cursor_location)
bgl.glEnd()
# restore opengl defaults
bgl.glLineWidth(1)
bgl.glDisable(bgl.GL_BLEND)
bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
class ModalDrawOperator(bpy.types.Operator):
"""Draw a line with the mouse"""
bl_idname = "view3d.modal_operator"
bl_label = "Simple Modal View3D Operator"
def modal(self, context, event):
context.area.tag_redraw()
if event.type in {'RIGHTMOUSE', 'ESC'}:
bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
return {'CANCELLED'}
return {'PASS_THROUGH'}
def invoke(self, context, event):
if context.area.type == 'VIEW_3D':
# the arguments we pass the the callback
args = (self, context)
# Add the region OpenGL drawing callback
# draw in view space with 'POST_VIEW' and 'PRE_VIEW'
self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback_px, args, 'WINDOW', 'POST_VIEW')
self.mouse_path = []
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
else:
self.report({'WARNING'}, "View3D not found, cannot run operator")
return {'CANCELLED'}
def register():
bpy.utils.register_class(ModalDrawOperator)
def unregister():
bpy.utils.unregister_class(ModalDrawOperator)
if __name__ == "__main__":
register()
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
bpy.ops.view3d.modal_operator({'area': area}, 'INVOKE_DEFAULT')
break