I liked your solution @Antonioya. You can clear the even more script. For example, this script here already is with draw_callback_px function and with a modal.
import bpy
import bgl
import blf
def draw_callback_px(self, context):
font_id = 0 # XXX, need to find out how best to get this.
# draw some text
bgl.glColor4f(1.0, 1.0, 1.0, 0.8)
blf.position(font_id, 15, 30, 0)
blf.size(font_id, 20, 72)
blf.draw(font_id, "Hello Word " )
bgl.glEnable(bgl.GL_BLEND)
bgl.glColor4f(0.0, 0.0, 0.0, 0.5)
bgl.glLineWidth(20)
bgl.glBegin(bgl.GL_LINE_STRIP)
bgl.glColor3f(1.0, 0.0, 0.0)
bgl.glVertex2f(100, 250)
bgl.glVertex2f(400, 300)
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 == 'LEFTMOUSE' and event.value == 'PRESS':
# Image resolution
u = 800
v = 600
#bgl.glDisable(bgl.GL_SCISSOR_TEST)
bgl.glViewport(0, 0, u, v)
bgl.glMatrixMode(bgl.GL_PROJECTION)
#bgl.glPushMatrix()
bgl.glLoadIdentity()
rx = context.region.width
ry = context.region.height
bgl.gluOrtho2D(0, rx, 0, ry)
bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)
draw_callback_px(self, context)
bgl.glFinish()
out = bpy.data.images.new("output", u, v)
buffer = bgl.Buffer(bgl.GL_FLOAT, u * v * 4)
bgl.glReadPixels(0, 0, u, v , bgl.GL_RGBA, bgl.GL_FLOAT, buffer)
out.pixels = buffer[:]
out.gl_free()
#bgl.glEnable(bgl.GL_SCISSOR_TEST)
elif event.type in {'ESC'}:
for a in bpy.data.images:
a.gl_free()
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_PIXEL', 'POST_VIEW' or 'PRE_VIEW'
self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback_px, args, 'WINDOW', 'POST_PIXEL')
self.mouse_path = event.mouse_region_x, event.mouse_region_y
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()
What it does ...
when you press the left mouse button, the script takes the resolution you set for the image, clean (alpha = 0) OpenGL that is in the background, draws once callback function, creates a new image, reads the OpenGL pixels, draws those pixels in the new image and ends.