def own_render(environment, img): if environment.window is None: config = gl.Config(double_buffer=False) environment.window = window.Window(width=WINDOW_WIDTH, height=WINDOW_HEIGHT, resizable=False, config=config) environment.window.clear() environment.window.switch_to() environment.window.dispatch_events() gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glOrtho(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT, 0, 10) width = img.shape[1] height = img.shape[0] img = np.ascontiguousarray(np.flip(img, axis=0)) img_data = image.ImageData( width, height, 'RGB', img.ctypes.data_as(POINTER(gl.GLubyte)), pitch=width * 3, ) img_data.blit(0, 0, 0, width=WINDOW_WIDTH, height=WINDOW_HEIGHT) x, y, z = environment.cur_pos environment.text_label.text = "pos: (%.2f, %.2f, %.2f), angle: %d, steps: %d, speed: %.2f m/s" % ( x, y, z, int(environment.cur_angle * 180 / math.pi), environment.step_count, environment.speed) environment.text_label.draw() gl.glFlush()
def _recreate(self, changes): # If flipping to/from fullscreen and using override_redirect (we # always are, _NET_WM_FULLSCREEN doesn't work), need to recreate the # window. # # A possible improvement could be to just hide the top window, # destroy the GLX window, and reshow it again when leaving fullscreen. # This would prevent the floating window from being moved by the # WM. if 'fullscreen' in changes or 'resizable' in changes: # clear out the GLX context self.switch_to() gl.glFlush() glx.glXMakeCurrent(self._x_display, 0, None) if self._glx_window: glx.glXDestroyWindow(self._x_display, self._glx_window) xlib.XDestroyWindow(self._x_display, self._window) self._glx_window = None self._window = None self._mapped = False # TODO: detect state loss only by examining context share. if 'context' in changes: self._lost_context = True self._lost_context_state = True self._create()
def on_draw(self): """ Render the screen. """ draw_start_time = timeit.default_timer() # This command has to happen before we start drawing arcade.start_render() # Draw all the sprites. self.sprite_list.draw() # Display info on sprites output = f"Sprite count: {len(self.sprite_list):,}" arcade.draw_text(output, 20, self.fullscreen_height - 20, arcade.color.BLACK, 16) # Display timings output = f"Drawing time: {self.draw_time:.3f}" arcade.draw_text(output, 20, self.fullscreen_height - 40, arcade.color.BLACK, 16) fps = self.fps.get_fps() output = f"FPS: {fps:3.0f}" arcade.draw_text(output, 20, self.fullscreen_height - 60, arcade.color.BLACK, 16) self.draw_time = timeit.default_timer() - draw_start_time self.fps.tick() gl.glFlush()
def drawVAO(vao, mode=GL.GL_TRIANGLES, flush=True): """Draw a vertex array using glDrawArrays. This method does not require shaders. Parameters ---------- vao : :obj:`VertexArrayObject` Vertex Array Object (VAO) to draw. mode : :obj:`int`, optional Drawing mode to use (e.g. GL_TRIANGLES, GL_QUADS, GL_POINTS, etc.) flush : :obj:`bool`, optional Flush queued drawing commands before returning. Returns ------- None Examples -------- # create a VAO vaoDesc = createVAO(vboVerts, vboTexCoords, vboNormals) # draw the VAO, renders the mesh drawVAO(vaoDesc, GL.GL_TRIANGLES) """ # draw the array GL.glBindVertexArray(vao.id) GL.glDrawArrays(mode, 0, vao.indices) if flush: GL.glFlush() # reset GL.glBindVertexArray(0)
def buffer_texture(width, height): id_ = gl.GLuint() gl.glGenTextures(1, byref(id_)) gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_TEXTURE_BIT) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glEnable(gl.GL_TEXTURE_2D) gl.glBindTexture(gl.GL_TEXTURE_2D, id_) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexImage2D( gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, (gl.GLubyte * (width*height * 4))(), ) gl.glFlush() gl.glBindTexture(gl.GL_TEXTURE_2D, 0) gl.glPopAttrib() return id_
def select_object(x, y, objects=None): from miru.context import context if objects is None: objects = context.camera.objects # following technique is adapted from # http://www.cse.msu.edu/~cse872/tutorial9.html w = context.window.width h = context.window.height select_buffer = ctypes.cast((100 * gl.GLuint)(), ctypes.POINTER(gl.GLuint)) gl.glSelectBuffer(100, select_buffer) viewport = (4 * gl.GLint)() gl.glGetIntegerv(gl.GL_VIEWPORT, viewport) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() # rotate the camera first angle = context.camera.angle gl.glRotatef(angle.z, 0, 0, 1) gl.glRotatef(angle.y, 0, 1, 0) gl.glRotatef(angle.x, 1, 0, 0) gl.gluPickMatrix(x, y, 3, 3, viewport) gl.glRenderMode(gl.GL_SELECT) gl.gluPerspective(45., w / float(h), 0.1, 1000.) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glInitNames() gl.glPushName(-1) context.camera.render(select_pass=1, visible=objects) gl.glFlush() hits = gl.glRenderMode(gl.GL_RENDER) gl.glPopName() selected = None if hits: try: m = sys.maxint << 100 idx = 0 for i in range(0, 100, 4): if not select_buffer[i]: selected = objects[idx] break m = min(select_buffer[i+1], m) if m == select_buffer[i+1]: idx = select_buffer[i+3] except IndexError: pass context.window.on_resize(context.window.width, context.window.height) return selected
def on_draw(self): """ Draw everything """ # Start timing how long this takes draw_start_time = timeit.default_timer() arcade.start_render() # Display sprites self.coin_list.draw() # Display info on sprites output = f"Sprite count: {len(self.coin_list):,}" arcade.draw_text(output, 20, SCREEN_HEIGHT - 20, arcade.color.BLACK, 16) # Display timings output = f"Drawing time: {self.draw_time:.3f}" arcade.draw_text(output, 20, SCREEN_HEIGHT - 40, arcade.color.BLACK, 16) fps = self.fps.get_fps() output = f"FPS: {fps:3.0f}" arcade.draw_text(output, 20, SCREEN_HEIGHT - 60, arcade.color.BLACK, 16) self.draw_time = timeit.default_timer() - draw_start_time self.fps.tick() gl.glFlush()
def detach(self): if not self.canvas: return self.set_current() gl.glFlush() glx.glXMakeCurrent(self.x_display, 0, None) super(XlibContext10, self).detach()
def upload(self): glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, self.handle) texture_data = bytes(self.image.flat) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, self.width, self.height, 0, self.format, self.type, texture_data) glFlush() self.uploaded = True
def create(cls, width, height, target=gl.GL_TEXTURE_2D, internalformat=gl.GL_RGBA, min_filter=None, mag_filter=None): """Create a Texture Create a Texture with the specified dimentions, target and format. On return, the texture will be bound. :Parameters: `width` : int Width of texture in pixels. `height` : int Height of texture in pixels. `target` : int GL constant giving texture target to use, typically ``GL_TEXTURE_2D``. `internalformat` : int GL constant giving internal format of texture; for example, ``GL_RGBA``. If ``None``, the texture will be created but not initialized. `min_filter` : int The minifaction filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST`` `mag_filter` : int The magnification filter used for this texture, commonly ``GL_LINEAR`` or ``GL_NEAREST`` :rtype: :py:class:`~pyglet.image.Texture` """ min_filter = min_filter or cls.default_min_filter mag_filter = mag_filter or cls.default_mag_filter tex_id = gl.GLuint() gl.glGenTextures(1, byref(tex_id)) gl.glBindTexture(target, tex_id.value) if target != gl.GL_TEXTURE_2D_MULTISAMPLE: gl.glTexParameteri(target, gl.GL_TEXTURE_MIN_FILTER, min_filter) gl.glTexParameteri(target, gl.GL_TEXTURE_MAG_FILTER, mag_filter) if internalformat is not None: blank = (gl.GLubyte * (width * height * 4))() gl.glTexImage2D(target, 0, internalformat, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, blank) gl.glFlush() texture = cls(width, height, target, tex_id.value) texture.min_filter = min_filter texture.mag_filter = mag_filter if target is gl.GL_TEXTURE_RECTANGLE: texture.tex_coords = (0, 0, 0, width, 0, 0, width, height, 0, 0, height, 0) else: texture.tex_coords = cls.tex_coords return texture
def on_draw(self): """ render the screen """ # This command has to happen before we start drawing arcade.start_render() self.board_sprite_list.draw() self.draw_grid(self.stone, self.stone_x, self.stone_y) gl.glFlush()
def on_expose(self, wid, event): width = wid.allocation.width height = wid.allocation.height self.display(width, height) if self.config.double_buffer: self.flip() else: gl.glFlush() return 0
def detach(self): if not self.canvas: return self.set_current() gl.glFlush() # needs to be in try/except? super(HeadlessContext, self).detach() egl.eglMakeCurrent(self.display_connection, 0, 0, None) self.egl_surface = None
def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing arcade.start_render() self.board_sprite_list.draw() # Manually draw the board #self.draw_grid(self.grid, 0, 0) gl.glFlush()
def detach(self): if not self.canvas: return self.set_current() gl.glFlush() # needs to be in try/except? super(XlibContext13, self).detach() glx.glXMakeContextCurrent(self.x_display, 0, 0, None) if self.glx_window: glx.glXDestroyWindow(self.x_display, self.glx_window) self.glx_window = None
def on_draw(self): self.fenetre3d.clear() #pgl.glPushMatrix() #pgl.glRotatef(self.fenetre3d.xRotation, 0, 1, 0) #pgl.glRotatef(0, 0, 1, 1) pgl.glBegin(ogl.GL_QUADS) #bleu pgl.glColor3ub(0, 0, 255) pgl.glVertex3f(0, 0, 0) pgl.glVertex3f(0, 10, 0) pgl.glVertex3f(self.arene.nb_colonne, 10, 0) pgl.glVertex3f(self.arene.nb_colonne, 0, 0) #rouge pgl.glColor3ub(255, 0, 0) pgl.glVertex3f(self.arene.nb_colonne, 0, 0) pgl.glVertex3f(self.arene.nb_colonne, 10, 0) pgl.glVertex3f(self.arene.nb_colonne, 10, self.arene.nb_ligne) pgl.glVertex3f(self.arene.nb_colonne, 0, self.arene.nb_ligne) #vert pgl.glColor3ub(0, 255, 0) pgl.glVertex3f(0, 0, self.arene.nb_ligne) pgl.glVertex3f(0, 10, self.arene.nb_ligne) pgl.glVertex3f(self.arene.nb_colonne, 10, self.arene.nb_ligne) pgl.glVertex3f(self.arene.nb_colonne, 0, self.arene.nb_ligne) #jaune pgl.glColor3ub(255, 255, 0) pgl.glVertex3f(00, 0, 00) pgl.glVertex3f(00, 10, 00) pgl.glVertex3f(00, 10, self.arene.nb_ligne) pgl.glVertex3f(00, 0, self.arene.nb_ligne) #blanc pgl.glColor3ub(255, 255, 255) pgl.glVertex3f(00, 0, self.arene.nb_ligne) pgl.glVertex3f(00, 0, 0) pgl.glVertex3f(self.arene.nb_colonne, 0, 0) pgl.glVertex3f(self.arene.nb_colonne, 0, self.arene.nb_ligne) self.draw() pgl.glEnd() """Permet de faire un screenshot""" kitten = pyglet.image.load('balise2.png') sprite = pyglet.sprite.Sprite(kitten) sprite.set_position(00, 80) sprite.draw() pyglet.image.get_buffer_manager().get_color_buffer().save( 'screenshot.png') pgl.glFlush()
def paintGL(self): _import_gl() glClear(GL_COLOR_BUFFER_BIT) glColor3f(1.0,1.0,1.0) glLoadIdentity() self.lookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) glScalef(1.0, 2.0, 1.0) glBegin(GL_TRIANGLES) glNormal3f(1,0,0) glVertex3f(1,0,0) glVertex3f(0,1,0) glVertex3f(1,1,0) glEnd() glFlush()
def close(self): # clear out the GLX context. Can fail if current context already # destroyed (on exit, say). try: gl.glFlush() except gl.GLException: pass glx.glXMakeCurrent(self._x_display, 0, None) self._unmap() if self._glx_window: glx.glXDestroyWindow(self._x_display, self._glx_window) if self._window: xlib.XDestroyWindow(self._x_display, self._window) self._window = None self._glx_window = None
def render(self, mode='human'): img = self.last_obs if mode == 'rgb_array': return img if self.window is None: config = pyglet.gl.Config(double_buffer=True) self.window = pyglet.window.Window(width=self.window_width, height=self.window_height, resizable=False, config=config) self.window.clear() self.window.switch_to() img_width = img.shape[1] img_height = img.shape[0] img = np.ascontiguousarray(np.flip(img, axis=0)) img_data = pyglet.image.ImageData( img_width, img_height, 'RGB', img.ctypes.data_as(POINTER(GLubyte)), pitch=img_width * 3, ) img_left = (self.window_width - img_width) // 2 img_top = (self.window_height - img_height) // 2 img_data.blit(img_left, img_top, 0, width=img_width, height=img_height) for a_label in self.labels.values(): # Draw the text label in the window a_label.draw() # Force execution of queued commands glFlush() # If we are not running the Pyglet event loop, # we have to manually flip the buffers and dispatch events if mode == 'human': self.window.flip() self.window.dispatch_events()
def on_draw(self): self.frame += 1 def search_and_update(origin): try: origin.event_update() except AttributeError: pass origin.determine_orientation() for obj in origin.children: search_and_update(obj) for obj in self.children: search_and_update(obj) arcade.start_render() self.sprite_list.draw() gl.glFlush()
def close(self): # clear out the GLX context. Can fail if current context already # destroyed (on exit, say). try: gl.glFlush() except gl.GLException: pass glx.glXMakeCurrent(self._x_display, 0, None) self._unmap() if self._glx_window: glx.glXDestroyWindow(self._x_display, self._glx_window) if self._window: xlib.XDestroyWindow(self._x_display, self._window) self._window = None self._glx_window = None if _have_utf8: xlib.XDestroyIC(self._x_ic) xlib.XCloseIM(self._x_im)
def create_point_texture(size, feather=0): """Create and load a circular grayscale image centered in a square texture with a width and height of size. The radius of the circle is size / 2. Since size is used as the texture width and height, it should typically be a power of two. Feather determines the softness of the edge of the circle. The default, zero, creates a hard edged circle. Larger feather values create softer edges for blending. The point at the center of the texture is always white. Return the OpenGL texture name (id) for the resulting texture. This value can be passed directy to a texturizer or glBindTexture """ from pyglet import gl assert feather >= 0, 'Expected feather value >= 0' coords = range(size) texel = (gl.GLfloat * size**2)() r = size / 2.0 c = feather + 1.0 for y in coords: col = y * size for x in coords: d = math.sqrt((x - r)**2 + (y - r)**2) if d < r and (1.0 - 1.0 / (d / r - 1.0)) < 100: texel[x + col] = c**2 / c**(1.0 - 1.0 / (d / r - 1.0)) else: texel[x + col] = 0 id = gl.GLuint() gl.glGenTextures(1, ctypes.byref(id)) gl.glBindTexture(gl.GL_TEXTURE_2D, id.value) gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 4) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_LUMINANCE, size, size, 0, gl.GL_LUMINANCE, gl.GL_FLOAT, ctypes.byref(texel)) gl.glFlush() return id.value
def draw(self): gl.glColor3f(*self.color) gl.glCallList(self.square) gl.glFlush()
def render(self, mode='human', close=False, text=False): """ Render the environment for human viewing """ if close: if self.window: self.window.close() return top_down = mode == 'top_down' # Render the image top = self._render_img( WINDOW_WIDTH, WINDOW_HEIGHT, self.multi_fbo_human, self.final_fbo_human, self.img_array_human, top_down = True ) bot = self._render_img( WINDOW_WIDTH, WINDOW_HEIGHT, self.multi_fbo_human, self.final_fbo_human, self.img_array_human, top_down = False ) win_width = WINDOW_WIDTH if self._view_mode == FULL_VIEW_MODE: img = np.concatenate((top, bot), axis=1) win_width = 2*WINDOW_WIDTH elif self._view_mode == TOP_DOWN_VIEW_MODE: img = top else: img = bot if self.window is not None: self.window.set_size(win_width, WINDOW_HEIGHT) # self.undistort - for UndistortWrapper if self.distortion and not self.undistort and mode != "free_cam": img = self.camera_model.distort(img) if mode == 'rgb_array': return img from pyglet import gl, window, image if self.window is None: config = gl.Config(double_buffer=False) self.window = window.Window( width=win_width, height=WINDOW_HEIGHT, resizable=False, config=config ) self.window.clear() self.window.switch_to() self.window.dispatch_events() # Bind the default frame buffer gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) # Setup orghogonal projection gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glOrtho(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT, 0, 10) # Draw the image to the rendering window width = img.shape[1] height = img.shape[0] img = np.ascontiguousarray(np.flip(img, axis=0)) img_data = image.ImageData( width, height, 'RGB', img.ctypes.data_as(POINTER(gl.GLubyte)), pitch=width * 3, ) img_data.blit( 0, 0, 0, width=WINDOW_WIDTH, height=WINDOW_HEIGHT ) # Display position/state information if text and mode != "free_cam": x, y, z = self.cur_pos self.text_label.text = "pos: (%.2f, %.2f, %.2f), angle: %d, steps: %d, speed: %.2f m/s" % ( x, y, z, int(self.cur_angle * 180 / math.pi), self.step_count, self.speed ) self.text_label.draw() # Force execution of queued commands gl.glFlush()
def drawVertexbuffers(vertexBuffer, *args, mode=GL.GL_TRIANGLES, flush=True): """Draw a vertex buffer using glDrawArrays. This method does not require shaders. Parameters ---------- vertexBuffer : :obj:`Vertexbuffer` Vertex buffer descriptor, must have 'bufferType' as GL_VERTEX_ARRAY. Optional vertex buffer descriptors can be passed as seperate arguments, they must have 'bufferTypes' as GL_TEXTURE_COORD_ARRAY, GL_NORMAL_ARRAY or GL_COLOR_ARRAY. mode : :obj:`int` Drawing mode to use (e.g. GL_TRIANGLES, GL_QUADS, GL_POINTS, etc.) flush : :obj:`bool` Flush queued drawing commands before returning. Returns ------- None Examples -------- # vertices of a triangle verts = [ 1.0, 1.0, 0.0, # v0 0.0, -1.0, 0.0, # v1 -1.0, 1.0, 0.0] # v2 # triangle vertex colors colors = [1.0, 0.0, 0.0, # v0 0.0, 1.0, 0.0, # v1 0.0, 0.0, 1.0] # v2 # load vertices to graphics device, return a descriptor vertexBuffer = createVertexbuffer(verts, 3) colorBuffer = createVertexbuffer(c, 3, GL.GL_COLOR_ARRAY) # draw the VBO drawVertexbuffer(vertexBuffer, colorBuffer, GL.GL_TRIANGLES) """ # must have a vertex pointer assert vertexBuffer.bufferType == GL.GL_VERTEX_ARRAY # bind and set the vertex pointer GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertexBuffer.id) GL.glVertexPointer(vertexBuffer.vertexSize, vertexBuffer.dtype, 0, None) GL.glEnableClientState(vertexBuffer.bufferType) # handle additional buffers if args: for buffer in args: # check if the number of indicies are the same if vertexBuffer.indices != buffer.indices: raise RuntimeError("Vertex buffer indices do not match!") GL.glBindBuffer(GL.GL_ARRAY_BUFFER, buffer.id) if buffer.bufferType == GL.GL_TEXTURE_COORD_ARRAY: GL.glTexCoordPointer(buffer.dtype, 0, None) elif buffer.bufferType == GL.GL_NORMAL_ARRAY: GL.glNormalPointer(buffer.dtype, 0, None) elif buffer.bufferType == GL.GL_COLOR_ARRAY: GL.glColorPointer(buffer.vertexSize, buffer.dtype, 0, None) GL.glEnableClientState(buffer.bufferType) GL.glDrawArrays(mode, 0, vertexBuffer.indices) # draw arrays # reset GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0) GL.glDisableClientState(vertexBuffer.bufferType) if args: for vbo in args: GL.glDisableClientState(vbo.bufferType) if flush: GL.glFlush()
stim1_no_change_draw_times.clear() stim2_no_change_draw_times.clear() demo_start=window.flip() event.clearEvents() fcount=0 stim1_type=stim1.__class__.__name__+u' ' stim2_type=stim2.__class__.__name__+u' ' while True: # For the textBox and TextStim resource, change the text every # chng_txt_each_flips, and record the time it takes to update the text # and redraw() each resource type. # # Make sure timing of stim is for the time taken for that stim alone. ;) gl.glFlush() gl.glFinish() if fcount==0 or fcount%chng_txt_each_flips==0: t=getRandomString(text_length) stim1_dur=updateStimText(stim1,stim1_type+t) stim1_txt_change_draw_times.append(stim1_dur) t=getRandomString(text_length) stim2_dur=updateStimText(stim2,stim2_type+t) stim2_txt_change_draw_times.append(stim2_dur) else: stim1_dur=updateStimText(stim1) stim1_no_change_draw_times.append(stim1_dur) stim2_dur=updateStimText(stim2) stim2_no_change_draw_times.append(stim2_dur)