Fix a bug in the T34039 hack in case when a modifier key is not mapped.
[blender.git] / release / scripts / templates_py / operator_modal_draw.py
1 import bpy
2 import bgl
3 import blf
4 import gpu
5 from gpu_extras.batch import batch_for_shader
6
7
8 def draw_callback_px(self, context):
9     print("mouse points", len(self.mouse_path))
10
11     font_id = 0  # XXX, need to find out how best to get this.
12
13     # draw some text
14     blf.position(font_id, 15, 30, 0)
15     blf.size(font_id, 20, 72)
16     blf.draw(font_id, "Hello Word " + str(len(self.mouse_path)))
17
18     # 50% alpha, 2 pixel width line
19     shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
20     bgl.glEnable(bgl.GL_BLEND)
21     bgl.glLineWidth(2)
22     batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": self.mouse_path})
23     shader.bind()
24     shader.uniform_float("color", (0.0, 0.0, 0.0, 0.5))
25     batch.draw(shader)
26
27     # restore opengl defaults
28     bgl.glLineWidth(1)
29     bgl.glDisable(bgl.GL_BLEND)
30
31
32 class ModalDrawOperator(bpy.types.Operator):
33     """Draw a line with the mouse"""
34     bl_idname = "view3d.modal_operator"
35     bl_label = "Simple Modal View3D Operator"
36
37     def modal(self, context, event):
38         context.area.tag_redraw()
39
40         if event.type == 'MOUSEMOVE':
41             self.mouse_path.append((event.mouse_region_x, event.mouse_region_y))
42
43         elif event.type == 'LEFTMOUSE':
44             bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
45             return {'FINISHED'}
46
47         elif event.type in {'RIGHTMOUSE', 'ESC'}:
48             bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
49             return {'CANCELLED'}
50
51         return {'RUNNING_MODAL'}
52
53     def invoke(self, context, event):
54         if context.area.type == 'VIEW_3D':
55             # the arguments we pass the the callback
56             args = (self, context)
57             # Add the region OpenGL drawing callback
58             # draw in view space with 'POST_VIEW' and 'PRE_VIEW'
59             self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback_px, args, 'WINDOW', 'POST_PIXEL')
60
61             self.mouse_path = []
62
63             context.window_manager.modal_handler_add(self)
64             return {'RUNNING_MODAL'}
65         else:
66             self.report({'WARNING'}, "View3D not found, cannot run operator")
67             return {'CANCELLED'}
68
69
70 def register():
71     bpy.utils.register_class(ModalDrawOperator)
72
73
74 def unregister():
75     bpy.utils.unregister_class(ModalDrawOperator)
76
77
78 if __name__ == "__main__":
79     register()