update for changes to blf module
[blender.git] / release / scripts / templates / operator_modal_draw.py
1 import bgl
2 import blf
3
4 def draw_callback_px(self, context):
5     print("mouse points", len(self.mouse_path))
6
7     font_id = 0 # XXX, need to find out how best to get this.
8
9     # draw some text
10     blf.position(font_id, 15, 30, 0)
11     blf.size(font_id, 20, 72)
12     blf.draw(font_id, "Hello Word " + str(len(self.mouse_path)))
13
14     # 50% alpha, 2 pixel width line
15     bgl.glEnable(bgl.GL_BLEND)
16     bgl.glColor4f(0.0, 0.0, 0.0, 0.5)
17     bgl.glLineWidth(2)
18
19     bgl.glBegin(bgl.GL_LINE_STRIP)
20     for x, y in self.mouse_path:
21         bgl.glVertex2i(x, y)
22
23     bgl.glEnd()
24
25     # restore opengl defaults
26     bgl.glLineWidth(1)
27     bgl.glDisable(bgl.GL_BLEND)
28     bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
29
30
31 class ModalDrawOperator(bpy.types.Operator):
32     '''Draw a line with the mouse'''
33     bl_idname = "view3d.modal_operator"
34     bl_label = "Simple Modal View3D Operator"
35
36     def modal(self, context, event):
37         context.area.tag_redraw()
38
39         if event.type == 'MOUSEMOVE':
40             self.mouse_path.append((event.mouse_region_x, event.mouse_region_y))
41
42         elif event.type == 'LEFTMOUSE':
43             context.region.callback_remove(self._handle)
44             return {'FINISHED'}
45
46         elif event.type in ('RIGHTMOUSE', 'ESC'):
47             context.region.callback_remove(self._handle)
48             return {'CANCELLED'}
49
50         return {'RUNNING_MODAL'}
51
52     def invoke(self, context, event):
53         if context.area.type == 'VIEW_3D':
54             context.manager.add_modal_handler(self)
55
56             # Add the region OpenGL drawing callback
57             # draw in view space with 'POST_VIEW' and 'PRE_VIEW'
58             self._handle = context.region.callback_add(draw_callback_px, (self, context), 'POST_PIXEL')
59
60             self.mouse_path = []
61
62             return {'RUNNING_MODAL'}
63         else:
64             self.report({'WARNING'}, "View3D not found, cannot run operator")
65             return {'CANCELLED'}
66
67
68 def register():
69     bpy.types.register(ModalDrawOperator)
70
71
72 def unregister():
73     bpy.types.unregister(ModalDrawOperator)
74
75
76 if __name__ == "__main__":
77     register()