Esempio n. 1
0
def screenshot(x, y, w, h, mode=bgl.GL_FRONT, type=bgl.GL_BYTE):
    """スクリーンショットを撮ってRGBAのfloatバッファを返す
    :param x: Window.x
    :type x: int
    :param y: Window.y
    :type y: int
    :param w: Window.width
    :type w: int
    :param h: Window.height
    :type h: int
    :param mode: 読み込み先
    :type mode: int
    :param type: バッファの型。bgl.GL_BYTE, bgl.GL_INT, ...
    :type type: int
    :return: スクリーンショット。float RGBA
    :rtype: bgl.Buffer
    """
    buf = bgl.Buffer(type, w * h * 4)
    mode_bak = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_READ_BUFFER, mode_bak)
    bgl.glReadBuffer(mode)
    bgl.glReadPixels(x, y, w, h, bgl.GL_RGBA, type, buf)
    bgl.glFinish()
    bgl.glReadBuffer(mode_bak[0])
    return buf
Esempio n. 2
0
def screenshot(x, y, w, h, mode=bgl.GL_FRONT, type=bgl.GL_BYTE):
    """スクリーンショットを撮ってRGBAのfloatバッファを返す
    :param x: Window.x
    :type x: int
    :param y: Window.y
    :type y: int
    :param w: Window.width
    :type w: int
    :param h: Window.height
    :type h: int
    :param mode: 読み込み先
    :type mode: int
    :param type: バッファの型。bgl.GL_BYTE, bgl.GL_INT, ...
    :type type: int
    :return: スクリーンショット。float RGBA
    :rtype: bgl.Buffer
    """
    buf = bgl.Buffer(type, w * h * 4)
    mode_bak = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_READ_BUFFER, mode_bak)
    bgl.glReadBuffer(mode)
    bgl.glReadPixels(x, y, w, h, bgl.GL_RGBA, type, buf)
    bgl.glFinish()
    bgl.glReadBuffer(mode_bak[0])
    return buf
Esempio n. 3
0
def gen_screenshot_texture(x, y, w, h, mode=None):
    scissor_is_enabled = bgl.Buffer(bgl.GL_BYTE, 1)
    bgl.glGetIntegerv(bgl.GL_SCISSOR_TEST, scissor_is_enabled)
    scissor_box = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, scissor_box)
    bgl.glEnable(bgl.GL_SCISSOR_TEST)
    bgl.glScissor(x, y, w, h)

    mode_bak = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_READ_BUFFER, mode_bak)
    if mode is not None:
        bgl.glReadBuffer(mode)

    pixels = bgl.Buffer(bgl.GL_BYTE, 4 * w * h)
    # RGBAにしないと斜めになる
    # GL_UNSIGNED_BYTEでないと色が僅かにずれる
    bgl.glReadPixels(x, y, w, h, bgl.GL_RGBA, bgl.GL_UNSIGNED_BYTE, pixels)
    bgl.glFinish()

    if mode is not None:
        bgl.glReadBuffer(mode_bak[0])

    # 反転。確認用
    # for i in range(4 * w * h):
    #     if (i % 4) != 3:
    #         pixels[i] = 255 - pixels[i]

    tex = gen_texture()
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)
    bgl.glTexImage2D(bgl.GL_TEXTURE_2D, 0, bgl.GL_RGBA, w, h, 0, bgl.GL_RGBA,
                     bgl.GL_UNSIGNED_BYTE, pixels)
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

    if not scissor_is_enabled[0]:
        bgl.glDisable(bgl.GL_SCISSOR_TEST)
    bgl.glScissor(*scissor_box)

    return tex
Esempio n. 4
0
def gen_screenshot_texture(x, y, w, h, mode=None):
    scissor_is_enabled = bgl.Buffer(bgl.GL_BYTE, 1)
    bgl.glGetIntegerv(bgl.GL_SCISSOR_TEST, scissor_is_enabled)
    scissor_box = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, scissor_box)
    bgl.glEnable(bgl.GL_SCISSOR_TEST)
    bgl.glScissor(x, y, w, h)

    mode_bak = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_READ_BUFFER, mode_bak)
    if mode is not None:
        bgl.glReadBuffer(mode)

    pixels = bgl.Buffer(bgl.GL_BYTE, 4 * w * h)
    # RGBAにしないと斜めになる
    # GL_UNSIGNED_BYTEでないと色が僅かにずれる
    bgl.glReadPixels(x, y, w, h, bgl.GL_RGBA, bgl.GL_UNSIGNED_BYTE, pixels)
    bgl.glFinish()

    if mode is not None:
        bgl.glReadBuffer(mode_bak[0])

    # 反転。確認用
    # for i in range(4 * w * h):
    #     if (i % 4) != 3:
    #         pixels[i] = 255 - pixels[i]

    tex = gen_texture()
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)
    bgl.glTexImage2D(bgl.GL_TEXTURE_2D, 0, bgl.GL_RGBA, w, h, 0, bgl.GL_RGBA,
                     bgl.GL_UNSIGNED_BYTE, pixels)
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

    if not scissor_is_enabled[0]:
        bgl.glDisable(bgl.GL_SCISSOR_TEST)
    bgl.glScissor(*scissor_box)

    return tex
    def render_main(self, context, objlist, animation=False):
        # noinspection PyBroadException,PyBroadException
        # Save old info
        scene = context.scene
        render = scene.render
        settings = render.image_settings
        depth = settings.color_depth
        settings.color_depth = '8'
        # noinspection PyBroadException
        try:

            # Get visible layers
            layers = []
            for x in range(0, 20):
                if scene.layers[x] is True:
                    layers.extend([x])

            # --------------------
            # Get resolution
            # --------------------
            render_scale = render.resolution_percentage / 100

            width = int(render.resolution_x * render_scale)
            height = int(render.resolution_y * render_scale)
            # ---------------------------------------
            # Get output path
            # ---------------------------------------
            temp_path = path.realpath(bpy.app.tempdir)
            if len(temp_path) > 0:
                outpath = path.join(temp_path, "archipack_tmp_render.png")
            else:
                self.report({
                    'ERROR'
                }, "Archipack: Unable to save temporary render image. Define a valid temp path"
                            )
                settings.color_depth = depth
                return False

            # Get Render Image
            img = self.get_render_image(outpath)
            if img is None:
                self.report({
                    'ERROR'
                }, "Archipack: Unable to save temporary render image. Define a valid temp path"
                            )
                settings.color_depth = depth
                return False

            # -----------------------------
            # Calculate rows and columns
            # -----------------------------
            tile_x = 240
            tile_y = 216
            row_num = ceil(height / tile_y)
            col_num = ceil(width / tile_x)
            print("Archipack: Image divided in " + str(row_num) + "x" +
                  str(col_num) + " tiles")

            # pixels out of visible area
            cut4 = (col_num * tile_x *
                    4) - width * 4  # pixels aout of drawing area
            totpixel4 = width * height * 4  # total pixels RGBA

            viewport_info = bgl.Buffer(bgl.GL_INT, 4)
            bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info)

            # Load image on memory
            img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST)

            # 2.77 API change
            if bpy.app.version >= (2, 77, 0):
                tex = img.bindcode[0]
            else:
                tex = img.bindcode

            # --------------------------------------------
            # Create output image (to apply texture)
            # --------------------------------------------
            if "archipack_output" in bpy.data.images:
                out_img = bpy.data.images["archipack_output"]
                if out_img is not None:
                    out_img.user_clear()
                    bpy.data.images.remove(out_img)

            out = bpy.data.images.new("archipack_output", width, height)
            tmp_pixels = [1] * totpixel4

            # --------------------------------
            # Loop for all tiles
            # --------------------------------
            for row in range(0, row_num):
                for col in range(0, col_num):
                    buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4)
                    bgl.glDisable(
                        bgl.GL_SCISSOR_TEST
                    )  # if remove this line, get blender screenshot not image
                    bgl.glViewport(0, 0, tile_x, tile_y)

                    bgl.glMatrixMode(bgl.GL_PROJECTION)
                    bgl.glLoadIdentity()

                    # defines ortographic view for single tile
                    x1 = tile_x * col
                    y1 = tile_y * row
                    bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y)

                    # Clear
                    bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
                    bgl.glClear(bgl.GL_COLOR_BUFFER_BIT
                                | bgl.GL_DEPTH_BUFFER_BIT)

                    bgl.glEnable(bgl.GL_TEXTURE_2D)
                    bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)

                    # defines drawing area
                    bgl.glBegin(bgl.GL_QUADS)

                    bgl.glColor3f(1.0, 1.0, 1.0)
                    bgl.glTexCoord2f(0.0, 0.0)
                    bgl.glVertex2f(0.0, 0.0)

                    bgl.glTexCoord2f(1.0, 0.0)
                    bgl.glVertex2f(width, 0.0)

                    bgl.glTexCoord2f(1.0, 1.0)
                    bgl.glVertex2f(width, height)

                    bgl.glTexCoord2f(0.0, 1.0)
                    bgl.glVertex2f(0.0, height)

                    bgl.glEnd()

                    # -----------------------------
                    # Loop to draw all lines
                    # -----------------------------
                    for o, d in objlist:
                        if o.hide is False:
                            # verify visible layer
                            for x in range(0, 20):
                                if o.layers[x] is True:
                                    if x in layers:
                                        context.scene.objects.active = o
                                        # print("%s: %s" % (o.name, d.manip_stack))
                                        manipulators = d.manip_stack
                                        if manipulators is not None:
                                            for m in manipulators:
                                                if m is not None:
                                                    m.draw_callback(
                                                        m,
                                                        context,
                                                        render=True)
                                    break

                    # -----------------------------
                    # Loop to draw all debug
                    # -----------------------------
                    """
                    if scene.archipack_debug is True:
                        selobj = bpy.context.selected_objects
                        for myobj in selobj:
                            if scene.archipack_debug_vertices is True:
                                draw_vertices(context, myobj, None, None)
                            if scene.archipack_debug_faces is True or scene.archipack_debug_normals is True:
                                draw_faces(context, myobj, None, None)
                    """
                    """
                    if scene.archipack_rf is True:
                        bgl.glColor3f(1.0, 1.0, 1.0)
                        rfcolor = scene.archipack_rf_color
                        rfborder = scene.archipack_rf_border
                        rfline = scene.archipack_rf_line

                        bgl.glLineWidth(rfline)
                        bgl.glColor4f(rfcolor[0], rfcolor[1], rfcolor[2], rfcolor[3])

                        x1 = rfborder
                        x2 = width - rfborder
                        y1 = int(ceil(rfborder / (width / height)))
                        y2 = height - y1
                        draw_rectangle((x1, y1), (x2, y2))
                    """
                    # --------------------------------
                    # copy pixels to temporary area
                    # --------------------------------
                    bgl.glFinish()
                    bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA,
                                     bgl.GL_FLOAT, buffer)  # read image data
                    for y in range(0, tile_y):
                        # final image pixels position
                        p1 = (y * width * 4) + (row * tile_y * width *
                                                4) + (col * tile_x * 4)
                        p2 = p1 + (tile_x * 4)
                        # buffer pixels position
                        b1 = y * width * 4
                        b2 = b1 + (tile_x * 4)

                        if p1 < totpixel4:  # avoid pixel row out of area
                            if col == col_num - 1:  # avoid pixel columns out of area
                                p2 -= cut4
                                b2 -= cut4

                            tmp_pixels[p1:p2] = buffer[b1:b2]

            # -----------------------
            # Copy temporary to final
            # -----------------------
            out.pixels = tmp_pixels[:]  # Assign image data
            img.gl_free()  # free opengl image memory

            # delete image
            img.user_clear()
            bpy.data.images.remove(img)
            # remove temp file
            remove(outpath)
            # reset
            bgl.glEnable(bgl.GL_SCISSOR_TEST)
            # -----------------------
            # restore opengl defaults
            # -----------------------
            bgl.glLineWidth(1)
            bgl.glDisable(bgl.GL_BLEND)
            bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
            # Saves image
            if out is not None:
                # and (scene.archipack_render is True or animation is True):
                ren_path = bpy.context.scene.render.filepath
                filename = "ap_frame"
                if len(ren_path) > 0:
                    if ren_path.endswith(path.sep):
                        initpath = path.realpath(ren_path) + path.sep
                    else:
                        (initpath, filename) = path.split(ren_path)

                ftxt = "%04d" % scene.frame_current
                outpath = path.realpath(
                    path.join(initpath, filename + ftxt + ".png"))

                self.save_image(outpath, out)

            settings.color_depth = depth
            return True

        except:
            settings.color_depth = depth
            print("Unexpected error:" + str(exc_info()))
            self.report({
                'ERROR'
            }, "Archipack: Unable to create render image. Be sure the output render path is correct"
                        )
            return False
Esempio n. 6
0
def render_opengl(self, context):
    from math import ceil

    layers = []
    scene = context.scene
    for x in range(0, 20):
        if scene.layers[x] is True:
            layers.extend([x])

    objlist = context.scene.objects
    render_scale = scene.render.resolution_percentage / 100

    width = int(scene.render.resolution_x * render_scale)
    height = int(scene.render.resolution_y * render_scale)

    # I cant use file_format becuase the pdf writer needs jpg format
    # the file_format returns 'JPEG' not 'JPG'
    #     file_format = context.scene.render.image_settings.file_format.lower()
    ren_path = bpy.path.abspath(bpy.context.scene.render.filepath) + ".jpg"

    #     if len(ren_path) > 0:
    #         if ren_path.endswith(os.path.sep):
    #             initpath = os.path.realpath(ren_path) + os.path.sep
    #         else:
    #             (initpath, filename) = os.path.split(ren_path)
    #         outpath = os.path.join(initpath, "ogl_tmp.png")
    #     else:
    #         self.report({'ERROR'}, "Invalid render path")
    #         return False

    img = get_render_image(ren_path)

    if img is None:
        self.report({'ERROR'}, "Invalid render path:" + ren_path)
        return False

    tile_x = 240
    tile_y = 216
    row_num = ceil(height / tile_y)
    col_num = ceil(width / tile_x)

    cut4 = (col_num * tile_x * 4) - width * 4
    totpixel4 = width * height * 4

    viewport_info = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info)

    img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST)

    # 2.77 API change
    if bpy.app.version >= (2, 77, 0):
        tex = img.bindcode[0]
    else:
        tex = img.bindcode

    if context.scene.name in bpy.data.images:
        old_img = bpy.data.images[context.scene.name]
        old_img.user_clear()
        bpy.data.images.remove(old_img)

    img_result = bpy.data.images.new(context.scene.name, width, height)

    tmp_pixels = [1] * totpixel4

    #---------- Loop for all tiles
    for row in range(0, row_num):
        for col in range(0, col_num):
            buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4)
            bgl.glDisable(
                bgl.GL_SCISSOR_TEST
            )  # if remove this line, get blender screenshot not image
            bgl.glViewport(0, 0, tile_x, tile_y)

            bgl.glMatrixMode(bgl.GL_PROJECTION)
            bgl.glLoadIdentity()

            # defines ortographic view for single tile
            x1 = tile_x * col
            y1 = tile_y * row
            bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y)

            # Clear
            bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
            bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)

            bgl.glEnable(bgl.GL_TEXTURE_2D)
            bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)

            # defines drawing area
            bgl.glBegin(bgl.GL_QUADS)

            bgl.glColor3f(1.0, 1.0, 1.0)
            bgl.glTexCoord2f(0.0, 0.0)
            bgl.glVertex2f(0.0, 0.0)

            bgl.glTexCoord2f(1.0, 0.0)
            bgl.glVertex2f(width, 0.0)

            bgl.glTexCoord2f(1.0, 1.0)
            bgl.glVertex2f(width, height)

            bgl.glTexCoord2f(0.0, 1.0)
            bgl.glVertex2f(0.0, height)

            bgl.glEnd()

            for obj in objlist:
                if obj.mv.type == 'VISDIM_A':
                    for x in range(0, 20):
                        if obj.layers[x] is True:
                            if x in layers:
                                opengl_dim = obj.mv.opengl_dim
                                if not opengl_dim.hide:
                                    draw_dimensions(context, obj, opengl_dim,
                                                    None, None)
                            break

            #---------- copy pixels to temporary area
            bgl.glFinish()
            bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT,
                             buffer)  # read image data
            for y in range(0, tile_y):
                # final image pixels position
                p1 = (y * width * 4) + (row * tile_y * width *
                                        4) + (col * tile_x * 4)
                p2 = p1 + (tile_x * 4)
                # buffer pixels position
                b1 = y * width * 4
                b2 = b1 + (tile_x * 4)

                if p1 < totpixel4:  # avoid pixel row out of area
                    if col == col_num - 1:  # avoid pixel columns out of area
                        p2 -= cut4
                        b2 -= cut4

                    tmp_pixels[p1:p2] = buffer[b1:b2]

    img_result.pixels = tmp_pixels[:]
    img.gl_free()

    img.user_clear()
    bpy.data.images.remove(img)
    os.remove(ren_path)
    bgl.glEnable(bgl.GL_SCISSOR_TEST)

    #---------- restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

    if img_result is not None:
        return img_result
    bgl.glEnd()

bgl.glColor4f(0, 1.0, 1.0, 1)
for edge in mesh.edges:
    bgl.glBegin(bgl.GL_LINES)
    for vert in edge.vertices:
        bgl.glVertex2f((int)(500 + 80 * verts[vert].x),
                       (int)(400 + 80 * verts[vert].y))
    bgl.glEnd()

# Draw a Text
font_id = 0
bgl.glColor4f(1.0, 1.0, 0.0, 1.0)
blf.size(font_id, 18, 72)
blf.position(font_id, 0.5, 0.5, 0)
blf.draw(font_id, "Hello World")

#
bgl.glFinish()
bgl.glReadPixels(0, 0, WIDTH, HEIGHT, bgl.GL_RGBA, bgl.GL_FLOAT,
                 buffer)  # read image data
out.pixels = buffer[:]  # Assign image data
img.gl_free()  # free opengl image memory

#reset
bgl.glEnable(bgl.GL_SCISSOR_TEST)
# restore opengl defaults
bgl.glLineWidth(1)
bgl.glDisable(bgl.GL_BLEND)
bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Esempio n. 8
0
def render_main(self, context, animation=False):
    # noinspection PyBroadException,PyBroadException
    try:
        # Get visible layers
        layers = []
        scene = context.scene
        for x in range(0, 20):
            if scene.layers[x] is True:
                layers.extend([x])

        # Get object list
        objlist = context.scene.objects
        # --------------------
        # Get resolution
        # --------------------
        scene = bpy.context.scene
        render_scale = scene.render.resolution_percentage / 100

        width = int(scene.render.resolution_x * render_scale)
        height = int(scene.render.resolution_y * render_scale)

        # ---------------------------------------
        # Get output path
        # ---------------------------------------
        ren_path = bpy.context.scene.render.filepath
        if len(ren_path) > 0:
            if ren_path.endswith(os.path.sep):
                initpath = os.path.realpath(ren_path) + os.path.sep
            else:
                (initpath, filename) = os.path.split(ren_path)
            outpath = os.path.join(initpath, "measureit_tmp_render.png")
        else:
            self.report({'ERROR'},
                        "MeasureIt: Unable to save temporary render image. Define a valid render path")
            return False

        # Get Render Image
        img = get_render_image(outpath)
        if img is None:
            self.report({'ERROR'},
                        "MeasureIt: Unable to save temporary render image. Define a valid render path")
            return False

        # -----------------------------
        # Calculate rows and columns
        # -----------------------------
        tile_x = 240
        tile_y = 216
        row_num = ceil(height / tile_y)
        col_num = ceil(width / tile_x)
        print("MeasureIt: Image divided in " + str(row_num) + "x" + str(col_num) + " tiles")

        # pixels out of visible area
        cut4 = (col_num * tile_x * 4) - width * 4  # pixels aout of drawing area
        totpixel4 = width * height * 4  # total pixels RGBA

        viewport_info = bgl.Buffer(bgl.GL_INT, 4)
        bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info)

        # Load image on memory
        img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST)
        tex = img.bindcode

        # --------------------------------------------
        # Create output image (to apply texture)
        # --------------------------------------------
        if "measureit_output" in bpy.data.images:
            out_img = bpy.data.images["measureit_output"]
            if out_img is not None:
                out_img.user_clear()
                bpy.data.images.remove(out_img)

        out = bpy.data.images.new("measureit_output", width, height)
        tmp_pixels = [1] * totpixel4

        # --------------------------------
        # Loop for all tiles
        # --------------------------------
        for row in range(0, row_num):
            for col in range(0, col_num):
                buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4)
                bgl.glDisable(bgl.GL_SCISSOR_TEST)  # if remove this line, get blender screenshot not image
                bgl.glViewport(0, 0, tile_x, tile_y)

                bgl.glMatrixMode(bgl.GL_PROJECTION)
                bgl.glLoadIdentity()

                # defines ortographic view for single tile
                x1 = tile_x * col
                y1 = tile_y * row
                bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y)

                # Clear
                bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
                bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)

                bgl.glEnable(bgl.GL_TEXTURE_2D)
                bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)

                # defines drawing area
                bgl.glBegin(bgl.GL_QUADS)

                bgl.glColor3f(1.0, 1.0, 1.0)
                bgl.glTexCoord2f(0.0, 0.0)
                bgl.glVertex2f(0.0, 0.0)

                bgl.glTexCoord2f(1.0, 0.0)
                bgl.glVertex2f(width, 0.0)

                bgl.glTexCoord2f(1.0, 1.0)
                bgl.glVertex2f(width, height)

                bgl.glTexCoord2f(0.0, 1.0)
                bgl.glVertex2f(0.0, height)

                bgl.glEnd()

                # -----------------------------
                # Loop to draw all lines
                # -----------------------------
                for myobj in objlist:
                    if myobj.hide is False:
                        if 'MeasureGenerator' in myobj:
                            # verify visible layer
                            for x in range(0, 20):
                                if myobj.layers[x] is True:
                                    if x in layers:
                                        op = myobj.MeasureGenerator[0]
                                        draw_segments(context, myobj, op, None, None)
                                    break

                if scene.measureit_rf is True:
                    bgl.glColor3f(1.0, 1.0, 1.0)
                    rfcolor = scene.measureit_rf_color
                    rfborder = scene.measureit_rf_border
                    rfline = scene.measureit_rf_line

                    bgl.glLineWidth(rfline)
                    bgl.glColor4f(rfcolor[0], rfcolor[1], rfcolor[2], rfcolor[3])

                    x1 = rfborder
                    x2 = width - rfborder
                    y1 = int(math.ceil(rfborder / (width / height)))
                    y2 = height - y1
                    draw_rectangle((x1, y1), (x2, y2))

                # --------------------------------
                # copy pixels to temporary area
                # --------------------------------
                bgl.glFinish()
                bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer)  # read image data
                for y in range(0, tile_y):
                    # final image pixels position
                    p1 = (y * width * 4) + (row * tile_y * width * 4) + (col * tile_x * 4)
                    p2 = p1 + (tile_x * 4)
                    # buffer pixels position
                    b1 = y * width * 4
                    b2 = b1 + (tile_x * 4)

                    if p1 < totpixel4:  # avoid pixel row out of area
                        if col == col_num - 1:  # avoid pixel columns out of area
                            p2 -= cut4
                            b2 -= cut4

                        tmp_pixels[p1:p2] = buffer[b1:b2]

        # -----------------------
        # Copy temporary to final
        # -----------------------
        out.pixels = tmp_pixels[:]  # Assign image data
        img.gl_free()  # free opengl image memory

        # delete image
        img.user_clear()
        bpy.data.images.remove(img)
        # remove temp file
        os.remove(outpath)
        # reset
        bgl.glEnable(bgl.GL_SCISSOR_TEST)
        # -----------------------
        # restore opengl defaults
        # -----------------------
        bgl.glLineWidth(1)
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
        # Saves image
        if out is not None and (scene.measureit_render is True or animation is True):
            ren_path = bpy.context.scene.render.filepath
            filename = "mit_frame"
            if len(ren_path) > 0:
                if ren_path.endswith(os.path.sep):
                    initpath = os.path.realpath(ren_path) + os.path.sep
                else:
                    (initpath, filename) = os.path.split(ren_path)

            ftxt = "%04d" % scene.frame_current
            outpath = os.path.join(initpath, filename + ftxt + ".png")

            save_image(self, outpath, out)

        return True

    except:
        print("Unexpected error:" + str(sys.exc_info()))
        self.report({'ERROR'}, "MeasureIt: Unable to create render image")
        return False
Esempio n. 9
0
    def execute(self, refholder):
        # pass
        tr = self.nodeTree.properties.TextureResolution
        print("begining execution " + str(tr))
        # compute A'
        mask = np.array([[0.05, 0.2, 0.05], [0.2, -1, 0.2], [0.05, 0.2, 0.05]])
        # Input data pixels
        A = self.inputs[0].getPixels()
        B = self.inputs[1].getPixels()

        # print(A)

        bgl.glGetIntegerv(bgl.GL_CURRENT_PROGRAM,
                          self.rdData[self.name]["prev_program"])
        bgl.glUseProgram(self.rdData[self.name]["program"])

        #set any uniforms needed
        bgl.glUniform1f(self.rdData[self.name]["feed_loc"],
                        self.inputs[2].value)
        bgl.glUniform1f(self.rdData[self.name]["kill_loc"],
                        self.inputs[3].value)
        bgl.glUniform1f(self.rdData[self.name]["da_loc"], self.inputs[4].value)
        bgl.glUniform1f(self.rdData[self.name]["db_loc"], self.inputs[5].value)
        bgl.glUniform1f(self.rdData[self.name]["dt_loc"], self.inputs[6].value)
        bgl.glUniform1f(self.rdData[self.name]["step_loc"], 1 / tr)

        bgl.glDisable(bgl.GL_SCISSOR_TEST)
        bgl.glViewport(0, 0, tr, tr)

        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glPushMatrix()
        bgl.glLoadIdentity()

        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glPushMatrix()
        bgl.glLoadIdentity()
        bgl.gluOrtho2D(0, 1, 0, 1)

        bgl.glEnable(bgl.GL_TEXTURE_2D)
        bgl.glActiveTexture(bgl.GL_TEXTURE0)

        channels = []
        if self.channels == '0':
            channels = [0]
        elif self.channels == '1':
            channels = [0, 1, 2]

        for j in channels:
            self.rdData[self.name]["npArray"][:, :, 0] = A[:, :, j]
            self.rdData[self.name]["npArray"][:, :, 1] = B[:, :, j]

            # Caution: Interfacing with Cython requires toList()
            self.rdData[self.name]["image"].pixels = self.rdData[
                self.name]["npArray"].flatten()

            self.rdData[self.name]["image"].gl_load(0, bgl.GL_LINEAR,
                                                    bgl.GL_LINEAR)

            bgl.glBindTexture(bgl.GL_TEXTURE_2D,
                              self.rdData[self.name]["image"].bindcode[0])
            bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_WRAP_S,
                                bgl.GL_REPEAT)
            bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_WRAP_T,
                                bgl.GL_REPEAT)

            for i in range(self.inputs[7].value):
                bgl.glClearDepth(1.0)
                bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
                bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)

                bgl.glBegin(bgl.GL_TRIANGLES)

                bgl.glColor3f(1.0, 1.0, 1.0)
                bgl.glTexCoord2f(0.0, 0.0)
                bgl.glVertex2f(-1.0, -1.0)
                bgl.glTexCoord2f(1.0, 0.0)
                bgl.glVertex2f(1.0, -1.0)
                bgl.glTexCoord2f(1.0, 1.0)
                bgl.glVertex2f(1.0, 1.0)

                bgl.glColor3f(1.0, 1.0, 1.0)
                bgl.glTexCoord2f(0.0, 0.0)
                bgl.glVertex2f(-1.0, -1.0)
                bgl.glTexCoord2f(1.0, 1.0)
                bgl.glVertex2f(1.0, 1.0)
                bgl.glTexCoord2f(0.0, 1.0)
                bgl.glVertex2f(-1.0, 1.0)
                bgl.glEnd()

                bgl.glCopyTexImage2D(
                    bgl.GL_TEXTURE_2D,  #target
                    0,  #level
                    bgl.GL_RGBA,  #internalformat
                    0,  #x
                    0,  #y
                    tr,
                    tr,
                    0  #border
                )

                #glFlush glFinish or none here?
                bgl.glFinish()

            bgl.glReadPixels(0, 0, tr, tr, bgl.GL_RGBA, bgl.GL_FLOAT,
                             self.rdData[self.name]["buffer"])
            self.rdData[self.name]["image"].pixels = self.rdData[
                self.name]["buffer"][:]
            #write the image channel
            npImage = np.asarray(self.rdData[self.name]["image"].pixels,
                                 dtype="float")
            self.rdData[self.name]["npArray"] = npImage.reshape(
                tr, tr, self.rdData[self.name]["image"].channels)

            self.outputs[0].setPackedImageFromChannels(
                self.rdData[self.name]["npArray"][:, :, 0], j, flatten=True)
            self.outputs[1].setPackedImageFromChannels(
                self.rdData[self.name]["npArray"][:, :, 1], j, flatten=True)
            self.outputs[2].setPackedImageFromPixels(
                self.rdData[self.name]["npArray"])

            self.inputs[0].setPackedImageFromChannels(
                self.rdData[self.name]["npArray"][:, :, 0], j, flatten=True)
            self.inputs[1].setPackedImageFromChannels(
                self.rdData[self.name]["npArray"][:, :, 1], j, flatten=True)

            # ================================= Test bed
            # self.outputs[0].getTexture().image.copy()
            # self.outputs[1].getTexture().image.copy()
            # self.outputs[2].getTexture().image.copy()

            # nparr = np.asarray(self.outputs[0].getTexture().image.pixels, dtype="float")
            # nparr = nparr.reshape(tr, tr, 4)
            # print(nparr)

            self.rdData[self.name]["image"].gl_free()

        #restore the state so blender wont break
        bgl.glEnable(bgl.GL_SCISSOR_TEST)
        bgl.glUseProgram(self.rdData[self.name]["prev_program"][0])
        bgl.glActiveTexture(bgl.GL_TEXTURE0)
Esempio n. 10
0
def render_opengl(self, context):
    from math import ceil

    layers = []
    scene = context.scene
    for x in range(0, 20):
        if scene.layers[x] is True:
            layers.extend([x])

    objlist = context.scene.objects
    render_scale = scene.render.resolution_percentage / 100

    width = int(scene.render.resolution_x * render_scale)
    height = int(scene.render.resolution_y * render_scale)
    
    # I cant use file_format becuase the pdf writer needs jpg format
    # the file_format returns 'JPEG' not 'JPG'
#     file_format = context.scene.render.image_settings.file_format.lower()
    ren_path = bpy.path.abspath(bpy.context.scene.render.filepath) + ".jpg"
    
#     if len(ren_path) > 0:
#         if ren_path.endswith(os.path.sep):
#             initpath = os.path.realpath(ren_path) + os.path.sep
#         else:
#             (initpath, filename) = os.path.split(ren_path)
#         outpath = os.path.join(initpath, "ogl_tmp.png")
#     else:
#         self.report({'ERROR'}, "Invalid render path")
#         return False

    img = get_render_image(ren_path)
    
    if img is None:
        self.report({'ERROR'}, "Invalid render path:" + ren_path)
        return False

    tile_x = 240
    tile_y = 216
    row_num = ceil(height / tile_y)
    col_num = ceil(width / tile_x)
    
    cut4 = (col_num * tile_x * 4) - width * 4  
    totpixel4 = width * height * 4 

    viewport_info = bgl.Buffer(bgl.GL_INT, 4)
    bgl.glGetIntegerv(bgl.GL_VIEWPORT, viewport_info)
    
    img.gl_load(0, bgl.GL_NEAREST, bgl.GL_NEAREST)

    # 2.77 API change
    if bpy.app.version >= (2, 77, 0):
        tex = img.bindcode[0]
    else:
        tex = img.bindcode
    
    if context.scene.name in bpy.data.images:
        old_img = bpy.data.images[context.scene.name]
        old_img.user_clear()
        bpy.data.images.remove(old_img)
             
    img_result = bpy.data.images.new(context.scene.name, width, height)        
    
    tmp_pixels = [1] * totpixel4

    #---------- Loop for all tiles
    for row in range(0, row_num):
        for col in range(0, col_num):
            buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4)
            bgl.glDisable(bgl.GL_SCISSOR_TEST)  # if remove this line, get blender screenshot not image
            bgl.glViewport(0, 0, tile_x, tile_y)

            bgl.glMatrixMode(bgl.GL_PROJECTION)
            bgl.glLoadIdentity()

            # defines ortographic view for single tile
            x1 = tile_x * col
            y1 = tile_y * row
            bgl.gluOrtho2D(x1, x1 + tile_x, y1, y1 + tile_y)

            # Clear
            bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
            bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)

            bgl.glEnable(bgl.GL_TEXTURE_2D)
            bgl.glBindTexture(bgl.GL_TEXTURE_2D, tex)

            # defines drawing area
            bgl.glBegin(bgl.GL_QUADS)

            bgl.glColor3f(1.0, 1.0, 1.0)
            bgl.glTexCoord2f(0.0, 0.0)
            bgl.glVertex2f(0.0, 0.0)

            bgl.glTexCoord2f(1.0, 0.0)
            bgl.glVertex2f(width, 0.0)

            bgl.glTexCoord2f(1.0, 1.0)
            bgl.glVertex2f(width, height)

            bgl.glTexCoord2f(0.0, 1.0)
            bgl.glVertex2f(0.0, height)

            bgl.glEnd()

            for obj in objlist:
                if obj.mv.type == 'VISDIM_A':
                    for x in range(0, 20):
                        if obj.layers[x] is True:
                            if x in layers:
                                opengl_dim = obj.mv.opengl_dim
                                if not opengl_dim.hide:
                                    draw_dimensions(context, obj, opengl_dim, None, None)
                            break 

            #---------- copy pixels to temporary area
            bgl.glFinish()
            bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer)  # read image data
            for y in range(0, tile_y):
                # final image pixels position
                p1 = (y * width * 4) + (row * tile_y * width * 4) + (col * tile_x * 4)
                p2 = p1 + (tile_x * 4)
                # buffer pixels position
                b1 = y * width * 4
                b2 = b1 + (tile_x * 4)

                if p1 < totpixel4:  # avoid pixel row out of area
                    if col == col_num - 1:  # avoid pixel columns out of area
                        p2 -= cut4
                        b2 -= cut4

                    tmp_pixels[p1:p2] = buffer[b1:b2]

    img_result.pixels = tmp_pixels[:]
    img.gl_free()

    img.user_clear()
    bpy.data.images.remove(img)
    os.remove(ren_path)
    bgl.glEnable(bgl.GL_SCISSOR_TEST)

    #---------- restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
    
    if img_result is not None:            
        return img_result