Exemple #1
0
	def glGetMatrix(self, type):
		buf = bgl.Buffer(bgl.GL_FLOAT, [4,4])
		bgl.glGetFloatv(type, buf)
		mat = Matrix()
		for i in range(0,4):
			for j in range(0,4):
				mat[i][j] = buf[j][i]
		return mat
    def ondraw_postview(self, obj_arm, bone):
        if obj_arm.hide_viewport or not obj_arm.data.xray.display_bone_shapes or not bone.xray.exportable:
            return

        if not obj_arm.name in bpy.context.scene.objects:
            return

        visible_armature_object = False
        for layer_index, layer in enumerate(obj_arm.layers):
            scene_layer = bpy.context.scene.layers[layer_index]
            if scene_layer and layer:
                visible_armature_object = True
                break

        if not visible_armature_object:
            return

        from .gl_utils import matrix_to_buffer, \
            draw_wire_cube, draw_wire_sphere, draw_wire_cylinder, draw_cross

        shape = self.shape
        if shape.type == '0':
            return
        bgl.glEnable(bgl.GL_BLEND)
        if bpy.context.active_bone \
                and (bpy.context.active_bone.id_data == obj_arm.data) \
                and (bpy.context.active_bone.name == bone.name):
            bgl.glColor4f(1.0, 0.0, 0.0, 0.7)
        else:
            bgl.glColor4f(0.0, 0.0, 1.0, 0.5)
        prev_line_width = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, prev_line_width)
        bgl.glPushMatrix()
        try:
            mat = obj_arm.matrix_world * obj_arm.pose.bones[bone.name].matrix \
                  * mathutils.Matrix.Scale(-1, 4, (0, 0, 1))
            bmat = mat
            bgl.glLineWidth(2)
            mat *= shape.get_matrix_basis()
            bgl.glMultMatrixf(matrix_to_buffer(mat.transposed()))
            if shape.type == '1':  # box
                draw_wire_cube(*shape.box_hsz)
            if shape.type == '2':  # sphere
                draw_wire_sphere(shape.sph_rad, 16)
            if shape.type == '3':  # cylinder
                draw_wire_cylinder(shape.cyl_rad, shape.cyl_hgh * 0.5, 16)
            bgl.glPopMatrix()
            bgl.glPushMatrix()
            ctr = self.mass.center
            trn = bmat * mathutils.Vector((ctr[0], ctr[2], ctr[1]))
            bgl.glTranslatef(*trn)
            draw_cross(0.05)
        finally:
            bgl.glPopMatrix()
            bgl.glLineWidth(prev_line_width[0])
Exemple #3
0
    def __init__(self, context):
        rv3d = context.region_data
        persmat = rv3d.perspective_matrix
        flatten_persmat = [persmat[i][j] for i in range(4) for j in range(4)]
        self.persmat_buffer = bgl.Buffer(bgl.GL_FLOAT, 16, flatten_persmat)

        # GL_BLEND
        blend = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_BLEND, blend)
        self.blend = blend[0]

        # GL_COLOR
        color = bgl.Buffer(bgl.GL_FLOAT, [4])
        bgl.glGetFloatv(bgl.GL_COLOR, color)
        self.color = color

        # GL_LINE_WIDTH
        line_width = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, line_width)
        self.line_width = line_width[0]

        # GL_Matrix_MODE
        matrix_mode = bgl.Buffer(bgl.GL_INT, [1])
        bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, matrix_mode)
        self.matrix_mode = matrix_mode[0]

        # GL_PROJECTION_MATRIX
        projection_matrix = bgl.Buffer(bgl.GL_DOUBLE, [16])
        bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, projection_matrix)
        self.projection_matrix = projection_matrix

        # blf: size, dpi
        self.size_dpi = (11, context.user_preferences.system.dpi)
    def ondraw_postview(self, obj_arm, bone):
        if obj_arm.hide or not obj_arm.data.xray.display_bone_shapes:
            return

        from .gl_utils import matrix_to_buffer, draw_wire_cube, draw_wire_sphere, draw_wire_cylinder

        shape = self.shape
        if shape.type == '0':
            return
        bgl.glEnable(bgl.GL_BLEND)
        if bpy.context.active_bone and (bpy.context.active_bone.id_data
                                        == obj_arm.data) and (
                                            bpy.context.active_bone.name
                                            == bone.name):
            bgl.glColor4f(1.0, 0.0, 0.0, 0.7)
        else:
            bgl.glColor4f(0.0, 0.0, 1.0, 0.5)
        prev_line_width = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, prev_line_width)
        bgl.glPushMatrix()
        try:
            m = obj_arm.matrix_world * obj_arm.pose.bones[
                bone.name].matrix * mathutils.Matrix.Scale(-1, 4, (0, 0, 1))
            bgl.glLineWidth(2)
            if shape.type == '1':  # box
                rt = shape.box_rot
                mr = mathutils.Matrix((rt[0:3], rt[3:6], rt[6:9])).transposed()
                m *= mathutils.Matrix.Translation(shape.box_trn) * mr.to_4x4()
                bgl.glMultMatrixf(matrix_to_buffer(m.transposed()))
                draw_wire_cube(*shape.box_hsz)
            if shape.type == '2':  # sphere
                m *= mathutils.Matrix.Translation(shape.sph_pos)
                bgl.glMultMatrixf(matrix_to_buffer(m.transposed()))
                draw_wire_sphere(shape.sph_rad, 16)
            if shape.type == '3':  # cylinder
                m *= mathutils.Matrix.Translation(shape.cyl_pos)
                bgl.glMultMatrixf(matrix_to_buffer(m.transposed()))
                v_dir = mathutils.Vector(shape.cyl_dir)
                q_rot = v_dir.rotation_difference((0, 1, 0))
                bgl.glMultMatrixf(matrix_to_buffer(q_rot.to_matrix().to_4x4()))
                draw_wire_cylinder(shape.cyl_rad, shape.cyl_hgh * 0.5, 16)
        finally:
            bgl.glPopMatrix()
            bgl.glLineWidth(prev_line_width[0])
Exemple #5
0
def draw_helpers():
    context = bpy.context
    obj = context.active_object

    if (context.active_object != None and obj.type == 'MESH'
            and context.active_object.mode == 'EDIT'):
        line_width = bgl.Buffer(bgl.GL_FLOAT, 1)
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, line_width)
        if context.window_manager.b4w_split and "b4w_select_vertex" in obj:
            vertex = obj.data.vertices
            array = b4w_vertex_to_loops_map[obj["b4w_select_vertex"]]
            ind = array[obj["b4w_select"] % len(array)]
            n = b4w_loops_normals[ind]
            draw_normal(context, vertex[obj["b4w_select_vertex"]].co, n, 1)
        if rotation_helper_params.is_active:
            draw_rotation_line()
            if rotation_helper_params.constraint:
                draw_axis()
        bgl.glLineWidth(line_width.to_list()[0])
Exemple #6
0
def draw_helpers():
    context = bpy.context
    obj = context.active_object

    if (context.active_object != None and obj.type == 'MESH' and
            context.active_object.mode == 'EDIT'):
        line_width = bgl.Buffer(bgl.GL_FLOAT, 1)
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, line_width)
        if context.window_manager.b4w_split and "b4w_select_vertex" in obj:
            vertex = obj.data.vertices
            array = b4w_vertex_to_loops_map[obj["b4w_select_vertex"]]
            ind = array[obj["b4w_select"]%len(array)]
            n = b4w_loops_normals[ind]
            draw_normal(context, vertex[obj["b4w_select_vertex"]].co, n, 1)
        if rotation_helper_params.is_active:
            draw_rotation_line()
            if rotation_helper_params.constraint:
                draw_axis()
        bgl.glLineWidth(line_width.to_list()[0])
Exemple #7
0
    def draw(self, context):
        """
        Draw vector icon on position of shared object
        """

        if self.locked is True:
            # When object is locked by current client, then visualize it by green color.
            # Otherwise visualize it by red color
            if self.locked_by_me is True:
                color = (0.0, 1.0, 0.0, 1.0)
            else:
                color = (1.0, 0.0, 0.0, 1.0)
        else:
            color = (0.0, 1.0, 1.0, 1.0)

        # Store Line width
        line_width_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, line_width_prev)
        line_width_prev = line_width_prev[0]

        # Store glColor4f
        col_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
        bgl.glGetFloatv(bgl.GL_COLOR, col_prev)

        pos = self.transform.pos.value
        if pos is not None:
            new_pos = location_3d_to_region_2d(
                context.region,
                context.space_data.region_3d,
                pos)
        else:
            # When position of object is not set atm, then draw
            # icon with stipple line
            new_pos = mathutils.Vector((0.0, 0.0, 0.0, 1.0))
            bgl.glEnable(bgl.GL_LINE_STIPPLE)

        verts = (
            (0.20000000298023224, 0.0),
            (0.19318519532680511, 0.051763709634542465),
            (0.17320513725280762, 0.09999989718198776),
            (0.14142143726348877, 0.14142127335071564),
            (0.10000012069940567, 0.17320501804351807),
            (0.13000015914440155, 0.22516652941703796),
            (0.06729313731193542, 0.25114068388938904),
            (0.0, 0.2600000202655792),
            (-0.0672929584980011, 0.2511407434940338),
            (-0.1300000101327896, 0.22516663372516632),
            (-0.1000000014901161, 0.17320509254932404),
            (-0.1414213627576828, 0.1414213627576828),
            (-0.1732050925493240, 0.09999999403953552),
            (-0.1931851655244827, 0.05176381394267082),
            (-0.2000000029802322, 0.0),
            (-0.2600000202655792, 0.0),
            (-0.2511407434940338, -0.06729292124509811),
            (-0.2251666486263275, -0.12999996542930603),
            (-0.1838478147983551, -0.18384772539138794),
            (-0.1300000697374344, -0.22516658902168274),
            (-0.1000000461935997, -0.17320506274700165),
            (-0.0517638735473156, -0.19318515062332153),
            (0.0, -0.20000000298023224),
            (0.05176372453570366, -0.19318519532680511),
            (0.09999991953372955, -0.17320513725280762),
            (0.12999990582466125, -0.2251666933298111),
            (0.18384768068790436, -0.18384787440299988),
            (0.22516657412052155, -0.13000008463859558),
            (0.25114068388938904, -0.06729305535554886),
            (0.26000002026557920, 0.0)
        )

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

        bgl.glPushMatrix()

        bgl.glTranslatef(new_pos[0], new_pos[1], 0)

        # TODO: Rotate this icon, when some other user change something (tranformation, mesh)
        # bgl.glRotatef(self.icon_angle, 0, 0, 1)

        # Draw icon
        bgl.glBegin(bgl.GL_LINE_LOOP)
        for vert in verts:
            bgl.glVertex2f(100.0 * vert[0], 100.0 * vert[1])
        bgl.glEnd()

        # When object is locked by someone else or it can not be selected, then draw cross over icon
        if self.locked is True and self.locked_by_me is False or \
                self.can_be_selected is False:
            bgl.glBegin(bgl.GL_LINES)
            bgl.glVertex2f(100.0 * verts[3][0], 100.0 * verts[3][1])
            bgl.glVertex2f(100.0 * verts[18][0], 100.0 * verts[18][1])
            bgl.glVertex2f(100.0 * verts[11][0], 100.0 * verts[11][1])
            bgl.glVertex2f(100.0 * verts[27][0], 100.0 * verts[27][1])
            bgl.glEnd()

        bgl.glPopMatrix()

        bgl.glDisable(bgl.GL_LINE_STIPPLE)
        bgl.glLineWidth(line_width_prev)
        bgl.glColor4f(col_prev[0], col_prev[1], col_prev[2], col_prev[3])

        # # Try to draw mesh IDs
        # if self.mesh_node is not None:
        #     self.mesh_node.draw_IDs(context, self.obj)
def draw_measurements_callback(self, context):
    sce = context.scene

    draw = 0
    if hasattr(sce, "measure_panel_draw"):
        draw = sce.measure_panel_draw

    # 2D drawing code example
    #bgl.glBegin(bgl.GL_LINE_STRIP)
    #bgl.glVertex2i(0, 0)
    #bgl.glVertex2i(80, 100)
    #bgl.glEnd()

    # Get measured 3D points and colors.
    line = getMeasurePoints(context)
    if (line and draw):
        p1, p2, color = line

        # Get and convert the Perspective Matrix of the current view/region.
        view3d = bpy.context
        region = view3d.region_data
        perspMatrix = region.perspective_matrix
        tempMat = [perspMatrix[i][j] for i in range(4) for j in range(4)]
        perspBuff = bgl.Buffer(bgl.GL_FLOAT, 16, tempMat)

        # ---
        # Store previous OpenGL settings.
        # Store MatrixMode
        MatrixMode_prev = bgl.Buffer(bgl.GL_INT, [1])
        bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, MatrixMode_prev)
        MatrixMode_prev = MatrixMode_prev[0]

        # Store projection matrix
        ProjMatrix_prev = bgl.Buffer(bgl.GL_DOUBLE, [16])
        bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, ProjMatrix_prev)

        # Store Line width
        lineWidth_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, lineWidth_prev)
        lineWidth_prev = lineWidth_prev[0]

        # Store GL_BLEND
        blend_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_BLEND, blend_prev)
        blend_prev = blend_prev[0]

        line_stipple_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_LINE_STIPPLE, line_stipple_prev)
        line_stipple_prev = line_stipple_prev[0]

        # Store glColor4f
        color_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
        bgl.glGetFloatv(bgl.GL_COLOR, color_prev)

        # ---
        # Prepare for 3D drawing
        bgl.glLoadIdentity()
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadMatrixf(perspBuff)

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_LINE_STIPPLE)

        # ---
        # Draw 3D stuff.
        width = 1
        bgl.glLineWidth(width)
        # X
        bgl.glColor4f(1, 0, 0, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p2[0], p1[1], p1[2])
        bgl.glEnd()
        # Y
        bgl.glColor4f(0, 1, 0, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p1[0], p2[1], p1[2])
        bgl.glEnd()
        # Z
        bgl.glColor4f(0, 0, 1, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p1[0], p1[1], p2[2])
        bgl.glEnd()

        # Dist
        width = 2
        bgl.glLineWidth(width)
        bgl.glColor4f(color[0], color[1], color[2], color[3])
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p2[0], p2[1], p2[2])
        bgl.glEnd()

        # ---
        # Restore previous OpenGL settings
        bgl.glLoadIdentity()
        bgl.glMatrixMode(MatrixMode_prev)
        bgl.glLoadMatrixf(ProjMatrix_prev)
        bgl.glLineWidth(lineWidth_prev)
        if not blend_prev:
            bgl.glDisable(bgl.GL_BLEND)
        if not line_stipple_prev:
            bgl.glDisable(bgl.GL_LINE_STIPPLE)
        bgl.glColor4f(color_prev[0],
            color_prev[1],
            color_prev[2],
            color_prev[3])

        # ---
        # Draw (2D) text
        # We do this after drawing the lines so
        # we can draw it OVER the line.
        coord_2d = location_3d_to_region_2d(context.region,
                                            context.space_data.region_3d,
                                            p1.lerp(p2, 0.5),
                                            )
        OFFSET_LINE = 10   # Offset the text a bit to the right.
        OFFSET_Y = 15      # Offset of the lines.
        OFFSET_VALUE = 30  # Offset of value(s) from the text.
        dist = (p1 - p2).length

        # Write distance value into the scene property,
        # so we can display it in the panel & refresh the panel.
        if hasattr(sce, "measure_panel_dist"):
            sce.measure_panel_dist = dist
            context.area.tag_redraw()

        texts = [("Dist:", round(dist, PRECISION)),
            ("X:", round(abs(p1[0] - p2[0]), PRECISION)),
            ("Y:", round(abs(p1[1] - p2[1]), PRECISION)),
            ("Z:", round(abs(p1[2] - p2[2]), PRECISION))]

        # Draw all texts
        # @todo Get user pref for text color in 3D View
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        blf.size(0, 12, 72)  # Prevent font size to randomly change.

        loc_x = coord_2d[0] + OFFSET_LINE
        loc_y = coord_2d[1]
        for t in texts:
            text = t[0]
            value = str(t[1]) + " BU"

            blf.position(0, loc_x, loc_y, 0)
            blf.draw(0, text)
            blf.position(0, loc_x + OFFSET_VALUE, loc_y, 0)
            blf.draw(0, value)

            loc_y -= OFFSET_Y

    # Handle mesh surface area calulations
    if (sce.measure_panel_calc_area):
        # Get a single selected object (or nothing).
        obj = getSingleObject(context)

        if (context.mode == 'EDIT_MESH'):
            obj = context.active_object

            if (obj and obj.type == 'MESH' and obj.data):
                # "Note: a Mesh will return the selection state of the mesh
                # when EditMode was last exited. A Python script operating
                # in EditMode must exit EditMode before getting the current
                # selection state of the mesh."
                # http://www.blender.org/documentation/249PythonDoc/
                # /Mesh.MVert-class.html#sel
                # We can only provide this by existing & re-entering EditMode.
                # @todo: Better way to do this?

                # Get mesh data from Object.
                mesh = obj.data

                # Get transformation matrix from object.
                ob_mat = obj.matrix_world
                # Also make an inversed copy! of the matrix.
                ob_mat_inv = ob_mat.copy()
                Matrix.invert(ob_mat_inv)

                # Get the selected vertices.
                # @todo: Better (more efficient) way to do this?
                verts_selected = [v for v in mesh.vertices if v.select == 1]

                if len(verts_selected) >= 3:
                    # Get selected faces
                    # @todo: Better (more efficient) way to do this?
                    faces_selected = [f for f in mesh.faces
                        if f.select == 1]

                    if len(faces_selected) > 0:
                        area, normal = objectSurfaceArea(obj, True,
                            measureGlobal(sce))
                        if (area >= 0):
                            sce.measure_panel_area1 = area
                            sce.measure_panel_normal1 = normal

        elif (context.mode == 'OBJECT'):
            # We are working in object mode.

            if len(context.selected_objects) > 2:
                return
# @todo Make this work again.
#                # We have more that 2 objects selected...
#
#                mesh_objects = [o for o in context.selected_objects
#                    if (o.type == 'MESH')]

#                if (len(mesh_objects) > 0):
#                    # ... and at least one of them is a mesh.
#
#                    for o in mesh_objects:
#                        area = objectSurfaceArea(o, False,
#                            measureGlobal(sce))
#                        if (area >= 0):
#                            #row.label(text=o.name, icon='OBJECT_DATA')
#                            #row.label(text=str(round(area, PRECISION))
#                            #    + " BU^2")

            elif len(context.selected_objects) == 2:
                # 2 objects selected.

                obj1, obj2 = context.selected_objects

                # Calculate surface area of the objects.
                area1, normal1 = objectSurfaceArea(obj1, False,
                    measureGlobal(sce))
                area2, normal2 = objectSurfaceArea(obj2, False,
                    measureGlobal(sce))
                sce.measure_panel_area1 = area1
                sce.measure_panel_area2 = area2
                sce.measure_panel_normal1 = normal1
                sce.measure_panel_normal2 = normal2

            elif (obj):
                # One object selected.

                # Calculate surface area of the object.
                area, normal = objectSurfaceArea(obj, False,
                    measureGlobal(sce))

                if (area >= 0):
                    sce.measure_panel_area1 = area
                    sce.measure_panel_normal1 = normal

    if (sce.measure_panel_calc_volume):
        obj = getSingleObject(context)

        if (context.mode == 'OBJECT'):
            # We are working in object mode.

            #if len(context.selected_objects) > 2:       # TODO

            #el
            if len(context.selected_objects) == 2:
                # 2 objects selected.

                obj1, obj2 = context.selected_objects

                # Calculate surface area of the objects.
                volume1 = objectVolume(obj1, measureGlobal(sce))
                volume2 = objectVolume(obj2, measureGlobal(sce))

                sce.measure_panel_volume1 = volume1
                sce.measure_panel_volume2 = volume2

            elif (obj):
                # One object selected.

                # Calculate surface area of the object.
                volume1 = objectVolume(obj, measureGlobal(sce))

                sce.measure_panel_volume1 = volume1
Exemple #9
0
def DrawNorth_callback(self, context):

    if not Sun.SP.ShowNorth and North.isActive:
        North.deactivate()
        return

    # ------------------------------------------------------------------
    # Set up the compass needle using the current north offset angle
    # less 90 degrees.  This forces the unit circle to begin at the
    # 12 O'clock instead of 3 O'clock position.
    # ------------------------------------------------------------------
    color = (0.2, 0.6, 1.0, 0.7)
    radius = 100
    angle = -(Sun.NorthOffset - math.pi / 2)
    x = math.cos(angle) * radius
    y = math.sin(angle) * radius

    p1, p2 = (0, 0, 0), (x, y, 0)  # Start & end of needle

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Thanks to Buerbaum Martin for the following which draws openGL
    # lines.  ( From his script space_view3d_panel_measure.py )
    #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    # ------------------------------------------------------------------
    # Convert the Perspective Matrix of the current view/region.
    # ------------------------------------------------------------------
    view3d = bpy.context
    region = view3d.region_data
    perspMatrix = region.perspective_matrix
    tempMat = [perspMatrix[j][i] for i in range(4) for j in range(4)]
    perspBuff = bgl.Buffer(bgl.GL_FLOAT, 16, tempMat)

    # ---------------------------------------------------------
    # Store previous OpenGL settings.
    # ---------------------------------------------------------
    MatrixMode_prev = bgl.Buffer(bgl.GL_INT, [1])
    bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, MatrixMode_prev)
    MatrixMode_prev = MatrixMode_prev[0]

    # Store projection matrix
    ProjMatrix_prev = bgl.Buffer(bgl.GL_DOUBLE, [16])
    bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, ProjMatrix_prev)

    # Store Line width
    lineWidth_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
    bgl.glGetFloatv(bgl.GL_LINE_WIDTH, lineWidth_prev)
    lineWidth_prev = lineWidth_prev[0]

    # Store GL_BLEND
    blend_prev = bgl.Buffer(bgl.GL_BYTE, [1])
    bgl.glGetFloatv(bgl.GL_BLEND, blend_prev)
    blend_prev = blend_prev[0]

    line_stipple_prev = bgl.Buffer(bgl.GL_BYTE, [1])
    bgl.glGetFloatv(bgl.GL_LINE_STIPPLE, line_stipple_prev)
    line_stipple_prev = line_stipple_prev[0]

    # Store glColor4f
    color_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
    bgl.glGetFloatv(bgl.GL_COLOR, color_prev)

    # ---------------------------------------------------------
    # Prepare for 3D drawing
    # ---------------------------------------------------------
    bgl.glLoadIdentity()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadMatrixf(perspBuff)

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINE_STIPPLE)

    # ------------------
    # and draw the line
    # ------------------
    width = 2
    bgl.glLineWidth(width)
    bgl.glColor4f(color[0], color[1], color[2], color[3])
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex3f(p1[0], p1[1], p1[2])
    bgl.glVertex3f(p2[0], p2[1], p2[2])
    bgl.glEnd()

    # ---------------------------------------------------------
    # Restore previous OpenGL settings
    # ---------------------------------------------------------
    bgl.glLoadIdentity()
    bgl.glMatrixMode(MatrixMode_prev)
    bgl.glLoadMatrixf(ProjMatrix_prev)
    bgl.glLineWidth(lineWidth_prev)

    if not blend_prev:
        bgl.glDisable(bgl.GL_BLEND)
    if not line_stipple_prev:
        bgl.glDisable(bgl.GL_LINE_STIPPLE)

    bgl.glColor4f(color_prev[0], color_prev[1], color_prev[2], color_prev[3])
Exemple #10
0
    def ondraw_postview(self, obj_arm, bone):
        # draw limits
        arm_xray = obj_arm.data.xray
        if IS_28:
            hide = obj_arm.hide_viewport
        else:
            hide = obj_arm.hide
        if not hide and arm_xray.display_bone_limits and \
                        bone.xray.exportable and obj_arm.mode == 'POSE':
            if bone.select and bone.xray.ikjoint.type in {'2', '3', '5'} and \
                    bpy.context.object.name == obj_arm.name:

                if IS_28:
                    from ..gpu_utils import draw_joint_limits
                    gpu.matrix.push()
                else:
                    from ..gl_utils import draw_joint_limits, matrix_to_buffer
                    bgl.glPushMatrix()
                    bgl.glEnable(bgl.GL_BLEND)
                mat_translate = mathutils.Matrix.Translation(
                    obj_arm.pose.bones[bone.name].matrix.to_translation())
                mat_rotate = obj_arm.data.bones[
                    bone.name].matrix_local.to_euler().to_matrix().to_4x4()
                if bone.parent:
                    mat_rotate_parent = obj_arm.pose.bones[
                        bone.parent.name].matrix_basis.to_euler().to_matrix(
                        ).to_4x4()
                else:
                    mat_rotate_parent = mathutils.Matrix()

                mat = multiply(obj_arm.matrix_world, mat_translate,
                               multiply(mat_rotate, mat_rotate_parent),
                               mathutils.Matrix.Scale(-1, 4, (0, 0, 1)))
                if IS_28:
                    gpu.matrix.multiply_matrix(mat)
                else:
                    bgl.glMultMatrixf(matrix_to_buffer(mat.transposed()))

                pose_bone = obj_arm.pose.bones[bone.name]
                if pose_bone.rotation_mode == 'QUATERNION':
                    rotate = pose_bone.rotation_quaternion.to_euler('XYZ')
                else:
                    rotate = obj_arm.pose.bones[bone.name].rotation_euler

                ik = bone.xray.ikjoint

                if arm_xray.display_bone_limit_x:
                    draw_joint_limits(rotate.x, ik.lim_x_min, ik.lim_x_max,
                                      'X', arm_xray.display_bone_limits_radius)

                if arm_xray.display_bone_limit_y:
                    draw_joint_limits(rotate.y, ik.lim_y_min, ik.lim_y_max,
                                      'Y', arm_xray.display_bone_limits_radius)

                if arm_xray.display_bone_limit_z:
                    draw_joint_limits(rotate.z, ik.lim_z_min, ik.lim_z_max,
                                      'Z', arm_xray.display_bone_limits_radius)

                if IS_28:
                    gpu.matrix.pop()
                else:
                    bgl.glPopMatrix()

        # draw shapes
        if IS_28:
            arm_hide = obj_arm.hide_viewport
        else:
            arm_hide = obj_arm.hide
        if arm_hide or not obj_arm.data.xray.display_bone_shapes or \
                        not bone.xray.exportable or obj_arm.mode == 'EDIT':
            return

        if IS_28:
            if not obj_arm.name in bpy.context.view_layer.objects:
                return
        else:
            if not obj_arm.name in bpy.context.scene.objects:
                return
            visible_armature_object = False
            for layer_index, layer in enumerate(obj_arm.layers):
                scene_layer = bpy.context.scene.layers[layer_index]
                if scene_layer and layer:
                    visible_armature_object = True
                    break

            if not visible_armature_object:
                return

        from ..gl_utils import matrix_to_buffer, \
            draw_wire_cube, draw_wire_sphere, draw_wire_cylinder, draw_cross

        shape = self.shape
        if shape.type == '0':
            return
        if IS_28:
            from ..gpu_utils import draw_wire_cube, draw_wire_sphere, \
                draw_wire_cylinder, draw_cross
            if bpy.context.active_bone \
                and (bpy.context.active_bone.id_data == obj_arm.data) \
                and (bpy.context.active_bone.name == bone.name):
                color = (1.0, 0.0, 0.0, 0.7)
            else:
                color = (0.0, 0.0, 1.0, 0.5)
            gpu.matrix.push()
            try:
                mat = multiply(obj_arm.matrix_world,
                               obj_arm.pose.bones[bone.name].matrix,
                               mathutils.Matrix.Scale(-1, 4, (0, 0, 1)))
                bmat = mat
                mat = multiply(mat, shape.get_matrix_basis())
                gpu.matrix.multiply_matrix(mat)
                if shape.type == '1':  # box
                    draw_wire_cube(*shape.box_hsz, color)
                if shape.type == '2':  # sphere
                    draw_wire_sphere(shape.sph_rad, 16, color)
                if shape.type == '3':  # cylinder
                    draw_wire_cylinder(shape.cyl_rad, shape.cyl_hgh * 0.5, 16,
                                       color)
                gpu.matrix.pop()
                gpu.matrix.push()
                ctr = self.mass.center
                trn = multiply(bmat, mathutils.Vector(
                    (ctr[0], ctr[2], ctr[1])))
                gpu.matrix.translate(trn)
                draw_cross(0.05, color)
            finally:
                gpu.matrix.pop()
        else:
            bgl.glEnable(bgl.GL_BLEND)
            if bpy.context.active_bone \
                and (bpy.context.active_bone.id_data == obj_arm.data) \
                and (bpy.context.active_bone.name == bone.name):
                bgl.glColor4f(1.0, 0.0, 0.0, 0.7)
            else:
                bgl.glColor4f(0.0, 0.0, 1.0, 0.5)
            prev_line_width = bgl.Buffer(bgl.GL_FLOAT, [1])
            bgl.glGetFloatv(bgl.GL_LINE_WIDTH, prev_line_width)
            bgl.glPushMatrix()
            try:
                mat = multiply(obj_arm.matrix_world,
                               obj_arm.pose.bones[bone.name].matrix,
                               mathutils.Matrix.Scale(-1, 4, (0, 0, 1)))
                bmat = mat
                bgl.glLineWidth(2)
                mat = multiply(mat, shape.get_matrix_basis())
                bgl.glMultMatrixf(matrix_to_buffer(mat.transposed()))
                if shape.type == '1':  # box
                    draw_wire_cube(*shape.box_hsz)
                if shape.type == '2':  # sphere
                    draw_wire_sphere(shape.sph_rad, 16)
                if shape.type == '3':  # cylinder
                    draw_wire_cylinder(shape.cyl_rad, shape.cyl_hgh * 0.5, 16)
                bgl.glPopMatrix()
                bgl.glPushMatrix()
                ctr = self.mass.center
                trn = multiply(bmat, mathutils.Vector(
                    (ctr[0], ctr[2], ctr[1])))
                bgl.glTranslatef(*trn)
                draw_cross(0.05)
            finally:
                bgl.glPopMatrix()
                bgl.glLineWidth(prev_line_width[0])
def draw_measurements_callback(self, context):
    sce = context.scene

    draw = 0
    if hasattr(sce, "measure_panel_draw"):
        draw = sce.measure_panel_draw

    # 2D drawing code example
    #bgl.glBegin(bgl.GL_LINE_STRIP)
    #bgl.glVertex2i(0, 0)
    #bgl.glVertex2i(80, 100)
    #bgl.glEnd()

    # Get measured 3D points and colors.
    line = getMeasurePoints(context)
    if (line and draw):
        p1, p2, color = line

        # Get and convert the Perspective Matrix of the current view/region.
        view3d = bpy.context
        region = view3d.region_data
        perspMatrix = region.perspective_matrix
        tempMat = [perspMatrix[i][j] for i in range(4) for j in range(4)]
        perspBuff = bgl.Buffer(bgl.GL_FLOAT, 16, tempMat)

        # ---
        # Store previous OpenGL settings.
        # Store MatrixMode
        MatrixMode_prev = bgl.Buffer(bgl.GL_INT, [1])
        bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, MatrixMode_prev)
        MatrixMode_prev = MatrixMode_prev[0]

        # Store projection matrix
        ProjMatrix_prev = bgl.Buffer(bgl.GL_DOUBLE, [16])
        bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, ProjMatrix_prev)

        # Store Line width
        lineWidth_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, lineWidth_prev)
        lineWidth_prev = lineWidth_prev[0]

        # Store GL_BLEND
        blend_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_BLEND, blend_prev)
        blend_prev = blend_prev[0]

        line_stipple_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_LINE_STIPPLE, line_stipple_prev)
        line_stipple_prev = line_stipple_prev[0]

        # Store glColor4f
        color_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
        bgl.glGetFloatv(bgl.GL_COLOR, color_prev)

        # ---
        # Prepare for 3D drawing
        bgl.glLoadIdentity()
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadMatrixf(perspBuff)

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_LINE_STIPPLE)

        # ---
        # Draw 3D stuff.
        width = 1
        bgl.glLineWidth(width)
        # X
        bgl.glColor4f(1, 0, 0, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p2[0], p1[1], p1[2])
        bgl.glEnd()
        # Y
        bgl.glColor4f(0, 1, 0, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p1[0], p2[1], p1[2])
        bgl.glEnd()
        # Z
        bgl.glColor4f(0, 0, 1, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p1[0], p1[1], p2[2])
        bgl.glEnd()

        # Dist
        width = 2
        bgl.glLineWidth(width)
        bgl.glColor4f(color[0], color[1], color[2], color[3])
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(p1[0], p1[1], p1[2])
        bgl.glVertex3f(p2[0], p2[1], p2[2])
        bgl.glEnd()

        # ---
        # Restore previous OpenGL settings
        bgl.glLoadIdentity()
        bgl.glMatrixMode(MatrixMode_prev)
        bgl.glLoadMatrixf(ProjMatrix_prev)
        bgl.glLineWidth(lineWidth_prev)
        if not blend_prev:
            bgl.glDisable(bgl.GL_BLEND)
        if not line_stipple_prev:
            bgl.glDisable(bgl.GL_LINE_STIPPLE)
        bgl.glColor4f(color_prev[0], color_prev[1], color_prev[2],
                      color_prev[3])

        # ---
        # Draw (2D) text
        # We do this after drawing the lines so
        # we can draw it OVER the line.
        coord_2d = location_3d_to_region_2d(
            context.region,
            context.space_data.region_3d,
            p1.lerp(p2, 0.5),
        )
        OFFSET_LINE = 10  # Offset the text a bit to the right.
        OFFSET_Y = 15  # Offset of the lines.
        OFFSET_VALUE = 30  # Offset of value(s) from the text.
        dist = (p1 - p2).length

        # Write distance value into the scene property,
        # so we can display it in the panel & refresh the panel.
        if hasattr(sce, "measure_panel_dist"):
            sce.measure_panel_dist = dist
            context.area.tag_redraw()

        texts = [("Dist:", round(dist, PRECISION)),
                 ("X:", round(abs(p1[0] - p2[0]), PRECISION)),
                 ("Y:", round(abs(p1[1] - p2[1]), PRECISION)),
                 ("Z:", round(abs(p1[2] - p2[2]), PRECISION))]

        # Draw all texts
        # @todo Get user pref for text color in 3D View
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        blf.size(0, 12, 72)  # Prevent font size to randomly change.

        loc_x = coord_2d[0] + OFFSET_LINE
        loc_y = coord_2d[1]
        for t in texts:
            text = t[0]
            value = str(t[1]) + " BU"

            blf.position(0, loc_x, loc_y, 0)
            blf.draw(0, text)
            blf.position(0, loc_x + OFFSET_VALUE, loc_y, 0)
            blf.draw(0, value)

            loc_y -= OFFSET_Y

    # Handle mesh surface area calulations
    if (sce.measure_panel_calc_area):
        # Get a single selected object (or nothing).
        obj = getSingleObject(context)

        if (context.mode == 'EDIT_MESH'):
            obj = context.active_object

            if (obj and obj.type == 'MESH' and obj.data):
                # "Note: a Mesh will return the selection state of the mesh
                # when EditMode was last exited. A Python script operating
                # in EditMode must exit EditMode before getting the current
                # selection state of the mesh."
                # http://www.blender.org/documentation/249PythonDoc/
                # /Mesh.MVert-class.html#sel
                # We can only provide this by existing & re-entering EditMode.
                # @todo: Better way to do this?

                # Get mesh data from Object.
                mesh = obj.data

                # Get transformation matrix from object.
                ob_mat = obj.matrix_world
                # Also make an inversed copy! of the matrix.
                ob_mat_inv = ob_mat.copy()
                Matrix.invert(ob_mat_inv)

                # Get the selected vertices.
                # @todo: Better (more efficient) way to do this?
                verts_selected = [v for v in mesh.vertices if v.select == 1]

                if len(verts_selected) >= 3:
                    # Get selected faces
                    # @todo: Better (more efficient) way to do this?
                    faces_selected = [f for f in mesh.faces if f.select == 1]

                    if len(faces_selected) > 0:
                        area, normal = objectSurfaceArea(
                            obj, True, measureGlobal(sce))
                        if (area >= 0):
                            sce.measure_panel_area1 = area
                            sce.measure_panel_normal1 = normal

        elif (context.mode == 'OBJECT'):
            # We are working in object mode.

            if len(context.selected_objects) > 2:
                return


# @todo Make this work again.
#                # We have more that 2 objects selected...
#
#                mesh_objects = [o for o in context.selected_objects
#                    if (o.type == 'MESH')]

#                if (len(mesh_objects) > 0):
#                    # ... and at least one of them is a mesh.
#
#                    for o in mesh_objects:
#                        area = objectSurfaceArea(o, False,
#                            measureGlobal(sce))
#                        if (area >= 0):
#                            #row.label(text=o.name, icon='OBJECT_DATA')
#                            #row.label(text=str(round(area, PRECISION))
#                            #    + " BU^2")

            elif len(context.selected_objects) == 2:
                # 2 objects selected.

                obj1, obj2 = context.selected_objects

                # Calculate surface area of the objects.
                area1, normal1 = objectSurfaceArea(obj1, False,
                                                   measureGlobal(sce))
                area2, normal2 = objectSurfaceArea(obj2, False,
                                                   measureGlobal(sce))
                sce.measure_panel_area1 = area1
                sce.measure_panel_area2 = area2
                sce.measure_panel_normal1 = normal1
                sce.measure_panel_normal2 = normal2

            elif (obj):
                # One object selected.

                # Calculate surface area of the object.
                area, normal = objectSurfaceArea(obj, False,
                                                 measureGlobal(sce))

                sce.measure_panel_area1 = area
                sce.measure_panel_normal1 = normal

    if (sce.measure_panel_calc_volume):
        obj = getSingleObject(context)

        if (context.mode == 'OBJECT'):
            # We are working in object mode.

            #if len(context.selected_objects) > 2:       # TODO

            #el
            if len(context.selected_objects) == 2:
                # 2 objects selected.

                obj1, obj2 = context.selected_objects

                # Calculate surface area of the objects.
                volume1 = objectVolume(obj1, measureGlobal(sce))
                volume2 = objectVolume(obj2, measureGlobal(sce))

                sce.measure_panel_volume1 = volume1
                sce.measure_panel_volume2 = volume2

            elif (obj):
                # One object selected.

                # Calculate surface area of the object.
                volume1 = objectVolume(obj, measureGlobal(sce))

                sce.measure_panel_volume1 = volume1
Exemple #12
0
def draw_stuff():
    # print("draw_stuff")
    # FIXME this should use glPushAttrib
    from bgl import glColor3f, glVertex3f, glBegin, glEnd, GL_POLYGON, GL_LINES
    global draw_stuff_dirty, draw_stuff_objects
    ctx = bpy.context
    if not len(ctx.selected_objects) and not ctx.object:
        return
    if not bpy.context.window_manager.thug_show_face_collision_colors:
        return

    VERT_FLAG = FACE_FLAGS["mFD_VERT"]
    WALLRIDABLE_FLAG = FACE_FLAGS["mFD_WALL_RIDABLE"]
    TRIGGER_FLAG = FACE_FLAGS["mFD_TRIGGER"]
    NON_COLLIDABLE_FLAG = FACE_FLAGS["mFD_NON_COLLIDABLE"]

    bgl.glPushAttrib(bgl.GL_ALL_ATTRIB_BITS)
    try:
        _tmp_buf = bgl.Buffer(bgl.GL_FLOAT, 1)
        bgl.glGetFloatv(bgl.GL_POLYGON_OFFSET_FACTOR, _tmp_buf)
        old_offset_factor = _tmp_buf[0]
        bgl.glGetFloatv(bgl.GL_POLYGON_OFFSET_UNITS, _tmp_buf)
        old_offset_units = _tmp_buf[0]
        del _tmp_buf

        objects = set([ob.name for ob in ctx.selected_objects] if ctx.mode == "OBJECT" else [ctx.object.name])
        if draw_stuff_objects != objects:
            draw_stuff_dirty = True
        # print("draw_stuff2")

        if not draw_stuff_dirty:
            bgl.glCallList(draw_stuff_display_list_id)
            bgl.glPolygonOffset(old_offset_factor, old_offset_units)
            bgl.glDisable(bgl.GL_POLYGON_OFFSET_FILL)
            bgl.glDisable(bgl.GL_CULL_FACE)
            return

        bm = None
        bgl.glNewList(draw_stuff_display_list_id, bgl.GL_COMPILE_AND_EXECUTE)
        try:
            bgl.glCullFace(bgl.GL_BACK)
            bgl.glEnable(bgl.GL_CULL_FACE)
            bgl.glEnable(bgl.GL_POLYGON_OFFSET_FILL)
            #bgl.glEnable(bgl.GL_POLYGON_OFFSET_LINE)
            bgl.glPolygonOffset(-2, -2)

            bgl.glEnable(bgl.GL_BLEND)
            bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA);

            prefs = ctx.user_preferences.addons[ADDON_NAME].preferences

            bgl.glLineWidth(prefs.line_width)

            draw_stuff_objects = objects
            bdobs = {ob.name: ob for ob in bpy.data.objects}
            for ob in objects:
                ob = bdobs[ob]
                if not bm: bm = bmesh.new()
                if (ob and
                        ob.type == "CURVE" and
                        ob.data.splines and
                        ob.data.splines[-1].points and
                        ob.thug_path_type == "Rail" and
                        ob.thug_rail_connects_to):
                    connects_to = bdobs[ob.thug_rail_connects_to]
                    if (connects_to and
                            connects_to.type == "CURVE" and
                            connects_to.data.splines and
                            connects_to.data.splines[0].points):
                        glBegin(GL_LINES)
                        bgl.glColor4f(*prefs.rail_end_connection_color)
                        v = ob.matrix_world * ob.data.splines[-1].points[-1].co.to_3d()
                        glVertex3f(v[0], v[1], v[2])
                        v = connects_to.matrix_world * connects_to.data.splines[0].points[0].co.to_3d()
                        glVertex3f(v[0], v[1], v[2])
                        glEnd()

                # Draw previews for area lights - tube/sphere lights and area lights
                if (ob and ob.type == 'LAMP'):
                    if ob.data.thug_light_props.light_type == 'TUBE':
                        if ob.data.thug_light_props.light_end_pos != (0, 0, 0):
                            glBegin(GL_LINES)
                            bgl.glColor4f(1.0, 0.75, 0.25, 1.0)
                            glVertex3f(ob.location[0], ob.location[1], ob.location[2])
                            glVertex3f(ob.location[0] + ob.data.thug_light_props.light_end_pos[0], ob.location[1] + ob.data.thug_light_props.light_end_pos[1], ob.location[2] + ob.data.thug_light_props.light_end_pos[2])
                            glEnd()
                        continue
                    elif ob.data.thug_light_props.light_type == 'SPHERE':
                        continue
                    elif ob.data.thug_light_props.light_type == 'AREA':
                        continue
                    else:
                        continue
                elif (ob and ob.type == 'EMPTY'):
                    if ob.thug_empty_props.empty_type == 'LightVolume' or ob.thug_empty_props.empty_type == 'CubemapProbe':
                        # Draw light volume bbox!
                        bbox, bbox_min, bbox_max, bbox_mid = get_bbox_from_node(ob)
                        
                        # 50% alpha, 2 pixel width line
                        bgl.glEnable(bgl.GL_BLEND)
                        bgl.glColor4f(1.0, 0.0, 0.0, 0.5)
                        bgl.glLineWidth(4)
                        
                        glBegin(bgl.GL_LINE_STRIP)
                        bgl.glVertex3f(*bbox[0])
                        bgl.glVertex3f(*bbox[1])
                        bgl.glVertex3f(*bbox[2])
                        bgl.glVertex3f(*bbox[3])
                        bgl.glVertex3f(*bbox[0])
                        bgl.glVertex3f(*bbox[4])
                        bgl.glVertex3f(*bbox[5])
                        bgl.glVertex3f(*bbox[6])
                        bgl.glVertex3f(*bbox[7])
                        bgl.glVertex3f(*bbox[4])
                        bgl.glEnd()

                        bgl.glBegin(bgl.GL_LINES)
                        bgl.glVertex3f(*bbox[1])
                        bgl.glVertex3f(*bbox[5])
                        bgl.glVertex3f(*bbox[2])
                        bgl.glVertex3f(*bbox[6])
                        bgl.glVertex3f(*bbox[3])
                        bgl.glVertex3f(*bbox[7])
                        glEnd()
                        
                if not ob or ob.type != "MESH":
                    continue

                if ob.mode == "EDIT":
                    bm.free()
                    bm = bmesh.from_edit_mesh(ob.data).copy()
                else:
                    bm.clear()
                    if ob.modifiers:
                        final_mesh = ob.to_mesh(bpy.context.scene, True, "PREVIEW")
                        try:
                            bm.from_mesh(final_mesh)
                        finally:
                            bpy.data.meshes.remove(final_mesh)
                    else:
                        bm.from_mesh(ob.data)

                arl = bm.edges.layers.int.get("thug_autorail")
                if arl:
                    bgl.glColor4f(*prefs.autorail_edge_color)
                    glBegin(GL_LINES)
                    for edge in bm.edges:
                        if edge[arl] == AUTORAIL_NONE:
                            continue

                        for vert in edge.verts:
                            v = ob.matrix_world * vert.co
                            glVertex3f(v[0], v[1], v[2])
                    glEnd()

                cfl = bm.faces.layers.int.get("collision_flags")
                flag_stuff = ((VERT_FLAG, prefs.vert_face_color),
                              (WALLRIDABLE_FLAG, prefs.wallridable_face_color),
                              (TRIGGER_FLAG, prefs.trigger_face_color),
                              (NON_COLLIDABLE_FLAG, prefs.non_collidable_face_color))
                if cfl:
                    bmesh.ops.triangulate(bm, faces=bm.faces)

                    for face in bm.faces:
                        drawn_face = False
                        if prefs.show_bad_face_colors:
                            if (face[cfl] & (VERT_FLAG | WALLRIDABLE_FLAG | NON_COLLIDABLE_FLAG) not in
                                (VERT_FLAG, WALLRIDABLE_FLAG, NON_COLLIDABLE_FLAG, 0)):
                                bgl.glColor4f(*prefs.bad_face_color)
                                glBegin(GL_POLYGON)
                                for vert in face.verts:
                                    v = ob.matrix_world * vert.co
                                    glVertex3f(v[0], v[1], v[2])
                                glEnd()
                                continue

                        for face_flag, face_color in flag_stuff:
                            if face[cfl] & face_flag and (not drawn_face or prefs.mix_face_colors):
                                bgl.glColor4f(*face_color)
                                drawn_face = True

                                glBegin(GL_POLYGON)
                                for vert in face.verts:
                                    v = ob.matrix_world * vert.co
                                    glVertex3f(v[0], v[1], v[2])
                                glEnd()
        finally:
            draw_stuff_dirty = False
            bgl.glEndList()
            if bm: bm.free()
            bgl.glPolygonOffset(old_offset_factor, old_offset_units)
            bgl.glDisable(bgl.GL_POLYGON_OFFSET_FILL)
    finally:
        bgl.glPopAttrib()
def draw_sunpath_callback(self, context):
    def drawLine(points, loop=False, color=(0.1, 0.4, 0.8, 0.8), thickness=2):
        bgl.glLineWidth(thickness)
        bgl.glBlendColor(color[0], color[1], color[2], color[3])
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for p in points:
            bgl.glVertex3f(p[0], p[1], p[2])
        if loop:
            p = points[0]
            bgl.glVertex3f(p[0], p[1], p[2])
        bgl.glEnd()
        return points

    def dayPoints(Month, Day):
        sc = bpy.context.scene
        N = sc.Site.northAxis
        Long = sc.Site.longitude
        Lat = sc.Site.latitude
        TimeZone = sc.Site.timezone
        dt = 4  # timesteps per hour
        coords = [(0.0, 0.0, 0.0)] * (24 * dt)
        i = 0
        for Hour in range(24):
            for T in range(dt):
                Minute = T * (60 / dt)
                (Az, El) = Solar_Pos(Long, Lat, TimeZone, Month, Day, Hour,
                                     Minute)
                if sc.ODS_SUN.sunpath.flat:
                    if sc.ODS_SUN.sunpath.equi:
                        coords[i] = azElToPolar(radians(Az) + N, radians(El))
                    else:
                        coords[i] = azElToXYZ(radians(Az) + N, radians(El))
                        coords[i][2] = 0.0
                else:
                    coords[i] = azElToXYZ(radians(Az) + N, radians(El))
                # Finally shift the coordinate to the offset centre
                for j in range(3):
                    coords[i][j] += sc.ODS_SUN.sunpath.pos[j]
                i += 1
        return coords

    def drawCompassRose(color=(0.8, 0.8, 0.8, 1.0)):
        def tick(ang, f):
            X = sin(ang)
            Y = cos(ang)
            return [(R * X + O[0], R * Y + O[1], O[2]),
                    (R * f * X + O[0], R * f * Y + O[1], O[2])]

        sc = bpy.context.scene
        R = sc.ODS_SUN.arcRadius
        N = sc.Site.northAxis
        O = sc.ODS_SUN.sunpath.pos
        T = [N + (i * 2 * pi / 360) for i in range(360)]
        # Draw inner concentric circles
        if sc.ODS_SUN.sunpath.circles:
            for i in range(1, 9):
                if sc.ODS_SUN.sunpath.flat and sc.ODS_SUN.sunpath.equi:
                    r = (i * R / 9)
                else:
                    r = R * sin((pi / 2) * (i / 9))
                P = [(r * sin(t) + O[0], r * cos(t) + O[1], O[2]) for t in T]
                drawLine(P, loop=True, color=color, thickness=0.7)
        # Draw the thick outer circle (90 degrees)
        P = [(R * sin(t) + O[0], R * cos(t) + O[1], O[2]) for t in T]
        drawLine(P, loop=True, color=color)
        # Draw the ticks
        drawLine(tick(N, 1.2), color=color)
        for i in range(8):
            T = N + (i * 2 * pi / 8)
            drawLine(tick(T, 1.1), color=color)
        for i in range(36):
            T = N + (i * 2 * pi / 36)
            drawLine(tick(T, 1.05), color=color)
        return

    def calcSunPath():
        datum = datetime.datetime(2010, 1, 1)
        for day in range(365):
            t = datum + datetime.timedelta(day)
            dp = dayPoints(t.month, t.day)
            points[day] = dp
            if t.day == 1:
                daylines[t.month - 1] = dp
        for i in range(0, 24):
            loops[i] = [points[day][i * 4] for day in range(365)]
        return None

    def getTextLocation():
        context = bpy.context
        scene = bpy.context.scene
        X = 62
        Y = 4
        pos_x = int((context.region.width) - X)
        pos_y = int(Y)  #(context.region.height)
        return (pos_x, pos_y)

    def drawTime():
        font_size = 20
        (r, g, b, alpha) = (1.0, 1.0, 1.0, 1.0)
        blf.size(0, font_size, 72)
        (pos_x, pos_y) = getTextLocation()
        blf.position(0, pos_x, pos_y, 0)
        bgl.glBlendColor(r, g, b, alpha)
        (hour, minute) = frameToTime(bpy.context.scene.frame_current)
        if hour >= 24:
            minute = 0
        blf.draw(0, "%02i:%02i" % (min(hour, 24), minute))
        return None

    def drawSunPath():
        for line in daylines:
            drawLine(line)
        for line in loops:
            drawLine(line, loop=True, color=(1.0, 0.8, 0.0, 1.0))
        drawCompassRose()
        return None

    # Draw the time
    if bpy.context.scene.ODS_SUN.sunpath.time:
        drawTime()

    if not bpy.context.scene.ODS_SUN.sunpath.path:
        return None

    # Get & convert the Perspective Matrix of the current view/region.
    #bgl.glClear(bgl.GL_COLOR_BUFFER_BIT)
    view3d = bpy.context
    region = view3d.region_data
    perspMatrix = region.perspective_matrix
    tempMat = [perspMatrix[j][i] for i in range(4) for j in range(4)]
    perspBuff = bgl.Buffer(bgl.GL_FLOAT, 16, tempMat)

    # ---
    # Store previous OpenGL settings.
    # Store MatrixMode
    MatrixMode_prev = bgl.Buffer(bgl.GL_INT, [1])
    bgl.glGetIntegerv(2976, MatrixMode_prev)  # bgl.GL_MATRIX_MODE
    MatrixMode_prev = MatrixMode_prev[0]

    # Store projection matrix
    ProjMatrix_prev = bgl.Buffer(bgl.GL_DOUBLE, [16])
    bgl.glGetFloatv(2983, ProjMatrix_prev)  # bgl.GL_PROJECTION_MATRIX

    # Store Line width
    lineWidth_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
    bgl.glGetFloatv(bgl.GL_LINE_WIDTH, lineWidth_prev)
    lineWidth_prev = lineWidth_prev[0]

    # Store GL_BLEND
    blend_prev = bgl.Buffer(bgl.GL_BYTE, [1])
    bgl.glGetFloatv(bgl.GL_BLEND, blend_prev)
    blend_prev = blend_prev[0]

    line_stipple_prev = bgl.Buffer(bgl.GL_BYTE, [1])
    bgl.glGetFloatv(2852, line_stipple_prev)  # bgl.GL_LINE_STIPPLE
    line_stipple_prev = line_stipple_prev[0]

    # Store glColor4f
    color_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
    bgl.glGetFloatv(bgl.GL_COLOR, color_prev)

    # ---
    # Prepare for 3D drawing
    bgl.glLoadIdentity()
    bgl.glMatrixMode(5889)  # bgl.GL_PROJECTION
    bgl.glLoadMatrixf(perspBuff)

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    #bgl.glEnable(bgl.GL_LINE_STIPPLE)
    if not bpy.context.scene.ODS_SUN.sunpath.xray:
        bgl.glEnable(bgl.GL_DEPTH_TEST)

    # Draw the day sunpath lines
    if bpy.context.scene.ODS_SUN.sunpath.recalc:
        calcSunPath()
        drawSunPath()
        bpy.context.scene.ODS_SUN.sunpath.recalc = False
    else:
        drawSunPath()

    # ---
    # Restore previous OpenGL settings
    if not bpy.context.scene.ODS_SUN.sunpath.xray:
        bgl.glDisable(bgl.GL_DEPTH_TEST)
    bgl.glLoadIdentity()
    bgl.glMatrixMode(MatrixMode_prev)
    bgl.glLoadMatrixf(ProjMatrix_prev)
    bgl.glLineWidth(lineWidth_prev)
    if not blend_prev:
        bgl.glDisable(bgl.GL_BLEND)
    if not line_stipple_prev:
        bgl.glDisable(2852)  # bgl.GL_LINE_STIPPLE
    bgl.glBlendColor(color_prev[0], color_prev[1], color_prev[2],
                     color_prev[3])

    return None
    def draw(self, area, region_data):
        """
        Draw avatar view in given context
        """
        # TODO: Add this color to addon option
        color = (1.0, 1.0, 0.5, 1.0)
        alpha = 2.0*math.atan((18.0/2.0)/self.lens.value[0])
        dist = 0.5/(math.tan(alpha/2.0))
        height = 1.0
        if self.height.value[0] == 0:
            width = 0.7
        else:
            width = self.width.value[0]/self.height.value[0]
                    
        points = {}
        points['border'] = [None, None, None, None]
        points['center'] = [None]
        
        # Points of face
        points['right_eye'] = [mathutils.Vector((0.25, 0.25, self.distance.value[0] - dist)), \
            mathutils.Vector((0.3, 0.25, self.distance.value[0] - dist)), \
            mathutils.Vector((0.3, 0.0, self.distance.value[0] - dist)), \
            mathutils.Vector((0.25, 0.0, self.distance.value[0] - dist)), \
            mathutils.Vector((0.25, 0.25, self.distance.value[0] - dist))]
        points['left_eye'] = [mathutils.Vector((-0.25, 0.25, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.3, 0.25, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.3, 0.0, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.25, 0.0, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.25, 0.25, self.distance.value[0] - dist))]
        
        points['mouth'] = [mathutils.Vector((-0.40912365913391113, -0.11777058243751526, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.3441678285598755, -0.15873458981513977, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.2563667893409729, -0.1998385488986969, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.18191590905189514, -0.22385218739509583, self.distance.value[0] - dist)), \
            mathutils.Vector((-0.10375960171222687, -0.23957833647727966, self.distance.value[0] - dist)), \
            mathutils.Vector((0.0, -0.2464955747127533, self.distance.value[0] - dist)), \
            mathutils.Vector((0.10375960171222687, -0.23957833647727966, self.distance.value[0] - dist)), \
            mathutils.Vector((0.18191590905189514, -0.22385218739509583, self.distance.value[0] - dist)), \
            mathutils.Vector((0.2563667893409729, -0.1998385488986969, self.distance.value[0] - dist)), \
            mathutils.Vector((0.3441678285598755, -0.15873458981513977, self.distance.value[0] - dist)), \
            mathutils.Vector((0.40912365913391113, -0.11777058243751526, self.distance.value[0] - dist))]            
                
        # Put border points of camera to basic position
        points['border'][0] = mathutils.Vector((-width/2.0, \
            -0.5, \
            self.distance.value[0] - dist,
            1.0))
        points['border'][1] = mathutils.Vector((width/2.0, \
            -0.5, \
            self.distance.value[0] - dist,
            1.0))
        points['border'][2] = mathutils.Vector((width/2.0, \
            0.5, \
            self.distance.value[0] - dist, \
            1.0))
        points['border'][3] = mathutils.Vector((-width/2.0, \
            0.5, \
            self.distance.value[0] - dist, \
            1.0))
        
        # Center of view
        points['center'][0] = mathutils.Vector((0.0, \
            0.0, \
            self.distance.value[0], \
            1.0))        
        
        # Create transformation (rotation) matrix
        rot_matrix = mathutils.Quaternion(self.rotation.value).to_matrix().to_4x4()
        
        # Transform points in all point groups
        for point_group in points.values():
            for index in range(len(point_group)):
                # Rotate points
                point_group[index] = (rot_matrix*point_group[index]).to_3d()
                # Move points
                point_group[index] += mathutils.Vector(self.location.value)
        
        # Get & convert the Perspective Matrix of the current view/region.
        perspMatrix = region_data.perspective_matrix
        tempMat = [perspMatrix[j][i] for i in range(4) for j in range(4)]
        perspBuff = bgl.Buffer(bgl.GL_FLOAT, 16, tempMat)
    
        # Store previous OpenGL settings.
        # Store MatrixMode
        MatrixMode_prev = bgl.Buffer(bgl.GL_INT, [1])
        bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, MatrixMode_prev)
        MatrixMode_prev = MatrixMode_prev[0]
    
        # Store projection matrix
        ProjMatrix_prev = bgl.Buffer(bgl.GL_DOUBLE, [16])
        bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, ProjMatrix_prev)
    
        # Store Line width
        lineWidth_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, lineWidth_prev)
        lineWidth_prev = lineWidth_prev[0]
    
        # Store GL_BLEND
        blend_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_BLEND, blend_prev)
        blend_prev = blend_prev[0]
        
        # Store GL_DEPTH_TEST
        depth_test_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_DEPTH_TEST, depth_test_prev)
        depth_test_prev = depth_test_prev[0]
            
        # Store GL_LINE_STIPPLE
        line_stipple_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_LINE_STIPPLE, line_stipple_prev)
        line_stipple_prev = line_stipple_prev[0]
    
        # Store glColor4f
        col_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
        bgl.glGetFloatv(bgl.GL_COLOR, col_prev)
        
        # Prepare for 3D drawing
        bgl.glLoadIdentity()
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadMatrixf(perspBuff)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_DEPTH_TEST)
                
        # Draw "Look At" point
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINES)
        bgl.glColor4f(color[0], color[1], color[2], color[3])
        
        bgl.glVertex3f(self.location.value[0]+0.1, \
            self.location.value[1], \
            self.location.value[2])
        bgl.glVertex3f(self.location.value[0]-0.1, \
            self.location.value[1], \
            self.location.value[2])
        
        bgl.glVertex3f(self.location.value[0], \
            self.location.value[1]+0.1, \
            self.location.value[2])
        bgl.glVertex3f(self.location.value[0], \
            self.location.value[1]-0.1, \
            self.location.value[2])
        
        bgl.glVertex3f(self.location.value[0], \
            self.location.value[1], \
            self.location.value[2]+0.1)
        bgl.glVertex3f(self.location.value[0], \
            self.location.value[1], \
            self.location.value[2]-0.1)
        
        bgl.glEnd()
        
        border = points['border']
        center = points['center']
        
        # Draw border of camera
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(border[0][0], border[0][1], border[0][2])
        bgl.glVertex3f(border[1][0], border[1][1], border[1][2])
        bgl.glVertex3f(border[2][0], border[2][1], border[2][2])
        bgl.glVertex3f(border[3][0], border[3][1], border[3][2])
        bgl.glVertex3f(border[0][0], border[0][1], border[0][2])
        bgl.glEnd()
        
        # Draw left eye
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for point in points['left_eye']:
            bgl.glVertex3f(point[0], point[1], point[2])
        bgl.glEnd()

        # Draw right eye
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for point in points['right_eye']:
            bgl.glVertex3f(point[0], point[1], point[2])
        bgl.glEnd()
        
        # Draw mouth
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for point in points['mouth']:
            bgl.glVertex3f(point[0], point[1], point[2])
        bgl.glEnd()
        
        # Draw dashed lines from center of "camera" to border of camera        
        bgl.glEnable(bgl.GL_LINE_STIPPLE)
        bgl.glBegin(bgl.GL_LINES)
        bgl.glVertex3f(border[0][0], border[0][1], border[0][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glVertex3f(border[1][0], border[1][1], border[1][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glVertex3f(border[2][0], border[2][1], border[2][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glVertex3f(border[3][0], border[3][1], border[3][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glEnd()
        
        # Draw dashed line from Look At point and center of camera
        bgl.glBegin(bgl.GL_LINES)
        bgl.glVertex3f(self.location.value[0], \
            self.location.value[1], \
            self.location.value[2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glEnd()
        bgl.glDisable(bgl.GL_LINE_STIPPLE)    

        # Restore previous OpenGL settings
        bgl.glLoadIdentity()
        bgl.glMatrixMode(MatrixMode_prev)
        bgl.glLoadMatrixf(ProjMatrix_prev)
        bgl.glLineWidth(lineWidth_prev)
        if not blend_prev:
            bgl.glDisable(bgl.GL_BLEND)
        if not line_stipple_prev:
            bgl.glDisable(bgl.GL_LINE_STIPPLE)
        if not depth_test_prev:
            bgl.glDisable(bgl.GL_DEPTH_TEST)

        # Draw username
        coord_2d = location_3d_to_region_2d(
            area.regions[4],
            region_data,
            center[0])
        font_id, font_size, my_dpi = 0, 12, 72 # TODO: add to addon options
        blf.size(font_id, font_size, my_dpi)
        text_width, text_height = blf.dimensions(font_id, self.username)
        blf.position(font_id, coord_2d[0], coord_2d[1], 0)
        blf.draw(font_id, self.username)

        bgl.glColor4f(col_prev[0], col_prev[1], col_prev[2], col_prev[3])
 def _get(self, instance, owner):
     glGetFloatv(GL_BLEND_COLOR, float4buf0)
     return Vector(float4buf0)
Exemple #16
0
def DrawNorth_callback(self, context):

    if not Sun.SP.ShowNorth and North.isActive:
        North.deactivate()
        return

    # ------------------------------------------------------------------
    # Set up the compass needle using the current north offset angle
    # less 90 degrees.  This forces the unit circle to begin at the
    # 12 O'clock instead of 3 O'clock position.
    # ------------------------------------------------------------------
    color = (0.2, 0.6, 1.0, 0.7)
    radius = 100
    angle = -(Sun.NorthOffset - math.pi / 2)
    x = math.cos(angle) * radius
    y = math.sin(angle) * radius

    p1, p2 = (0, 0, 0), (x, y, 0)   # Start & end of needle

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Thanks to Buerbaum Martin for the following which draws openGL
    # lines.  ( From his script space_view3d_panel_measure.py )
    #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    # ------------------------------------------------------------------
    # Convert the Perspective Matrix of the current view/region.
    # ------------------------------------------------------------------
    view3d = bpy.context
    region = view3d.region_data
    perspMatrix = region.perspective_matrix
    tempMat = [perspMatrix[j][i] for i in range(4) for j in range(4)]
    perspBuff = bgl.Buffer(bgl.GL_FLOAT, 16, tempMat)

    # ---------------------------------------------------------
    # Store previous OpenGL settings.
    # ---------------------------------------------------------
    MatrixMode_prev = bgl.Buffer(bgl.GL_INT, [1])
    bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, MatrixMode_prev)
    MatrixMode_prev = MatrixMode_prev[0]

    # Store projection matrix
    ProjMatrix_prev = bgl.Buffer(bgl.GL_DOUBLE, [16])
    bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, ProjMatrix_prev)

    # Store Line width
    lineWidth_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
    bgl.glGetFloatv(bgl.GL_LINE_WIDTH, lineWidth_prev)
    lineWidth_prev = lineWidth_prev[0]

    # Store GL_BLEND
    blend_prev = bgl.Buffer(bgl.GL_BYTE, [1])
    bgl.glGetFloatv(bgl.GL_BLEND, blend_prev)
    blend_prev = blend_prev[0]

    line_stipple_prev = bgl.Buffer(bgl.GL_BYTE, [1])
    bgl.glGetFloatv(bgl.GL_LINE_STIPPLE, line_stipple_prev)
    line_stipple_prev = line_stipple_prev[0]

    # Store glColor4f
    color_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
    bgl.glGetFloatv(bgl.GL_COLOR, color_prev)

    # ---------------------------------------------------------
    # Prepare for 3D drawing
    # ---------------------------------------------------------
    bgl.glLoadIdentity()
    bgl.glMatrixMode(bgl.GL_PROJECTION)
    bgl.glLoadMatrixf(perspBuff)

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINE_STIPPLE)

    # ------------------
    # and draw the line
    # ------------------
    width = 2
    bgl.glLineWidth(width)
    bgl.glColor4f(color[0], color[1], color[2], color[3])
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex3f(p1[0], p1[1], p1[2])
    bgl.glVertex3f(p2[0], p2[1], p2[2])
    bgl.glEnd()

    # ---------------------------------------------------------
    # Restore previous OpenGL settings
    # ---------------------------------------------------------
    bgl.glLoadIdentity()
    bgl.glMatrixMode(MatrixMode_prev)
    bgl.glLoadMatrixf(ProjMatrix_prev)
    bgl.glLineWidth(lineWidth_prev)

    if not blend_prev:
        bgl.glDisable(bgl.GL_BLEND)
    if not line_stipple_prev:
        bgl.glDisable(bgl.GL_LINE_STIPPLE)

    bgl.glColor4f(color_prev[0],
                  color_prev[1],
                  color_prev[2],
                  color_prev[3])
Exemple #17
0
    def draw(self, context):
        """
        Draw avatar view in given context
        """
        # TODO: Add this color to Add-on option
        color = (1.0, 1.0, 0.5, 1.0)
        alpha = 2.0 * math.atan((18.0 / 2.0) / self.lens.value[0])
        dist = 0.5 / (math.tan(alpha / 2.0))
        if self.height.value[0] == 0:
            width = 0.7
        else:
            width = self.width.value[0] / self.height.value[0]

        points = dict()
        points['border'] = [None, None, None, None]
        points['center'] = [None]

        # Points of face
        points['right_eye'] = [
            mathutils.Vector((0.25, 0.25, self.distance.value[0] - dist)),
            mathutils.Vector((0.3, 0.25, self.distance.value[0] - dist)),
            mathutils.Vector((0.3, 0.0, self.distance.value[0] - dist)),
            mathutils.Vector((0.25, 0.0, self.distance.value[0] - dist)),
            mathutils.Vector((0.25, 0.25, self.distance.value[0] - dist))
        ]
        points['left_eye'] = [
            mathutils.Vector((-0.25, 0.25, self.distance.value[0] - dist)),
            mathutils.Vector((-0.3, 0.25, self.distance.value[0] - dist)),
            mathutils.Vector((-0.3, 0.0, self.distance.value[0] - dist)),
            mathutils.Vector((-0.25, 0.0, self.distance.value[0] - dist)),
            mathutils.Vector((-0.25, 0.25, self.distance.value[0] - dist))
        ]

        points['mouth'] = [
            mathutils.Vector((-0.40912365913391113, -0.11777058243751526,
                              self.distance.value[0] - dist)),
            mathutils.Vector((-0.3441678285598755, -0.15873458981513977,
                              self.distance.value[0] - dist)),
            mathutils.Vector((-0.2563667893409729, -0.1998385488986969,
                              self.distance.value[0] - dist)),
            mathutils.Vector((-0.18191590905189514, -0.22385218739509583,
                              self.distance.value[0] - dist)),
            mathutils.Vector((-0.10375960171222687, -0.23957833647727966,
                              self.distance.value[0] - dist)),
            mathutils.Vector(
                (0.0, -0.2464955747127533, self.distance.value[0] - dist)),
            mathutils.Vector((0.10375960171222687, -0.23957833647727966,
                              self.distance.value[0] - dist)),
            mathutils.Vector((0.18191590905189514, -0.22385218739509583,
                              self.distance.value[0] - dist)),
            mathutils.Vector((0.2563667893409729, -0.1998385488986969,
                              self.distance.value[0] - dist)),
            mathutils.Vector((0.3441678285598755, -0.15873458981513977,
                              self.distance.value[0] - dist)),
            mathutils.Vector((0.40912365913391113, -0.11777058243751526,
                              self.distance.value[0] - dist))
        ]

        # Put border points of camera to basic position
        points['border'][0] = mathutils.Vector(
            (-width / 2.0, -0.5, self.distance.value[0] - dist, 1.0))
        points['border'][1] = mathutils.Vector(
            (width / 2.0, -0.5, self.distance.value[0] - dist, 1.0))
        points['border'][2] = mathutils.Vector(
            (width / 2.0, 0.5, self.distance.value[0] - dist, 1.0))
        points['border'][3] = mathutils.Vector(
            (-width / 2.0, 0.5, self.distance.value[0] - dist, 1.0))

        # Center of view
        points['center'][0] = mathutils.Vector(
            (0.0, 0.0, self.distance.value[0], 1.0))

        # Create transformation (rotation) matrix
        rot_matrix = mathutils.Quaternion(
            self.rotation.value).to_matrix().to_4x4()

        # Transform points in all point groups
        for point_group in points.values():
            for index in range(len(point_group)):
                # Rotate points
                point_group[index] = (rot_matrix * point_group[index]).to_3d()
                # Move points
                point_group[index] += mathutils.Vector(self.location.value)

        border = points['border']
        center = points['center']

        # Store glColor4f
        col_prev = bgl.Buffer(bgl.GL_FLOAT, [4])
        bgl.glGetFloatv(bgl.GL_COLOR, col_prev)

        bgl.glColor4f(color[0], color[1], color[2], color[3])

        # Draw username
        coord_2d = location_3d_to_region_2d(context.region,
                                            context.space_data.region_3d,
                                            center[0])

        # When coordinates are not outside window, then draw the name of avatar
        if coord_2d is not None:
            # TODO: add to Add-on options
            font_id, font_size, my_dpi = 0, 12, 72
            blf.size(font_id, font_size, my_dpi)
            blf.position(font_id, coord_2d[0] + 2, coord_2d[1] + 2, 0)
            blf.draw(font_id, str(self.username))

        # Get & convert the Perspective Matrix of the current view/region.
        persp_matrix = context.space_data.region_3d.perspective_matrix
        temp_mat = [persp_matrix[j][i] for i in range(4) for j in range(4)]
        persp_buff = bgl.Buffer(bgl.GL_FLOAT, 16, temp_mat)

        # Store previous OpenGL settings.
        # Store MatrixMode
        matrix_mode_prev = bgl.Buffer(bgl.GL_INT, [1])
        bgl.glGetIntegerv(bgl.GL_MATRIX_MODE, matrix_mode_prev)
        matrix_mode_prev = matrix_mode_prev[0]

        # Store projection matrix
        proj_matrix_prev = bgl.Buffer(bgl.GL_DOUBLE, [16])
        bgl.glGetFloatv(bgl.GL_PROJECTION_MATRIX, proj_matrix_prev)

        # Store Line width
        line_width_prev = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, line_width_prev)
        line_width_prev = line_width_prev[0]

        # Store GL_BLEND
        blend_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_BLEND, blend_prev)
        blend_prev = blend_prev[0]

        # Store GL_DEPTH_TEST
        depth_test_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_DEPTH_TEST, depth_test_prev)
        depth_test_prev = depth_test_prev[0]

        # Store GL_LINE_STIPPLE
        line_stipple_prev = bgl.Buffer(bgl.GL_BYTE, [1])
        bgl.glGetFloatv(bgl.GL_LINE_STIPPLE, line_stipple_prev)
        line_stipple_prev = line_stipple_prev[0]

        # Prepare for 3D drawing
        bgl.glLoadIdentity()
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glLoadMatrixf(persp_buff)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glEnable(bgl.GL_DEPTH_TEST)

        # Draw "Look At" point
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINES)
        bgl.glColor4f(color[0], color[1], color[2], color[3])

        bgl.glVertex3f(self.location.value[0] + 0.1, self.location.value[1],
                       self.location.value[2])
        bgl.glVertex3f(self.location.value[0] - 0.1, self.location.value[1],
                       self.location.value[2])

        bgl.glVertex3f(self.location.value[0], self.location.value[1] + 0.1,
                       self.location.value[2])
        bgl.glVertex3f(self.location.value[0], self.location.value[1] - 0.1,
                       self.location.value[2])

        bgl.glVertex3f(self.location.value[0], self.location.value[1],
                       self.location.value[2] + 0.1)
        bgl.glVertex3f(self.location.value[0], self.location.value[1],
                       self.location.value[2] - 0.1)

        bgl.glEnd()

        # Draw border of camera
        bgl.glBegin(bgl.GL_LINE_STRIP)
        bgl.glVertex3f(border[0][0], border[0][1], border[0][2])
        bgl.glVertex3f(border[1][0], border[1][1], border[1][2])
        bgl.glVertex3f(border[2][0], border[2][1], border[2][2])
        bgl.glVertex3f(border[3][0], border[3][1], border[3][2])
        bgl.glVertex3f(border[0][0], border[0][1], border[0][2])
        bgl.glEnd()

        # Draw left eye
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for point in points['left_eye']:
            bgl.glVertex3f(point[0], point[1], point[2])
        bgl.glEnd()

        # Draw right eye
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for point in points['right_eye']:
            bgl.glVertex3f(point[0], point[1], point[2])
        bgl.glEnd()

        # Draw mouth
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for point in points['mouth']:
            bgl.glVertex3f(point[0], point[1], point[2])
        bgl.glEnd()

        # Draw dashed lines from center of "camera" to border of camera
        bgl.glEnable(bgl.GL_LINE_STIPPLE)
        bgl.glBegin(bgl.GL_LINES)
        bgl.glVertex3f(border[0][0], border[0][1], border[0][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glVertex3f(border[1][0], border[1][1], border[1][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glVertex3f(border[2][0], border[2][1], border[2][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glVertex3f(border[3][0], border[3][1], border[3][2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glEnd()

        # Draw dashed line from Look At point and center of camera
        bgl.glBegin(bgl.GL_LINES)
        bgl.glVertex3f(self.location.value[0], self.location.value[1],
                       self.location.value[2])
        bgl.glVertex3f(center[0][0], center[0][1], center[0][2])
        bgl.glEnd()
        bgl.glDisable(bgl.GL_LINE_STIPPLE)

        # Restore previous OpenGL settings
        bgl.glLoadIdentity()
        bgl.glMatrixMode(matrix_mode_prev)
        bgl.glLoadMatrixf(proj_matrix_prev)
        bgl.glLineWidth(line_width_prev)
        if not blend_prev:
            bgl.glDisable(bgl.GL_BLEND)
        if not line_stipple_prev:
            bgl.glDisable(bgl.GL_LINE_STIPPLE)
        if not depth_test_prev:
            bgl.glDisable(bgl.GL_DEPTH_TEST)

        bgl.glColor4f(col_prev[0], col_prev[1], col_prev[2], col_prev[3])
 def _get(self, instance, owner):
     glGetFloatv(GL_LINE_WIDTH, float1buf0)
     return float1buf0[0]
Exemple #19
0
    def ondraw_postview(self, obj_arm, bone):
        # draw limits
        arm_xray = obj_arm.data.xray
        if version_utils.IS_28:
            hide_global = obj_arm.hide_viewport
            view_layer = bpy.context.view_layer
            hide_viewport = obj_arm.hide_get(view_layer=view_layer)
            hide = hide_global or hide_viewport
        else:
            hide = obj_arm.hide
        multiply = version_utils.get_multiply()

        prev_line_width = bgl.Buffer(bgl.GL_FLOAT, [1])
        bgl.glGetFloatv(bgl.GL_LINE_WIDTH, prev_line_width)
        bgl.glLineWidth(viewport.settings.LINE_WIDTH)

        bgl.glEnable(bgl.GL_BLEND)

        hide_bone = bone.hide
        hided = hide or hide_bone
        is_pose = obj_arm.mode == 'POSE'
        exportable = bone.xray.exportable
        draw_overlays = not hided and is_pose and exportable

        preferences = version_utils.get_preferences()
        # set color
        if is_pose:
            active_bone = bpy.context.active_bone
            color = None
            if active_bone:
                if active_bone.id_data == obj_arm.data:
                    if active_bone.name == bone.name:
                        color = preferences.gl_active_shape_color
            if color is None:
                if bone.select:
                    color = preferences.gl_select_shape_color
                else:
                    color = preferences.gl_shape_color
        else:
            color = preferences.gl_object_mode_shape_color

        if draw_overlays and arm_xray.display_bone_limits:
            context_obj = bpy.context.object
            if context_obj:
                is_active_object = context_obj.name == obj_arm.name
            else:
                is_active_object = False
            has_limits = bone.xray.ikjoint.type in {'2', '3', '5'}
            if bone.select and has_limits and is_active_object:
                draw_joint_limits = viewport.get_draw_joint_limits()

                if version_utils.IS_28:
                    gpu.matrix.push()
                else:
                    bgl.glPushMatrix()

                translate = obj_arm.pose.bones[bone.name].matrix.to_translation()
                mat_translate = mathutils.Matrix.Translation(translate)
                mat_rotate = obj_arm.data.bones[bone.name].matrix_local.to_euler().to_matrix().to_4x4()
                if bone.parent:
                    mat_rotate_parent = obj_arm.pose.bones[bone.parent.name].matrix_basis.to_euler().to_matrix().to_4x4()
                else:
                    mat_rotate_parent = mathutils.Matrix()

                mat = multiply(
                    obj_arm.matrix_world,
                    mat_translate,
                    multiply(mat_rotate, mat_rotate_parent),
                    mathutils.Matrix.Scale(-1, 4, (0, 0, 1))
                )
                if version_utils.IS_28:
                    gpu.matrix.multiply_matrix(mat)
                else:
                    bgl.glMultMatrixf(
                        viewport.gl_utils.matrix_to_buffer(mat.transposed())
                    )

                pose_bone = obj_arm.pose.bones[bone.name]
                if pose_bone.rotation_mode == 'QUATERNION':
                    rotate = pose_bone.rotation_quaternion.to_euler('XYZ')
                else:
                    rotate = obj_arm.pose.bones[bone.name].rotation_euler

                if arm_xray.joint_limits_type == 'IK':
                    limits = (
                        pose_bone.ik_min_x, pose_bone.ik_max_x,
                        pose_bone.ik_min_y, pose_bone.ik_max_y,
                        pose_bone.ik_min_z, pose_bone.ik_max_z
                    )
                else:
                    ik = bone.xray.ikjoint
                    limits = (
                        ik.lim_x_min, ik.lim_x_max,
                        ik.lim_y_min, ik.lim_y_max,
                        ik.lim_z_min, ik.lim_z_max
                    )

                is_joint = bone.xray.ikjoint.type == '2'
                is_wheel = bone.xray.ikjoint.type == '3'
                is_slider = bone.xray.ikjoint.type == '5'

                if arm_xray.display_bone_limit_x and (is_joint or is_wheel):
                    draw_joint_limits(
                        rotate.x, limits[0], limits[1], 'X',
                        arm_xray.display_bone_limits_radius
                    )

                if arm_xray.display_bone_limit_y and is_joint:
                    draw_joint_limits(
                        rotate.y, limits[2], limits[3], 'Y',
                        arm_xray.display_bone_limits_radius
                    )

                if arm_xray.display_bone_limit_z and is_joint:
                    draw_joint_limits(
                        rotate.z, limits[4], limits[5], 'Z',
                        arm_xray.display_bone_limits_radius
                    )

                # slider limits
                if arm_xray.display_bone_limit_z and is_slider:
                    draw_slider_rotation_limits = viewport.get_draw_slider_rotation_limits()
                    draw_slider_rotation_limits(
                        rotate.z, limits[2], limits[3],
                        arm_xray.display_bone_limits_radius
                    )
                    bone_matrix = obj_arm.data.bones[bone.name].matrix_local.to_4x4()
                    slider_mat = multiply(
                        obj_arm.matrix_world,
                        bone_matrix
                    )
                    if version_utils.IS_28:
                        gpu.matrix.pop()
                        gpu.matrix.push()
                        gpu.matrix.multiply_matrix(slider_mat)
                    else:
                        bgl.glPopMatrix()
                        bgl.glPushMatrix()
                        bgl.glMultMatrixf(
                            viewport.gl_utils.matrix_to_buffer(slider_mat.transposed())
                        )
                    draw_slider_slide_limits = viewport.get_draw_slider_slide_limits()
                    draw_slider_slide_limits(limits[0], limits[1], color)

                if version_utils.IS_28:
                    gpu.matrix.pop()
                else:
                    bgl.glPopMatrix()

        mat = multiply(
            obj_arm.matrix_world,
            obj_arm.pose.bones[bone.name].matrix,
            mathutils.Matrix.Scale(-1, 4, (0, 0, 1))
        )
        bmat = mat

        if not version_utils.IS_28:
            bgl.glColor4f(*color)

        shape = self.shape
        if shape.type == '0':
            bgl.glLineWidth(prev_line_width[0])
            return

        # draw mass centers
        is_edit = obj_arm.mode == 'EDIT'
        draw_mass = obj_arm.data.xray.display_bone_mass_centers
        if draw_mass and exportable and not hided and not is_edit:
            ctr = self.mass.center
            trn = multiply(
                bmat,
                mathutils.Vector((ctr[0], ctr[2], ctr[1]))
            )
            cross_size = obj_arm.data.xray.bone_mass_center_cross_size
            if version_utils.IS_28:
                gpu.matrix.push()
                gpu.matrix.translate(trn)
                viewport.draw_cross(cross_size, color=color)
                gpu.matrix.pop()
            else:
                bgl.glPopMatrix()
                bgl.glPushMatrix()
                bgl.glTranslatef(*trn)
                viewport.draw_cross(cross_size)
                bgl.glPopMatrix()

        # draw shapes
        draw_shapes = obj_arm.data.xray.display_bone_shapes
        if hided or not draw_shapes or not exportable or is_edit:
            bgl.glLineWidth(prev_line_width[0])
            return

        if version_utils.IS_28:
            if not obj_arm.name in bpy.context.view_layer.objects:
                bgl.glLineWidth(prev_line_width[0])
                return
        else:
            if not obj_arm.name in bpy.context.scene.objects:
                bgl.glLineWidth(prev_line_width[0])
                return
            visible_armature_object = False
            for layer_index, layer in enumerate(obj_arm.layers):
                scene_layer = bpy.context.scene.layers[layer_index]
                if scene_layer and layer:
                    visible_armature_object = True
                    break

            if not visible_armature_object:
                bgl.glLineWidth(prev_line_width[0])
                return

        if version_utils.IS_28:
            gpu.matrix.push()
            try:
                mat = multiply(mat, shape.get_matrix_basis())
                gpu.matrix.multiply_matrix(mat)
                if shape.type == '1':  # box
                    viewport.draw_cube(*shape.box_hsz, color=color)
                if shape.type == '2':  # sphere
                    viewport.draw_sphere(
                        shape.sph_rad,
                        viewport.settings.BONE_SHAPE_SPHERE_SEGMENTS_COUNT,
                        color=color
                    )
                if shape.type == '3':  # cylinder
                    viewport.draw_cylinder(
                        shape.cyl_rad,
                        shape.cyl_hgh * 0.5,
                        viewport.settings.BONE_SHAPE_CYLINDER_SEGMENTS_COUNT,
                        color
                    )
            finally:
                gpu.matrix.pop()
        else:
            bgl.glPopMatrix()
            bgl.glPushMatrix()
            try:
                mat = multiply(mat, shape.get_matrix_basis())
                bgl.glMultMatrixf(
                    viewport.gl_utils.matrix_to_buffer(mat.transposed())
                )
                if shape.type == '1':  # box
                    viewport.draw_cube(*shape.box_hsz)
                if shape.type == '2':  # sphere
                    viewport.draw_sphere(
                        shape.sph_rad,
                        viewport.settings.BONE_SHAPE_SPHERE_SEGMENTS_COUNT
                    )
                if shape.type == '3':  # cylinder
                    viewport.draw_cylinder(
                        shape.cyl_rad,
                        shape.cyl_hgh * 0.5,
                        viewport.settings.BONE_SHAPE_CYLINDER_SEGMENTS_COUNT
                    )
            finally:
                bgl.glPopMatrix()
        bgl.glLineWidth(prev_line_width[0])
 def _get(self, instance, owner):
     glGetFloatv(GL_POLYGON_OFFSET_FACTOR, float2buf0)
     glGetFloatv(GL_POLYGON_OFFSET_UNITS, float2buf1)
     return PolygonOffset(float2buf0[0], float2buf1[0])
 def _get(self, instance, owner):
     glGetFloatv(GL_DEPTH_RANGE, float2buf0)
     return DepthRange(*float2buf0)