Пример #1
0
def draw_circle_select(m_coords, radius = 16, p_col = (0.7,0.8,1.0,0.6), enabled = False, sub = False):
    if(enabled):
        f_col = p_col
        if sub:
            f_col = (1.0, 0.5, 0.4, 0.6)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBegin(bgl.GL_POLYGON)
        bgl.glColor4f(f_col[0], f_col[1], f_col[2], f_col[3]/3)

        point_x = m_coords[0]
        point_y = m_coords[1]

        radius = int(radius)

        for x in range(0, radius*2):
            bgl.glVertex2f(point_x + radius * math.cos(x * (360/(radius*2)) / 180 * 3.14159), point_y + radius * math.sin(x * (360/(radius*2)) / 180 * 3.14159))
        bgl.glEnd()

        bgl.glBegin(bgl.GL_LINES)
        bgl.glColor4f(f_col[0], f_col[1], f_col[2], f_col[3])
        for x in range(0, radius*2):
            bgl.glVertex2f(point_x + radius * math.cos(x * (360 / (radius * 2)) / 180 * 3.14159),
                           point_y + radius * math.sin(x * (360 / (radius * 2)) / 180 * 3.14159))

        bgl.glEnd()
        # restore opengl defaults
        bgl.glLineWidth(1)
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #2
0
def draw_callback_px(self, context):
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 0.5)
    bgl.glLineWidth(2)

    if context.scene.curve_freehand.use_pressure:
        from mathutils import noise
        pt_a = self.mouse_path[0]
        for i in range(1, len(self.mouse_path)):
            # weak but good enough for preview
            pt_b = self.mouse_path[i]
            bgl.glPointSize(1 + (pt_a[2] * 40.0))
            bgl.glBegin(bgl.GL_POINTS)
            bgl.glVertex2i(pt_a[0], pt_a[1])
            bgl.glVertex2i(pt_b[0], pt_b[1])
            bgl.glEnd()
            pt_a = pt_b
    else:
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for pt in self.mouse_path:
            bgl.glVertex2i(pt[0], pt[1])
        bgl.glEnd()

    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #3
0
 def draw3d_closed_polylines(context, lpoints, color, thickness, LINE_TYPE, mirror):
     #if type(lpoints) is types.GeneratorType:
     #    lpoints = list(lpoints)
     lpoints = [[mirror(pt) for pt in points] for points in lpoints]
     if len(lpoints) == 0: return
     if LINE_TYPE == "GL_LINE_STIPPLE":
         bgl.glLineStipple(4, 0x5555)  #play with this later
         bgl.glEnable(bgl.GL_LINE_STIPPLE)  
     bgl.glEnable(bgl.GL_BLEND)
     bgl.glLineWidth(thickness)
     bgl.glColor4f(*color)
     for points in lpoints:
         set_depthrange(0.0, 0.997, points)
         bgl.glBegin(bgl.GL_LINE_STRIP)
         for coord in chain(points,points[:1]):
             bgl.glVertex3f(*coord)
         bgl.glEnd()
     # if settings.symmetry_plane == 'x':
     #     bgl.glColor4f(*color_mirror)
     #     for points in lpoints:
     #         bgl.glBegin(bgl.GL_LINE_STRIP)
     #         for coord in points:
     #             bgl.glVertex3f(-coord.x, coord.y, coord.z)
     #         bgl.glVertex3f(-points[0].x, points[0].y, points[0].z)
     #         bgl.glEnd()
         
     bgl.glLineWidth(1)
     if LINE_TYPE == "GL_LINE_STIPPLE":
         bgl.glDisable(bgl.GL_LINE_STIPPLE)
         bgl.glEnable(bgl.GL_BLEND)  # back to uninterrupted lines  
Пример #4
0
def draw_line(self, context, vertexloc, vertexnorm, colour, thick):
    obj = context.active_object
    
    #get obj rotation
    rot = obj.rotation_euler.to_matrix().inverted()
    scale = obj.scale
    vertex = vertexloc * rot
    normal = vertexnorm * rot

    x1 = vertex[0] * scale[0] + obj.location[0]
    y1 = vertex[1] * scale[1] + obj.location[1]
    z1 = vertex[2] * scale[2] + obj.location[2]
    
    x2 = normal[0]*context.scene.tool_settings.normal_size* scale[0] + x1
    y2 = normal[1]*context.scene.tool_settings.normal_size* scale[1] + y1
    z2 = normal[2]*context.scene.tool_settings.normal_size* scale[2] + z1
    
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glLineWidth(thick)
    # set colour
    bgl.glColor4f(*colour)
    
    # draw line
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex3f(x1,y1,z1)
    bgl.glVertex3f(x2,y2,z2)
    bgl.glEnd()
    bgl.glDisable(bgl.GL_BLEND)
Пример #5
0
def draw_callback_px(self, context):
    print("mouse points", len(self.mouse_path))

    font_id = 0  # XXX, need to find out how best to get this.

    # draw some text
    blf.position(font_id, 15, 30, 0)
    blf.size(font_id, 20, 72)
    blf.draw(font_id, "Hello Word " + str(len(self.mouse_path)))

    # 50% alpha, 2 pixel width line
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 0.5)
    bgl.glLineWidth(2)

    bgl.glBegin(bgl.GL_LINE_STRIP)
    for x, y in self.mouse_path:
        bgl.glVertex2i(x, y)

    bgl.glEnd()

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #6
0
def mi_draw_3d_polyline(points, p_size, p_col, x_ray):
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glLineWidth(1)

    if x_ray is True:
        bgl.glDisable(bgl.GL_DEPTH_TEST)

    bgl.glPointSize(p_size)
#    bgl.glBegin(bgl.GL_LINE_LOOP)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glColor4f(p_col[0], p_col[1], p_col[2], p_col[3])
 #   bgl.glBegin(bgl.GL_POLYGON)

    for point in points:
        bgl.glVertex3f(point[0], point[1], point[2])

    if x_ray is True:
        bgl.glEnable(bgl.GL_DEPTH_TEST)

    bgl.glEnd()

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #7
0
    def draw(self, context, render=False):
        """
            render flag when rendering
        """

        # print("draw_line %s" % (type(self).__name__))
        bgl.glPushAttrib(bgl.GL_ENABLE_BIT)
        if self.style == bgl.GL_LINE_STIPPLE:
            bgl.glLineStipple(1, 0x9999)
        bgl.glEnable(self.style)
        bgl.glEnable(bgl.GL_BLEND)
        if render:
            # enable anti-alias on lines
            bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glColor4f(*self.colour)
        bgl.glLineWidth(self.width)
        if self.closed:
            bgl.glBegin(bgl.GL_LINE_LOOP)
        else:
            bgl.glBegin(bgl.GL_LINE_STRIP)

        for pt in self.pts:
            x, y = self.position_2d_from_coord(context, pt, render)
            bgl.glVertex2f(x, y)
        self._end()
Пример #8
0
def draw_polyline_from_3dpoints(context, points_3d, color, thickness, LINE_TYPE):
    '''
    a simple way to draw a line
    slow...becuase it must convert to screen every time
    but allows you to pan and zoom around
    
    args:
        points_3d: a list of tuples representing x,y SCREEN coordinate eg [(10,30),(11,31),...]
        color: tuple (r,g,b,a)
        thickness: integer? maybe a float
        LINE_TYPE:  eg...bgl.GL_LINE_STIPPLE or 
    '''
    points = [location_3d_to_region_2d(context.region, context.space_data.region_3d, loc) for loc in points_3d]
    if LINE_TYPE == "GL_LINE_STIPPLE":  
        bgl.glLineStipple(4, 0x5555)  #play with this later
        bgl.glEnable(bgl.GL_LINE_STIPPLE)  
    bgl.glEnable(bgl.GL_BLEND)
    
    bgl.glColor4f(*color)
    bgl.glLineWidth(thickness)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for coord in points:  
        bgl.glVertex2f(*coord)  
    
    bgl.glEnd()  
      
    if LINE_TYPE == "GL_LINE_STIPPLE":  
        bgl.glDisable(bgl.GL_LINE_STIPPLE)  
        bgl.glEnable(bgl.GL_BLEND)  # back to uninterupted lines  
        bgl.glLineWidth(1)
    return
Пример #9
0
def draw_line(point0, point1, width):
    bgl.glLineWidth(width)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex3f(point0.x, point0.y, point0.z)
    bgl.glVertex3f(point1.x, point1.y, point1.z)
    bgl.glEnd()
    bgl.glLineWidth(1)
	def drawCurvePoints(self):
		#Draw Lines between Control Points

		bgl.glEnable(bgl.GL_POINT_SMOOTH)
		bgl.glColor3d(0,1,0)
		bgl.glPointSize(3)
		bgl.glBegin(bgl.GL_POINTS)

		for i in range(len(self.curvePoints)):
			tup = self.curvePoints[i].to_tuple()
			bgl.glVertex3f( *tup )
		bgl.glEnd()

		bgl.glLineWidth(1)
		bgl.glColor3f(0,.5,0)
		bgl.glBegin(bgl.GL_LINES)
		'''
		for i in range(0, len(self.curvePoints)-1):
			if i%(self.tesselate+1) != self.tesselate:
				tup = self.curvePoints[i]
				tup1 = self.curvePoints[i+1]
				bgl.glVertex3f( *tup )
				bgl.glVertex3f( *tup1 )
		'''
		for i in range(0, len(self.curvePoints)-1):
			tup = self.curvePoints[i].to_tuple()
			tup1 = self.curvePoints[i+1].to_tuple()
			bgl.glVertex3f(tup[0], tup[1], tup[2])
			bgl.glVertex3f(tup1[0], tup1[1], tup1[2])
		bgl.glEnd()
Пример #11
0
def draw_polyline_from_points(context, points, color, thickness, LINE_TYPE):
    '''
    a simple way to draw a line
    args:
        points: a list of tuples representing x,y SCREEN coordinate eg [(10,30),(11,31),...]
        color: tuple (r,g,b,a)
        thickness: integer? maybe a float
        LINE_TYPE:  eg...bgl.GL_LINE_STIPPLE or 
    '''
    
    if LINE_TYPE == "GL_LINE_STIPPLE":  
        bgl.glLineStipple(4, 0x5555)  #play with this later
        bgl.glEnable(bgl.GL_LINE_STIPPLE)  
    bgl.glEnable(bgl.GL_BLEND)
    
    current_width = bgl.GL_LINE_WIDTH
    bgl.glColor4f(*color)
    bgl.glLineWidth(thickness)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    
    for coord in points:  
        bgl.glVertex2f(*coord)  
    
    bgl.glEnd()  
    bgl.glLineWidth(1)  
    if LINE_TYPE == "GL_LINE_STIPPLE":  
        bgl.glDisable(bgl.GL_LINE_STIPPLE)  
        bgl.glEnable(bgl.GL_BLEND)  # back to uninterupted lines  
      
    return
Пример #12
0
def display_line_between_two_points(region, rv3d, p1_3d, p2_3d):

    bgl.glEnable(bgl.GL_BLEND)

    p1_2d = view3d_utils.location_3d_to_region_2d(region, rv3d, p1_3d)
    p2_2d = view3d_utils.location_3d_to_region_2d(region, rv3d, p2_3d)

    if p1_2d is None:
        p1_2d = (0.0, 0.0)
        p2_2d = (0.0, 0.0)

    col_line_main = addon_settings_graph()['col_line_main']
    col_line_shadow = addon_settings_graph()['col_line_shadow']

    bgl.glColor4f(*col_line_shadow)
    bgl.glLineWidth(1.4)
    bgl.glBegin(bgl.GL_LINE_STRIP) 
    bgl.glVertex2f((p1_2d[0]-1),(p1_2d[1]-1))
    bgl.glVertex2f((p2_2d[0]-1),(p2_2d[1]-1))
    bgl.glEnd()
    bgl.glColor4f(*col_line_main)
    bgl.glLineWidth(1.4)
    bgl.glBegin(bgl.GL_LINE_STRIP) 
    bgl.glVertex2f(*p1_2d)
    bgl.glVertex2f(*p2_2d)
    bgl.glEnd()

    bgl.glDisable(bgl.GL_BLEND)
Пример #13
0
def draw_target_limits(cam, rot_limits, dist_limits, rotation_mat, draw_color, use_limits):
    dist_min = 0 if dist_limits is None else dist_limits[0]
    dist_max = ((cam.data.b4w_target - cam.location).length 
            if dist_limits is None else dist_limits[1])

    # draw external lines
    if dist_limits is not None:
        arc_min = get_arc_points(cam.data.b4w_target, lambda x: dist_min, 
                (0, 0, 1), RANGE_2PI[0], RANGE_2PI[1], rotation_mat)
        draw_limit_strip(arc_min, draw_color)
        arc_max = get_arc_points(cam.data.b4w_target, lambda x: dist_max, 
                (0, 0, 1), RANGE_2PI[0], RANGE_2PI[1], rotation_mat)
        draw_limit_strip(arc_max, draw_color)

    # draw main lines
    arcs = []
    for i in range(NUM_RINGS + 1):
        arc_radius = (dist_max - dist_min) * i / NUM_RINGS + dist_min
        arcs.append(get_arc_points(cam.data.b4w_target, lambda x: arc_radius, 
                (0, 0, 1), rot_limits[0], rot_limits[1], rotation_mat))

    for i in range(len(arcs)):
        is_border = dist_limits is not None and (i == 0 or i == len(arcs) - 1)
        draw_limit_strip(arcs[i], draw_color, is_border)

    for i in range(len(arcs[0])):
        is_border = use_limits and (i == 0 or i == len(arcs[0]) - 1)
        draw_limit_strip([arcs[0][i], arcs[-1][i]], draw_color, is_border)

    bgl.glLineWidth(1)
Пример #14
0
 def __exit__(self, type, value, traceback):
     bgl.glEnd()
     # restore opengl defaults
     bgl.glLineWidth(1)
     bgl.glDisable(bgl.GL_BLEND)
     bgl.glEnable(bgl.GL_DEPTH_TEST)
     bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #15
0
def draw_normal(context, vertexloc, vertexnorm, objscale, is_selected = True):
    # draw normals in object mode
    obj = context.active_object
    color1, thick1 = (0.5, 1.0, 1.0, 1.0), 3

    # input in localspace
    vertexloc = copy.copy(vertexloc)
    vertexloc.resize_4d()
    obmat = obj.matrix_world
    r1 = obmat*vertexloc
    r1.resize_3d()
    del vertexloc
    r2 = obj.rotation_euler.to_matrix() * mathutils.Vector(vertexnorm)
    r2 = r2* objscale
    r2 = r2* context.scene.tool_settings.normal_size + r1

    bgl.glEnable(bgl.GL_BLEND)

    bgl.glLineWidth(thick1)
    # set colour
    bgl.glColor4f(*color1)
    # draw line
    bgl.glBegin(bgl.GL_LINES)

    bgl.glVertex3f(r1.x,r1.y,r1.z)
    bgl.glVertex3f(r2.x,r2.y,r2.z)

    bgl.glEnd()
    bgl.glDisable(bgl.GL_BLEND)
Пример #16
0
def draw_callback(self, context):

    scene = context.scene
    x = int(round(context.region.width * 0.01 + (self._t_target - scene.frame_start) * self._ppf))
    string = str(self._t_target)
    string = string[0 : string.index(".") + 3]
    font_id = 0  # XXX, need to find out how best to get this.

    # draw marker
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1, 0, 0, 1)
    bgl.glLineWidth(2)

    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2i(x, 17)
    bgl.glVertex2i(x, context.region.height)
    bgl.glEnd()

    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

    # draw frame number
    if self._show_frame_indicator:
        blf.position(font_id, x + 5, 21, 0)
        blf.size(font_id, 12, 72)
        blf.draw(font_id, string)
Пример #17
0
    def draw_postpixel(self, context):
        ''' Place post pixel drawing code in here '''
        settings = common_utilities.get_settings()
        region,r3d = context.region,context.space_data.region_3d
        
        color_inactive = RetopoFlowPreferences.theme_colors_mesh[settings.theme]
        color_selection = RetopoFlowPreferences.theme_colors_selection[settings.theme]
        color_active = RetopoFlowPreferences.theme_colors_active[settings.theme]

        color_frozen = RetopoFlowPreferences.theme_colors_frozen[settings.theme]
        color_warning = RetopoFlowPreferences.theme_colors_warning[settings.theme]

        bgl.glEnable(bgl.GL_POINT_SMOOTH)

        color_handle = (color_inactive[0], color_inactive[1], color_inactive[2], 1.00)
        color_border = (color_inactive[0], color_inactive[1], color_inactive[2], 1.00)
        color_fill = (color_inactive[0], color_inactive[1], color_inactive[2], 0.20)
        

        bgl.glLineWidth(1)

        if self.fsm_mode == 'brush scale tool':
            # scaling brush size
            self.sketch_brush.draw(context, color=(1, 1, 1, .5), linewidth=1, color_size=(1, 1, 1, 1))
        elif not self.is_navigating:
            # draw the brush oriented to surface
            hit_p3d,hit_norm = self.src_bmc.raycast_screen(self.cur_pos, region, r3d)
            if hit_p3d:
                common_drawing_px.draw_circle(context, hit_p3d, hit_norm.normalized(), self.stroke_radius, (1,1,1,.5))
Пример #18
0
 def draw3d_closed_polylines(context, lpoints, color, thickness, LINE_TYPE):
     lpoints = list(lpoints)
     if LINE_TYPE == "GL_LINE_STIPPLE":
         bgl.glLineStipple(4, 0x5555)  #play with this later
         bgl.glEnable(bgl.GL_LINE_STIPPLE)  
     bgl.glEnable(bgl.GL_BLEND)
     bgl.glLineWidth(thickness)
     bgl.glDepthRange(0.0, 0.997)
     bgl.glColor4f(*color)
     for points in lpoints:
         bgl.glBegin(bgl.GL_LINE_STRIP)
         for coord in points:
             bgl.glVertex3f(*coord)
         bgl.glVertex3f(*points[0])
         bgl.glEnd()
     if settings.symmetry_plane == 'x':
         bgl.glColor4f(*color_mirror)
         for points in lpoints:
             bgl.glBegin(bgl.GL_LINE_STRIP)
             for coord in points:
                 bgl.glVertex3f(-coord.x, coord.y, coord.z)
             bgl.glVertex3f(-points[0].x, points[0].y, points[0].z)
             bgl.glEnd()
         
     bgl.glLineWidth(1)
     if LINE_TYPE == "GL_LINE_STIPPLE":
         bgl.glDisable(bgl.GL_LINE_STIPPLE)
         bgl.glEnable(bgl.GL_BLEND)  # back to uninterrupted lines  
Пример #19
0
def DRAW_RunResize(self, context):

    # Restore opengl defaults
    bgl.glDisable(bgl.GL_POINTS)
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #20
0
    def post_view_callback(self, context):
        start = self.vertex_co
        normal_size = context.tool_settings.normal_size
        view_3d_theme = context.user_preferences.themes['Default'].view_3d

        default_color = view_3d_theme.split_normal
        highlight_color = [0.25, 1.0, 0.56]

        # Draw all normals of selected vertex.
        bgl.glBegin(bgl.GL_LINES)
        bgl.glColor3f(*default_color)
        bgl.glLineWidth(1)
        for n in self.normals:
            end = start + Vector(n) * normal_size
            bgl.glVertex3f(*start)
            bgl.glVertex3f(*end)
        bgl.glEnd()

        # Highlight selected normal.
        bgl.glColor3f(*highlight_color)
        bgl.glLineWidth(2)
        bgl.glBegin(bgl.GL_LINES)
        end = start + Vector(self.normals[self.normals_idx]) * normal_size
        bgl.glVertex3f(*start)
        bgl.glVertex3f(*end)
        bgl.glEnd()
Пример #21
0
def draw_ephestos(self,context):
    global show_world
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 0.5)
    bgl.glLineWidth(1.5)

    """
    #set colour to use
    bgl.glColor4f(0.5,0.0,0.5,0.3)

    x_region = round((bpy.context.area.regions[4].width-5)/2)
    y_region = round((bpy.context.area.regions[4].height-5)/2)
    print("x_region : ",x_region)
    print("y_region : ",y_region)
    bgl.glRecti(5,5,x_region, y_region)
    """
#    if show_world:
    world.draw()
    '''
    good_rounded_box.draw_new(ephestos)
    world.draw_new(ephestos)
#        show_world = False
    red_morph.draw_new(ephestos)
    green_morph.draw_new(ephestos)
    blue_morph.draw_new(ephestos)
    multiline_text.draw_new(ephestos)
    rounded_box.draw_new(ephestos)
    one_String.draw_new(ephestos)
#PKHG.stringfieldTest.???
    test_stringfield.draw_new( ephestos)
    '''
    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
 def draw_Cartesian(self):#vertices):
     ob = bpy.context.scene.objects.active.location
     rgn = bpy.context.region
     rv3d = bpy.context.space_data.region_3d
     #bgl.glClear()
     
     bgl.glEnable(bgl.GL_BLEND)
     bgl.glLineWidth(4)    
     bgl.glBegin(bgl.GL_LINE_STRIP)
     v3d = Vector((0, 0, 0))
     v2d = location_3d_to_region_2d(rgn, rv3d, v3d)
     bgl.glVertex2f(*v2d)
     bgl.glColor4f(100, 0.0, 0.0, 1)
     v3d = mathutils.Vector((ob.x,0,0))
     v2d = location_3d_to_region_2d(rgn, rv3d, v3d)
     bgl.glVertex2f(*v2d)
     bgl.glColor4f(0, 100.0, 0.0, 1)
     v3d = mathutils.Vector((ob.x,ob.y,0))
     v2d = location_3d_to_region_2d(rgn, rv3d, v3d)
     bgl.glVertex2f(*v2d)
     bgl.glColor4f(0, 0.0, 100.0, 1)
     v3d = mathutils.Vector((ob.x,ob.y,ob.z))
     v2d = location_3d_to_region_2d(rgn, rv3d, v3d)
     bgl.glVertex2f(*v2d)
     bgl.glEnd()
     bgl.glLineWidth(1)
     bgl.glDisable(bgl.GL_BLEND)
     
     bgl.glColor4f(1, 1, 1, 1)
     self.draw_value(Vector((ob.x/2,0,0)), str(round(ob.x, 2)))
     self.draw_value(Vector((ob.x, ob.y/2, 0)), str(round(ob.y, 2)))
     self.draw_value(Vector((ob.x, ob.y, ob.z/2)), str(round(ob.z, 2)))
Пример #23
0
def screen_v3dBGL_overlay(context, args):

    if not args[2]:
        return

    alpha = args[3]
    

    region = context.region
    region3d = context.space_data.region_3d

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

    for matrix, color in args[0]:
        r, g, b = color
        bgl.glColor4f(r, g, b, alpha)
        bgl.glBegin(bgl.GL_QUADS)
        M = Matrix(matrix)
        for x, y in [(-.5, .5), (.5 ,.5), (.5 ,-.5), (-.5 ,-.5)]:
            vector3d = M * Vector((x, y, 0))
            vector2d = loc3d2d(region, region3d, vector3d)
            bgl.glVertex2f(*vector2d)

        bgl.glEnd()

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #24
0
def draw_callback_px(self, context):
    if(self.ShowCursor):
        region = bpy.context.region
        rv3d = bpy.context.space_data.region_3d
        view_width = context.region.width
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glLineWidth(2)
        bgl.glColor4f(1.0, 0.8, 0.0, 1.0)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        idx = 0
        for i in range(int(len(self.CLR_C)/3)):
            vector3d = (self.CLR_C[idx * 3] * self.CRadius + self.CurLoc.x,self.CLR_C[idx * 3  + 1] * self.CRadius + self.CurLoc.y,self.CLR_C[idx * 3 + 2] * self.CRadius + self.CurLoc.z)
            vector2d = bpy_extras.view3d_utils.location_3d_to_region_2d(region, rv3d, vector3d)
            bgl.glVertex2f(*vector2d)
            idx += 1
        bgl.glEnd()
        bgl.glBegin(bgl.GL_LINE_STRIP)
        idx = 0
        for i in range(int(len(self.CLR_C)/3)):
            vector3d = (self.CLR_C[idx * 3] * self.CRadius/3.0 + self.CurLoc.x,self.CLR_C[idx * 3  + 1] * self.CRadius/3.0 + self.CurLoc.y,self.CLR_C[idx * 3 + 2] * self.CRadius/3.0 + self.CurLoc.z)
            vector2d = bpy_extras.view3d_utils.location_3d_to_region_2d(region, rv3d, vector3d)
            bgl.glVertex2f(*vector2d)
            idx += 1
        bgl.glEnd()
        bgl.glLineWidth(1)
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #25
0
def draw_callback_px(self, context):
    
    if init_functions(self, context) == None:
        return
        
    region = context.region
    rv3d = context.space_data.region_3d
    points, guide_verts = init_functions(self, context)
    
    arc_verts = get_arc_from_state(points, guide_verts, context)

    # draw bevel, followed by symmetry line, then fillet edge loop
    draw_polyline_from_coordinates(context, points, "GL_LINE_STIPPLE")
    draw_polyline_from_coordinates(context, guide_verts, "GL_LINE_STIPPLE")
    draw_polyline_from_coordinates(context, arc_verts, "GL_BLEND")

    # draw arc verts, then radial centre   
    if DRAW_POINTS:
        draw_points(context, arc_verts, 4.2, gl_col1)    
        draw_points(context, [guide_verts[1]], 5.2, gl_col2)
    
    # draw bottom left, above object name the number of vertices in the fillet
    draw_text(context, (65, 30), context.scene.NumVerts)
        
    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
    return
Пример #26
0
 def restore_opengl(self):
     # Restore OpenGL to its default state.
     bgl.glColor4f(0, 0, 0, 1)
     bgl.glDepthRange(0, 1)
     bgl.glLineWidth(1)
     bgl.glPolygonOffset(0, 0)
     bgl.glDisable(bgl.GL_BLEND | bgl.GL_POLYGON_OFFSET_FILL)
Пример #27
0
def vray_draw_light_shape():
    if not bpy.context:
        return
    ob = bpy.context.active_object
    if not ob:
        return
    if ob.type not in {'LAMP'}:
        return

    la = ob.data

    VRayLight = LibUtils.GetLightPropGroup(la)

    bgl.glEnable(bgl.GL_POINT_SMOOTH)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

    col = lamp_color if VRayLight.enabled else lamp_color_off
    bgl.glColor4f(*col)

    if la.type == 'POINT':
        if la.vray.omni_type == 'SPHERE':
            vray_draw_light_sphere_shape(ob)
    elif la.type == 'SUN':
        if la.vray.direct_type == 'DIRECT':
            vray_draw_light_direct_shape(ob)

    # Reset draw
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #28
0
def draw_shape_traffic_light(mat, scene_scs_props):
    """
    Draws shape for "Locator" of "Traffic Semaphore" type.
    :param mat:
    :return:
    """
    glLineWidth(2.0)
    glBegin(GL_LINE_STRIP)
    glColor3f(scene_scs_props.locator_prefab_wire_color.r, scene_scs_props.locator_prefab_wire_color.g, scene_scs_props.locator_prefab_wire_color.b)
    glVertex3f(*(mat * Vector((0.0, 0.0, scene_scs_props.locator_empty_size))))
    glVertex3f(*(mat * Vector((0.0, 0.0, 0.45))))
    glVertex3f(*(mat * Vector((-0.0866, 0.0, 0.5))))
    glVertex3f(*(mat * Vector((-0.0866, 0.0, 0.84))))
    glVertex3f(*(mat * Vector((0.0, 0.0, 0.89))))
    glVertex3f(*(mat * Vector((0.0866, 0.0, 0.84))))
    glVertex3f(*(mat * Vector((0.0866, 0.0, 0.5))))
    glVertex3f(*(mat * Vector((0.0, 0.0, 0.45))))
    glEnd()
    for val in (0.5, 0.62, 0.74):
        glBegin(GL_LINE_LOOP)
        glVertex3f(*(mat * Vector((0.0, 0.0, val))))
        glVertex3f(*(mat * Vector((-0.0433, 0.0, 0.025 + val))))
        glVertex3f(*(mat * Vector((-0.0433, 0.0, 0.075 + val))))
        glVertex3f(*(mat * Vector((0.0, 0.0, 0.1 + val))))
        glVertex3f(*(mat * Vector((0.0433, 0.0, 0.075 + val))))
        glVertex3f(*(mat * Vector((0.0433, 0.0, 0.025 + val))))
        glEnd()
    glLineWidth(1.0)
Пример #29
0
def sync_draw_callback(self, context):
    # polling
    if context.mode != "EDIT_MESH":
        return

    # draw vertices
    bgl.glColor4f(1.0, 0.0, 0.0, 1.0)
    bgl.glPointSize(4)
    bgl.glBegin(bgl.GL_POINTS)
    for x, y in self.position_vertices:
        bgl.glVertex2i(x, y)
    bgl.glEnd()

    # draw edges
    bgl.glColor4f(1.0, 0.0, 0.0, 1.0)
    bgl.glLineWidth(1.5)
    bgl.glBegin(bgl.GL_LINES)
    for x, y in self.position_edges:
        bgl.glVertex2i(x, y)
    bgl.glEnd()
    bgl.glLineWidth(1)

    # draw faces
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1.0, 0.0, 0.0, 0.3)
    bgl.glBegin(bgl.GL_QUADS)
    for x, y in self.position_faces:
        bgl.glVertex2i(x, y)
    bgl.glEnd()
    bgl.glDisable(bgl.GL_BLEND)
Пример #30
0
def h_draw_arc_wire(cx, cy, r, start_angle, arc_angle, color=(1,1,1,1), width=1, segs=12):
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)

    start_angle = math.radians(start_angle)
    arc_angle = math.radians(arc_angle)
    
    theta = arc_angle / (segs-1)
    
    tangencial_factor = math.tan(theta)
    radial_factor = math.cos(theta)
    
    x = r * math.cos(start_angle)
    y = r * math.sin(start_angle)
    
    bgl.glColor4f(*color)
    bgl.glLineWidth(width)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    
    for i in range(segs):
        bgl.glVertex2f(x + cx, y + cy)
        
        tx = -y
        ty = x
        
        x += tx * tangencial_factor
        y += ty * tangencial_factor
        x *= radial_factor
        y *= radial_factor

    bgl.glEnd()
    
    bgl.glDisable(bgl.GL_BLEND)
Пример #31
0
def drawCallback():

    if bpy.context.mode == 'EDIT_MESH':

        obj = bpy.context.object

        bl = obj.border_lines
        if obj and obj.type == 'MESH' and obj.data:
            if bl.borderlines_use:
                mesh = obj.data
                matrix_world = obj.matrix_world
                settings = bpy.context.user_preferences.themes[0].view_3d

                transform = settings.transform
                edge_select = settings.edge_select
                wire_edit = settings.wire_edit
                wire = settings.wire
                object_active = settings.object_active

                glLineWidth(bl.borderlines_width)

                draw_with_test = True

                if bm_old[0] is None or not bm_old[0].is_valid:
                    bm = bm_old[0] = bmesh.from_edit_mesh(mesh)

                else:
                    bm = bm_old[0]

                no_depth = not bpy.context.space_data.use_occlude_geometry

                if no_depth:
                    glDisable(GL_DEPTH_TEST)

                    draw_with_test = False

                    if bl.finer_lines_behind_use:
                        glLineWidth(bl.borderlines_width / 4.0)
                        draw_with_test = True

                    glBegin(GL_LINES)

                    if bl.custom_color_use:
                        glColor3f(*bl.custom_color)
                        for edge in bm.edges:
                            if edge.is_valid and edge.is_boundary:
                                coords = [
                                    matrix_world * vert.co
                                    for vert in edge.verts
                                ]
                                for coord in coords:
                                    glVertex3f(*coord)

                    else:
                        active = bm.select_history.active
                        for edge in bm.edges:
                            if edge.is_valid and edge.is_boundary and not edge.hide:
                                coords = [
                                    matrix_world * vert.co
                                    for vert in edge.verts
                                ]

                                if active == edge:
                                    drawColorSize(coords, transform)
                                elif edge.select:
                                    drawColorSize(coords, edge_select)
                                else:
                                    drawColorSize(coords, wire_edit)

                    glEnd()

                    glLineWidth(bl.borderlines_width)

                    glEnable(GL_DEPTH_TEST)

                if draw_with_test:

                    glBegin(GL_LINES)

                    if bl.custom_color_use:
                        glColor3f(*bl.custom_color)
                        for edge in bm.edges:
                            if edge.is_valid and edge.is_boundary:
                                coords = [
                                    matrix_world * vert.co
                                    for vert in edge.verts
                                ]
                                for coord in coords:
                                    glVertex3f(*coord)

                    else:
                        active = bm.select_history.active
                        for edge in bm.edges:
                            if edge.is_valid and edge.is_boundary:
                                coords = [
                                    matrix_world * vert.co
                                    for vert in edge.verts
                                ]

                                if active == edge:
                                    drawColorSize(coords, transform)
                                elif edge.select:
                                    drawColorSize(coords, edge_select)
                                else:
                                    drawColorSize(coords, wire_edit)

                    glEnd()

    elif bpy.context.mode == 'OBJECT':
        for obj in bpy.context.visible_objects:
            if obj and obj.type == 'MESH' and obj.data:
                if (obj.show_wire or bpy.context.space_data.viewport_shade
                        == 'WIREFRAME'):
                    bl = obj.border_lines

                    if bl.borderlines_use:

                        mesh = obj.data
                        matrix_world = obj.matrix_world
                        settings = bpy.context.user_preferences.themes[
                            0].view_3d

                        wire = settings.wire
                        object_selected = settings.object_selected

                        counts = edge_face_count(mesh)

                        glLineWidth(bl.borderlines_width)

                        glBegin(GL_LINES)

                        if bl.custom_color_use:
                            glColor3f(*bl.custom_color)
                        elif obj == bpy.context.active_object and obj.select:
                            glColor3f(*settings.object_active)
                        elif obj.select:
                            glColor3f(*settings.object_selected)
                        else:
                            glColor3f(*settings.wire)

                        for edge, count in zip(mesh.edges, counts):
                            # border edges
                            if count == 1:
                                coords = [
                                    matrix_world * Vector(mesh.vertices[i].co)
                                    for i in edge.key
                                ]
                                for coord in coords:
                                    glVertex3f(*coord)

                        glEnd()

    glLineWidth(1.0)
Пример #32
0
def DRAW_Overlay(self, context):

    np_print('DRAW_Overlay_START',';','NP020PL.flag = ', NP020PL.flag)

    flag = NP020PL.flag
    helper = NP020PL.helper
    region = bpy.context.region
    rv3d = bpy.context.region_data
    rw = region.width
    rh = region.height
    co2d = view3d_utils.location_3d_to_region_2d(region, rv3d, helper.location)
    frompoints = NP020PL.frompoints
    topoints = NP020PL.topoints


    col_line_main = (1.0, 1.0, 1.0, 1.0)
    col_line_shadow = (0.1, 0.1, 0.1, 0.25)

    #greys:
    mark_col_A = (0.25, 0.25, 0.25, 1.0)
    mark_col_B = (0.5, 0.5, 0.5, 1.0)
    mark_col_C = (0.75, 0.75, 0.75, 1.0)

    #marins
    mark_col_A = (0.25, 0.35, 0.4, 1.0)
    mark_col_B = (0.5, 0.6, 0.65, 1.0)
    mark_col_C = (0.67, 0.77, 0.82, 1.0)

    # writing the dots for recwidget widget at center of scene:

    r = 12
    angstep = 20
    psize = 25
    pofsetx = 15
    pofsety = 15
    fsize = 20
    fofsetx = -8
    fofsety = -7



    widget_circle = construct_circle_2d(r, angstep)


    if flag == 'RUNTRANSF0':
        instruct = 'place start for point a'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap'
        keys_neg = 'RMB, ESC - quit'
        frompoints[0] = helper.location

    elif flag == 'RUNTRANST0':
        instruct = 'place target for point a'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap, MMB - lock axis, NUMPAD - value'
        keys_neg = 'RMB, ESC - quit'
        topoints[0] = helper.location

    elif flag == 'RUNTRANSF1':
        instruct = 'place start for point b'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap, MMB - lock axis, NUMPAD - value, RMB - align A (translate)'
        keys_neg = 'ESC - quit'
        frompoints[1] = helper.location

    elif flag == 'RUNTRANST1':
        instruct = 'place target for point b'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap, MMB - lock axis, NUMPAD - value, RMB - align A (translate)'
        keys_neg = 'ESC - quit'
        topoints[1] = helper.location

    elif flag == 'RUNTRANSF2':
        instruct = 'place start for point c'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap, MMB - lock axis, NUMPAD - value, RMB - align AB (translate, rotate)'
        keys_neg = 'ESC - quit'
        frompoints[2] = helper.location

    elif flag == 'RUNTRANST2':
        instruct = 'place target for point c'
        keys_aff = 'LMB - select, CTRL - snap, ENT - change snap, MMB - lock axis, NUMPAD - value, RMB - align AB (translate, rotate)'
        keys_neg = 'ESC - quit'
        topoints[2] = helper.location


    # ON-SCREEN INSTRUCTIONS:


    keys_nav = ''

    display_instructions(region, rv3d, instruct, keys_aff, keys_nav, keys_neg)


    # LINE:

    for i, frompoint in enumerate(frompoints):
        topoint = topoints[i]
        if frompoint != None and topoint != None:
            bgl.glColor4f(*col_line_shadow)
            bgl.glLineWidth(1.4)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            frompoint = view3d_utils.location_3d_to_region_2d(region, rv3d, frompoint)
            topoint = view3d_utils.location_3d_to_region_2d(region, rv3d, topoint)
            bgl.glVertex2f((frompoint[0] - 1), (frompoint[1] - 1))
            bgl.glVertex2f((topoint[0] - 1), (topoint[1] - 1))
            bgl.glEnd()

            bgl.glColor4f(*col_line_main)
            bgl.glLineWidth(1.4)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            bgl.glVertex2f(*frompoint)
            bgl.glVertex2f(*topoint)
            bgl.glEnd()


    # drawing of markers:
    i = 0
    for point in frompoints:
        if point != None:
            point = view3d_utils.location_3d_to_region_2d(region, rv3d, point)
            point[0] = point[0] + pofsetx
            point[1] = point[1] + pofsety
            widget = []
            for co in widget_circle:
                c = [0.0, 0.0]
                c[0] = co[0] + point[0] + pofsetx
                c[1] = co[1] + point[1] + pofsety
                widget.append(c)
            bgl.glEnable(bgl.GL_BLEND)
            if i == 0:
                bgl.glColor4f(*mark_col_A)
                mark = "A"
            elif i == 1:
                bgl.glColor4f(*mark_col_B)
                mark = "B"
            elif i == 2:
                bgl.glColor4f(*mark_col_C)
                mark = "C"

            '''
            bgl.glLineWidth(1)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            for co in widget:
                bgl.glVertex2f(*co)
            bgl.glVertex2f(*widget[len(widget) - 1])
            bgl.glEnd()
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            for co in widget:
                bgl.glVertex2f(*co)
            bgl.glEnd()
            '''
            font_id = 0
            bgl.glEnable(bgl.GL_POINT_SMOOTH)
            bgl.glPointSize(psize)
            bgl.glBegin(bgl.GL_POINTS)
            bgl.glVertex2f(*point)
            bgl.glEnd()
            bgl.glDisable(bgl.GL_POINT_SMOOTH)

            bgl.glColor4f(1.0, 1.0, 1.0, 0.75)
            blf.size(font_id, fsize, 72)
            blf.position(font_id, point[0] + fofsetx, point[1] + fofsety, 0)
            blf.draw(font_id, mark)
            i = i + 1

    i = 0
    for point in topoints:
        if point != None:
            point = view3d_utils.location_3d_to_region_2d(region, rv3d, point)
            point[0] = point[0] + pofsetx
            point[1] = point[1] + pofsety
            widget = []
            for co in widget_circle:
                c = [0.0, 0.0]
                c[0] = co[0] + point[0] + pofsetx
                c[1] = co[1] + point[1] + pofsety
                widget.append(c)
            bgl.glEnable(bgl.GL_BLEND)
            if i == 0:
                bgl.glColor4f(*mark_col_A)
                mark = "A'"
            elif i == 1:
                bgl.glColor4f(*mark_col_B)
                mark = "B'"
            elif i == 2:
                bgl.glColor4f(*mark_col_C)
                mark = "C'"
            '''
            bgl.glLineWidth(1)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            for co in widget:
                bgl.glVertex2f(*co)
            bgl.glVertex2f(*widget[len(widget) - 1])
            bgl.glEnd()
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            for co in widget:
                bgl.glVertex2f(*co)
            bgl.glEnd()
            '''
            font_id = 0
            bgl.glEnable(bgl.GL_POINT_SMOOTH)
            bgl.glPointSize(psize)
            bgl.glBegin(bgl.GL_POINTS)
            bgl.glVertex2f(*point)
            bgl.glEnd()
            bgl.glDisable(bgl.GL_POINT_SMOOTH)

            bgl.glColor4f(1.0, 1.0, 1.0, 0.75)
            blf.size(font_id, fsize, 72)
            blf.position(font_id, point[0] + fofsetx, point[1] + fofsety, 0)
            blf.draw(font_id, mark)
            i = i + 1


    #ENDING:

    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #33
0
def draw_callback_view(n_id, cached_view, options):
    def Vector_generate2(prop):
        # try:
        #     return [[Vector(v[:3]) for v in obj] for obj in prop]
        # except ValueEror:
        #     return []
        return [[Vector(v) for v in obj] for obj in prop]

    # context = bpy.context
    if options["timings"]:
        start = time.perf_counter()

    if options['draw_list'] == 0:

        sl1 = cached_view[n_id + 'v']
        sl2 = cached_view[n_id + 'ep']
        sl3 = cached_view[n_id + 'm']

        if sl1:
            data_vector = Vector_generate2(sl1)
            verlen = len(data_vector) - 1
        else:
            if not sl3:
                # end early: no matrix and no vertices
                callback_disable(n_id)
                return

            # display matrix repr only.
            data_vector = []
            verlen = 0

        options['verlen'] = verlen
        data_polygons = []
        data_edges = []

        if sl2 and sl2[0]:
            if isinstance(sl2[0], int):
                #callback_disable(n_id)
                return

            len_sl2 = len(sl2[0][0])
            if len_sl2 == 2:
                data_edges = sl2
            elif len_sl2 > 2:
                data_polygons = sl2

        if sl3:
            data_matrix = Matrix_generate(sl3)
        else:
            data_matrix = [Matrix() for i in range(verlen + 1)]

        if (data_vector, data_polygons, data_matrix, data_edges) == (0, 0, 0,
                                                                     0):
            return

        try:
            existing_list = drawlists_3dview.get(n_id)
            if existing_list:
                the_display_list = existing_list
            else:
                the_display_list = glGenLists(1)
                drawlists_3dview[n_id] = the_display_list

            glNewList(the_display_list, GL_COMPILE)
            draw_geometry(n_id, options, data_vector, data_polygons,
                          data_matrix, data_edges)
        except Exception as err:
            print("Error in callback!:")
            traceback.print_exc()
            options['error'] = True
        finally:
            glEndList()

    elif options['draw_list'] == 1:
        # this is called when all you do is rotate around the already obtained geometry
        the_display_list = drawlists_3dview.get(n_id)

    if not 'error' in options:
        glCallList(the_display_list)
        # print(the_display_list, n_id)
        glFlush()

    # restore to system state
    glLineWidth(1)

    if options["timings"]:
        stop = time.perf_counter()
        print("callback drawn in {:4f}".format(stop - start))

    # has drawn once with success.
    options['draw_list'] = 1
Пример #34
0
def draw_geometry(n_id, options, data_vector, data_polygons, data_matrix,
                  data_edges):

    show_verts = options['show_verts']
    show_edges = options['show_edges']
    show_faces = options['show_faces']

    vertex_colors = options['vertex_colors']
    edge_colors = options['edge_colors']
    edge_width = options['edge_width']

    tran = options['transparent']
    shade = options['shading']

    verlen = options['verlen']
    max_verts_ = [len(d) for d in data_vector]

    if tran:
        polyholy = GL_POLYGON_STIPPLE
        edgeholy = GL_LINE_STIPPLE
        edgeline = GL_LINE_STRIP
    else:
        polyholy = GL_POLYGON
        edgeholy = GL_LINE
        edgeline = GL_LINES

    def get_max_k(i, verlen):
        k = i
        if i > verlen:
            k = verlen
        return k

    ''' vertices '''

    glEnable(GL_POINT_SIZE)
    glEnable(GL_POINT_SMOOTH)
    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
    # glHint(GL_POINT_SMOOTH_HINT, GL_FASTEST)

    vsize = options['vertex_size']

    if show_verts and data_vector:

        glPointSize(vsize)
        glColor3f(*vertex_colors)
        glBegin(GL_POINTS)

        for i, matrix in enumerate(data_matrix):
            k = get_max_k(i, verlen)
            for vert in data_vector[k]:
                vec = data_matrix[i] * vert
                glVertex3f(*vec)

        glEnd()

    glDisable(GL_POINT_SIZE)
    glDisable(GL_POINT_SMOOTH)
    ''' polygons '''

    if data_polygons and data_vector:
        num_datapolygon_lists = len(data_polygons)

        glEnable(polyholy)
        for i, matrix in enumerate(data_matrix):

            k = get_max_k(i, verlen)
            mesh_edges = set()
            if k >= num_datapolygon_lists:
                k = (num_datapolygon_lists - 1)
                #break

            if len(data_vector[k]) < 3:
                print("can't make faces between fewer than 3 vertices")
                continue

            for j, pol in enumerate(data_polygons[k]):

                if max(pol) >= max_verts_[k]:
                    continue

                if show_faces:
                    display_face(options, pol, data_vector, data_matrix, k, i)

                # collect raw edges, sort by index, use set to prevent dupes.
                if show_edges:
                    er = list(pol) + [pol[0]]
                    kb = {
                        tuple(sorted((e, er[i + 1])))
                        for i, e in enumerate(er[:-1])
                    }
                    mesh_edges.update(kb)

            if show_edges and mesh_edges:
                # glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
                glEnable(edgeholy)
                glLineWidth(edge_width)
                glColor3f(*edge_colors)
                glBegin(GL_LINES)
                for edge in mesh_edges:
                    for p in edge:
                        vec = data_matrix[i] * data_vector[k][p]
                        glVertex3f(*vec)

                glEnd()
                glDisable(edgeholy)

        glDisable(polyholy)
    ''' edges '''

    if data_edges and data_vector and show_edges:

        glColor3f(*edge_colors)
        glLineWidth(edge_width)
        # glEnable(GL_LINE_SMOOTH)
        glEnable(edgeholy)
        # glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)

        for i, matrix in enumerate(data_matrix):
            k = get_max_k(i, verlen)

            if k >= len(data_edges):
                continue

            if len(data_vector[k]) < 2:
                print("can't make edges between fewer than 2 vertices")
                continue

            for line in data_edges[k]:

                # i think this catches edges which refer to indices not present in
                # the accompanying vertex list.
                if max(line) >= max_verts_[k]:
                    continue

                glBegin(edgeline)
                for p in line:
                    vec = data_matrix[i] * data_vector[k][p]
                    glVertex3f(*vec)
                glEnd()

        glDisable(edgeholy)
        # glDisable(GL_LINE_SMOOTH)
    ''' matrix '''

    if data_matrix and not data_vector:
        md = MatrixDraw()
        for mat in data_matrix:
            md.draw_matrix(mat)
Пример #35
0
def draw_brush_cursor(self, context, event):
    wm = context.window_manager
    asset_sketcher = wm.asset_sketcher
    region = bpy.context.region
    rv3d = bpy.context.space_data.region_3d

    self.circle_color = [0.102758, 0.643065, 1.000000, 1.000000]
    if event.ctrl and not self.f_key and event.type != "MIDDLEMOUSE":
        self.circle_color = [1.000000, 0.202489, 0.401234, 1.000000]
    elif self.f_key:
        self.circle_color = [1.0, 1.0, 1.0, .7]

    ### draw brush
    if wm.asset_sketcher.sketch_mode in ["SCALE", "PAINT"]:
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(self.circle_color[0], self.circle_color[1],
                      self.circle_color[2], self.circle_color[3])
        bgl.glLineWidth(2)

        ### draw brush circle
        bgl.glBegin(bgl.GL_LINE_STRIP)
        steps = 32
        angle = (2 * math.pi) / steps

        if self.brush_stroke:
            radius = (wm.asset_sketcher.brush_size / 2) * self.pen_pressure
        else:
            radius = (wm.asset_sketcher.brush_size / 2)

        ### calc smooth visual normal interpolation

        rot_mat = self.ground_normal_current.rotation_difference(
            Vector((0, 0, 1))).to_matrix().to_3x3()

        for i in range(steps + 1):
            x = self.projected_mouse[0] + radius * math.cos(angle * i)
            y = self.projected_mouse[1] + radius * math.sin(angle * i)
            z = self.projected_mouse[2]

            p = Vector((x, y, z))

            ### rotate circle to match the ground normal
            p -= self.projected_mouse
            p = p * rot_mat
            p += self.projected_mouse

            ### convert 3d vectors to 2d screen
            p_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
                region, rv3d, p)
            if p_2d != None:
                bgl.glVertex2f(p_2d[0], p_2d[1])
            #bgl.glVertex3f(p[0],p[1],p[2])
        bgl.glEnd()

        bgl.glBegin(bgl.GL_LINE_STRIP)

        p1 = self.projected_mouse
        p2 = self.projected_mouse + (self.ground_normal_current *
                                     get_zoom(self, context) * .05)
        p1_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p1)
        p2_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p2)
        if p1_2d != None and p2_2d != None:
            bgl.glVertex2f(p1_2d[0], p1_2d[1])
            bgl.glVertex2f(p2_2d[0], p2_2d[1])

        bgl.glEnd()

    elif wm.asset_sketcher.sketch_mode == "GRID":

        mat = get_grid_mat(self, context)

        ### draw grid cursor

        bgl.glColor4f(self.circle_color[0], self.circle_color[1],
                      self.circle_color[2], self.circle_color[3])
        bgl.glLineWidth(2)
        bgl.glBegin(bgl.GL_LINE_STRIP)

        ### draw tile square
        p = self.projected_mouse + (Vector(
            (asset_sketcher.sketch_grid_size / 2,
             asset_sketcher.sketch_grid_size / 2, 0)) * mat)
        p_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p)
        if p_2d != None:
            bgl.glVertex2f(p_2d[0], p_2d[1])

        p = self.projected_mouse + (Vector(
            (asset_sketcher.sketch_grid_size / 2,
             -asset_sketcher.sketch_grid_size / 2, 0)) * mat)
        p_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p)
        if p_2d != None:
            bgl.glVertex2f(p_2d[0], p_2d[1])

        p = self.projected_mouse + (Vector(
            (-asset_sketcher.sketch_grid_size / 2,
             -asset_sketcher.sketch_grid_size / 2, 0)) * mat)
        p_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p)
        if p_2d != None:
            bgl.glVertex2f(p_2d[0], p_2d[1])

        p = self.projected_mouse + (Vector(
            (-asset_sketcher.sketch_grid_size / 2,
             asset_sketcher.sketch_grid_size / 2, 0)) * mat)
        p_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p)
        if p_2d != None:
            bgl.glVertex2f(p_2d[0], p_2d[1])

        p = self.projected_mouse + (Vector(
            (asset_sketcher.sketch_grid_size / 2,
             asset_sketcher.sketch_grid_size / 2, 0)) * mat)
        p_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p)
        if p_2d != None:
            bgl.glVertex2f(p_2d[0], p_2d[1])
        bgl.glEnd()

    restore_opengl_defaults()
Пример #36
0
def restore_opengl_defaults():
    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #37
0
def draw_grid(self, context, event):
    wm = context.window_manager
    asset_sketcher = wm.asset_sketcher
    region = bpy.context.region
    rv3d = bpy.context.space_data.region_3d

    self.circle_color = [0.102758, 0.643065, 1.000000, 1.000000]
    if event.ctrl and event.type != "MIDDLEMOUSE":
        self.circle_color = [1.000000, 0.202489, 0.401234, 1.000000]

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(self.circle_color[0], self.circle_color[1],
                  self.circle_color[2], self.circle_color[3])

    ### draw brush center point
    bgl.glPointSize(5)
    bgl.glColor4f(self.circle_color[0], self.circle_color[1],
                  self.circle_color[2], .5)
    bgl.glBegin(bgl.GL_POINTS)
    p = bpy_extras.view3d_utils.location_3d_to_region_2d(
        region, rv3d, self.projected_mouse)
    if p != None:
        bgl.glVertex2f(p[0], p[1])
    bgl.glEnd()

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(self.circle_color[0], self.circle_color[1],
                  self.circle_color[2], self.circle_color[3])
    bgl.glLineWidth(2)

    ### Plane XY
    mat = get_grid_mat(self, context)

    bgl.glBegin(bgl.GL_LINE_STRIP)
    ### draw tile grid
    grid_size = 18
    for i in range(grid_size):

        self.circle_color = [0.102758, 0.643065, 1.000000, 1.000000]
        bgl.glColor4f(self.circle_color[0], self.circle_color[1],
                      self.circle_color[2], .4)
        bgl.glLineWidth(1)

        offset = Vector(
            ((grid_size / 2) - .5,
             (grid_size / 2) - .5, 0)) * asset_sketcher.sketch_grid_size

        bgl.glBegin(bgl.GL_LINE_STRIP)
        p = self.projected_mouse + ((Vector(
            (0, i * asset_sketcher.sketch_grid_size, 0)) - offset) * mat)
        p_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p)
        bgl.glVertex3f(p[0], p[1], p[2])

        p = self.projected_mouse + ((Vector(
            ((grid_size - 1) * asset_sketcher.sketch_grid_size,
             i * asset_sketcher.sketch_grid_size, 0)) - offset) * mat)
        p_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p)
        bgl.glVertex3f(p[0], p[1], p[2])
        bgl.glEnd()

        bgl.glBegin(bgl.GL_LINE_STRIP)
        p = self.projected_mouse + ((Vector(
            (i * asset_sketcher.sketch_grid_size, 0, 0)) - offset) * mat)
        p_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p)
        bgl.glVertex3f(p[0], p[1], p[2])

        p = self.projected_mouse + ((Vector(
            (i * asset_sketcher.sketch_grid_size,
             (grid_size - 1) * asset_sketcher.sketch_grid_size, 0)) - offset) *
                                    mat)
        p_2d = bpy_extras.view3d_utils.location_3d_to_region_2d(
            region, rv3d, p)
        bgl.glVertex3f(p[0], p[1], p[2])
        bgl.glEnd()

    restore_opengl_defaults()
Пример #38
0
 def _end(self):
     bgl.glEnd()
     bgl.glPopAttrib()
     bgl.glLineWidth(1)
     bgl.glDisable(bgl.GL_BLEND)
     bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #39
0
 def draw_callback(self, op, context):
     bgl.glLineWidth(4)
     self.shader.bind()
     self.shader.uniform_float("color", (1, 1, 1))
     self.batch.draw(self.shader)
Пример #40
0
def draw_callback_2d(self, context):
    """Callback function for 2d drawing.
    """
    active = context.object
    selected = context.selected_objects
    if active and selected:
        objects = set(selected + [active])
    else:
        objects = []
    wm = context.window_manager

    # code that can be used to draw on 2d surface in 3d mode, not used any more
    # due to separate handlers for 2d and 3d
    # bgl.glMatrixMode(bgl.GL_PROJECTION)
    # bgl.glLoadIdentity()
    # bgl.gluOrtho2D(0, bpy.context.region.width, 0, bpy.context.region.height)
    # bgl.glMatrixMode(bgl.GL_MODELVIEW)
    # bgl.glLoadIdentity()

    bgl.glEnable(bgl.GL_BLEND)

    # submechanisms
    if objects and wm.draw_submechanisms:
        groupedobjects = [o for o in objects if hasattr(o, 'users_group')]
        # draw spanning tree
        submechanism_groups = set([
            group for obj in groupedobjects for group in obj.users_group
            if group.name.startswith('submechanism:')
        ])
        for group in submechanism_groups:
            for joint in group.objects:
                if 'submechanism/spanningtree' in joint:
                    draw_path(joint['submechanism/spanningtree'],
                              color=colors['submechanism'])
                    #joint['submechanism/independent'],
                    #joint['submechanism/active'])
        # draw labels
        for obj in [obj for obj in objects if obj.phobostype == 'link']:
            if 'submechanism/jointname' in obj:
                origin = to2d(obj.matrix_world.translation)
                draw_textbox(obj['submechanism/jointname'],
                             origin,
                             textsize=6,
                             textcolor=colors['dark_grey'],
                             backgroundcolor=(*colors['submechanism'][:3],
                                              0.7),
                             offset=Vector((16, 0)))
                draw_textbox(nUtils.getObjectName(obj, 'joint'),
                             origin,
                             textsize=6,
                             textcolor=colors['dark_grey'],
                             backgroundcolor=colors['bright_background'],
                             rightalign=True,
                             offset=Vector((-16, 0)))

    # interfaces
    if selected:
        for interface in [
                obj for obj in selected if obj.phobostype == 'interface'
        ]:
            color = interface.active_material.diffuse_color
            maxc = max(color)
            color = [0.6 + c / maxc * 0.4 for c in color]
            bgcolor = [
                c * 0.4 for c in interface.active_material.diffuse_color
            ]
            draw_textbox(nUtils.getObjectName(interface),
                         to2d(interface.matrix_world.translation),
                         textsize=6,
                         textcolor=(*color,
                                    1.0 if interface.show_name else 0.4),
                         backgroundcolor=(*bgcolor, 1.0)
                         if interface.show_name else colors['background'],
                         linewidth=3 if interface.show_name else 2)

    # progress bar
    if wm.draw_progress and context.window_manager.progress not in [0, 1]:
        draw_progressbar(wm.progress)

    # log messages
    if wm.draw_messages:
        for m in range(wm.phobos_msg_count):
            opacity = 1.0
            if 1 >= m <= wm.phobos_msg_offset - 1 or m >= wm.phobos_msg_count - 2:
                opacity = 0.5
            if wm.phobos_msg_offset > 1 > m or m >= wm.phobos_msg_count - 1:
                opacity = 0.1
            try:
                msg = messages[m + wm.phobos_msg_offset]
                draw_message(msg['text'],
                             msg['type'],
                             m,
                             opacity,
                             offset=wm.phobos_msg_offset)
            except IndexError:
                pass

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #41
0
def draw_callback_px(self, context):

    if not context.window_manager.jewelcraft.widget_toggle or context.space_data.show_only_render:
        return

    prefs = context.user_preferences.addons[var.ADDON_ID].preferences
    use_ovrd = prefs.widget_use_overrides
    default_settings = {
        "color": prefs.widget_color,
        "linewidth": prefs.widget_linewidth,
        "distance": prefs.widget_distance,
    }
    obs = context.selected_objects if prefs.widget_selection_only else context.visible_objects
    key = "jewelcraft_widget" if use_ovrd and prefs.widget_overrides_only else "gem"

    bgl.glEnable(bgl.GL_BLEND)

    if prefs.widget_x_ray:
        bgl.glDisable(bgl.GL_DEPTH_TEST)

    for ob in obs:
        if key in ob:
            settings = default_settings.copy()

            if use_ovrd and "jewelcraft_widget" in ob:
                settings.update(ob["jewelcraft_widget"])

            bgl.glLineWidth(settings["linewidth"])
            bgl.glColor4f(*settings["color"])
            radius = max(ob.dimensions[:2]) / 2 + settings["distance"]

            mat_loc = Matrix.Translation(ob.matrix_world.translation)
            mat_rot = ob.matrix_world.to_quaternion().to_matrix().to_4x4()
            mat = mat_loc * mat_rot

            coords = circle_coords(radius)

            bgl.glBegin(bgl.GL_LINE_LOOP)
            for co in coords:
                bgl.glVertex3f(*(mat * co))
            bgl.glEnd()

            # Duplifaces
            # ----------------------------

            if ob.parent and ob.parent.dupli_type == "FACES":

                ob.parent.dupli_list_create(context.scene)

                for dup in ob.parent.dupli_list:
                    if dup.object == ob:
                        mat = dup.matrix
                        bgl.glBegin(bgl.GL_LINE_LOOP)
                        for co in coords:
                            bgl.glVertex3f(*(mat * co))
                        bgl.glEnd()

                ob.parent.dupli_list_clear()

    # Restore OpenGL defaults
    # ----------------------------

    bgl.glLineWidth(1)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_DEPTH_TEST)
Пример #42
0
def draw_callback_px(self, context):
	font_id = 0
	region = context.region
	UIColor = (0.992, 0.5518, 0.0, 1.0)

	# Cut Type
	RECTANGLE = 0
	LINE = 1
	CIRCLE = 2
	self.carver_prefs = context.preferences.addons[__package__].preferences

	# Color
	color1 = (1.0, 1.0, 1.0, 1.0)
	color2 = UIColor

	#The mouse is outside the active region
	if not self.in_view_3d:
		color1 = color2 = (1.0, 0.2, 0.1, 1.0)

	# Primitives type
	PrimitiveType = "Rectangle"
	if self.CutType == CIRCLE:
		PrimitiveType = "Circle"
	if self.CutType == LINE:
		PrimitiveType = "Line"

	# Width screen
	overlap = context.preferences.system.use_region_overlap

	t_panel_width = 0
	if overlap:
		for region in context.area.regions:
			if region.type == 'TOOLS':
				t_panel_width = region.width

	# Initial position
	region_width = int(region.width / 2.0)
	y_txt = 10


	# Draw the center command from bottom to top

	# Get the size of the text
	text_size = 18 if region.width >= 850 else 12
	blf.size(0, int(round(text_size * bpy.context.preferences.view.ui_scale, 0)), 72)

	# Help Display
	if (self.ObjectMode is False) and (self.ProfileMode is False):

		# Depth Cursor
		TypeStr = "Cursor Depth [" + self.carver_prefs.Key_Depth + "]"
		BoolStr = "(ON)" if self.snapCursor else "(OFF)"
		help_txt = [[TypeStr, BoolStr]]

		# Close poygonal shape
		if self.CreateMode and self.CutType == LINE:
			TypeStr = "Close [" + self.carver_prefs.Key_Close + "]"
			BoolStr = "(ON)" if self.Closed else "(OFF)"
			help_txt += [[TypeStr, BoolStr]]

		if self.CreateMode is False:
			# Apply Booleans
			TypeStr = "Apply Operations [" + self.carver_prefs.Key_Apply + "]"
			BoolStr = "(OFF)" if self.dont_apply_boolean else "(ON)"
			help_txt += [[TypeStr, BoolStr]]

			#Auto update for bevel
			TypeStr = "Bevel Update [" + self.carver_prefs.Key_Update + "]"
			BoolStr = "(ON)" if self.Auto_BevelUpdate else "(OFF)"
			help_txt += [[TypeStr, BoolStr]]

		# Circle subdivisions
		if self.CutType == CIRCLE:
			TypeStr = "Subdivisions [" + self.carver_prefs.Key_Subrem + "][" + self.carver_prefs.Key_Subadd + "]"
			BoolStr = str((int(360 / self.stepAngle[self.step])))
			help_txt += [[TypeStr, BoolStr]]

		if self.CreateMode:
			help_txt += [["Type [Space]", PrimitiveType]]
		else:
			help_txt += [["Cut Type [Space]", PrimitiveType]]

	else:
		# Instantiate
		TypeStr = "Instantiate [" + self.carver_prefs.Key_Instant + "]"
		BoolStr = "(ON)" if self.Instantiate else "(OFF)"
		help_txt = [[TypeStr, BoolStr]]

		# Random rotation
		if self.alt:
			TypeStr = "Random Rotation [" + self.carver_prefs.Key_Randrot + "]"
			BoolStr = "(ON)" if self.RandomRotation else "(OFF)"
			help_txt += [[TypeStr, BoolStr]]

		# Thickness
		if self.BrushSolidify:
			TypeStr = "Thickness [" + self.carver_prefs.Key_Depth + "]"
			if self.ProfileMode:
				BoolStr = str(round(self.ProfileBrush.modifiers["CT_SOLIDIFY"].thickness, 2))
			if self.ObjectMode:
				BoolStr = str(round(self.ObjectBrush.modifiers["CT_SOLIDIFY"].thickness, 2))
			help_txt += [[TypeStr, BoolStr]]

		# Brush depth
		if (self.ObjectMode):
			TypeStr = "Carve Depth [" + self.carver_prefs.Key_Depth + "]"
			BoolStr = str(round(self.ObjectBrush.data.vertices[0].co.z, 2))
			help_txt += [[TypeStr, BoolStr]]

			TypeStr = "Brush Depth [" + self.carver_prefs.Key_BrushDepth + "]"
			BoolStr = str(round(self.BrushDepthOffset, 2))
			help_txt += [[TypeStr, BoolStr]]

	help_txt, bloc_height, max_option, max_key, comma = get_text_info(self, context, help_txt)
	xCmd = region_width - (max_option + max_key + comma) / 2
	draw_string(self, color1, color2, xCmd, y_txt, help_txt, max_option, divide = 2)


	# Separator (Line)
	LineWidth = (max_option + max_key + comma) / 2
	if region.width >= 850:
		LineWidth = 140

	LineWidth = (max_option + max_key + comma)
	coords = [(int(region_width - LineWidth/2), y_txt + bloc_height + 8), \
			  (int(region_width + LineWidth/2), y_txt + bloc_height + 8)]
	draw_shader(self, UIColor, 1, 'LINES', coords, self.carver_prefs.LineWidth)

	# Command Display
	if self.CreateMode and ((self.ObjectMode is False) and (self.ProfileMode is False)):
		BooleanMode = "Create"
	else:
		if self.ObjectMode or self.ProfileMode:
			BooleanType = "Difference) [T]" if self.BoolOps == self.difference else "Union) [T]"
			BooleanMode = \
				"Object Brush (" + BooleanType if self.ObjectMode else "Profil Brush (" + BooleanType
		else:
			BooleanMode = \
				"Difference" if (self.shift is False) and (self.ForceRebool is False) else "Rebool"

	# Display boolean mode
	text_size = 40 if region.width >= 850 else 20
	blf.size(0, int(round(text_size * bpy.context.preferences.view.ui_scale, 0)), 72)

	draw_string(self, color2, color2, region_width - (blf.dimensions(0, BooleanMode)[0]) / 2, \
				y_txt + bloc_height + 16, BooleanMode, 0, divide = 2)

	if region.width >= 850:

		if self.AskHelp is False:
			# "H for Help" text
			blf.size(0, int(round(13 * bpy.context.preferences.view.ui_scale, 0)), 72)
			help_txt = "[" + self.carver_prefs.Key_Help + "] for help"
			txt_width = blf.dimensions(0, help_txt)[0]
			txt_height = (blf.dimensions(0, "gM")[1] * 1.45)

			# Draw a rectangle and put the text "H for Help"
			xrect = 40
			yrect = 40
			rect_vertices = [(xrect - 5, yrect - 5), (xrect + txt_width + 5, yrect - 5), \
							 (xrect + txt_width + 5, yrect + txt_height + 5), (xrect - 5, yrect + txt_height + 5)]
			draw_shader(self, (0.0, 0.0, 0.0),  0.3, 'TRI_FAN', rect_vertices, self.carver_prefs.LineWidth)
			draw_string(self, color1, color2, xrect, yrect, help_txt, 0)

		else:
			#Draw the help text
			xHelp = 30 + t_panel_width
			yHelp = 10

			if self.ObjectMode or self.ProfileMode:
				if self.ProfileMode:
					help_txt = [["Object Mode", self.carver_prefs.Key_Brush]]
				else:
					help_txt = [["Cut Mode", self.carver_prefs.Key_Brush]]

			else:
				help_txt =[
					  ["Profil Brush", self.carver_prefs.Key_Brush],\
					  ["Move Cursor", "Ctrl + LMB"]
					  ]

			if (self.ObjectMode is False) and (self.ProfileMode is False):
				if self.CreateMode is False:
					help_txt +=[
						   ["Create geometry", self.carver_prefs.Key_Create],\
						   ]
				else:
					help_txt +=[
						   ["Cut", self.carver_prefs.Key_Create],\
						   ]
				if self.CutMode == RECTANGLE:
					help_txt +=[
						   ["Dimension", "MouseMove"],\
						   ["Move all", "Alt"],\
						   ["Validate", "LMB"],\
						   ["Rebool", "Shift"]
						   ]

				elif self.CutMode == CIRCLE:
					help_txt +=[
						   ["Rotation and Radius", "MouseMove"],\
						   ["Move all", "Alt"],\
						   ["Subdivision", self.carver_prefs.Key_Subrem + " " + self.carver_prefs.Key_Subadd],\
						   ["Incremental rotation", "Ctrl"],\
						   ["Rebool", "Shift"]
						   ]

				elif self.CutMode == LINE:
					help_txt +=[
						   ["Dimension", "MouseMove"],\
						   ["Move all", "Alt"],\
						   ["Validate", "Space"],\
						   ["Rebool", "Shift"],\
						   ["Snap", "Ctrl"],\
						   ["Scale Snap", "WheelMouse"],\
						   ]
			else:
				# ObjectMode
				help_txt +=[
					   ["Difference", "Space"],\
					   ["Rebool", "Shift + Space"],\
					   ["Duplicate", "Alt + Space"],\
					   ["Scale", self.carver_prefs.Key_Scale],\
					   ["Rotation", "LMB + Move"],\
					   ["Step Angle", "CTRL + LMB + Move"],\
					   ]

				if self.ProfileMode:
					help_txt +=[["Previous or Next Profile", self.carver_prefs.Key_Subadd + " " + self.carver_prefs.Key_Subrem]]

				help_txt +=[
					   ["Create / Delete rows",  chr(8597)],\
					   ["Create / Delete cols",  chr(8596)],\
					   ["Gap for rows or columns",  self.carver_prefs.Key_Gapy + " " + self.carver_prefs.Key_Gapx]
					   ]

			blf.size(0, int(round(15 * bpy.context.preferences.view.ui_scale, 0)), 72)
			help_txt, bloc_height, max_option, max_key, comma = get_text_info(self, context, help_txt)
			draw_string(self, color1, color2, xHelp, yHelp, help_txt, max_option)

	if self.ProfileMode:
		xrect = region.width - t_panel_width - 80
		yrect = 80
		coords = [(xrect, yrect), (xrect+60, yrect), (xrect+60, yrect-60), (xrect, yrect-60)]

		# Draw rectangle background in the lower right
		draw_shader(self, (0.0, 0.0, 0.0),  0.3, 'TRI_FAN', coords, size=self.carver_prefs.LineWidth)

		# Use numpy to get the vertices and indices of the profile object to draw
		WidthProfil = 50
		location = Vector((region.width - t_panel_width - WidthProfil, 50, 0))
		ProfilScale = 20.0
		coords = []
		mesh = bpy.data.meshes[self.Profils[self.nProfil][0]]
		mesh.calc_loop_triangles()
		vertices = np.empty((len(mesh.vertices), 3), 'f')
		indices = np.empty((len(mesh.loop_triangles), 3), 'i')
		mesh.vertices.foreach_get("co", np.reshape(vertices, len(mesh.vertices) * 3))
		mesh.loop_triangles.foreach_get("vertices", np.reshape(indices, len(mesh.loop_triangles) * 3))

		for idx, vals in enumerate(vertices):
			coords.append([
			vals[0] * ProfilScale + location.x,
			vals[1] * ProfilScale + location.y,
			vals[2] * ProfilScale + location.z
			])

		#Draw the silhouette of the mesh
		draw_shader(self, UIColor,  0.5, 'TRIS', coords, size=self.carver_prefs.LineWidth, indices=indices)


	if self.CutMode:

		if len(self.mouse_path) > 1:
			x0 = self.mouse_path[0][0]
			y0 = self.mouse_path[0][1]
			x1 = self.mouse_path[1][0]
			y1 = self.mouse_path[1][1]

		# Cut rectangle
		if self.CutType == RECTANGLE:
			coords = [
			(x0 + self.xpos, y0 + self.ypos), (x1 + self.xpos, y0 + self.ypos), \
			(x1 + self.xpos, y1 + self.ypos), (x0 + self.xpos, y1 + self.ypos)
			]
			indices = ((0, 1, 2), (2, 0, 3))

			self.rectangle_coord = coords

			draw_shader(self, UIColor, 1, 'LINE_LOOP', coords, size=self.carver_prefs.LineWidth)

			#Draw points
			draw_shader(self, UIColor, 1, 'POINTS', coords, size=3)

			if self.shift or self.CreateMode:
				draw_shader(self, UIColor, 0.5, 'TRIS', coords, size=self.carver_prefs.LineWidth, indices=indices)

			# Draw grid (based on the overlay options) to show the incremental snapping
			if self.ctrl:
				mini_grid(self, context, UIColor)

		# Cut Line
		elif self.CutType == LINE:
			coords = []
			indices = []
			top_grid = False

			for idx, vals in enumerate(self.mouse_path):
				coords.append([vals[0] + self.xpos, vals[1] + self.ypos])
				indices.append([idx])

			# Draw lines
			if self.Closed:
				draw_shader(self, UIColor, 1.0, 'LINE_LOOP', coords, size=self.carver_prefs.LineWidth)
			else:
				draw_shader(self, UIColor, 1.0, 'LINE_STRIP', coords, size=self.carver_prefs.LineWidth)

			# Draw points
			draw_shader(self, UIColor, 1.0, 'POINTS', coords, size=3)

			# Draw polygon
			if (self.shift) or (self.CreateMode and self.Closed):
				draw_shader(self, UIColor, 0.5, 'TRI_FAN', coords, size=self.carver_prefs.LineWidth)

			# Draw grid (based on the overlay options) to show the incremental snapping
			if self.ctrl:
				mini_grid(self, context, UIColor)

		# Circle Cut
		elif self.CutType == CIRCLE:
			# Create a circle using a tri fan
			tris_coords, indices = draw_circle(self, x0, y0)

			# Remove the vertex in the center to get the outer line of the circle
			line_coords = tris_coords[1:]
			draw_shader(self, UIColor, 1.0, 'LINE_LOOP', line_coords, size=self.carver_prefs.LineWidth)

			if self.shift or self.CreateMode:
				draw_shader(self, UIColor, 0.5, 'TRIS', tris_coords, size=self.carver_prefs.LineWidth, indices=indices)

	if (self.ObjectMode or self.ProfileMode) and len(self.CurrentSelection) > 0:
		if self.ShowCursor:
			region = context.region
			rv3d = context.space_data.region_3d

			if self.ObjectMode:
				ob = self.ObjectBrush
			if self.ProfileMode:
				ob = self.ProfileBrush
			mat = ob.matrix_world

			# 50% alpha, 2 pixel width line
			bgl.glEnable(bgl.GL_BLEND)

			bbox = [mat @ Vector(b) for b in ob.bound_box]
			objBBDiagonal = objDiagonal(self.CurrentSelection[0])

			if self.shift:
				gl_size = 4
				UIColor = (0.5, 1.0, 0.0, 1.0)
			else:
				gl_size = 2
				UIColor = (1.0, 0.8, 0.0, 1.0)

			line_coords = []
			idx = 0
			CRadius = ((bbox[7] - bbox[0]).length) / 2
			for i in range(int(len(self.CLR_C) / 3)):
				vector3d = (self.CLR_C[idx * 3] * CRadius + self.CurLoc.x, \
							self.CLR_C[idx * 3 + 1] * CRadius + self.CurLoc.y, \
							self.CLR_C[idx * 3 + 2] * CRadius + self.CurLoc.z)
				vector2d = bpy_extras.view3d_utils.location_3d_to_region_2d(region, rv3d, vector3d)
				if vector2d is not None:
					line_coords.append((vector2d[0], vector2d[1]))
				idx += 1
			if len(line_coords) > 0 :
				draw_shader(self, UIColor, 1.0, 'LINE_LOOP', line_coords, size=gl_size)

			# Object display
			if self.quat_rot is not None:
				ob.location = self.CurLoc
				v = Vector()
				v.x = v.y = 0.0
				v.z = self.BrushDepthOffset
				ob.location += self.quat_rot @ v

				e = Euler()
				e.x = 0.0
				e.y = 0.0
				e.z = self.aRotZ / 25.0

				qe = e.to_quaternion()
				qRot = self.quat_rot @ qe
				ob.rotation_mode = 'QUATERNION'
				ob.rotation_quaternion = qRot
				ob.rotation_mode = 'XYZ'

				if self.ProfileMode:
					if self.ProfileBrush is not None:
						self.ProfileBrush.location = self.CurLoc
						self.ProfileBrush.rotation_mode = 'QUATERNION'
						self.ProfileBrush.rotation_quaternion = qRot
						self.ProfileBrush.rotation_mode = 'XYZ'

	# Opengl defaults
	bgl.glLineWidth(1)
	bgl.glDisable(bgl.GL_BLEND)
Пример #43
0
def draw_line_strip_batch(batch, color, thickness=1):
    shader = get_uniform_color_shader()
    bgl.glLineWidth(thickness)
    shader.bind()
    shader.uniform_float("color", color)
    batch.draw(shader)
Пример #44
0
    def draw_callback(cls, context):
        # FIXME: 起動中にaddonを無効にした場合,get_instance()が例外を吐く
        prefs = ScreenCastKeysPreferences.get_instance()
        """:type: ScreenCastKeysPreferences"""

        if context.window.as_pointer() != cls.origin['window']:
            return
        rect = cls.calc_draw_rectangle(context)
        if not rect:
            return
        xmin, ymin, xmax, ymax = rect
        win, _area, _region, x, y = cls.get_origin(context)
        w = xmax - x
        h = ymax - y
        if w == h == 0:
            return
        region = context.region
        area = context.area
        if region.type == 'WINDOW':
            r_xmin, r_ymin, r_xmax, r_ymax = region_window_rectangle(area)
        else:
            r_xmin, r_ymin, r_xmax, r_ymax = (
                region.x,
                region.y,
                region.x + region.width - 1,
                region.y + region.height - 1)
        if not intersect_aabb(
                (r_xmin, r_ymin), (r_xmax, r_ymax),
                (xmin + 1, ymin + 1), (xmax - 1, ymax - 1)):
            return

        current_time = time.time()
        draw_any = False

        font_size = prefs.font_size
        font_id = 0
        dpi = context.user_preferences.system.dpi
        blf.size(font_id, font_size, dpi)

        def draw_text(text):
            col = prefs.color_shadow
            bgl.glColor4f(*col[:3], col[3] * 20)
            blf.blur(font_id, 5)
            blf.draw(font_id, text)
            blf.blur(font_id, 0)

            bgl.glColor3f(*prefs.color)
            blf.draw(font_id, text)

        def draw_line(p1, p2):
            bgl.glEnable(bgl.GL_BLEND)
            bgl.glEnable(bgl.GL_LINE_SMOOTH)

            bgl.glLineWidth(3.0)
            bgl.glColor4f(*prefs.color_shadow)
            bgl.glBegin(bgl.GL_LINES)
            bgl.glVertex2f(*p1)
            bgl.glVertex2f(*p2)
            bgl.glEnd()

            bgl.glLineWidth(1.0 if prefs.color_shadow[-1] == 0.0 else 1.5)
            bgl.glColor3f(*prefs.color)
            bgl.glBegin(bgl.GL_LINES)
            bgl.glVertex2f(*p1)
            bgl.glVertex2f(*p2)
            bgl.glEnd()

            bgl.glLineWidth(1.0)
            bgl.glDisable(bgl.GL_LINE_SMOOTH)

        # user_preferences.system.use_region_overlapが真の場合に、
        # 二重に描画されるのを防ぐ
        glscissorbox = bgl.Buffer(bgl.GL_INT, 4)
        bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, glscissorbox)
        if context.area.type == 'VIEW_3D' and region.type == 'WINDOW':
            xmin, ymin, xmax, ymax = region_rectangle_v3d(context)
            bgl.glScissor(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1)

        th = blf.dimensions(0, string.printable)[1]
        px = x - region.x
        py = y - region.y

        operator_log = cls.removed_old_operator_log()
        if prefs.show_last_operator and operator_log:
            t, name, idname_py, addr = operator_log[-1]
            if current_time - t <= prefs.display_time:
                color = prefs.color
                bgl.glColor3f(*color)

                text = bpy.app.translations.pgettext_iface(name, 'Operator')
                text += " ('{}')".format(idname_py)

                blf.position(font_id, px, py, 0)
                draw_text(text)
                py += th + th * cls.SEPARATOR_HEIGHT * 0.2
                tw = blf.dimensions(font_id, 'Left Mouse')[0]  # 適当
                draw_line((px, py), (px + tw, py))
                py += th * cls.SEPARATOR_HEIGHT * 0.8

                draw_any = True

            else:
                py += th + th * cls.SEPARATOR_HEIGHT

        bgl.glColor3f(*prefs.color)
        if cls.hold_keys or mhm.is_rendering():
            col = prefs.color_shadow[:3] + (prefs.color_shadow[3] * 2,)
            mod_names = cls.sorted_modifiers(cls.hold_keys)
            if mhm.is_rendering():
                if 0:
                    text = '- - -'
                else:
                    text = ''
            else:
                text = ' + '.join(mod_names)
            blf.position(font_id, px, py, 0)
            # blf.draw(font_id, text)
            draw_text(text)
            py += th
            draw_any = True
        else:
            py += th

        event_log = cls.removed_old_event_log()

        if cls.hold_keys or event_log:
            py += th * cls.SEPARATOR_HEIGHT * 0.2
            tw = blf.dimensions(font_id, 'Left Mouse')[0]  # 適当
            draw_line((px, py), (px + tw, py))
            py += th * cls.SEPARATOR_HEIGHT * 0.8
            draw_any = True
        else:
            py += th * cls.SEPARATOR_HEIGHT

        for event_time, event_type, modifiers, count in event_log[::-1]:
            color = prefs.color
            bgl.glColor3f(*color)

            text = event_type.names[event_type.name]
            if modifiers:
                mod_names = cls.sorted_modifiers(modifiers)
                text = ' + '.join(mod_names) + ' + ' + text
            if count > 1:
                text += ' x' + str(count)
            blf.position(font_id, px, py, 0)
            # blf.draw(font_id, text)
            draw_text(text)

            py += th
            draw_any = True

        bgl.glDisable(bgl.GL_BLEND)
        bgl.glScissor(*glscissorbox)
        bgl.glLineWidth(1.0)
        # blf.disable(font_id, blf.SHADOW)

        if draw_any:
            cls.draw_regions_prev.add(region.as_pointer())
Пример #45
0
def DRAW_Overlay(self, context):

    np_print('DRAW_Overlay_START', ';', 'NP020FB.flag = ', NP020FB.flag)
    '''
    addon_prefs = context.user_preferences.addons[__package__].preferences
    badge = addon_prefs.npfb_badge
    badge_size = addon_prefs.npfb_badge_size
    dist_scale = addon_prefs.npfb_dist_scale
    '''
    flag = NP020FB.flag
    helper = NP020FB.helper
    matrix = helper.matrix_world.to_3x3()
    region = bpy.context.region
    rv3d = bpy.context.region_data
    rw = region.width
    rh = region.height
    qdef = NP020FB.qdef
    ndef = NP020FB.ndef
    ro_hor_def = NP020FB.ro_hor_def
    constrain = NP020FB.constrain
    np_print('rw, rh', rw, rh)
    rmin = int(min(rw, rh) / 50)
    if rmin == 0: rmin = 1
    co2d = view3d_utils.location_3d_to_region_2d(region, rv3d, helper.location)
    if qdef != None and constrain == False:
        q = qdef
        n = ndef
        pointloc = helper.location
        ro_hor = ro_hor_def

    elif qdef != None and constrain == True:
        q = qdef
        n = ndef
        pointloc = get_ro_normal_from_vertical(region, rv3d, co2d)[2]
        ro_hor = ro_hor_def

    else:
        q = get_ro_normal_from_vertical(region, rv3d, co2d)[1]
        n = get_ro_normal_from_vertical(region, rv3d, co2d)[0]
        pointloc = get_ro_normal_from_vertical(region, rv3d, co2d)[2]
        ro_hor, isohipse = get_ro_x_from_iso(region, rv3d, co2d,
                                             helper.location)

    if pointloc == Vector((0.0, 0.0, 0.0)): pointloc = helper.location
    np_print('n / q', n, q)
    NP020FB.q = q
    NP020FB.n = n
    NP020FB.pointloc = pointloc
    NP020FB.ro_hor = ro_hor
    np_print('co2d, n, q', co2d, n, q)

    # Acquiring factor for graphics scaling in order to be space - independent

    fac = get_fac_from_view_loc_plane(region, rv3d, rmin, helper.location, q)
    NP020FB.fac = fac

    symbol = [[18, 37], [21, 37], [23, 33], [26, 33]]
    badge_mode = 'RUN'

    if qdef != None:
        matrix.rotate(ro_hor)
        matrix.rotate(qdef)
    NP020FB.matrix = matrix

    if flag == 'RUNTRANS0':
        instruct = 'choose plane / place corner point'
        keys_aff = 'LMB - select, CTRL - snap, ENT - lock plane'
        keys_nav = ''
        keys_neg = 'ESC, RMB - quit'
        box = [
            helper.location, helper.location, helper.location, helper.location,
            helper.location, helper.location, helper.location, helper.location
        ]

        message_main = 'CTRL+SNAP'
        message_aux = None
        aux_num = None
        aux_str = None

    elif flag == 'RUNTRANS1':
        instruct = 'define the width of the box'
        keys_aff = 'LMB - select, CTRL - snap, NUMPAD - value'
        keys_nav = ''
        keys_neg = 'ESC, RMB - quit'
        p0 = NP020FB.p0
        box = [
            p0, helper.location, helper.location, p0, p0, helper.location,
            helper.location, p0
        ]

        message_main = 'CTRL+SNAP'
        message_aux = None
        aux_num = None
        aux_str = None

    elif flag == 'RUNTRANS2':
        instruct = 'define the length of the box'
        keys_aff = 'LMB - select, CTRL - snap, NUMPAD - value'
        keys_nav = ''
        keys_neg = 'ESC, RMB - quit'
        p0 = NP020FB.p0
        p1 = NP020FB.p1
        box = [
            p0, p1, helper.location, p0 + (helper.location - p1), p0, p1,
            helper.location, p0 + (helper.location - p1)
        ]

        message_main = 'CTRL+SNAP'
        message_aux = None
        aux_num = None
        aux_str = None

    elif flag == 'RUNTRANS3':
        instruct = 'define the height of the box'
        keys_aff = 'LMB - select, CTRL - snap, NUMPAD - value'
        keys_nav = ''
        keys_neg = 'ESC, RMB - quit'
        p0 = NP020FB.p0
        p1 = NP020FB.p1
        p2 = NP020FB.p2
        p3 = p0 + (p2 - p1)
        h = helper.location - p2
        box = [p0, p1, p2, p3, p0 + h, p1 + h, p2 + h, p3 + h]

        message_main = 'CTRL+SNAP'
        message_aux = None
        aux_num = None
        aux_str = None

    NP020FB.box = box

    # ON-SCREEN INSTRUCTIONS:

    display_instructions(region, rv3d, instruct, keys_aff, keys_nav, keys_neg)

    # drawing of box:

    box_2d = []
    for co in box:
        co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
        box_2d.append(co)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
    bgl.glLineWidth(1)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i in range(0, 4):
        bgl.glVertex2f(*box_2d[i])
    bgl.glVertex2f(*box_2d[0])
    bgl.glVertex2f(*box_2d[4])
    bgl.glVertex2f(*box_2d[7])
    bgl.glVertex2f(*box_2d[3])
    bgl.glVertex2f(*box_2d[7])
    bgl.glVertex2f(*box_2d[6])
    bgl.glVertex2f(*box_2d[2])
    bgl.glVertex2f(*box_2d[6])
    bgl.glVertex2f(*box_2d[5])
    bgl.glVertex2f(*box_2d[1])
    bgl.glVertex2f(*box_2d[5])
    bgl.glVertex2f(*box_2d[4])
    bgl.glEnd()
    bgl.glColor4f(1.0, 1.0, 1.0, 0.25)
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    boxfaces = ((0, 1, 2, 3), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6),
                (3, 0, 4, 7), (4, 5, 6, 7))
    for face in boxfaces:
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        bgl.glVertex2f(*box_2d[face[0]])
        bgl.glVertex2f(*box_2d[face[1]])
        bgl.glVertex2f(*box_2d[face[2]])
        bgl.glVertex2f(*box_2d[face[3]])
        bgl.glEnd()

    # Drawing the small badge near the cursor with the basic instructions:

    display_cursor_badge(co2d, symbol, badge_mode, message_main, message_aux,
                         aux_num, aux_str)

    # writing the dots for boxwidget widget at center of scene:

    geowidget_base = [(0.0, 0.0, 0.0), (5.0, 0.0, 0.0), (5.0, -3.0, 0.0),
                      (0.0, -3.0, 0.0)]
    geowidget_top = [(0.0, 0.0, 4.0), (5.0, 0.0, 4.0), (5.0, -3.0, 4.0),
                     (0.0, -3.0, 4.0)]
    geowidget_rest = [(0.0, 0.0, 0.0), (0.0, 0.0, 4.0), (5.0, 0.0, 4.0),
                      (5.0, 0.0, 0.0), (5.0, -3.0, 0.0), (5.0, -3.0, 4.0),
                      (0.0, -3.0, 4.0), (0.0, -3.0, 0.0)]

    # ON-SCREEN DISPLAY OF GEOWIDGET:

    display_geowidget(region, rv3d, fac, ro_hor, q, helper.location, n, qdef,
                      geowidget_base, geowidget_top, geowidget_rest)

    # ON-SCREEN DISTANCES AND OTHERS:
    '''

    if addon_prefs.npfb_suffix == 'None':
        suffix = None

    elif addon_prefs.npfb_suffix == 'km':
        suffix = ' km'

    elif addon_prefs.npfb_suffix == 'm':
        suffix = ' m'

    elif addon_prefs.npfb_suffix == 'cm':
        suffix = ' cm'

    elif addon_prefs.npfb_suffix == 'mm':
        suffix = ' mm'

    elif addon_prefs.npfb_suffix == 'nm':
        suffix = ' nm'

    elif addon_prefs.npfb_suffix == "'":
        suffix = "'"

    elif addon_prefs.npfb_suffix == '"':
        suffix = '"'

    elif addon_prefs.npfb_suffix == 'thou':
        suffix = ' thou'
    '''

    # ON-SCREEN DISTANCES:

    display_distance_between_two_points(region, rv3d, box[0], box[1])
    display_distance_between_two_points(region, rv3d, box[1], box[2])
    display_distance_between_two_points(region, rv3d, box[2], box[6])

    #ENDING:

    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #46
0
    def draw_item(self, item, index, active, enabled, highlight):
        prefs = self.prefs
        menu = self.menu
        current_items = menu.current_items

        colors = prefs.colors
        widget_unit = self.widget_unit

        num = len(current_items)
        if index == 0:
            direction = "top"
        elif num % 2 == 0 and index == int(num / 2):
            direction = "bottom"
        elif index < num / 2:
            direction = "right"
        else:
            direction = "left"

        icon_box = item.icon_box_rect
        text_box = item.text_box_rect

        if active:
            col = colors.item_inner_sel
            if not enabled:
                col = vagl.thin_color(col, 0.5)  # TODO: 調整
        else:
            col = colors.item_inner
        if colors.item_show_shaded:
            col_box_top, col_box_bottom = vagl.shade_color(
                col, colors.item_shadetop, colors.item_shadedown)
        else:
            col_box_top = col_box_bottom = col

        if menu.draw_type == 'SIMPLE':
            icon_box_poly_coords = line_coords_icon = []
            icon_size = self.icon_size
        else:
            u1, v1, u2, v2 = icon_box
            if menu.draw_type == 'BOX':
                icon_box_poly_coords = line_coords_icon = (
                    self.round_corner([u1, v1], "bottom_left") +
                    self.round_corner([u2, v1], "bottom_right") +
                    self.round_corner([u2, v2], "top_right") +
                    self.round_corner([u1, v2], "top_left")
                )

                f = self.widget_unit - self.icon_size
                icon_expand = min(max(0.0, menu.icon_expand), 1.0)
                icon_size = self.icon_size + f * icon_expand
            else:
                icon_box_poly_coords = line_coords_icon = []
                subdivide = 32
                radius = (u2 - u1) / 2
                angle = math.pi
                ang = math.pi * 2 / subdivide
                icon_center = (u1 + u2) / 2, (v1 + v2) / 2
                for i in range(subdivide):
                    co = [icon_center[0] + radius * math.cos(angle),
                          icon_center[1] + radius * math.sin(angle)]
                    icon_box_poly_coords.append(co)
                    angle += ang

                icon_expand = min(max(-1.0, menu.icon_expand), 1.0)
                if icon_expand > 0:
                    f = self.widget_unit - self.icon_size
                    icon_size = self.icon_size + f * icon_expand
                else:
                    f = self.icon_size - self.widget_unit * math.sin(math.pi / 4)
                    icon_size = self.icon_size - f * -icon_expand
            icon_size *= menu.icon_scale

        if text_box:
            x1, y1, x2, y2 = text_box
            bottom_left = self.round_corner([x1, y1], "bottom_left")
            bottm_right = self.round_corner([x2, y1], "bottom_right")
            top_right = self.round_corner([x2, y2], "top_right")
            top_left = self.round_corner([x1, y2], "top_left")
            text_box_poly_coords = line_coords = (
                top_left + bottom_left + bottm_right + top_right)
        else:
            text_box_poly_coords = line_coords = []

        if colors.menu_show_shaded:
            _, text_box_rect_top = self.calc_item_rect(0, "DUMMY", "")
            _, text_box_rect_down = self.calc_item_rect(
                int(len(current_items) / 2), "DUMMY", "")
            menu_ymax = text_box_rect_top[3]
            menu_ymin = text_box_rect_down[1]
            col_menu_inner_top, col_menu_inner_bottom = vagl.shade_color(
                colors.menu_inner, colors.menu_shadetop, colors.menu_shadedown)

        def get_menu_inner_color(y):
            y = max(menu_ymin, min(y, menu_ymax))
            f = (y - menu_ymin) / (menu_ymax - menu_ymin)
            return vagl.blend_color(col_menu_inner_top,
                                    col_menu_inner_bottom, f)

        # Draw Back
        # menu back color
        bgl.glColor4f(*colors.menu_inner)
        if colors.menu_inner[3] > 0.0:
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            for v in text_box_poly_coords:
                if colors.menu_show_shaded:
                    col = get_menu_inner_color(v[1])
                    bgl.glColor4f(*col)
                bgl.glVertex2f(*v)
            bgl.glEnd()
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            for v in icon_box_poly_coords:
                if colors.menu_show_shaded:
                    col = get_menu_inner_color(v[1])
                    bgl.glColor4f(*col)
                bgl.glVertex2f(*v)
            bgl.glEnd()

        # item inner
        bgl.glColor4f(*col_box_top)
        if col_box_top[3] > 0.0 or col_box_bottom[3] > 0.0:
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            for v in text_box_poly_coords:
                if colors.item_show_shaded:
                    f = (v[1] - text_box[1]) / widget_unit
                    col = vagl.blend_color(col_box_top, col_box_bottom, f)
                    bgl.glColor4f(*col)
                bgl.glVertex2f(*v)
            bgl.glEnd()
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            for v in icon_box_poly_coords:
                if colors.item_show_shaded:
                    f = (v[1] - icon_box[1]) / (icon_box[3] - icon_box[1])
                    col = vagl.blend_color(col_box_top, col_box_bottom, f)
                    bgl.glColor4f(*col)
                bgl.glVertex2f(*v)
            bgl.glEnd()

        # Draw Icon
        if icon_box:
            icon_center = [(icon_box[0] + icon_box[2]) / 2,
                           (icon_box[1] + icon_box[3]) / 2]
            icon_x = icon_center[0] - icon_size / 2
            icon_y = icon_center[1] - icon_size / 2
            rotation = -math.pi * 2 / num * index
            self.draw_icon(item.icon, icon_x, icon_y, icon_size, active,
                           enabled, rotation, icon_box_poly_coords)

        # Draw Outline
        if highlight:
            bgl.glColor4f(*colors.item_highlight)
            bgl.glLineWidth(2.0)
        else:
            bgl.glColor4f(*colors.item_outline)
        bgl.glBegin(bgl.GL_LINE_LOOP)
        for v in line_coords:
            bgl.glVertex2f(*v)
        bgl.glEnd()
        bgl.glBegin(bgl.GL_LINE_LOOP)
        for v in line_coords_icon:
            bgl.glVertex2f(*v)
        bgl.glEnd()
        bgl.glLineWidth(1.0)

        # Draw Text
        if text_box:
            if not enabled:
                col = vagl.thin_color(colors.item_text, 0.5)
            elif active:
                col = list(colors.item_text_sel)
            else:
                col = list(colors.item_text)
            bgl.glColor4f(*col)
            if menu.draw_type == 'SIMPLE':
                if icon_box:
                    # (0.4 | WU | 0.1 | text | 0.5)
                    x = text_box[0] + widget_unit * 1.5
                else:
                    # ( 0.5 | text | 0.5 )
                    x = text_box[0] + widget_unit * 0.5
            else:
                x = text_box[0] + widget_unit * 0.5

            th = blf.dimensions(prefs.font_id, CALC_TEXT_HEIGHT)[1]
            y = text_box[1] + widget_unit / 2 - th / 2
            blf.position(prefs.font_id, x, y, 0)
            vagl.blf_draw(prefs.font_id, item.label)

        # Menu Marker
        if item.menu:
            b = math.sqrt(2)
            f = b * math.sin(math.pi / 4) / 2
            box = text_box or icon_box
            if direction == "left":
                co = [box[0] + 2, box[1] + 2]
                v = [-f, -f]
            else:
                co = [box[2] - 2, box[1] + 2]
                v = [f, -f]
            if (menu.active_item_index == index and item.enabled and
                    menu.is_valid_click):
                l = 14
            else:
                l = 10
            v = [v[0] * l, v[1] * l]
            bgl.glColor4f(*colors.menu_inner)
            vagl.draw_triangle_relative(co, l * b, v, poly=True)
            bgl.glColor4f(*colors.menu_marker)
            vagl.draw_triangle_relative(co, l * b, v, poly=True)
            bgl.glColor4f(*colors.menu_marker_outline)
            vagl.draw_triangle_relative(co, l * b, v)

        # Shortcut
        ls = ('ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN',
              'EIGHT', 'NINE')
        if item.shortcut in ls:
            shortcut = str(ls.index(item.shortcut))
        else:
            shortcut = item.shortcut
        if shortcut and shortcut != 'NONE':
            if direction == "left":
                tw = blf.dimensions(prefs.font_id, shortcut)[0]
                x = text_box[0] - widget_unit / 2 - tw
            else:
                x = text_box[2] + widget_unit / 2
            y = text_box[1] + widget_unit / 2 - th / 2
            blf.position(prefs.font_id, x, y, 0)
            bgl.glColor4f(*colors.text)
            vagl.blf_draw(prefs.font_id, shortcut)
Пример #47
0
def glLineWidth(width):
    inst = InternalData.get_instance()
    inst.set_line_width(width)

    bgl.glLineWidth(width)
    def draw_callback_px(self, context, image_coords):

        #image = bpy.data.images[1]
        area = context.area
        shader = gpu.shader.from_builtin('2D_IMAGE')

        # Draw spritesheet
        batch = batch_for_shader(
            shader,
            'TRI_FAN',
            {
                "pos": (
                    image_coords[0],
                    image_coords[1],
                    image_coords[2],
                    image_coords[3],
                ),
                "texCoord": ((0, 0), (1, 0), (1, 1), (0, 1)),
            },
        )

        if self.image.gl_load():
            raise Exception()

        bgl.glActiveTexture(bgl.GL_TEXTURE0)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, self.image.bindcode)

        shader.bind()
        shader.uniform_int("image", 0)
        # shader.uniform_int("image", 0)
        batch.draw(shader)

        #######################################################################
        # Draw Grid overlay
        #######################################################################

        x_cell_count = self.sheet_attributes['X Cells']
        y_cell_count = self.sheet_attributes['Y Cells']
        total = x_cell_count * y_cell_count + self.sheet_attributes[
            'Total Offset']

        x_step = 1.0 / x_cell_count
        y_step = 1.0 / y_cell_count

        coords = []
        indices = []

        # Created normalized grid coords and line indices
        cell_index = 0
        for row in range(y_cell_count):
            for column in range(x_cell_count):
                if cell_index == total:
                    continue

                # Rectangle coords
                coords.extend((
                    Vector((x_step * column, y_step * row)),
                    Vector((x_step * (1 + column), y_step * row)),
                    Vector((x_step * (1 + column), y_step * (1 + row))),
                    Vector((x_step * column, y_step * (1 + row))),
                ))

                base_indices = (
                    (0, 1),
                    (1, 2),
                    (2, 3),
                    (3, 0),
                )
                index_offset = 4 * cell_index
                for a, b in base_indices:
                    indices.append((a + index_offset, b + index_offset))

                cell_index += 1

        x_scaler = abs(image_coords[0][0] - image_coords[1][0])
        y_scaler = abs(image_coords[0][1] - image_coords[3][1]) * -1

        coords = list(
            map(lambda xy: Vector((xy[0] * x_scaler, xy[1] * y_scaler)),
                coords))
        coords = list(map(lambda xy: xy + Vector(image_coords[3]), coords))

        shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
        batch = batch_for_shader(shader,
                                 'LINES', {"pos": coords},
                                 indices=indices)

        # bgl.glEnable(bgl.GL_FRAMEBUFFER_SRGB)  glLineWidth(width):
        bgl.glLineWidth(2)

        shader.bind()
        # shader.uniform_float("color", (1, 0, 0, 1))
        shader.uniform_float(
            "color", COLORS[list(COLORS.keys())[self.draw_color_index]])
        batch.draw(shader)

        #######################################################################

        # Draw Text
        active_color = (1, 1, 1, 1)
        inactive_color = (0.5, 0.5, 0.5, 1)

        font_id = 0

        origin_x = 2
        origin_y = 80
        y_step = -20
        blf.size(font_id, 24, 72)

        for i, (key, value) in enumerate(self.sheet_attributes.items()):
            blf.position(font_id, origin_x, origin_y + (y_step * i), 0)
            if key == self.states[self.state_index]:
                blf.color(font_id, *active_color)
            else:
                blf.color(font_id, *inactive_color)
            blf.draw(font_id, "{}: {}".format(key, value))

        blf.position(font_id, origin_x,
                     origin_y + (y_step * len(self.sheet_attributes.items())),
                     0)
        blf.color(font_id, *inactive_color)
        blf.draw(font_id, "Change Color: C")
Пример #49
0
    def draw_px(self, context):
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glPointSize(8)
        bgl.glLineWidth(2.0)

        shader = self.shader
        if self.sewing_index >= 0:  #if we are negative, we are not editing sewing.
            current_sewing = self.garment.garment_sewings[
                self.sewing_index] if self.sewing_index >= 0 else None
            if self._state in ['pick_target_segment', 'pick_source_segment'
                               ] and current_sewing:  # hover highlight
                pattern_obj_name = current_sewing.source_obj.name if self._state == 'pick_source_segment' else current_sewing.target_obj.name
                segments = self.patter_segments_cache[pattern_obj_name]
                points = None
                for seg_id, segment in enumerate(segments):
                    if self.closest_segment_id == seg_id:
                        points = [(point[0], point[1], point[2])
                                  for point in segment]
                        break
                if points:
                    batch = batch_for_shader(shader, "POINTS", {"pos": points})
                    shader.bind()
                    shader.uniform_float("color", (0.2, 0.9, 0.2, 0.5))
                    batch.draw(shader)

            if self._state in [
                    'pick_target_pattern'
            ] and current_sewing:  # higligh source segment, when defining target
                segments = self.patter_segments_cache[
                    current_sewing.source_obj.name]
                segment = segments[current_sewing.segment_id_from]
                points = [(point[0], point[1], point[2]) for point in segment]
                if points:
                    batch = batch_for_shader(shader, "POINTS", {"pos": points})
                    shader.bind()
                    shader.uniform_float("color", (0.2, 0.9, 0.2, 0.5))
                    batch.draw(shader)

        points = []
        # drawing  sewing
        for i, sewing in enumerate(self.garment.garment_sewings):
            # self.closest_segment_id<0: #skip sewing if we are defining sewing_to
            if self.sewing_index == i and self._state in [
                    'pick_source_segment', 'pick_target_pattern'
            ]:
                continue

            if sewing.source_obj is not None and sewing.target_obj is not None:
                if sewing.source_obj.name not in self.patter_segments_cache.keys(
                ) or sewing.target_obj.name not in self.patter_segments_cache:
                    continue
                vert_stich_01_list = self.patter_segments_cache[
                    sewing.source_obj.name]
                vert_stich_02_list = self.patter_segments_cache[
                    sewing.target_obj.name]

                if sewing.segment_id_from >= len(vert_stich_01_list):
                    sewing.segment_id_from = 0
                if sewing.segment_id_to >= len(vert_stich_02_list):
                    sewing.segment_id_to = 0

                verts_form = vert_stich_01_list[sewing.segment_id_from]
                if self.sewing_index == i and self.closest_segment_id >= 0:
                    verts_to = vert_stich_02_list[self.closest_segment_id]
                else:
                    verts_to = vert_stich_02_list[sewing.segment_id_to]
            else:
                continue

            if sewing.flip:
                verts_to = list(reversed(verts_to))

            points = []
            for (point_from, point_to) in zip(verts_form, verts_to):
                points.extend([(point_from.x, point_from.y, point_from.z),
                               (point_to.x, point_to.y, point_to.z)])
            batch = batch_for_shader(shader, 'LINES', {"pos": points})
            shader.bind()
            if self.sewing_index == i:  # draw currently defined sewing
                shader.uniform_float("color", (0.2, 0.9, 0.2, 0.5))
            else:
                shader.uniform_float("color", (1.0, 0.8, 0.0, 0.5))
            batch.draw(shader)
        # batch = shader.new_batch('LINES', {"pos": points})

        #restore opengl defaults
        bgl.glLineWidth(1)
        bgl.glPointSize(1)
        bgl.glDisable(bgl.GL_BLEND)
Пример #50
0
def DRAW_DisplayCage(self, context):

    flag = NP020PS.flag
    flag = 'DISPLAY'
    cage3d = NP020PS.cage3d
    cross3d = NP020PS.cross3d
    c3d = NP020PS.c3d

    region = context.region
    rv3d = context.region_data
    cage2d = copy.deepcopy(cage3d)
    cross2d = copy.deepcopy(cross3d)

    for co in cage3d.items():
        #np_print(co[0])
        cage2d[co[0]] = view3d_utils.location_3d_to_region_2d(
            region, rv3d, co[1])
    for co in cross3d.items():
        cross2d[co[0]] = view3d_utils.location_3d_to_region_2d(
            region, rv3d, co[1])
    c2d = view3d_utils.location_3d_to_region_2d(region, rv3d, c3d)

    points = copy.deepcopy(cage2d)
    points.update(cross2d)

    # DRAWING START:
    bgl.glEnable(bgl.GL_BLEND)

    if flag == 'DISPLAY':
        instruct = 'select a handle'
        keys_aff = 'LMB - confirm, CTRL - force proportional, SHIFT - force central, TAB - apply scale / rotation'
        keys_nav = ''
        keys_neg = 'ESC - quit'

    if self.flag_con:
        mark_col = (1.0, 0.5, 0.0, 1.0)
    else:
        mark_col = (0.3, 0.6, 1.0, 1.0)

    # ON-SCREEN INSTRUCTIONS:

    display_instructions(region, rv3d, instruct, keys_aff, keys_nav, keys_neg)

    sensor = 60
    self.mode = None
    co2d = mathutils.Vector(self.co2d)
    distmin = mathutils.Vector(co2d - c2d).length

    # Hover markers - detection
    for co in points.items():
        dist = mathutils.Vector(co2d - co[1]).length
        if dist < distmin:
            distmin = dist
            if distmin < sensor:
                self.mode = co[0]
                self.hoverco = co[1]

    # Drawing the graphical representation of scale cage, calculated from selection's bound box:
    if self.mode == None:
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        bgl.glLineWidth(1.4)
    else:
        bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
        bgl.glLineWidth(1.0)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(*cage2d[0])
    bgl.glVertex2f(*cage2d[1])
    bgl.glVertex2f(*cage2d[2])
    bgl.glVertex2f(*cage2d[3])
    bgl.glVertex2f(*cage2d[0])
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(*cage2d[4])
    bgl.glVertex2f(*cage2d[5])
    bgl.glVertex2f(*cage2d[6])
    bgl.glVertex2f(*cage2d[7])
    bgl.glVertex2f(*cage2d[4])
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(*cage2d[0])
    bgl.glVertex2f(*cage2d[4])
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(*cage2d[1])
    bgl.glVertex2f(*cage2d[5])
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(*cage2d[2])
    bgl.glVertex2f(*cage2d[6])
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(*cage2d[3])
    bgl.glVertex2f(*cage2d[7])
    bgl.glEnd()
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    bgl.glLineWidth(1.0)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(*cross2d['xmin'])
    bgl.glVertex2f(*cross2d['xmax'])
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(*cross2d['ymin'])
    bgl.glVertex2f(*cross2d['ymax'])
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    bgl.glVertex2f(*cross2d['zmin'])
    bgl.glVertex2f(*cross2d['zmax'])
    bgl.glEnd()
    #bgl.glDepthRange(0,0)
    bgl.glColor4f(0.35, 0.65, 1.0, 1.0)
    bgl.glPointSize(9)
    bgl.glBegin(bgl.GL_POINTS)
    for [a, b] in cross2d.values():
        bgl.glVertex2f(a, b)
    bgl.glEnd()
    bgl.glEnable(bgl.GL_POINT_SMOOTH)
    bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
    bgl.glPointSize(11)
    bgl.glBegin(bgl.GL_POINTS)
    for co in cage2d.items():
        if len(str(co[0])) == 1:
            bgl.glVertex2f(*co[1])
    bgl.glEnd()
    bgl.glDisable(bgl.GL_POINT_SMOOTH)

    markers = {}
    markers[0] = (points[0], points[10], points[40], points[0], points[30],
                  points[40], points[0], points[10], points[30])
    markers[1] = (points[1], points[10], points[15], points[1], points[12],
                  points[15], points[1], points[10], points[12])
    markers[2] = (points[2], points[12], points[26], points[2], points[23],
                  points[26], points[2], points[12], points[23])
    markers[3] = (points[3], points[30], points[37], points[3], points[23],
                  points[37], points[3], points[30], points[23])
    markers[4] = (points[4], points[45], points[47], points[4], points[40],
                  points[47], points[4], points[40], points[45])
    markers[5] = (points[5], points[45], points[56], points[5], points[15],
                  points[56], points[5], points[15], points[45])
    markers[6] = (points[6], points[26], points[67], points[6], points[56],
                  points[67], points[6], points[26], points[56])
    markers[7] = (points[7], points[37], points[67], points[7], points[47],
                  points[67], points[7], points[37], points[47])
    markers['xmin'] = (points[0], points[3], points[7], points[4], points[0])
    markers['xmax'] = (points[1], points[2], points[6], points[5], points[1])
    markers['ymin'] = (points[0], points[1], points[5], points[4], points[0])
    markers['ymax'] = (points[2], points[3], points[7], points[6], points[2])
    markers['zmin'] = (points[0], points[1], points[2], points[3], points[0])
    markers['zmax'] = (points[4], points[5], points[6], points[7], points[4])

    pivot = {}
    if self.flag_cenpivot:
        pivot[0] = c2d
        pivot[1] = c2d
        pivot[2] = c2d
        pivot[3] = c2d
        pivot[4] = c2d
        pivot[5] = c2d
        pivot[6] = c2d
        pivot[7] = c2d
        pivot['xmin'] = c2d
        pivot['xmax'] = c2d
        pivot['ymin'] = c2d
        pivot['ymax'] = c2d
        pivot['zmin'] = c2d
        pivot['zmax'] = c2d
    else:
        pivot[0] = points[6]
        pivot[1] = points[7]
        pivot[2] = points[4]
        pivot[3] = points[5]
        pivot[4] = points[2]
        pivot[5] = points[3]
        pivot[6] = points[0]
        pivot[7] = points[1]
        pivot['xmin'] = points['xmax']
        pivot['xmax'] = points['xmin']
        pivot['ymin'] = points['ymax']
        pivot['ymax'] = points['ymin']
        pivot['zmin'] = points['zmax']
        pivot['zmax'] = points['zmin']

    np_print('self.mode = ', self.mode)
    fields = False
    field_contours = False
    pivots = True
    pivot_lines = True
    if fields:
        # Hover markers - fields
        bgl.glColor4f(0.65, 0.85, 1.0, 0.35)
        for mark in markers.items():
            if mark[0] == self.mode:
                #if type(mark[0]) is not str:
                #bgl.glColor4f(1.0, 1.0, 1.0, 0.3)
                bgl.glBegin(bgl.GL_TRIANGLE_FAN)
                for x, y in mark[1]:
                    bgl.glVertex2f(x, y)
                bgl.glEnd()

    if field_contours:
        # Hover markers - contours
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        bgl.glLineWidth(1.2)
        for mark in markers.items():
            if mark[0] == self.mode:
                if type(mark[0]) is not str:
                    #bgl.glColor4f(0.3, 0.6, 1.0, 0.5)
                    bgl.glColor4f(1.0, 1.0, 1.0, 0.75)
                    bgl.glLineWidth(1.0)
                bgl.glBegin(bgl.GL_LINE_STRIP)
                for x, y in mark[1]:
                    bgl.glVertex2f(x, y)
                bgl.glEnd()

    # Hover markers - pivot

    bgl.glEnable(bgl.GL_POINT_SMOOTH)

    bgl.glColor4f(*mark_col)
    bgl.glPointSize(12)
    for p in pivot.items():
        if p[0] == self.mode:
            if pivots:
                bgl.glBegin(bgl.GL_POINTS)
                #np_print(p[1])
                bgl.glVertex2f(*p[1])
                bgl.glEnd()

            if pivot_lines:
                bgl.glLineWidth(1.0)
                #bgl.glEnable(bgl.GL_LINE_STIPPLE)
                bgl.glBegin(bgl.GL_LINE_STRIP)
                bgl.glVertex2f(*points[self.mode])
                bgl.glVertex2f(*p[1])
                bgl.glEnd()
                #bgl.glDisable(bgl.GL_LINE_STIPPLE)

    if self.flag_cenpivot:
        bgl.glColor4f(1.0, 0.5, 0.0, 1.0)
        bgl.glPointSize(12)
        bgl.glBegin(bgl.GL_POINTS)
        bgl.glVertex2f(*c2d)
        bgl.glEnd()

    bgl.glDisable(bgl.GL_POINT_SMOOTH)

    # Hover markers - points
    bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
    bgl.glPointSize(16)
    for mark in markers.items():
        if mark[0] == self.mode:
            if type(mark[0]) is not str:
                bgl.glColor4f(*mark_col)
                bgl.glEnable(bgl.GL_POINT_SMOOTH)
                bgl.glPointSize(18)
            bgl.glBegin(bgl.GL_POINTS)
            bgl.glVertex2f(*points[self.mode])
            bgl.glEnd()
            bgl.glColor4f(*mark_col)
            bgl.glPointSize(12)
            if type(mark[0]) is not str:
                bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
                bgl.glEnable(bgl.GL_POINT_SMOOTH)
                bgl.glPointSize(14)
            bgl.glBegin(bgl.GL_POINTS)
            bgl.glVertex2f(*points[self.mode])
            bgl.glEnd()
            bgl.glDisable(bgl.GL_POINT_SMOOTH)

    if self.flag_force:
        flash_size = 7
        flash = [[0, 0], [2, 2], [1, 2], [2, 4], [0, 2], [1, 2], [0, 0]]
        for co in flash:
            co[0] = round(
                (co[0] * flash_size), 0) + self.co2d[0] + flash_size * 2
            co[1] = round(
                (co[1] * flash_size), 0) + self.co2d[1] - flash_size * 2

        bgl.glColor4f(0.95, 0.95, 0.0, 1.0)
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        for i, co in enumerate(flash):
            if i in range(0, 3): bgl.glVertex2f(*co)
        bgl.glEnd()
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        for i, co in enumerate(flash):
            if i in range(3, 6): bgl.glVertex2f(*co)
        bgl.glEnd()
        bgl.glColor4f(1.0, 0.7, 0.0, 1.0)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for co in flash:
            bgl.glVertex2f(*co)
        bgl.glEnd()

    # Restore opengl defaults
    bgl.glDisable(bgl.GL_POINTS)
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #51
0
def DRAW_Overlay(self, context):

    print('DRAW_Overlay_START', ';', 'NP020RM.flag = ', NP020RM.flag)

    flag = NP020RM.flag
    helper = NP020RM.helper
    angstep = NP020RM.angstep
    region = bpy.context.region
    rv3d = bpy.context.region_data
    rw = region.width
    rh = region.height
    if NP020RM.centerloc == None: centerloc = helper.location
    else: centerloc = NP020RM.centerloc
    qdef = NP020RM.qdef
    ndef = NP020RM.ndef
    alpha_0 = NP020RM.alpha_0
    alpha_1 = NP020RM.alpha_1
    print('rw, rh', rw, rh)
    rmin = int(min(rw, rh) / 10)
    if rmin == 0: rmin = 1
    co2d = self.co2d
    if flag in ('RUNTRANSCENTER', 'RUNTRANSSTART'):
        co2d = view3d_utils.location_3d_to_region_2d(region, rv3d,
                                                     helper.location)
    if qdef == None:
        q = get_ro_normal_from_vertical(region, rv3d, co2d)[1]
        n = get_ro_normal_from_vertical(region, rv3d, co2d)[0]
    else:
        q = qdef
        n = ndef
    NP020RM.q = q
    NP020RM.n = n
    #co2d_exp = (event.mouse_region_x, event.mouse_region_y)
    #n_exp = get_ro_normal_from_vertical(region, rv3d, co2d_exp)[0]
    #print ('co2d, n, q, n_exp', co2d, n, q)

    # writing the dots for circle at center of scene:
    radius = 1
    ang = 0.0
    circle = [(0.0, 0.0, 0.0)]
    while ang < 360.0:
        circle.append(((cos(radians(ang)) * radius),
                       (sin(radians(ang)) * radius), (0.0)))
        ang += 10
    circle.append(
        ((cos(radians(0.0)) * radius), (sin(radians(0.0)) * radius), (0.0)))

    # rotating and translating the circle to user picked angle and place:
    circle = rotate_graphic(circle, q)
    circle = translate_graphic(circle, centerloc)

    rmax = 1
    for i, co in enumerate(circle):
        co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
        circle[i] = co
    for i in range(1, 18):
        r = (circle[0] - circle[i]).length
        r1 = (circle[0] - circle[i + 18]).length
        #if (r + r1) > rmax and abs(r - r1) < min(r, r1)/5: rmax = (r+r1)/2
        #if (r + r1) > rmax and abs(r - r1) < min(r, r1)/10: rmax = r + r1
        if (r + r1) > rmax and (r + r1) / 2 < rmin: rmax = (r + r1)
        elif (r + r1) > rmax and (r + r1) / 2 >= rmin:
            rmax = (r + r1) * rmin / (((r + r1) / 2) - ((r + r1) / 2) - rmin)
        rmax = abs(rmax)
        circle[i] = co
    print('rmin', rmin)
    print('rmax', rmax)
    if flag not in ('RUNTRANSSTART', 'RUNROTEND'):
        fac = (rmin * 2) / rmax
        NP020RM.fac = fac
    else:
        fac = NP020RM.fac

    radius = 1 * fac
    ang = 0.0
    circle = [(0.0, 0.0, 0.0)]
    while ang < 360.0:
        circle.append(((cos(radians(ang)) * radius),
                       (sin(radians(ang)) * radius), (0.0)))
        ang += 10
    circle.append(
        ((cos(radians(0.0)) * radius), (sin(radians(0.0)) * radius), (0.0)))

    if flag == 'RUNTRANSCENTER':
        instruct = 'place center point'
        keys_aff = 'LMB / ENT / NUMPAD ENT - confirm, CTRL - snap'
        keys_nav = ''
        keys_neg = 'ESC - quit'

        r1 = 1
        r2 = 1.5
        walpha = construct_roto_widget(alpha_0, alpha_1, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_L = construct_roto_widget(90, 0, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_D = construct_roto_widget(0, 90, fac, r1, r2, angstep)

    elif flag == 'BGLPLANE':
        instruct = 'choose rotation plane'
        keys_aff = 'LMB / ENT / NUMPAD ENT - confirm'
        keys_nav = 'MMB / SCROLL - navigate'
        keys_neg = 'ESC - quit'

        ro_hor, isohipse = get_ro_x_from_iso(region, rv3d, co2d, centerloc)
        NP020RM.ro_hor = copy.deepcopy(ro_hor)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(1.0, 0.0, 0.0, 1.0)
        bgl.glLineWidth(2)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for co in isohipse:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glPointSize(4)
        bgl.glBegin(bgl.GL_POINTS)
        for co in isohipse:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        r1 = 1
        r2 = 1.5
        walpha = construct_roto_widget(alpha_0, alpha_1, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_L = construct_roto_widget(90, 0, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_D = construct_roto_widget(0, 90, fac, r1, r2, angstep)

        circle = rotate_graphic(circle, ro_hor)
        walpha = rotate_graphic(walpha, ro_hor)
        wbeta_L = rotate_graphic(wbeta_L, ro_hor)
        wbeta_D = rotate_graphic(wbeta_D, ro_hor)

        circle = rotate_graphic(circle, q)
        walpha = rotate_graphic(walpha, q)
        wbeta_L = rotate_graphic(wbeta_L, q)
        wbeta_D = rotate_graphic(wbeta_D, q)

    elif flag == 'RUNTRANSSTART':
        instruct = 'place start point'
        keys_aff = 'LMB / ENT / NUMPAD ENT - confirm, CTRL - snap'
        keys_nav = ''
        keys_neg = 'ESC - quit'

        hloc = helper.location
        #print('hloc', hloc)
        hlocb = hloc + n
        #print('hlocb', hlocb)
        #print('centerloc, n', centerloc, n)
        proj_start = mathutils.geometry.intersect_line_plane(
            helper.location, (helper.location + n), centerloc, n)
        NP020RM.proj_start = proj_start
        if proj_start == centerloc:
            proj = centerloc + Vector((0.0, 0.0, 0.001))
        #print ('proj_start' , proj_start)

        alpha_0, isohipse = get_angle_from_iso_planar(centerloc, n, proj_start)
        alpha_1 = alpha_0
        NP020RM.alpha_0 = alpha_0
        NP020RM.alpha_1 = alpha_1
        print('alpha_0', alpha_0)

        ro_hor = NP020RM.ro_hor

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(1.0, 0.0, 0.0, 1.0)
        bgl.glLineWidth(2)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for co in isohipse:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glPointSize(4)
        bgl.glBegin(bgl.GL_POINTS)
        for co in isohipse:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        r1 = 1
        r2 = 1.5
        walpha = construct_roto_widget(alpha_0, alpha_1, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_L = construct_roto_widget(alpha_1, 0, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_D = construct_roto_widget(0, alpha_0, fac, r1, r2, angstep)

        circle = rotate_graphic(circle, ro_hor)
        walpha = rotate_graphic(walpha, ro_hor)
        wbeta_L = rotate_graphic(wbeta_L, ro_hor)
        wbeta_D = rotate_graphic(wbeta_D, ro_hor)

        circle = rotate_graphic(circle, q)
        walpha = rotate_graphic(walpha, q)
        wbeta_L = rotate_graphic(wbeta_L, q)
        wbeta_D = rotate_graphic(wbeta_D, q)

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(0.5, 0.5, 1.0, 1.0)
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        points = (helper.location, proj_start, centerloc)
        for co in points:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        co = view3d_utils.location_3d_to_region_2d(region, rv3d, proj_start)
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glPointSize(14)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBegin(bgl.GL_POINTS)
        bgl.glVertex2f(*co)
        bgl.glEnd()

    elif flag == 'RUNROTEND':
        instruct = 'place end point'
        keys_aff = 'LMB / ENT / NUMPAD ENT - confirm, CTRL - snap'
        keys_nav = ''
        keys_neg = 'ESC - quit'
        for k, v in bpy.context.active_operator.properties.items():
            print(k, v)
        alpha_0 = NP020RM.alpha_0_def
        hloc = helper.location
        startloc = NP020RM.startloc
        endloc = helper.location
        proj_start = NP020RM.proj_start
        #print('hloc', hloc)
        hlocb = hloc + n
        #print('hlocb', hlocb)
        #print('centerloc, n', centerloc, n)
        proj_end = mathutils.geometry.intersect_line_plane(
            helper.location, (helper.location + n), centerloc, n)
        if proj_end == centerloc:
            proj_end = centerloc + Vector((0.0, 0.0, 0.001))
        #print ('proj_end' , proj_end)

        alpha = get_angle_vector_from_vector(centerloc, proj_start, proj_end)
        alpha_1 = alpha_0 + alpha
        print('alpha_0', alpha_0)

        ro_hor = NP020RM.ro_hor

        rot_helper_0 = NP020RM.rot_helper_0
        print('rot_helper_0 =', rot_helper_0)
        rot_helper_1 = helper.rotation_euler
        print('rot_helper_1 =', rot_helper_1)
        alpha_real = get_eul_z_angle_difffff_in_rotated_system(
            rot_helper_0, rot_helper_1, ndef)
        print('alpha_real =', alpha_real)

        delta = (abs(alpha_real) - (360 * int(abs(alpha_real) / 360)))
        if alpha_real >= 0:
            if alpha_0 + delta < 360: alpha_1 = alpha_0 + delta
            else: alpha_1 = delta - (360 - alpha_0)
        else:
            if delta < alpha_0:
                alpha_1 = alpha_0
                alpha_0 = alpha_1 - delta
            else:
                alpha_1 = alpha_0
                alpha_0 = 360 - (delta - alpha_0)

        if alpha_1 == alpha_0: alpha_1 = alpha_0 + 0.001
        r1 = 1
        r2 = 1.5
        walpha = construct_roto_widget(alpha_0, alpha_1, fac, r1, r2, angstep)

        r1 = 1.5
        r2 = 2
        wbeta_L = construct_roto_widget(alpha_1, alpha_0, fac, r1, r2, angstep)
        '''
        r1 = 1.5
        r2 = 2
        wbeta_D = construct_roto_widget(0, alpha_0, fac, r1, r2, angstep)
        '''

        circle = rotate_graphic(circle, ro_hor)
        walpha = rotate_graphic(walpha, ro_hor)
        wbeta_L = rotate_graphic(wbeta_L, ro_hor)
        #wbeta_D = rotate_graphic(wbeta_D, ro_hor)

        circle = rotate_graphic(circle, q)
        walpha = rotate_graphic(walpha, q)
        wbeta_L = rotate_graphic(wbeta_L, q)
        #wbeta_D = rotate_graphic(wbeta_D, q)

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(0.5, 0.5, 1.0, 1.0)
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        points = (helper.location, proj_end, centerloc, proj_start)
        for co in points:
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
        bgl.glEnd()

        co = view3d_utils.location_3d_to_region_2d(region, rv3d, proj_end)
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glPointSize(14)
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glBegin(bgl.GL_POINTS)
        bgl.glVertex2f(*co)
        bgl.glEnd()

        # NUMERICAL ANGLE:

        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
        font_id = 0
        blf.size(font_id, 20, 72)
        ang_pos = view3d_utils.location_3d_to_region_2d(
            region, rv3d, centerloc)
        blf.position(font_id, ang_pos[0] + 2, ang_pos[1] - 2, 0)
        blf.draw(font_id, str(round(alpha_real, 2)))
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        blf.position(font_id, ang_pos[0], ang_pos[1], 0)
        blf.draw(font_id, str(round(alpha_real, 2)))

    # DRAWING START:
    bgl.glEnable(bgl.GL_BLEND)

    # ON-SCREEN INSTRUCTIONS:

    display_instructions(region, rv3d, instruct, keys_aff, keys_nav, keys_neg)

    print('centerloc', centerloc)
    circle = translate_graphic(circle, centerloc)

    walpha = translate_graphic(walpha, centerloc)
    wbeta_L = translate_graphic(wbeta_L, centerloc)
    if flag is not 'RUNROTEND': wbeta_D = translate_graphic(wbeta_D, centerloc)

    print('rv3d', rv3d)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.6)
    bgl.glLineWidth(1)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i, co in enumerate(circle):
        co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
        bgl.glVertex2f(*co)
        circle[i] = co
    bgl.glEnd()
    print('centerloc', centerloc)

    # drawing of walpha contours:
    bgl.glColor4f(1.0, 1.0, 1.0, 0.6)
    bgl.glLineWidth(1)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i, co in enumerate(walpha):
        co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
        bgl.glVertex2f(*co)
        walpha[i] = co
    bgl.glEnd()
    #print ('walpha', walpha)
    bgl.glColor4f(0.0, 0.0, 0.0, 0.5)

    # drawing of walpha fields:
    print('alpha_0, alpha_1 =', alpha_0, alpha_1)
    if alpha_1 >= alpha_0: alpha = alpha_1 - alpha_0
    else: alpha = alpha_1 + (360 - alpha_0)
    sides = int(alpha / NP020RM.angstep) + 1
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glVertex2f(*walpha[0])
    bgl.glVertex2f(*walpha[1])
    bgl.glVertex2f(*walpha[2])
    bgl.glVertex2f(*walpha[(sides * 2) + 1])
    bgl.glEnd()
    for i in range(1, sides):
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        bgl.glVertex2f(*walpha[((sides * 2) + 2) - i])
        bgl.glVertex2f(*walpha[i + 1])
        bgl.glVertex2f(*walpha[2 + i])
        bgl.glVertex2f(*walpha[((sides * 2) + 2) - (i + 1)])
        bgl.glEnd()

    # drawing of wbeta_L contours:
    bgl.glColor4f(1.0, 1.0, 1.0, 0.6)
    bgl.glLineWidth(1)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i, co in enumerate(wbeta_L):
        co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
        bgl.glVertex2f(*co)
        wbeta_L[i] = co
    bgl.glEnd()
    #print ('wbeta_L', wbeta_L)
    bgl.glColor4f(0.65, 0.85, 1.0, 0.35)

    # drawing of wbeta_L fields:
    if flag == 'RUNROTEND':
        if alpha_0 >= alpha_1: alpha = alpha_0 - alpha_1
        else: alpha = alpha_0 + (360 - alpha_1)
    else: alpha = 360 - alpha_1
    sides = int(alpha / NP020RM.angstep) + 1
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glVertex2f(*wbeta_L[0])
    bgl.glVertex2f(*wbeta_L[1])
    bgl.glVertex2f(*wbeta_L[2])
    bgl.glVertex2f(*wbeta_L[(sides * 2) + 1])
    bgl.glEnd()
    for i in range(1, sides):
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        bgl.glVertex2f(*wbeta_L[((sides * 2) + 2) - i])
        bgl.glVertex2f(*wbeta_L[i + 1])
        bgl.glVertex2f(*wbeta_L[2 + i])
        bgl.glVertex2f(*wbeta_L[((sides * 2) + 2) - (i + 1)])
        bgl.glEnd()

    if flag is not 'RUNROTEND':
        # drawing of wbeta_D contours:
        bgl.glColor4f(1.0, 1.0, 1.0, 0.6)
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for i, co in enumerate(wbeta_D):
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
            wbeta_D[i] = co
        bgl.glEnd()
        #print ('wbeta_D', wbeta_D)
        bgl.glColor4f(0.35, 0.6, 0.75, 0.35)

        # drawing of wbeta_D fields:

        alpha = alpha_0
        sides = int(alpha / NP020RM.angstep) + 1
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        bgl.glVertex2f(*wbeta_D[0])
        bgl.glVertex2f(*wbeta_D[1])
        bgl.glVertex2f(*wbeta_D[2])
        bgl.glVertex2f(*wbeta_D[(sides * 2) + 1])
        bgl.glEnd()
        for i in range(1, sides):
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            bgl.glVertex2f(*wbeta_D[((sides * 2) + 2) - i])
            bgl.glVertex2f(*wbeta_D[i + 1])
            bgl.glVertex2f(*wbeta_D[2 + i])
            bgl.glVertex2f(*wbeta_D[((sides * 2) + 2) - (i + 1)])
            bgl.glEnd()

    #ENDING

    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #52
0
def draw_callback_nodeoutline(self, context):
    if context.window_manager.rsn_node_list == '':
        pass

    bgl.glLineWidth(1)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

    shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')

    # draw outline
    ########################

    # set color
    task_outer = (self.task_color[0], self.task_color[1], self.task_color[2],
                  self.alpha)
    file_path_outer = (self.file_path_color[0], self.file_path_color[1],
                       self.file_path_color[2], self.alpha)

    col_outer = (self.settings_color[0], self.settings_color[1],
                 self.settings_color[2], self.alpha)
    col_inner = (0.0, 0.0, 0.0, self.alpha + 0.1)

    node_list = context.window_manager.rsn_node_list.split(',')

    # draw all nodes
    for node_name in node_list:
        try:
            node = context.space_data.edit_tree.nodes[node_name]
            if node.bl_idname == 'RSNodeTaskNode':
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius * 1.25,
                                         colour=task_outer)
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius * 1.25 - 1.25,
                                         colour=col_inner)
            elif node.bl_idname in {
                    'RenderNodeSceneFilePath', 'RSNodeFilePathInputNode'
            }:
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius,
                                         colour=file_path_outer)
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius - 1,
                                         colour=col_inner)
            elif node.bl_idname != 'NodeReroute':
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius,
                                         colour=col_outer)
                draw_rounded_node_border(shader,
                                         node,
                                         radius=self.radius - 1,
                                         colour=col_inner)
        except KeyError:
            pass

    # draw text
    ##################
    if self.show_text_info:
        # properties text
        task_text = "No Active Task!" if context.window_manager.rsn_viewer_node == '' else context.window_manager.rsn_viewer_node
        camera = context.scene.camera.name if context.scene.camera else "No Scene camera"
        is_save = True if bpy.data.filepath != '' else False
        file_path_text = context.scene.render.filepath if is_save else "Save your file first!"

        texts = [
            f"Task: {task_text}",
            f"Camera: {camera}",
            f"Engine: {context.scene.render.engine}",
            f"Frame: {context.scene.frame_start} - {context.scene.frame_end}",
            f"FilePath: {file_path_text}",
        ]

        # text background
        r, g, b = self.background_color
        longest_text = max(texts, key=len, default='')
        size = blf.dimensions(0, longest_text)  # get the longest text
        size = [v * 1.5 / context.preferences.view.ui_scale
                for v in size]  # scale with the ui scale

        # set corner
        top = 125
        bottom = 25
        step = 25

        vertices = [
            (10 + size[0], top + size[1]),
            (20, top + size[1]),
            (20, 25),
            (10 + size[0], bottom),
        ]

        draw_round_rectangle(shader,
                             vertices,
                             radius=18,
                             colour=(0, 0, 0, self.alpha))  # shadow
        draw_round_rectangle(shader,
                             vertices,
                             radius=14,
                             colour=(r, g, b, self.alpha))  # main box

        # draw texts
        r, g, b = self.text_color
        size = 20

        for i, text in enumerate(texts):
            draw_text_2d((r, g, b, self.alpha, size), text, 20, top - step * i)

    # restore
    #####################
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glDisable(bgl.GL_LINE_SMOOTH)
Пример #53
0
def Draw_map_callback(self, context):

    if context.area != Map.view3d_area:
        return
    elif context.area.type == 'PROPERTIES' and \
        context.space_data.context != 'WORLD':
        return

    # Check if window area has changed for sticky zoom
    theMap = Map.object[0]
    if Map.region.width < Map.saved_region_width:
        diff = Map.saved_region_width - Map.region.width
        if theMap.origin.x + theMap.width > Map.saved_region_width:
            if theMap.origin.x > 0:
                theMap.origin.x -= diff
            else:
                theMap.width -= diff
        else:
            if Map.toolProps is not None:
                if Map.toolProps.width > Map.toolProps_width:
                    theMap.origin.x -= diff
                Map.toolProps_width = Map.toolProps.width
            if theMap.origin.x < 0:
                theMap.origin.x += diff
    else:
        diff = Map.region.width - Map.saved_region_width
        if theMap.width > Map.saved_region_width:
            theMap.width += diff
        else:
            if Map.toolProps is not None:
                if Map.toolProps.width < Map.toolProps_width:
                    theMap.origin.x += diff
                Map.toolProps_width = Map.toolProps.width
    theMap.set_dimensions(theMap.width)
    Map.saved_region_width = Map.region.width

    # Latitude and longitude are set to an equidistant
    # cylindrical projection with lat/long 0/0 exactly
    # in the middle of the image.

    zLong = theMap.width / 2
    longFac = zLong / 180
    zLat = theMap.height / 2
    latFac = zLat / 90
    crossChange = True

    if not Map.action == 'PAN':
        x = Map.mouse.x
        y = Map.mouse.y
        if x < theMap.origin.x or x > theMap.origin.x + theMap.width:
            crossChange = False
            x = 0
        else:
            testBoundary = theMap.origin.x + theMap.width
            if testBoundary < Map.region.width:
                rightBoundary = testBoundary
            else:
                rightBoundary = Map.region.width
            if x > rightBoundary:
                crossChange = False
                x = rightBoundary
        cX = x - zLong - theMap.origin.x

        if longFac:
            newLongitude = cX / longFac
        else:
            newLongitude = 0.0

        if y < theMap.origin.y or y < 0:
            crossChange = False
            y = 0
        elif y > theMap.origin.y + theMap.height:
            crossChange = False
            y = theMap.origin.y + theMap.height
        cY = y - zLat - theMap.origin.y

        if latFac:
            newLatitude = cY / latFac
        else:
            newLatitude = 0.0

        if newLatitude == Map.latitude and newLongitude == Map.longitude:
            crossChange = False
        else:
            Map.latitude = newLatitude
            Map.longitude = newLongitude
    else:
        if Map.grab.offset.x < Map.grab.spot.x:
            off = Map.grab.spot.x - Map.grab.offset.x
            theMap.origin.x -= off
        else:
            off = Map.grab.offset.x - Map.grab.spot.x
            theMap.origin.x += off
        if Map.grab.offset.y < Map.grab.spot.y:
            off = Map.grab.spot.y - Map.grab.offset.y
            theMap.origin.y -= off
        else:
            off = Map.grab.offset.y - Map.grab.spot.y
            theMap.origin.y += off
        Map.grab.spot.x = Map.mouse.x
        Map.grab.spot.y = Map.mouse.y

    Lx = theMap.origin.x
    Ly = theMap.origin.y

    # ---------------------
    # Draw a textured quad
    # ---------------------

    if not Map.textureless:
        bgl.glEnable(bgl.GL_BLEND)
        if Map.glImage.bindcode == 0:
            Map.load_gl_image()
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, Map.glImage.bindcode)
        bgl.glEnable(bgl.GL_TEXTURE_2D)
        bgl.glColor4f(1.0, 1.0, 1.0, Map.object[0].opacity)
        bgl.glBegin(bgl.GL_QUADS)
        bgl.glTexCoord2f(0.0, 0.0)
        bgl.glVertex2f(Lx, Ly)
        bgl.glTexCoord2f(1.0, 0.0)
        bgl.glVertex2f(Lx + theMap.width, Ly)
        bgl.glTexCoord2f(1.0, 1.0)
        bgl.glVertex2f(Lx + theMap.width, Ly + theMap.height)
        bgl.glTexCoord2f(0.0, 1.0)
        bgl.glVertex2f(Lx, theMap.height + Ly)
        bgl.glEnd()
        bgl.glDisable(bgl.GL_TEXTURE_2D)

    # -----------------------
    # Output text for stats
    # -----------------------
    if Map.action == 'TIME' or Map.action == 'DAY' or Map.showInfo:
        Map.show_text_in_viewport(Map.object[1])

    # ---------------------
    # draw the crosshair
    # ---------------------
    x = theMap.width / 2.0
    if crossChange and not Map.lockCrosshair:
        if Map.action != 'Y':
            Sun.SP.Longitude = newLongitude
    longitude = (Sun.SP.Longitude * x / 180.0) + x

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINES)
    bgl.glLineWidth(1.0)
    alpha = 1.0 if Map.action == 'Y' else 0.5
    color = (0.894, 0.741, .510, alpha)
    bgl.glColor4f(color[0], color[1], color[2], color[3])
    bgl.glBegin(bgl.GL_LINES)
    bgl.glVertex2f(Lx + longitude, Ly)
    bgl.glVertex2f(Lx + longitude, Ly + theMap.height)
    bgl.glEnd()

    y = theMap.height / 2.0
    if crossChange and not Map.lockCrosshair:
        if Map.action != 'X':
            Sun.SP.Latitude = newLatitude
    latitude = (Sun.SP.Latitude * y / 90.0) + y

    alpha = 1.0 if Map.action == 'X' else 0.5
    color = (0.894, 0.741, .510, alpha)
    bgl.glColor4f(color[0], color[1], color[2], color[3])
    bgl.glBegin(bgl.GL_LINES)
    bgl.glVertex2f(Lx, Ly + latitude)
    bgl.glVertex2f(Lx + theMap.width, Ly + latitude)
    bgl.glEnd()

    # ---------------------
    # draw the border
    # ---------------------
    bgl.glDisable(bgl.GL_BLEND)
    color = (0.6, 0.6, .6, 1.0)
    bgl.glColor4f(color[0], color[1], color[2], color[3])
    bgl.glBegin(bgl.GL_LINE_LOOP)
    bgl.glVertex2f(Lx, Ly)
    bgl.glVertex2f(Lx + theMap.width, Ly)
    bgl.glVertex2f(Lx + theMap.width, Ly + theMap.height)
    bgl.glVertex2f(Lx, theMap.height + Ly)
    bgl.glVertex2f(Lx, Ly)
    bgl.glEnd()

    if not Sun.ShowRiseSet or not Map.lineWidth:
        bgl.glDisable(bgl.GL_LINES)
        bgl.glFlush()
        return

    if Map.action == 'G':
        draw_text_region()

    # ------------------------
    # draw the sunrise, sunset
    # ------------------------

    def draw_angled_line(color, angle, bx, by):
        x = math.cos(angle) * radius
        y = math.sin(angle) * radius
        bgl.glColor4f(color[0], color[1], color[2], color[3])
        bgl.glBegin(bgl.GL_LINES)
        bgl.glVertex2f(bx, by)
        bgl.glVertex2f(bx + x, by + y)
        bgl.glEnd()

    px = Lx + longitude
    py = Ly + latitude

    radius = 30 + Map.lineWidth * 10
    if Sun.RiseSetOK and Map.lineWidth:
        color = (0.2, 0.6, 1.0, 0.9)
        angle = -(degToRad(Sun.Sunrise.azimuth) - math.pi / 2)
        bgl.glLineWidth(Map.lineWidth)
        draw_angled_line(color, angle, px, py)

        color = (0.86, 0.18, 0.18, 0.9)
        angle = -(degToRad(Sun.Sunset.azimuth) - math.pi / 2)
        draw_angled_line(color, angle, px, py)

    # ------------------------
    # draw current time line
    # ------------------------

    if Map.textureless:
        phi = degToRad(Sun.AzNorth) * -1
    else:
        phi = degToRad(Sun.Azimuth) * -1
    x = math.sin(phi) * math.sin(-Sun.Theta) * (radius + 10)
    y = math.sin(Sun.Theta) * math.cos(phi) * (radius + 10)
    night = (0.24, 0.29, 0.94, 0.9)
    day = (0.85, 0.77, 0.60, 0.9)
    if Sun.SolarNoon.elevation < 0.0:
        color = night
    elif Sun.Elevation >= Sun.Sunrise.elevation:
        if Sun.Time >= Sun.Sunset.time and \
            Sun.Elevation <= Sun.Sunset.elevation:
            color = night
        else:
            color = day
    else:
        color = night
    bgl.glLineWidth(Map.lineWidth + 1.0)

    bgl.glColor4f(color[0], color[1], color[2], color[3])
    bgl.glBegin(bgl.GL_LINES)
    bgl.glVertex2f(px, py)
    bgl.glVertex2f(px + x, py + y)
    bgl.glEnd()
    bgl.glLineWidth(1.0)
    bgl.glDisable(bgl.GL_LINES)
    bgl.glFlush()
Пример #54
0
 def line_width(self, width): bgl.glLineWidth(max(1, self.scale(width)))
 def point_size(self, size): bgl.glPointSize(max(1, self.scale(size)))
Пример #55
0
def draw_callback1_px(self, context):

    # Getting the first object and face that raycast hits:
    mode = self.mode
    np_print('mode:', mode)
    region = self.region
    np_print('region', region)
    rv3d = self.rv3d
    np_print('rv3d', rv3d)
    co2d = self.co2d
    np_print('self.co2d', co2d)
    co3d = 1
    center = Vector((0, 0, 0))
    normal = Vector((0.0, 0.0, 1.0))
    scenecast = scene_cast(region, rv3d, co2d)
    np_print('scenecast', scenecast)
    hitob = scenecast[4]
    np_print('hitob', hitob)

    if mode == 0:
        instruct = 'paint material on object / objects'

    elif mode == 1:
        instruct = 'pick material to paint with'

    elif mode == 2:
        instruct = 'pick material to paint with'

    elif mode == 3:
        instruct = 'paint material on single face'

    elif mode == 4:
        instruct = 'paint material on object / objects'
        if hitob is not None:
            acob = bpy.context.scene.objects.active
            bpy.context.scene.objects.active = hitob
            slots = hitob.material_slots
            for i, s in enumerate(slots):
                hitob.active_material_index = i
                bpy.ops.object.material_slot_remove()
            if self.shader is not None:
                hitob.data.materials.append(self.shader)
            np_print(hitob.select)
            if hitob.select == True:
                np_print('true')
                for ob in self.selob:
                    bpy.context.scene.objects.active = ob
                    slots = ob.material_slots
                    for i, s in enumerate(slots):
                        ob.active_material_index = i
                        bpy.ops.object.material_slot_remove()
                    if self.shader is not None:
                        ob.data.materials.append(self.shader)
            bpy.context.scene.objects.active = acob
            #bpy.context.scene.update()
            np_print('040')

    elif mode == 5:
        instruct = 'pick material to paint with'
        if hitob is not None:
            mat = None
            findex = scenecast[3]
            np_print('findex', findex)
            me = hitob.data
            np_print('me', me)
            bme = bmesh.new()
            bme.from_mesh(me)
            bme.faces.ensure_lookup_table()
            np_print('faces', bme.faces)
            np_print('face', bme.faces[findex])
            bmeface = bme.faces[findex]
            matindex = bmeface.material_index
            np_print('material_index', matindex)
            slots = list(hitob.material_slots)
            np_print('slots', slots)
            np_print('len slots', len(slots))
            np_print('slots', slots)
            if len(slots) == 0:
                self.shader = None
                self.shadername = 'None'
            elif slots[matindex].material is not None:
                self.shader = slots[matindex].material
                self.shadername = slots[matindex].material.name
            else:
                self.shader = None
                self.shadername = 'None'
            bpy.context.scene.objects.active = hitob
            hitob.active_material_index = matindex
            np_print('self.shader', self.shader)
            np_print('050')
        else:
            self.shader = None
            self.shadername = 'None'

    elif mode == 6:
        instruct = 'pick material to paint with'

    elif mode == 7:
        instruct = 'paint material on single face'
        if hitob is not None:
            acob = bpy.context.scene.objects.active
            bpy.context.scene.objects.active = hitob
            findex = scenecast[3]
            np_print('findex', findex)
            me = hitob.data
            np_print('me', me)
            bpy.ops.object.mode_set(mode='EDIT')
            bme = bmesh.from_edit_mesh(me)
            bme.faces.ensure_lookup_table()
            np_print('faces', bme.faces)
            np_print('face', bme.faces[findex])
            bmeface = bme.faces[findex]
            slots = list(hitob.material_slots)
            np_print('slots', list(slots))
            m = 0
            if list(slots) == []:
                hitob.data.materials.append(None)
            slots = list(hitob.material_slots)
            for i, s in enumerate(slots):
                np_print('s', s)
                if s.name == self.shadername:
                    m = 1
                    matindex = i
                elif s.material == None and self.shader == None:
                    m = 1
                    matindex = i
            if m == 0:
                hitob.data.materials.append(self.shader)
                matindex = len(slots) - 1
            hitob.active_material_index = matindex
            bpy.context.tool_settings.mesh_select_mode = False, False, True
            bpy.ops.mesh.select_all(action='DESELECT')
            bmeface.select = True
            bmesh.update_edit_mesh(me, True)
            bpy.ops.object.material_slot_assign()
            bpy.ops.mesh.select_all(action='DESELECT')
            bpy.ops.object.mode_set(mode='OBJECT')
            bpy.context.scene.objects.active = acob

    # ON-SCREEN INSTRUCTIONS:

    keys_aff = 'LMB - paint object / objects, CTRL - take material, ALT - paint single face'
    keys_nav = 'MMB, SCROLL - navigate'
    keys_neg = 'ESC - quit'

    display_instructions(region, rv3d, instruct, keys_aff, keys_nav, keys_neg)

    col_bg_fill_main_run = addon_settings_graph()['col_bg_fill_main_run']
    col_bg_fill_main_nav = addon_settings_graph()['col_bg_fill_main_nav']

    # Drawing the small icon near the cursor and the shader name:
    # First color is for lighter themes, second for default and darker themes:
    if mode in {1, 2, 5, 6}:
        square = [[17, 30], [17, 39], [26, 39], [26, 30]]
        cur = [[17, 36], [18, 35], [14, 31], [14, 30], [15, 30], [19, 34],
               [18, 35], [20, 37], [21, 37], [21, 36], [19, 34], [20, 33]]
        curpipe = [[18, 35], [14, 31], [14, 30], [15, 30], [19, 34], [18, 35]]
        curcap = [[18, 35], [20, 37], [21, 37], [21, 36], [19, 34], [18, 35]]
        scale = 2.8
        col_square = col_bg_fill_main_run
        for co in square:
            co[0] = round((co[0] * scale), 0) - 35 + co2d[0]
            co[1] = round((co[1] * scale), 0) - 88 + co2d[1]
        for co in cur:
            co[0] = round((co[0] * scale), 0) - 25 + co2d[0]
            co[1] = round((co[1] * scale), 0) - 86 + co2d[1]
        for co in curcap:
            co[0] = round((co[0] * scale), 0) - 25 + co2d[0]
            co[1] = round((co[1] * scale), 0) - 86 + co2d[1]
        for co in curpipe:
            co[0] = round((co[0] * scale), 0) - 25 + co2d[0]
            co[1] = round((co[1] * scale), 0) - 86 + co2d[1]
        bgl.glColor4f(*col_square)
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        for x, y in square:
            bgl.glVertex2f(x, y)
        bgl.glEnd()
        #bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        bgl.glColor4f(1.0, 1.0, 1.0, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for x, y in cur:
            bgl.glVertex2f(x, y)
        bgl.glEnd()
        if mode in {2, 6}:
            bgl.glColor4f(1.0, 0.5, 0.5, 1.0)
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        for x, y in curcap:
            bgl.glVertex2f(x, y)
        bgl.glEnd()

    else:
        square = [[17, 30], [17, 39], [26, 39], [26, 30]]
        cur = [[18, 30], [21, 33], [18, 36], [14, 32], [16, 32], [18, 30]]
        curtip = [[14, 32], [16, 32], [15, 33], [14, 32]]
        curbag = [[18, 30], [15, 33], [21, 33], [18, 30]]
        scale = 2.8
        if mode in (3, 7): col_square = col_bg_fill_main_nav
        else: col_square = (0.25, 0.35, 0.4, 0.87)
        for co in square:
            co[0] = round((co[0] * scale), 0) - 35 + co2d[0]
            co[1] = round((co[1] * scale), 0) - 88 + co2d[1]
        for co in cur:
            co[0] = round((co[0] * scale), 0) - 25 + co2d[0]
            co[1] = round((co[1] * scale), 0) - 84 + co2d[1]
        for co in curtip:
            co[0] = round((co[0] * scale), 0) - 25 + co2d[0]
            co[1] = round((co[1] * scale), 0) - 84 + co2d[1]
        for co in curbag:
            co[0] = round((co[0] * scale), 0) - 25 + co2d[0]
            co[1] = round((co[1] * scale), 0) - 84 + co2d[1]
        bgl.glColor4f(*col_square)
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        for x, y in square:
            bgl.glVertex2f(x, y)
        bgl.glEnd()
        #bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        bgl.glColor4f(1.0, 1.0, 1.0, 0.8)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for x, y in cur:
            bgl.glVertex2f(x, y)
        bgl.glEnd()
        '''
        if mode in {3, 7}:
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            for x,y in curtip:
                bgl.glVertex2f(x,y)
            bgl.glEnd()
            bgl.glLineWidth(2)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            for x,y in curtip:
                bgl.glVertex2f(x,y)
            bgl.glEnd()
            bgl.glLineWidth(1)
        '''
        if self.shader is not None:
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
            for x, y in curbag:
                bgl.glVertex2f(x, y)
            bgl.glEnd()

    bgl.glColor4f(0.25, 0.35, 0.4, 0.87)
    font_id = 0
    blf.size(font_id, 15, 72)
    blf.position(font_id, co2d[0] + 47, co2d[1] - 3, 0)
    blf.draw(font_id, self.shadername)

    bgl.glColor4f(1.0, 1.0, 1.0, 0.8)
    font_id = 0
    blf.size(font_id, 15, 72)
    blf.position(font_id, co2d[0] + 46, co2d[1] - 2, 0)
    blf.draw(font_id, self.shadername)

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #56
0
def _draw(self, context):
    if not context.space_data.overlay.show_overlays:
        return

    global _font_loc

    prefs = context.preferences.addons[var.ADDON_ID].preferences
    props = context.scene.jewelcraft
    show_all = props.overlay_show_all
    use_ovrd = props.overlay_use_overrides
    default_spacing = props.overlay_spacing
    default_color = prefs.overlay_color
    default_linewidth = prefs.overlay_linewidth
    diplay_thold = default_spacing + 0.5
    depsgraph = context.evaluated_depsgraph_get()
    gems_count = 0
    is_gem = False
    is_df = context.mode == "EDIT_MESH" and context.edit_object.is_instancer

    if is_df:
        df = context.edit_object
        for ob1 in df.children:
            if "gem" in ob1:
                is_gem = True
                break
    else:
        ob1 = context.object
        if ob1:
            is_gem = "gem" in ob1 and ob1.select_get()

    if not (show_all or is_gem):
        return

    if is_gem:
        if use_ovrd and "gem_overlay" in ob1:
            ob1_spacing = ob1["gem_overlay"].get("spacing", default_spacing)
        else:
            ob1_spacing = default_spacing

        from_scene_scale = unit.Scale(context).from_scene

        if is_df:
            df_pass = False
            df.update_from_editmode()

            if df.modifiers and df.is_deform_modified(context.scene,
                                                      "PREVIEW"):
                df_eval = df.evaluated_get(depsgraph)
                polys = df_eval.to_mesh().polygons
            else:
                df_eval = df
                polys = df.data.polygons

            poly = polys[df.data.polygons.active]
            loc1 = df.matrix_world @ poly.center
            mat_rot = poly.normal.to_track_quat("Z", "Y").to_matrix().to_4x4()
            df_eval.to_mesh_clear()
        else:
            loc1 = ob1.matrix_world.to_translation()
            mat_rot = ob1.matrix_world.to_quaternion().to_matrix().to_4x4()

        rad1 = max(ob1.dimensions.xy) / 2
        mat_loc = Matrix.Translation(loc1)
        mat1 = mat_loc @ mat_rot
        mat1.freeze()

    bgl.glEnable(bgl.GL_BLEND)

    if var.USE_POLYLINE:
        shader = gpu.shader.from_builtin("3D_POLYLINE_UNIFORM_COLOR")
    else:
        shader = gpu.shader.from_builtin("3D_UNIFORM_COLOR")
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glDepthMask(bgl.GL_FALSE)

    if not props.overlay_show_in_front:
        bgl.glEnable(bgl.GL_DEPTH_TEST)

    shader.bind()

    for dup in depsgraph.object_instances:

        if dup.is_instance:
            ob2 = dup.instance_object.original
        else:
            ob2 = dup.object.original

        if "gem" not in ob2:
            continue

        gems_count += 1

        rad2 = max(ob2.dimensions.xy) / 2
        loc2 = dup.matrix_world.translation
        spacing_thold = False

        if is_gem:
            dis_obs = (loc1 - loc2).length
            dis_gap = from_scene_scale(dis_obs - (rad1 + rad2))
            dis_thold = dis_gap < diplay_thold

            if not (show_all or dis_thold):
                continue

            is_act = False

            if is_df:
                if not df_pass:
                    df_pass = is_act = dup.matrix_world.translation == loc1
            else:
                if not dup.is_instance:
                    is_act = ob2 is ob1

            use_diplay_dis = not is_act and dis_thold
        else:
            use_diplay_dis = False

        if show_all or use_diplay_dis:
            if use_ovrd and "gem_overlay" in ob2:
                _color = ob2["gem_overlay"].get("color", default_color)
                _linewidth = ob2["gem_overlay"].get("linewidth",
                                                    default_linewidth)
                _spacing = ob2["gem_overlay"].get("spacing", default_spacing)
            else:
                _color = default_color
                _linewidth = default_linewidth
                _spacing = default_spacing

            shader.uniform_float("color", _color)

            if var.USE_POLYLINE:
                shader.uniform_float("lineWidth", _linewidth)
            else:
                bgl.glLineWidth(_linewidth)

            if dup.is_instance:
                mat2 = dup.matrix_world.copy()
            else:
                mat_loc = Matrix.Translation(loc2)
                mat_rot = dup.matrix_world.to_quaternion().to_matrix().to_4x4()
                mat2 = mat_loc @ mat_rot

            mat2.freeze()

        if use_diplay_dis:
            if dis_obs:
                co1, co2 = nearest_coords(rad1, rad2, mat1, mat2)
                dis_gap = from_scene_scale(
                    calc_gap(co1, co2, loc1, dis_obs, rad1))
                dis_thold = dis_gap < diplay_thold
                spacing_thold = dis_gap < (_spacing + 0.3)

                if not (show_all or dis_thold):
                    continue

                mid = co1.lerp(co2, 0.5)
            else:
                co1 = co2 = mid = loc2.copy()

            if dis_thold:
                if dis_gap < 0.1:
                    shader.uniform_float("color", (1.0, 0.0, 0.0, 1.0))
                elif dis_gap < _spacing:
                    shader.uniform_float("color", (1.0, 0.9, 0.0, 1.0))

                _font_loc.append(
                    (dis_gap, mid, from_scene_scale(max(ob1_spacing,
                                                        _spacing))))

                batch = batch_for_shader(shader, "LINES", {"pos": (co1, co2)})
                batch.draw(shader)

        if show_all or spacing_thold:
            batch = batch_for_shader(
                shader, "LINE_LOOP",
                {"pos": _circle_cos(rad2 + _spacing, mat2)})
            batch.draw(shader)

    _CC.set(gems_count)
    restore_gl()
Пример #57
0
def mesh_check_draw_callback():
    obj = bpy.context.object
    if obj and obj.type == 'MESH':
        if draw_enabled[0]:
            mesh = obj.data
            matrix_world = obj.matrix_world

            glLineWidth(edge_width[0])

            if bpy.context.mode == 'EDIT_MESH':
                use_occlude = True

                if bm_old[0] is None or not bm_old[0].is_valid:
                    bm = bm_old[0] = bmesh.from_edit_mesh(mesh)
                else:
                    bm = bm_old[0]

                no_depth = not bpy.context.space_data.use_occlude_geometry

                if no_depth:
                    glDisable(GL_DEPTH_TEST)

                    use_occlude = False

                    if finer_lines[0]:
                        glLineWidth(edge_width[0] / 4.0)
                        use_occlude = True

                    for face in bm.faces:
                        if len([verts for verts in face.verts]) == 3:
                            faces = [matrix_world * vert.co for vert in face.verts]
                            glColor4f(*faces_tri_color[0])
                            glEnable(GL_BLEND)
                            glBegin(GL_POLYGON)
                            draw_poly(faces)
                            glEnd()

                            for edge in face.edges:
                                if edge.is_valid:
                                    edges = [matrix_world * vert.co for vert in edge.verts]
                                    glColor4f(*edges_tri_color[0])
                                    glBegin(GL_LINES)
                                    draw_poly(edges)
                                    glEnd()

                        elif len([verts for verts in face.verts]) > 4:
                            new_faces = []
                            faces = []
                            coords = [v.co for v in face.verts]
                            indices = [v.index for v in face.verts]
                            for pol in tessellate([coords]):
                                new_faces.append([indices[i] for i in pol])

                            for f in new_faces:
                                faces.append(
                                        [((matrix_world * bm.verts[i].co)[0] + face.normal.x * 0.001,
                                        (matrix_world * bm.verts[i].co)[1] + face.normal.y * 0.001,
                                        (matrix_world * bm.verts[i].co)[2] + face.normal.z * 0.001)
                                        for i in f]
                                        )

                            for f in faces:
                                glColor4f(*faces_ngons_color[0])
                                glEnable(GL_BLEND)
                                glBegin(GL_POLYGON)
                                draw_poly(f)
                                glEnd()

                            for edge in face.edges:
                                if edge.is_valid:
                                    edges = [matrix_world * vert.co for vert in edge.verts]
                                    glColor4f(*edges_ngons_color[0])
                                    glBegin(GL_LINES)
                                    draw_poly(edges)
                                    glEnd()

                    glDisable(GL_BLEND)
                    glColor4f(0.0, 0.0, 0.0, 1.0)
                    glLineWidth(edge_width[0])
                    glEnable(GL_DEPTH_TEST)

                if use_occlude:

                    for face in bm.faces:
                        if len([verts for verts in face.verts]) == 3:
                            faces = []
                            for vert in face.verts:
                                vert_face = matrix_world * vert.co
                                faces.append(
                                        (vert_face[0] + face.normal.x * 0.001,
                                        vert_face[1] + face.normal.y * 0.001,
                                        vert_face[2] + face.normal.z * 0.001)
                                        )

                            glColor4f(*faces_tri_color[0])
                            glEnable(GL_BLEND)
                            glBegin(GL_POLYGON)
                            draw_poly(faces)
                            glEnd()

                            for edge in face.edges:
                                if edge.is_valid:
                                    edges = []
                                    for vert in edge.verts:
                                        vert_edge = matrix_world * vert.co
                                        edges.append(
                                            (vert_edge[0] + face.normal.x * 0.001,
                                            vert_edge[1] + face.normal.y * 0.001,
                                            vert_edge[2] + face.normal.z * 0.001)
                                            )
                                    glColor4f(*edges_tri_color[0])
                                    glBegin(GL_LINES)
                                    draw_poly(edges)
                                    glEnd()

                        elif len([verts for verts in face.verts]) > 4:
                            new_faces = []
                            faces = []
                            coords = [v.co for v in face.verts]
                            indices = [v.index for v in face.verts]
                            for pol in tessellate([coords]):
                                new_faces.append([indices[i] for i in pol])

                            for f in new_faces:
                                faces.append([
                                        ((matrix_world * bm.verts[i].co)[0] + face.normal.x * 0.001,
                                         (matrix_world * bm.verts[i].co)[1] + face.normal.y * 0.001,
                                         (matrix_world * bm.verts[i].co)[2] + face.normal.z * 0.001)
                                        for i in f]
                                        )

                            for f in faces:
                                glColor4f(*faces_ngons_color[0])
                                glEnable(GL_BLEND)
                                glBegin(GL_POLYGON)
                                draw_poly(f)
                                glEnd()

                            for edge in face.edges:
                                if edge.is_valid:
                                    edges = []
                                    for vert in edge.verts:
                                        vert_edge = matrix_world * vert.co
                                        edges.append(
                                                (vert_edge[0] + face.normal.x * 0.001,
                                                vert_edge[1] + face.normal.y * 0.001,
                                                vert_edge[2] + face.normal.z * 0.001)
                                                )
                                    glColor4f(*edges_ngons_color[0])
                                    glBegin(GL_LINES)
                                    draw_poly(edges)
                                    glEnd()

                    glDisable(GL_BLEND)
                    glColor4f(0.0, 0.0, 0.0, 1.0)
Пример #58
0
def draw_callback_px(self, context):
    """Draws Code Editors Minimap and indentation marks"""
    def draw_line(origin, length, thickness, vertical=False):
        """Drawing lines with polys, its faster"""
        x = (origin[0] + thickness) if vertical else (origin[0] + length)
        y = (origin[1] + length) if vertical else (origin[1] + thickness)
        bgl.glBegin(bgl.GL_QUADS)
        for v1, v2 in [origin, (x, origin[1]), (x, y), (origin[0], y)]:
            bgl.glVertex2i(v1, v2)
        bgl.glEnd()
        return

    # abort if another text editor
    if self.area == context.area and self.window == context.window:
        bgl.glEnable(bgl.GL_BLEND)
    else:
        return

    start = time.clock()

    # init params
    font_id = 0
    self.width = next(region.width for region in context.area.regions
                      if region.type == 'WINDOW')
    self.height = next(region.height for region in context.area.regions
                       if region.type == 'WINDOW')
    dpi_r = context.user_preferences.system.dpi / 72.0
    self.left_edge = self.width - round(
        dpi_r * (self.width + 5 * self.minimap_width) / 10.0)
    self.right_edge = self.width - round(dpi_r * 15)
    self.opacity = min(max(0, (self.width - self.min_width) / 100.0), 1)

    # compute character dimensions
    mcw = dpi_r * self.minimap_symbol_width  # minimap char width
    mlh = round(dpi_r * self.minimap_line_height)  # minimap line height
    fs = context.space_data.font_size
    cw = round(dpi_r * round(2 + 0.6 * (fs - 4)))  # char width
    ch = round(dpi_r * round(2 + 1.3 * (fs - 2) +
                             ((fs % 10) == 0)))  # char height

    # panel background box
    self.tab_width = round(dpi_r * 25) if (self.tabs
                                           and len(bpy.data.texts) > 1) else 0
    bgl.glColor4f(self.background.r, self.background.g, self.background.b,
                  (1 - self.bg_opacity) * self.opacity)
    bgl.glBegin(bgl.GL_QUADS)
    for x, y in [(self.left_edge - self.tab_width, self.height),
                 (self.right_edge, self.height), (self.right_edge, 0),
                 (self.left_edge - self.tab_width, 0)]:
        bgl.glVertex2i(x, y)
    bgl.glEnd()

    # line numbers background
    space = context.space_data
    if space.text:
        lines = len(space.text.lines)
        lines_digits = len(str(lines)) if space.show_line_numbers else 0
        self.line_bar_width = int(dpi_r * 5) + cw * (lines_digits)
        bgl.glColor4f(self.background.r, self.background.g, self.background.b,
                      1)
        bgl.glBegin(bgl.GL_QUADS)
        for x, y in [(0, self.height), (self.line_bar_width, self.height),
                     (self.line_bar_width, 0), (0, 0)]:
            bgl.glVertex2i(x, y)
        bgl.glEnd()
        # shadow
        bgl.glLineWidth(1.0 * dpi_r)
        for id, intensity in enumerate(
            [0.2, 0.1, 0.07, 0.05, 0.03, 0.02, 0.01]):
            bgl.glColor4f(0.0, 0.0, 0.0, intensity)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            for x, y in [(self.line_bar_width + id, 0),
                         (self.line_bar_width + id, self.height)]:
                bgl.glVertex2i(x, y)
            bgl.glEnd()

    # minimap shadow
    for id, intensity in enumerate([0.2, 0.1, 0.07, 0.05, 0.03, 0.02, 0.01]):
        bgl.glColor4f(0.0, 0.0, 0.0, intensity * self.opacity)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for x, y in [(self.left_edge - id - self.tab_width, 0),
                     (self.left_edge - id - self.tab_width, self.height)]:
            bgl.glVertex2i(x, y)
        bgl.glEnd()

    # divider
    if self.tab_width:
        bgl.glColor4f(0.0, 0.0, 0.0, 0.2 * self.opacity)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for x, y in [(self.left_edge, 0), (self.left_edge, self.height)]:
            bgl.glVertex2i(x, y)
        bgl.glEnd()

    # if there is text in window
    if space.text and self.opacity:

        # minimap horizontal sliding based on text block length
        max_slide = max(0, mlh * (lines + self.height / ch) - self.height)
        self.slide = int(max_slide * space.top / lines)
        minimap_top_line = int(self.slide / mlh)
        minimap_bot_line = int((self.height + self.slide) / mlh)

        # draw minimap visible box
        if self.in_minimap:
            bgl.glColor4f(1.0, 1.0, 1.0, 0.1 * self.opacity)
        else:
            bgl.glColor4f(1.0, 1.0, 1.0, 0.07 * self.opacity)
        bgl.glBegin(bgl.GL_QUADS)
        for x, y in [
            (self.left_edge, self.height - mlh * space.top + self.slide),
            (self.right_edge, self.height - mlh * space.top + self.slide),
            (self.right_edge, self.height - mlh *
             (space.top + space.visible_lines) + self.slide),
            (self.left_edge, self.height - mlh *
             (space.top + space.visible_lines) + self.slide)
        ]:
            bgl.glVertex2i(x, y)
        bgl.glEnd()

        # draw minimap code
        for segment in self.segments[:-1]:
            bgl.glColor4f(segment['col'][0], segment['col'][1],
                          segment['col'][2], 0.4 * self.opacity)
            for id, element in enumerate(
                    segment['elements'][minimap_top_line:minimap_bot_line]):
                loc_y = mlh * (id + minimap_top_line + 3) - self.slide
                for sub_element in element:
                    draw_line(
                        (self.left_edge + int(mcw * (sub_element[0] + 4)),
                         self.height - loc_y),
                        int(mcw * (sub_element[1] - sub_element[0])),
                        int(0.5 * mlh))

        # minimap code marks
        bgl.glColor4f(self.segments[-2]['col'][0], self.segments[-2]['col'][1],
                      self.segments[-2]['col'][2],
                      0.3 * self.block_trans * self.opacity)
        for id, element in enumerate(self.segments[-2]['elements']):
            for sub_element in element:
                if sub_element[
                        2] >= space.top or id < space.top + space.visible_lines:
                    draw_line(
                        (self.left_edge + int(mcw * (sub_element[0] + 4)),
                         self.height - mlh * (id + 3) + self.slide),
                        -int(mlh * (sub_element[2] - id - 1)), int(0.5 * mlh),
                        True)

    # draw dotted indentation marks
    bgl.glLineWidth(1.0 * dpi_r)
    if space.text:
        bgl.glColor4f(self.segments[0]['col'][0], self.segments[0]['col'][1],
                      self.segments[0]['col'][2], self.indent_trans)
        for id, element in enumerate(
                self.segments[-1]['elements'][space.top:space.top +
                                              space.visible_lines]):
            loc_y = id
            for sub_element in element:
                draw_line(
                    (int(dpi_r * 10) + cw *
                     (lines_digits + sub_element[0] + 4), self.height - ch *
                     (loc_y)), -ch, int(1 * dpi_r), True)

        # draw code block marks
        bgl.glColor4f(self.segments[-2]['col'][0], self.segments[-2]['col'][1],
                      self.segments[-2]['col'][2], self.block_trans)
        for id, element in enumerate(self.segments[-2]['elements']):
            for sub_element in element:
                if sub_element[
                        2] >= space.top or id < space.top + space.visible_lines:
                    bgl.glBegin(bgl.GL_LINE_STRIP)
                    bgl.glVertex2i(
                        int(dpi_r * 10 + cw * (lines_digits + sub_element[0])),
                        self.height - ch * (id + 1 - space.top))
                    bgl.glVertex2i(
                        int(dpi_r * 10 + cw * (lines_digits + sub_element[0])),
                        self.height - int(ch * (sub_element[2] - space.top)))
                    bgl.glVertex2i(
                        int(dpi_r * 10 + cw *
                            (lines_digits + sub_element[0] + 1)),
                        self.height - int(ch * (sub_element[2] - space.top)))
                    bgl.glEnd()

    # tab dividers
    if self.tab_width and self.opacity:
        self.tab_height = min(200, int(self.height / len(bpy.data.texts)))
        y_loc = self.height - 5
        for text in bpy.data.texts:
            # tab selection
            if text.name == self.in_tab:
                bgl.glColor4f(1.0, 1.0, 1.0, 0.05 * self.opacity)
                bgl.glBegin(bgl.GL_QUADS)
                for x, y in [(self.left_edge - self.tab_width, y_loc),
                             (self.left_edge, y_loc),
                             (self.left_edge, y_loc - self.tab_height),
                             (self.left_edge - self.tab_width,
                              y_loc - self.tab_height)]:
                    bgl.glVertex2i(x, y)
                bgl.glEnd()
            # tab active
            if context.space_data.text and text.name == context.space_data.text.name:
                bgl.glColor4f(1.0, 1.0, 1.0, 0.05 * self.opacity)
                bgl.glBegin(bgl.GL_QUADS)
                for x, y in [(self.left_edge - self.tab_width, y_loc),
                             (self.left_edge, y_loc),
                             (self.left_edge, y_loc - self.tab_height),
                             (self.left_edge - self.tab_width,
                              y_loc - self.tab_height)]:
                    bgl.glVertex2i(x, y)
                bgl.glEnd()
            bgl.glColor4f(0.0, 0.0, 0.0, 0.2 * self.opacity)
            y_loc -= self.tab_height
            bgl.glBegin(bgl.GL_LINE_STRIP)
            for x, y in [(self.left_edge - self.tab_width, y_loc),
                         (self.left_edge, y_loc)]:
                bgl.glVertex2i(x, y)
            bgl.glEnd()

    # draw fps
#    bgl.glColor4f(1, 1, 1, 0.2)
#    blf.size(font_id, fs, int(dpi_r*72))
#    blf.position(font_id, self.left_edge-50, 5, 0)
#    blf.draw(font_id, str(round(1/(time.clock() - start),3)))

# draw line numbers
    if space.text:
        bgl.glColor4f(self.segments[0]['col'][0], self.segments[0]['col'][1],
                      self.segments[0]['col'][2], 0.5)
        for id in range(space.top,
                        min(space.top + space.visible_lines + 1, lines + 1)):
            if self.in_line_bar and self.segments[-2]['elements'][id - 1]:
                bgl.glColor4f(self.segments[-2]['col'][0],
                              self.segments[-2]['col'][1],
                              self.segments[-2]['col'][2], 1)
                blf.position(font_id,
                             2 + int(0.5 * cw * (len(str(lines)) - 1)),
                             self.height - ch * (id - space.top) + 3, 0)
                #blf.draw(font_id, '→')
                blf.draw(font_id, '↓')
                bgl.glColor4f(self.segments[0]['col'][0],
                              self.segments[0]['col'][1],
                              self.segments[0]['col'][2], 0.5)
            else:
                blf.position(
                    font_id,
                    2 + int(0.5 * cw * (len(str(lines)) - len(str(id)))),
                    self.height - ch * (id - space.top) + 3, 0)
                blf.draw(font_id, str(id))

    # draw file names
    if self.tab_width:
        blf.enable(font_id, blf.ROTATION)
        blf.rotation(font_id, 1.570796)
        y_loc = self.height
        for text in bpy.data.texts:
            text_max_length = max(2, int((self.tab_height - 40) / cw))
            name = text.name[:text_max_length]
            if text_max_length < len(text.name):
                name += '...'
            bgl.glColor4f(
                self.segments[0]['col'][0], self.segments[0]['col'][1],
                self.segments[0]['col'][2],
                (0.7 if text.name == self.in_tab else 0.4) * self.opacity)
            blf.position(
                font_id, self.left_edge - round(
                    (self.tab_width - ch) / 2.0) - 5,
                round(y_loc - (self.tab_height / 2) - cw * len(name) / 2), 0)
            blf.draw(font_id, name)
            y_loc -= self.tab_height

    # restore opengl defaults
    bgl.glColor4f(0, 0, 0, 1)
    bgl.glLineWidth(1.0)
    bgl.glDisable(bgl.GL_BLEND)
    blf.disable(font_id, blf.ROTATION)
    return
Пример #59
0
 def _set(self, instance, value):
     glLineWidth(value)
Пример #60
0
def display_geowidget(region, rv3d, fac, ro_hor, q, helploc, n, qdef,
                      geowidget_base, geowidget_top, geowidget_rest):

    geowidget_cross = [(0.0, 2.1, 0.0), (0.0, 0.9, 0.0), (-2.1, 0.0, 0.0),
                       (-0.9, 0.0, 0.0)]

    # drawing of geowidget - cross part:
    for i, co in enumerate(geowidget_cross):
        co = Vector(co)
        co = co * fac
        geowidget_cross[i] = co

    geowidget_cross = rotate_graphic(geowidget_cross, ro_hor)
    geowidget_cross = rotate_graphic(geowidget_cross, q)
    geowidget_cross = translate_graphic(geowidget_cross, helploc)

    col_gw_line_cross = addon_settings_graph('col_gw_line_cross')
    col_gw_line_base_free = addon_settings_graph('col_gw_line_base_free')
    col_gw_line_base_lock_x = addon_settings_graph('col_gw_line_base_lock_x')
    col_gw_line_base_lock_y = addon_settings_graph('col_gw_line_base_lock_y')
    col_gw_line_base_lock_z = addon_settings_graph('col_gw_line_base_lock_z')
    col_gw_line_base_lock_arb = addon_settings_graph(
        'col_gw_line_base_lock_arb')
    col_gw_line_all = addon_settings_graph('col_gw_line_all')

    col_gw_fill_base_x = addon_settings_graph('col_gw_fill_base_x')
    col_gw_fill_base_y = addon_settings_graph('col_gw_fill_base_y')
    col_gw_fill_base_z = addon_settings_graph('col_gw_fill_base_z')
    col_gw_fill_base_arb = addon_settings_graph('col_gw_fill_base_arb')

    bgl.glColor4f(*col_gw_line_cross)
    bgl.glLineWidth(1)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i, co in enumerate(geowidget_cross):
        if i in range(
                0, 2
        ):  # range is always - first as is, second one one higher than last
            #np_print(i)
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
            geowidget_cross[i] = co
    bgl.glEnd()
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i, co in enumerate(geowidget_cross):
        if i in range(
                2, 4
        ):  # range is always - first as is, second one one higher than last
            #np_print(i)
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
            geowidget_cross[i] = co
    bgl.glEnd()

    # drawing of geowidget - base part:

    for i, co in enumerate(geowidget_base):
        co = Vector(co)
        co = co * fac
        geowidget_base[i] = co

    geowidget_base = rotate_graphic(geowidget_base, ro_hor)
    geowidget_base = rotate_graphic(geowidget_base, q)
    geowidget_base = translate_graphic(geowidget_base, helploc)

    n = n.to_tuple()
    n = list(n)
    for i, co in enumerate(n):
        n[i] = abs(round(co, 4))
    np_print('n for color', n)

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(*col_gw_line_base_free)
    bgl.glLineWidth(1)
    if qdef != None:
        if n[0] == 0.0 and n[1] == 0.0 and n[2] == 1.0:
            bgl.glColor4f(*col_gw_line_base_lock_z)
        elif n[0] == 1.0 and n[1] == 0.0 and n[2] == 0.0:
            bgl.glColor4f(*col_gw_line_base_lock_x)
        elif n[0] == 0.0 and n[1] == 1.0 and n[2] == 0.0:
            bgl.glColor4f(*col_gw_line_base_lock_y)
        else:
            bgl.glColor4f(*col_gw_line_base_lock_arb)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for i, co in enumerate(geowidget_base):
        #np_print(i)
        co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
        bgl.glVertex2f(*co)
        geowidget_base[i] = co
    bgl.glVertex2f(*geowidget_base[0])
    bgl.glEnd()

    bgl.glColor4f(*col_gw_fill_base_arb)
    if n[0] == 0.0 and n[1] == 0.0 and n[2] == 1.0:
        bgl.glColor4f(*col_gw_fill_base_z)
        np_print('go_Z')
    elif n[0] == 1.0 and n[1] == 0.0 and n[2] == 0.0:
        bgl.glColor4f(*col_gw_fill_base_x)
        np_print('go_X')
    elif n[0] == 0.0 and n[1] == 1.0 and n[2] == 0.0:
        bgl.glColor4f(*col_gw_fill_base_y)
        np_print('go_Y')
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    for co in geowidget_base:
        bgl.glVertex2f(*co)
    bgl.glEnd()

    # drawing of geowidget - top part:

    if geowidget_top != None:
        for i, co in enumerate(geowidget_top):
            co = Vector(co)
            co = co * fac
            geowidget_top[i] = co

        geowidget_top = rotate_graphic(geowidget_top, ro_hor)
        geowidget_top = rotate_graphic(geowidget_top, q)
        geowidget_top = translate_graphic(geowidget_top, helploc)

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(*col_gw_line_all)
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for i, co in enumerate(geowidget_top):
            #np_print(i)
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
            geowidget_top[i] = co
        bgl.glVertex2f(*geowidget_top[0])
        bgl.glEnd()

    # drawing of geowidget - rest part:

    if geowidget_rest != None:
        for i, co in enumerate(geowidget_rest):
            co = Vector(co)
            co = co * fac
            geowidget_rest[i] = co

        geowidget_rest = rotate_graphic(geowidget_rest, ro_hor)
        geowidget_rest = rotate_graphic(geowidget_rest, q)
        geowidget_rest = translate_graphic(geowidget_rest, helploc)

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(*col_gw_line_all)
        bgl.glLineWidth(1)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for i, co in enumerate(geowidget_rest):
            #np_print(i)
            co = view3d_utils.location_3d_to_region_2d(region, rv3d, co)
            bgl.glVertex2f(*co)
            geowidget_rest[i] = co
        bgl.glVertex2f(*geowidget_rest[0])
        bgl.glEnd()