Exemplo n.º 1
0
    def draw_texture(x=0, y=0, w=30, h=10, texname=texname):
        # function to draw a texture
        bgl.glDisable(bgl.GL_DEPTH_TEST)

        act_tex = bgl.Buffer(bgl.GL_INT, 1)
        bgl.glGetIntegerv(bgl.GL_TEXTURE_2D, act_tex)

        bgl.glEnable(bgl.GL_TEXTURE_2D)
        bgl.glActiveTexture(bgl.GL_TEXTURE0)
        bgl.glTexEnvf(bgl.GL_TEXTURE_ENV, bgl.GL_TEXTURE_ENV_MODE, bgl.GL_REPLACE)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, texname)

        texco = [(0, 1), (1, 1), (1, 0), (0, 0)]
        verco = [(x, y), (x + w, y), (x + w, y - h), (x, y - h)]

        bgl.glPolygonMode(bgl.GL_FRONT_AND_BACK, bgl.GL_FILL)
        bgl.glBegin(bgl.GL_QUADS)
        for i in range(4):
            bgl.glTexCoord3f(texco[i][0], texco[i][1], 0.0)
            bgl.glVertex2f(verco[i][0], verco[i][1])
        bgl.glEnd()

        # restoring settings
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, act_tex[0])
        bgl.glDisable(bgl.GL_TEXTURE_2D)
Exemplo n.º 2
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)
Exemplo n.º 3
0
    def draw_preview(self):
        bgl.glPushAttrib(bgl.GL_ALL_ATTRIB_BITS)
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glPushMatrix()
        bgl.glLoadIdentity()
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glPushMatrix()
        bgl.glLoadIdentity()

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glDisable(bgl.GL_DEPTH_TEST)

        bgl.glBegin(bgl.GL_QUADS)   # TODO: not use immediate mode
        bgl.glColor4f(0,0,0.2,0.5)
        bgl.glVertex2f(-1, -1)
        bgl.glVertex2f( 1, -1)
        bgl.glColor4f(0,0,0.2,0)
        bgl.glVertex2f( 1,  1)
        bgl.glVertex2f(-1,  1)
        bgl.glEnd()

        bgl.glPopMatrix()
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glPopMatrix()
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glPopAttrib()
Exemplo n.º 4
0
def screen_v3dBGL(context, args):
    region = context.region
    region3d = context.space_data.region_3d
    
    points = args[0]
    colors = args[1]
    size= 5.0
    
    bgl.glEnable(bgl.GL_POINT_SMOOTH) # for round vertex
    bgl.glPointSize(size)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    
    if colors:
        bgl.glBegin(bgl.GL_POINTS)
        for coord, color in zip(points, colors):
            bgl.glColor4f(*color)    
            bgl.glVertex3f(*coord)
        bgl.glEnd()

    else:
        gl_col = (0.9, 0.9, 0.8, 1.0)
        bgl.glColor4f(*gl_col)    
        bgl.glBegin(bgl.GL_POINTS)
        for coord in points:
            bgl.glVertex3f(*coord)
        bgl.glEnd()        
    
    bgl.glDisable(bgl.GL_POINT_SMOOTH)
    bgl.glDisable(bgl.GL_POINTS)
Exemplo n.º 5
0
    def draw_postpixel(self):
        bgl.glPushAttrib(bgl.GL_ALL_ATTRIB_BITS)

        bgl.glEnable(bgl.GL_BLEND)

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

        bgl.glColor4f(1,0,0,0.2)    # TODO: use window background color??
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glDisable(bgl.GL_DEPTH_TEST)
        bgl.glBegin(bgl.GL_QUADS)   # TODO: not use immediate mode
        bgl.glVertex2f(-1, -1)
        bgl.glVertex2f( 1, -1)
        bgl.glVertex2f( 1,  1)
        bgl.glVertex2f(-1,  1)
        bgl.glEnd()

        bgl.glPopMatrix()
        bgl.glMatrixMode(bgl.GL_MODELVIEW)
        bgl.glPopMatrix()
        bgl.glMatrixMode(bgl.GL_PROJECTION)
        bgl.glPopAttrib()
Exemplo n.º 6
0
 def reload(self, path):
     bgl.glEnable(bgl.GL_TEXTURE_2D)
     
     if path == self.path: return
     if path in logic.texture_cache:
         img = logic.texture_cache[path]
     else:
         img = texture.ImageFFmpeg(path)
         img.scale = False
         if self._cache:
             logic.texture_cache[path] = img
     
     data = img.image
     if data == None:
         print("Could not load the image", img)
         self.valid = False
         return
             
     self.bind()
     bgl.glTexImage2D(bgl.GL_TEXTURE_2D, 0, bgl.GL_RGBA, img.size[0],
                      img.size[1], 0, bgl.GL_RGBA,
                      bgl.GL_UNSIGNED_BYTE, data)
     
     self.size = img.size[:]
     self.path = path
     
     img = None
Exemplo n.º 7
0
def h_draw_gradient_rect(bounds, gradient, border_width=1, border_radius=0, border_color=(0, 0, 0, 1), wire=False):
    if len(gradient.colors) != len(gradient.offsets): return
    
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    
    h_mask_begin(bounds, border_radius)
    
    mode = bgl.GL_LINE_STRIP if wire else bgl.GL_TRIANGLE_STRIP
    
    bgl.glBegin(mode)
    if gradient.orientation == 0: # HOR
        for i in range(len(gradient.colors)):
            bgl.glColor4f(*gradient.colors[i])
            x = (bounds[2] * clamp(gradient.offsets[i], 0.0, 1.0)) + bounds[0]
            bgl.glVertex2f(x, bounds[1])
            bgl.glVertex2f(x, bounds[1]+bounds[3])
    elif gradient.orientation == 1: # VER
        for i in range(len(gradient.colors)):
            bgl.glColor4f(*gradient.colors[i])
            y = (bounds[3] * clamp(gradient.offsets[i], 0.0, 1.0)) + bounds[1]
            bgl.glVertex2f(bounds[0], y)
            bgl.glVertex2f(bounds[0]+bounds[2], y)
    bgl.glEnd()
        
    h_mask_end()
    
    if border_width > 0:
        h_round_rect_wire(bounds, border_radius, color=border_color, width=border_width)
    
    bgl.glDisable(bgl.GL_BLEND)
 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)))
Exemplo n.º 9
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)
Exemplo n.º 10
0
def h_draw_texture(id, w, h, bounds, coords):    
    bgl.glEnable(bgl.GL_TEXTURE_2D)
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, id)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
    
    bgl.glColor4f(*(1,1,1,1))
    
    B = bounds
    C = coords
    
    D = [
        (C[0][0]/w, C[0][1]/h),
        (C[1][0]/w, C[1][1]/h),
        (C[2][0]/w, C[2][1]/h),
        (C[3][0]/w, C[3][1]/h),
    ]
    #print(D)
    
    bgl.glBegin(bgl.GL_QUADS)
    bgl.glTexCoord2f(D[0][0], D[0][1])    
    bgl.glVertex2f(B[0], B[1])
    
    bgl.glTexCoord2f(D[1][0], D[1][1])    
    bgl.glVertex2f(B[0]+B[2], B[1])
    
    bgl.glTexCoord2f(D[2][0], D[2][1])    
    bgl.glVertex2f(B[0]+B[2], B[1]+B[3])
    
    bgl.glTexCoord2f(D[3][0], D[3][1])    
    bgl.glVertex2f(B[0], B[1]+B[3])
    bgl.glEnd()

    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)
    bgl.glDisable(bgl.GL_TEXTURE_2D)
Exemplo n.º 11
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)
Exemplo n.º 12
0
def cursor_history_draw(cls,context):
    cc = context.scene.cursor_history

    draw = 0
    if hasattr(cc, "historyDraw"):
        draw = cc.historyDraw

    if(draw):
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glShadeModel(bgl.GL_FLAT)
        alpha = 1-PHI_INV
        # History Trace
        if cc.historyPosition[0]<0:
            return
        bgl.glBegin(bgl.GL_LINE_STRIP)
        ccc = 0
        for iii in range(cc.historyWindow+1):
            ix_rel = iii - int(cc.historyWindow / 2)
            ix = cc.historyPosition[0] + ix_rel
            if(ix<0 or ix>=len(cc.historyLocation)):
                continue
            ppp = region3d_get_2d_coordinates(context, cc.historyLocation[ix])
            if(ix_rel<=0):
                bgl.glColor4f(0, 0, 0, alpha)
            else:
                bgl.glColor4f(1, 0, 0, alpha)
            bgl.glVertex2f(ppp[0], ppp[1])
            ccc = ccc + 1
        bgl.glEnd()
Exemplo n.º 13
0
 def draw_one(u):
     c = PCVCache.cache[u]
     # update matrix, every frame for now, it should be done better.. but it works well..
     m = c['object'].matrix_world
     matrix = []
     for v in m.transposed():
         matrix.extend(list(v.to_tuple()))
     matrix_buffer = bgl.Buffer(bgl.GL_FLOAT, len(matrix), matrix)
     c['matrix'] = m
     c['matrix_buffer'] = matrix_buffer
     
     bgl.glPushMatrix()
     bgl.glMultMatrixf(c['matrix_buffer'])
     
     bgl.glEnable(bgl.GL_DEPTH_TEST)
     bgl.glEnableClientState(bgl.GL_VERTEX_ARRAY)
     bgl.glVertexPointer(3, bgl.GL_FLOAT, 0, c['vertex_buffer'])
     bgl.glEnableClientState(bgl.GL_COLOR_ARRAY)
     bgl.glColorPointer(3, bgl.GL_FLOAT, 0, c['color_buffer'])
     
     if(PCVCache.cache[u]['smooth']):
         bgl.glEnable(bgl.GL_POINT_SMOOTH)
     
     l = int((c['length'] / 100) * c['display_percent'])
     bgl.glDrawArrays(bgl.GL_POINTS, 0, l)
     
     bgl.glDisableClientState(bgl.GL_VERTEX_ARRAY)
     bgl.glDisableClientState(bgl.GL_COLOR_ARRAY)
     
     if(c['smooth']):
         bgl.glDisable(bgl.GL_POINT_SMOOTH)
     bgl.glDisable(bgl.GL_DEPTH_TEST)
     
     bgl.glPopMatrix()
Exemplo n.º 14
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)
    def draw_callback_px(self, context):
        if context.region.id != self.region_id:
            return
        posx = 70
        posy1 = 30
        posy2 = 50
        text_interval = 5
        font_id = 0
        blf.size(font_id, 11, context.user_preferences.system.dpi)
        bgl.glEnable(bgl.GL_BLEND)
        if self.changing_mgtype:
            bgl.glColor4f(1.0, 1.0, 0.0, 1.0)
        else:
            bgl.glColor4f(1.0, 1.0, 1.0, 1.0)

        # draw origin
        bgl.glLineWidth(2)
        radius = path_threthold
        radius2 = radius + 5
        x, y, z = self.path[0]
        bgl.glBegin(bgl.GL_LINES)
        for i in range(4):
            r = math.pi / 2 * i + math.pi / 4
            bgl.glVertex2f(x + radius * math.cos(r), y + radius * math.sin(r))
            bgl.glVertex2f(x + radius2 * math.cos(r),
                           y + radius2 * math.sin(r))
        bgl.glEnd()
        bgl.glLineWidth(1)

        # draw lines
        bgl.glEnable(bgl.GL_LINE_STIPPLE)
        bgl.glLineStipple(1, int(0b101010101010101))  # (factor, pattern)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for v in self.path:
            bgl.glVertex2f(v[0], v[1])
        bgl.glEnd()
        bgl.glLineStipple(1, 1)
        bgl.glDisable(bgl.GL_LINE_STIPPLE)

        # draw txt
        if self.action or self.mgitem:
            x = posx
            for txt in self.action:
                blf.position(font_id, x, posy1, 0)
                blf.draw(font_id, txt)
                text_width, text_height = blf.dimensions(font_id, txt)
                x += text_width + text_interval
            if self.mgitem:
                blf.position(font_id, posx, posy2, 0)
                blf.draw(font_id, self.mgitem.name)
        else:
            #blf.position(font_id, posx, posy2, 0)
            #blf.draw(font_id, '[Mouse Gesture]')
            pass

        # restore opengl defaults
        bgl.glLineWidth(1)
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
        blf.size(0, 11, context.user_preferences.system.dpi)
Exemplo n.º 16
0
def draw_texture(x, y, w, h, texture, mode=None):
    mode_bak = bgl.Buffer(bgl.GL_INT, 1)
    bgl.glGetIntegerv(bgl.GL_DRAW_BUFFER, mode_bak)
    if mode is not None:
        bgl.glDrawBuffer(mode)

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

    bgl.glColor4d(1.0, 1.0, 1.0, 1.0)
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glTexCoord2d(0.0, 0.0)
    bgl.glVertex2i(x, y)
    bgl.glTexCoord2d(1.0, 0.0)
    bgl.glVertex2i(x + w, y)
    bgl.glTexCoord2d(1.0, 1.0)
    bgl.glVertex2i(x + w, y + h)
    bgl.glTexCoord2d(0.0, 1.0)
    bgl.glVertex2i(x, y + h)
    bgl.glEnd()

    bgl.glDisable(bgl.GL_TEXTURE_2D)
    bgl.glBindTexture(bgl.GL_TEXTURE_2D, 0)

    if mode is not None:
        bgl.glDrawBuffer(mode_bak[0])
def draw_channel_color(scroller_width, channel_coords, curx, color):
    from bgl import glColor4f, glRectf, glEnable, glDisable, glBlendFunc, GL_BLEND, GL_ONE, GL_SRC_ALPHA

    context = bpy.context

    # Strip coords
    s_x1, s_y1, s_x2, s_y2 = channel_coords

    # Drawing coords
    x = 0
    d_y1 = s_y1
    d_y2 = s_y2
    d_x1 = s_x1
    d_x2 = s_x2

    # be careful not to override the current frame line
    cf_x = context.scene.frame_current_final
    y = 0

    r, g, b, a = color
    glColor4f(r, g, b, a)
    glEnable(GL_BLEND)
    # glBlendFunc(GL_SRC_ALPHA, GL_ONE);

    if d_x1 < cf_x and cf_x < d_x2:
        # current frame line over strip
        glRectf(d_x1, d_y1, cf_x - curx, d_y2)
        glRectf(cf_x + curx, d_y1, d_x2, d_y2)
    else:
        # Normal, full rectangle draw
        glRectf(d_x1, d_y1, d_x2, d_y2)

    glDisable(GL_BLEND)
Exemplo n.º 18
0
def draw_callback(self, context):
    mid = int(360 * self.recv / self.fsize)
    cx = 200
    cy = 30
    blf.position(0, 230, 23, 0)
    blf.size(0, 20, 72)
    blf.draw(0, "{0:2d}% of {1}".format(100 * self.recv // self.fsize, self.hfsize))

    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(0.7, 0.7, 0.7, 0.8)
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glVertex2i(cx, cy)
    for i in range(mid):
        x = cx + 20 * math.sin(math.radians(float(i)))
        y = cy + 20 * math.cos(math.radians(float(i)))
        bgl.glVertex2f(x, y)
    bgl.glEnd()

    bgl.glColor4f(0.0, 0.0, 0.0, 0.6)
    bgl.glBegin(bgl.GL_TRIANGLE_FAN)
    bgl.glVertex2i(cx, cy)
    for i in range(mid, 360):
        x = cx + 20 * math.sin(math.radians(float(i)))
        y = cy + 20 * math.cos(math.radians(float(i)))
        bgl.glVertex2f(x, y)
    bgl.glEnd()

    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
	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()
Exemplo n.º 20
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)
Exemplo n.º 21
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)
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.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  
      
    return
Exemplo n.º 23
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)
Exemplo n.º 24
0
 def draw(self):
     width = render.getWindowWidth()
     height = render.getWindowHeight()
     
     # 2D Projection
     bgl.glMatrixMode(bgl.GL_PROJECTION)
     bgl.glLoadIdentity()
     bgl.glOrtho(0, width, height, 0, -1, 1)
     bgl.glMatrixMode(bgl.GL_MODELVIEW)
     bgl.glLoadIdentity()
     
     # 2D Shading
     bgl.glDisable(bgl.GL_CULL_FACE)
     bgl.glDisable(bgl.GL_LIGHTING)
     bgl.glDisable(bgl.GL_DEPTH_TEST)
     bgl.glShadeModel(bgl.GL_SMOOTH)
     
     # Line antialias
     bgl.glEnable(bgl.GL_LINE_SMOOTH)
     bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
     
     # 2D Blending (Alpha)
     bgl.glEnable(bgl.GL_BLEND)
     bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
     
     if len(self.controls.values()) <= 0: return
     
     ctrls = sorted(self.controls.values(), key=lambda x: x.zorder)
     for c in ctrls:
         c.draw()
Exemplo n.º 25
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)
Exemplo n.º 26
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)
Exemplo n.º 27
0
def viconutil_draw_lineloop_smooth(pts):
    linesmooth = vagl.Buffer('bool', 0, bgl.GL_LINE_SMOOTH)
    if not linesmooth:
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
    viconutil_draw_lineloop(pts)
    if not linesmooth:
        bgl.glDisable(bgl.GL_LINE_SMOOTH)
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)  
    
    
    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
Exemplo n.º 29
0
def h_draw_arc(cx, cy, r, start_angle, arc_angle, color=(1,1,1,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.glBegin(bgl.GL_POLYGON)
    
    bgl.glVertex2f(cx, cy)
    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)
    def visualise(self, context):
        area = context.area
        speaker = context.scene.speaker
        action = getAction(speaker)
        scene = context.scene
        frame = scene.frame_current
        """
        print("MHHM")
        action = context.screen.sound_driver_areas["VIEW_3D_4"].action
        print("THIS WORKING", action)
        #action = context.area.sound_action # NEW IDEA REFACTO
        """
        if action is None:
            return None

        area_settings = self.area_settings(context)
        if area_settings is None:
            return None
        (x, y) = area_settings.loc
        fw = context.area.regions[-1].width - (x + 20)
        fh = context.area.regions[-1].height - 50
        area_settings = self.area_settings(context)

        AMP = area_settings.height * fh / 100
        if action.get("MIDI"):

            bgl.glEnable(bgl.GL_BLEND)
            self.draw_box(x, y + AMP, 3 * fw, 20, color=self.gridcol)
            bgl.glDisable(bgl.GL_BLEND)
            self.draw_action_header_text(x, y + AMP, speaker, action)
            self.draw_midi_keyboard(x, y, fw, AMP, action=action, frame=frame)
        else:
            self.draw_spectrum(context, x, y, speaker, action)
Exemplo n.º 31
0
    def render_main(self, context, objlist, animation=False):
        # noinspection PyBroadException,PyBroadException
        # Save old info
        scene = context.scene
        render = scene.render
        settings = render.image_settings
        depth = settings.color_depth
        settings.color_depth = '8'
        # noinspection PyBroadException
        try:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    bgl.glEnd()

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

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

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

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

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

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

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

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

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

                self.save_image(outpath, out)

            settings.color_depth = depth
            return True

        except:
            settings.color_depth = depth
            print("Unexpected error:" + str(exc_info()))
            self.report({
                'ERROR'
            }, "Archipack: Unable to create render image. Be sure the output render path is correct"
                        )
            return False
Exemplo n.º 32
0
    def draw_2D(self, context):
        settings = common_utilities.get_settings()
        region,r3d = context.region,context.space_data.region_3d
        
        color_inactive = settings.theme_colors_mesh[settings.theme]
        color_selection = settings.theme_colors_selection[settings.theme]
        color_active = settings.theme_colors_active[settings.theme]

        color_frozen = settings.theme_colors_frozen[settings.theme]
        color_warning = settings.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)
        

        if self.fsm_mode == 'sketch' and self.sketch:
            # Draw smoothing line (end of sketch to current mouse position)
            common_drawing_px.draw_polyline_from_points(context, [self.sketch_curpos, self.sketch[-1][0]], color_active, 1, "GL_LINE_SMOOTH")

            # Draw sketching stroke
            common_drawing_px.draw_polyline_from_points(context, [co[0] for co in self.sketch], color_selection, 2, "GL_LINE_STIPPLE")

        if self.fsm_mode in {'scale tool','rotate tool'}:
            # Draw a scale/rotate line from tool origin to current mouse position
            common_drawing_px.draw_polyline_from_points(context, [self.action_center, self.mode_pos], (0, 0, 0, 0.5), 1, "GL_LINE_STIPPLE")

        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 self.fsm_mode not in {'grab tool','scale tool','rotate tool'} and not self.is_navigating:
            # draw the brush oriented to surface
            ray,hit = common_utilities.ray_cast_region2d_bvh(region, r3d, self.cur_pos, mesh_cache['bvh'], self.mx, settings)
            hit_p3d,hit_norm,hit_idx = hit
            if hit_idx != None: # and not self.hover_ed:
                mx = self.mx
                mxnorm = mx.transposed().inverted().to_3x3()
                hit_p3d = mx * hit_p3d
                hit_norm = mxnorm * hit_norm
                common_drawing_px.draw_circle(context, hit_p3d, hit_norm.normalized(), self.stroke_radius, (1,1,1,.5))

            if self.fsm_mode == 'sketch' and self.sketch:
                ray,hit = common_utilities.ray_cast_region2d_bvh(region, r3d, self.sketch[0][0], mesh_cache['bvh'],self.mx, settings)
                hit_p3d,hit_norm,hit_idx = hit
                if hit_idx != None:
                    mx = self.mx
                    mxnorm = mx.transposed().inverted().to_3x3()
                    hit_p3d = mx * hit_p3d
                    hit_norm = mxnorm * hit_norm
                    common_drawing_px.draw_circle(context, hit_p3d, hit_norm.normalized(), self.stroke_radius, (1,1,1,.5))

        if self.hover_ed and False:  #EXTEND  to display hoverable edges
            color = (color_selection[0], color_selection[1], color_selection[2], 1.00)
            common_drawing_px.draw_bmedge(context, self.hover_ed, self.dest_obj.matrix_world, 2, color)

        if self.act_gedge:
            if settings.show_segment_count:
                bgl.glColor4f(*color_active)
                self.draw_gedge_info(self.act_gedge, context)
        
        if self.act_gpatch:
            if settings.show_segment_count:
                bgl.glColor4f(*color_active)
                self.draw_gpatch_info(self.act_gpatch, context)
        
        if True:
            txt = 'v:%d e:%d s:%d p:%d' % (len(self.polystrips.gverts), len(self.polystrips.gedges), len(self.polystrips.gedgeseries), len(self.polystrips.gpatches))
            txt_width, txt_height = blf.dimensions(0, txt)
            
            bgl.glEnable(bgl.GL_BLEND)
            
            bgl.glColor4f(0,0,0,0.8)
            bgl.glBegin(bgl.GL_QUADS)
            bgl.glVertex2f(0, 0)
            bgl.glVertex2f(10+txt_width, 0)
            bgl.glVertex2f(10+txt_width, 10+txt_height)
            bgl.glVertex2f(0, 10+txt_height)
            bgl.glEnd()
            
            bgl.glColor4f(1,1,1,1)
            blf.position(0, 5, 5, 0)
            blf.draw(0, txt)
Exemplo n.º 33
0
    def draw_3d(self, context):
        settings = common_utilities.get_settings()
        region,r3d = context.region,context.space_data.region_3d
        
        color_inactive = settings.theme_colors_mesh[settings.theme]
        color_selection = settings.theme_colors_selection[settings.theme]
        color_active = settings.theme_colors_active[settings.theme]

        color_frozen = settings.theme_colors_frozen[settings.theme]
        color_warning = settings.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)
        color_mirror = (color_frozen[0], color_frozen[1], color_frozen[2], 0.20)
        
        bgl.glDepthRange(0.0, 0.999)
        bgl.glEnable(bgl.GL_DEPTH_TEST)
        
        def draw3d_polyline(context, points, color, thickness, LINE_TYPE):
            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.glDepthRange(0.0, 0.997)
            bgl.glBegin(bgl.GL_LINE_STRIP)
            for coord in points: bgl.glVertex3f(*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 uninterrupted lines  
        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  
        def draw3d_quad(context, points, color):
            bgl.glEnable(bgl.GL_BLEND)
            bgl.glDepthRange(0.0, 0.999)
            bgl.glBegin(bgl.GL_QUADS)
            bgl.glColor4f(*color)
            for coord in points:
                bgl.glVertex3f(*coord)
            if settings.symmetry_plane == 'x':
                bgl.glColor4f(*color_mirror)
                for coord in points:
                    bgl.glVertex3f(-coord.x,coord.y,coord.z)
            bgl.glEnd()
        def draw3d_quads(context, lpoints, color, color_mirror):
            lpoints = list(lpoints)
            bgl.glEnable(bgl.GL_BLEND)
            bgl.glDepthRange(0.0, 0.999)
            bgl.glBegin(bgl.GL_QUADS)
            bgl.glColor4f(*color)
            for points in lpoints:
                for coord in points:
                    bgl.glVertex3f(*coord)
            if settings.symmetry_plane == 'x':
                bgl.glColor4f(*color_mirror)
                for points in lpoints:
                    for coord in points:
                        bgl.glVertex3f(-coord.x,coord.y,coord.z)
            bgl.glEnd()
        def draw3d_points(context, points, color, size):
            bgl.glColor4f(*color)
            bgl.glPointSize(size)
            bgl.glDepthRange(0.0, 0.997)
            bgl.glBegin(bgl.GL_POINTS)
            for coord in points: bgl.glVertex3f(*coord)
            bgl.glEnd()
            bgl.glPointSize(1.0)
        
        def freeze_color(c):
            return (
                c[0] * 0.5 + color_frozen[0] * 0.5,
                c[1] * 0.5 + color_frozen[1] * 0.5,
                c[2] * 0.5 + color_frozen[2] * 0.5,
                c[3])


        ### Existing Geometry ###
        opts = {
            'poly color': (color_frozen[0], color_frozen[1], color_frozen[2], 0.20),
            'poly depth': (0, 0.999),
            'poly mirror color': (color_mirror[0], color_mirror[1], color_mirror[2], color_mirror[3]),
            'poly mirror depth': (0, 0.999),
            
            'line color': (color_frozen[0], color_frozen[1], color_frozen[2], 1.00),
            'line depth': (0, 0.997),
            'line mirror color': (color_mirror[0], color_mirror[1], color_mirror[2], color_mirror[3]),
            'line mirror depth': (0, 0.997),
            'line mirror stipple': True,
            
            'mirror x': self.settings.symmetry_plane == 'x',
        }
        self.tar_bmeshrender.draw(opts=opts)

        ### Patches ###
        for gpatch in self.polystrips.gpatches:
            if gpatch == self.act_gpatch:
                color_border = (color_active[0], color_active[1], color_active[2], 0.50)
                color_fill = (color_active[0], color_active[1], color_active[2], 0.20)
            else:
                color_border = (color_inactive[0], color_inactive[1], color_inactive[2], 0.50)
                color_fill = (color_inactive[0], color_inactive[1], color_inactive[2], 0.10)
            if gpatch.is_frozen() and gpatch == self.act_gpatch:
                color_border = (color_frozen[0], color_frozen[1], color_frozen[2], 1.00)
                color_fill   = (color_active[0], color_active[1], color_active[2], 0.20)
            elif gpatch.is_frozen():
                color_border = (color_frozen[0], color_frozen[1], color_frozen[2], 1.00)
                color_fill   = (color_frozen[0], color_frozen[1], color_frozen[2], 0.20)
            if gpatch.count_error and gpatch == self.act_gpatch:
                color_border = (color_warning[0], color_warning[1], color_warning[2], 0.50)
                color_fill   = (color_active[0], color_active[1], color_active[2], 0.20)
            elif gpatch.count_error:
                color_border = (color_warning[0], color_warning[1], color_warning[2], 0.50)
                color_fill   = (color_warning[0], color_warning[1], color_warning[2], 0.10)
            
            draw3d_quads(context, gpatch.iter_segments(), color_fill, color_mirror)
            draw3d_closed_polylines(context, gpatch.iter_segments(), color_border, 1, "GL_LINE_STIPPLE")
            draw3d_points(context, [p for p,v,k in gpatch.pts if v], color_border, 3)
            

        ### Edges ###
        for gedge in self.polystrips.gedges:
            # Color active strip
            if gedge == self.act_gedge:
                color_border = (color_active[0], color_active[1], color_active[2], 1.00)
                color_fill   = (color_active[0], color_active[1], color_active[2], 0.20)
            # Color selected strips
            elif gedge in self.sel_gedges:
                color_border = (color_selection[0], color_selection[1], color_selection[2], 0.75)
                color_fill   = (color_selection[0], color_selection[1], color_selection[2], 0.20)
            # Color unselected strips
            else:
                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)
            
            if gedge.is_frozen() and gedge in self.sel_gedges:
                color_border = (color_frozen[0], color_frozen[1], color_frozen[2], 1.00)
                color_fill   = (color_active[0], color_active[1], color_active[2], 0.20)
            elif gedge.is_frozen():
                color_border = (color_frozen[0], color_frozen[1], color_frozen[2], 1.00)
                color_fill   = (color_frozen[0], color_frozen[1], color_frozen[2], 0.20)
            
            draw3d_quads(context, gedge.iter_segments(), color_fill, color_mirror)
            draw3d_closed_polylines(context, gedge.iter_segments(), color_border, 1, "GL_LINE_STIPPLE")

            if settings.debug >= 2:
                # draw bezier
                p0,p1,p2,p3 = gedge.gvert0.snap_pos, gedge.gvert1.snap_pos, gedge.gvert2.snap_pos, gedge.gvert3.snap_pos
                p3d = [cubic_bezier_blend_t(p0,p1,p2,p3,t/16.0) for t in range(17)]
                draw3d_polyline(context, p3d, (1,1,1,0.5),1, "GL_LINE_STIPPLE")
        
        if settings.debug >= 2:
            for gp in self.polystrips.gpatches:
                for rev,gedgeseries in zip(gp.rev, gp.gedgeseries):
                    for revge,ge in zip(gedgeseries.rev, gedgeseries.gedges):
                        color = (0.25,0.5,0.25,0.9) if not revge else (0.5,0.25,0.25,0.9)
                        draw3d_arrow(context, ge.gvert0.snap_pos, ge.gvert3.snap_pos, ge.gvert0.snap_norm, color, 2, '')
                    color = (0.5,1.0,0.5,0.5) if not rev else (1,0.5,0.5,0.5)
                    draw3d_arrow(context, gedgeseries.gvert0.snap_pos, gedgeseries.gvert3.snap_pos, gedgeseries.gvert0.snap_norm, color, 2, '')

        ### Verts ###
        for gv in self.polystrips.gverts:
            p0,p1,p2,p3 = gv.get_corners()

            if gv.is_unconnected() and not gv.from_mesh: continue

            is_active = False
            is_active |= gv == self.act_gvert
            is_active |= self.act_gedge!=None and (self.act_gedge.gvert0 == gv or self.act_gedge.gvert1 == gv)
            is_active |= self.act_gedge!=None and (self.act_gedge.gvert2 == gv or self.act_gedge.gvert3 == gv)

            # Theme colors for selected and unselected gverts
            if is_active:
                color_border = (color_active[0], color_active[1], color_active[2], 0.75)
                color_fill   = (color_active[0], color_active[1], color_active[2], 0.20)
            else:
                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)
            # # Take care of gverts in selected edges
            if gv in self.sel_gverts:
                color_border = (color_selection[0], color_selection[1], color_selection[2], 0.75)
                color_fill   = (color_selection[0], color_selection[1], color_selection[2], 0.20)
            if gv.is_frozen() and is_active :
                color_border = (color_frozen[0], color_frozen[1], color_frozen[2], 1.00)
                color_fill   = (color_active[0], color_active[1], color_active[2], 0.20)
            elif gv.is_frozen():
                color_border = (color_frozen[0], color_frozen[1], color_frozen[2], 1.00)
                color_fill   = (color_frozen[0], color_frozen[1], color_frozen[2], 0.20)

            p3d = [p0,p1,p2,p3,p0]
            draw3d_quads(context, [[p0,p1,p2,p3]], color_fill, color_mirror)
            draw3d_polyline(context, p3d, color_border, 1, "GL_LINE_STIPPLE")

        # Draw inner gvert handles (dots) on each gedge
        p3d = [gvert.position for gvert in self.polystrips.gverts if not gvert.is_unconnected()]
        # color_handle = (color_active[0], color_active[1], color_active[2], 1.00)
        draw3d_points(context, p3d, color_handle, 4)

        ### Vert Handles ###
        if self.act_gvert:
            color_handle = (color_active[0], color_active[1], color_active[2], 1.00)
            gv = self.act_gvert
            p0 = gv.position
            draw3d_points(context, [p0], color_handle, 8)
            
            if gv.is_inner():
                # Draw inner handle when selected
                p1 = gv.gedge_inner.get_outer_gvert_at(gv).position
                draw3d_polyline(context, [p0,p1], color_handle, 2, "GL_LINE_SMOOTH")
            else:
                # Draw both handles when gvert is selected
                p3d = [ge.get_inner_gvert_at(gv).position for ge in gv.get_gedges_notnone() if not ge.is_zippered() and not ge.is_frozen()]
                draw3d_points(context, p3d, color_handle, 8)
                # Draw connecting line between handles
                for p1 in p3d:
                    draw3d_polyline(context, [p0,p1], color_handle, 2, "GL_LINE_SMOOTH")

        # Draw gvert handles on active gedge
        if self.act_gedge and not self.act_gedge.is_frozen():
            color_handle = (color_active[0], color_active[1], color_active[2], 1.00)
            ge = self.act_gedge
            if self.act_gedge.is_zippered():
                p3d = [ge.gvert0.position, ge.gvert3.position]
                draw3d_points(context, p3d, color_handle, 8)
            else:
                p3d = [gv.position for gv in ge.gverts()]
                draw3d_points(context, p3d, color_handle, 8)
                draw3d_polyline(context, [p3d[0], p3d[1]], color_handle, 2, "GL_LINE_SMOOTH")
                draw3d_polyline(context, [p3d[2], p3d[3]], color_handle, 2, "GL_LINE_SMOOTH")
                if False:
                    # draw each normal of each gvert
                    for p,n in zip(p3d,[gv.snap_norm for gv in ge.gverts()]):
                        draw3d_polyline(context, [p,p+n*0.1], color_handle, 1, "GL_LINE_SMOOTH")
        
        if self.hov_gvert:  #TODO, hover color
            color_border = (color_selection[0], color_selection[1], color_selection[2], 1.00)
            color_fill   = (color_selection[0], color_selection[1], color_selection[2], 0.20)
            
            gv = self.hov_gvert
            p0,p1,p2,p3 = gv.get_corners()
            p3d = [p0,p1,p2,p3,p0]
            draw3d_quad(context, [p0,p1,p2,p3], color_fill)
            draw3d_polyline(context, p3d, color_border, 1, "GL_LINE_STIPPLE")
            

        bgl.glLineWidth(1)
        bgl.glDepthRange(0.0, 1.0)
Exemplo n.º 34
0
def restore_gl_defaults():
    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glEnable(bgl.GL_DEPTH_TEST)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Exemplo n.º 35
0
def draw_mouse(context, shape, style, alpha):
    # shape and position
    sc = context.scene
    mouse_size = sc.screencast_keys_mouse_size
    font_size = sc.screencast_keys_font_size
    box_draw = sc.screencast_keys_box_draw

    pos_x, pos_y = getDisplayLocation(context)

    if sc.screencast_keys_mouse_position == 'left':
        offset_x = pos_x
    if sc.screencast_keys_mouse_position == 'right':
        offset_x = context.region.width - pos_x - (mouse_size * MOUSE_RATIO)

    offset_y = pos_y
    if font_size > mouse_size:
        offset_y += (font_size - mouse_size) / 2

    shape_data = get_shape_data(shape)

    bgl.glTranslatef(offset_x, offset_y, 0)

    # color
    r, g, b, a = sc.screencast_keys_text_color
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(r, g, b, alpha)

    # inner shape for filled style
    if style == "filled":
        inner_shape = []
        for i in shape_data:
            inner_shape.append(i[0])

    # outer shape
    for i in shape_data:
        shape_segment = i
        shape_segment[0] = [mouse_size * k for k in shape_segment[0]]
        shape_segment[1] = [mouse_size * k for k in shape_segment[1]]
        shape_segment[2] = [mouse_size * k for k in shape_segment[2]]
        shape_segment[3] = [mouse_size * k for k in shape_segment[3]]

        # create the buffer
        shape_buffer = bgl.Buffer(bgl.GL_FLOAT, [4, 3], shape_segment)

        # create the map and draw the triangle fan
        bgl.glMap1f(bgl.GL_MAP1_VERTEX_3, 0.0, 1.0, 3, 4, shape_buffer)
        bgl.glEnable(bgl.GL_MAP1_VERTEX_3)

        if style == "outline":
            bgl.glBegin(bgl.GL_LINE_STRIP)
        else:  # style == "filled"
            bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        for j in range(10):
            bgl.glEvalCoord1f(j / 10.0)
        x, y, z = shape_segment[3]

        # make sure the last vertex is indeed the last one, to avoid gaps
        bgl.glVertex3f(x, y, z)
        bgl.glEnd()
        bgl.glDisable(bgl.GL_MAP1_VERTEX_3)

    # draw interior
    if style == "filled":
        bgl.glBegin(bgl.GL_TRIANGLE_FAN)
        for i in inner_shape:
            j = [mouse_size * k for k in i]
            x, y, z = j
            bgl.glVertex3f(x, y, z)
        bgl.glEnd()

    bgl.glTranslatef(-offset_x, -offset_y, 0)
Exemplo n.º 36
0
def draw_callback_px_box(self, context):
    wm = context.window_manager
    sc = context.scene

    if not wm.screencast_keys_keys:
        return

    font_size = sc.screencast_keys_font_size
    mouse_size = sc.screencast_keys_mouse_size

    if sc.screencast_keys_mouse_position == 'right':
        mouse_size = 25

    box_draw = sc.screencast_keys_box_draw
    pos_x, pos_y = getDisplayLocation(context)

    # get text-width/height to resize the box
    blf.size(0, sc.screencast_keys_font_size, 72)
    box_width, box_height = sc.screencast_keys_box_width, 0
    final = 0
    row_count = 0
    box_hide = sc.screencast_keys_box_hide
    label_time_max = sc.screencast_keys_fade_time

    for i in range(len(self.key)):
        label_time = time.time() - self.time[i]

        if label_time < label_time_max:  # only display key-presses of last 4 seconds
            box_width, box_height = getBoundingBox(box_width, box_height,
                                                   self.key[i])
            row_count += 1
            final = i + 1
            box_hide = False
        else:
            break

    # Got the size right, now draw box using proper colors
    box_color_r, box_color_g, box_color_b, box_color_alpha = sc.screencast_keys_box_color

    if box_draw and not box_hide:
        padding_x = 16
        padding_y = 12
        x0 = max(0, pos_x - padding_x)
        y0 = max(0, pos_y - padding_y)
        x1 = pos_x + box_width + mouse_size * MOUSE_RATIO * 1.3 + padding_x
        y1 = pos_y + max(mouse_size, font_size * row_count) + padding_y
        positions = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]]
        settings = [[bgl.GL_QUADS, min(0.0, box_color_alpha)],
                    [bgl.GL_LINE_LOOP,
                     min(0.0, box_color_alpha)]]

        for mode, box_alpha in settings:
            bgl.glEnable(bgl.GL_BLEND)
            bgl.glBegin(mode)
            bgl.glColor4f(box_color_r, box_color_g, box_color_b,
                          box_color_alpha)
            for v1, v2 in positions:
                bgl.glVertex2f(v1, v2)
            bgl.glEnd()

    if sc.screencast_keys_show_operator:
        draw_last_operator(context, pos_x, pos_y)

    if sc.screencast_keys_timer_show:
        draw_timer(context, pos_x, pos_y)

    # get rid of status texts that aren't displayed anymore
    self.key = self.key[:final]
    self.time = self.time[:final]
Exemplo n.º 37
0
def glSetDefaultOptions():
    # bgl.glEnable(bgl.GL_MULTISAMPLE)
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_DEPTH_TEST)
Exemplo n.º 38
0
def draw_callback(self, context):
    ctx = bpy.context

    region = context.region
    rv3d = context.region_data

    viewport_center = (region.x + region.width / 2,
                       region.y + region.height / 2)
    view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d,
                                                      viewport_center)
    ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d,
                                                     viewport_center)

    shader.bind()

    bgl.glEnable(bgl.GL_DEPTH_TEST)

    #Draw cursor
    if self.show_cursor:
        brush_radius = context.scene.normal_brush_props.radius

        m = calc_vertex_transform_world(self.cursor_pos, self.cursor_normal)
        mS = mathutils.Matrix.Scale(brush_radius, 4)
        m = m @ mS

        #Tangent to mesh
        gpu.matrix.push()

        gpu.matrix.multiply_matrix(m)

        shader.uniform_float("color", (1, 0, 1, 1))
        batchCircle.draw(shader)

        gpu.matrix.pop()

        #Brush normal direction
        brush_type = context.scene.normal_brush_props.brush_type
        brush_normal = context.scene.normal_brush_props.normal

        if brush_type == "FIXED":
            gpu.matrix.push()

            m = calc_vertex_transform_world(self.cursor_pos, brush_normal)
            gpu.matrix.multiply_matrix(m)

            shader.uniform_float("color", (0, 1, 1, 1))
            batchLine.draw(shader)

            gpu.matrix.pop()

    #Draw editable normals
    shader.uniform_float("color", (1, 1, 0, 1))

    normLength = context.scene.normal_brush_props.normal_length
    mS = mathutils.Matrix.Scale(normLength, 4)

    shader.uniform_float("color", (1, 1, 0, 1))

    for obj in ctx.selected_objects:
        if obj.type == 'MESH':
            success = obj.update_from_editmode()
            mesh = obj.data

            mesh.calc_normals_split()
            coordsNormals = []

            for l in mesh.loops:

                v = mesh.vertices[l.vertex_index]
                coordsNormals.append(v.co)
                coordsNormals.append(v.co + l.normal * normLength)

            batchNormals = batch_for_shader(shader, 'LINES',
                                            {"pos": coordsNormals})

            gpu.matrix.push()

            gpu.matrix.multiply_matrix(obj.matrix_world)
            batchNormals.draw(shader)

            gpu.matrix.pop()

    bgl.glDisable(bgl.GL_DEPTH_TEST)
Exemplo n.º 39
0
    def draw_to_viewport(view_min, view_max, show_extra, label_counter,
                         tilegrid, sprytile_data, cursor_loc, region, rv3d,
                         middle_btn, context):
        """Draw the offscreen texture into the viewport"""

        # Prepare some data that will be used for drawing
        grid_size = SprytileGui.loaded_grid.grid
        padding = SprytileGui.loaded_grid.padding

        # Draw work plane
        SprytileGui.draw_work_plane(grid_size, sprytile_data, cursor_loc,
                                    region, rv3d, middle_btn)

        # Setup GL for drawing the offscreen texture
        bgl.glColor4f(1.0, 1.0, 1.0, 1.0)
        bgl.glBindTexture(bgl.GL_TEXTURE_2D, SprytileGui.texture)
        # Backup texture filter
        old_mag_filter = Buffer(bgl.GL_INT, [1])
        bgl.glGetTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
                                old_mag_filter)
        # Set texture filter
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER,
                            bgl.GL_NEAREST)
        bgl.glEnable(bgl.GL_TEXTURE_2D)
        bgl.glEnable(bgl.GL_BLEND)

        # Draw the preview tile
        if middle_btn is False:
            SprytileGui.draw_preview_tile(context, region, rv3d)

        # Calculate actual view size
        view_size = int(view_max.x - view_min.x), int(view_max.y - view_min.y)

        # Save the original scissor box, and then set new scissor setting
        scissor_box = bgl.Buffer(bgl.GL_INT, [4])
        bgl.glGetIntegerv(bgl.GL_SCISSOR_BOX, scissor_box)
        bgl.glScissor(
            int(view_min.x) + scissor_box[0],
            int(view_min.y) + scissor_box[1], view_size[0], view_size[1])

        # Draw the tile select UI
        SprytileGui.draw_tile_select_ui(view_min, view_max, view_size,
                                        SprytileGui.tex_size, grid_size,
                                        padding, show_extra)

        # restore opengl defaults
        bgl.glScissor(scissor_box[0], scissor_box[1], scissor_box[2],
                      scissor_box[3])
        bgl.glLineWidth(1)
        bgl.glTexParameteri(bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_MAG_FILTER,
                            old_mag_filter[0])

        # Draw label
        if label_counter > 0:
            import math

            def ease_out_circ(t, b, c, d):
                t /= d
                t -= 1
                return c * math.sqrt(1 - t * t) + b

            font_id = 0
            font_size = 16
            pad = 5
            box_pad = font_size + (pad * 2)
            fade = label_counter
            fade = ease_out_circ(fade, 0, SprytileGui.label_frames,
                                 SprytileGui.label_frames)
            fade /= SprytileGui.label_frames

            bgl.glColor4f(0.0, 0.0, 0.0, 0.75 * fade)
            bgl.glBegin(bgl.GL_QUADS)
            uv = [(0, 0), (0, 1), (1, 1), (1, 0)]
            vtx = [(view_min.x, view_max.y),
                   (view_min.x, view_max.y + box_pad),
                   (view_max.x, view_max.y + +box_pad),
                   (view_max.x, view_max.y)]
            for i in range(4):
                glTexCoord2f(uv[i][0], uv[i][1])
                glVertex2f(vtx[i][0], vtx[i][1])
            bgl.glEnd()

            bgl.glColor4f(1.0, 1.0, 1.0, 1.0 * fade)
            blf.size(font_id, font_size, 72)

            x_pos = view_min.x + pad
            y_pos = view_max.y + pad

            label_string = "%dx%d" % (tilegrid.grid[0], tilegrid.grid[1])
            if tilegrid.name != "":
                label_string = "%s - %s" % (label_string, tilegrid.name)
            blf.position(font_id, x_pos, y_pos, 0)
            blf.draw(font_id, label_string)

        bgl.glDisable(bgl.GL_BLEND)
        bgl.glDisable(bgl.GL_TEXTURE_2D)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Exemplo n.º 40
0
    def draw_midi_keyboard(self, mx, my, w, h, action=None, frame=0):
        '''
        Intented to create a keyboard where key widths are
        accurately in position.

        See http://www.mathpages.com/home/kmath043.htm
        for the math.

        This keyboard has following properties (x=octave width).
        1. All white keys have equal width in front (W=x/7).
        2. All black keys have equal width (B=x/12).
        3. The narrow part of white keys C, D and E is W - B*2/3
        4. The narrow part of white keys F, G, A, and B is W - B*3/4
        '''
        bgl.glEnable(bgl.GL_BLEND)
        octaves = 7
        octave_width = (w - 20) / octaves
        wkw = octave_width / 7
        bkw = octave_width / 12
        cde = wkw - 2 * bkw / 3
        fgab = wkw - 3 * bkw / 4
        wkh = h
        bkh = 0.60 * h

        by = my + wkh - bkh
        x = mx
        y = my
        white = (1.0, 1.0, 1.0, 1.0)
        black = (0.0, 0.0, 0.0, 1.0)
        # draw the white keys
        fc_color = True
        whitenotes = [0, 2, 4, 5, 7, 9, 11]
        blacknotes_1 = [1, 3]
        blacknotes_2 = [6, 8, 10]
        for octave in range(octaves):

            for i in range(7):
                col = white
                if action:
                    #print("XXXXXXXX", '%d"]' % (octave * 12 + whitenotes[i]))
                    fcurves = [fc for fc in action.fcurves if (fc.group.select or fc.select) and fc.data_path.endswith('%d"]' % (octave * 12 + whitenotes[i]))]
                    #fc = action.fcurves.find('["%s%d"]' % (action["channel_name"], octave * 12 + whitenotes[i]))
                    for fc in fcurves:
                        if fc.evaluate(frame) > 0:
                            debug.print("BGL", fc.data_path)
                            r, g, b = fc.color if fc_color else (1, 0, 0)
                            col = (r, g, b, 1.0)
                self.draw_box(x, y, wkw, wkh, color=col)
                x += (wkw + 1)
            # draw the black keys
            x = octave * 7 * (wkw + 1) + cde + mx + 1

            for i in range(2):
                col = black
                if action:
                    fc = action.fcurves.find('["%s%d"]' % (action["channel_name"], octave * 12 + blacknotes_1[i]))
                    if fc:
                        if fc.evaluate(frame) > 0:
                            r, g, b = fc.color if fc_color else (1, 0, 0)
                            col = (r, g, b, 1.0)
                self.draw_box(x, by, bkw, bkh, color=col)
                x += cde + bkw + 1
            x += fgab
            for i in range(3):
                col = black
                if action:
                    fc = action.fcurves.find('["%s%d"]' % (action["channel_name"], octave * 12 + blacknotes_2[i]))
                    if fc:
                        if fc.evaluate(frame) > 0:
                            r, g, b = fc.color if fc_color else (1, 0, 0)
                            col = (r, g, b, 1.0)
                self.draw_box(x, by, bkw, bkh, color=col)
                x += fgab + bkw + 1
            x += 1
Exemplo n.º 41
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
    try:
        if self.window == context.window and self.area == context.area:
            bgl.glEnable(bgl.GL_BLEND)
        else:
            return
    except:
        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
    #chfx = round(dpi_r * (2 + 1.3 * (fs - 2) + ((fs % 10) == 0))) # char height fixed
    # 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)
    #bgl.glVertex2i(self.left_edge-self.tab_width, self.height)
    bgl.glVertex2i(self.left_edge, self.height)
    bgl.glVertex2i(self.right_edge, self.height)
    bgl.glVertex2i(self.right_edge, 0)
    #bgl.glVertex2i(self.left_edge-self.tab_width, 0)
    bgl.glVertex2i(self.left_edge, 0)
    bgl.glEnd()

    # space = context.space_data
    # if space.text:
    #     lines = len(space.text.lines)
    #     lines_digits = len(str(lines)) if space.show_line_numbers else 0

    #### AQUI Y AHORA
    #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(1, 0, 0, 0.3)
#        for id in range(space.top, min(space.top+space.visible_lines+1, lines+1)):
#            if id in [2, 1, 4, 8, 24, 55]:
#                bgl.glBegin(bgl.GL_QUADS)
#                bgl.glVertex2i(0, self.height-chfx*(id-space.top))
#                bgl.glVertex2i(self.line_bar_width, self.height-chfx*(id-space.top))
#                bgl.glVertex2i(self.line_bar_width, self.height-chfx*(id-1-space.top))
#                bgl.glVertex2i(0, self.height-chfx*(id-1-space.top))
#                bgl.glEnd()
#                #bgl.glColor4f(1, 0, 0, 0.5)
#blf.size(font_id, fs, int(dpi_r)*72)
#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, '*')
# 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, u'▓▓')

# 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)
        #bgl.glVertex2i(self.left_edge-id-self.tab_width, 0)
        #bgl.glVertex2i(self.left_edge-id-self.tab_width, self.height)
        bgl.glVertex2i(self.left_edge - id, 0)
        bgl.glVertex2i(self.left_edge - id, self.height)
        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)
    #     bgl.glVertex2i(self.left_edge, 0)
    #     bgl.glVertex2i(self.left_edge, self.height)
    #     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)
        bgl.glVertex2i(self.left_edge,
                       self.height - mlh * space.top + self.slide)
        bgl.glVertex2i(self.right_edge,
                       self.height - mlh * space.top + self.slide)
        bgl.glVertex2i(
            self.right_edge,
            self.height - mlh * (space.top + space.visible_lines) + self.slide)
        bgl.glVertex2i(
            self.left_edge,
            self.height - mlh * (space.top + space.visible_lines) + self.slide)
        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)
    #             bgl.glVertex2i(self.left_edge-self.tab_width, y_loc)
    #             bgl.glVertex2i(self.left_edge, y_loc)
    #             bgl.glVertex2i(self.left_edge, y_loc-self.tab_height)
    #             bgl.glVertex2i(self.left_edge-self.tab_width, y_loc-self.tab_height)
    #             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)
    #             bgl.glVertex2i(self.left_edge-self.tab_width, y_loc)
    #             bgl.glVertex2i(self.left_edge, y_loc)
    #             bgl.glVertex2i(self.left_edge, y_loc-self.tab_height)
    #             bgl.glVertex2i(self.left_edge-self.tab_width, y_loc-self.tab_height)
    #             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)
    #         bgl.glVertex2i(self.left_edge-self.tab_width, y_loc)
    #         bgl.glVertex2i(self.left_edge, y_loc)
    #         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(1, 0, 0, 0.5)
#        for id in range(space.top, min(space.top+space.visible_lines+1, lines+1)):
#            blf.size(font_id, fs, int(dpi_r*72))
#            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, '*')
#    #     # 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)):
#         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, u'▓▓')

# 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
Exemplo n.º 42
0
    def glsl_draw(self):
        if GlslDrawObj.myinstance is None and GlslDrawObj.draw_func is None:
            glsl_draw_obj = GlslDrawObj()
            glsl_draw_obj.build_scene()
        else:
            glsl_draw_obj = GlslDrawObj.myinstance
        model_offset = Matrix.Translation((glsl_draw_obj.draw_x_offset, 0, 0))
        light_pos = [
            i + n
            for i, n in zip(
                glsl_draw_obj.light.location, [-glsl_draw_obj.draw_x_offset, 0, 0]
            )
        ]
        batches = glsl_draw_obj.batches
        depth_shader = glsl_draw_obj.depth_shader
        toon_shader = glsl_draw_obj.toon_shader
        offscreen = glsl_draw_obj.offscreen
        # need bone etc changed only update
        depth_matrix = None

        light = glsl_draw_obj.light
        light_lookat = light.rotation_euler.to_quaternion() @ Vector((0, 0, -1))
        # TODO このへん
        tar = light_lookat.normalized()
        up = light.rotation_euler.to_quaternion() @ Vector((0, 1, 0))
        tmp_bound_len = Vector(glsl_draw_obj.bounding_center).length
        camera_bias = 0.2
        loc = Vector(
            [
                glsl_draw_obj.bounding_center[i]
                + tar[i] * (tmp_bound_len + camera_bias)
                for i in range(3)
            ]
        )

        loc = model_offset @ loc
        v_matrix = lookat_cross(loc, tar, up)
        const_proj = 2 * max(glsl_draw_obj.bounding_size) / 2
        p_matrix = ortho_proj_mat(
            -const_proj, const_proj, -const_proj, const_proj, -const_proj, const_proj
        )
        depth_matrix = v_matrix @ p_matrix  # reuse in main shader
        depth_matrix.transpose()

        # region shader depth path
        with offscreen.bind():
            bgl.glClearColor(10, 10, 10, 1)
            bgl.glClear(bgl.GL_COLOR_BUFFER_BIT | bgl.GL_DEPTH_BUFFER_BIT)
            for bat in batches:
                mat = bat[0]
                mat.update()
                depth_bat = bat[2]
                depth_shader.bind()

                bgl.glEnable(bgl.GL_BLEND)
                if mat.alpha_method == "TRANSPARENT":
                    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
                    bgl.glDepthMask(bgl.GL_TRUE)
                    bgl.glEnable(bgl.GL_DEPTH_TEST)
                elif mat.alpha_method == "OPAQUE":
                    bgl.glBlendFunc(bgl.GL_ONE, bgl.GL_ZERO)
                    bgl.glDepthMask(bgl.GL_TRUE)
                    bgl.glEnable(bgl.GL_DEPTH_TEST)
                elif mat.alpha_method == "CLIP":
                    bgl.glBlendFunc(bgl.GL_ONE, bgl.GL_ZERO)
                    bgl.glDepthMask(bgl.GL_TRUE)
                    bgl.glEnable(bgl.GL_DEPTH_TEST)

                if mat.cull_mode == "BACK":
                    bgl.glEnable(bgl.GL_CULL_FACE)
                    bgl.glCullFace(bgl.GL_BACK)
                else:
                    bgl.glDisable(bgl.GL_CULL_FACE)
                bgl.glEnable(bgl.GL_CULL_FACE)  # そも輪郭線がの影は落ちる?
                bgl.glCullFace(bgl.GL_BACK)

                depth_shader.uniform_float(
                    "obj_matrix", model_offset
                )  # obj.matrix_world)
                depth_shader.uniform_float("depthMVP", depth_matrix)

                depth_bat.draw(depth_shader)
        # endregion shader depth path

        # region shader main
        vp_mat = bpy.context.region_data.perspective_matrix
        projection_mat = bpy.context.region_data.window_matrix
        view_dir = bpy.context.region_data.view_matrix[2][:3]
        view_up = bpy.context.region_data.view_matrix[1][:3]
        normal_world_to_view_matrix = (
            bpy.context.region_data.view_matrix.inverted_safe().transposed()
        )
        aspect = bpy.context.area.width / bpy.context.area.height

        for is_outline in [0, 1]:
            for bat in batches:

                toon_bat = bat[1]
                toon_shader.bind()
                mat = bat[0]

                if is_outline == 1 and mat.float_dic["OutlineWidthMode"] == 0:
                    continue
                # mat.update() #already in depth path
                bgl.glEnable(bgl.GL_BLEND)
                bgl.glDepthMask(bgl.GL_TRUE)
                bgl.glEnable(bgl.GL_DEPTH_TEST)
                if mat.alpha_method == "TRANSPARENT":
                    bgl.glBlendFunc(bgl.GL_SRC_ALPHA, bgl.GL_ONE_MINUS_SRC_ALPHA)
                elif mat.alpha_method == "OPAQUE":
                    bgl.glBlendFunc(bgl.GL_ONE, bgl.GL_ZERO)
                elif mat.alpha_method == "CLIP":
                    bgl.glBlendFunc(bgl.GL_ONE, bgl.GL_ZERO)

                if is_outline == 0:
                    if mat.cull_mode == "BACK":
                        bgl.glEnable(bgl.GL_CULL_FACE)
                        bgl.glCullFace(bgl.GL_BACK)
                    else:
                        bgl.glDisable(bgl.GL_CULL_FACE)
                else:
                    bgl.glEnable(bgl.GL_CULL_FACE)
                    bgl.glCullFace(bgl.GL_BACK)

                toon_shader.uniform_float(
                    "obj_matrix", model_offset
                )  # obj.matrix_world)
                toon_shader.uniform_float("projectionMatrix", projection_mat)
                toon_shader.uniform_float("viewProjectionMatrix", vp_mat)
                toon_shader.uniform_float("viewDirection", view_dir)
                toon_shader.uniform_float("viewUpDirection", view_up)
                toon_shader.uniform_float(
                    "normalWorldToViewMatrix", normal_world_to_view_matrix
                )
                toon_shader.uniform_float("depthMVP", depth_matrix)
                toon_shader.uniform_float("lightpos", light_pos)
                toon_shader.uniform_float("aspect", aspect)
                toon_shader.uniform_float("is_outline", is_outline)
                toon_shader.uniform_float("isDebug", 0.0)

                toon_shader.uniform_float(
                    "is_cutout", 1.0 if mat.alpha_method == "CLIP" else 0.0
                )

                float_keys = [
                    "CutoffRate",
                    "BumpScale",
                    "ReceiveShadowRate",
                    "ShadeShift",
                    "ShadeToony",
                    "RimLightingMix",
                    "RimFresnelPower",
                    "RimLift",
                    "ShadingGradeRate",
                    "LightColorAttenuation",
                    "IndirectLightIntensity",
                    "OutlineWidth",
                    "OutlineScaleMaxDistance",
                    "OutlineLightingMix",
                    "UV_Scroll_X",
                    "UV_Scroll_Y",
                    "UV_Scroll_Rotation",
                    "OutlineWidthMode",
                    "OutlineColorMode",
                ]

                for k in float_keys:
                    toon_shader.uniform_float(k, mat.float_dic[k])

                for k, v in mat.vector_dic.items():
                    toon_shader.uniform_float(k, v)

                bgl.glActiveTexture(bgl.GL_TEXTURE0)
                bgl.glBindTexture(bgl.GL_TEXTURE_2D, offscreen.color_texture)
                bgl.glTexParameteri(
                    bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_WRAP_S, bgl.GL_CLAMP_TO_EDGE
                )  # TODO
                bgl.glTexParameteri(
                    bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_WRAP_T, bgl.GL_CLAMP_TO_EDGE
                )
                toon_shader.uniform_int("depth_image", 0)

                for i, k in enumerate(mat.texture_dic.keys()):
                    bgl.glActiveTexture(bgl.GL_TEXTURE1 + i)
                    texture = mat.texture_dic[k]
                    bgl.glBindTexture(bgl.GL_TEXTURE_2D, texture.bindcode)
                    bgl.glTexParameteri(
                        bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_WRAP_S, bgl.GL_CLAMP_TO_EDGE
                    )  # TODO
                    bgl.glTexParameteri(
                        bgl.GL_TEXTURE_2D, bgl.GL_TEXTURE_WRAP_T, bgl.GL_CLAMP_TO_EDGE
                    )
                    toon_shader.uniform_int(k, 1 + i)

                toon_bat.draw(toon_shader)
Exemplo n.º 43
0
def draw_callback_px(self, context):
    # circle graphic, text, and slider
    unify_settings = bpy.context.tool_settings.unified_paint_settings
    strength = unify_settings.strength if self.uni_str else self.brush.strength
    size = unify_settings.size if self.uni_size else self.brush.size

    if self.graphic:
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(self.brushcolor.r, self.brushcolor.g, self.brushcolor.b,
                      strength * 0.25)
        bgl.glBegin(bgl.GL_POLYGON)
        for x, y in self.circlepoints:
            bgl.glVertex2i(
                int(size * x) + self.cur[0],
                int(size * y) + self.cur[1])
        bgl.glEnd()
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

    if self.text != 'NONE' and self.doingstr:
        if self.text == 'MEDIUM':
            fontsize = 11
        elif self.text == 'LARGE':
            fontsize = 22
        else:
            fontsize = 8

        font_id = 0
        blf.size(font_id, fontsize, 72)
        blf.shadow(font_id, 0, 0.0, 0.0, 0.0, 1.0)
        blf.enable(font_id, blf.SHADOW)

        if strength < 0.001:
            text = "0.001"
        else:
            text = str(strength)[0:5]
        textsize = blf.dimensions(font_id, text)

        xpos = self.start[0] + self.offset[0]
        ypos = self.start[1] + self.offset[1]

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(self.backcolor.r, self.backcolor.g, self.backcolor.b,
                      0.5)

        bgl.glBegin(bgl.GL_POLYGON)
        for x, y in self.rectpoints:
            bgl.glVertex2i(
                int(textsize[0] * x) + xpos,
                int(textsize[1] * y) + ypos)
        bgl.glEnd()

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

        blf.position(font_id, xpos, ypos, 0)
        blf.draw(font_id, text)

        blf.disable(font_id, blf.SHADOW)

    if self.slider != 'NONE' and self.doingstr:
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glColor4f(self.backcolor.r, self.backcolor.g, self.backcolor.b,
                      0.5)

        xpos = self.start[0] + self.offset[0] - self.sliderwidth + (
            32
            if self.text == 'MEDIUM' else 64 if self.text == 'LARGE' else 23)
        ypos = self.start[1] + self.offset[
            1] - self.sliderheight  # + (1 if self.slider != 'SMALL' else 0)

        if strength <= 1.0:
            sliderscale = strength
        elif strength > 5.0:
            sliderscale = strength / 10
        elif strength > 2.0:
            sliderscale = strength / 5
        else:
            sliderscale = strength / 2

        bgl.glBegin(bgl.GL_POLYGON)
        for x, y in self.rectpoints:
            bgl.glVertex2i(
                int(self.sliderwidth * x) + xpos,
                int(self.sliderheight * y) + ypos - 1)
        bgl.glEnd()

        bgl.glColor4f(self.frontcolor.r, self.frontcolor.g, self.frontcolor.b,
                      0.8)

        bgl.glBegin(bgl.GL_POLYGON)
        for x, y in self.rectpoints:
            bgl.glVertex2i(
                int(self.sliderwidth * x * sliderscale) + xpos,
                int(self.sliderheight * y * 0.75) + ypos)
        bgl.glEnd()

        bgl.glDisable(bgl.GL_BLEND)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Exemplo n.º 44
0
def glEnableStipple(enable=True):
    if enable:
        bgl.glLineStipple(4, 0x5555)
        bgl.glEnable(bgl.GL_LINE_STIPPLE)
    else:
        bgl.glDisable(bgl.GL_LINE_STIPPLE)
Exemplo n.º 45
0
def gui_update(self, context):

    xvalue = round(
        bpy.context.object.modifiers["Array"].constant_offset_displace[0] *
        10000) / 10000
    yvalue = round(
        bpy.context.object.modifiers["Array"].constant_offset_displace[1] *
        10000) / 10000
    zvalue = round(
        bpy.context.object.modifiers["Array"].constant_offset_displace[2] *
        10000) / 10000

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

    is_bool = False
    is_bevel = False
    is_bevel_3 = False
    is_bevel_2 = False
    is_solidify = False
    is_multiselected = False
    is_notselected = False
    is_noactiveobject = False
    multislist = bpy.context.selected_objects
    activeobject = bpy.context.scene.objects.active
    is_formerge = False
    current_dir = os.path.basename(os.path.dirname(os.path.abspath(__file__)))
    user_preferences = bpy.context.user_preferences
    #addon_pref = user_preferences.addons[current_dir].preferences

    if len(multislist) > 1:
        is_multiselected = True
    if len(multislist) < 1:
        is_notselected = True
    if activeobject == None:
        is_noactiveobject = True

    for obj in bpy.context.selected_objects:
        if obj.name.startswith("AP"):
            is_formerge = True
            pass

    for mode in bpy.context.object.modifiers:
        if mode.type == 'BEVEL':
            if mode.limit_method == 'WEIGHT':
                is_bevel = True
        if mode.type == "BEVEL":
            if mode.profile > 0.70 and mode.profile < 0.72:
                is_bevel_3 = True
                #print("Bevel 3 is true")
        if mode.type == "BEVEL":
            if mode.limit_method == 'ANGLE' or mode.limit_method == 'NONE':
                is_bevel_2 = True
                #print("Bevel 2 is true")
        if mode.type == 'BOOLEAN':
            is_bool = True
        if mode.type == 'SOLIDIFY':
            is_solidify = True

    arraycount = 0,
    try:
        arraycount = bpy.context.object.modifiers[self.id].count
    except:
        arraycount = 0

    #Show Count
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0],
                 self.click_pos[1] + 0.55 * get_dpi(), 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 36, get_dpi())
    #blf.draw(font_id, str(bpy.context.object.modifiers[self.id].count))

    # Underline Up Top
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    bgl.glLineWidth(int(0.032 * get_dpi()))
    bgl.glBegin(bgl.GL_LINE_STRIP)
    #bgl.glVertex2d(20, 40)
    for n in range(-1, int(2.9 * get_dpi())):
        bgl.glVertex2i(self.click_pos[0] + n + 2,
                       self.click_pos[1] + int(get_dpi() / 3.2))
    bgl.glEnd()

    # draw some text / Needs To Show Axis
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0],
                 self.click_pos[1] + 0.1 * get_dpi(), 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 12, get_dpi())
    blf.draw(font_id, "Array | Axis(X/Y/Z)")

    # draw some text / Needs To Show Axis
    '''
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0], self.click_pos[1]+0.083 * get_dpi(), 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 12, get_dpi())
    blf.draw(font_id, "Q >> X/Y/Z - Additional Array Axis" )
    '''

    # draw some text / Needs To Show Axis
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0],
                 self.click_pos[1] - 0.1 * get_dpi(), 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 12, get_dpi())
    blf.draw(font_id, "R >> Radial Array Toggle")

    # And Underline Up Top
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    bgl.glLineWidth(int(0.032 * get_dpi()))
    bgl.glBegin(bgl.GL_LINE_STRIP)

    for n in range(-1, int(2.9 * get_dpi())):
        bgl.glVertex2i(self.click_pos[0] + n + 2,
                       self.click_pos[1] + int(get_dpi() / 26) - 30)
    bgl.glEnd()

    #Show X
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0],
                 self.click_pos[1] - 0.400 * get_dpi(), 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 12, get_dpi())
    blf.draw(font_id, "x:  " + str(xvalue))

    #Show y
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0],
                 self.click_pos[1] - 0.600 * get_dpi(), 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 12, get_dpi())
    blf.draw(font_id, "y:  " + str(yvalue))

    #Show z
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0],
                 self.click_pos[1] - 0.800 * get_dpi(), 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 12, get_dpi())
    blf.draw(font_id, "z:  " + str(zvalue))

    #Show Additional Mesh Information
    bgl.glEnable(bgl.GL_BLEND)
    blf.position(font_id, self.click_pos[0], self.click_pos[1] - 1 * get_dpi(),
                 0)
    bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
    blf.size(font_id, 12, get_dpi())
    if is_bevel_2 == True:
        #blf.draw(font_id, "Standard Mesh")
        blf.draw(font_id, "Adding Array On A Bevelled Mesh")
    elif is_bevel_3 == True:
        #blf.draw(font_id, "CStep / Sstep")
        blf.draw(font_id, "Adding Array On A (C/S)Stepped Mesh")
    elif is_bevel == True:
        #blf.draw(font_id, "CSsharp / Ssharp")
        blf.draw(font_id, "Adding Array On A CSharpened Mesh")
    elif is_bool == True:
        #blf.draw(font_id, "Pending Boolean")
        blf.draw(font_id, "There Is A Pending Boolean On This Mesh")
    else:
        blf.draw(font_id, "Normal Mesh ")
    ''' 
    if addon_pref.Diagnostics_Mode :
        #Diagnostic
        bgl.glEnable(bgl.GL_BLEND)
        blf.position(font_id, self.click_pos[0], self.click_pos[1]-27, 0)
        bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
        blf.size(font_id, 12, get_dpi())
        blf.draw(font_id, "Standard is - " + str(is_bevel_2) + "      " + "Sstep is - " + str(is_bevel_3)+ "      "  + "CSharp is - " + str(is_bevel))      
    '''
    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
Exemplo n.º 46
0
def draw_view():

    ######################
    ######## BIND ########
    ######################

    first_time = not bgl.glIsVertexArray(namespace['vao'][0])

    if first_time:
        namespace['uniform_set'] = False

        # Unlike VBOs, a VAO has to be generated and deleted from within the draw callback in which it will be bound.
        bgl.glGenVertexArrays(1, namespace['vao'])
        bgl.glBindVertexArray(namespace['vao'][0])

        float_byte_count = 4

        # Attribute: "point", 3D float vector
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, namespace['vbo_point'][0])
        bgl.glBufferData(bgl.GL_ARRAY_BUFFER,
                         len(namespace['data_point']) * float_byte_count,
                         namespace['data_point'], bgl.GL_DYNAMIC_DRAW)

        bgl.glVertexAttribPointer(0, 3, bgl.GL_FLOAT, bgl.GL_FALSE, 0, None)
        bgl.glEnableVertexAttribArray(0)

        # Attribute: "color", 4D float vector
        bgl.glBindBuffer(bgl.GL_ARRAY_BUFFER, namespace['vbo_color'][0])
        bgl.glBufferData(bgl.GL_ARRAY_BUFFER,
                         len(namespace['data_color']) * float_byte_count,
                         namespace['data_color'], bgl.GL_DYNAMIC_DRAW)

        bgl.glVertexAttribPointer(1, 4, bgl.GL_FLOAT, bgl.GL_FALSE, 0, None)
        bgl.glEnableVertexAttribArray(1)

        bgl.glBindVertexArray(0)

    ######################
    ######## DRAW ########
    ######################

    bgl.glEnable(bgl.GL_BLEND)

    bgl.glUseProgram(namespace['shader_program'])

    if not namespace['uniform_set']:
        bgl.glUniformMatrix4fv(
            namespace['perspective_uniform_location'],
            1,
            bgl.
            GL_TRUE,  # Matrices in Blender are row-major while matrices in OpenGL are column-major, so Blender's perspective matrix has to be transposed for OpenGL.
            namespace['projection_matrix'])

        # In this case I only want to update the uniform once, even though namespace['projection_matrix'] is being updated constantly.
        namespace['uniform_set'] = True

    bgl.glBindVertexArray(namespace['vao'][0])
    bgl.glDrawArrays(bgl.GL_TRIANGLES, 0, 3)

    bgl.glUseProgram(0)
    bgl.glBindVertexArray(0)

    bgl.glDisable(bgl.GL_BLEND)
Exemplo n.º 47
0
    def draw_3D_stuff(self):
        context = self.context
        region,r3d = context.region,context.space_data.region_3d
        view_dir = r3d.view_rotation * Vector((0,0,-1))
        view_loc = r3d.view_location - view_dir * r3d.view_distance
        view_ortho = (r3d.view_perspective == "ORTHO")
        if view_ortho: view_loc -= view_dir * 1000.0

        bgl.glEnable(bgl.GL_POINT_SMOOTH)
        bgl.glDepthRange(0.0, 1.0)
        bgl.glEnable(bgl.GL_DEPTH_TEST)
        bgl.glLineWidth(1)
        bgl.glDepthRange(0.0, 1.0)

        if self._state != "segmentation":
            #CurveNetwork, BezierSegments
            for seg in self.spline_net.segments:
                if len(seg.draw_tessellation) == 0: continue

                #has not been successfully converted to InputPoints and InputSegments
                if seg.is_inet_dirty:
                    draw3d_polyline(seg.draw_tessellation, orange2, 4, view_loc, view_ortho)

                #if len(seg.ip_tesselation):
                #    draw3d_polyline(seg.ip_tesselation,  blue, 2, view_loc, view_ortho)
                #    draw3d_points(seg.ip_tesselation, green2, 4, view_loc, view_ortho)

            draw3d_points(self.spline_net.point_world_locs, green2, 6, view_loc, view_ortho)

            # Polylines...InputSegments
            for seg in self.input_net.segments:
                #bad segment with a preview path provided by geodesic
                if seg.bad_segment and not len(seg.path) > 2:
                    draw3d_polyline([seg.ip0.world_loc, seg.ip1.world_loc], pink, 2, view_loc, view_ortho)

                #s
                elif len(seg.path) >= 2 and not seg.bad_segment and seg not in self.network_cutter.completed_segments:
                    draw3d_polyline(seg.path,  blue, 2, view_loc, view_ortho)

                elif len(seg.path) >= 2 and not seg.bad_segment and seg in self.network_cutter.completed_segments:
                    draw3d_polyline(seg.path,  green2, 2, view_loc, view_ortho)

                elif len(seg.path) >= 2 and seg.bad_segment:
                    draw3d_polyline(seg.path,  orange2, 2, view_loc, view_ortho)
                    draw3d_polyline([seg.ip0.world_loc, seg.ip1.world_loc], orange2, 2, view_loc, view_ortho)

                elif seg.calculation_complete == False:
                    draw3d_polyline([seg.ip0.world_loc, seg.ip1.world_loc], orange2, 2, view_loc, view_ortho)
                else:
                    draw3d_polyline([seg.ip0.world_loc, seg.ip1.world_loc], blue2, 2, view_loc, view_ortho)


            if self.network_cutter.the_bad_segment:
                seg = self.network_cutter.the_bad_segment
                draw3d_polyline([seg.ip0.world_loc, seg.ip1.world_loc],  red, 4, view_loc, view_ortho)


        if self._state == "segmentation":
            #draw the hovered patch
            #TODO, segmentation only happens AFTER CUtting
            #So it would be MUCH easier to just draw the damn edges of the patch
            if self.net_ui_context.hovered_near[0] == "PATCH":
                p = self.net_ui_context.hovered_near[1]
                if p != self.network_cutter.active_patch:
                    for spline_seg in p.spline_net_segments:
                        for iseg in spline_seg.input_segments:
                            draw3d_polyline([iseg.ip0.world_loc] + iseg.path + [iseg.ip1.world_loc],  orange2, 4, view_loc, view_ortho)

            if self.network_cutter.active_patch:
                for spline_seg in self.network_cutter.active_patch.spline_net_segments:
                    for iseg in spline_seg.input_segments:
                            draw3d_polyline([iseg.ip0.world_loc] + iseg.path + [iseg.ip1.world_loc],  orange2, 4, view_loc, view_ortho)

        if self._state == "spline":
            draw3d_points(self.input_net.point_world_locs, blue, 2, view_loc, view_ortho)
        elif self._state != "segmentation":
            draw3d_points(self.input_net.point_world_locs, blue, 6, view_loc, view_ortho)

        #draw the seed/face patch points
        draw3d_points([p.world_loc for p in self.network_cutter.face_patches], orange2, 6, view_loc, view_ortho)


        #draw the actively processing Input Point (IP Steper Debug) for debug stepper cutting
        if self.network_cutter.active_ip:
            draw3d_points([self.network_cutter.active_ip.world_loc], purple, 20, view_loc, view_ortho)
            draw3d_points([ip.world_loc for ip in self.network_cutter.ip_chain], purple, 12, view_loc, view_ortho)

        if self.network_cutter.seg_enter:
            draw3d_polyline(self.network_cutter.seg_enter.path, green2, 4, view_loc, view_ortho)

        if self.network_cutter.seg_exit:
            draw3d_polyline(self.network_cutter.seg_exit.path, red, 4, view_loc, view_ortho)

        bgl.glLineWidth(1)
        bgl.glDepthFunc(bgl.GL_LEQUAL)
        bgl.glDepthRange(0.0, 1.0)
        bgl.glDepthMask(bgl.GL_TRUE)
Exemplo n.º 48
0
def draw_boundings(self, context):
    for obj in bpy.data.objects:
        if obj.type == 'MESH' and obj.data.b4w_override_boundings:

            bounding_box = obj.data.b4w_boundings

            min_x = bounding_box.min_x
            max_x = bounding_box.max_x
            min_y = bounding_box.min_y
            max_y = bounding_box.max_y
            min_z = bounding_box.min_z
            max_z = bounding_box.max_z

            x_width = max_x - min_x
            y_width = max_y - min_y
            z_width = max_z - min_z

            cen = [0] * 3
            cen[0] = (max_x + min_x) / 2
            cen[1] = (max_y + min_y) / 2
            cen[2] = (max_z + min_z) / 2

            wm = obj.matrix_world

            if context.window_manager.b4w_draw_bound_box:
                bgl.glEnable(bgl.GL_BLEND)
                bgl.glLineWidth(2)
                # set colour
                bgl.glColor4f(0.5, 1.0, 1.0, 1.0)

                # draw boundings
                bgl.glBegin(bgl.GL_LINE_STRIP)
                co = mathutils.Vector((min_x, min_y, min_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((max_x, min_y, min_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((max_x, max_y, min_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((min_x, max_y, min_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                bgl.glEnd()

                bgl.glBegin(bgl.GL_LINE_STRIP)
                co = mathutils.Vector((min_x, min_y, max_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((min_x, min_y, min_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((min_x, max_y, min_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((min_x, max_y, max_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                bgl.glEnd()

                bgl.glBegin(bgl.GL_LINE_STRIP)
                co = mathutils.Vector((max_x, min_y, max_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((min_x, min_y, max_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((min_x, max_y, max_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((max_x, max_y, max_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                bgl.glEnd()

                bgl.glBegin(bgl.GL_LINE_STRIP)
                co = mathutils.Vector((max_x, max_y, min_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((max_x, max_y, max_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((max_x, min_y, max_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                co = mathutils.Vector((max_x, min_y, min_z))
                co = wm * co
                bgl.glVertex3f(co[0], co[1], co[2])
                bgl.glEnd()
                bgl.glLineWidth(1)

            if context.window_manager.b4w_draw_bound_sphere:
                #draw spehere
                bgl.glColor4f(1.0, 0.5, 1.0, 1.0)

                r = math.sqrt(x_width * x_width + y_width * y_width +
                              z_width * z_width) / 2
                draw_elipse(cen, r, (1, 0, 0), 1, wm)
                draw_elipse(cen, r, (0, 1, 0), 1, wm)
                draw_elipse(cen, r, (0, 0, 1), 1, wm)

                bgl.glDisable(bgl.GL_BLEND)

            if context.window_manager.b4w_draw_bound_ellipsoid:

                #draw ellipsoid
                bgl.glColor4f(1.0, 1.0, 0.5, 1.0)

                sq3 = math.sqrt(3) / 2

                draw_elipse(cen, sq3 * z_width, (1, 0, 0), y_width / z_width,
                            wm)
                draw_elipse(cen, sq3 * x_width, (0, 1, 0), z_width / x_width,
                            wm)
                draw_elipse(cen, sq3 * x_width, (0, 0, 1), y_width / x_width,
                            wm)

                bgl.glDisable(bgl.GL_BLEND)
Exemplo n.º 49
0
def draw_callback_px(self, context):
    bgl.glColor4f(0, 1, 0.0, 0.9)
    bgl.glEnable(bgl.GL_BLEND)
    font_id = 0

    so = bpy.context.selected_objects
    v = []
    vv = []
    caml = 0.125 * sum(
        (Vector(b) for b in bpy.context.scene.camera.bound_box), Vector())
    camw = bpy.context.scene.camera.matrix_world * caml
    objl = bpy.context.active_object
    v.append(camw)
    local_bbox_center = 0.125 * sum(
        (Vector(b) for b in objl.bound_box), Vector())
    #vv.append(local_bbox_center)
    global_bbox_center = objl.matrix_world * local_bbox_center
    #print(global_bbox_center)
    v.append(global_bbox_center)
    #for n in range(len(x)-1,-1,1):
    #    for objl in so:
    #        vx=[]
    #        vy=[]
    #        vz=[]
    #        local_bbox_center = 0.125 * sum((Vector(b) for b in objl.bound_box), Vector())
    #        #vv.append(local_bbox_center)
    #        global_bbox_center = objl.matrix_world * local_bbox_center
    #        #print(global_bbox_center)
    #        v.append(global_bbox_center)
    #    #for n in range(len(x)-1,-1,1):
    v0 = v[0]
    v1 = v[1]
    x = (v1[0] - v0[0])**2
    y = (v1[1] - v0[1])**2
    z = (v1[2] - v0[2])**2
    dist = sqrt(x + y + z)
    dir = v1 - v0
    print(dist)
    print(dir)

    verts2d = []


    new2dCo = location_3d_to_region_2d(bpy.context.region, \
                                           bpy.context.space_data.region_3d, \
                                           v[0])
    new2dCo1 = location_3d_to_region_2d(bpy.context.region, \
                                           bpy.context.space_data.region_3d, \
                                           v[1])
    verts2d.append([new2dCo.x, new2dCo.y])
    verts2d.append([new2dCo1.x, new2dCo1.y])

    #print(ve)

    bgl.glLineWidth(2)
    bgl.glBegin(bgl.GL_LINE_LOOP)

    for x, y in verts2d:
        bgl.glVertex2f(x, y)

    bgl.glEnd()
    bgl.glDisable(bgl.GL_BLEND)
    #restore defaults
    bgl.glLineWidth(1)
    bgl.glColor4f(1, 1, 1, 1.0)
    blf.position(font_id, 15, 30, 0)
    blf.size(font_id, 20, 72)

    blf.draw(font_id, "DISTANCIA:" + str(round(dist)))

    return
Exemplo n.º 50
0
def draw_callback_px(self, context):
    # draw 3d point OpenGL in the 3D View
    bgl.glEnable(bgl.GL_BLEND)
    if self.bool_constrain:
        if self.vector_constrain == Vector((1, 0, 0)):
            Color4f = (self.axis_x_color + (1.0, ))
        elif self.vector_constrain == Vector((0, 1, 0)):
            Color4f = (self.axis_y_color + (1.0, ))
        elif self.vector_constrain == Vector((0, 0, 1)):
            Color4f = (self.axis_z_color + (1.0, ))
        else:
            Color4f = self.constrain_shift_color
    else:
        if self.type == 'OUT':
            Color4f = self.out_color
        elif self.type == 'FACE':
            Color4f = self.face_color
        elif self.type == 'EDGE':
            Color4f = self.edge_color
        elif self.type == 'VERT':
            Color4f = self.vert_color
        elif self.type == 'CENTER':
            Color4f = self.center_color
        elif self.type == 'PERPENDICULAR':
            Color4f = self.perpendicular_color

    bgl.glColor4f(*Color4f)
    bgl.glDepthRange(0, 0)
    bgl.glPointSize(10)
    bgl.glBegin(bgl.GL_POINTS)
    bgl.glVertex3f(*self.location)
    bgl.glEnd()
    bgl.glDisable(bgl.GL_BLEND)

    # draw 3d line OpenGL in the 3D View
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glDepthRange(0, 0.9999)
    bgl.glColor4f(1.0, 0.8, 0.0, 1.0)
    bgl.glLineWidth(2)
    bgl.glEnable(bgl.GL_LINE_STIPPLE)
    bgl.glBegin(bgl.GL_LINE_STRIP)
    for vert_co in self.list_vertices_co:
        bgl.glVertex3f(*vert_co)
    bgl.glVertex3f(*self.location)
    bgl.glEnd()

    # restore opengl defaults
    bgl.glDepthRange(0, 1)
    bgl.glPointSize(1)
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glDisable(bgl.GL_LINE_STIPPLE)
    bgl.glColor4f(0.0, 0.0, 0.0, 1.0)

    a = ""
    if self.list_vertices_co != [] and self.length_entered == "":
        a = 'length: ' + str(
            round((self.list_vertices_co[-1] - self.location).length, 3))
    elif self.list_vertices_co != [] and self.length_entered != "":
        a = 'length: ' + self.length_entered

    context.area.header_text_set(
        "hit: %.3f %.3f %.3f %s" %
        (self.location[0], self.location[1], self.location[2], a))
def draw_callback_px(self, context):
    allocate_main_ui(self, context)

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

    addon_prefs = context.preferences.addons[__package__].preferences

    # main window background
    main_window = self.areas["Main Window"]
    outline_color = addon_prefs.qcd_ogl_widget_menu_back_outline
    background_color = addon_prefs.qcd_ogl_widget_menu_back_inner
    draw_rounded_rect(main_window,
                      shader,
                      outline_color[:] + (1, ),
                      outline=True)
    draw_rounded_rect(main_window, shader, background_color)

    # draw window title
    window_title = self.areas["Window Title"]
    x = window_title["vert"][0]
    y = window_title["vert"][1]
    h = window_title["height"]
    text = window_title["value"]
    text_color = addon_prefs.qcd_ogl_widget_menu_back_text
    font_id = 0
    blf.position(font_id, x, y, 0)
    blf.size(font_id, int(h), 72)
    blf.color(font_id, text_color[0], text_color[1], text_color[2], 1)
    blf.draw(font_id, text)

    # refresh shader - not sure why this is needed
    shader.bind()

    in_tooltip_area = False

    for num in range(20):
        slot_num = num + 1
        qcd_slot = qcd_slots.get_name(f"{slot_num}")
        if qcd_slot:
            qcd_laycol = layer_collections[qcd_slot]["ptr"]
            collection_objects = qcd_laycol.collection.objects
            selected_objects = qcd_operators.get_move_selection()
            active_object = qcd_operators.get_move_active()
            button_area = self.areas[f"Button {slot_num}"]

            # colors
            button_color = addon_prefs.qcd_ogl_widget_tool_inner
            icon_color = addon_prefs.qcd_ogl_widget_tool_text
            if not qcd_laycol.exclude:
                button_color = addon_prefs.qcd_ogl_widget_tool_inner_sel
                icon_color = addon_prefs.qcd_ogl_widget_tool_text_sel

            if mouse_in_area(self.mouse_pos, button_area):
                in_tooltip_area = True

                mod = 0.1

                if button_color[0] + mod > 1 or button_color[
                        1] + mod > 1 or button_color[2] + mod > 1:
                    mod = -mod

                button_color = (button_color[0] + mod, button_color[1] + mod,
                                button_color[2] + mod, button_color[3])

            # button roundness
            tl = tr = bl = br = 0
            rounding = 5

            if num < 10:
                if not f"{num+2}" in qcd_slots:
                    tr = rounding

                if not f"{num}" in qcd_slots:
                    tl = rounding
            else:
                if not f"{num+2}" in qcd_slots:
                    br = rounding

                if not f"{num}" in qcd_slots:
                    bl = rounding

            if num in [0, 5]:
                tl = rounding
            elif num in [4, 9]:
                tr = rounding
            elif num in [10, 15]:
                bl = rounding
            elif num in [14, 19]:
                br = rounding

            # draw button
            outline_color = addon_prefs.qcd_ogl_widget_tool_outline
            draw_rounded_rect(button_area,
                              shader,
                              outline_color[:] + (1, ),
                              tl,
                              tr,
                              bl,
                              br,
                              outline=True)
            draw_rounded_rect(button_area, shader, button_color, tl, tr, bl,
                              br)

            # ACTIVE OBJECT
            if active_object and active_object in selected_objects and active_object.name in collection_objects:
                active_object_indicator = self.areas[
                    f"Button {slot_num} Active Object Indicator"]

                vertices = get_circle_coords(active_object_indicator)
                shader.uniform_float("color", icon_color[:] + (1, ))
                batch = batch_for_shader(shader, 'TRI_FAN', {"pos": vertices})

                bgl.glEnable(bgl.GL_BLEND)

                batch.draw(shader)

                bgl.glDisable(bgl.GL_BLEND)

            # SELECTED OBJECTS
            elif not set(selected_objects).isdisjoint(collection_objects):
                selected_object_indicator = self.areas[
                    f"Button {slot_num} Selected Object Indicator"]

                alpha = addon_prefs.qcd_ogl_selected_icon_alpha
                vertices = get_circle_coords(selected_object_indicator)
                shader.uniform_float("color", icon_color[:] + (alpha, ))
                batch = batch_for_shader(shader, 'LINE_STRIP',
                                         {"pos": vertices})

                bgl.glLineWidth(2 * scale_factor())
                bgl.glEnable(bgl.GL_BLEND)
                bgl.glEnable(bgl.GL_LINE_SMOOTH)
                bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

                batch.draw(shader)

                bgl.glDisable(bgl.GL_LINE_SMOOTH)
                bgl.glDisable(bgl.GL_BLEND)

            # OBJECTS
            elif collection_objects:
                object_indicator = self.areas[
                    f"Button {slot_num} Object Indicator"]

                alpha = addon_prefs.qcd_ogl_objects_icon_alpha
                vertices, indices = get_coords(object_indicator)
                shader.uniform_float("color", icon_color[:] + (alpha, ))
                batch = batch_for_shader(shader,
                                         'TRIS', {"pos": vertices},
                                         indices=indices)

                bgl.glEnable(bgl.GL_BLEND)

                batch.draw(shader)

                bgl.glDisable(bgl.GL_BLEND)

        # X ICON
        else:
            X_icon = self.areas[f"X_icon {slot_num}"]
            X_icon_color = addon_prefs.qcd_ogl_widget_menu_back_text

            vertices, indices = get_x_coords(X_icon)
            shader.uniform_float("color", X_icon_color[:] + (1, ))
            batch = batch_for_shader(shader,
                                     'TRIS', {"pos": vertices},
                                     indices=indices)

            bgl.glEnable(bgl.GL_BLEND)
            bgl.glEnable(bgl.GL_POLYGON_SMOOTH)
            bgl.glHint(bgl.GL_POLYGON_SMOOTH_HINT, bgl.GL_NICEST)

            batch.draw(shader)

            bgl.glDisable(bgl.GL_POLYGON_SMOOTH)
            bgl.glDisable(bgl.GL_BLEND)

    if in_tooltip_area:
        if self.draw_tooltip:
            draw_tooltip(
                self, context, shader,
                "Move Object To QCD Slot\n  * Shift-Click to toggle objects\' slot"
            )
            self.hover_time = None

        else:
            if not self.hover_time:
                self.hover_time = time.time()
Exemplo n.º 52
0
def draw_callback_3d(operator, context):

    scn = context.scene
    dofu = scn.dof_utils

    if is_camera(context.object):
        cam_ob = context.object
    elif is_camera(scn.camera):
        cam_ob = scn.camera
    else:
        return

    mat = cam_ob.matrix_world
    cam = cam_ob.data
    nmat = mat.normalized()
    target_scale = (1, 1, 1)
    smat = Matrix()
    for i in range(3):
        smat[i][i] = target_scale[i]
    temp_matrix = nmat @ smat  # cam_ob.matrix_world = nmat * smat

    start = temp_matrix @ Vector((0, 0, -cam.clip_start))
    end = temp_matrix @ Vector((0, 0, -cam.clip_end))
    d = cam.dof.focus_distance

    if cam.dof.focus_object is None:
        near_limit, far_limit = dof_calculation(cam, d)
        dof_loc = temp_matrix @ Vector((0, 0, -(near_limit)))
        dof_loc_end = temp_matrix @ Vector((0, 0, -(far_limit)))

    else:
        pt = cam.dof.focus_object.matrix_world.translation
        loc = intersect_point_line(pt, temp_matrix.translation,
                                   temp_matrix @ Vector((0, 0, -1)))
        d = ((loc[0] - start).length
             ) + cam.clip_start  # respect the clipping start value

        near_limit, far_limit = dof_calculation(cam, d)
        dof_loc = temp_matrix @ Vector((0, 0, -(near_limit)))
        dof_loc_end = temp_matrix @ Vector((0, 0, -(far_limit)))

    dofu.limits = (d, near_limit, far_limit)

    # 80% alpha, 2 pixel width line
    bgl.glEnable(bgl.GL_BLEND)
    bgl.glEnable(bgl.GL_LINE_SMOOTH)
    bgl.glEnable(bgl.GL_DEPTH_TEST)

    # check overlay
    if dofu.overlay:
        bgl.glDisable(bgl.GL_DEPTH_TEST)
    else:
        bgl.glEnable(bgl.GL_DEPTH_TEST)

    # set line width
    bgl.glLineWidth(2)

    def line(color, start, end):
        vertices = [start, end]
        shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR')
        batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": vertices})
        shader.bind()
        shader.uniform_float("color", color)
        batch.draw(shader)
        #bgl.glColor4f(*color)
        #bgl.glBegin(bgl.GL_LINES)
        #bgl.glVertex3f(*start)
        #bgl.glVertex3f(*end)
        #bgl.glEnd()

    # define the lines
    line((1.0, 1.0, 1.0, 0.1), dof_loc_end, end)
    line((1.0, 1.0, 1.0, 0.1), dof_loc, start)
    line((dofu.color_limits[0], dofu.color_limits[1], dofu.color_limits[2],
          dofu.opacity_limits), dof_loc_end, dof_loc)

    if dofu.size_limits > 0.0:
        #draw_empty(matrix=temp_matrix, offset=-near_limit, size=1)
        for i in [near_limit, far_limit]:
            draw_circle(matrix=temp_matrix,
                        offset=-i,
                        color=(dofu.color_limits[0], dofu.color_limits[1],
                               dofu.color_limits[2], dofu.opacity_limits),
                        radius=dofu.size_limits,
                        fill=dofu.fill_limits,
                        num_segments=dofu.segments_limits)

    if dofu.draw_focus:
        draw_empty_2d(matrix=temp_matrix,
                      offset=-d,
                      size=dofu.size_limits * 1.7,
                      color=(dofu.color_limits[0], dofu.color_limits[1],
                             dofu.color_limits[2], dofu.opacity_limits))

    # restore opengl defaults
    bgl.glLineWidth(1)
    bgl.glDisable(bgl.GL_BLEND)
    bgl.glDisable(bgl.GL_LINE_SMOOTH)
    bgl.glEnable(bgl.GL_DEPTH_TEST)
    def draw_callback_px(self, context):
        # draw 3d point OpenGL in the 3D View
        bgl.glEnable(bgl.GL_BLEND)
        bgl.glDisable(bgl.GL_DEPTH_TEST)
        # bgl.glPushMatrix()
        # bgl.glMultMatrixf(self.obj_glmatrix)

        if self.vector_constrain:
            vc = self.vector_constrain
            if hasattr(self, 'preloc') and self.type in {'VERT', 'FACE'}:
                bgl.glColor4f(1.0, 1.0, 1.0, 0.5)
                bgl.glPointSize(5)
                bgl.glBegin(bgl.GL_POINTS)
                bgl.glVertex3f(*self.preloc)
                bgl.glEnd()
            if vc[2] == 'X':
                Color4f = (self.axis_x_color + (1.0, ))
            elif vc[2] == 'Y':
                Color4f = (self.axis_y_color + (1.0, ))
            elif vc[2] == 'Z':
                Color4f = (self.axis_z_color + (1.0, ))
            else:
                Color4f = self.constrain_shift_color
        else:
            if self.type == 'OUT':
                Color4f = self.out_color
            elif self.type == 'FACE':
                Color4f = self.face_color
            elif self.type == 'EDGE':
                Color4f = self.edge_color
            elif self.type == 'VERT':
                Color4f = self.vert_color
            elif self.type == 'CENTER':
                Color4f = self.center_color
            elif self.type == 'PERPENDICULAR':
                Color4f = self.perpendicular_color
            else:  # self.type == None
                Color4f = self.out_color

        bgl.glColor4f(*Color4f)
        bgl.glPointSize(10)
        bgl.glBegin(bgl.GL_POINTS)
        bgl.glVertex3f(*self.location)
        bgl.glEnd()

        # draw 3d line OpenGL in the 3D View
        bgl.glEnable(bgl.GL_DEPTH_TEST)
        bgl.glDepthRange(0, 0.9999)
        bgl.glColor4f(1.0, 0.8, 0.0, 1.0)
        bgl.glLineWidth(2)
        bgl.glEnable(bgl.GL_LINE_STIPPLE)
        bgl.glBegin(bgl.GL_LINE_STRIP)
        for vert_co in self.list_verts_co:
            bgl.glVertex3f(*vert_co)
        bgl.glVertex3f(*self.location)
        bgl.glEnd()

        # restore opengl defaults
        # bgl.glPopMatrix()
        bgl.glDepthRange(0, 1)
        bgl.glPointSize(1)
        bgl.glLineWidth(1)
        bgl.glDisable(bgl.GL_BLEND)
        bgl.glDisable(bgl.GL_LINE_STIPPLE)
        bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
def draw_rounded_rect(area,
                      shader,
                      color,
                      tl=5,
                      tr=5,
                      bl=5,
                      br=5,
                      outline=False):
    sides = 32

    tl = round(tl * scale_factor())
    tr = round(tr * scale_factor())
    bl = round(bl * scale_factor())
    br = round(br * scale_factor())

    bgl.glEnable(bgl.GL_BLEND)

    if outline:
        thickness = round(2 * scale_factor())
        thickness = max(thickness, 2)

        bgl.glLineWidth(thickness)
        bgl.glEnable(bgl.GL_LINE_SMOOTH)
        bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)

    draw_type = 'TRI_FAN' if not outline else 'LINE_STRIP'

    # top left corner
    vert_x = area["vert"][0] + tl
    vert_y = area["vert"][1] - tl
    tl_vert = (vert_x, vert_y)
    vertices = [(vert_x, vert_y)] if not outline else []

    for side in range(sides + 1):
        if (8 <= side <= 16):
            cosine = tl * cos(side * 2 * pi / sides) + vert_x
            sine = tl * sin(side * 2 * pi / sides) + vert_y
            vertices.append((cosine, sine))

    batch = batch_for_shader(shader, draw_type, {"pos": vertices})
    shader.bind()
    shader.uniform_float("color", color)
    batch.draw(shader)

    # top right corner
    vert_x = area["vert"][0] + area["width"] - tr
    vert_y = area["vert"][1] - tr
    tr_vert = (vert_x, vert_y)
    vertices = [(vert_x, vert_y)] if not outline else []

    for side in range(sides + 1):
        if (0 <= side <= 8):
            cosine = tr * cos(side * 2 * pi / sides) + vert_x
            sine = tr * sin(side * 2 * pi / sides) + vert_y
            vertices.append((cosine, sine))

    batch = batch_for_shader(shader, draw_type, {"pos": vertices})
    shader.bind()
    shader.uniform_float("color", color)
    batch.draw(shader)

    # bottom left corner
    vert_x = area["vert"][0] + bl
    vert_y = area["vert"][1] - area["height"] + bl
    bl_vert = (vert_x, vert_y)
    vertices = [(vert_x, vert_y)] if not outline else []

    for side in range(sides + 1):
        if (16 <= side <= 24):
            cosine = bl * cos(side * 2 * pi / sides) + vert_x
            sine = bl * sin(side * 2 * pi / sides) + vert_y
            vertices.append((cosine, sine))

    batch = batch_for_shader(shader, draw_type, {"pos": vertices})
    shader.bind()
    shader.uniform_float("color", color)
    batch.draw(shader)

    # bottom right corner
    vert_x = area["vert"][0] + area["width"] - br
    vert_y = area["vert"][1] - area["height"] + br
    br_vert = (vert_x, vert_y)
    vertices = [(vert_x, vert_y)] if not outline else []

    for side in range(sides + 1):
        if (24 <= side <= 32):
            cosine = br * cos(side * 2 * pi / sides) + vert_x
            sine = br * sin(side * 2 * pi / sides) + vert_y
            vertices.append((cosine, sine))

    batch = batch_for_shader(shader, draw_type, {"pos": vertices})
    shader.bind()
    shader.uniform_float("color", color)
    batch.draw(shader)

    if not outline:
        vertices = []
        indices = []
        base_ind = 0

        # left edge
        width = max(tl, bl)
        le_x = tl_vert[0] - tl
        vertices.extend([(le_x, tl_vert[1]), (le_x + width, tl_vert[1]),
                         (le_x, bl_vert[1]), (le_x + width, bl_vert[1])])
        indices.extend([(base_ind, base_ind + 1, base_ind + 2),
                        (base_ind + 2, base_ind + 3, base_ind + 1)])
        base_ind += 4

        # right edge
        width = max(tr, br)
        re_x = tr_vert[0] + tr
        vertices.extend([(re_x, tr_vert[1]), (re_x - width, tr_vert[1]),
                         (re_x, br_vert[1]), (re_x - width, br_vert[1])])
        indices.extend([(base_ind, base_ind + 1, base_ind + 2),
                        (base_ind + 2, base_ind + 3, base_ind + 1)])
        base_ind += 4

        # top edge
        width = max(tl, tr)
        te_y = tl_vert[1] + tl
        vertices.extend([(tl_vert[0], te_y), (tl_vert[0], te_y - width),
                         (tr_vert[0], te_y), (tr_vert[0], te_y - width)])
        indices.extend([(base_ind, base_ind + 1, base_ind + 2),
                        (base_ind + 2, base_ind + 3, base_ind + 1)])
        base_ind += 4

        # bottom edge
        width = max(bl, br)
        be_y = bl_vert[1] - bl
        vertices.extend([(bl_vert[0], be_y), (bl_vert[0], be_y + width),
                         (br_vert[0], be_y), (br_vert[0], be_y + width)])
        indices.extend([(base_ind, base_ind + 1, base_ind + 2),
                        (base_ind + 2, base_ind + 3, base_ind + 1)])
        base_ind += 4

        # middle
        vertices.extend([tl_vert, tr_vert, bl_vert, br_vert])
        indices.extend([(base_ind, base_ind + 1, base_ind + 2),
                        (base_ind + 2, base_ind + 3, base_ind + 1)])

        batch = batch_for_shader(shader,
                                 'TRIS', {"pos": vertices},
                                 indices=indices)

        shader.uniform_float("color", color)
        batch.draw(shader)

    else:
        overlap = round(thickness / 2 - scale_factor() / 2)

        # left edge
        le_x = tl_vert[0] - tl
        vertices = [(le_x, tl_vert[1] + (overlap if tl == 0 else 0)),
                    (le_x, bl_vert[1] - (overlap if bl == 0 else 0))]

        batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": vertices})
        batch.draw(shader)

        # right edge
        re_x = tr_vert[0] + tr
        vertices = [(re_x, tr_vert[1] + (overlap if tr == 0 else 0)),
                    (re_x, br_vert[1] - (overlap if br == 0 else 0))]

        batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": vertices})
        batch.draw(shader)

        # top edge
        te_y = tl_vert[1] + tl
        vertices = [(tl_vert[0] - (overlap if tl == 0 else 0), te_y),
                    (tr_vert[0] + (overlap if tr == 0 else 0), te_y)]

        batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": vertices})
        batch.draw(shader)

        # bottom edge
        be_y = bl_vert[1] - bl
        vertices = [(bl_vert[0] - (overlap if bl == 0 else 0), be_y),
                    (br_vert[0] + (overlap if br == 0 else 0), be_y)]

        batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": vertices})
        batch.draw(shader)

        bgl.glDisable(bgl.GL_LINE_SMOOTH)

    bgl.glDisable(bgl.GL_BLEND)
Exemplo n.º 55
0
    def draw_postpixel(self):
        # TODO: put all logic into set_next_state(), such as vertex snapping, edge splitting, etc.

        #if self.rfcontext.nav or self.mode != 'main': return
        if not self.actions.using_onlymods('insert'): return  # 'insert alt1'??
        hit_pos = self.actions.hit_pos
        if not hit_pos: return

        self.set_next_state()

        bgl.glEnable(bgl.GL_BLEND)
        CC_DRAW.stipple(pattern=[4, 4])
        CC_DRAW.point_size(8)
        CC_DRAW.line_width(2)

        if self.next_state == 'knife selected edge':
            bmv1, bmv2 = self.nearest_edge.verts
            faces = self.nearest_edge.link_faces
            if faces:
                for f in faces:
                    lco = []
                    for v0, v1 in iter_pairs(f.verts, True):
                        lco.append(v0.co)
                        if (v0 == bmv1 and v1 == bmv2) or (v0 == bmv2
                                                           and v1 == bmv1):
                            lco.append(hit_pos)
                    self.draw_lines(lco)
            else:
                self.draw_lines([bmv1.co, hit_pos])
                self.draw_lines([bmv2.co, hit_pos])

        elif self.next_state == 'new vertex':
            p0 = hit_pos
            e1, d = self.rfcontext.nearest2D_edge(edges=self.vis_edges)
            if e1:
                bmv1, bmv2 = e1.verts
                if d is not None and d < self.rfcontext.drawing.scale(15):
                    f = next(iter(e1.link_faces), None)
                    if f:
                        lco = []
                        for v0, v1 in iter_pairs(f.verts, True):
                            lco.append(v0.co)
                            if (v0 == bmv1 and v1 == bmv2) or (v0 == bmv2
                                                               and v1 == bmv1):
                                lco.append(p0)
                        self.draw_lines(lco)
                    else:
                        self.draw_lines([bmv1.co, hit_pos])
                        self.draw_lines([bmv2.co, hit_pos])
                else:
                    self.draw_lines([hit_pos])
            else:
                self.draw_lines([hit_pos])

        elif self.next_state in {'vert-edge', 'vert-edge-vert'}:
            sel_verts = self.sel_verts
            bmv0 = next(iter(sel_verts))
            if self.nearest_vert:
                p0 = self.nearest_vert.co
            elif self.next_state == 'vert-edge':
                p0 = hit_pos
                e1, d = self.rfcontext.nearest2D_edge(edges=self.vis_edges)
                if e1:
                    bmv1, bmv2 = e1.verts
                    if d is not None and d < self.rfcontext.drawing.scale(15):
                        f = next(iter(e1.link_faces), None)
                        if f:
                            lco = []
                            for v0, v1 in iter_pairs(f.verts, True):
                                lco.append(v0.co)
                                if (v0 == bmv1
                                        and v1 == bmv2) or (v0 == bmv2
                                                            and v1 == bmv1):
                                    lco.append(p0)
                            self.draw_lines(lco)
                        else:
                            self.draw_lines([bmv1.co, p0])
                            self.draw_lines([bmv2.co, p0])
            elif self.next_state == 'vert-edge-vert':
                p0 = hit_pos
            else:
                return
            self.draw_lines([bmv0.co, p0])

        elif self.actions.shift and not self.actions.ctrl:
            if self.next_state in [
                    'edge-face', 'edge-quad', 'edge-quad-snap', 'tri-quad'
            ]:
                nearest_vert, _ = self.rfcontext.nearest2D_vert(
                    verts=self.sel_verts,
                    max_dist=options['polypen merge dist'])
                if nearest_vert:
                    self.draw_lines([nearest_vert.co, hit_pos])

        elif not self.actions.shift and self.actions.ctrl:
            if self.next_state == 'edge-face':
                e0, _ = self.rfcontext.nearest2D_edge(
                    edges=self.sel_edges)  #next(iter(self.sel_edges))
                if not e0: return
                e1, d = self.rfcontext.nearest2D_edge(edges=self.vis_edges)
                if e1 and d < self.rfcontext.drawing.scale(15) and e0 == e1:
                    bmv1, bmv2 = e1.verts
                    p0 = hit_pos
                    f = next(iter(e1.link_faces), None)
                    if f:
                        lco = []
                        for v0, v1 in iter_pairs(f.verts, True):
                            lco.append(v0.co)
                            if (v0 == bmv1 and v1 == bmv2) or (v0 == bmv2
                                                               and v1 == bmv1):
                                lco.append(p0)
                        self.draw_lines(lco)
                    else:
                        self.draw_lines([bmv1.co, hit_pos])
                        self.draw_lines([bmv2.co, hit_pos])
                else:
                    # self.draw_lines([hit_pos])
                    bmv1, bmv2 = e0.verts
                    if self.nearest_vert and not self.nearest_vert.select:
                        p0 = self.nearest_vert.co
                    else:
                        p0 = hit_pos
                    self.draw_lines([p0, bmv1.co, bmv2.co])

            elif self.next_state == 'edge-quad':
                # a Desmos construction of how this works: https://www.desmos.com/geometry/bmmx206thi
                xy0, xy1, xy2, xy3 = self._get_edge_quad_verts()
                if xy0 is None: return
                co0 = self.rfcontext.raycast_sources_Point2D(xy0)[0]
                co1 = self.rfcontext.raycast_sources_Point2D(xy1)[0]
                co2 = self.rfcontext.raycast_sources_Point2D(xy2)[0]
                co3 = self.rfcontext.raycast_sources_Point2D(xy3)[0]
                self.draw_lines([co1, co2, co3, co0])

            elif self.next_state == 'edge-quad-snap':
                e0, _ = self.rfcontext.nearest2D_edge(edges=self.sel_edges)
                e1 = self.nearest_edge
                if not e0 or not e1: return
                bmv0, bmv1 = e0.verts
                bmv2, bmv3 = e1.verts
                p0, p1 = self.rfcontext.Point_to_Point2D(
                    bmv0.co), self.rfcontext.Point_to_Point2D(bmv1.co)
                p2, p3 = self.rfcontext.Point_to_Point2D(
                    bmv2.co), self.rfcontext.Point_to_Point2D(bmv3.co)
                if intersect2d_segment_segment(p1, p2, p3, p0):
                    bmv2, bmv3 = bmv3, bmv2
                # if e0.vector2D(self.rfcontext.Point_to_Point2D).dot(e1.vector2D(self.rfcontext.Point_to_Point2D)) > 0:
                #     bmv2,bmv3 = bmv3,bmv2
                self.draw_lines([bmv0.co, bmv1.co, bmv2.co, bmv3.co])

            elif self.next_state == 'tri-quad':
                if self.nearest_vert and not self.nearest_vert.select:
                    p0 = self.nearest_vert.co
                else:
                    p0 = hit_pos
                e1, _ = self.rfcontext.nearest2D_edge(edges=self.sel_edges)
                if not e1: return
                bmv1, bmv2 = e1.verts
                f = next(iter(e1.link_faces), None)
                if not f: return
                lco = []
                for v0, v1 in iter_pairs(f.verts, True):
                    lco.append(v0.co)
                    if (v0 == bmv1 and v1 == bmv2) or (v0 == bmv2
                                                       and v1 == bmv1):
                        lco.append(p0)
                self.draw_lines(lco)
Exemplo n.º 56
0
def PS_draw_bgl(self, context):
    if context.mode == 'EDIT_MESH':  # context.active_object != None and context.active_object.select_get() and
        #start_time = time.time()

        props = context.preferences.addons[__package__].preferences
        settings = context.scene.ps_set_

        theme = context.preferences.themes['Default']
        vertex_size = theme.view_3d.vertex_size

        # Color
        VA_Col = props.v_alone_color[0], props.v_alone_color[
            1], props.v_alone_color[2], props.v_alone_color[3]
        VE_Col = props.VE_color[0], props.VE_color[1], props.VE_color[
            2], props.VE_color[3]
        F_Col = props.F_color[0], props.F_color[1], props.F_color[
            2], props.opacity
        sel_Col = props.select_color[0], props.select_color[
            1], props.select_color[2], 1.0

        bgl.glEnable(bgl.GL_BLEND)
        bgl.glLineWidth(props.edge_width)
        bgl.glPointSize(vertex_size + props.verts_size)
        bgl.glCullFace(bgl.GL_BACK)

        if props.xray_ret == False:
            bgl.glEnable(bgl.GL_DEPTH_TEST)
            bgl.glEnable(bgl.GL_CULL_FACE)

        if props.line_smooth:
            bgl.glEnable(bgl.GL_LINE_SMOOTH)

        #bgl.glDepthRange(0, 0.99999)
        #bgl.glDepthFunc(600)
        bgl.glDepthMask(False)

        is_perspective = context.region_data.is_perspective
        if is_perspective:
            z_bias = props.z_bias / 350
        else:
            z_bias = 1.0

        tool_retopo = active_tool().idname in tools_ret  # Retopology Tools
        if tool_retopo:
            shader = shader_uni
        else:
            shader = shader_sm

        shader.bind()

        view_mat = context.region_data.perspective_matrix
        shader.uniform_float("view_mat", view_mat)
        shader.uniform_float("Z_Bias", z_bias)
        shader.uniform_float("Z_Offset", props.z_offset)

        if props.use_mod_ret:
            depsgraph = context.evaluated_depsgraph_get()

        uniques = context.objects_in_mode_unique_data
        #uniques = context.selected_objects
        #uniques = context.objects_in_mode
        for obj in uniques:
            if props.use_mod_ret:
                if len(obj.modifiers) > 0:
                    depsgraph.update()

                ob_eval = obj.evaluated_get(depsgraph)
                me = ob_eval.to_mesh()

                bm = bmesh.new()
                bm.from_mesh(me, face_normals=True, use_shape_key=False)

                bm.verts.ensure_lookup_table()
                bm.edges.ensure_lookup_table()
                bm.faces.ensure_lookup_table()

            else:
                bm = bmesh.from_edit_mesh(obj.data)

            if len(bm.verts) <= props.maxP_retop:
                # Если выбран инструмент ретопологии
                if tool_retopo:
                    # все вертексы
                    vCo = [obj.matrix_world @ v.co for v in bm.verts]
                    vNm = [v.normal for v in bm.verts]

                    # --- FACES
                    if settings.draw_faces:
                        loop_triangles = bm.calc_loop_triangles()
                        faces_indices = [[
                            loop.vert.index for loop in looptris
                        ] for looptris in loop_triangles]

                        FACES = batch_for_shader(shader,
                                                 'TRIS', {
                                                     "pos": vCo,
                                                     'nrm': vNm
                                                 },
                                                 indices=faces_indices)
                        shader.uniform_float("color", F_Col)
                        FACES.draw(shader)

                    # --- EDGES
                    if settings.draw_edges:
                        #edges_indices = [ [e.verts[0].index, e.verts[1].index]  for e in bm.edges]
                        edges_ind = [e.index for e in bm.edges]
                        edges_cord = [
                            obj.matrix_world @ v.co for i in edges_ind
                            for v in bm.edges[i].verts
                        ]
                        eNm = [
                            v.normal for i in edges_ind
                            for v in bm.edges[i].verts
                        ]

                        EDGES = batch_for_shader(shader, 'LINES', {
                            "pos": edges_cord,
                            'nrm': eNm
                        })
                        shader.uniform_float("color", VE_Col)
                        EDGES.draw(shader)

                    # --- VERTS
                    # только одиночные вертексы
                    if settings.draw_verts:
                        vCo_one = [
                            obj.matrix_world @ v.co for v in bm.verts
                            if len(v.link_faces) < 1
                        ]  #not v.is_manifold] (not v.is_manifold and v.is_wire)
                        vCo_one_Nm = [
                            v.normal for v in bm.verts if len(v.link_faces) < 1
                        ]
                        VERTS = batch_for_shader(shader, 'POINTS', {
                            "pos": vCo_one,
                            'nrm': vCo_one_Nm
                        })
                        shader.uniform_float("color", VA_Col)
                        VERTS.draw(shader)

                # Если выбраны обычные инструменты
                else:
                    # --- FACES
                    vCo = [obj.matrix_world @ v.co for v in bm.verts]
                    vNm = [v.normal for v in bm.verts]
                    v_len = len(vCo)

                    if settings.draw_faces:
                        loop_triangles = bm.calc_loop_triangles()
                        faces_indices = [[
                            loop.vert.index for loop in looptris
                        ] for looptris in loop_triangles]

                        face_col = [F_Col for i in range(v_len)]
                        FACES = batch_for_shader(shader,
                                                 'TRIS', {
                                                     "pos": vCo,
                                                     "col": face_col,
                                                     'nrm': vNm
                                                 },
                                                 indices=faces_indices)
                        FACES.draw(shader)

                    # --- EDGES
                    if settings.draw_edges:
                        edges_ind = [e.index for e in bm.edges]
                        edges_cord = [
                            obj.matrix_world @ v.co for i in edges_ind
                            for v in bm.edges[i].verts
                        ]
                        eNm = [
                            v.normal for i in edges_ind
                            for v in bm.edges[i].verts
                        ]

                        edge_col = [VE_Col for i in range(len(edges_cord))]

                        for i, edge in enumerate(
                                bm.edges):  # Окрашивание выделенных элементов
                            if edge.select:
                                ind = i * 2
                                ind2 = ind + 1
                                edge_col[ind] = sel_Col
                                edge_col[ind2] = sel_Col
                        #edges_indices = [ [e.verts[0].index, e.verts[1].index]  for e in bm.edges]
                        EDGES = batch_for_shader(shader, 'LINES', {
                            "pos": edges_cord,
                            "col": edge_col,
                            'nrm': eNm
                        })  # , indices=edges_indices
                        EDGES.draw(shader)

                    # --- VERTS
                    if settings.draw_verts:
                        vert_col = [VE_Col for i in range(v_len)]

                        for i, vert in enumerate(
                                bm.verts):  # Окрашивание выделенных элементов
                            if len(vert.link_faces) < 1:
                                vert_col[i] = VA_Col

                            if vert.select:
                                #face_col[i] = select_color_f
                                vert_col[i] = sel_Col
                                #edge_col[i] = sel_Col

                        VERTS = batch_for_shader(shader, 'POINTS', {
                            "pos": vCo,
                            "col": vert_col,
                            'nrm': vNm
                        })
                        if context.tool_settings.mesh_select_mode[0]:
                            VERTS.draw(shader)

            if props.use_mod_ret:
                bm.free()
        """ if props.line_smooth:
            bgl.glDisable(bgl.GL_LINE_SMOOTH) """
        """ bgl.glDisable(bgl.GL_DEPTH_TEST)
Exemplo n.º 57
0
def glSwitch(attr, value):
    if value:
        bgl.glEnable(attr)
    else:
        bgl.glDisable(attr)
Exemplo n.º 58
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[0])
        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()
Exemplo n.º 59
0
    def draw_target_and_sources(self):
        if not self.actions.r3d: return
        if not self.loading_done: return
        # if self.fps_low_warning: return     # skip drawing if low FPS warning is showing

        buf_matrix_target = self.rftarget_draw.rfmesh.xform.mx_p # self.rftarget_draw.buf_matrix_model
        buf_matrix_target_inv = self.rftarget_draw.rfmesh.xform.imx_p # self.rftarget_draw.buf_matrix_inverse
        buf_matrix_view = self.actions.r3d.view_matrix # XForm.to_bglMatrix(self.actions.r3d.view_matrix)
        buf_matrix_view_invtrans = matrix_normal(self.actions.r3d.view_matrix) # XForm.to_bglMatrix(matrix_normal(self.actions.r3d.view_matrix))
        buf_matrix_proj = self.actions.r3d.window_matrix # XForm.to_bglMatrix(self.actions.r3d.window_matrix)
        view_forward = self.Vec_forward()  # self.actions.r3d.view_rotation * Vector((0,0,-1))

        # bgl.glEnable(bgl.GL_MULTISAMPLE)
        # bgl.glEnable(bgl.GL_LINE_SMOOTH)
        # bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glEnable(bgl.GL_BLEND)
        # bgl.glEnable(bgl.GL_POINT_SMOOTH)

        if options['symmetry view'] != 'None' and self.rftarget.mirror_mod.xyz:
            if options['symmetry view'] in {'Edge', 'Face'}:
                # get frame of target, used for symmetry decorations on sources
                ft = self.rftarget.get_frame()
                # render sources
                for rs,rfs in zip(self.rfsources, self.rfsources_draw):
                    rfs.draw(
                        view_forward, self.unit_scaling_factor,
                        buf_matrix_target, buf_matrix_target_inv,
                        buf_matrix_view, buf_matrix_view_invtrans, buf_matrix_proj,
                        1.00, 0.05, False, 0.5,
                        False,
                        symmetry=self.rftarget.mirror_mod.xyz,
                        symmetry_view=options['symmetry view'],
                        symmetry_effect=options['symmetry effect'],
                        symmetry_frame=ft,
                    )
            elif options['symmetry view'] == 'Plane':
                # draw symmetry planes
                bgl.glEnable(bgl.GL_DEPTH_TEST)
                bgl.glDepthFunc(bgl.GL_LEQUAL)
                bgl.glDisable(bgl.GL_CULL_FACE)
                drawing = Globals.drawing
                a = pow(options['symmetry effect'], 2.0) # fudge this value, because effect is different with plane than edge/face
                r = (1.0, 0.2, 0.2, a)
                g = (0.2, 1.0, 0.2, a)
                b = (0.2, 0.2, 1.0, a)
                w2l = self.rftarget_draw.rfmesh.xform.w2l_point
                l2w = self.rftarget_draw.rfmesh.xform.l2w_point
                # for rfs in self.rfsources:
                #     corners = [self.Point_to_Point2D(l2w(p)) for p in rfs.get_local_bbox(w2l).corners]
                #     drawing.draw2D_lines(corners, (1,1,1,1))
                corners = [ c for s in self.rfsources for c in s.get_local_bbox(w2l).corners ]
                mx, Mx = min(c.x for c in corners), max(c.x for c in corners)
                my, My = min(c.y for c in corners), max(c.y for c in corners)
                mz, Mz = min(c.z for c in corners), max(c.z for c in corners)
                cx, cy, cz = mx + (Mx - mx) / 2, my + (My - my) / 2, mz + (Mz - mz) / 2
                mx, Mx = cx + (mx - cx) * 1.2, cx + (Mx - cx) * 1.2
                my, My = cy + (my - cy) * 1.2, cy + (My - cy) * 1.2
                mz, Mz = cz + (mz - cz) * 1.2, cz + (Mz - cz) * 1.2
                if self.rftarget.mirror_mod.x:
                    quad = [ l2w(Point((0, my, mz))), l2w(Point((0, my, Mz))), l2w(Point((0, My, Mz))), l2w(Point((0, My, mz))) ]
                    drawing.draw3D_triangles([quad[0], quad[1], quad[2], quad[0], quad[2], quad[3]], [r, r, r, r, r, r])
                if self.rftarget.mirror_mod.y:
                    quad = [ l2w(Point((mx, 0, mz))), l2w(Point((mx, 0, Mz))), l2w(Point((Mx, 0, Mz))), l2w(Point((Mx, 0, mz))) ]
                    drawing.draw3D_triangles([quad[0], quad[1], quad[2], quad[0], quad[2], quad[3]], [g, g, g, g, g, g])
                if self.rftarget.mirror_mod.z:
                    quad = [ l2w(Point((mx, my, 0))), l2w(Point((mx, My, 0))), l2w(Point((Mx, My, 0))), l2w(Point((Mx, my, 0))) ]
                    drawing.draw3D_triangles([quad[0], quad[1], quad[2], quad[0], quad[2], quad[3]], [b, b, b, b, b, b])

        # render target
        # bgl.glEnable(bgl.GL_MULTISAMPLE)
        # bgl.glEnable(bgl.GL_LINE_SMOOTH)
        # bgl.glHint(bgl.GL_LINE_SMOOTH_HINT, bgl.GL_NICEST)
        bgl.glEnable(bgl.GL_BLEND)
        if True:
            alpha_above,alpha_below = options['target alpha'],options['target hidden alpha']
            cull_backfaces = options['target cull backfaces']
            alpha_backface = options['target alpha backface']
            self.rftarget_draw.draw(
                view_forward, self.unit_scaling_factor,
                buf_matrix_target, buf_matrix_target_inv,
                buf_matrix_view, buf_matrix_view_invtrans, buf_matrix_proj,
                alpha_above, alpha_below, cull_backfaces, alpha_backface,
                True
            )
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)