def get_uniform_data(program): """ Args: program: Returns: """ uniforms = {} count = pointer(GLint()) buffer_size = GLsizei(32) length = GLsizei() size = GLint() data_type = GLenum() uniform_name = c_string('', size=buffer_size.value) glGetProgramiv(program, GL_ACTIVE_UNIFORMS, count) for i in range(count.contents.value): glGetActiveUniform(program, GLuint(i), buffer_size, length, size, data_type, uniform_name) uniform_name_ = uniform_name.value.decode('utf-8') data_type_string = temp[data_type.value] uniforms[uniform_name_] = { 'dtype': table[data_type_string]['dtype'], 'index': i, 'size': size.value, 'value': None, 'location': glGetUniformLocation(program, uniform_name), 'function': table[data_type_string]['function'], } print(uniform_name_, uniforms[uniform_name_]) return uniforms
def reload(self, maxlength, count, fn, locfn): """ Template to reload a cache of uniforms or attributes """ prog = self.prog() if prog is None: raise RuntimeError('Shader was freed') maxlength = getattr(prog, maxlength) name_buf = (c_char * maxlength)() name_buf_ptr = cast(name_buf, POINTER(c_char)) type_buf = GLenum(0) name_buf_length = GLint(0) buf_size = GLint(0) self.cache = {} for i in range(getattr(prog, count)): fn(prog.pid, i, maxlength, byref(name_buf_length), byref(buf_size), byref(type_buf), name_buf_ptr) type = type_buf.value name_len = name_buf_length.value name = bytes(name_buf)[0:name_len].decode('UTF-8') size = buf_size.value loc = GLint( locfn(prog.pid, name_buf_ptr) ) #Kept in a c_int to quickly send the value when setting self.cache_item_build(loc, size, name, type)
def __init__(self, src): sid = False try: sid = glCreateShaderObjectARB(self.shader_type) except GLException: pass if not sid: raise ShaderError("Can't create shader object!") l = GLsizei(len(src)) buf = create_string_buffer(src, len(src) + 10) pbuf = pointer(buf) glShaderSourceARB(sid, 1, cast(byref(pbuf), POINTER(POINTER(c_char))), byref(l)) glCompileShader(sid) v = GLint() glGetShaderiv(sid, GL_COMPILE_STATUS, byref(v)) if not v: log = _get_infolog(sid) e = ShaderError("Error compiling shader!") e.infolog = log raise e self.sid = sid
class GLGetObject(object): """ Descriptor that wraps glGet* function """ __slots__ = ['pname'] buffer = GLint(0) def __init__(self, pname): self.pname = pname def __set__(self): raise AttributeError('Attribute is not writable') def __delete__(self): raise AttributeError('Attribute cannot be deleted')
def read_opengl_array(_id, length, fn, ctype=c_char): """ Wrapper to easily read data from functions of this kind fn(identifier, buffer_lenght_in, buffer_length_out, buffer) """ global out_buffer_length buffer = (ctype * length)() buffer_ptr = cast(buffer, POINTER(ctype)) fn(_id, length, byref(GLint(0)), buffer_ptr) return buffer
def current_program(): """ Return the currently bound shader program or None if there is None. The returned shader do not own the underlying buffer. """ cprog = GLint(0) glGetIntegerv(GL_CURRENT_PROGRAM, byref(cprog)) if cprog.value == 0: return None else: return ShaderProgram(cprog)
def print_error(message): nonlocal error error = True status = GLint() glGetProgramiv(program, GL_INFO_LOG_LENGTH, byref( status)) # Getting the number of char in info log to 'status' output = create_string_buffer(status.value) # status.value) glGetProgramInfoLog(program, status, None, output) print(message, output.value.decode('utf-8'), file=sys.stderr)
def _setOpenGLInfo(self): # OpenGL info: self['openGLVendor'] = gl_info.get_vendor() self['openGLRenderingEngine'] = gl_info.get_renderer() self['openGLVersion'] = gl_info.get_version() GLextensionsOfInterest = ['GL_ARB_multitexture', 'GL_EXT_framebuffer_object', 'GL_ARB_fragment_program', 'GL_ARB_shader_objects', 'GL_ARB_vertex_shader', 'GL_ARB_texture_non_power_of_two', 'GL_ARB_texture_float', 'GL_STEREO'] for ext in GLextensionsOfInterest: self['openGLext.'+ext] = bool(gl_info.have_extension(ext)) maxVerts = GLint() glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts) self['openGLmaxVerticesInVertexArray'] = maxVerts.value
def program_status(program: GLuint, status_type: int) -> int: """ Args: program: The handle to the program. status_type: GL_DELETE_STATUS, GL_LINK_STATUS, GL_VALIDATE_STATUS, GL_INFO_LOG_LENGTH, GL_ATTACHED_SHADERS, GL_ACTIVE_ATOMIC_COUNTER_BUFFERS, GL_ACTIVE_ATTRIBUTES, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, GL_ACTIVE_UNIFORMS, GL_ACTIVE_UNIFORM_BLOCKS, GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH, GL_ACTIVE_UNIFORM_MAX_LENGTH, GL_COMPUTE_WORK_GROUP_SIZE GL_PROGRAM_BINARY_LENGTH, GL_TRANSFORM_FEEDBACK_BUFFER_MODE, GL_TRANSFORM_FEEDBACK_VARYINGS, GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH, GL_GEOMETRY_VERTICES_OUT, GL_GEOMETRY_INPUT_TYPE, GL_GEOMETRY_OUTPUT_TYPE. Returns: Status code. """ status = GLint() glGetProgramiv(program, status_type, byref(status)) return status.value
def shader_status(shader: GLuint, status_type: int) -> GLint: """ Returns the status of the 'shader' for any given 'status_type'. Errors: GL_INVALID_VALUE: if shader is not a value generated by OpenGL. GL_INVALID_OPERATION: if shader does not refer to a shader object. GL_INVALID_ENUM: if status_type is not an accepted value. Args: shader: The handle to the shader. status_type: GL_SHADER_TYPE, GL_DELETE_STATUS, GL_COMPILE_STATUS, GL_INFO_LOG_LENGTH, GL_SHADER_SOURCE_LENGTH. Returns: """ status = GLint() glGetShaderiv(shader, status_type, byref(status)) return status.value
def print_error(message): nonlocal error error = True status = GLint() glGetShaderiv(shader, GL_INFO_LOG_LENGTH, byref(status)) output = create_string_buffer(status.value) glGetShaderInfoLog(shader, status, None, output) shader_source = '\n'.join([ '{:<3} | '.format(row) + line for row, line in enumerate(shader.source.splitlines(), start=1) ]) print(message, output.value.decode('utf-8'), 'Shader source:', shader_source, file=sys.stderr, sep='\n')
def __init__(self, *shaders): pid = False try: pid = glCreateProgramObjectARB() except GLException: raise ShaderError("Can't create program object!") for s in shaders: glAttachObjectARB(pid, s.sid) glLinkProgram(pid) v = GLint(0) glGetProgramiv(pid, GL_LINK_STATUS, byref(v)) if not v: log = _get_infolog(pid) e = ShaderError("Error linking program!") e.infolog = log raise e self.pid = pid self.uniform = _UniformAccesser(self) self.attrib = _AttributeAccesser(self)
import pyglet print("pyglet", pyglet.version) # pyo is a new dependency, for sound: try: import pyo print("pyo", '%i.%i.%i' % pyo.getVersion()) except Exception: print('pyo [not installed]') from psychopy import __version__ print("\nPsychoPy", __version__) win = visual.Window([100, 100]) # some drivers want a window open first print("have shaders:", win._haveShaders) print("\nOpenGL info:") # get info about the graphics card and drivers print("vendor:", gl_info.get_vendor()) print("rendering engine:", gl_info.get_renderer()) print("OpenGL version:", gl_info.get_version()) print("(Selected) Extensions:") extensionsOfInterest = ['GL_ARB_multitexture', 'GL_EXT_framebuffer_object', 'GL_ARB_fragment_program', 'GL_ARB_shader_objects', 'GL_ARB_vertex_shader', 'GL_ARB_texture_non_power_of_two', 'GL_ARB_texture_float', 'GL_STEREO'] for ext in extensionsOfInterest: print("\t", bool(gl_info.have_extension(ext)), ext) # also determine nVertices that can be used in vertex arrays maxVerts = GLint() glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts) print('\tmax vertices in vertex array:', maxVerts.value)
def getInfoText(self): """Get system information text.""" outputText = "" # text to return # show the PsychoPy version from psychopy import __version__ outputText += self.getLine("PsychoPy", __version__) # get system paths outputText += self.getLine("\nPaths to files on the system:") for key in ['userPrefsFile', 'appDataFile', 'demos', 'appFile']: outputText += self.getLine( " %s: %s" % (key, preferences.prefs.paths[key])) # system information such as OS, CPU and memory outputText += self.getLine("\nSystem Info:") outputText += self.getLine( ' '*4, 'Operating System: {}'.format(platform.platform())) outputText += self.getLine( ' ' * 4, 'Processor: {}'.format(platform.processor())) # requires psutil try: import psutil outputText += self.getLine( ' ' * 4, 'CPU freq (MHz): {}'.format(psutil.cpu_freq().max)) outputText += self.getLine( ' ' * 4, 'CPU cores: {} (physical), {} (logical)'.format( psutil.cpu_count(False), psutil.cpu_count())) outputText += self.getLine( ' ' * 4, 'Installed memory: {} (Total), {} (Available)'.format( *psutil.virtual_memory())) except ImportError: outputText += self.getLine(' ' * 4, 'CPU freq (MHz): N/A') outputText += self.getLine( ' ' * 4, 'CPU cores: {} (logical)'.format(os.cpu_count())) outputText += self.getLine(' ' * 4, 'Installed memory: N/A') # if on MacOS if sys.platform == 'darwin': OSXver, junk, architecture = platform.mac_ver() outputText += self.getLine( ' ' * 4, "macOS %s running on %s" % (OSXver, architecture)) # Python information outputText += self.getLine("\nPython info:") outputText += self.getLine(' '*4, 'Executable path:', sys.executable) outputText += self.getLine(' '*4, 'Version:', sys.version) outputText += self.getLine(' ' * 4, '(Selected) Installed Packages:') import numpy outputText += self.getLine(' '*8, "numpy ({})".format( numpy.__version__)) import scipy outputText += self.getLine(' '*8, "scipy ({})".format( scipy.__version__)) import matplotlib outputText += self.getLine(' '*8, "matplotlib ({})".format( matplotlib.__version__)) import pyglet outputText += self.getLine(' '*8, "pyglet ({})".format(pyglet.version)) try: import glfw outputText += self.getLine(' '*8, "PyGLFW ({})".format( glfw.__version__)) except Exception: outputText += self.getLine(' '*8, 'PyGLFW [not installed]') # sound related try: import pyo outputText += self.getLine( ' '*8, "pyo", ('%i.%i.%i' % pyo.getVersion())) except Exception: outputText += self.getLine(' '*8, 'pyo [not installed]') try: import psychtoolbox outputText += self.getLine(' '*8, "psychtoolbox ({})".format( psychtoolbox._version.__version__)) except Exception: outputText += self.getLine(' '*8, 'psychtoolbox [not installed]') # wxpython version try: import wx outputText += self.getLine(' '*8, "wxPython ({})".format( wx.__version__)) except Exception: outputText += self.getLine(' '*8, 'wxPython [not installed]') # get OpenGL details win = visual.Window([100, 100]) # some drivers want a window open first outputText += self.getLine("\nOpenGL Info:") # # get info about the graphics card and drivers outputText += self.getLine( ' '*4, "Vendor:", gl_info.get_vendor()) outputText += self.getLine( ' '*4, "Rendering engine:", gl_info.get_renderer()) outputText += self.getLine( ' '*4, "OpenGL version:", gl_info.get_version()) outputText += self.getLine( ' '*4, "Shaders supported: ", win._haveShaders) # get opengl extensions outputText += self.getLine(' '*4, "(Selected) Extensions:") extensionsOfInterest = [ 'GL_ARB_multitexture', 'GL_EXT_framebuffer_object', 'GL_ARB_fragment_program', 'GL_ARB_shader_objects', 'GL_ARB_vertex_shader', 'GL_ARB_texture_non_power_of_two', 'GL_ARB_texture_float', 'GL_STEREO'] for ext in extensionsOfInterest: outputText += self.getLine( ' '*8, ext + ':', bool(gl_info.have_extension(ext))) # also determine nVertices that can be used in vertex arrays maxVerts = GLint() glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts) outputText += self.getLine( ' '*4, 'max vertices in vertex array:', maxVerts.value) win.close() return outputText
def __init__(self, shaders, attributes, uniforms): vertex_shader = shaders[0] fragment_shader = shaders[1] vertex_handle = glCreateShader(GL_VERTEX_SHADER) glShaderSource( vertex_handle, 1, cast(pointer(pointer(create_string_buffer(vertex_shader))), POINTER(POINTER(GLchar))), None) glCompileShader(vertex_handle) fragment_handle = glCreateShader(GL_FRAGMENT_SHADER) glShaderSource( fragment_handle, 1, cast(pointer(pointer(create_string_buffer(fragment_shader))), POINTER(POINTER(GLchar))), None) glCompileShader(fragment_handle) # Create attributes. attribute_mapping = [] for attribute in attributes: attribute_mapping.append(create_string_buffer(attribute)) try: # Create program. program_handle = glCreateProgram() glAttachShader(program_handle, vertex_handle) glAttachShader(program_handle, fragment_handle) for index, name in enumerate(attributes): # CHANGED glBindAttribLocation(program_handle, index, name) glLinkProgram(program_handle) glValidateProgram(program_handle) glUseProgram(program_handle) except GLException: # Print errors. status = GLint() glGetShaderiv(vertex_handle, GL_INFO_LOG_LENGTH, byref(status)) output = create_string_buffer(status.value) glGetShaderInfoLog(vertex_handle, status, None, output) print(output.value.decode('utf-8')) status = GLint() glGetShaderiv(fragment_handle, GL_INFO_LOG_LENGTH, byref(status)) output = create_string_buffer(status.value) glGetShaderInfoLog(fragment_handle, status, None, output) print(output.value.decode('utf-8')) status = GLint() glGetProgramiv(program_handle, GL_INFO_LOG_LENGTH, byref( status)) # Getting the number of char in info log to 'status' output = create_string_buffer(status.value) # status.value) glGetProgramInfoLog(program_handle, status, None, output) print(output.value.decode('utf-8')) # # Get uniform location. # uniform_mapping = {} # for uniform in uniforms: # name = create_string_buffer(uniform) # location = glGetUniformLocation(program_handle, cast(pointer(name), POINTER(GLchar))) # uniform_mapping[uniform] = location active_shaders = GLint() glGetProgramiv(program_handle, GL_ACTIVE_UNIFORMS, active_shaders) buffer_size = GLsizei(255) data_type = GLenum(0) string_buffer = create_string_buffer(buffer_size.value) name = c_char_p(addressof(string_buffer)) uniform_mapping = {} for index in range(active_shaders.value): glGetActiveUniform(program_handle, index, buffer_size, None, None, byref(data_type), name) if name.value in uniforms: location = glGetUniformLocation( program_handle, cast(pointer(name), POINTER(GLchar))) uniform = Uniform(name.value, location, data_type.value) uniform_mapping[name.value] = uniform super().__init__(program_handle) self.uniforms = uniform_mapping self.attributes = attribute_mapping
def __init__(self, shaders, attributes, uniforms): # Create vertex shader. vertex_shader = shaders[0] vertex_handle = glCreateShader(GL_VERTEX_SHADER) glShaderSource(vertex_handle, 1, c_string_array(vertex_shader), None) glCompileShader(vertex_handle) # Create fragment shader. fragment_shader = shaders[1] fragment_handle = glCreateShader(GL_FRAGMENT_SHADER) glShaderSource(fragment_handle, 1, c_string_array(fragment_shader), None) glCompileShader(fragment_handle) try: # Create program. program_handle = glCreateProgram() # Attach shaders glAttachShader(program_handle, vertex_handle) glAttachShader(program_handle, fragment_handle) # Bind attributes. for index, name in enumerate(attributes): glBindAttribLocation(program_handle, index, c_string(name)) # Link, validate and use. glLinkProgram(program_handle) glValidateProgram(program_handle) glUseProgram(program_handle) except GLException: # Print errors. status = GLint() glGetShaderiv(vertex_handle, GL_INFO_LOG_LENGTH, byref(status)) output = create_string_buffer(status.value) glGetShaderInfoLog(vertex_handle, status, None, output) print(output.value.decode('utf-8')) status = GLint() glGetShaderiv(fragment_handle, GL_INFO_LOG_LENGTH, byref(status)) output = create_string_buffer(status.value) glGetShaderInfoLog(fragment_handle, status, None, output) print(output.value.decode('utf-8')) status = GLint() glGetProgramiv(program_handle, GL_INFO_LOG_LENGTH, byref( status)) # Getting the number of char in info log to 'status' output = create_string_buffer(status.value) # status.value) glGetProgramInfoLog(program_handle, status, None, output) print(output.value.decode('utf-8')) # Query uniform data. active_uniforms = GLint() glGetProgramiv(program_handle, GL_ACTIVE_UNIFORMS, active_uniforms) buffer_size = GLsizei(255) data_type = GLenum(0) string_buffer = create_string_buffer(buffer_size.value) name = c_char_p(addressof(string_buffer)) uniform_mapping = {} for index in range(active_uniforms.value): glGetActiveUniform(program_handle, index, buffer_size, None, None, byref(data_type), name) if name.value in uniforms: location = glGetUniformLocation( program_handle, cast(pointer(name), POINTER(GLchar))) uniform = Uniform(name.value, location, data_type.value) uniform_mapping[name.value] = uniform self.id = GLuint(program_handle) self.uniforms = uniform_mapping self.attributes = attributes
def getSysInfo(win): try: from collections import OrderedDict except Exception: from psychopy.iohub import OrderedDict # based on sysInfo.py from pyglet.gl import gl_info, GLint, glGetIntegerv, GL_MAX_ELEMENTS_VERTICES import sys, platform sys_info = OrderedDict() sys_info['OS'] = OrderedDict() sys_info['OS']['Name'] = platform.platform() if sys.platform == 'darwin': OSXver, _, architecture = platform.mac_ver() sys_info['OS']['OSX Version'] = OSXver sys_info['OS']['OSX Architecture'] = architecture sys_info['Computer Hardware'] = OrderedDict() try: import psutil def getMemoryInfo(): rdict = dict() nt = psutil.virtual_memory() for name in nt._fields: value = getattr(nt, name) if name != 'percent': value = bytes2human(value) rdict[name.capitalize( )] = value # '%s%s%-10s : %7s\n'%(rstr, '\t' * indent, name.capitalize(), value) return rdict core_count = psutil.cpu_count(logical=False) logical_psu_count = psutil.cpu_count() memory_info = getMemoryInfo() sys_info['Computer Hardware']['CPUs (cores / logical)'] = ( core_count, logical_psu_count) sys_info['Computer Hardware']['System Memory'] = memory_info except Exception: sys_info['Computer Hardware']['Failed'] = 'psutil 2.x + is required.' sys_info['Python'] = OrderedDict() sys_info['Python']['exe'] = sys.executable sys_info['Python']['version'] = sys.version sys_info['Packages'] = OrderedDict() try: import numpy sys_info['Packages']['numpy'] = numpy.__version__ except ImportError: sys_info['Packages']['numpy'] = "Not Installed" try: import pyglet sys_info['Packages']['pyglet'] = pyglet.version except ImportError: sys_info['Packages']['pyglet'] = "Not Installed" try: import cv2 sys_info['Packages']['cv2'] = cv2.__version__ except ImportError: sys_info['Packages']['cv2'] = "Not Installed" try: import psychopy sys_info['Packages']['PsychoPy'] = psychopy.__version__ except ImportError: sys_info['Packages']['PsychoPy'] = "Not Installed" sys_info['Graphics'] = OrderedDict() sys_info['Graphics']['shaders'] = win._haveShaders sys_info['Graphics']['opengl'] = OrderedDict() sys_info['Graphics']['opengl']['version'] = gl_info.get_version() sys_info['Graphics']['opengl']['vendor'] = gl_info.get_vendor() sys_info['Graphics']['opengl']['engine'] = gl_info.get_renderer() maxVerts = GLint() glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, maxVerts) sys_info['Graphics']['opengl']['Max vert in VA'] = maxVerts.value sys_info['Graphics']['opengl']['extensions'] = OrderedDict() extensionsOfInterest = [ 'GL_ARB_multitexture', 'GL_EXT_framebuffer_object', 'GL_ARB_fragment_program', 'GL_ARB_shader_objects', 'GL_ARB_vertex_shader', 'GL_ARB_texture_non_power_of_two', 'GL_ARB_texture_float', 'GL_STEREO' ] for ext in extensionsOfInterest: sys_info['Graphics']['opengl']['extensions'][ext] = bool( gl_info.have_extension(ext)) sys_info['Processes'] = OrderedDict() if sys.platform == 'darwin': sys_info['Processes']['Failed'] = 'Not Supported on OSX.' elif SAVE_PER_PROCESS_DATA: try: import psutil for proc in psutil.process_iter(): pkey = proc.pid vattrs = [ 'name', 'exe', 'ppid', 'num_threads', 'memory_percent', 'cpu_percent', 'cpu_affinity', 'nice', 'num_ctx_switches' ] procinfo = proc.as_dict(attrs=vattrs, ad_value=u"Access Denied") if procinfo['exe'] is not u"Access Denied" and ( SAVE_PER_PROCESS_DATA is True or SAVE_PER_PROCESS_DATA == procinfo['name']): sys_info['Processes'][pkey] = procinfo except ImportError: sys_info['Processes']['Failed'] = 'psutil 2.x + is required.' else: sys_info['Processes'][ 'Disabled'] = 'Per Process details disabled by user.' return sys_info
def create(cls, vertex_source, fragment_source, attributes, uniforms): number_of_string = 1 # Create vertex shader. vertex_handle = glCreateShader(GL_VERTEX_SHADER) glShaderSource(vertex_handle, number_of_string, c_pointer_to_char_pointers(vertex_source), None) glCompileShader(vertex_handle) # Create fragment shader. fragment_handle = glCreateShader(GL_FRAGMENT_SHADER) glShaderSource(fragment_handle, number_of_string, c_pointer_to_char_pointers(fragment_source), None) glCompileShader(fragment_handle) # Create attributes. attribute_mapping = [] for attribute in attributes: attribute_mapping.append(c_string(attribute)) try: # Create program. program_handle = glCreateProgram() glAttachShader(program_handle, vertex_handle) glAttachShader(program_handle, fragment_handle) for index, name in enumerate(attribute_mapping): glBindAttribLocation(program_handle, index, name) glLinkProgram(program_handle) glValidateProgram(program_handle) glUseProgram(program_handle) except GLException as error: # Print vertex shader errors. status = GLint() glGetShaderiv(vertex_handle, GL_INFO_LOG_LENGTH, byref(status)) output = create_string_buffer(status.value) glGetShaderInfoLog(vertex_handle, status, None, output) print(output.value.decode('utf-8')) # Print fragment shader errors. status = GLint() glGetShaderiv(fragment_handle, GL_INFO_LOG_LENGTH, byref(status)) output = create_string_buffer(status.value) glGetShaderInfoLog(fragment_handle, status, None, output) print(output.value.decode('utf-8')) # Print program errors. status = GLint() glGetProgramiv(program_handle, GL_INFO_LOG_LENGTH, byref( status)) # Getting the number of char in info log to 'status' output = create_string_buffer(status.value) # status.value) glGetProgramInfoLog(program_handle, status, None, output) print(output.value.decode('utf-8')) raise error # Get uniform location. uniform_mapping = {} for uniform in uniforms: name = c_string(uniform) location = glGetUniformLocation( program_handle, cast(pointer(name), POINTER(c_char))) uniform_mapping[uniform] = location return cls(program_handle, uniform_mapping)