我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pyglet.gl()。
def __init__(self, size, target, usage): self.size = size self.target = target self.usage = usage self._context = pyglet.gl.current_context id = GLuint() glGenBuffers(1, id) self.id = id.value glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glBindBuffer(target, self.id) glBufferData(target, self.size, None, self.usage) glPopClientAttrib() global _workaround_vbo_finish if pyglet.gl.current_context._workaround_vbo_finish: _workaround_vbo_finish = True
def on_draw(self): gl.glClearColor(0.0, 0.0, 0.0, 0.0) self.clear() if time.time() - self.start_time > 0.1: gl.glViewport(0, 0, self.tex_width, self.tex_height) with self.fbo: with self.reaction_shader: gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4) gl.glViewport(0, 0, self.width, self.height) with self.render_shader: gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4) if self.video_on and (self.frame_count % self.sample_rate == 0): self.write_video_frame() self.frame_count += 1
def set_background_color(color: Color): """ This specifies the background color of the window. Args: :color (tuple): List of 3 or 4 bytes in RGB/RGBA format. Returns: None Raises: None Example: >>> import arcade >>> arcade.open_window(800,600,"Drawing Example") >>> arcade.set_background_color(arcade.color.RED) >>> arcade.start_render() >>> arcade.finish_render() >>> arcade.quick_run(0.25) """ gl.glClearColor(color[0]/255, color[1]/255, color[2]/255, 1)
def on_resize(self, width, height): '''A default resize event handler. This default handler updates the GL viewport to cover the entire window and sets the ``GL_PROJECTION`` matrix to be orthogonal in window space. The bottom-left corner is (0, 0) and the top-right corner is the width and height of the window in pixels. Override this event handler with your own to create another projection, for example in perspective. ''' gl.glViewport(0, 0, width, height) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(0, width, 0, height, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW)
def set_state(self): pyglet.gl.glLineWidth(self.lineweight) if 'D' in self.state: # pyglet.gl.glEnable(pyglet.gl.GL_TEXTURE_2D) pyglet.gl.glShadeModel(pyglet.gl.GL_SMOOTH) pyglet.gl.glEnable(pyglet.gl.GL_LINE_SMOOTH) if 'A' in self.state: pyglet.gl.glEnable(pyglet.gl.GL_BLEND) pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA, pyglet.gl.GL_ONE_MINUS_SRC_ALPHA) if 'N' in self.state: pyglet.gl.glHint(pyglet.gl.GL_LINE_SMOOTH_HINT, pyglet.gl.GL_NICEST); # def unset_state(self): # pass
def __init__(self, width, height, display=None): display = get_display(display) self.width = width self.height = height self.window = pyglet.window.Window(width=width, height=height, display=display) self.window.on_close = self.window_closed_by_user self.geoms = [] self.onetime_geoms = [] self.transform = Transform() gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
def render(self, return_rgb_array=False): gl.glClearColor(1,1,1,1) self.window.clear() self.window.switch_to() self.window.dispatch_events() self.transform.enable() for geom in self.geoms: geom.render() for geom in self.onetime_geoms: geom.render() self.transform.disable() arr = None if return_rgb_array: buffer = pyglet.image.get_buffer_manager().get_color_buffer() image_data = buffer.get_image_data() arr = np.fromstring(image_data.data, dtype=np.uint8, sep='') # In https://github.com/openai/gym-http-api/issues/2, we # discovered that someone using Xmonad on Arch was having # a window of size 598 x 398, though a 600 x 400 window # was requested. (Guess Xmonad was preserving a pixel for # the boundary.) So we use the buffer height/width rather # than the requested one. arr = arr.reshape(buffer.height, buffer.width, 4) arr = arr[::-1,:,0:3] self.window.flip() self.onetime_geoms = [] return arr # Convenience
def enable(self): gl.glPushMatrix() gl.glTranslatef(self.translation[0], self.translation[1], 0) # translate to GL loc ppint gl.glRotatef(RAD2DEG * self.rotation, 0, 0, 1.0) gl.glScalef(self.scale[0], self.scale[1], 1)
def disable(self): gl.glPopMatrix()
def enable(self): gl.glColor4f(*self.vec4)
def disable(self): gl.glDisable(gl.GL_LINE_STIPPLE)
def enable(self): gl.glLineWidth(self.stroke)
def render1(self): gl.glBegin(gl.GL_POINTS) # draw point gl.glVertex3f(0.0, 0.0, 0.0) gl.glEnd()
def render1(self): if len(self.v) == 4 : gl.glBegin(gl.GL_QUADS) elif len(self.v) > 4 : gl.glBegin(gl.GL_POLYGON) else: gl.glBegin(gl.GL_TRIANGLES) for p in self.v: gl.glVertex3f(p[0], p[1],0) # draw each vertex gl.glEnd()
def render1(self): gl.glBegin(gl.GL_LINE_LOOP if self.close else gl.GL_LINE_STRIP) for p in self.v: gl.glVertex3f(p[0], p[1],0) # draw each vertex gl.glEnd()
def dump_gl(context=None): '''Dump GL info.''' if context is not None: info = context.get_info() else: from pyglet.gl import gl_info as info print('gl_info.get_version():', info.get_version()) print('gl_info.get_vendor():', info.get_vendor()) print('gl_info.get_renderer():', info.get_renderer()) print('gl_info.get_extensions():') extensions = list(info.get_extensions()) extensions.sort() for name in extensions: print(' ', name)
def dump_glu(): '''Dump GLU info.''' from pyglet.gl import glu_info print('glu_info.get_version():', glu_info.get_version()) print('glu_info.get_extensions():') extensions = list(glu_info.get_extensions()) extensions.sort() for name in extensions: print(' ', name)
def dump_glx(): '''Dump GLX info.''' try: from pyglet.gl import glx_info except: print('GLX not available.') return import pyglet window = pyglet.window.Window(visible=False) print('context.is_direct():', window.context.is_direct()) window.close() if not glx_info.have_version(1, 1): print('Version: < 1.1') else: print('glx_info.get_server_vendor():', glx_info.get_server_vendor()) print('glx_info.get_server_version():', glx_info.get_server_version()) print('glx_info.get_server_extensions():') for name in glx_info.get_server_extensions(): print(' ', name) print('glx_info.get_client_vendor():', glx_info.get_client_vendor()) print('glx_info.get_client_version():', glx_info.get_client_version()) print('glx_info.get_client_extensions():') for name in glx_info.get_client_extensions(): print(' ', name) print('glx_info.get_extensions():') for name in glx_info.get_extensions(): print(' ', name)
def dump(): '''Dump all information to stdout.''' _try_dump('Python', dump_python) _try_dump('pyglet', dump_pyglet) _try_dump('pyglet.window', dump_window) _try_dump('pyglet.gl.glu_info', dump_glu) _try_dump('pyglet.gl.glx_info', dump_glx) _try_dump('pyglet.media', dump_media) _try_dump('pyglet.media.avbin', dump_avbin) _try_dump('pyglet.media.drivers.openal', dump_al) _try_dump('pyglet.input.wintab', dump_wintab)
def link_GL(name, restype, argtypes, requires=None, suggestions=None): try: func = getattr(gl_lib, name) func.restype = restype func.argtypes = argtypes decorate_function(func, name) return func except AttributeError: # Not in opengl32.dll. Try and get a pointer from WGL. try: fargs = (restype,) + tuple(argtypes) ftype = ctypes.WINFUNCTYPE(*fargs) if _have_get_proc_address: from pyglet.gl import gl_info if gl_info.have_context(): address = wglGetProcAddress(name) if address: func = cast(address, ftype) decorate_function(func, name) return func else: # Insert proxy until we have a context return WGLFunctionProxy(name, ftype, requires, suggestions) except: pass return missing_function(name, requires, suggestions)
def link_GLU(name, restype, argtypes, requires=None, suggestions=None): try: func = getattr(glu_lib, name) func.restype = restype func.argtypes = argtypes decorate_function(func, name) return func except AttributeError: # Not in glu32.dll. Try and get a pointer from WGL. try: fargs = (restype,) + tuple(argtypes) ftype = ctypes.WINFUNCTYPE(*fargs) if _have_get_proc_address: from pyglet.gl import gl_info if gl_info.have_context(): address = wglGetProcAddress(name) if address: func = cast(address, ftype) decorate_function(func, name) return func else: # Insert proxy until we have a context return WGLFunctionProxy(name, ftype, requires, suggestions) except: pass return missing_function(name, requires, suggestions)
def create_buffer(size, target=GL_ARRAY_BUFFER, usage=GL_DYNAMIC_DRAW, vbo=True): '''Create a buffer of vertex data. :Parameters: `size` : int Size of the buffer, in bytes `target` : int OpenGL target buffer `usage` : int OpenGL usage constant `vbo` : bool True if a `VertexBufferObject` should be created if the driver supports it; otherwise only a `VertexArray` is created. :rtype: `AbstractBuffer` ''' from pyglet import gl if (vbo and gl_info.have_version(1, 5) and _enable_vbo and not gl.current_context._workaround_vbo): return VertexBufferObject(size, target, usage) else: return VertexArray(size)
def create_mappable_buffer(size, target=GL_ARRAY_BUFFER, usage=GL_DYNAMIC_DRAW, vbo=True): '''Create a mappable buffer of vertex data. :Parameters: `size` : int Size of the buffer, in bytes `target` : int OpenGL target buffer `usage` : int OpenGL usage constant `vbo` : bool True if a `VertexBufferObject` should be created if the driver supports it; otherwise only a `VertexArray` is created. :rtype: `AbstractBuffer` with `AbstractMappable` ''' from pyglet import gl if (vbo and gl_info.have_version(1, 5) and _enable_vbo and not gl.current_context._workaround_vbo): return MappableVertexBufferObject(size, target, usage) else: return VertexArray(size)
def _get_default_batch(): shared_object_space = gl.current_context.object_space try: return shared_object_space.pyglet_graphics_default_batch except AttributeError: shared_object_space.pyglet_graphics_default_batch = Batch() return shared_object_space.pyglet_graphics_default_batch
def create_texture_from_ndarray(array): height, width = array.shape[:2] texture = pyglet.image.Texture.create_for_size(gl.GL_TEXTURE_2D, width, height, gl.GL_RGBA32F_ARB) gl.glBindTexture(texture.target, texture.id) gl.glTexImage2D(texture.target, texture.level, gl.GL_RGBA32F_ARB, width, height, 0, gl.GL_RGBA, gl.GL_FLOAT, array.ctypes.data) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glBindTexture(texture.target, 0) return texture # species: [Du, Dv, feed, kill]
def _setColor(color=[]): # pyglet.gl.glClear(pyglet.gl.GL_COLOR_BUFFER_BIT) if len(color) == 0: color = [255, 255, 0] pyglet.gl.glColor3f( color[0]/255.0 , color[1]/255.0 , color[2]/255.0 )
def start_render(): """ Get set up to render. Required to be called before drawing anything to the screen. """ gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
def draw_point(x: float, y: float, color: Color, size: float): """ Draw a point. Args: :x: x position of point. :y: y position of point. :color: color, specified in a list of 3 or 4 bytes in RGB or RGBA format. :size: Size of the point in pixels. Returns: None Raises: None Example: >>> import arcade >>> arcade.open_window(800,600,"Drawing Example") >>> arcade.set_background_color(arcade.color.WHITE) >>> arcade.start_render() >>> arcade.draw_point(60, 495, arcade.color.RED, 10) >>> arcade.draw_point(70, 495, (255, 0, 0, 127), 10) >>> arcade.finish_render() >>> arcade.quick_run(0.25) """ gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glLoadIdentity() gl.glPointSize(size) if len(color) == 4: gl.glColor4ub(color[0], color[1], color[2], color[3]) elif len(color) == 3: gl.glColor4ub(color[0], color[1], color[2], 255) gl.glBegin(gl.GL_POINTS) gl.glVertex3f(x, y, 0.5) gl.glEnd()
def render_text(text: pyglet.text.Label, start_x: float, start_y: float, rotation=0): """ Render text created by the create_text function. """ gl.glLoadIdentity() gl.glTranslatef(start_x, start_y, 0) if rotation: gl.glRotatef(rotation, 0, 0, 1) text.draw()
def init_gl(self): gl.glClearColor(.93, .93, 1, 1) #glColor3f(1, 0, 0) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_CULL_FACE) gl.glEnable(gl.GL_LIGHTING) gl.glEnable(gl.GL_LIGHT0) gl.glEnable(gl.GL_LIGHT1) gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION, _gl_vector(.5, .5, 1, 0)) gl.glLightfv(gl.GL_LIGHT0, gl.GL_SPECULAR, _gl_vector(.5, .5, 1, 1)) gl.glLightfv(gl.GL_LIGHT0, gl.GL_DIFFUSE, _gl_vector(1, 1, 1, 1)) gl.glLightfv(gl.GL_LIGHT1, gl.GL_POSITION, _gl_vector(1, 0, .5, 0)) gl.glLightfv(gl.GL_LIGHT1, gl.GL_DIFFUSE, _gl_vector(.5, .5, .5, 1)) gl.glLightfv(gl.GL_LIGHT1, gl.GL_SPECULAR, _gl_vector(1, 1, 1, 1)) gl.glColorMaterial(gl.GL_FRONT_AND_BACK, gl.GL_AMBIENT_AND_DIFFUSE) gl.glEnable(gl.GL_COLOR_MATERIAL) gl.glShadeModel(gl.GL_SMOOTH) gl.glMaterialfv(gl.GL_FRONT, gl.GL_AMBIENT, _gl_vector(0.192250, 0.192250, 0.192250)) gl.glMaterialfv(gl.GL_FRONT, gl.GL_DIFFUSE, _gl_vector(0.507540, 0.507540, 0.507540)) gl.glMaterialfv(gl.GL_FRONT, gl.GL_SPECULAR, _gl_vector(.5082730,.5082730,.5082730)) gl.glMaterialf(gl.GL_FRONT, gl.GL_SHININESS, .4 * 128.0); gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
def update_flags(self): if self.view['wireframe']: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE) else: gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_FILL) if self.view['cull']: gl.glEnable(gl.GL_CULL_FACE) else: gl.glDisable(gl.GL_CULL_FACE)
def on_resize(self, width, height): gl.glViewport(0, 0, width, height) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.gluPerspective(60., width / float(height), .01, 1000.) gl.glMatrixMode(gl.GL_MODELVIEW) self.view['ball'].place([width/2, height/2], (width+height)/2)
def _gl_matrix(array): ''' Convert a sane numpy transformation matrix (row major, (4,4)) to an stupid GLfloat transformation matrix (column major, (16,)) ''' a = np.array(array).T.reshape(-1) return (gl.GLfloat * len(a))(*a)
def _gl_vector(array, *args): ''' Convert an array and an optional set of args into a flat vector of GLfloat ''' array = np.array(array) if len(args) > 0: array = np.append(array, args) vector = (gl.GLfloat * len(array))(*array) return vector
def draw(self, x, y): gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_CURRENT_BIT) gl.glColor4f(1, 1, 1, 1) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) self.texture.blit(x - self.hot_x, y - self.hot_y, 0) gl.glPopAttrib()
def switch_to(self): '''Make this window the current OpenGL rendering context. Only one OpenGL context can be active at a time. This method sets the current window's context to be current. You should use this method in preference to `pyglet.gl.Context.set_current`, as it may perform additional initialisation functions. ''' raise NotImplementedError('abstract')
def draw_mouse_cursor(self): '''Draw the custom mouse cursor. If the current mouse cursor has ``drawable`` set, this method is called before the buffers are flipped to render it. This method always leaves the ``GL_MODELVIEW`` matrix as current, regardless of what it was set to previously. No other GL state is affected. There is little need to override this method; instead, subclass ``MouseCursor`` and provide your own ``draw`` method. ''' # Draw mouse cursor if set and visible. # XXX leaves state in modelview regardless of starting state if (self._mouse_cursor.drawable and self._mouse_visible and self._mouse_in_window): gl.glMatrixMode(gl.GL_PROJECTION) gl.glPushMatrix() gl.glLoadIdentity() gl.glOrtho(0, self.width, 0, self.height, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glLoadIdentity() self._mouse_cursor.draw(self._mouse_x, self._mouse_y) gl.glMatrixMode(gl.GL_PROJECTION) gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPopMatrix() # Properties provide read-only access to instance variables. Use # set_* methods to change them if applicable.
def clear(self): '''Clear the window. This is a convenience method for clearing the color and depth buffer. The window must be the active context (see `switch_to`). ''' gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)