def get_input(get_what): textInput = '' gl.glClearColor(0,0,0,1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) stim_display.refresh() simple_wait(0.500) my_text = get_what+textInput drawText( my_text , instruction_font , stim_display_res[0] , xLoc=stim_display_res[0]/2 , yLoc=stim_display_res[1]/2 , fg=[200,200,200,255] ) stim_display.refresh() done = False while not done: if not stamper_child.qFrom.empty(): event = stamper_child.qFrom.get() if event['type'] == 'key' : response = event['value'] if response=='q': exit_safely() elif response == 'backspace': if textInput!='': textInput = textInput[0:(len(textInput)-1)] my_text = get_what+textInput drawText( my_text , instruction_font , stim_display_res[0] , xLoc=stim_display_res[0]/2 , yLoc=stim_display_res[1]/2 , fg=[200,200,200,255] ) stim_display.refresh() elif response == 'return': done = True else: textInput = textInput + response my_text = get_what+textInput drawText( my_text , instruction_font , stim_display_res[0] , xLoc=stim_display_res[0]/2 , yLoc=stim_display_res[1]/2 , fg=[200,200,200,255] ) stim_display.refresh() stim_display.refresh() return textInput
def cleanup_gl(self): GL.glDeleteTextures(numpy.array([self.trace_map, self.font_atlas] + [self.textures[column][row] for column in self.textures for row in self.textures[column]], 'uint32')) self.textures = {}
def glLight(self,onoff): """Toggle lights on/off.""" if onoff: self.glLightSpec() GL.glEnable(GL.GL_LIGHTING) else: GL.glDisable(GL.GL_LIGHTING)
def display(self): now = time.time() timedelt = now-self.timestamp self.timestamp = now self.current_fps = 1.0/timedelt hid_js.read_js(self.camera) view = self.camera.matrix() # updating shared variables in shader data block. Also see # timer() self.shader_data_block.map() self.shader_data_block.set('u_view', view) self.shader_data_block.set("camera_position", np.array(self.camera.loc, dtype=np.float32)) self.light_count += 1 if self.light_count == 2: self.light_count = 0 self.lights = self.get_lights() self.shader_data_block.set("light_diffuse", np.array(self.lights, dtype=np.float32)) self.shader_data_block.unmap() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) for drawable in self.drawables: drawable.draw() glut.glutSwapBuffers()
def Resize( self, width, height ) : # Resize the viewport gl.glViewport( 0, 0, width, height ) # Resize the trackball self.trackball.Resize( width, height ) # Compute perspective projection matrix self.SetProjectionMatrix( width, height )
def drawGL(self,**kargs): GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPushMatrix() GL.glMultMatrixf(self.rot) self.actor.use_list() GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPopMatrix()
def drawGL(self, mode="wireframe", color=None): """Draw the text.""" ## if self.zoom: ## GD.canvas.zoom_2D(self.zoom) if self.color is not None: GL.glColor3fv(self.color) gluttext.glutDrawText(self.text, self.x, self.y, self.font, gravity=self.gravity)
def initializeGL(self, gls): self.gls = gls # Basic solid-color program self.prog = self.gls.shader_cache.get("vert2", "frag1") self.mat_loc = GL.glGetUniformLocation(self.prog, "mat") self.col_loc = GL.glGetUniformLocation(self.prog, "color") # Build a VBO for rendering square "drag-handles" self.vbo_handles_ar = numpy.ndarray(4, dtype=[("vertex", numpy.float32, 2)]) self.vbo_handles_ar["vertex"] = numpy.array(corners) * HANDLE_HALF_SIZE self.vbo_handles = VBO(self.vbo_handles_ar, GL.GL_STATIC_DRAW, GL.GL_ARRAY_BUFFER) self.vao_handles = VAO() with self.vbo_handles, self.vao_handles: vbobind(self.prog, self.vbo_handles_ar.dtype, "vertex").assign() # Build a VBO/VAO for the perimeter # We don't initialize it here because it is updated every render # 4 verticies for outside perimeter # 6 verticies for each dim self.vbo_per_dim_ar = numpy.zeros(16, dtype=[("vertex", numpy.float32, 2)]) self.vbo_per_dim = VBO(self.vbo_per_dim_ar, GL.GL_DYNAMIC_DRAW, GL.GL_ARRAY_BUFFER) self.vao_per_dim = VAO() with self.vao_per_dim, self.vbo_per_dim: vbobind(self.prog, self.vbo_per_dim_ar.dtype, "vertex").assign()
def on_key(self, *args): ESCAPE = '\033' if args[0] == ESCAPE or args[0] == 'q': os._exit(0) elif args[0] == 'r': self.rotate = [0., 0., 0.] self.translate = [0., 0., 0.] self.scale = 1.0 elif args[0] == 'l': if self.lights: self.lights = False else: self.lights = True elif args[0] == 's': try: from PIL import Image except: try: import Image except: raise ImportError("Cannot Find appropriate Image Library, for Saving") vp = GL.glGetIntegerv(GL.GL_VIEWPORT) pixel_array = GL.glReadPixels(0,0,vp[2],vp[3],GL.GL_RGB,GL.GL_UNSIGNED_BYTE) pilImage = Image.fromstring(mode="RGB",size=(vp[3],vp[2]),data=pixel_array) pilImage = pilImage.transpose(Image.FLIP_TOP_BOTTOM) pilImage.save(self.save_file + str(self.save_count) + '.png') self.save_count += 1
def drawGL(self,**kargs): GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPushMatrix() GL.glTranslate(*self.trl) self.actor.use_list() GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPopMatrix()
def resizeGL(self, w, h): h = 1 if h == 0 else h GL.glViewport(0, 0, w, h) self.projection.ratio = w / h self.widget_projection.right = w self.widget_projection.bottom = h self._screensize = m.Vector(w, h)
def drawGL(self,**kargs): """Draw the text.""" ## if self.zoom: ## pf.canvas.zoom_2D(self.zoom) if self.color is not None: GL.glColor3fv(self.color) gluttext.glutDrawText(self.text,self.x,self.y,font=self.font,gravity=self.gravity)
def load_textures(self): if self.gamecount() <= 1: # Make sure that this is always a list self.textures = gl.glGenTextures(2) else: self.textures = gl.glGenTextures(self.gamecount()) c = 0 for game in self.gamelist: textureSurface = game.getSurface() textureData = pygame.image.tostring(textureSurface, "RGBX", 1) gl.glBindTexture(gl.GL_TEXTURE_2D, self.textures[c]) gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, textureSurface.get_width(), textureSurface.get_height(), 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, textureData, ) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) c += 1
def draw(self,mode='wireframe',color=None): """Draw the text.""" self.count += 1 # GD.canvas.makeCurrent() if self.color is not None: GL.glColor3fv(self.color) GD.canvas.renderText(self.x,GD.canvas.height()-self.y,self.text,self.font)
def __setitem__(self, idxs, data): """Set the contents of the buffer. Currently, only :py:obj:`Ellipsis` is valid as an index. :param idxs: The indices to set. A new buffer will be created if :py:obj:`Ellipsis` is passed. :param data: The new contents of the buffer. If a :py:class:`numpy.ndarray` is passed, it will be used to initialize the buffer. If a :py:class:`numpy.dtype` is passed, the buffer will not be initialized. :type data: :py:class:`numpy.dtype` or :py:class:`numpy.ndarray` .. warning:: |buffer-bind| """ if idxs is Ellipsis: if isinstance(data, dtype): dt = data data = None else: dt = ( data.dtype if product(data.shape) == 1 else dtype((data.dtype, data.shape)) ) try: binding = next(iter(self.active_bindings)) except StopIteration: raise RuntimeError("Buffer data can only be set if it is bound.") GL.glBufferData(binding, dt.itemsize, data, self.usage) self.dtype = dt else: raise NotImplementedError("TODO: Allow changing replacing buffer dtypes.")
def flush(self): """Ensures changes are visible to GL for rendering. This has two actions depending on how the buffer was mapped. If it was mapped with :py:obj:`GL.GL_MAP_FLUSH_EXPLICIT_BIT` the buffer is flushed using :py:func:`GL.glFlushMappedBufferRange` Otherwise, a memory barrier is issued. This requires ``ARB_shader_image_load_store``. .. warning:: |buffer-bind| """ # FIXME: FLUSH_EXPLICIT_BIT is for flushing sub-ranges (no auto-flush at unmap?), so flush minimal region instead of whole mapped region try: binding = next(iter(self.gl_buffer.active_bindings)) except StopIteration: raise RuntimeError("Buffer mappings can only be flushed if the buffer is bound.") if self.access & GL.GL_MAP_FLUSH_EXPLICIT_BIT: length = self.dtype.itemsize * product(self.shape) GL.glFlushMappedBufferRange(binding, self.offset, length) else: GL.glMemoryBarrier(GL.GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT)
def timer(fps): global clock global data global phi, theta clock += 0.005 * 1000.0/fps # for scaling #loc = gl.glGetUniformLocation(program, "scale") #gl.glUniform1f(loc, (1+np.cos(clock))/2.0) loc = gl.glGetUniformLocation(program, "transform") # transform['transform'] = [ # (np.cos(clock),np.sin(clock),0,0), # (-np.sin(clock),np.cos(clock),0,0), # (0,0,1,0), (0,0,0,1) ] # gl.glUniformMatrix4fv(loc, 1, False, transform['transform']) # Rotate cube theta += 0.5 # degrees phi += 0.5 # degrees model = np.eye(4, dtype=np.float32) rotate(model, theta, 0, 0, 1) rotate(model, phi, 0, 1, 0) gl.glUniformMatrix4fv(loc, 1, False, model) glut.glutTimerFunc(1000/fps, timer, fps) glut.glutPostRedisplay()
def glutDrawText(text,x,y,font='hv18',gravity=''): """Draw the given text at given 2D position in window. If adjust == 'center', the text will be horizontally centered on the insertion point. If adjust == 'right', the text will be right aligned on the point. Any other setting will align the text left. Default is to center. """ # !!! Do not use GLUT.glutBitmapLength(font, text) width = glutBitmapLength(font, text) height = glutFontHeight(font) w2,h2 = 0.5*width,0.4*height x -= w2 y -= h2 if 'E' in gravity: x += w2 elif 'W' in gravity: x -= w2 if 'N' in gravity: y += h2 elif 'S' in gravity: y -= h2 GL.glRasterPos2f(float(x),float(y)); #GD.debug("RENDERING WITH FONT %s" % font) glutRenderText(text,font)
def setSize (self,w,h): if h == 0: # prevent divide by zero h = 1 GL.glViewport(0, 0, w, h) self.aspect = float(w)/h self.camera.setLens(aspect=self.aspect) self.display()
def _draw_legend(self): """ Draw the color scale legend. """ if not self._color_mode: return legend_height = self.height-self.padding_top-self.padding_bottom #draw each legend block block_height = float(legend_height)/LEGEND_NUM_BLOCKS x = self.width - self.padding_right + LEGEND_LEFT_PAD for i in range(LEGEND_NUM_BLOCKS): color = unpack_color(COLORS[self._color_mode][int(255*i/float(LEGEND_NUM_BLOCKS-1))]) GL.glColor4f(*numpy.array(color)/255.0) y = self.height - (i+1)*block_height - self.padding_bottom self._draw_rect(x, y, LEGEND_WIDTH, block_height) #draw rectangle around color scale border GL.glColor3f(*LEGEND_BORDER_COLOR_SPEC) self._draw_rect(x, self.padding_top, LEGEND_WIDTH, legend_height, fill=False) #draw each legend label label_spacing = float(legend_height)/(LEGEND_NUM_LABELS-1) x = self.width - (self.padding_right - LEGEND_LEFT_PAD - LEGEND_WIDTH)/2 for i in range(LEGEND_NUM_LABELS): proportion = i/float(LEGEND_NUM_LABELS-1) dB = proportion*(self._maximum - self._minimum) + self._minimum y = self.height - i*label_spacing - self.padding_bottom txt = gltext.Text('%ddB'%int(dB), font_size=LEGEND_FONT_SIZE, centered=True) txt.draw_text(wx.Point(x, y))
def setPerspectiveMode(): #just getting back out of orthographic mode GL.glMatrixMode(GL.GL_PROJECTION) GL.glPopMatrix() GL.glMatrixMode( GL.GL_MODELVIEW ) GL.glLoadIdentity() GL.glEnable(GL.GL_DEPTH_TEST)
def run(): hid_js.init_js() BoarGL.glbase.init_gl(sys.argv) print gl.glGetString(gl.GL_RENDERER) print gl.glGetString(gl.GL_VERSION) driver = SpecTree() driver.run()
def main_hack(): pygame.init() flags = pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE screen = pygame.display.set_mode((600, 600), flags) Shaders.Setup() wpl = WordPictureLoader() w = random.choice(wpl.all_words) w = 'ox' word = wpl.WordPictureForWord(w) print w glViewport(0, 0, 600, 600) clock = pygame.time.Clock() t = 0 while True: dt = clock.tick() #print clock for e in pygame.event.get(): if e.type == pygame.QUIT: return if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE: return t += dt / 1000. GL.glClear(GL.GL_COLOR_BUFFER_BIT) word.RenderSetup((1, 1, 1, 1), (2.0, 0.3, 0.3, 1.0), 600, 600) word.Render(t, -5) # t - 5.0) pygame.display.flip()
def setup(self): self.window = pyglet.window.Window(resizable=True) # glutInit(*sys.argv) glClearColor(*config.BACKGROUND_COLOR) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) # glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) # glEnable(GL_BLEND) # glBlendFunc(GL_SRC_ALPHA, GL_DST_ALPHA) # glBlendFunc(GL_ONE, GL_ONE) # glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glEnable(GL_NORMALIZE) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glEnable(GL_LIGHT1) glEnable(GL_LIGHT2) G.glLightfv(GL_LIGHT0, GL_DIFFUSE, (.8, .8, .8, 1.)) @self.window.event def on_resize(width, height): self.size = (width, height) for win in self.subWindows: self._adjust_subwindow(win) return pyglet.event.EVENT_HANDLED @self.window.event def on_draw(): self.draw()
def render(self, objects=[]): for obj in self.frameSetupObjs: #print "renderer draw obj:", obj.__class__.__name__ obj.draw(self) if (None != self.camera): #print "renderer draw obj:", obj.__class__.__name__ self.camera.draw(self) for o in self.objects + objects: #print "renderer draw obj:", obj.__class__.__name__ o.draw(self) GL.glDepthMask(GL.GL_FALSE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) for o in self.translucentObjects: #glMatrixMode(GL_MODELVIEW) #glLoadIdentity() #self.camera.draw() #print "renderer draw obj:", obj.__class__.__name__ try: o.draw(self) except: traceback.print_exc() sys.exit() glDisable(GL_BLEND) GL.glDepthMask(GL.GL_TRUE) self._renderScreenObjects()
def glGetVertexAttribOffset(index, pname): try: # maybe the fixed it return GL.glGetVertexAttribPointerv(index, pname) except TypeError: pointer = (ctypes.c_void_p*1)() GL.glGetVertexAttribPointerv(index, pname, pointer) return pointer[0] or 0
def glShaderSource(shader, source): # Some implementation do not like getting a list of single chars if isinstance(source, (tuple, list)): strings = [s for s in source] else: strings = [source] GL.glShaderSource(shader, strings)
def setupViewport(self, width, height): GL.glViewport(0, 0, width, height) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(0, width, 0, height, 0, 1) # Displacement trick for exact pixelization GL.glTranslatef(0.375, 0.375, 0)
def draw(self, rbcoords, index): from OpenGL import GL,GLUT coords = self.aasystem.to_atomistic(rbcoords) com=np.mean(coords, axis=0) i=0 for xx in coords: if(i%3 == 0): color = [1.0, 0.0, 0.0] radius = 0.35 else: color = [1.0, 1.0, 1.0] radius = 0.3 if index == 2: color = [0.5, 1.0, .5] i+=1 GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, color) x=xx-com GL.glPushMatrix() GL.glTranslate(x[0],x[1],x[2]) GLUT.glutSolidSphere(radius,30,30) GL.glPopMatrix() for i in xrange(self.nrigid): color = [1.0, 0.0, 0.0] if index == 2: color = [0.5, 1.0, .5] GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, color) self.drawCylinder(coords[3*i]-com, coords[3*i+1]-com) self.drawCylinder(coords[3*i]-com, coords[3*i+2]-com)
def glPushAttrib(cls, *attribs): allAttribs = reduce(lambda a, b: a | b, attribs) try: GL.glPushAttrib(allAttribs) yield finally: GL.glPopAttrib()
def delete_shader(self): if self.shader is not None: GL.glDeleteShader(self.shader) self._shader = None
import OpenGL.GL as gl import OpenGL.GLU as glu pygame.init() window_name = '.'.join(sys.argv[0].split('.')[:-1]) pygame.display.set_caption(window_name if window_name != '' else 'pygame') pygame.display.gl_set_attribute(pylocals.GL_MULTISAMPLEBUFFERS, 1) pygame.display.gl_set_attribute(pylocals.GL_MULTISAMPLESAMPLES, 4) SCREEN = pygame.display.set_mode((800, 600), pylocals.DOUBLEBUF | pylocals.OPENGL) done = False clock = pygame.time.Clock() FRAME_RATE = 120 T_DELAY = 0.5 gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearColor(54 / 255.0, 54 / 255.0, 54 / 255.0, 0) glu.gluPerspective(45, 4 / 3.0, 0.1, 12.0) gl.glTranslatef(0.0, 0.0, -8.0) #---------------------------------------------------------------------- faces = [] for i in range(6): side = np.loadtxt("matrices/solved/side{}.txt".format(i)) faces.append(np.uint8(side)) faces = sorted(faces, key=lambda b: b[1][1], reverse=False)
def __del__(self): GL.glUseProgram(0) if self.glid: # if this is a valid shader object GL.glDeleteProgram(self.glid) # object dies => destroy GL object
def __init__(self, vertex_source, fragment_source): """ Shader can be initialized with raw strings or source file names """ self.glid = None vert = self._compile_shader(vertex_source, GL.GL_VERTEX_SHADER) frag = self._compile_shader(fragment_source, GL.GL_FRAGMENT_SHADER) if vert and frag: self.glid = GL.glCreateProgram() # pylint: disable=E1111 GL.glAttachShader(self.glid, vert) GL.glAttachShader(self.glid, frag) GL.glLinkProgram(self.glid) GL.glDeleteShader(vert) GL.glDeleteShader(frag) status = GL.glGetProgramiv(self.glid, GL.GL_LINK_STATUS) if not status: print(GL.glGetProgramInfoLog(self.glid).decode('ascii')) GL.glDeleteProgram(self.glid) self.glid = None
def __del__(self): GL.glDeleteVertexArrays(1, [self.glid]) GL.glDeleteBuffers(1, self.buffers)
nuklear = nk.NuklearContext(ctx) fontAtlas = nkGLFW3.FontAtlas() nkGLFW3.glfw3_font_stash_begin(ctypes.byref(fontAtlas)) nkGLFW3.glfw3_font_stash_end() # Install a key handler def on_key(window, key, scancode, action, mods): if key == glfw.GLFW_KEY_ESCAPE and action == glfw.GLFW_PRESS: glfw.glfwSetWindowShouldClose(window, 1) glfw.glfwSetKeyCallback(window, on_key) gl.glClearColor(0.1, 0.18, 0.24, 1.0) gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearDepth(1.0) gl.glDepthFunc(gl.GL_LEQUAL) class Camera: def __init__(self): self.x = 0.0 self.y = 0.0 self.z = 10.0 self.rotationX = 0.0 self.rotationY = 0.0
def init(self): # Light setup ogl.glDisable(ogl.GL_LIGHT0) ogl.glEnable(ogl.GL_LIGHT1) # Light default parameters light_ambient = [1.0, 1.0, 1.0, 1.0] light_specular = [1.0, 1.0, 1.0, 1.0] light_diffuse = [1.0, 1.0, 1.0, 1.0] ogl.glLightf(ogl.GL_LIGHT1, ogl.GL_SPOT_EXPONENT, 3.0) ogl.glLightf(ogl.GL_LIGHT1, ogl.GL_SPOT_CUTOFF, 10.0) ogl.glLightf(ogl.GL_LIGHT1, ogl.GL_CONSTANT_ATTENUATION, 0.1) ogl.glLightf(ogl.GL_LIGHT1, ogl.GL_LINEAR_ATTENUATION, 0.3) ogl.glLightf(ogl.GL_LIGHT1, ogl.GL_QUADRATIC_ATTENUATION, 0.3) ogl.glLightfv(ogl.GL_LIGHT1, ogl.GL_AMBIENT, light_ambient) ogl.glLightfv(ogl.GL_LIGHT1, ogl.GL_SPECULAR, light_specular) ogl.glLightfv(ogl.GL_LIGHT1, ogl.GL_DIFFUSE, light_diffuse) # Restore previous viewer state. self.restoreStateFromFile() # Opens help window self.help()
l.error("Disabling sound system.") count += 1 if count < failed: l.warning("Some SDL modules failed to initialize.") pygame.display.gl_set_attribute(pygame.GL_ACCUM_RED_SIZE, 8) pygame.display.gl_set_attribute(pygame.GL_ACCUM_GREEN_SIZE, 8) pygame.display.gl_set_attribute(pygame.GL_ACCUM_BLUE_SIZE, 8) pygame.display.gl_set_attribute(pygame.GL_ACCUM_ALPHA_SIZE, 8) global screen screen = pygame.display.set_mode( (WIDTH,HEIGHT), pygame.OPENGL | pygame.DOUBLEBUF | pygame.RESIZABLE, 16 ) gl.glClearAccum(0,0,0,0) gl.glClear(gl.GL_ACCUM_BUFFER_BIT) gl.glClearColor(*BACKGROUND_COLOR) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) gl.glEnable(gl.GL_TEXTURE_2D) pygame.display.set_caption("FIVE TONS OF FLAX !") def get_turn_actions(): global next_ticks, total_wait_time global skip_c, fskip if next_ticks == 0:
def __init__(self, shader): self.shader = shader # triangle position buffer position = np.array(((0, .5, 0), (.5, -.5, 0), (-.5, -.5, 0)), 'f') self.glid = GL.glGenVertexArrays(1) # create OpenGL vertex array id GL.glBindVertexArray(self.glid) # activate to receive state below self.buffers = [GL.glGenBuffers(1) ] # create buffer for position attrib # bind the vbo, upload position data to GPU, declare its size and type GL.glEnableVertexAttribArray(0) # assign to layout = 0 attribute GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.buffers[0]) GL.glBufferData(GL.GL_ARRAY_BUFFER, position, GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(0, 3, GL.GL_FLOAT, False, 0, None) # cleanup and unbind so no accidental subsequent state update GL.glBindVertexArray(0) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
def delete_program(self): if self.program is not None: GL.glDeleteProgram(self.program) self.program = None
def make_freetype_texture(self, program): """ Function doc """ coords = np.zeros(3,np.float32) uv_pos = np.zeros(4,np.float32) vertex_array_object = GL.glGenVertexArrays(1) GL.glBindVertexArray(vertex_array_object) coord_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, coord_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, coords.itemsize*len(coords), coords, GL.GL_DYNAMIC_DRAW) gl_coord = GL.glGetAttribLocation(program, 'vert_coord') GL.glEnableVertexAttribArray(gl_coord) GL.glVertexAttribPointer(gl_coord, 3, GL.GL_FLOAT, GL.GL_FALSE, 3*coords.itemsize, ctypes.c_void_p(0)) tex_vbo = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, tex_vbo) GL.glBufferData(GL.GL_ARRAY_BUFFER, uv_pos.itemsize*len(uv_pos), uv_pos, GL.GL_DYNAMIC_DRAW) gl_texture = GL.glGetAttribLocation(program, 'vert_uv') GL.glEnableVertexAttribArray(gl_texture) GL.glVertexAttribPointer(gl_texture, 4, GL.GL_FLOAT, GL.GL_FALSE, 4*uv_pos.itemsize, ctypes.c_void_p(0)) GL.glBindVertexArray(0) GL.glDisableVertexAttribArray(gl_coord) GL.glDisableVertexAttribArray(gl_texture) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) self.vao = vertex_array_object self.vbos = (coord_vbo, tex_vbo) return True
def make_freetype_font(self): """ Function doc """ face = ft.Face(self.font_file) face.set_char_size(self.char_res*64) # Determine largest glyph size width, height, ascender, descender = 0, 0, 0, 0 for c in range(32,128): face.load_char(chr(c), ft.FT_LOAD_RENDER | ft.FT_LOAD_FORCE_AUTOHINT) bitmap = face.glyph.bitmap width = max(width, bitmap.width) ascender = max(ascender, face.glyph.bitmap_top) descender = max(descender, bitmap.rows-face.glyph.bitmap_top) height = ascender+descender # Generate texture data self.font_buffer = np.zeros((height*6, width*16), dtype=np.ubyte) for j in range(6): for i in range(16): face.load_char(chr(32+j*16+i), ft.FT_LOAD_RENDER | ft.FT_LOAD_FORCE_AUTOHINT ) bitmap = face.glyph.bitmap x = i*width + face.glyph.bitmap_left y = j*height + ascender - face.glyph.bitmap_top self.font_buffer[y:y+bitmap.rows,x:x+bitmap.width].flat = bitmap.buffer # Bound texture GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1) self.texture_id = GL.glGenTextures(1) GL.glBindTexture(GL.GL_TEXTURE_2D, self.texture_id) GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RED, self.font_buffer.shape[1], self.font_buffer.shape[0], 0, GL.GL_RED, GL.GL_UNSIGNED_BYTE, self.font_buffer) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR) GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR) # Fill the font variables with data self.text_u = width/float(self.font_buffer.shape[1]) self.text_v = height/float(self.font_buffer.shape[0]) return True
def bind_vert_attrib(self, name, bind_loc, size): loc = GL.glGetAttribLocation(self.program, name) GL.glEnableVertexAttribArray(loc) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, bind_loc) GL.glVertexAttribPointer(loc, size, GL.GL_FLOAT, False, 0, None)
def _set_uniform(self, name, value): # We need to figure out how to pass it in. if name not in self._uniform_funcs: self._uniform_funcs[name] = self._guess_uniform_func(value) loc = GL.glGetUniformLocation(self.program, name) return self._uniform_funcs[name](loc, value)
def enable(self): GL.glUseProgram(self.program) yield GL.glUseProgram(0)
def disable_vert_attrib(self, name): loc = GL.glGetAttribLocation(self.program, name) GL.glDisableVertexAttribArray(loc)
def display(self): with self.mainfbo: self.clear() self.render() gl.glMemoryBarrier(gl.GL_FRAMEBUFFER_BARRIER_BIT) if self.emulate: gl.glClearColor(0, 0, 0, 0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glViewport(0, 0, int(self.screenWidth / 2), self.screenHeight) self.tree.render(0) gl.glViewport(int(self.screenWidth / 2), 0, int(self.screenWidth / 2), self.screenHeight) self.texquad.render() else: gl.glClearColor(0, 0, 0, 0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) if self.preview: self.texquad.render() else: self.signalgenerator.render() glut.glutSwapBuffers() glut.glutPostRedisplay()
def render(self, mat, trace, render_settings=RENDER_STANDARD): color_a = self.parent.color_for_trace(trace) + [1] color_a = self.parent.sel_colormod(render_settings & RENDER_SELECTED, color_a) with self.__uniform_shader, self.__uniform_shader_vao: GL.glUniform1f(self.__uniform_shader.uniforms.thickness, trace.thickness / 2) GL.glUniform2f(self.__uniform_shader.uniforms.pos_a, trace.p0.x, trace.p0.y) GL.glUniform2f(self.__uniform_shader.uniforms.pos_b, trace.p1.x, trace.p1.y) GL.glUniformMatrix3fv(self.__uniform_shader.uniforms.mat, 1, True, mat.ctypes.data_as(GLI.c_float_p)) GL.glUniform4f(self.__uniform_shader.uniforms.color, *color_a) if render_settings & RENDER_OUTLINES: GL.glDrawArrays(GL.GL_LINE_LOOP, 2, NUM_ENDCAP_SEGMENTS * 2) else: GL.glDrawElements(GL.GL_TRIANGLES, TRIANGLES_SIZE, GL.GL_UNSIGNED_INT, ctypes.c_void_p(0))
def clear(self): gl.glClearColor(0, 0, 0, 0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE)
def reshape(self, width, height): self.screenWidth = width self.screenHeight = height gl.glViewport(0, 0, width, height)
def disable(self): GL.glDisable(GL.GL_STENCIL_TEST)
def reset(self): self.enable() GL.glClearStencil(0) GL.glClear(GL.GL_STENCIL_BUFFER_BIT) GL.glPushMatrix() GL.glTranslate(self.pos[0], self.pos[1], 0) GL.glDisable(GL.GL_LIGHTING) GL.glDisable(GL.GL_DEPTH_TEST) GL.glDepthMask(GL.GL_FALSE) GL.glStencilFunc(GL.GL_NEVER, 0, 0) GL.glStencilOp(GL.GL_INCR, GL.GL_INCR, GL.GL_INCR) GL.glColor3f(1.0, 1.0, 1.0) GL.glScalef(self.winAspect, 1.0, 1.0) GLU.gluDisk(self._quad, 0, self.size, 120, 2) GL.glStencilFunc(GL.GL_EQUAL, 1, 1) GL.glStencilOp(GL.GL_KEEP, GL.GL_KEEP, GL.GL_KEEP) GL.glPopMatrix()
def enable(self): GL.glEnable(GL.GL_STENCIL_TEST)
def render_deferred_layer(self, mat, layer): if not self.__prepared: self.prepare() trace_settings = self.__deferred_layer[layer] count = len(trace_settings) if count == 0: return # key format: is_selected, is_outline draw_bins = defaultdict(list) draw_range_bins = dict() # Bin the traces by draw call for t, tr in trace_settings: is_selected = bool(tr & RENDER_SELECTED) is_outline = bool(tr & RENDER_OUTLINES) draw_bins[is_selected, is_outline].append(self.__last_prepared[t]) # Build draw ranges for key, bin in draw_bins.items(): draw_range_bins[key] = get_consolidated_draws_1(draw_bins[key]) # HACK / Fixme: Precalculate selected / nonselected colors color_a = self.parent.color_for_layer(layer) + [1] color_sel = self.parent.sel_colormod(True, color_a) has_base_instance = False with self.__attribute_shader, self.__attribute_shader_vao: # Setup overall calls GL.glUniformMatrix3fv(self.__attribute_shader.uniforms.mat, 1, True, mat.ctypes.data_as(GLI.c_float_p)) for (is_selected, is_outline), ranges in draw_range_bins.items(): if is_selected: color = color_sel else: color = color_a GL.glUniform4f(self.__attribute_shader.uniforms.color, *color) if has_base_instance: # Many instances backport glDrawElementsInstancedBaseInstance # This is faster than continually rebinding, so support if possible if not is_outline: for first, last in ranges: # filled traces come first in the array GL.glDrawElementsInstancedBaseInstance( GL.GL_TRIANGLES, TRIANGLES_SIZE, GL.GL_UNSIGNED_INT, ctypes.c_void_p(0), last - first, first) else: for first, last in ranges: # Then outline traces. We reuse the vertex data for the outside GL.glDrawArraysInstancedBaseInstance( GL.GL_LINE_LOOP, 2, NUM_ENDCAP_SEGMENTS * 2, last - first, first) else: with self.instance_vbo: if not is_outline: for first, last in ranges: # filled traces come first in the array self.__base_rebind(first) GL.glDrawElementsInstanced( GL.GL_TRIANGLES, TRIANGLES_SIZE, GL.GL_UNSIGNED_INT, ctypes.c_void_p(0), last - first) else: for first, last in ranges: self.__base_rebind(first) # Then outline traces. We reuse the vertex data for the outside GL.glDrawArraysInstanced( GL.GL_LINE_LOOP, 2, NUM_ENDCAP_SEGMENTS * 2, last - first)
def load_matrices(self, program, view_mat, proj_mat): """ Function doc """ view = GL.glGetUniformLocation(program, 'view_mat') GL.glUniformMatrix4fv(view, 1, GL.GL_FALSE, view_mat) proj = GL.glGetUniformLocation(program, 'proj_mat') GL.glUniformMatrix4fv(proj, 1, GL.GL_FALSE, proj_mat)
def to_opengl(self, **kwords): if not GL_enabled: return GL.glDisable(GL.GL_LIGHTING) if self.is_closed: is_outer = self.is_outer() if not is_outer: color = GL.glGetFloatv(GL.GL_CURRENT_COLOR) GL.glColor(color[0], color[1], color[2], color[3] / 2) GL.glLineWidth(LINE_WIDTH_INNER) else: GL.glLineWidth(LINE_WIDTH_OUTER) GL.glBegin(GL.GL_LINE_LOOP) for point in self._points: GL.glVertex3f(point[0], point[1], point[2]) GL.glEnd() if not is_outer: GL.glColor(*color) # reset line width GL.glLineWidth(1.0) else: for line in self.get_lines(): line.to_opengl(**kwords)
def quad(self, primitive, x1, y1, x2, y2, x3, y3, x4, y4): GL.glBegin(primitive) GL.glVertex2d(x1, y1) GL.glVertex2d(x2, y2) GL.glVertex2d(x3, y3) GL.glVertex2d(x4, y4) GL.glEnd()
def gl_display_in_window(self): active_window = glfwGetCurrentContext() if glfwWindowShouldClose(self._window): self.close_window() return glfwMakeContextCurrent(self._window) clear_gl_screen() hdpi_factor = getHDPIFactor(self._window) r = self.marker_scale * hdpi_factor gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() p_window_size = glfwGetFramebufferSize(self._window) gl.glOrtho(0, p_window_size[0], p_window_size[1], 0, -1, 1) # Switch back to Model View Matrix gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() def map_value(value, in_range=(0, 1), out_range=(0, 1)): ratio = (out_range[1] - out_range[0]) / (in_range[1] - in_range[0]) return (value - in_range[0]) * ratio + out_range[0] pad = 90 * r screen_pos = ( map_value(self.display_pos[0], out_range=(pad, p_window_size[0] - pad)), map_value(self.display_pos[1], out_range=(p_window_size[1] - pad, pad)), ) alpha = ( 1.0 ) # interp_fn(self.screen_marker_state,0.,1.,float(self.sample_duration+self.lead_in+self.lead_out),float(self.lead_in),float(self.sample_duration+self.lead_in)) r2 = 2 * r draw_points( [screen_pos], size=60 * r2, color=RGBA(0.0, 0.0, 0.0, alpha), sharpness=0.9 ) draw_points( [screen_pos], size=38 * r2, color=RGBA(1.0, 1.0, 1.0, alpha), sharpness=0.8 ) draw_points( [screen_pos], size=19 * r2, color=RGBA(0.0, 0.0, 0.0, alpha), sharpness=0.55 ) # some feedback on the detection state color = ( RGBA(0.0, 0.8, 0.0, alpha) if len(self.markers) and self.on_position else RGBA(0.8, 0.0, 0.0, alpha) ) draw_points([screen_pos], size=3 * r2, color=color, sharpness=0.5) if self.clicks_to_close < 5: self.glfont.set_size(int(p_window_size[0] / 30.0)) self.glfont.draw_text( p_window_size[0] / 2.0, p_window_size[1] / 4.0, "Touch {} more times to cancel calibration.".format( self.clicks_to_close ), ) glfwSwapBuffers(self._window) glfwMakeContextCurrent(active_window)
def makeObject(self): # trolltechGreen = QColor.fromCmykF(0.40, 0.0, 1.0, 0.0) # NumSectors = 15 # x1 = +0.06 # y1 = -0.14 # x2 = +0.14 # y2 = -0.06 # x3 = +0.08 # y3 = +0.00 # x4 = +0.30 # y4 = +0.22 self.list_RECT1 = GL.glGenLists(1) GL.glNewList(self.list_RECT1, GL.GL_COMPILE) # for i in range(NumSectors): # angle1 = float((i * 2 * math.pi) / NumSectors) # x5 = 0.30 * math.sin(angle1) # y5 = 0.30 * math.cos(angle1) # x6 = 0.20 * math.sin(angle1) # y6 = 0.20 * math.cos(angle1) # angle2 = float(((i + 1) * 2 * math.pi) / NumSectors) # x7 = 0.20 * math.sin(angle2) # y7 = 0.20 * math.cos(angle2) # x8 = 0.30 * math.sin(angle2) # y8 = 0.30 * math.cos(angle2) # self.qglColor(trolltechGreen) # self.quad(GL.GL_QUADS, x5, y5, x6, y6, x7, y7, x8, y8) # self.qglColor(Qt.black) # self.quad(GL.GL_LINE_LOOP, x5, y5, x6, y6, x7, y7, x8, y8) self.qglColor(Qt.yellow) GL.glBegin(GL.GL_QUADS) GL.glVertex2d(0, 0) GL.glVertex2d(rect1Width, 0) GL.glVertex2d(rect1Width, windowHeight - passHeight - rect1Height) GL.glVertex2d(0, windowHeight - passHeight - rect1Height) GL.glVertex2d(0, (windowHeight - rect1Height)) GL.glVertex2d(rect1Width, (windowHeight - rect1Height)) GL.glVertex2d(rect1Width, windowHeight) GL.glVertex2d(0, windowHeight) GL.glEnd() # self.qglColor(trolltechGreen) # self.quad(GL.GL_QUADS, x1, y1, x2, y2, y2, x2, y1, x1) # self.quad(GL.GL_QUADS, x3, y3, x4, y4, y4, x4, y3, x3) # self.qglColor(Qt.black) # self.quad(GL.GL_LINE_LOOP, x1, y1, x2, y2, y2, x2, y1, x1) # self.quad(GL.GL_LINE_LOOP, x3, y3, x4, y4, y4, x4, y3, x3) GL.glEndList() self.list_RECT2 = GL.glGenLists(2) GL.glNewList(self.list_RECT2, GL.GL_COMPILE) self.qglColor(Qt.blue) GL.glBegin(GL.GL_QUADS) GL.glVertex2d(0, 0) GL.glVertex2d(rect2Width, 0) GL.glVertex2d(rect2Width, rect2Height) GL.glVertex2d(0, rect2Height) GL.glEnd() GL.glEndList()
def initializeGL(self): GL.glViewport(0, 0, windowWindth, windowHeight) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glOrtho(0.0, windowWindth, 0.0, windowHeight, 0.0, 1.0) GL.glMatrixMode (GL.GL_MODELVIEW) GL.glLoadIdentity() self.makeObject()