def initialise_glfw(): """Initialises the GLFW window and world UI""" if not glfw.init(): sys.exit(1) # glfw.window_hint(glfw.OPENGL_DEBUG_CONTEXT, 1) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) # This can be used to turn on multisampling AA for the default render target. # glfw.window_hint(glfw.SAMPLES, g_currentMsaaSamples) window = glfw.create_window(START_WIDTH, START_HEIGHT, "The Mega-racer world", None, None) if not window: glfw.terminate() sys.exit(1) glfw.make_context_current(window) print( "{}\nOpenGL\n Vendor: {}\n Renderer: {}\n Version: {}\n{}\n".format( ''.center(38, '-'), glGetString(GL_VENDOR).decode("utf8"), glGetString(GL_RENDERER).decode("utf8"), glGetString(GL_VERSION).decode("utf8"), ''.center(38, '-')), flush=True) # Enable some much-needed hardware functions that are off by default. glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) return window
def get_gl_info_string(glpane): # grantham 20051129 """Return a string containing some useful information about the OpenGL implementation. Use the GL context from the given QGLWidget glpane (by calling glpane.makeCurrent()). """ glpane.makeCurrent() #bruce 070308 added glpane arg and makeCurrent call gl_info_string = '' gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR) gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION) gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER) gl_info_string += 'GL_EXTENSIONS : "%s"\n' % glGetString(GL_EXTENSIONS) from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("get_gl_info_string call glAreTexturesResident?", Choice_boolean_False): # Give a practical indication of how much video memory is available. # Should also do this with VBOs. # I'm pretty sure this code is right, but PyOpenGL seg faults in # glAreTexturesResident, so it's disabled until I can figure that # out. [grantham] [bruce 070308 added the debug_pref] all_tex_in = True tex_bytes = '\0' * (512 * 512 * 4) tex_names = [] tex_count = 0 tex_names = glGenTextures(1024) glEnable(GL_TEXTURE_2D) while all_tex_in: glBindTexture(GL_TEXTURE_2D, tex_names[tex_count]) gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA, GL_UNSIGNED_BYTE, tex_bytes) tex_count += 1 glTexCoord2f(0.0, 0.0) glBegin(GL_QUADS) glVertex2f(0.0, 0.0) glVertex2f(1.0, 0.0) glVertex2f(1.0, 1.0) glVertex2f(0.0, 1.0) glEnd() glFinish() residences = glAreTexturesResident(tex_names[:tex_count]) all_tex_in = reduce(lambda a,b: a and b, residences) # bruce 070308 sees this exception from this line: # TypeError: reduce() arg 2 must support iteration glDisable(GL_TEXTURE_2D) glDeleteTextures(tex_names) gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \ % tex_count return gl_info_string
def get_gl_info_string(glpane): # grantham 20051129 """Return a string containing some useful information about the OpenGL implementation. Use the GL context from the given QGLWidget glpane (by calling glpane.makeCurrent()). """ glpane.makeCurrent() #bruce 070308 added glpane arg and makeCurrent call gl_info_string = '' gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR) gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION) gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER) gl_info_string += 'GL_EXTENSIONS : "%s"\n' % glGetString(GL_EXTENSIONS) from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("get_gl_info_string call glAreTexturesResident?", Choice_boolean_False): # Give a practical indication of how much video memory is available. # Should also do this with VBOs. # I'm pretty sure this code is right, but PyOpenGL seg faults in # glAreTexturesResident, so it's disabled until I can figure that # out. [grantham] [bruce 070308 added the debug_pref] all_tex_in = True tex_bytes = '\0' * (512 * 512 * 4) tex_names = [] tex_count = 0 tex_names = glGenTextures(1024) glEnable(GL_TEXTURE_2D) while all_tex_in: glBindTexture(GL_TEXTURE_2D, tex_names[tex_count]) gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA, GL_UNSIGNED_BYTE, tex_bytes) tex_count += 1 glTexCoord2f(0.0, 0.0) glBegin(GL_QUADS) glVertex2f(0.0, 0.0) glVertex2f(1.0, 0.0) glVertex2f(1.0, 1.0) glVertex2f(0.0, 1.0) glEnd() glFinish() residences = glAreTexturesResident(tex_names[:tex_count]) all_tex_in = reduce(lambda a, b: a and b, residences) # bruce 070308 sees this exception from this line: # TypeError: reduce() arg 2 must support iteration glDisable(GL_TEXTURE_2D) glDeleteTextures(tex_names) gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \ % tex_count return gl_info_string
def opengl_info(): """ Print out information relating to OpenGL, such as the version of OpenGL and the OpenGL Shading Language being used, the vendor and renderer """ print "OpenGL version:\t\t%s" % glGetString(GL_VERSION) print "GLSL version:\t\t%s" % glGetString(GL_SHADING_LANGUAGE_VERSION) print "Vendor:\t\t\t%s" % glGetString(GL_VENDOR) print "Renderer:\t\t%s" % glGetString(GL_RENDERER)
def main(): import pygtk pygtk.require('2.0') import gtk.gdkgl, gtk.gtkgl #@UnresolvedImport assert gtk.gdkgl is not None and gtk.gtkgl is not None print("loading OpenGL.GL") from OpenGL.GL import GL_VERSION, glGetString from OpenGL.GL.ARB.fragment_program import glInitFragmentProgramARB glconfig = gtk.gdkgl.Config(mode=gtk.gdkgl.MODE_RGB | gtk.gdkgl.MODE_DOUBLE | gtk.gdkgl.MODE_DEPTH) print("glconfig=%s" % glconfig) win = gtk.Window() win.set_title('test GL') glarea = gtk.gtkgl.DrawingArea(glconfig=glconfig, share_list=None, render_type=gtk.gdkgl.RGBA_TYPE) win.add(glarea) glarea.realize() glcontext = glarea.get_gl_context() print("glcontext=%s" % glcontext) pixmap = gtk.gdk.Pixmap(None, 120, 120, 24) print("pixmap=%s" % pixmap) glext = gtk.gdkgl.ext(pixmap) print("glext=%s" % glext) gldrawable = gtk.gdkgl.Pixmap(glconfig, pixmap) print("gldrawable=%s" % gldrawable) if gldrawable is None: raise ImportError("failed to initialize") glcontext = gtk.gdkgl.Context(gldrawable, direct=True) if not gldrawable.gl_begin(glcontext): raise ImportError("gl_begin failed on %s" % gldrawable) try: gl_major = int(glGetString(GL_VERSION)[0]) gl_minor = int(glGetString(GL_VERSION)[2]) if gl_major <= 1 and gl_minor < 1: raise ImportError( "** OpenGL output requires OpenGL version 1.1 or greater, not %s.%s" % (gl_major, gl_minor)) print("found valid OpenGL: %s.%s" % (gl_major, gl_minor)) #this allows us to do CSC via OpenGL: #see http://www.opengl.org/registry/specs/ARB/fragment_program.txt if not glInitFragmentProgramARB(): raise ImportError( "** OpenGL output requires glInitFragmentProgramARB") finally: gldrawable.gl_end() del glcontext, gldrawable, glext, glconfig
def get_info(): from OpenGL.GL import (glGetString, glGetIntegerv, GL_VENDOR, GL_VERSION, GL_SHADING_LANGUAGE_VERSION, GL_RENDERER, GL_MAJOR_VERSION, GL_MINOR_VERSION) return { 'major': glGetIntegerv(GL_MAJOR_VERSION), 'minor': glGetIntegerv(GL_MINOR_VERSION), 'vendor': glGetString(GL_VENDOR), 'version': glGetString(GL_VERSION), 'shader_language_version': glGetString(GL_SHADING_LANGUAGE_VERSION), 'renderer': glGetString(GL_RENDERER), }
def main(): import pygtk pygtk.require("2.0") import gtk.gdkgl, gtk.gtkgl # @UnresolvedImport assert gtk.gdkgl is not None and gtk.gtkgl is not None print("loading OpenGL.GL") from OpenGL.GL import GL_VERSION, glGetString from OpenGL.GL.ARB.fragment_program import glInitFragmentProgramARB glconfig = gtk.gdkgl.Config(mode=gtk.gdkgl.MODE_RGB | gtk.gdkgl.MODE_DOUBLE | gtk.gdkgl.MODE_DEPTH) print("glconfig=%s" % glconfig) win = gtk.Window() win.set_title("test GL") glarea = gtk.gtkgl.DrawingArea(glconfig=glconfig, share_list=None, render_type=gtk.gdkgl.RGBA_TYPE) win.add(glarea) glarea.realize() glcontext = glarea.get_gl_context() print("glcontext=%s" % glcontext) pixmap = gtk.gdk.Pixmap(None, 120, 120, 24) print("pixmap=%s" % pixmap) glext = gtk.gdkgl.ext(pixmap) print("glext=%s" % glext) gldrawable = gtk.gdkgl.Pixmap(glconfig, pixmap) print("gldrawable=%s" % gldrawable) if gldrawable is None: raise ImportError("failed to initialize") glcontext = gtk.gdkgl.Context(gldrawable, direct=True) if not gldrawable.gl_begin(glcontext): raise ImportError("gl_begin failed on %s" % gldrawable) try: gl_major = int(glGetString(GL_VERSION)[0]) gl_minor = int(glGetString(GL_VERSION)[2]) if gl_major <= 1 and gl_minor < 1: raise ImportError( "** OpenGL output requires OpenGL version 1.1 or greater, not %s.%s" % (gl_major, gl_minor) ) print("found valid OpenGL: %s.%s" % (gl_major, gl_minor)) # this allows us to do CSC via OpenGL: # see http://www.opengl.org/registry/specs/ARB/fragment_program.txt if not glInitFragmentProgramARB(): raise ImportError("** OpenGL output requires glInitFragmentProgramARB") finally: gldrawable.gl_end() del glcontext, gldrawable, glext, glconfig
def main(): _width = 256 _height = 256 # Whether hidpi is active #def on_error(error, message): # log.warning(message) #glfw.glfwSetErrorCallback(on_error) egl_display = egl.eglGetDisplay(egl.EGL_DEFAULT_DISPLAY) major, minor = egl.EGLint(), egl.EGLint() egl.eglInitialize(egl_display, pointer(major), pointer(minor)) config_attribs = [ egl.EGL_SURFACE_TYPE, egl.EGL_PBUFFER_BIT, egl.EGL_BLUE_SIZE, 8, egl.EGL_GREEN_SIZE, 8, egl.EGL_RED_SIZE, 8, egl.EGL_DEPTH_SIZE, 24, egl.EGL_RENDERABLE_TYPE, egl.EGL_OPENGL_BIT, egl.EGL_NONE ] config_attribs = (egl.EGLint * len(config_attribs))(*config_attribs) num_configs = egl.EGLint() egl_cfg = egl.EGLConfig() egl.eglChooseConfig(egl_display, config_attribs, pointer(egl_cfg), 1, pointer(num_configs)) pbuffer_attribs = [ egl.EGL_WIDTH, _width, egl.EGL_HEIGHT, _height, egl.EGL_NONE, ] pbuffer_attribs = (egl.EGLint * len(pbuffer_attribs))(*pbuffer_attribs) egl_surf = egl.eglCreatePbufferSurface(egl_display, egl_cfg, pbuffer_attribs) egl.eglBindAPI(egl.EGL_OPENGL_API) egl_context = egl.eglCreateContext(egl_display, egl_cfg, egl.EGL_NO_CONTEXT, None) egl.eglMakeCurrent(egl_display, egl_surf, egl_surf, egl_context) #print("context made current") print('Vendor: {}'.format(glGetString(GL_VENDOR).decode('utf-8'))) print('Opengl version: {}'.format(glGetString(GL_VERSION).decode('utf-8'))) print('GLSL Version: {}'.format( glGetString(GL_SHADING_LANGUAGE_VERSION).decode('utf-8'))) print('Renderer: {}'.format(glGetString(GL_RENDERER).decode('utf-8')))
def _init_glfw(self, width, height): if not glfwInit(): raise RuntimeError('glfwInit failed') glfwSetErrorCallback(self._cb_glfw_error) glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3) glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3) # TODO self._window = glfwCreateWindow(width, height, 'bel') if self._window is None: raise RuntimeError('glfwCreateWindow failed') glfwSetCursorPosCallback(self._window, self._cb_cursor_pos) glfwSetKeyCallback(self._window, self._cb_key) glfwSetMouseButtonCallback(self._window, self._cb_mouse_button) glfwMakeContextCurrent(self._window) LOG.info('GL_VERSION: %s', glGetString(GL_VERSION).decode()) # TODO self._draw_state.fb_size = glfwGetFramebufferSize(self._window) self._add_default_materials()
def initializeGL(self): ''' Initialize GL ''' self.fieldtemp = [ 1.0, "GL_NEAREST", "GL_NEAREST", "GL_NEAREST_MIPMAP_NEAREST", "On" ] try: js = jsonload(path.join(SAVE_DIR, "gfx_settings.rgs")) self.fieldtemp[0] = loadFloat('gfx.anifilt', js.get('anifilt')) self.fieldtemp[1] = loadString('gfx.minfilter', js.get('minfilter')) self.fieldtemp[2] = loadString('gfx.magfilter', js.get('magfilter')) self.fieldtemp[3] = loadString('gfx.mipminfilter', js.get('mipminfilter')) self.fieldtemp[4] = loadString('gfx.FSAA', js.get('FSAA')) except: #print("no settings detected") pass #mipmap support and NPOT texture support block if not hasGLExtension("GL_ARB_framebuffer_object"): #print("GL_ARB_framebuffer_object not supported, switching to GL_GENERATE_MIPMAP") self.npot = 2 version = glGetString(GL_VERSION) if int(version[0]) == 1 and int( version[2]) < 4: #no opengl 1.4 support #print("GL_GENERATE_MIPMAP not supported, not using mipmapping") self.npot = 1 if not hasGLExtension("GL_ARB_texture_rectangle"): #print("GL_TEXTURE_RECTANGLE_ARB not supported, switching to GL_TEXTURE_2D") self.texext = GL_TEXTURE_2D self.npot = 0 #assorted settings block if hasGLExtension("GL_EXT_texture_filter_anisotropic" ) and self.fieldtemp[0] > 1.0: self.anifilt = self.fieldtemp[0] #print("using " + str(self.fieldtemp[0]) + "x anisotropic texture filtering. max: " + str(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT))) self.minfilter = self.interpretString(self.fieldtemp[1]) self.magfilter = self.interpretString(self.fieldtemp[2]) self.mipminfilter = self.interpretString(self.fieldtemp[3]) if self.mipminfilter == "Off": self.mipminfilter = -1 if self.format().sampleBuffers() and self.fieldtemp[4] == "On": #print("enabling " + str(self.format().samples()) + "x FSAA") glEnable(GL_MULTISAMPLE) else: pass #print("FSAA not supported and/or disabled") glEnable(self.texext) glEnable(GL_BLEND) glDisable(GL_DEPTH_TEST) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glViewport(0, 0, self.width(), self.height()) glClearColor(0.0, 0.0, 0.0, 0.0)
def __init__(self, width=800, height=600, x=112, y=84): self.init_opengl(width=width, height=height, x=x, y=y) print("OpenGL Version: {0}".format(glGetString(GL_VERSION))) self.clock = Clock(speed=100) self.timer = Clock(snooze_interval=1/30) self.frame_index = 0 self.event_index = 0 self.is_recording = False VERTEX_SHADER = compileShader(""" void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; }""", GL_VERTEX_SHADER) FRAGMENT_SHADER = compileShader(""" void main() { gl_FragColor = vec4(0.8, 0.8, 0.8, 1); }""", GL_FRAGMENT_SHADER) self.shader = compileProgram(VERTEX_SHADER, FRAGMENT_SHADER) self.coordsys = vbo.VBO( np.array([ [-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1] ], 'f') ) self.blob = None self.objects = [] self.shaded_objects = [] self.mouse_x = None self.mouse_y = None self.show_help = False self._help_string = None self.show_info = False self.spectrum = None self.detector = Detector('/Users/tamasgal/Data/KM3NeT/Detector/km3net_jul13_90m.detx') self.dom_positions = np.array([tuple(pos) for pos in self.detector.dom_positions], 'f') self.min_z = min([z for x, y, z in self.dom_positions]) self.max_z = max([z for x, y, z in self.dom_positions]) camera.target = Position((0, 0, (self.max_z - self.min_z) / 2)) self.dom_positions_vbo = vbo.VBO(self.dom_positions) self.pump = EvtPump(filename='/Users/tamasgal/Data/KM3NeT/Luigi/nueCC.evt') self.load_blob(0) self.clock.reset() self.timer.reset() glutMainLoop()
def debug_info(setup): from OpenGL.GL import ( glClearColor, glClear, GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, glGetString, GL_VENDOR, GL_EXTENSIONS, glFinish, ) display, ctx, surface = setup glClearColor(1.0, 1.0, 1.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) log.info("Vendor: %s", glGetString(GL_VENDOR)) log.info("Extensions: %s", glGetString(GL_EXTENSIONS)) glFinish()
def getstr(k): try: return glGetString(k) except Exception as e: # pragma: no cover self.props["safe"] = False result = getattr(e, "result", None) if result and isinstance(result, str): return result raise
def main(): if not glfw.init(): return -1 glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(960, 540, "Window", None, None) if not window: glfw.terminate() return -1 glfw.make_context_current(window) glfw.swap_interval(1) version = glGetString(GL_VERSION).decode('utf-8') print(version) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) renderer = Renderer.Renderer() gui = Gui.Gui(window) testMenu = Test.TestMenu() testMenu.RegisterTest("Clear Color", TestClearColor.TestClearColor) testMenu.RegisterTest("Texture2D", TestTexture2D.TestTexture2D) currentTest = testMenu while not glfw.window_should_close(window): glClearColor(0.0, 0.0, 0.0, 1.0) renderer.Clear() gui.NewFrame() if currentTest: currentTest.OnUpdate() currentTest.OnRender() Gui.begin("Tests") if not currentTest == testMenu and Gui.button("<-"): currentTest = testMenu testMenu.m_CurrentTest = None currentTest.OnImGuiRender() if testMenu.m_CurrentTest and not (currentTest == testMenu.m_CurrentTest): currentTest = testMenu.m_CurrentTest Gui.end() Gui.framerate() gui.EndFrame() glfw.swap_buffers(window) glfw.poll_events() del currentTest del testMenu gui.endGui() glfw.terminate() return 0
def update_texture_yuv(self, img_data, x, y, width, height, rowstrides, pixel_format): assert x==0 and y==0 assert self.textures is not None, "no OpenGL textures!" if self.pixel_format is None or self.pixel_format!=pixel_format or self.texture_size!=(width, height): self.pixel_format = pixel_format self.texture_size = (width, height) divs = get_subsampling_divs(pixel_format) debug("GL creating new YUV textures for pixel format %s using divs=%s", pixel_format, divs) self.gl_marker("Creating new YUV textures") # Create textures of the same size as the window's glEnable(GL_TEXTURE_RECTANGLE_ARB) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): (div_w, div_h) = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glEnable(GL_TEXTURE_RECTANGLE_ARB) mag_filter = GL_NEAREST if div_w > 1 or div_h > 1: mag_filter = GL_LINEAR glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, mag_filter) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width/div_w, height/div_h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0) debug("Assigning fragment program") glEnable(GL_FRAGMENT_PROGRAM_ARB) if not self.yuv_shader: self.yuv_shader = [ 1 ] glGenProgramsARB(1, self.yuv_shader) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv_shader[0]) prog = GL_COLORSPACE_CONVERSIONS glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(prog), prog) err = glGetString(GL_PROGRAM_ERROR_STRING_ARB) if err: #FIXME: maybe we should do something else here? log.error(err) self.gl_marker("Updating YUV textures") divs = get_subsampling_divs(pixel_format) U_width = 0 U_height = 0 for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): (div_w, div_h) = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[index]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width/div_w, height/div_h, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[index]) if index == 1: U_width = width/div_w U_height = height/div_h elif index == 2: if width/div_w != U_width: log.error("Width of V plane is %d, differs from width of corresponding U plane (%d), pixel_format is %d", width/div_w, U_width, pixel_format) if height/div_h != U_height: log.error("Height of V plane is %d, differs from height of corresponding U plane (%d)", height/div_h, U_height)
def gl_init_shaders(self): assert self.shaders is None # Create and assign fragment programs self.shaders = [1, 2] glGenProgramsARB(2, self.shaders) for progid, progstr in ((YUV2RGB_SHADER, YUV2RGB_shader), (RGBP2RGB_SHADER, RGBP2RGB_shader)): glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[progid]) glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(progstr), progstr) err = glGetString(GL_PROGRAM_ERROR_STRING_ARB) if err: # FIXME: maybe we should do something else here? log.error(err)
def init_gl(self): version = glGetString(GL_VERSION) pymt_logger.info('Window: OpenGL version <%s>' % str(version)) line_smooth = pymt.pymt_config.getint('graphics', 'line_smooth') if line_smooth: if line_smooth == 1: hint = GL_FASTEST else: hint = GL_NICEST glHint(GL_LINE_SMOOTH_HINT, hint) glEnable(GL_LINE_SMOOTH)
def init_gl(self): version = glGetString(GL_VERSION) pymt_logger.info("Window: OpenGL version <%s>" % str(version)) line_smooth = pymt.pymt_config.getint("graphics", "line_smooth") if line_smooth: if line_smooth == 1: hint = GL_FASTEST else: hint = GL_NICEST glHint(GL_LINE_SMOOTH_HINT, hint) glEnable(GL_LINE_SMOOTH)
def gl_init_shaders(self): assert self.shaders is None # Create and assign fragment programs self.shaders = [ 1, 2 ] glGenProgramsARB(2, self.shaders) for progid, progstr in ((YUV2RGB_SHADER, YUV2RGB_shader), (RGBP2RGB_SHADER, RGBP2RGB_shader)): glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[progid]) glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(progstr), progstr) err = glGetString(GL_PROGRAM_ERROR_STRING_ARB) if err: #FIXME: maybe we should do something else here? log.error(err)
def main(): # Parse command line arguments parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", action="store_true", default=False) args = parser.parse_args() if args.verbose: level = logging.DEBUG if args.verbose else logging.ERROR logging.getLogger("voxel").setLevel(level) # Initialize the window glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(800, 600) glutInitWindowPosition(0, 0) glutCreateWindow("--VOXEL--") glutIgnoreKeyRepeat(1) # Create application and bind functions to GLUT a = VoxelApp() glutDisplayFunc(a.display) glutIdleFunc(a.idle) glutReshapeFunc(a.resize) glutKeyboardFunc(a.keyboard) glutKeyboardUpFunc(a.keyboard_up) glutMouseFunc(a.mouse_press) glutMotionFunc(a.mouse_move) # Log diagnostic information log.debug("GL_RENDERER = %s" % (glGetString(GL_RENDERER), )) log.debug("GL_VERSION = %s" % (glGetString(GL_VERSION), )) log.debug("GL_VENDOR = %s" % (glGetString(GL_VENDOR), )) log.debug("GL_EXTENSIONS = ") for ext in sorted(glGetString(GL_EXTENSIONS).split()): log.debug(" %s" % (ext, )) glutMainLoop()
def main(): # Parse command line arguments parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='store_true', default=False) args = parser.parse_args() if args.verbose: level = logging.DEBUG if args.verbose else logging.ERROR logging.getLogger('voxel').setLevel(level) # Initialize the window glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(800, 600) glutInitWindowPosition(0, 0) glutCreateWindow("--VOXEL--") glutIgnoreKeyRepeat(1) # Create application and bind functions to GLUT a = VoxelApp() glutDisplayFunc(a.display) glutIdleFunc(a.idle) glutReshapeFunc(a.resize) glutKeyboardFunc(a.keyboard) glutKeyboardUpFunc(a.keyboard_up) glutMouseFunc(a.mouse_press) glutMotionFunc(a.mouse_move) # Log diagnostic information log.debug("GL_RENDERER = %s" % (glGetString(GL_RENDERER),)) log.debug("GL_VERSION = %s" % (glGetString(GL_VERSION),)) log.debug("GL_VENDOR = %s" % (glGetString(GL_VENDOR),)) log.debug("GL_EXTENSIONS = ") for ext in sorted(glGetString(GL_EXTENSIONS).split()): log.debug(" %s" % (ext,)) glutMainLoop()
def update_texture_yuv(self, img_data, x, y, width, height, rowstrides, pixel_format): window_width, window_height = self.size assert self.textures is not None, "no OpenGL textures!" if self.pixel_format is None or self.pixel_format!=pixel_format: self.pixel_format = pixel_format divs = self.get_subsampling_divs(pixel_format) log("GL creating new YUV textures for pixel format %s using divs=%s", pixel_format, divs) # Create textures of the same size as the window's glEnable(GL_TEXTURE_RECTANGLE_ARB) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): div = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glEnable(GL_TEXTURE_RECTANGLE_ARB) mag_filter = GL_NEAREST if div>1: mag_filter = GL_LINEAR glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, mag_filter) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, window_width/div, window_height/div, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0) log("Assigning fragment program") glEnable(GL_FRAGMENT_PROGRAM_ARB) if not self.yuv_shader: self.yuv_shader = [ 1 ] glGenProgramsARB(1, self.yuv_shader) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv_shader[0]) prog = GL_COLORSPACE_CONVERSIONS glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(prog), prog) err = glGetString(GL_PROGRAM_ERROR_STRING_ARB) if err: #FIXME: maybe we should do something else here? log.error(err) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv_shader[0]) # Clamp width and height to the actual texture size if x + width > window_width: width = window_width - x if y + height > window_height: height = window_height - y divs = self.get_subsampling_divs(pixel_format) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): div = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[index]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width/div, height/div, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[index]) glFlush()
def hasGLExtension( specifier ): """Given a string specifier, check for extension being available""" global AVAILABLE_GL_EXTENSIONS specifier = as_8_bit(specifier).replace(as_8_bit('.'),as_8_bit('_')) if specifier.startswith( VERSION_PREFIX ): specifier = [ int(x) for x in specifier[ len(VERSION_PREFIX):].split(as_8_bit('_')) ] version = getGLVersion() if not version: return version return specifier <= version else: from OpenGL.GL import glGetString, GL_EXTENSIONS from OpenGL import error if not AVAILABLE_GL_EXTENSIONS: try: AVAILABLE_GL_EXTENSIONS[:] = glGetString( GL_EXTENSIONS ).split() except (AttributeError, error.GLError) as err: # OpenGL 3.0 deprecates glGetString( GL_EXTENSIONS ) from OpenGL.GL.VERSION.GL_3_0 import GL_NUM_EXTENSIONS, glGetStringi from OpenGL.GL import glGetIntegerv count = glGetIntegerv( GL_NUM_EXTENSIONS ) for i in range( count ): extension = glGetStringi( GL_EXTENSIONS, i ) AVAILABLE_GL_EXTENSIONS.append( extension ) # Add included-by-reference extensions... version = getGLVersion() if not version: # should not be possible? return version check = tuple( version[:2] ) for (v,v_exts) in VERSION_EXTENSIONS: if v <= check: for v_ext in v_exts: if v_ext not in AVAILABLE_GL_EXTENSIONS: AVAILABLE_GL_EXTENSIONS.append( v_ext ) else: break result = specifier in AVAILABLE_GL_EXTENSIONS log.info( 'GL Extension %s %s', specifier, ['unavailable','available'][bool(result)] ) return result
def hasGLExtension( specifier ): """Given a string specifier, check for extension being available""" global AVAILABLE_GL_EXTENSIONS, CURRENT_GL_VERSION specifier = specifier.replace('.','_') if specifier.startswith( VERSION_PREFIX ): from OpenGL.GL import glGetString, GL_VERSION if not CURRENT_GL_VERSION: new = glGetString( GL_VERSION ) if new: CURRENT_GL_VERSION = [ int(x) for x in new.split(' ',1)[0].split( '.' ) ] else: return False # not yet loaded/supported specifier = [ int(x) for x in specifier[ len(VERSION_PREFIX):].split('_') ] return specifier <= CURRENT_GL_VERSION else: from OpenGL.GL import glGetString, GL_EXTENSIONS if not AVAILABLE_GL_EXTENSIONS: AVAILABLE_GL_EXTENSIONS[:] = glGetString( GL_EXTENSIONS ).split() return specifier in AVAILABLE_GL_EXTENSIONS
def gl_init_shaders(self): assert self.shaders is None # Create and assign fragment programs self.shaders = [ 1, 2 ] glGenProgramsARB(2, self.shaders) for name, progid, progstr in (("YUV2RGB", YUV2RGB_SHADER, YUV2RGB_shader), ("RGBP2RGB", RGBP2RGB_SHADER, RGBP2RGB_shader)): glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[progid]) glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(progstr), progstr) err = glGetString(GL_PROGRAM_ERROR_STRING_ARB) if err: log.error("OpenGL shader %s failed:", name) log.error(" %s", err) raise Exception("OpenGL shader %s setup failure: %s" % (name, err)) else: log("%s shader initialized", name)
def getGLVersion(): """Retrieve 2-int declaration of major/minor GL version returns [int(major),int(minor)] or False if not loaded """ global CURRENT_GL_VERSION if not CURRENT_GL_VERSION: from OpenGL.GL import glGetString, GL_VERSION new = glGetString(GL_VERSION) log.info("OpenGL Version: %s", new) if new: CURRENT_GL_VERSION = [int(x) for x in new.split(" ", 1)[0].split(".")] else: return False # not yet loaded/supported return CURRENT_GL_VERSION
def getGLVersion(): """Retrieve 2-int declaration of major/minor GL version returns [int(major),int(minor)] or False if not loaded """ global CURRENT_GL_VERSION if not CURRENT_GL_VERSION: from OpenGL.GL import glGetString, GL_VERSION new = glGetString(GL_VERSION) log.info('OpenGL Version: %s', new) if new: CURRENT_GL_VERSION = [ int(x) for x in new.split(' ', 1)[0].split('.') ] else: return False # not yet loaded/supported return CURRENT_GL_VERSION
def hasGLExtension(specifier): """Given a string specifier, check for extension being available""" global AVAILABLE_GL_EXTENSIONS specifier = specifier.replace(".", "_") if specifier.startswith(VERSION_PREFIX): specifier = [int(x) for x in specifier[len(VERSION_PREFIX) :].split("_")] version = getGLVersion() if not version: return version return specifier <= version else: from OpenGL.GL import glGetString, GL_EXTENSIONS if not AVAILABLE_GL_EXTENSIONS: AVAILABLE_GL_EXTENSIONS[:] = glGetString(GL_EXTENSIONS).split() result = specifier in AVAILABLE_GL_EXTENSIONS log.info("GL Extension %s %s", specifier, ["unavailable", "available"][bool(result)]) return result
def _try_shader_init(self): """ This runs at most once, when this kind of shader is first needed. It should try to set up this kind of shader in this GL resource context, and if this works, set self.shader to the shader. When anything goes wrong it should simply print an error and return without setting self.shader (or setting both that and self.shader.error). It's ok for this to raise an exception, though when practical it's preferable to print an error and exit normally (so the error message can be more specific and understandable). (If we ever have more than one GL resource context, we'll want to factor it into the part that doesn't depend on context (to avoid redundant error messages) and the part that does.) """ if glGetString(GL_EXTENSIONS).find("GL_ARB_shader_objects") >= 0: print "note: this session WILL try to use %s-shaders" % self.primtype pass else: # REVIEW: # Could we support shaders with the older GL_ARB_vertex_program and # GL_ARB_fragment_program with some work? Get assembly-like vertex # and fragment programs from the GLSL source using an option of the # nVidia Cg compiler. Needs some loading API changes too... # [Russ comment, late 2008] print "note: this session WOULD try to use %s-shaders,\n" % self.primtype, \ "but GL_EXTENSION GL_ARB_shader_objects is not supported.\n" return shader_class = self.get_shader_class() self.shader = shader_class() if not self.shader.error: # see also shader_available # Note: self.shader.error is possible at this stage; see above. print "%s shader initialization is complete." % self.primtype primitiveBuffer_class = self.get_primitiveBuffer_class() self.primitiveBuffer = primitiveBuffer_class( self) print "%s primitive buffer initialization is complete." % self.primtype print return
def _try_shader_init(self): """ This runs at most once, when this kind of shader is first needed. It should try to set up this kind of shader in this GL resource context, and if this works, set self.shader to the shader. When anything goes wrong it should simply print an error and return without setting self.shader (or setting both that and self.shader.error). It's ok for this to raise an exception, though when practical it's preferable to print an error and exit normally (so the error message can be more specific and understandable). (If we ever have more than one GL resource context, we'll want to factor it into the part that doesn't depend on context (to avoid redundant error messages) and the part that does.) """ if glGetString(GL_EXTENSIONS).find("GL_ARB_shader_objects") >= 0: print "note: this session WILL try to use %s-shaders" % self.primtype pass else: # REVIEW: # Could we support shaders with the older GL_ARB_vertex_program and # GL_ARB_fragment_program with some work? Get assembly-like vertex # and fragment programs from the GLSL source using an option of the # nVidia Cg compiler. Needs some loading API changes too... # [Russ comment, late 2008] print "note: this session WOULD try to use %s-shaders,\n" % self.primtype, \ "but GL_EXTENSION GL_ARB_shader_objects is not supported.\n" return shader_class = self.get_shader_class() self.shader = shader_class() if not self.shader.error: # see also shader_available # Note: self.shader.error is possible at this stage; see above. print "%s shader initialization is complete." % self.primtype primitiveBuffer_class = self.get_primitiveBuffer_class() self.primitiveBuffer = primitiveBuffer_class(self) print "%s primitive buffer initialization is complete." % self.primtype print return
def initWindow(self): self.window = MainWindow(self) self.window.setWindowTitle('CS791a') glFormat = QGLFormat() glFormat.setDoubleBuffer(True) glFormat.setDirectRendering(True) glFormat.setProfile(QGLFormat.CoreProfile) glFormat.setVersion(3,3) QGLFormat.setDefaultFormat(glFormat) #glFormat.setOption(QGLFormat.OpenGL_Version_3_3) self.graphics = GraphicsManager(self) self.graphics.makeCurrent() self.window.setCentralWidget(self.graphics) self.window.resize(1600,900) print(glGetString(GL_VERSION))
def hasGLExtension(specifier): """Given a string specifier, check for extension being available""" global AVAILABLE_GL_EXTENSIONS specifier = specifier.replace('.', '_') if specifier.startswith(VERSION_PREFIX): specifier = [ int(x) for x in specifier[len(VERSION_PREFIX):].split('_') ] version = getGLVersion() if not version: return version return specifier <= version else: from OpenGL.GL import glGetString, GL_EXTENSIONS if not AVAILABLE_GL_EXTENSIONS: AVAILABLE_GL_EXTENSIONS[:] = glGetString(GL_EXTENSIONS).split() result = specifier in AVAILABLE_GL_EXTENSIONS log.info('GL Extension %s %s', specifier, ['unavailable', 'available'][bool(result)]) return result
def get_shader(context_identifier: str, shader_name: str) -> OpenGL.GL.shaders.ShaderProgram: shader_key = (context_identifier, shader_name) if shader_key not in _shaders: gl_version_match = GL_VERSION_MATCH.match( glGetString(GL_SHADING_LANGUAGE_VERSION).decode("utf-8")) if gl_version_match: gl_version_tuple = tuple(int(v) for v in gl_version_match.groups()) if gl_version_tuple >= (3, 30): gl_version = "330" # opengl 3.3 else: gl_version = "120" # opengl 2.1 else: # in theory this shouldn't happen if the version is correctly formatted. gl_version = "330" def compile_shader(): return OpenGL.GL.shaders.compileProgram( _load_shader( os.path.join(shader_dir, f"{shader_name}_{gl_version}.vert"), GL_VERTEX_SHADER, ), _load_shader( os.path.join(shader_dir, f"{shader_name}_{gl_version}.frag"), GL_FRAGMENT_SHADER, ), ) try: shader = compile_shader() except OpenGL.GL.shaders.ShaderValidationError: # on Mac the above fails if there is no VBO bound glBindVertexArray(glGenVertexArrays(1)) shader = compile_shader() glBindVertexArray(0) _shaders[shader_key] = shader return _shaders[shader_key]
def get_gl_info_string(glpane): # grantham 20051129 """ Return a string containing some useful information about the OpenGL implementation. Use the GL context from the given QGLWidget glpane (by calling glpane.makeCurrent()). """ glpane.makeCurrent() #bruce 070308 added glpane arg and makeCurrent call gl_info_string = '' gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR) gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION) gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER) gl_extensions = glGetString(GL_EXTENSIONS) gl_extensions = gl_extensions.strip() gl_extensions = gl_extensions.replace(" ", "\n* ") gl_info_string += 'GL_EXTENSIONS : \n* %s\n' % gl_extensions if debug_pref("Graphics Card Info: call glAreTexturesResident?", Choice_boolean_False): # Give a practical indication of how much video memory is available. # Should also do this with VBOs. # I'm pretty sure this code is right, but PyOpenGL seg faults in # glAreTexturesResident, so it's disabled until I can figure that # out. [grantham] [bruce 070308 added the debug_pref] all_tex_in = True tex_bytes = '\0' * (512 * 512 * 4) tex_names = [] tex_count = 0 tex_names = glGenTextures(1024) glEnable(GL_TEXTURE_2D) while all_tex_in: glBindTexture(GL_TEXTURE_2D, tex_names[tex_count]) gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA, GL_UNSIGNED_BYTE, tex_bytes) tex_count += 1 glTexCoord2f(0.0, 0.0) glBegin(GL_QUADS) glVertex2f(0.0, 0.0) glVertex2f(1.0, 0.0) glVertex2f(1.0, 1.0) glVertex2f(0.0, 1.0) glEnd() glFinish() residences = glAreTexturesResident(tex_names[:tex_count]) all_tex_in = reduce(lambda a,b: a and b, residences) # bruce 070308 sees this exception from this line: # TypeError: reduce() arg 2 must support iteration glDisable(GL_TEXTURE_2D) glDeleteTextures(tex_names) gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \ % tex_count pass if True: ## or could be a debug_pref("Graphics Card Info: get all GL_MAX symbols?") #bruce 090314 new feature import OpenGL.GL symbols = [x for x in dir(OpenGL.GL) if x.startswith('GL_MAX_')] symbols.sort() gl_info_string += '\n' for symbol in symbols: try: numeric_symbol = getattr(OpenGL.GL, symbol) intval = glGetInteger(numeric_symbol) except: # this happens to most symbols, not sure why if debug_flags.atom_debug: print_compact_traceback( "%s = ??: " % symbol ) # overkill, only the exception itself matters # typical output (on Bruce's MacBookPro, 090314): ## GL_MAX_4D_TEXTURE_SIZE_SGIS = ??: ## <type 'exceptions.KeyError'>: ## ('Unknown specifier GL_MAX_4D_TEXTURE_SIZE_SGIS (33080)', ## 'Failure in cConverter <OpenGL.converters.SizedOutput object at 0x1457fab0>', ## [GL_MAX_4D_TEXTURE_SIZE_SGIS], 1, <OpenGL.wrapper.glGetIntegerv object at 0x1458aa30>) ## [graphics_card_info.py:122] [wrapper.py:676] [converters.py:195] [converters.py:234] pass pass ## gl_info_string += "%s = ??\n" % symbol else: gl_info_string += "%s = %r\n" % (symbol, intval) continue pass return gl_info_string
def run(): #Start OpenGL and ask it for an OpenGL context pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode(SCREEN_SIZE, pygame.HWSURFACE|pygame.OPENGL|pygame.DOUBLEBUF) #The first thing we do is print some OpenGL details and check that we have a good enough version print("OpenGL Implementation Details:") if glGetString(GL_VENDOR): print("\tGL_VENDOR: {}".format(glGetString(GL_VENDOR).decode())) if glGetString(GL_RENDERER): print("\tGL_RENDERER: {}".format(glGetString(GL_RENDERER).decode())) if glGetString(GL_VERSION): print("\tGL_VERSION: {}".format(glGetString(GL_VERSION).decode())) if glGetString(GL_SHADING_LANGUAGE_VERSION): print("\tGL_SHADING_LANGUAGE_VERSION: {}".format(glGetString(GL_SHADING_LANGUAGE_VERSION).decode())) major_version = int(glGetString(GL_VERSION).decode().split()[0].split('.')[0]) minor_version = int(glGetString(GL_VERSION).decode().split()[0].split('.')[1]) if major_version < 3 or (major_version < 3 and minor_version < 0): print("OpenGL version must be at least 3.0 (found {0})".format(glGetString(GL_VERSION).decode().split()[0])) #Now onto the OpenGL initialisation #Set up depth culling glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) glDepthFunc(GL_LEQUAL) glDepthRange(0.0, 1.0) #We create out shaders which do little more than set a flat colour for each face VERTEX_SHADER = shaders.compileShader(b""" #version 130 in vec4 position; in vec4 normal; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat4 modelMatrix; flat out float theColor; void main() { vec4 temp = modelMatrix * position; temp = viewMatrix * temp; gl_Position = projectionMatrix * temp; theColor = clamp(abs(dot(normalize(normal.xyz), normalize(vec3(0.9,0.1,0.5)))), 0, 1); } """, GL_VERTEX_SHADER) FRAGMENT_SHADER = shaders.compileShader(b""" #version 130 flat in float theColor; out vec4 outputColor; void main() { outputColor = vec4(1.0, 0.5, theColor, 1.0); } """, GL_FRAGMENT_SHADER) shader = shaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER) #And then grab our attribute locations from it glBindAttribLocation(shader, 0, b"position") glBindAttribLocation(shader, 1, b"normal") #Create the Vertex Array Object to hold our volume mesh vertexArrayObject = GLuint(0) glGenVertexArrays(1, vertexArrayObject) glBindVertexArray(vertexArrayObject) #Create the index buffer object indexPositions = vbo.VBO(indices, target=GL_ELEMENT_ARRAY_BUFFER, usage=GL_STATIC_DRAW) #Create the VBO vertexPositions = vbo.VBO(vertices, usage=GL_STATIC_DRAW) #Bind our VBOs and set up our data layout specifications with indexPositions, vertexPositions: glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, False, 6*vertices.dtype.itemsize, vertexPositions+(0*vertices.dtype.itemsize)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL_FLOAT, False, 6*vertices.dtype.itemsize, vertexPositions+(3*vertices.dtype.itemsize)) glBindVertexArray(0) glDisableVertexAttribArray(0) #Now grab out transformation martix locations modelMatrixUnif = glGetUniformLocation(shader, b"modelMatrix") viewMatrixUnif = glGetUniformLocation(shader, b"viewMatrix") projectionMatrixUnif = glGetUniformLocation(shader, b"projectionMatrix") modelMatrix = np.array([[1.0,0.0,0.0,-32.0],[0.0,1.0,0.0,-32.0],[0.0,0.0,1.0,-32.0],[0.0,0.0,0.0,1.0]], dtype='f') viewMatrix = np.array([[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,0.0,1.0,-50.0],[0.0,0.0,0.0,1.0]], dtype='f') projectionMatrix = np.array([[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0]], dtype='f') #These next few lines just set up our camera frustum fovDeg = 45.0 frustumScale = 1.0 / tan(radians(fovDeg) / 2.0) zNear = 1.0 zFar = 1000.0 projectionMatrix[0][0] = frustumScale projectionMatrix[1][1] = frustumScale projectionMatrix[2][2] = (zFar + zNear) / (zNear - zFar) projectionMatrix[2][3] = -1.0 projectionMatrix[3][2] = (2 * zFar * zNear) / (zNear - zFar) #viewMatrix and projectionMatrix don't change ever so just set them once here with shader: glUniformMatrix4fv(projectionMatrixUnif, 1, GL_TRUE, projectionMatrix) glUniformMatrix4fv(viewMatrixUnif, 1, GL_TRUE, viewMatrix) #These are used to track the rotation of the volume LastFrameMousePos = (0,0) CurrentMousePos = (0,0) xRotation = 0 yRotation = 0 while True: clock.tick() for event in pygame.event.get(): if event.type == pygame.QUIT: return if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE: return if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: CurrentMousePos = event.pos LastFrameMousePos = CurrentMousePos if event.type == pygame.MOUSEMOTION and 1 in event.buttons: CurrentMousePos = event.pos diff = (CurrentMousePos[0] - LastFrameMousePos[0], CurrentMousePos[1] - LastFrameMousePos[1]) xRotation += event.rel[0] yRotation += event.rel[1] LastFrameMousePos = CurrentMousePos glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #Perform the rotation of the mesh moveToOrigin = np.array([[1.0,0.0,0.0,-32.0],[0.0,1.0,0.0,-32.0],[0.0,0.0,1.0,-32.0],[0.0,0.0,0.0,1.0]], dtype='f') rotateAroundX = np.array([[1.0,0.0,0.0,0.0],[0.0,cos(radians(yRotation)),-sin(radians(yRotation)),0.0],[0.0,sin(radians(yRotation)),cos(radians(yRotation)),0.0],[0.0,0.0,0.0,1.0]], dtype='f') rotateAroundY = np.array([[cos(radians(xRotation)),0.0,sin(radians(xRotation)),0.0],[0.0,1.0,0.0,0.0],[-sin(radians(xRotation)),0.0,cos(radians(xRotation)),0.0],[0.0,0.0,0.0,1.0]], dtype='f') modelMatrix = rotateAroundY.dot(rotateAroundX.dot(moveToOrigin)) with shader: glUniformMatrix4fv(modelMatrixUnif, 1, GL_TRUE, modelMatrix) glBindVertexArray(vertexArrayObject) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glBindVertexArray(0) # Show the screen pygame.display.flip()
def update_texture_yuv420(self, img_data, x, y, width, height, rowstrides): drawable = self.glarea.get_gl_drawable() context = self.glarea.get_gl_context() window_width, window_height = self.get_size() if not drawable.gl_begin(context): raise Exception("** Cannot create OpenGL rendering context!") assert self.textures is not None if self.current_mode == GLClientWindow.MODE_RGB: raise Exception("** RGB -> YUV mode change unimplemented!") elif self.current_mode == GLClientWindow.MODE_UNINITIALIZED: log("Creating new YUV textures") # Create textures of the same size as the window's glEnable(GL_TEXTURE_RECTANGLE_ARB) glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, window_width, window_height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[1]) glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, window_width/2, window_height/2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[2]) glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, window_width/2, window_height/2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0); log("Assigning fragment program") glEnable(GL_FRAGMENT_PROGRAM_ARB) if not self.yuv420_shader: self.yuv420_shader = [ 1 ] glGenProgramsARB(1, self.yuv420_shader) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv420_shader[0]) prog = GL_COLORSPACE_CONVERSIONS glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(prog), prog) log.error(glGetString(GL_PROGRAM_ERROR_STRING_ARB)) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv420_shader[0]) self.current_mode = GLClientWindow.MODE_YUV # Clamp width and height to the actual texture size if x + width > window_width: width = window_width - x if y + height > window_height: height = window_height - y glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[0]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[0]) glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[1]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[1]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width/2, height/2, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[1]) glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[2]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[2]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width/2, height/2, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[2]) drawable.gl_end() self.render_image()
def setup_drawer(): """ Set up the usual constant display lists in the current OpenGL context. WARNING: THIS IS ONLY CORRECT IF ONLY ONE GL CONTEXT CONTAINS DISPLAY LISTS -- or more precisely, only the GL context this has last been called in (or one which shares its display lists) will work properly with the routines in drawer.py, since the allocated display list names are stored in globals set by this function, but in general those names might differ if this was called in different GL contexts. """ #bruce 060613 added docstring, cleaned up display list name allocation # bruce 071030 renamed from setup to setup_drawer spherelistbase = glGenLists(numSphereSizes) sphereList = [] for i in range(numSphereSizes): sphereList += [spherelistbase + i] glNewList(sphereList[i], GL_COMPILE) glBegin(GL_TRIANGLE_STRIP) # GL_LINE_LOOP to see edges. stripVerts = getSphereTriStrips(i) for vertNorm in stripVerts: glNormal3fv(vertNorm) glVertex3fv(vertNorm) continue glEnd() glEndList() continue drawing_globals.sphereList = sphereList # Sphere triangle-strip vertices for each level of detail. # (Cache and re-use the work of making them.) # Can use in converter-wrappered calls like glVertexPointerfv, # but the python arrays are re-copied to C each time. sphereArrays = [] for i in range(numSphereSizes): sphereArrays += [getSphereTriStrips(i)] continue drawing_globals.sphereArrays = sphereArrays # Sphere glDrawArrays triangle-strip vertices for C calls. # (Cache and re-use the work of converting a C version.) # Used in thinly-wrappered calls like glVertexPointer. sphereCArrays = [] for i in range(numSphereSizes): CArray = numpy.array(sphereArrays[i], dtype=numpy.float32) sphereCArrays += [CArray] continue drawing_globals.sphereCArrays = sphereCArrays # Sphere indexed vertices. # (Cache and re-use the work of making the indexes.) # Can use in converter-wrappered calls like glDrawElementsui, # but the python arrays are re-copied to C each time. sphereElements = [] # Pairs of lists (index, verts) . for i in range(numSphereSizes): sphereElements += [indexVerts(sphereArrays[i], .0001)] continue drawing_globals.sphereElements = sphereElements # Sphere glDrawElements index and vertex arrays for C calls. sphereCIndexTypes = [] # numpy index unsigned types. sphereGLIndexTypes = [] # GL index types for drawElements. sphereCElements = [] # Pairs of numpy arrays (Cindex, Cverts) . for i in range(numSphereSizes): (index, verts) = sphereElements[i] if len(index) < 256: Ctype = numpy.uint8 GLtype = GL_UNSIGNED_BYTE else: Ctype = numpy.uint16 GLtype = GL_UNSIGNED_SHORT pass sphereCIndexTypes += [Ctype] sphereGLIndexTypes += [GLtype] sphereCIndex = numpy.array(index, dtype=Ctype) sphereCVerts = numpy.array(verts, dtype=numpy.float32) sphereCElements += [(sphereCIndex, sphereCVerts)] continue drawing_globals.sphereCIndexTypes = sphereCIndexTypes drawing_globals.sphereGLIndexTypes = sphereGLIndexTypes drawing_globals.sphereCElements = sphereCElements if glGetString(GL_EXTENSIONS).find("GL_ARB_vertex_buffer_object") >= 0: # A GLBufferObject version for glDrawArrays. sphereArrayVBOs = [] for i in range(numSphereSizes): vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB, sphereCArrays[i], GL_STATIC_DRAW) sphereArrayVBOs += [vbo] continue drawing_globals.sphereArrayVBOs = sphereArrayVBOs # A GLBufferObject version for glDrawElements indexed verts. sphereElementVBOs = [] # Pairs of (IBO, VBO) for i in range(numSphereSizes): ibo = GLBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, sphereCElements[i][0], GL_STATIC_DRAW) vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB, sphereCElements[i][1], GL_STATIC_DRAW) sphereElementVBOs += [(ibo, vbo)] continue drawing_globals.sphereElementVBOs = sphereElementVBOs ibo.unbind() vbo.unbind() pass #bruce 060415 drawing_globals.wiresphere1list = wiresphere1list = glGenLists(1) glNewList(wiresphere1list, GL_COMPILE) didlines = {} # don't draw each triangle edge more than once def shoulddoline(v1, v2): # make sure not list (unhashable) or Numeric array (bug in __eq__) v1 = tuple(v1) v2 = tuple(v2) if (v1, v2) not in didlines: didlines[(v1, v2)] = didlines[(v2, v1)] = None return True return False def doline(v1, v2): if shoulddoline(v1, v2): glVertex3fv(v1) glVertex3fv(v2) return glBegin(GL_LINES) ocdec = getSphereTriangles(1) for tri in ocdec: #e Could probably optim this more, e.g. using a vertex array or VBO or # maybe GL_LINE_STRIP. doline(tri[0], tri[1]) doline(tri[1], tri[2]) doline(tri[2], tri[0]) glEnd() glEndList() drawing_globals.CylList = CylList = glGenLists(1) glNewList(CylList, GL_COMPILE) glBegin(GL_TRIANGLE_STRIP) for (vtop, ntop, vbot, nbot) in drawing_globals.cylinderEdges: glNormal3fv(nbot) glVertex3fv(vbot) glNormal3fv(ntop) glVertex3fv(vtop) glEnd() glEndList() drawing_globals.CapList = CapList = glGenLists(1) glNewList(CapList, GL_COMPILE) glNormal3fv(drawing_globals.cap0n) glBegin(GL_POLYGON) for p in drawing_globals.drum0: glVertex3fv(p) glEnd() glNormal3fv(drawing_globals.cap1n) glBegin(GL_POLYGON) #bruce 060609 fix "ragged edge" bug in this endcap: drum1 -> drum2 for p in drawing_globals.drum2: glVertex3fv(p) glEnd() glEndList() drawing_globals.diamondGridList = diamondGridList = glGenLists(1) glNewList(diamondGridList, GL_COMPILE) glBegin(GL_LINES) for p in drawing_globals.digrid: glVertex(p[0]) glVertex(p[1]) glEnd() glEndList() drawing_globals.lonsGridList = lonsGridList = glGenLists(1) glNewList(lonsGridList, GL_COMPILE) glBegin(GL_LINES) for p in drawing_globals.lonsEdges: glVertex(p[0]) glVertex(p[1]) glEnd() glEndList() drawing_globals.CubeList = CubeList = glGenLists(1) glNewList(CubeList, GL_COMPILE) glBegin(GL_QUAD_STRIP) # note: CubeList has only 4 faces of the cube; only suitable for use in # wireframes; see also solidCubeList [bruce 051215 comment reporting # grantham 20051213 observation] glVertex((-1, -1, -1)) glVertex((1, -1, -1)) glVertex((-1, 1, -1)) glVertex((1, 1, -1)) glVertex((-1, 1, 1)) glVertex((1, 1, 1)) glVertex((-1, -1, 1)) glVertex((1, -1, 1)) glVertex((-1, -1, -1)) glVertex((1, -1, -1)) glEnd() glEndList() drawing_globals.solidCubeList = solidCubeList = glGenLists(1) glNewList(solidCubeList, GL_COMPILE) glBegin(GL_QUADS) for i in xrange(len(drawing_globals.cubeIndices)): avenormals = V(0, 0, 0) #bruce 060302 fixed normals for flat shading for j in xrange(4): nTuple = tuple( drawing_globals.cubeNormals[drawing_globals.cubeIndices[i][j]]) avenormals += A(nTuple) avenormals = norm(avenormals) for j in xrange(4): vTuple = tuple(drawing_globals.cubeVertices[ drawing_globals.cubeIndices[i][j]]) #bruce 060302 made size compatible with glut.glutSolidCube(1.0) vTuple = A(vTuple) * 0.5 glNormal3fv(avenormals) glVertex3fv(vTuple) glEnd() glEndList() drawing_globals.rotSignList = rotSignList = glGenLists(1) glNewList(rotSignList, GL_COMPILE) glBegin(GL_LINE_STRIP) for ii in xrange(len(drawing_globals.rotS0n)): glVertex3fv(tuple(drawing_globals.rotS0n[ii])) glEnd() glBegin(GL_LINE_STRIP) for ii in xrange(len(drawing_globals.rotS1n)): glVertex3fv(tuple(drawing_globals.rotS1n[ii])) glEnd() glBegin(GL_TRIANGLES) for v in drawing_globals.arrow0Vertices + drawing_globals.arrow1Vertices: glVertex3f(v[0], v[1], v[2]) glEnd() glEndList() drawing_globals.linearArrowList = linearArrowList = glGenLists(1) glNewList(linearArrowList, GL_COMPILE) glBegin(GL_TRIANGLES) for v in drawing_globals.linearArrowVertices: glVertex3f(v[0], v[1], v[2]) glEnd() glEndList() drawing_globals.linearLineList = linearLineList = glGenLists(1) glNewList(linearLineList, GL_COMPILE) glEnable(GL_LINE_SMOOTH) glBegin(GL_LINES) glVertex3f(0.0, 0.0, -drawing_globals.halfHeight) glVertex3f(0.0, 0.0, drawing_globals.halfHeight) glEnd() glDisable(GL_LINE_SMOOTH) glEndList() drawing_globals.circleList = circleList = glGenLists(1) glNewList(circleList, GL_COMPILE) glBegin(GL_LINE_LOOP) for ii in range(60): x = cos(ii * 2.0 * pi / 60) y = sin(ii * 2.0 * pi / 60) glVertex3f(x, y, 0.0) glEnd() glEndList() # piotr 080405 drawing_globals.filledCircleList = filledCircleList = glGenLists(1) glNewList(filledCircleList, GL_COMPILE) glBegin(GL_POLYGON) for ii in range(60): x = cos(ii * 2.0 * pi / 60) y = sin(ii * 2.0 * pi / 60) glVertex3f(x, y, 0.0) glEnd() glEndList() drawing_globals.lineCubeList = lineCubeList = glGenLists(1) glNewList(lineCubeList, GL_COMPILE) glBegin(GL_LINES) cvIndices = [ 0, 1, 2, 3, 4, 5, 6, 7, 0, 3, 1, 2, 5, 6, 4, 7, 0, 4, 1, 5, 2, 6, 3, 7 ] for i in cvIndices: glVertex3fv(tuple(drawing_globals.cubeVertices[i])) glEnd() glEndList() # Debug Preferences from utilities.debug_prefs import debug_pref, Choice_boolean_True from utilities.debug_prefs import Choice_boolean_False choices = [Choice_boolean_False, Choice_boolean_True] # 20060314 grantham initial_choice = choices[drawing_globals.allow_color_sorting_default] drawing_globals.allow_color_sorting_pref = debug_pref( "Use Color Sorting?", initial_choice, prefs_key=drawing_globals.allow_color_sorting_prefs_key) #bruce 060323 removed non_debug = True for A7 release, changed default #value to False (far above), and changed its prefs_key so developers #start with the new default value. #russ 080225: Added. initial_choice = choices[drawing_globals.use_color_sorted_dls_default] drawing_globals.use_color_sorted_dls_pref = debug_pref( "Use Color-sorted Display Lists?", initial_choice, prefs_key=drawing_globals.use_color_sorted_dls_prefs_key) #russ 080225: Added. initial_choice = choices[drawing_globals.use_color_sorted_vbos_default] drawing_globals.use_color_sorted_vbos_pref = debug_pref( "Use Color-sorted Vertex Buffer Objects?", initial_choice, prefs_key=drawing_globals.use_color_sorted_vbos_prefs_key) #russ 080403: Added drawing variant selection variants = [ "0. OpenGL 1.0 - glBegin/glEnd tri-strips vertex-by-vertex.", "1. OpenGL 1.1 - glDrawArrays from CPU RAM.", "2. OpenGL 1.1 - glDrawElements indexed arrays from CPU RAM.", "3. OpenGL 1.5 - glDrawArrays from graphics RAM VBO.", "4. OpenGL 1.5 - glDrawElements, verts in VBO, index in CPU.", "5. OpenGL 1.5 - VBO/IBO buffered glDrawElements." ] drawing_globals.use_drawing_variant = debug_pref( "GLPane: drawing method", Choice(names=variants, values=range(len(variants)), defaultValue=drawing_globals.use_drawing_variant_default), prefs_key=drawing_globals.use_drawing_variant_prefs_key) # temporarily always print this, while default setting might be in flux, # and to avoid confusion if the two necessary prefs are set differently # [bruce 080305] if (drawing_globals.allow_color_sorting_pref and drawing_globals.use_color_sorted_dls_pref): print "\nnote: this session WILL use color sorted display lists" else: print "\nnote: this session will NOT use color sorted display lists" if (drawing_globals.allow_color_sorting_pref and drawing_globals.use_color_sorted_vbos_pref): print "note: this session WILL use", \ "color sorted Vertex Buffer Objects\n" else: print "note: this session will NOT use", \ "color sorted Vertex Buffer Objects\n" # 20060313 grantham Added use_c_renderer debug pref, can # take out when C renderer used by default. if drawing_globals.quux_module_import_succeeded: initial_choice = choices[drawing_globals.use_c_renderer_default] drawing_globals.use_c_renderer = (debug_pref( "Use native C renderer?", initial_choice, prefs_key=drawing_globals.use_c_renderer_prefs_key)) #bruce 060323 removed non_debug = True for A7 release, and changed # its prefs_key so developers start over with the default value. #initTexture('C:\\Huaicai\\atom\\temp\\newSample.png', 128,128) return # from setup_drawer
def update_texture_yuv(self, img_data, x, y, width, height, rowstrides, pixel_format): window_width, window_height = self.size assert self.textures is not None, "no OpenGL textures!" if self.pixel_format is None or self.pixel_format != pixel_format: self.pixel_format = pixel_format divs = self.get_subsampling_divs(pixel_format) log( "GL creating new YUV textures for pixel format %s using divs=%s", pixel_format, divs) # Create textures of the same size as the window's glEnable(GL_TEXTURE_RECTANGLE_ARB) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): div = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glEnable(GL_TEXTURE_RECTANGLE_ARB) mag_filter = GL_NEAREST if div > 1: mag_filter = GL_LINEAR glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, mag_filter) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, window_width / div, window_height / div, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0) log("Assigning fragment program") glEnable(GL_FRAGMENT_PROGRAM_ARB) if not self.yuv_shader: self.yuv_shader = [1] glGenProgramsARB(1, self.yuv_shader) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv_shader[0]) prog = GL_COLORSPACE_CONVERSIONS glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(prog), prog) err = glGetString(GL_PROGRAM_ERROR_STRING_ARB) if err: #FIXME: maybe we should do something else here? log.error(err) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv_shader[0]) # Clamp width and height to the actual texture size if x + width > window_width: width = window_width - x if y + height > window_height: height = window_height - y divs = self.get_subsampling_divs(pixel_format) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): div = divs[index] glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[index]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width / div, height / div, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[index]) glFlush()
class JuMEG_GLS_Plotter(object): """ Helper class for using GLSL shader programs """ def __init__(self, vertex=None, fragment=None): self.__vao_id = None self.__vao_data = np.array([]) self.__color = np.array([1.0, 0.0, 1.0, 1.0], dtype=np.float32) self.color = [0.0, 0.0, 1.0, 1.0] #np.array( [0.0,0.0,1.0,1.0],dtype=np.float32 ) #self.vertex_pos=None self.gls_pgr = None self.init_shader(vertex=vertex, fragment=fragment) def __get_color(self): return self.__color def __set_color(self, v): self.__color = v plot_color = property(__get_color, __set_color) def __get_vao_id(self): return self.__vao_id def __set_vao_id(self, v): self.__vao_id = v vao_id = property(__get_vao_id, __set_vao_id) def __get_vao_data(self): return self.__vao_data def __set_vao_data(self, data): self.__vao_data = data vao_data = property(__get_vao_data, __set_vao_data) def __get_vbo_data_points(self): return int(self.vao_data.size / 2) data_points = property(__get_vbo_data_points) print "INIT" print 'Vendor: %s' % (glGetString(GL_VENDOR)) print 'Opengl version: %s' % (glGetString(GL_VERSION)) print 'GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION)) print 'Renderer: %s' % (glGetString(GL_RENDERER)) print "done\n" def init_shader(self, vertex=None, fragment=None): if self.gls_pgr: glUseProgram(0) if self.gls_pgr.shader_id: glDeleteShader(self.gls_pgr.shader_id) if vertex is None: vertex = """ #version 330 attribute vec2 xy_pos; uniform vec4 xy_color; uniform vec4 xy_color1; varying vec4 frg_color; void main(void) { frg_color = xy_color; gl_Position = vec4(xy_pos,0, 1.0); } """ print vertex if fragment is None: fragment = """ #version 330 varying vec4 frg_color; void main(void) { gl_FragColor = frg_color; } """ print fragment self.gls_pgr = ShaderProgram(vertex, fragment) glUseProgram(self.gls_pgr.program_id) self.vertIndex = self.gls_pgr.attribute_location('xy_pos') #glVertexAttribPointer(self.gls_pgr.attribute_location('xy_pos'), 2, GL_FLOAT, GL_FALSE, 0, None) # Turn on this vertex attribute in the shader #glEnableVertexAttribArray(0) self.gls_id_xy_color = self.gls_pgr.uniform_location("xy_color") print self.gls_id_xy_color cid = glGetUniformLocation(self.gls_pgr.program_id, "xy_color1") print cid glUniform4fv(self.gls_id_xy_color, 1, self.color) # attributes #self.vertex_pos = glGetAttribLocation(self.gls_pgr, "vin_position") def init_vao_vbo(self, data=None): if data.size: self.vao_data = data # Lets create a VAO and bind it # Think of VAO's as object that encapsulate buffer state # Using a VAO enables you to cut down on calls in your draw # loop which generally makes things run faster self.vertexBuffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) glBufferData(GL_ARRAY_BUFFER, 4 * len(self.vao_data), self.vao_data, GL_DYNAMIC_DRAW) #self.vbo_id = glGenBuffers(1) #glBindBuffer(GL_ARRAY_BUFFER, self.vbo_id) #vertexData = numpy.array(quadV, numpy.float32) #glBufferData(GL_ARRAY_BUFFER, 4*len(self.vao_data), self.vao_data,GL_DYNAMIC_DRAW) # self.vao_id = \ #vao_id=glGenVertexArrays(1,None) #self.vao_id=vao_id #print vao_id #glBindVertexArray(self.vao_id[0]) # Lets create our Vertex Buffer objects - these are the buffers # that will contain our per vertex data #self.vbo_id = glGenBuffers(1) # Bind a buffer before we can use it #glBindBuffer(GL_ARRAY_BUFFER, self.vbo_id[0]) # Now go ahead and fill this bound buffer with some data #glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(self.data), self.data, GL_DYNAMIC_DRAW) # Now specify how the shader program will be receiving this data # In this case the data from this buffer will be available in the shader as the vin_position vertex attribute # Now do the same for the other vertex buffer #glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1]) #glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(color_data), color_data, GL_STATIC_DRAW) #glVertexAttribPointer(program.attribute_location('vin_color'), 3, GL_FLOAT, GL_FALSE, 0, None) #glEnableVertexAttribArray(1) # Lets unbind our vbo and vao state # We will bind these again in the draw loop glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) def vao_update(self, data): if data.size: self.vao_data = data # Bind a buffer before we can use it glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) # Now go ahead and fill this bound buffer with some data glBufferSubData(GL_ARRAY_BUFFER, 0, ArrayDatatype.arrayByteCount(self.vao_data), self.vao_data) def plot(self): # Specify shader to be used glUseProgram(self.gls_pgr.program_id) # Bind VAO - this will automatically # bind all the vbo's saving us a bunch # of calls #glBindVertexArray(self.vao_id) glUniform4fv(self.gls_id_xy_color, 1, self.plot_color) # Modern GL makes the draw call really simple # All the complexity has been pushed elsewhere glEnableVertexAttribArray(self.vertIndex) # set buffers glBindBuffer(GL_ARRAY_BUFFER, self.vertexBuffer) glVertexAttribPointer(self.vertIndex, 2, GL_FLOAT, GL_FALSE, 0, None) glDrawArrays(GL_LINE_STRIP, 0, self.data_points - 1) # Lets unbind the shader and vertex array state glUseProgram(0) # disable arrays glDisableVertexAttribArray(self.vertIndex) glBindVertexArray(0) # Now lets show our master piece on the screen # SwapBuffers() # If the user has closed the window in anger # then terminate this program # running = running and GetWindowParam(OPENED) def reset(self): glUseProgram(0) glDisableVertexAttribArray(self.vertIndex) glBindVertexArray(0)
def __init__(self, detector_file=None, event_file=None, min_tot=None, skip_to_blob=0, width=1000, height=700, x=50, y=50): self.camera = Camera() self.camera.is_rotating = True self.colourist = Colourist() current_path = os.path.dirname(os.path.abspath(__file__)) if not detector_file: detector_file = os.path.join(current_path, 'data/km3net_jul13_90m_r1494_corrected.detx') self.load_logo() self.init_opengl(width=width, height=height, x=x, y=y) print("OpenGL Version: {0}".format(glGetString(GL_VERSION))) self.clock = Clock(speed=100) self.timer = Clock(snooze_interval=1/30) self.frame_index = 0 self.event_index = skip_to_blob self.is_recording = False self.min_tot = min_tot VERTEX_SHADER = compileShader(""" void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; }""", GL_VERTEX_SHADER) FRAGMENT_SHADER = compileShader(""" void main() { gl_FragColor = vec4(0.5, 0.5, 0.5, 1); }""", GL_FRAGMENT_SHADER) self.shader = compileProgram(VERTEX_SHADER, FRAGMENT_SHADER) self.blob = None self.objects = {} self.shaded_objects = [] self.mouse_x = None self.mouse_y = None self.show_secondaries = True self.show_help = False self._help_string = None self.show_info = True self.spectrum = None self.current_spectrum = 'default' self.cmap = self.colourist.default_cmap self.min_hit_time = None self.max_hit_time = None self.detector = Detector(detector_file) dom_positions = self.detector.dom_positions min_z = min([z for x, y, z in dom_positions]) max_z = max([z for x, y, z in dom_positions]) z_shift = (max_z - min_z) / 2 self.dom_positions = np.array([tuple(pos) for pos in dom_positions], 'f') self.camera.target = Position((0, 0, z_shift)) self.dom_positions_vbo = vbo.VBO(self.dom_positions) if event_file: self.pump = EvtPump(filename=event_file) try: self.load_blob(skip_to_blob) except IndexError: print("Could not load blob at index {0}".format(skip_to_blob)) print("Starting from the first one...") self.load_blob(0) else: print("No event file specified. Only the detector will be shown.") self.clock.reset() self.timer.reset() glutMainLoop()
def update_texture_yuv420(self, img_data, x, y, width, height, rowstrides): drawable = self.glarea.get_gl_drawable() context = self.glarea.get_gl_context() window_width, window_height = self.get_size() if not drawable.gl_begin(context): raise Exception("** Cannot create OpenGL rendering context!") assert self.textures is not None if self.current_mode == GLClientWindow.MODE_RGB: raise Exception("** RGB -> YUV mode change unimplemented!") elif self.current_mode == GLClientWindow.MODE_UNINITIALIZED: log("Creating new YUV textures") # Create textures of the same size as the window's glEnable(GL_TEXTURE_RECTANGLE_ARB) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, window_width, window_height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[1]) glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, window_width / 2, window_height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0) glActiveTexture(GL_TEXTURE2) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[2]) glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, window_width / 2, window_height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0) log("Assigning fragment program") glEnable(GL_FRAGMENT_PROGRAM_ARB) if not self.yuv420_shader: self.yuv420_shader = [1] glGenProgramsARB(1, self.yuv420_shader) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv420_shader[0]) prog = GL_COLORSPACE_CONVERSIONS glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(prog), prog) log.error(glGetString(GL_PROGRAM_ERROR_STRING_ARB)) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv420_shader[0]) self.current_mode = GLClientWindow.MODE_YUV # Clamp width and height to the actual texture size if x + width > window_width: width = window_width - x if y + height > window_height: height = window_height - y glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[0]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[0]) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[1]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[1]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width / 2, height / 2, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[1]) glActiveTexture(GL_TEXTURE2) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[2]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[2]) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width / 2, height / 2, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[2]) drawable.gl_end() self.render_image()
from OpenGL.GL.ARB.vertex_program import glGenProgramsARB, glBindProgramARB, glProgramStringARB from OpenGL.GL.ARB.fragment_program import glInitFragmentProgramARB from xpra.gl_colorspace_conversions import GL_COLORSPACE_CONVERSIONS #sanity checks: OpenGL version try: from gtk import gdk glconfig = gtk.gdkgl.Config(mode=gtk.gdkgl.MODE_RGB | gtk.gdkgl.MODE_SINGLE) glext = gtk.gdkgl.ext(gdk.Pixmap(gdk.get_default_root_window(), 1, 1)) gldrawable = glext.set_gl_capability(glconfig) glcontext = gtk.gdkgl.Context(gldrawable, direct=True) if not gldrawable.gl_begin(glcontext): raise ImportError("gl_begin failed on %s" % gldrawable) try: gl_major = int(glGetString(GL_VERSION)[0]) gl_minor = int(glGetString(GL_VERSION)[2]) if gl_major <= 1 and gl_minor < 1: raise ImportError( "** OpenGL output requires OpenGL version 1.1 or greater, not %s.%s" % (gl_major, gl_minor)) log.info("found valid OpenGL: %s.%s", gl_major, gl_minor) #this allows us to do CSC via OpenGL: #see http://www.opengl.org/registry/specs/ARB/fragment_program.txt use_openGL_CSC = glInitFragmentProgramARB() finally: gldrawable.gl_end() del glcontext, gldrawable, glext, glconfig except Exception, e: raise ImportError("** OpenGL initialization error: %s" % e)
def check_GL_support(gldrawable, glcontext, min_texture_size=0, force_enable=False): if not gldrawable.gl_begin(glcontext): raise ImportError("gl_begin failed on %s" % gldrawable) props = {} try: #log redirection: def redirect_log(logger_name): logger = logging.getLogger(logger_name) assert logger is not None logger.saved_handlers = logger.handlers logger.saved_propagate = logger.propagate logger.handlers = [CaptureHandler()] logger.propagate = 0 return logger fhlogger = redirect_log('OpenGL.formathandler') elogger = redirect_log('OpenGL.extensions') alogger = redirect_log('OpenGL.acceleratesupport') arlogger = redirect_log('OpenGL.arrays') clogger = redirect_log('OpenGL.converters') import OpenGL props["pyopengl"] = OpenGL.__version__ from OpenGL.GL import GL_VERSION, GL_EXTENSIONS from OpenGL.GL import glGetString, glGetInteger gl_version_str = glGetString(GL_VERSION) if gl_version_str is None: gl_check_error("OpenGL version is missing - cannot continue") return {} gl_major = int(gl_version_str[0]) gl_minor = int(gl_version_str[2]) props["opengl"] = gl_major, gl_minor MIN_VERSION = (1,1) if (gl_major, gl_minor) < MIN_VERSION: gl_check_error("OpenGL output requires version %s or greater, not %s.%s" % (".".join([str(x) for x in MIN_VERSION]), gl_major, gl_minor)) else: log("found valid OpenGL version: %s.%s", gl_major, gl_minor) from OpenGL import version as OpenGL_version try: import OpenGL_accelerate except: OpenGL_accelerate = None props["zerocopy"] = is_pyopengl_memoryview_safe(OpenGL_version.__version__) and bool(OpenGL_accelerate) try: extensions = glGetString(GL_EXTENSIONS).split(" ") except: extensions = [] gl_check_error("OpenGL could not find the list of GL extensions - does the graphics driver support OpenGL?") log("OpenGL extensions found: %s", ", ".join(extensions)) props["extensions"] = extensions from OpenGL.arrays.arraydatatype import ArrayDatatype try: log("found the following array handlers: %s", set(ArrayDatatype.getRegistry().values())) except: pass from OpenGL.GL import GL_RENDERER, GL_VENDOR, GL_SHADING_LANGUAGE_VERSION for d,s,fatal in (("vendor", GL_VENDOR, True), ("renderer", GL_RENDERER, True), ("shading language version", GL_SHADING_LANGUAGE_VERSION, False)): try: v = glGetString(s) log("%s: %s", d, v) except: if fatal: gl_check_error("OpenGL property '%s' is missing" % d) else: log("OpenGL property '%s' is missing", d) v = "" props[d] = v from OpenGL.GLU import gluGetString, GLU_VERSION, GLU_EXTENSIONS for d,s in {"GLU version": GLU_VERSION, "GLU extensions":GLU_EXTENSIONS}.items(): v = gluGetString(s) log("%s: %s", d, v) props[d] = v blacklisted = None whitelisted = None for k,vlist in BLACKLIST.items(): v = props.get(k) if v in vlist: log("%s '%s' found in blacklist: %s", k, v, vlist) blacklisted = k, v for k,vlist in WHITELIST.items(): v = props.get(k) if v in vlist: log("%s '%s' found in whitelist: %s", k, v, vlist) whitelisted = k, v if blacklisted: if whitelisted: log.info("%s '%s' enabled (found in both blacklist and whitelist)", *whitelisted) elif force_enable: log.warn("Warning: %s '%s' is blacklisted!", *blacklisted) else: gl_check_error("%s '%s' is blacklisted!" % (blacklisted)) #check for specific functions we need: from OpenGL.GL import glActiveTexture, glTexSubImage2D, glTexCoord2i, \ glViewport, glMatrixMode, glLoadIdentity, glOrtho, \ glEnableClientState, glGenTextures, glDisable, \ glBindTexture, glPixelStorei, glEnable, glBegin, glFlush, \ glTexParameteri, glTexEnvi, glHint, glBlendFunc, glLineStipple, \ glTexImage2D, \ glMultiTexCoord2i, \ glVertex2i, glEnd check_functions(glActiveTexture, glTexSubImage2D, glTexCoord2i, \ glViewport, glMatrixMode, glLoadIdentity, glOrtho, \ glEnableClientState, glGenTextures, glDisable, \ glBindTexture, glPixelStorei, glEnable, glBegin, glFlush, \ glTexParameteri, glTexEnvi, glHint, glBlendFunc, glLineStipple, \ glTexImage2D, \ glMultiTexCoord2i, \ glVertex2i, glEnd) glEnablei = None try: from OpenGL.GL import glEnablei except: pass if not bool(glEnablei): log.warn("OpenGL glEnablei is not available, disabling transparency") global GL_ALPHA_SUPPORTED GL_ALPHA_SUPPORTED = False #check for framebuffer functions we need: from OpenGL.GL.ARB.framebuffer_object import GL_FRAMEBUFFER, \ GL_COLOR_ATTACHMENT0, glGenFramebuffers, glBindFramebuffer, glFramebufferTexture2D check_functions(GL_FRAMEBUFFER, \ GL_COLOR_ATTACHMENT0, glGenFramebuffers, glBindFramebuffer, glFramebufferTexture2D) for ext in required_extensions: if ext not in extensions: gl_check_error("OpenGL driver lacks support for extension: %s" % ext) else: log("Extension %s is present", ext) #this allows us to do CSC via OpenGL: #see http://www.opengl.org/registry/specs/ARB/fragment_program.txt from OpenGL.GL.ARB.fragment_program import glInitFragmentProgramARB if not glInitFragmentProgramARB(): gl_check_error("OpenGL output requires glInitFragmentProgramARB") else: log("glInitFragmentProgramARB works") from OpenGL.GL.ARB.texture_rectangle import glInitTextureRectangleARB if not glInitTextureRectangleARB(): gl_check_error("OpenGL output requires glInitTextureRectangleARB") else: log("glInitTextureRectangleARB works") from OpenGL.GL.ARB.vertex_program import glGenProgramsARB, glDeleteProgramsARB, \ glBindProgramARB, glProgramStringARB check_functions(glGenProgramsARB, glDeleteProgramsARB, glBindProgramARB, glProgramStringARB) try: from OpenGL.GL import GL_MAX_TEXTURE_SIZE texture_size = glGetInteger(GL_MAX_TEXTURE_SIZE) #this one may be missing? rect_texture_size = texture_size try: from OpenGL.GL import GL_MAX_RECTANGLE_TEXTURE_SIZE rect_texture_size = glGetInteger(GL_MAX_RECTANGLE_TEXTURE_SIZE) except ImportError, e: log("OpenGL: %s", e) log("using GL_MAX_TEXTURE_SIZE=%s as default", texture_size) except Exception, e: emsg = str(e) if hasattr(e, "description"): emsg = e.description gl_check_error("unable to query max texture size: %s" % emsg) return props if min_texture_size>texture_size or min_texture_size>rect_texture_size: gl_check_error("The texture size is too small: %s" % texture_size) else: log("Texture size GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB=%s, GL_MAX_TEXTURE_SIZE=%s", rect_texture_size, texture_size) props["texture-size-limit"] = min(rect_texture_size, texture_size) return props
def setup_drawer(): """ Set up the usual constant display lists in the current OpenGL context. WARNING: THIS IS ONLY CORRECT IF ONLY ONE GL CONTEXT CONTAINS DISPLAY LISTS -- or more precisely, only the GL context this has last been called in (or one which shares its display lists) will work properly with the routines in drawer.py, since the allocated display list names are stored in globals set by this function, but in general those names might differ if this was called in different GL contexts. """ spherelistbase = glGenLists(_NUM_SPHERE_SIZES) sphereList = [] for i in range(_NUM_SPHERE_SIZES): sphereList += [spherelistbase+i] glNewList(sphereList[i], GL_COMPILE) glBegin(GL_TRIANGLE_STRIP) # GL_LINE_LOOP to see edges stripVerts = getSphereTriStrips(i) for vertNorm in stripVerts: glNormal3fv(vertNorm) glVertex3fv(vertNorm) continue glEnd() glEndList() continue drawing_globals.sphereList = sphereList # Sphere triangle-strip vertices for each level of detail. # (Cache and re-use the work of making them.) # Can use in converter-wrappered calls like glVertexPointerfv, # but the python arrays are re-copied to C each time. sphereArrays = [] for i in range(_NUM_SPHERE_SIZES): sphereArrays += [getSphereTriStrips(i)] continue drawing_globals.sphereArrays = sphereArrays # Sphere glDrawArrays triangle-strip vertices for C calls. # (Cache and re-use the work of converting a C version.) # Used in thinly-wrappered calls like glVertexPointer. sphereCArrays = [] for i in range(_NUM_SPHERE_SIZES): CArray = numpy.array(sphereArrays[i], dtype = numpy.float32) sphereCArrays += [CArray] continue drawing_globals.sphereCArrays = sphereCArrays # Sphere indexed vertices. # (Cache and re-use the work of making the indexes.) # Can use in converter-wrappered calls like glDrawElementsui, # but the python arrays are re-copied to C each time. sphereElements = [] # Pairs of lists (index, verts) . for i in range(_NUM_SPHERE_SIZES): sphereElements += [indexVerts(sphereArrays[i], .0001)] continue drawing_globals.sphereElements = sphereElements # Sphere glDrawElements index and vertex arrays for C calls. sphereCIndexTypes = [] # numpy index unsigned types. sphereGLIndexTypes = [] # GL index types for drawElements. sphereCElements = [] # Pairs of numpy arrays (Cindex, Cverts) . for i in range(_NUM_SPHERE_SIZES): (index, verts) = sphereElements[i] if len(index) < 256: Ctype = numpy.uint8 GLtype = GL_UNSIGNED_BYTE else: Ctype = numpy.uint16 GLtype = GL_UNSIGNED_SHORT pass sphereCIndexTypes += [Ctype] sphereGLIndexTypes += [GLtype] sphereCIndex = numpy.array(index, dtype = Ctype) sphereCVerts = numpy.array(verts, dtype = numpy.float32) sphereCElements += [(sphereCIndex, sphereCVerts)] continue drawing_globals.sphereCIndexTypes = sphereCIndexTypes drawing_globals.sphereGLIndexTypes = sphereGLIndexTypes drawing_globals.sphereCElements = sphereCElements if glGetString(GL_EXTENSIONS).find("GL_ARB_vertex_buffer_object") >= 0: # A GLBufferObject version for glDrawArrays. sphereArrayVBOs = [] for i in range(_NUM_SPHERE_SIZES): vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB, sphereCArrays[i], GL_STATIC_DRAW) sphereArrayVBOs += [vbo] continue drawing_globals.sphereArrayVBOs = sphereArrayVBOs # A GLBufferObject version for glDrawElements indexed verts. sphereElementVBOs = [] # Pairs of (IBO, VBO) for i in range(_NUM_SPHERE_SIZES): ibo = GLBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, sphereCElements[i][0], GL_STATIC_DRAW) vbo = GLBufferObject(GL_ARRAY_BUFFER_ARB, sphereCElements[i][1], GL_STATIC_DRAW) sphereElementVBOs += [(ibo, vbo)] continue drawing_globals.sphereElementVBOs = sphereElementVBOs ibo.unbind() vbo.unbind() pass #bruce 060415 drawing_globals.wiresphere1list = wiresphere1list = glGenLists(1) glNewList(wiresphere1list, GL_COMPILE) didlines = {} # don't draw each triangle edge more than once def shoulddoline(v1,v2): # make sure not list (unhashable) or Numeric array (bug in __eq__) v1 = tuple(v1) v2 = tuple(v2) if (v1,v2) not in didlines: didlines[(v1,v2)] = didlines[(v2,v1)] = None return True return False def doline(v1,v2): if shoulddoline(v1,v2): glVertex3fv(v1) glVertex3fv(v2) return glBegin(GL_LINES) ocdec = getSphereTriangles(1) for tri in ocdec: #e Could probably optim this more, e.g. using a vertex array or VBO or # maybe GL_LINE_STRIP. doline(tri[0], tri[1]) doline(tri[1], tri[2]) doline(tri[2], tri[0]) glEnd() glEndList() drawing_globals.CylList = CylList = glGenLists(1) glNewList(CylList, GL_COMPILE) glBegin(GL_TRIANGLE_STRIP) for (vtop, ntop, vbot, nbot) in drawing_globals.cylinderEdges: glNormal3fv(nbot) glVertex3fv(vbot) glNormal3fv(ntop) glVertex3fv(vtop) glEnd() glEndList() drawing_globals.CapList = CapList = glGenLists(1) glNewList(CapList, GL_COMPILE) glNormal3fv(drawing_globals.cap0n) glBegin(GL_POLYGON) for p in drawing_globals.drum0: glVertex3fv(p) glEnd() glNormal3fv(drawing_globals.cap1n) glBegin(GL_POLYGON) #bruce 060609 fix "ragged edge" bug in this endcap: drum1 -> drum2 for p in drawing_globals.drum2: glVertex3fv(p) glEnd() glEndList() drawing_globals.diamondGridList = diamondGridList = glGenLists(1) glNewList(diamondGridList, GL_COMPILE) glBegin(GL_LINES) for p in drawing_globals.digrid: glVertex(p[0]) glVertex(p[1]) glEnd() glEndList() drawing_globals.lonsGridList = lonsGridList = glGenLists(1) glNewList(lonsGridList, GL_COMPILE) glBegin(GL_LINES) for p in drawing_globals.lonsEdges: glVertex(p[0]) glVertex(p[1]) glEnd() glEndList() drawing_globals.CubeList = CubeList = glGenLists(1) glNewList(CubeList, GL_COMPILE) glBegin(GL_QUAD_STRIP) # note: CubeList has only 4 faces of the cube; only suitable for use in # wireframes; see also solidCubeList [bruce 051215 comment reporting # grantham 20051213 observation] glVertex((-1,-1,-1)) glVertex(( 1,-1,-1)) glVertex((-1, 1,-1)) glVertex(( 1, 1,-1)) glVertex((-1, 1, 1)) glVertex(( 1, 1, 1)) glVertex((-1,-1, 1)) glVertex(( 1,-1, 1)) glVertex((-1,-1,-1)) glVertex(( 1,-1,-1)) glEnd() glEndList() drawing_globals.solidCubeList = solidCubeList = glGenLists(1) glNewList(solidCubeList, GL_COMPILE) glBegin(GL_QUADS) for i in xrange(len(drawing_globals.cubeIndices)): avenormals = V(0,0,0) #bruce 060302 fixed normals for flat shading for j in xrange(4) : nTuple = tuple( drawing_globals.cubeNormals[drawing_globals.cubeIndices[i][j]]) avenormals += A(nTuple) avenormals = norm(avenormals) for j in xrange(4) : vTuple = tuple( drawing_globals.cubeVertices[drawing_globals.cubeIndices[i][j]]) #bruce 060302 made size compatible with glut.glutSolidCube(1.0) vTuple = A(vTuple) * 0.5 glNormal3fv(avenormals) glVertex3fv(vTuple) glEnd() glEndList() drawing_globals.rotSignList = rotSignList = glGenLists(1) glNewList(rotSignList, GL_COMPILE) glBegin(GL_LINE_STRIP) for ii in xrange(len(drawing_globals.rotS0n)): glVertex3fv(tuple(drawing_globals.rotS0n[ii])) glEnd() glBegin(GL_LINE_STRIP) for ii in xrange(len(drawing_globals.rotS1n)): glVertex3fv(tuple(drawing_globals.rotS1n[ii])) glEnd() glBegin(GL_TRIANGLES) for v in drawing_globals.arrow0Vertices + drawing_globals.arrow1Vertices: glVertex3f(v[0], v[1], v[2]) glEnd() glEndList() drawing_globals.linearArrowList = linearArrowList = glGenLists(1) glNewList(linearArrowList, GL_COMPILE) glBegin(GL_TRIANGLES) for v in drawing_globals.linearArrowVertices: glVertex3f(v[0], v[1], v[2]) glEnd() glEndList() drawing_globals.linearLineList = linearLineList = glGenLists(1) glNewList(linearLineList, GL_COMPILE) glEnable(GL_LINE_SMOOTH) glBegin(GL_LINES) glVertex3f(0.0, 0.0, -drawing_globals.halfHeight) glVertex3f(0.0, 0.0, drawing_globals.halfHeight) glEnd() glDisable(GL_LINE_SMOOTH) glEndList() drawing_globals.circleList = circleList = glGenLists(1) glNewList(circleList, GL_COMPILE) glBegin(GL_LINE_LOOP) for ii in range(60): x = cos(ii*2.0*pi/60) y = sin(ii*2.0*pi/60) glVertex3f(x, y, 0.0) glEnd() glEndList() # piotr 080405 drawing_globals.filledCircleList = filledCircleList = glGenLists(1) glNewList(filledCircleList, GL_COMPILE) glBegin(GL_POLYGON) for ii in range(60): x = cos(ii*2.0*pi/60) y = sin(ii*2.0*pi/60) glVertex3f(x, y, 0.0) glEnd() glEndList() drawing_globals.lineCubeList = lineCubeList = glGenLists(1) glNewList(lineCubeList, GL_COMPILE) glBegin(GL_LINES) cvIndices = [0,1, 2,3, 4,5, 6,7, 0,3, 1,2, 5,6, 4,7, 0,4, 1,5, 2,6, 3,7] for i in cvIndices: glVertex3fv(tuple(drawing_globals.cubeVertices[i])) glEnd() glEndList() #initTexture('C:\\Huaicai\\atom\\temp\\newSample.png', 128,128) return # from setup_drawer
def paint_yuv420(self, img_data, x, y, width, height, rowstrides): #import time #before=time.time() # OpenGL begin if not self.gldrawable.gl_begin(self.glcontext): log.error("OUCH") return False # Upload texture if self.textures[0] == 0: self.textures = glGenTextures(3) glEnable(GL_FRAGMENT_PROGRAM_ARB) if not self.yuv420_shader: self.yuv420_shader = [1] glGenProgramsARB(1, self.yuv420_shader) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv420_shader[0]) # The following fragprog is: # * MIT X11 license, Copyright (c) 2007 by: # * Michael Dominic K. <*****@*****.**> #http://www.mdk.org.pl/2007/11/17/gl-colorspace-conversions prog = """!!ARBfp1.0 # cgc version 3.1.0010, build date Feb 10 2012 # command line args: -profile arbfp1 # source file: yuv.cg #vendor NVIDIA Corporation #version 3.1.0.10 #profile arbfp1 #program main #semantic main.IN #var float2 IN.texcoord1 : $vin.TEXCOORD0 : TEX0 : 0 : 1 #var float2 IN.texcoord2 : $vin.TEXCOORD1 : TEX1 : 0 : 1 #var float2 IN.texcoord3 : $vin.TEXCOORD2 : TEX2 : 0 : 1 #var samplerRECT IN.texture1 : TEXUNIT0 : texunit 0 : 0 : 1 #var samplerRECT IN.texture2 : TEXUNIT1 : texunit 1 : 0 : 1 #var samplerRECT IN.texture3 : TEXUNIT2 : texunit 2 : 0 : 1 #var float4 IN.color : $vin.COLOR0 : COL0 : 0 : 1 #var float4 main.color : $vout.COLOR0 : COL : -1 : 1 #const c[0] = 1.1643835 2.017231 0 0.5 #const c[1] = 0.0625 1.1643835 -0.3917616 -0.81296802 #const c[2] = 1.1643835 0 1.5960271 PARAM c[3] = { { 1.1643835, 2.017231, 0, 0.5 }, { 0.0625, 1.1643835, -0.3917616, -0.81296802 }, { 1.1643835, 0, 1.5960271 } }; TEMP R0; TEMP R1; TEX R0.x, fragment.texcoord[2], texture[2], RECT; ADD R1.z, R0.x, -c[0].w; TEX R1.x, fragment.texcoord[0], texture[0], RECT; TEX R0.x, fragment.texcoord[1], texture[1], RECT; ADD R1.x, R1, -c[1]; ADD R1.y, R0.x, -c[0].w; DP3 result.color.z, R1, c[0]; DP3 result.color.y, R1, c[1].yzww; DP3 result.color.x, R1, c[2]; MOV result.color.w, fragment.color.primary; END # 10 instructions, 2 R-regs """ glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(prog), prog) log.error(glGetString(GL_PROGRAM_ERROR_STRING_ARB)) glEnable(GL_FRAGMENT_PROGRAM_ARB) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.yuv420_shader[0]) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[0]) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[0]) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[1]) glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[1]) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width / 2, height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[1]) glActiveTexture(GL_TEXTURE2) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[2]) glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstrides[2]) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_LUMINANCE, width / 2, height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, img_data[2]) vtxarrays = 0 if vtxarrays == 1: texcoords = [[0, 0], [0, height], [width, height], [width, 0]] vtxcoords = texcoords texcoords_half = [[0, 0], [0, height / 2], [width / 2, height / 2], [width / 2, 0]] glVertexPointeri(vtxcoords) glActiveTexture(GL_TEXTURE0) glClientActiveTexture(GL_TEXTURE0) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glTexCoordPointeri(texcoords) glActiveTexture(GL_TEXTURE1) glClientActiveTexture(GL_TEXTURE1) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glTexCoordPointeri(texcoords_half) glActiveTexture(GL_TEXTURE2) glClientActiveTexture(GL_TEXTURE2) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glTexCoordPointeri(texcoords_half) glDrawArrays(GL_QUADS, 0, 4) else: glBegin(GL_QUADS) glMultiTexCoord2i(GL_TEXTURE0, 0, 0) glMultiTexCoord2i(GL_TEXTURE1, 0, 0) glMultiTexCoord2i(GL_TEXTURE2, 0, 0) glVertex2i(0, 0) glMultiTexCoord2i(GL_TEXTURE0, 0, height) glMultiTexCoord2i(GL_TEXTURE1, 0, height / 2) glMultiTexCoord2i(GL_TEXTURE2, 0, height / 2) glVertex2i(0, height) glMultiTexCoord2i(GL_TEXTURE0, width, height) glMultiTexCoord2i(GL_TEXTURE1, width / 2, height / 2) glMultiTexCoord2i(GL_TEXTURE2, width / 2, height / 2) glVertex2i(width, height) glMultiTexCoord2i(GL_TEXTURE0, width, 0) glMultiTexCoord2i(GL_TEXTURE1, width / 2, 0) glMultiTexCoord2i(GL_TEXTURE2, width / 2, 0) glVertex2i(width, 0) glEnd() # OpenGL end #self.gldrawable.swap_buffers() # self.gldrawable.swap_buffers() glFinish() self.gldrawable.gl_end()
def get_gl_info_string(glpane): # grantham 20051129 """ Return a string containing some useful information about the OpenGL implementation. Use the GL context from the given QGLWidget glpane (by calling glpane.makeCurrent()). """ glpane.makeCurrent() #bruce 070308 added glpane arg and makeCurrent call gl_info_string = '' gl_info_string += 'GL_VENDOR : "%s"\n' % glGetString(GL_VENDOR) gl_info_string += 'GL_VERSION : "%s"\n' % glGetString(GL_VERSION) gl_info_string += 'GL_RENDERER : "%s"\n' % glGetString(GL_RENDERER) gl_extensions = glGetString(GL_EXTENSIONS) gl_extensions = gl_extensions.strip() gl_extensions = gl_extensions.replace(" ", "\n* ") gl_info_string += 'GL_EXTENSIONS : \n* %s\n' % gl_extensions if debug_pref("Graphics Card Info: call glAreTexturesResident?", Choice_boolean_False): # Give a practical indication of how much video memory is available. # Should also do this with VBOs. # I'm pretty sure this code is right, but PyOpenGL seg faults in # glAreTexturesResident, so it's disabled until I can figure that # out. [grantham] [bruce 070308 added the debug_pref] all_tex_in = True tex_bytes = '\0' * (512 * 512 * 4) tex_names = [] tex_count = 0 tex_names = glGenTextures(1024) glEnable(GL_TEXTURE_2D) while all_tex_in: glBindTexture(GL_TEXTURE_2D, tex_names[tex_count]) gluBuild2DMipmaps(GL_TEXTURE_2D, 4, 512, 512, GL_RGBA, GL_UNSIGNED_BYTE, tex_bytes) tex_count += 1 glTexCoord2f(0.0, 0.0) glBegin(GL_QUADS) glVertex2f(0.0, 0.0) glVertex2f(1.0, 0.0) glVertex2f(1.0, 1.0) glVertex2f(0.0, 1.0) glEnd() glFinish() residences = glAreTexturesResident(tex_names[:tex_count]) all_tex_in = reduce(lambda a, b: a and b, residences) # bruce 070308 sees this exception from this line: # TypeError: reduce() arg 2 must support iteration glDisable(GL_TEXTURE_2D) glDeleteTextures(tex_names) gl_info_string += "Could create %d 512x512 RGBA resident textures\n" \ % tex_count pass if True: ## or could be a debug_pref("Graphics Card Info: get all GL_MAX symbols?") #bruce 090314 new feature import OpenGL.GL symbols = [x for x in dir(OpenGL.GL) if x.startswith('GL_MAX_')] symbols.sort() gl_info_string += '\n' for symbol in symbols: try: numeric_symbol = getattr(OpenGL.GL, symbol) intval = glGetInteger(numeric_symbol) except: # this happens to most symbols, not sure why if debug_flags.atom_debug: print_compact_traceback("%s = ??: " % symbol) # overkill, only the exception itself matters # typical output (on Bruce's MacBookPro, 090314): ## GL_MAX_4D_TEXTURE_SIZE_SGIS = ??: ## <type 'exceptions.KeyError'>: ## ('Unknown specifier GL_MAX_4D_TEXTURE_SIZE_SGIS (33080)', ## 'Failure in cConverter <OpenGL.converters.SizedOutput object at 0x1457fab0>', ## [GL_MAX_4D_TEXTURE_SIZE_SGIS], 1, <OpenGL.wrapper.glGetIntegerv object at 0x1458aa30>) ## [graphics_card_info.py:122] [wrapper.py:676] [converters.py:195] [converters.py:234] pass pass ## gl_info_string += "%s = ??\n" % symbol else: gl_info_string += "%s = %r\n" % (symbol, intval) continue pass return gl_info_string
if not OpenWindow(1400, 800, 0, 0, 0, 0, 32, 0, WINDOW): print "OpenWindow failed" Terminate() sys.exit(-1) # Every time a key on the keyboard is clicked # call our callback function SetKeyCallback(key_callback) SetWindowTitle("Modern opengl example") Enable(AUTO_POLL_EVENTS) # If everything went well the following calls # will display the version of opengl being used print 'Vendor: %s' % (glGetString(GL_VENDOR)) print 'Opengl version: %s' % (glGetString(GL_VERSION)) print 'GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION)) print 'Renderer: %s' % (glGetString(GL_RENDERER)) glClearColor(0.95, 1.0, 0.95, 0) # Lets compile our shaders since the use of shaders is now # mandatory. We need at least a vertex and fragment shader # begore we can draw anything program = ShaderProgram(fragment=fragment, vertex=vertex) # Lets create a VAO and bind it # Think of VAO's as object that encapsulate buffer state # Using a VAO enables you to cut down on calls in your draw # loop which generally makes things run faster
def gl_init(self): drawable = self.gl_begin() w, h = self.size debug("%s.gl_init() GL Pixmap backing size: %d x %d, drawable=%s", self, w, h, drawable) if not drawable: return None if not self.gl_setup: #ensure python knows which scope we're talking about: global glInitStringMarkerGREMEDY, glStringMarkerGREMEDY global glInitFrameTerminatorGREMEDY, glFrameTerminatorGREMEDY # Ask GL to send us all debug messages if GL_DEBUG_OUTPUT and gl_debug_callback and glInitDebugKHR() == True: glEnable(GL_DEBUG_OUTPUT) glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS) glDebugMessageCallback(gl_debug_callback, None) glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, None, GL_TRUE) # Initialize string_marker GL debugging extension if available if glInitStringMarkerGREMEDY and glInitStringMarkerGREMEDY() == True: log.info("Extension GL_GREMEDY_string_marker available. Will output detailed information about each frame.") else: # General case - running without debugger, extension not available glStringMarkerGREMEDY = None #don't bother trying again for another window: glInitStringMarkerGREMEDY = None # Initialize frame_terminator GL debugging extension if available if glInitFrameTerminatorGREMEDY and glInitFrameTerminatorGREMEDY() == True: log.info("Enabling GL frame terminator debugging.") else: glFrameTerminatorGREMEDY = None #don't bother trying again for another window: glInitFrameTerminatorGREMEDY = None self.gl_marker("Initializing GL context for window size %d x %d" % (w, h)) # Initialize viewport and matrices for 2D rendering glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, w, h, 0.0, -1.0, 1.0) glMatrixMode(GL_MODELVIEW) #TODO glEnableClientState(GL_VERTEX_ARRAY) #TODO glEnableClientState(GL_TEXTURE_COORD_ARRAY) # Clear to white glClearColor(1.0, 1.0, 1.0, 1.0) # Default state is good for YUV painting: # - fragment program enabled # - YUV fragment program bound # - render to offscreen FBO glEnable(GL_FRAGMENT_PROGRAM_ARB) if self.textures is None: self.textures = glGenTextures(5) debug("%s.gl_init() textures of size %s : %s", self, self.size, self.textures) if self.offscreen_fbo is None: self.offscreen_fbo = glGenFramebuffers(1) # Define empty FBO texture and set rendering to FBO glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) # nvidia needs this even though we don't use mipmaps (repeated through this file): glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, None) glBindFramebuffer(GL_FRAMEBUFFER, self.offscreen_fbo) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glClear(GL_COLOR_BUFFER_BIT) # Create and assign fragment programs if not self.shaders: self.shaders = [ 1, 2 ] glGenProgramsARB(2, self.shaders) for progid, progstr in ((0, YUV2RGB_shader), (1, RGBP2RGB_shader)): glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[progid]) glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, len(progstr), progstr) err = glGetString(GL_PROGRAM_ERROR_STRING_ARB) if err: #FIXME: maybe we should do something else here? log.error(err) # Bind program 0 for YUV painting by default glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[0]) self.gl_setup = True return drawable
def main(): pg.init() display = (1680, 1050) pg.display.set_mode(display, DOUBLEBUF|OPENGL) # If everything went well the following calls # will display the version of opengl being used print('Vendor: %s' % (glGetString(GL_VENDOR))) print('Opengl version: %s' % (glGetString(GL_VERSION))) print('GLSL Version: %s' % (glGetString(GL_SHADING_LANGUAGE_VERSION))) print('Renderer: %s' % (glGetString(GL_RENDERER))) glClearColor(0.95, 1.0, 0.95, 0) # Lets compile our shaders since the use of shaders is now # mandatory. We need at least a vertex and fragment shader # begore we can draw anything program = ShaderProgram(fragment=fragment, vertex=vertex) # Lets create a VAO and bind it # Think of VAO's as object that encapsulate buffer state # Using a VAO enables you to cut down on calls in your draw # loop which generally makes things run faster vao_id = glGenVertexArrays(1) glBindVertexArray(vao_id) # Lets create our Vertex Buffer objects - these are the buffers # that will contain our per vertex data vbo_id = glGenBuffers(2) # Bind a buffer before we can use it glBindBuffer(GL_ARRAY_BUFFER, vbo_id[0]) # Now go ahead and fill this bound buffer with some data glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(vertex_data), vertex_data, GL_STATIC_DRAW) # Now specify how the shader program will be receiving this data # In this case the data from this buffer will be available in the shader as the vin_position vertex attribute glVertexAttribPointer(program.attribute_location('vin_position'), 3, GL_FLOAT, GL_FALSE, 0, None) # Turn on this vertex attribute in the shader glEnableVertexAttribArray(0) # Now do the same for the other vertex buffer glBindBuffer(GL_ARRAY_BUFFER, vbo_id[1]) glBufferData(GL_ARRAY_BUFFER, ArrayDatatype.arrayByteCount(color_data), color_data, GL_STATIC_DRAW) glVertexAttribPointer(program.attribute_location('vin_color'), 3, GL_FLOAT, GL_FALSE, 0, None) glEnableVertexAttribArray(1) # Lets unbind our vbo and vao state # We will bind these again in the draw loop glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) while True: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() quit() glClear(GL_COLOR_BUFFER_BIT) # Specify shader to be used glUseProgram(program.program_id) # Bind VAO - this will automatically # bind all the vbo's saving us a bunch # of calls glBindVertexArray(vao_id) # Modern GL makes the draw call really simple # All the complexity has been pushed elsewhere glDrawArrays(GL_TRIANGLES, 0, 3) # Lets unbind the shader and vertex array state glUseProgram(0) glBindVertexArray(0) # Now lets show our master piece on the screen pg.display.flip() pg.time.wait(10)
def do_check_GL_support(force_enable): props = {} try: #log redirection: def redirect_log(logger_name): logger = logging.getLogger(logger_name) assert logger is not None logger.saved_handlers = logger.handlers logger.saved_propagate = logger.propagate logger.handlers = [CaptureHandler()] logger.propagate = 0 return logger fhlogger = redirect_log('OpenGL.formathandler') elogger = redirect_log('OpenGL.extensions') alogger = redirect_log('OpenGL.acceleratesupport') arlogger = redirect_log('OpenGL.arrays') clogger = redirect_log('OpenGL.converters') import OpenGL props["pyopengl"] = OpenGL.__version__ from OpenGL.GL import GL_VERSION, GL_EXTENSIONS from OpenGL.GL import glGetString, glGetInteger, glGetIntegerv gl_version_str = glGetString(GL_VERSION) if gl_version_str is None: gl_check_error("OpenGL version is missing - cannot continue") return {} gl_major = int(gl_version_str[0]) gl_minor = int(gl_version_str[2]) props["opengl"] = gl_major, gl_minor MIN_VERSION = (1,1) if (gl_major, gl_minor) < MIN_VERSION: gl_check_error("OpenGL output requires version %s or greater, not %s.%s" % (".".join([str(x) for x in MIN_VERSION]), gl_major, gl_minor)) else: log("found valid OpenGL version: %s.%s", gl_major, gl_minor) from OpenGL import version as OpenGL_version pyopengl_version = OpenGL_version.__version__ try: import OpenGL_accelerate accel_version = OpenGL_accelerate.__version__ props["accelerate"] = accel_version log("OpenGL_accelerate version %s", accel_version) except: log("OpenGL_accelerate not found") OpenGL_accelerate = None accel_version = None if accel_version is not None and pyopengl_version!=accel_version: global _version_warning_shown if not _version_warning_shown: log.warn("Warning: version mismatch between PyOpenGL and PyOpenGL-accelerate") log.warn(" this may cause crashes") _version_warning_shown = True vsplit = pyopengl_version.split('.') #we now require PyOpenGL 3.1 or later if vsplit[:2]<['3','1'] and not force_enable: gl_check_error("PyOpenGL version 3.1 or later is required (found version %s)" % pyopengl_version) return {} props["zerocopy"] = bool(OpenGL_accelerate) and is_pyopengl_memoryview_safe(pyopengl_version, accel_version) try: extensions = glGetString(GL_EXTENSIONS).decode().split(" ") except: log("error querying extensions", exc_info=True) extensions = [] gl_check_error("OpenGL could not find the list of GL extensions - does the graphics driver support OpenGL?") log("OpenGL extensions found: %s", ", ".join(extensions)) props["extensions"] = extensions from OpenGL.arrays.arraydatatype import ArrayDatatype try: log("found the following array handlers: %s", set(ArrayDatatype.getRegistry().values())) except: pass from OpenGL.GL import GL_RENDERER, GL_VENDOR, GL_SHADING_LANGUAGE_VERSION def fixstring(v): try: return str(v).strip() except: return str(v) for d,s,fatal in (("vendor", GL_VENDOR, True), ("renderer", GL_RENDERER, True), ("shading language version", GL_SHADING_LANGUAGE_VERSION, False)): try: v = glGetString(s) v = fixstring(v.decode()) log("%s: %s", d, v) except: if fatal: gl_check_error("OpenGL property '%s' is missing" % d) else: log("OpenGL property '%s' is missing", d) v = "" props[d] = v vendor = props["vendor"] version_req = VERSION_REQ.get(vendor) if version_req: req_maj, req_min = version_req if gl_major<req_maj or (gl_major==req_maj and gl_minor<req_min): if force_enable: log.warn("Warning: '%s' OpenGL driver requires version %i.%i", vendor, req_maj, req_min) log.warn(" version %i.%i was found", gl_major, gl_minor) else: gl_check_error("OpenGL version %i.%i is too old, %i.%i is required for %s" % (gl_major, gl_minor, req_maj, req_min, vendor)) from OpenGL.GLU import gluGetString, GLU_VERSION, GLU_EXTENSIONS for d,s in {"GLU version": GLU_VERSION, "GLU extensions":GLU_EXTENSIONS}.items(): v = gluGetString(s) v = v.decode() log("%s: %s", d, v) props[d] = v blacklisted = None whitelisted = None greylisted = None for k,vlist in BLACKLIST.items(): v = props.get(k) if v in vlist: log("%s '%s' found in blacklist: %s", k, v, vlist) blacklisted = k, v for k,vlist in GREYLIST.items(): v = props.get(k) if v in vlist: log("%s '%s' found in greylist: %s", k, v, vlist) greylisted = k, v for k,vlist in WHITELIST.items(): v = props.get(k) if v in vlist: log("%s '%s' found in whitelist: %s", k, v, vlist) whitelisted = k, v if blacklisted: if whitelisted: log.info("%s '%s' enabled (found in both blacklist and whitelist)", *whitelisted) elif force_enable: log.warn("Warning: %s '%s' is blacklisted!", *blacklisted) else: gl_check_error("%s '%s' is blacklisted!" % (blacklisted)) safe = bool(whitelisted) or not (bool(greylisted) or bool(blacklisted)) if safe and sys.version_info[0]>2: log.warn("Warning: OpenGL python3 support is not enabled by default") safe = False props["safe"] = safe #check for specific functions we need: from OpenGL.GL import glActiveTexture, glTexSubImage2D, glTexCoord2i, \ glViewport, glMatrixMode, glLoadIdentity, glOrtho, \ glEnableClientState, glGenTextures, glDisable, \ glBindTexture, glPixelStorei, glEnable, glBegin, glFlush, \ glTexParameteri, glTexEnvi, glHint, glBlendFunc, glLineStipple, \ glTexImage2D, \ glMultiTexCoord2i, \ glVertex2i, glEnd check_functions(glActiveTexture, glTexSubImage2D, glTexCoord2i, \ glViewport, glMatrixMode, glLoadIdentity, glOrtho, \ glEnableClientState, glGenTextures, glDisable, \ glBindTexture, glPixelStorei, glEnable, glBegin, glFlush, \ glTexParameteri, glTexEnvi, glHint, glBlendFunc, glLineStipple, \ glTexImage2D, \ glMultiTexCoord2i, \ glVertex2i, glEnd) glEnablei = None try: from OpenGL.GL import glEnablei except: pass if not bool(glEnablei): log.warn("OpenGL glEnablei is not available, disabling transparency") global GL_ALPHA_SUPPORTED GL_ALPHA_SUPPORTED = False props["transparency"] = GL_ALPHA_SUPPORTED #check for framebuffer functions we need: from OpenGL.GL.ARB.framebuffer_object import GL_FRAMEBUFFER, \ GL_COLOR_ATTACHMENT0, glGenFramebuffers, glBindFramebuffer, glFramebufferTexture2D check_functions(GL_FRAMEBUFFER, \ GL_COLOR_ATTACHMENT0, glGenFramebuffers, glBindFramebuffer, glFramebufferTexture2D) for ext in required_extensions: if ext not in extensions: gl_check_error("OpenGL driver lacks support for extension: %s" % ext) else: log("Extension %s is present", ext) #this allows us to do CSC via OpenGL: #see http://www.opengl.org/registry/specs/ARB/fragment_program.txt from OpenGL.GL.ARB.fragment_program import glInitFragmentProgramARB if not glInitFragmentProgramARB(): gl_check_error("OpenGL output requires glInitFragmentProgramARB") else: log("glInitFragmentProgramARB works") from OpenGL.GL.ARB.texture_rectangle import glInitTextureRectangleARB if not glInitTextureRectangleARB(): gl_check_error("OpenGL output requires glInitTextureRectangleARB") else: log("glInitTextureRectangleARB works") from OpenGL.GL.ARB.vertex_program import glGenProgramsARB, glDeleteProgramsARB, \ glBindProgramARB, glProgramStringARB check_functions(glGenProgramsARB, glDeleteProgramsARB, glBindProgramARB, glProgramStringARB) try: from OpenGL.GL import GL_MAX_TEXTURE_SIZE texture_size = glGetInteger(GL_MAX_TEXTURE_SIZE) #this one may be missing? rect_texture_size = texture_size try: from OpenGL.GL import GL_MAX_RECTANGLE_TEXTURE_SIZE rect_texture_size = glGetInteger(GL_MAX_RECTANGLE_TEXTURE_SIZE) except ImportError as e: log("OpenGL: %s", e) log("using GL_MAX_TEXTURE_SIZE=%s as default", texture_size) except Exception as e: emsg = str(e) if hasattr(e, "description"): emsg = e.description gl_check_error("unable to query max texture size: %s" % emsg) return props log("Texture size GL_MAX_RECTANGLE_TEXTURE_SIZE=%s, GL_MAX_TEXTURE_SIZE=%s", rect_texture_size, texture_size) texture_size_limit = min(rect_texture_size, texture_size) props["texture-size-limit"] = texture_size_limit try: from OpenGL.GL import GL_MAX_VIEWPORT_DIMS v = glGetIntegerv(GL_MAX_VIEWPORT_DIMS) max_viewport_dims = v[0], v[1] assert max_viewport_dims[0]>=texture_size_limit and max_viewport_dims[1]>=texture_size_limit log("GL_MAX_VIEWPORT_DIMS=%s", max_viewport_dims) except ImportError as e: log.error("Error querying max viewport dims: %s", e) max_viewport_dims = texture_size_limit, texture_size_limit props["max-viewport-dims"] = max_viewport_dims return props finally: for x in alogger.handlers[0].records: #strip default message prefix: msg = x.getMessage().replace("No OpenGL_accelerate module loaded: ", "") if msg=="No module named OpenGL_accelerate": msg = "missing accelerate module" if msg!="OpenGL_accelerate module loaded": msg = "PyOpenGL warning: %s" % msg log.info(msg) #format handler messages: STRIP_LOG_MESSAGE = "Unable to load registered array format handler " missing_handlers = [] for x in fhlogger.handlers[0].records: msg = x.getMessage() p = msg.find(STRIP_LOG_MESSAGE) if p<0: #unknown message, log it: log.info(msg) continue format_handler = msg[p+len(STRIP_LOG_MESSAGE):] p = format_handler.find(":") if p>0: format_handler = format_handler[:p] missing_handlers.append(format_handler) if len(missing_handlers)>0: log.warn("PyOpenGL warning: missing array format handlers: %s", ", ".join(missing_handlers)) for x in elogger.handlers[0].records: msg = x.getMessage() #ignore extension messages: p = msg.startswith("GL Extension ") and msg.endswith("available") if not p: log.info(msg) missing_accelerators = [] STRIP_AR_HEAD = "Unable to load" STRIP_AR_TAIL = "from OpenGL_accelerate" for x in arlogger.handlers[0].records+clogger.handlers[0].records: msg = x.getMessage() if msg.startswith(STRIP_AR_HEAD) and msg.endswith(STRIP_AR_TAIL): m = msg[len(STRIP_AR_HEAD):-len(STRIP_AR_TAIL)].strip() m = m.replace("accelerators", "").replace("accelerator", "").strip() missing_accelerators.append(m) continue elif msg.startswith("Using accelerated"): log(msg) else: log.info(msg) if missing_accelerators: log.info("OpenGL accelerate missing: %s", ", ".join(missing_accelerators)) def restore_logger(logger): logger.handlers = logger.saved_handlers logger.propagate = logger.saved_propagate restore_logger(fhlogger) restore_logger(elogger) restore_logger(alogger) restore_logger(arlogger) restore_logger(clogger)
def show_glsl_version(): version = glGetString( GL_SHADING_LANGUAGE_VERSION ) version = version.split(as_8_bit(' '))[0] version = [int(x) for x in version.split(as_8_bit('.'))[:2]] return version
if t[0] == 'b': value = glGetBooleanv(id) if operator.isSequence(value): value = map(_boolean, value) else: value = _boolean(value) elif t[0] == 'i': value = glGetIntegerv(id) elif t[0] == 'd': value = glGetDoublev(id) elif t[0] == 'e': if len(t) > 1: if t[1] == 'u': x = gluGetString(id) else: x = glGetString(id) else: x = id x = string.split(x) x.sort() y = [] for ext in x: try: __import__('OpenGL.' + string.replace(ext, '_', '.', 2), globals(), locals(), ['*']) y.append('<b>%s</b>' % ext) except ImportError: y.append(ext) value = string.join(y, '<br>') else: if len(t) > 1: if t[1] == 'u':
def check_GL_support(gldrawable, glcontext, min_texture_size=0, force_enable=False): if not gldrawable.gl_begin(glcontext): raise ImportError("gl_begin failed on %s" % gldrawable) props = {} try: if SILENCE_FORMAT_HANDLER_LOGGER: debug("silencing formathandler warnings") logging.getLogger('OpenGL.formathandler').setLevel(logging.WARN) import OpenGL props["pyopengl"] = OpenGL.__version__ from OpenGL.GL import GL_VERSION, GL_EXTENSIONS from OpenGL.GL import glGetString, glGetInteger gl_version_str = glGetString(GL_VERSION) if gl_version_str is None: gl_check_error("OpenGL version is missing - cannot continue") return {} gl_major = int(gl_version_str[0]) gl_minor = int(gl_version_str[2]) props["opengl"] = gl_major, gl_minor MIN_VERSION = (1,1) if (gl_major, gl_minor) < MIN_VERSION: gl_check_error("OpenGL output requires version %s or greater, not %s.%s" % (".".join([str(x) for x in MIN_VERSION]), gl_major, gl_minor)) else: debug("found valid OpenGL version: %s.%s", gl_major, gl_minor) try: extensions = glGetString(GL_EXTENSIONS).split(" ") except: gl_check_error("OpenGL could not find the list of GL extensions - does the graphics driver support OpenGL?") debug("OpenGL extensions found: %s", ", ".join(extensions)) props["extensions"] = extensions from OpenGL.arrays.arraydatatype import ArrayDatatype try: debug("found the following array handlers: %s", set(ArrayDatatype.getRegistry().values())) except: pass from OpenGL.GL import GL_RENDERER, GL_VENDOR, GL_SHADING_LANGUAGE_VERSION for d,s,fatal in (("vendor", GL_VENDOR, True), ("renderer", GL_RENDERER, True), ("shading language version", GL_SHADING_LANGUAGE_VERSION, False)): try: v = glGetString(s) debug("%s: %s", d, v) except: if fatal: gl_check_error("OpenGL property '%s' is missing" % d) else: log.warn("OpenGL property '%s' is missing" % d) v = "" props[d] = v from OpenGL.GLU import gluGetString, GLU_VERSION, GLU_EXTENSIONS for d,s in {"GLU version": GLU_VERSION, "GLU extensions":GLU_EXTENSIONS}.items(): v = gluGetString(s) debug("%s: %s", d, v) props[d] = v for k,vlist in BLACKLIST.items(): v = props.get(k) if v in vlist: if force_enable: log.warn("Warning: %s '%s' is blacklisted!", k, v) else: gl_check_error("%s '%s' is blacklisted!" % (k, v)) #check for specific functions we need: from OpenGL.GL import glActiveTexture, glTexSubImage2D, glTexCoord2i, \ glViewport, glMatrixMode, glLoadIdentity, glOrtho, \ glEnableClientState, glGenTextures, glDisable, \ glBindTexture, glPixelStorei, glEnable, glBegin, glFlush, \ glTexParameteri, \ glTexImage2D, \ glMultiTexCoord2i, \ glVertex2i, glEnd check_functions(glActiveTexture, glTexSubImage2D, glTexCoord2i, \ glViewport, glMatrixMode, glLoadIdentity, glOrtho, \ glEnableClientState, glGenTextures, glDisable, \ glBindTexture, glPixelStorei, glEnable, glBegin, glFlush, \ glTexParameteri, \ glTexImage2D, \ glMultiTexCoord2i, \ glVertex2i, glEnd) #check for framebuffer functions we need: from OpenGL.GL.ARB.framebuffer_object import GL_FRAMEBUFFER, \ GL_COLOR_ATTACHMENT0, glGenFramebuffers, glBindFramebuffer, glFramebufferTexture2D check_functions(GL_FRAMEBUFFER, \ GL_COLOR_ATTACHMENT0, glGenFramebuffers, glBindFramebuffer, glFramebufferTexture2D) for ext in required_extensions: if ext not in extensions: gl_check_error("OpenGL driver lacks support for extension: %s" % ext) else: debug("Extension %s is present", ext) #this allows us to do CSC via OpenGL: #see http://www.opengl.org/registry/specs/ARB/fragment_program.txt from OpenGL.GL.ARB.fragment_program import glInitFragmentProgramARB if not glInitFragmentProgramARB(): gl_check_error("OpenGL output requires glInitFragmentProgramARB") else: debug("glInitFragmentProgramARB works") from OpenGL.GL.ARB.texture_rectangle import glInitTextureRectangleARB if not glInitTextureRectangleARB(): gl_check_error("OpenGL output requires glInitTextureRectangleARB") else: debug("glInitTextureRectangleARB works") from OpenGL.GL.ARB.vertex_program import glGenProgramsARB, glDeleteProgramsARB, \ glBindProgramARB, glProgramStringARB check_functions(glGenProgramsARB, glDeleteProgramsARB, glBindProgramARB, glProgramStringARB) from OpenGL.GL import GL_MAX_RECTANGLE_TEXTURE_SIZE, GL_MAX_TEXTURE_SIZE texture_size = glGetInteger(GL_MAX_TEXTURE_SIZE) rect_texture_size = glGetInteger(GL_MAX_RECTANGLE_TEXTURE_SIZE) if min_texture_size>texture_size or min_texture_size>rect_texture_size: gl_check_error("The texture size is too small: %s" % texture_size) else: debug("Texture size GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB=%s, GL_MAX_TEXTURE_SIZE=%s", rect_texture_size, texture_size) return props finally: if SILENCE_FORMAT_HANDLER_LOGGER: try: logging.getLogger('OpenGL.formathandler').setLevel(logging.INFO) except: pass gldrawable.gl_end()
glVertex2i, glEnd from OpenGL.GL.ARB.vertex_program import glGenProgramsARB, glBindProgramARB, glProgramStringARB from OpenGL.GL.ARB.fragment_program import glInitFragmentProgramARB from xpra.gl_colorspace_conversions import GL_COLORSPACE_CONVERSIONS #sanity checks: OpenGL version try: from gtk import gdk glconfig = gtk.gdkgl.Config(mode=gtk.gdkgl.MODE_RGB|gtk.gdkgl.MODE_SINGLE) glext = gtk.gdkgl.ext(gdk.Pixmap(gdk.get_default_root_window(), 1, 1)) gldrawable = glext.set_gl_capability(glconfig) glcontext = gtk.gdkgl.Context(gldrawable, direct=True) if not gldrawable.gl_begin(glcontext): raise ImportError("gl_begin failed on %s" % gldrawable) try: gl_major = int(glGetString(GL_VERSION)[0]) gl_minor = int(glGetString(GL_VERSION)[2]) if gl_major<=1 and gl_minor<1: raise ImportError("** OpenGL output requires OpenGL version 1.1 or greater, not %s.%s" % (gl_major, gl_minor)) log.info("found valid OpenGL: %s.%s", gl_major, gl_minor) #this allows us to do CSC via OpenGL: #see http://www.opengl.org/registry/specs/ARB/fragment_program.txt use_openGL_CSC = glInitFragmentProgramARB() finally: gldrawable.gl_end() del glcontext, gldrawable, glext, glconfig except Exception, e: raise ImportError("** OpenGL initialization error: %s" % e)