def allocate(self, shape): """ Allocate a new region of given shape. Parameters ---------- shape : (int,int) Shape of region as (heigth, width) Return ------ Texture2D or None """ height, width = shape best_height = sys.maxint best_index = -1 best_width = sys.maxint region = 0, 0, width, height for i in range(len(self.nodes)): y = self._fit(i, width, height) if y >= 0: node = self.nodes[i] if (y+height < best_height or (y+height == best_height and node[2] < best_width)): best_height = y+height best_index = i best_width = node[2] region = node[0], y, width, height if best_index == -1: log.warn("No enough free space in atlas") return None node = region[0], region[1]+height, width self.nodes.insert(best_index, node) i = best_index+1 while i < len(self.nodes): node = self.nodes[i] prev_node = self.nodes[i-1] if node[0] < prev_node[0]+prev_node[2]: shrink = prev_node[0]+prev_node[2] - node[0] x,y,w = self.nodes[i] self.nodes[i] = x+shrink, y, w-shrink if self.nodes[i][2] <= 0: del self.nodes[i] i -= 1 else: break else: break i += 1 self._merge() self.used += width*height x,y,width,height = region return region
def allocate(self, shape): """ Allocate a new region of given shape. Parameters ---------- shape : (int,int) Shape of region as (heigth, width) Return ------ Texture2D or None """ height, width = shape best_height = sys.maxsize best_index = -1 best_width = sys.maxsize region = 0, 0, width, height for i in range(len(self.nodes)): y = self._fit(i, width, height) if y >= 0: node = self.nodes[i] if (y + height < best_height or (y + height == best_height and node[2] < best_width)): best_height = y + height best_index = i best_width = node[2] region = node[0], y, width, height if best_index == -1: log.warn("No enough free space in atlas") return None node = region[0], region[1] + height, width self.nodes.insert(best_index, node) i = best_index + 1 while i < len(self.nodes): node = self.nodes[i] prev_node = self.nodes[i - 1] if node[0] < prev_node[0] + prev_node[2]: shrink = prev_node[0] + prev_node[2] - node[0] x, y, w = self.nodes[i] self.nodes[i] = x + shrink, y, w - shrink if self.nodes[i][2] <= 0: del self.nodes[i] i -= 1 else: break else: break i += 1 self._merge() self.used += width * height x, y, width, height = region return region
def __init__( self, width=256, height=256, title=None, visible=True, aspect=None, decoration=True, fullscreen=False, config=None, context=None, color=(0,0,0,1), vsync=False): if vsync: log.warn('vsync not implemented for osxglut backend') if len(__windows__) > 0: log.critical( """OSXGLUT backend is unstable with more than one window.\n""" """Exiting...""") sys.exit(0) window.Window.__init__(self, width=width, height=height, title=title, visible=visible, aspect=aspect, decoration=decoration, fullscreen=fullscreen, config=config, context=context, color=color) if config is None: config = configuration.Configuration() set_configuration(config) self._native_window = glut.glutCreateWindow( self._title ) if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_CONTINUE_EXECUTION) glut.glutSetOption(glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS, glut.GLUT_ACTION_CONTINUE_EXECUTION) glut.glutWMCloseFunc( self._close ) glut.glutDisplayFunc( self._display ) glut.glutReshapeFunc( self._reshape ) glut.glutKeyboardFunc( self._keyboard ) glut.glutKeyboardUpFunc( self._keyboard_up ) glut.glutMouseFunc( self._mouse ) glut.glutMotionFunc( self._motion ) glut.glutPassiveMotionFunc( self._passive_motion ) glut.glutVisibilityFunc( self._visibility ) glut.glutEntryFunc( self._entry ) glut.glutSpecialFunc( self._special ) glut.glutSpecialUpFunc( self._special_up ) glut.glutReshapeWindow( self._width, self._height ) if visible: glut.glutShowWindow() else: glut.glutHideWindow() # This ensures glutCheckLoop never blocks def on_idle(): pass glut.glutIdleFunc(on_idle) __windows__.append(self)
def __init__(self, content=None, parent=None): Transformable.__init__(self, content, parent) self._items = [] for element in content: if not element.tag.startswith(namespace): continue tag = element.tag[len(namespace):] if tag == "g": item = Group(element, self) elif tag == "path": item = Path(element, self) else: log.warn("Unhandled SVG tag (%s)" % tag) continue self._items.append(item)
def __init__(self, content=None, parent=None): Transformable.__init__(self, content, parent) self._items = [] for element in content: if not element.tag.startswith(namespace): continue tag = element.tag[len(namespace) :] if tag == "g": item = Group(element, self) elif tag == "path": item = Path(element, self) else: log.warn("Unhandled SVG tag (%s)" % tag) continue self._items.append(item)
def parse(cls, color, alpha ): """ Color parsing """ if color is None: return if isinstance(color, str): # Named color if color[0] != '#': color = color.lower().strip() color = color.replace(' ','') color = color.replace('-','') color = _colors.get(color) if color[0] != '#': log.warn("Unknown color name : %s" % color) return 0,0,0,1 # Hexadecimal color color = color[1:] if len(color) == 3: color += 'f' if len(color) == 4: color = ''.join([color[i] for i in [0,0,1,1,2,2,3,3]]) if len(color) == 6: color += 'ff' r,g,b,a = [c/255.0 for c in bytearray.fromhex(color)] if alpha is not None: a = alpha return r,g,b,a # Tuple/list/array color elif isinstance(color, (list, tuple, np.ndarray)): color = np.clip(color, 0, 1) if alpha is not None: color[3] = alpha return color # Unknown format else: log.warn("Unknown color format : %s" % color) return 0,0,0,1
def parse(cls, color, alpha): """ Color parsing """ if color is None: return if isinstance(color, str): # Named color if color[0] != '#': color = color.lower().strip() color = color.replace(' ', '') color = color.replace('-', '') color = _colors.get(color) if color[0] != '#': log.warn("Unknown color name : %s" % color) return 0, 0, 0, 1 # Hexadecimal color color = color[1:] if len(color) == 3: color += 'f' if len(color) == 4: color = ''.join([color[i] for i in [0, 0, 1, 1, 2, 2, 3, 3]]) if len(color) == 6: color += 'ff' r, g, b, a = [ord(c) / 255.0 for c in color.decode('hex')] if alpha is not None: a = alpha return r, g, b, a # Tuple/list/array color elif isinstance(color, (list, tuple, np.ndarray)): color = np.clip(color, 0, 1) if alpha is not None: color[3] = alpha return color # Unknown format else: log.warn("Unknown color format : %s" % color) return 0, 0, 0, 1
def __init__(self, colors=[], count=0, alpha=None): """ Colors initialization Parameters ---------- colors : list List of color names or values count : int Number of colors alpha : float Alpha channels """ if isinstance(colors, str): if colors[0] != '#': colors = _colors.get(colors) if isinstance(colors, str): colors = [colors] if len(colors) > 0: n = len(colors) self._data = np.zeros((n,4),dtype=np.float32) for i in range(n): self._data[i] = Color(colors[i]).rgba elif count > 0: self._data = np.zeros((count,4),dtype=np.float32) else: log.warn("Colors must be declared with a list or a color count") self._data = np.zeros((1,4),dtype=np.float32) if alpha is not None: self._data[:,3] = alpha
def __init__(self, colors=[], count=0, alpha=None): """ Colors initialization Parameters ---------- colors : list List of color names or values count : int Number of colors alpha : float Alpha channels """ if isinstance(colors, str): if colors[0] != '#': colors = _colors.get(colors) if isinstance(colors, str): colors = [colors] if len(colors) > 0: n = len(colors) self._data = np.zeros((n, 4), dtype=np.float32) for i in range(n): self._data[i] = Color(colors[i]).rgba elif count > 0: self._data = np.zeros((count, 4), dtype=np.float32) else: log.warn("Colors must be declared with a list or a color count") self._data = np.zeros((1, 4), dtype=np.float32) if alpha is not None: self._data[:, 3] = alpha
def set_position(self, x, y): """ Set window position """ log.warn('%s backend cannot set window position' % self._backend.name())
def set_size(self, width, height): """ Set window size """ log.warn('%s backend cannot set window size' % self._backend.name())
def set_title(self, title): """ Set window title """ log.warn('%s backend cannot set window title' % self._backend.name())
def hide(self): """ Hide the window """ log.warn('%s backend cannot hide window' % self._backend.name())
def show(self): """ Make the window visible """ log.warn('%s backend cannot show window' % self._backend.name())
def get_title(self): log.warn('%s backend cannot get window title' % __name__)
def swap(self): """ Swap GL buffers """ log.warn('%s backend cannot swap buffers' % self._backend.name())
def get_size(self): """ Get window size """ log.warn('%s backend cannot get window size' % self._backend.name())
def get_title(self): """ Get window title """ log.warn('%s backend cannot get window title' % self._backend.name())
def close(self): """ Close (destroy) the window """ log.warn('%s backend cannot close window' % self._backend.name())
def set_screen(self, screen): """ Set window screen """ log.warn('%s backend cannot set screen' % self._backend.name())
def set_fullscreen(self, fullscreen): """ Set window fullscreen mode """ log.warn('%s backend cannot set fullscreen mode' % self._backend.name())
def get_position(self): """ Get window position """ log.warn('%s backend cannot get position' % self._backend.name())
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, Nicolas P. Rougier # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- import ctypes from glumpy.log import log from OpenGL.arrays import numpymodule try: numpymodule.NumpyHandler.ERROR_ON_COPY = True except TypeError: log.warn("Cannot set error on copy on GPU copy") from OpenGL import contextdata def cleanupCallback(context=None): """Create a cleanup callback to clear context-specific storage for the current context""" def callback(context=contextdata.getContext(context)): """Clean up the context, assumes that the context will *not* render again!""" contextdata.cleanupContext(context) return callback from OpenGL.GL import * from OpenGL.GL.EXT.geometry_shader4 import * from OpenGL.GL.NV.geometry_program4 import * from OpenGL.GL.ARB.texture_rg import *
def set_fullscreen(self, fullsrceen): """ Set window fullscreen mode """ log.warn('%s backend cannot set fullscreen mode' % self._backend.name())
def set_title(self, title): log.warn('%s backend cannot set window title' % __name__)
def get_fullscreen(self): """ Get window fullscreen mode """ log.warn('%s backend cannot get fullscreen mode' % self._backend.name())
def activate(self): """ Activate window """ log.warn('%s backend cannot make window active' % self._backend.name())
def set_size(self, width, height): log.warn('%s backend cannot set window size' % __name__)
def get_screen(self): """ Get window screen """ log.warn('%s backend cannot get screen' % self._backend.name())
def get_size(self): log.warn('%s backend cannot get window size' % __name__)
def gl_get_configuration(): """ Read gl configuration independently of backends. """ import ctypes import OpenGL.GL as gl configuration = Configuration() gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) value = ctypes.c_int() try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_FRONT_LEFT, gl.GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, value ) configuration._red_size = value.value except: log.warn("Cannot read RED channel size from the framebuffer") configuration._red_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_FRONT_LEFT, gl.GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, value ) configuration._green_size = value.value except: log.warn("Cannot read GREEN channel size from the framebuffer") configuration._green_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_FRONT_LEFT, gl.GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, value ) configuration._blue_size = value.value except: log.warn("Cannot read BLUE channel size from the framebuffer") configuration._blue_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_FRONT_LEFT, gl.GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, value ) configuration._alpha_size = value.value except: log.warn("Cannot read ALPHA channel size from the framebuffer") configuration._alpha_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_DEPTH, gl.GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, value ) configuration._depth_size = value.value except: log.warn("Cannot read DEPTH size from the framebuffer") configuration._depth_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_STENCIL, gl.GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, value ) configuration._stencil_size = value.value except: log.warn("Cannot read STENCIL size from the framebuffer") configuration._stencil_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_FRONT_LEFT, gl.GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, value ) if value.value == gl.GL_LINEAR: configuration._srgb = False elif value.value == gl.GL_SRGB: configuration._srgb = True except: log.warn("Cannot read sRGB value from the framebuffer") configuration._srgb = False configuration._stereo = gl.glGetInteger(gl.GL_STEREO) configuration._double_buffer = gl.glGetInteger(gl.GL_DOUBLEBUFFER) configuration._samples = gl.glGetInteger(gl.GL_SAMPLES) # Dumb parsing of the GL_VERSION string version = gl.glGetString(gl.GL_VERSION) version = version.split(" ")[0] major,minor = version.split('.')[:2] configuration._version = version configuration._major_version = int(major) configuration._minor_version = int(minor) configuration._profile = "unknown" return configuration
def get_position(self): log.warn('%s backend cannot get position' % __name__)
def gl_get_configuration(): """ Read gl configuration independently of backends. """ import ctypes import OpenGL.GL as gl configuration = Configuration() try: gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) except: log.warn("Cannot bind framebuffer") value = ctypes.c_int() try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_FRONT_LEFT, gl.GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE, value) configuration._red_size = value.value except: log.warn("Cannot read RED channel size from the framebuffer") configuration._red_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_FRONT_LEFT, gl.GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE, value) configuration._green_size = value.value except: log.warn("Cannot read GREEN channel size from the framebuffer") configuration._green_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_FRONT_LEFT, gl.GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE, value) configuration._blue_size = value.value except: log.warn("Cannot read BLUE channel size from the framebuffer") configuration._blue_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_FRONT_LEFT, gl.GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, value) configuration._alpha_size = value.value except: log.warn("Cannot read ALPHA channel size from the framebuffer") configuration._alpha_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_DEPTH, gl.GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, value) configuration._depth_size = value.value except: log.warn("Cannot read DEPTH size from the framebuffer") configuration._depth_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_STENCIL, gl.GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, value) configuration._stencil_size = value.value except: log.warn("Cannot read STENCIL size from the framebuffer") configuration._stencil_size = 0 try: gl.glGetFramebufferAttachmentParameteriv( gl.GL_FRAMEBUFFER, gl.GL_FRONT_LEFT, gl.GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, value) if value.value == gl.GL_LINEAR: configuration._srgb = False elif value.value == gl.GL_SRGB: configuration._srgb = True except: log.warn("Cannot read sRGB value from the framebuffer") configuration._srgb = False configuration._stereo = gl.glGetInteger(gl.GL_STEREO) configuration._double_buffer = gl.glGetInteger(gl.GL_DOUBLEBUFFER) configuration._samples = gl.glGetInteger(gl.GL_SAMPLES) # Dumb parsing of the GL_VERSION string version = gl.glGetString(gl.GL_VERSION) version = version.split(" ")[0] major, minor = version.split('.')[:2] configuration._version = version configuration._major_version = int(major) configuration._minor_version = int(minor) configuration._profile = "unknown" return configuration
def set_position(self, x, y): log.warn('%s backend cannot set window position' % __name__)
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) 2014, Nicolas P. Rougier # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- import ctypes from glumpy.log import log from OpenGL.arrays import numpymodule try: numpymodule.NumpyHandler.ERROR_ON_COPY = True except TypeError: log.warn("Cannot set error on copy on GPU copy") from OpenGL import contextdata def cleanupCallback( context=None ): """Create a cleanup callback to clear context-specific storage for the current context""" def callback( context = contextdata.getContext( context ) ): """Clean up the context, assumes that the context will *not* render again!""" contextdata.cleanupContext( context ) return callback from OpenGL.GL import * from OpenGL.GL.EXT.geometry_shader4 import * from OpenGL.GL.NV.geometry_program4 import * from OpenGL.GL.ARB.texture_rg import * # Patch: pythonize the glGetActiveAttrib _glGetActiveAttrib = glGetActiveAttrib
def __init__(self, width=256, height=256, title=None, visible=True, aspect=None, decoration=True, fullscreen=False, config=None, context=None, color=(0, 0, 0, 1), vsync=False): if vsync: log.warn('vsync not implemented for freeglut backend') if len(__windows__) > 0: log.critical( """OSXGLUT backend is unstable with more than one window.\n""" """Exiting...""") sys.exit(0) window.Window.__init__(self, width=width, height=height, title=title, visible=visible, aspect=aspect, decoration=decoration, fullscreen=fullscreen, config=config, context=context, color=color) if config is None: config = configuration.Configuration() set_configuration(config) self._native_window = glut.glutCreateWindow(self._title) if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_CONTINUE_EXECUTION) glut.glutSetOption(glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS, glut.GLUT_ACTION_CONTINUE_EXECUTION) glut.glutWMCloseFunc(self._close) glut.glutDisplayFunc(self._display) glut.glutReshapeFunc(self._reshape) glut.glutKeyboardFunc(self._keyboard) glut.glutKeyboardUpFunc(self._keyboard_up) glut.glutMouseFunc(self._mouse) glut.glutMotionFunc(self._motion) glut.glutPassiveMotionFunc(self._passive_motion) glut.glutVisibilityFunc(self._visibility) glut.glutEntryFunc(self._entry) glut.glutSpecialFunc(self._special) glut.glutSpecialUpFunc(self._special_up) glut.glutReshapeWindow(self._width, self._height) if visible: glut.glutShowWindow() else: glut.glutHideWindow() # This ensures glutCheckLoop never blocks def on_idle(): pass glut.glutIdleFunc(on_idle) __windows__.append(self)