def circle(pos, radius, color=(1.0,1.0,1.0), alpha=1.0,segments=6): """ Draws a circle with gluDisk :param pos: center of the circle :type pos: 2-float tuple :param radius: radius of the circle :type radius: float :param color: the color in [0..1] range :type color: 3-float tuple :param alpha: the alpha value in [0..1] range :param segments: number of segments :type segments: int """ glDisable(GL_TEXTURE_2D) c = gluNewQuadric() glColor4f(color[0], color[1], color[2], alpha) glPushMatrix() glTranslatef(pos[0], pos[1], 0) gluDisk(c, 0, radius, segments, 1) glPopMatrix() glColor4f(1.0,1.0,1.0,1.0) glEnable(GL_TEXTURE_2D)
def draw_points(self): self.points_lock.acquire() try: from pyglet.gl import glCallList, glBegin, GL_LINE_STRIP, glColor4f, glVertex2f, glEnd # line from previous iterate to next iterate of function glBegin(GL_LINE_STRIP) glColor4f(1, 1, 1, 0.3) state_index = self.state_indices[0] for i in [1, 2]: state_previous = self.point.state[state_index] self.point.state = self.system.iterate(self.point.state, self.point.parameters) glVertex2f(state_previous, state_previous) glVertex2f(state_previous, self.point.state[state_index]) glEnd() # call display lists, doesn't work in init_points() if self.server.iteration <= 1: glCallList(self.iterate_list) glCallList(self.reflection_list) except Exception, detail: print "draw_points()", type(detail), detail
def draw(self, win=None): """Draw the current frame to a particular visual.Window (or to the default win for this object if not specified). The current position in the movie will be determined automatically. This method should be called on every frame that the movie is meant to appear. """ if (self.status == NOT_STARTED or (self.status == FINISHED and self.loop)): self.play() elif self.status == FINISHED and not self.loop: return if win is None: win = self.win self._selectWindow(win) self._updateFrameTexture() # will check if it's needed # scale the drawing frame and get to centre of field GL.glPushMatrix() # push before drawing, pop after # push the data for client attributes GL.glPushClientAttrib(GL.GL_CLIENT_ALL_ATTRIB_BITS) self.win.setScale('pix') # move to centre of stimulus and rotate vertsPix = self.verticesPix # bind textures GL.glActiveTexture(GL.GL_TEXTURE1) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glEnable(GL.GL_TEXTURE_2D) GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID) GL.glEnable(GL.GL_TEXTURE_2D) # sets opacity (1,1,1 = RGB placeholder) GL.glColor4f(1, 1, 1, self.opacity) array = (GL.GLfloat * 32)( 1, 1, # texture coords vertsPix[0, 0], vertsPix[0, 1], 0., # vertex 0, 1, vertsPix[1, 0], vertsPix[1, 1], 0., 0, 0, vertsPix[2, 0], vertsPix[2, 1], 0., 1, 0, vertsPix[3, 0], vertsPix[3, 1], 0., ) # 2D texture array, 3D vertex array GL.glInterleavedArrays(GL.GL_T2F_V3F, 0, array) GL.glDrawArrays(GL.GL_QUADS, 0, 4) GL.glPopClientAttrib() GL.glPopAttrib() GL.glPopMatrix() # unbind the textures GL.glActiveTexture(GL.GL_TEXTURE0) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) GL.glEnable(GL.GL_TEXTURE_2D) # implicitly disables 1D
def core_draw(self): super(PointDisplayCanvas, self).core_draw() points,point_colors, linesegs,lineseg_colors = self.extra_points_linesegs gl.glColor4f(0.0,1.0,0.0,1.0) # green point if points is not None: if point_colors is None: point_colors = [ (0,1,0,1) ] * len(points) gl.glBegin(gl.GL_POINTS) for color_4tuple,pt in zip(point_colors,points): gl.glColor4f(*color_4tuple) gl.glVertex2f(pt[0],pt[1]) gl.glEnd() if linesegs is not None: if lineseg_colors is None: lineseg_colors = [ (0,1,0,1) ] * len(linesegs) for color_4tuple,this_lineseg in zip(lineseg_colors,linesegs): gl.glBegin(gl.GL_LINE_STRIP) gl.glColor4f(*color_4tuple) for (x,y) in zip(this_lineseg[0::2],this_lineseg[1::2]): gl.glVertex2f(x,y) gl.glEnd() if self.red_points is not None: gl.glColor4f(1.0,0.0,0.0,0.5) # 50% alpha gl.glBegin(gl.GL_POINTS) for pt in self.red_points: gl.glVertex2f(pt[0],pt[1]) gl.glEnd() gl.glColor4f(1.0,1.0,1.0,1.0) # restore white color
def render_indicators(self, W, H): gl.glBegin(gl.GL_QUADS) s = W/40.0 h = H/40.0 gl.glColor4f(0,0,0,1) gl.glVertex3f(W, 0, 0) gl.glVertex3f(W, 5*h, 0) gl.glVertex3f(0, 5*h, 0) gl.glVertex3f(0, 0, 0) def vertical_ind(place, val, color): gl.glColor4f(color[0], color[1], color[2], 1) gl.glVertex3f((place+0)*s, h + h*val, 0) gl.glVertex3f((place+1)*s, h + h*val, 0) gl.glVertex3f((place+1)*s, h, 0) gl.glVertex3f((place+0)*s, h, 0) def horiz_ind(place, val, color): gl.glColor4f(color[0], color[1], color[2], 1) gl.glVertex3f((place+0)*s, 4*h , 0) gl.glVertex3f((place+val)*s, 4*h, 0) gl.glVertex3f((place+val)*s, 2*h, 0) gl.glVertex3f((place+0)*s, 2*h, 0) true_speed = np.sqrt(np.square(self.car.hull.linearVelocity[0]) + np.square(self.car.hull.linearVelocity[1])) vertical_ind(5, 0.02*true_speed, (1,1,1)) vertical_ind(7, 0.01*self.car.wheels[0].omega, (0.0,0,1)) # ABS sensors vertical_ind(8, 0.01*self.car.wheels[1].omega, (0.0,0,1)) vertical_ind(9, 0.01*self.car.wheels[2].omega, (0.2,0,1)) vertical_ind(10,0.01*self.car.wheels[3].omega, (0.2,0,1)) horiz_ind(20, -10.0*self.car.wheels[0].joint.angle, (0,1,0)) horiz_ind(30, -0.8*self.car.hull.angularVelocity, (1,0,0)) gl.glEnd() self.score_label.text = "%04i" % self.reward self.score_label.draw()
def _draw_rects(shape_list, vertex_vbo_id, texture_coord_vbo_id): """ Draw a set of rectangles using vertex buffers. This is more efficient than drawing them individually. """ GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glEnable(GL.GL_TEXTURE_2D) GL.glHint(GL.GL_POLYGON_SMOOTH_HINT, GL.GL_NICEST) GL.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST) # GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) # GL.glMatrixMode(GL.GL_MODELVIEW) # GL.glDisable(GL.GL_BLEND) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertex_vbo_id) GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY) GL.glEnableClientState(GL.GL_VERTEX_ARRAY) GL.glVertexPointer(2, GL.GL_FLOAT, 0, 0) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, texture_coord_vbo_id) offset = 0 for shape in shape_list: if shape.can_cache: texture_coord_vbo_id = None GL.glColor4f(1, 1, 1, shape.alpha) _render_rect_filled(shape, offset, shape.texture.texture_id, texture_coord_vbo_id) offset += 4 else: shape.draw()
def core_draw(self): super(PointDisplayCanvas, self).core_draw() points, point_colors, linesegs, lineseg_colors = self.extra_points_linesegs gl.glColor4f(0.0, 1.0, 0.0, 1.0) # green point if points is not None: if point_colors is None: point_colors = [(0, 1, 0, 1)] * len(points) gl.glBegin(gl.GL_POINTS) for color_4tuple, pt in zip(point_colors, points): gl.glColor4f(*color_4tuple) gl.glVertex2f(pt[0], pt[1]) gl.glEnd() if linesegs is not None: if lineseg_colors is None: lineseg_colors = [(0, 1, 0, 1)] * len(linesegs) gl.glBegin(gl.GL_LINES) for color_4tuple, (x0, y0, x1, y1) in zip(lineseg_colors, linesegs): gl.glColor4f(*color_4tuple) gl.glVertex2f(x0, y0) gl.glVertex2f(x1, y1) gl.glEnd() if self.red_points is not None: gl.glColor4f(1.0, 0.0, 0.0, 1.0) gl.glBegin(gl.GL_POINTS) for pt in self.red_points: gl.glVertex2f(pt[0], pt[1]) gl.glEnd() gl.glColor4f(1.0, 1.0, 1.0, 1.0) # restore white color
def draw(self, frame): # The gneneral plan here is: # 1. Get the dots in the range of 0-255. # 2. Create a texture with the dots data. # 3. Draw the texture, scaled up with nearest-neighbor. # 4. Draw a mask over the dots to give them a slightly more realistic look. gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glLoadIdentity() # Draw the dots in this color: #gl.glColor3f(1.0, 0.5, 0.25) gl.glScalef(1, -1, 1) gl.glTranslatef(0, -DMD_SIZE[1]*DMD_SCALE, 0) #data = frame.get_data_mult() #this new jk_get_data will read the dots using the dmd function #and convert them via the map to rGB. data = self.jk_get_data(frame) image = pyglet.image.ImageData(DMD_SIZE[0], DMD_SIZE[1], 'RGB', data, pitch=DMD_SIZE[0] * 3) gl.glTexParameteri(image.get_texture().target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) image.blit(0, 0, width=DMD_SIZE[0]*DMD_SCALE, height=DMD_SIZE[1]*DMD_SCALE) del image gl.glScalef(DMD_SCALE/float(MASK_SIZE), DMD_SCALE/float(MASK_SIZE), 1.0) gl.glColor4f(1.0, 1.0, 1.0, 1.0) self.mask_texture.blit_tiled(x=0, y=0, z=0, width=DMD_SIZE[0]*MASK_SIZE, height=DMD_SIZE[1]*MASK_SIZE)
def draw_circle(cx, cy, r, num_segments=None, mode=gl.GL_POLYGON, color=(1, 1, 1, 1)): if not num_segments: num_segments = get_num_circle_segments(r) theta = 2 * math.pi / float(num_segments) tangetial_factor = math.tan(theta) radial_factor = math.cos(theta) x = float(r) y = 0.0 gl.glColor4f(color[0], color[1], color[2], color[3]) gl.glBegin(mode) for i in xrange(num_segments): gl.glVertex2f(x + cx, y + cy) tx = y * -1 ty = x x += tx * tangetial_factor y += ty * tangetial_factor x *= radial_factor y *= radial_factor gl.glEnd()
def draw(self): glPushMatrix() glTranslatef(self.xoffset, self.yoffset, self.zoffset) def color(i): if i % self.graduations_major == 0: glColor4f(*self.color_grads_major) elif i % (self.graduations_major / 2) == 0: glColor4f(*self.color_grads_interm) else: if self.light: return False glColor4f(*self.color_grads_minor) return True # draw the grid glBegin(GL_LINES) for i in range(0, int(math.ceil(self.width + 1))): if color(i): glVertex3f(float(i), 0.0, 0.0) glVertex3f(float(i), self.depth, 0.0) for i in range(0, int(math.ceil(self.depth + 1))): if color(i): glVertex3f(0, float(i), 0.0) glVertex3f(self.width, float(i), 0.0) glEnd() # draw fill glColor4f(*self.color_fill) glRectf(0.0, 0.0, float(self.width), float(self.depth)) glPopMatrix()
def setupOpenGL(self): gl.glClearColor(0., 0., 0., 1.) gl.glColor4f(1.0, 0.0, 0.0, 0.5) gl.glEnable(gl.GL_DEPTH_TEST) #gl.glEnable(gl.GL_CULL_FACE) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
def draw(self): from miru.context import context gl.glEnable(gl.GL_LINE_STIPPLE) gl.glLineStipple(1, 0x51315) gl.glColor4f(*self.color) for c in self.metaCamera.cameras: vp = c.projection x = vp.x == 0 and 1 or vp.x width = vp.x == 0 and vp.width - 1 or vp.width width = (vp.x + vp.width) >= context.window.width and width - 1 or width y = vp.y == 0 and 1 or vp.y height = vp.y == 0 and vp.height - 1 or vp.height height = (vp.y + vp.height) >= context.window.height and height - 1 or height gl.glBegin(gl.GL_LINE_LOOP) gl.glVertex2f(x, y) gl.glVertex2f(x, y + height) gl.glVertex2f(x + width, y + height) gl.glVertex2f(x + width, y) gl.glEnd() gl.glDisable(gl.GL_LINE_LOOP) gl.glColor4f(1,1,1,1)
def line(a, b, color=(1.0,1.0,1.0), width=1, aa=False, alpha=1.0): """ Draws a line from point *a* to point *b* using GL_LINE_STRIP optionaly with GL_LINE_SMOOTH when *aa=True* :param a: Point a :type a: 2-float tuple :param b: Point b :type b: 2-float tuple :param color: the color in [0..1] range :type color: 3-float tuple :param width: The with for glLineWidth() :param aa: Anti aliasing Flag :param alpha: the alpha value in [0..1] range """ glColor4f(color[0], color[1], color[2], alpha) glLineWidth(width) if aa: glEnable(GL_LINE_SMOOTH) draw(2, GL_LINES, ('v2f', (a[0], a[1], b[0], b[1])))
def rect(a, b, color=(1.0,1.0,1.0), alpha=1.0): """ Draws a rectangle in the plane spanned by a,b with GL_QUADS :param a: Point a :type a: 2-float tuple :param b: Point b :type b: 2-float tuple :param color: the color in [0..1] range :type color: 3-float tuple :param aa: Anti aliasing Flag :param alpha: the alpha value in [0..1] range """ glDisable(GL_TEXTURE_2D) glBegin(GL_QUADS) glVertex3f(a[0], a[1], 0) glVertex3f(b[0], a[1], 0) glVertex3f(b[0], b[1], 0) glVertex3f(a[0], b[1], 0) glEnd() glEnable(GL_TEXTURE_2D) glColor4f(color+(alpha,))
def draw_points(self): self.points_lock.acquire() try: from pyglet.gl import glBegin, glEnd, GL_POINTS, glColor4f, glVertex2f glBegin(GL_POINTS) for i in xrange(0, len(self.points)): p = self.points[i] parameter_index = self.parameter_indices[0] state_index = self.state_indices[0] glColor4f(1, 1, 1, p.age / (self.age_max*2.0)) glVertex2f(p.parameters[parameter_index], p.state[state_index]) p.state = self.system.iterate(p.state, p.parameters) p.age += 1 #if p.age >= self.age_max: # self.points[i] = OrbitPoint(tool=self, varying_parameter=p.parameters[parameter_index]) glEnd() except Exception, detail: print 'draw_points()', type(detail), detail
def draw(self, offset=(0, 0)): w, h = offset r, g, b, a = self.color pyglet.graphics.draw(len(self.vertices), gl.GL_POLYGON, ('v2f', [int(p) for p in flatten((x+w, y+h) for x, y in self.vertices)]), ('c4B', [int(c) for c in ((r, g, b, a*255) * len(self.vertices))]), ) gl.glColor4f(1, 1, 1, 1)
def set_state(self): gl.glPushAttrib(gl.GL_LINE_BIT | gl.GL_CURRENT_BIT) gl.glLineWidth(2) if self.facet.is_border_facet: colour = self.BORDER_FACET_COLOUR else: colour = self.INNER_FACET_COLOUR gl.glColor4f(*colour)
def draw(self): if not self.should_draw: return glColor3f(1, 1, 1) self.texture.blit(0, 100) glColor4f(1, 1, 1, 0.65) glRectf(0, 0, self.width, 100) self.lbls.draw() self.draw_subcontrols()
def rectangle(x1, y1, x2, y2, color=(1, 0, 0, 1)): glColor4f(*color) glBegin(GL_POLYGON) glVertex2f(x1, y1) glVertex2f(x1, y2) glVertex2f(x2, y2) glVertex2f(x2, y1) glEnd()
def draw(self): glPushMatrix() glRotatef(self.angle, 0., 0., 1.) glScalef(self.scale, 1., 1.) glTranslatef(0., -common_res.ray.height/2, 0.) glColor4f(1., 1., 1., self.alpha) common_res.ray.blit(0, 0) glPopMatrix()
def draw_grid(self): gl.glColor4f(0.23, 0.23, 0.23, 1.0) #Horizontal lines for i in range(rows): graphics.draw(2, gl.GL_LINES, ('v2i', (0, i * cell_size, window_width, i * cell_size))) #Vertical lines for j in range(columns): graphics.draw(2, gl.GL_LINES, ('v2i', (j * cell_size, 0, j * cell_size, window_height)))
def draw(self, win=None): #set the window to draw to if win==None: win=self.win if win.winType=='pyglet': win.winHandle.switch_to() #work out next default depth if self.depth==0: thisDepth = self.win._defDepth self.win._defDepth += _depthIncrements[self.win.winType] else: thisDepth=self.depth GL.glPushMatrix() #scale and rotate prevScale = self.win.setScale(self._winScale) GL.glTranslatef(self._posRendered[0],self._posRendered[1],thisDepth)#NB depth is set already GL.glRotatef(self.ori,0.0,0.0,1.0) self.win.setScale('pix',None, prevScale) if self._useShaders: #then rgb needs to be set as glColor #setup color desiredRGB = (self.rgb*self.contrast+1)/2.0#RGB in range 0:1 and scaled for contrast if numpy.any(desiredRGB**2.0>1.0): desiredRGB=[0.6,0.6,0.4] GL.glColor4f(desiredRGB[0],desiredRGB[1],desiredRGB[2], self.opacity) else: #color is set in texture, so set glColor to white GL.glColor4f(1,1,1,1) GL.glDisable(GL.GL_DEPTH_TEST) #should text have a depth or just on top? #update list if necss and then call it if self.win.winType=='pyglet': #and align based on x anchor if self.alignHoriz=='right': GL.glTranslatef(-self.width,0,0)#NB depth is set already if self.alignHoriz in ['center', 'centre']: GL.glTranslatef(-self.width/2,0,0)#NB depth is set already #unbind the mask texture regardless GL.glActiveTexture(GL.GL_TEXTURE1) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) #unbind the main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) #then allow pyglet to bind and use texture during drawing self.glyphStr.draw() GL.glDisable(GL.GL_TEXTURE_2D) else: #for pygame we should (and can) use a drawing list if self.needUpdate: self._updateList() GL.glCallList(self._listID) GL.glEnable(GL.GL_DEPTH_TEST) # Enables Depth Testing GL.glPopMatrix()
def draw_fan(center, vertices, color): gl.glPushMatrix() gl.glColor4f(*color) gl.glBegin(gl.GL_TRIANGLE_FAN) gl.glVertex2f(center[0], center[1]) for vertex in vertices: gl.glVertex2f(vertex[0], vertex[1]) gl.glEnd() gl.glPopMatrix()
def draw_ui(self): if DropDownMenu._submenu_count >= self.level: gl.glColor4f(1, 1, 1, 0.5) gl.glRectf(self.x, self.y, self.x + self.width, self.y - self.height) gl.glColor4f(0, 0, 0, 0.5) gl.glRectf(self.x + 1, self.y - 1, self.x + self.width - 1, self.y - self.height + 1) super(DropDownMenu, self).draw() for sm in self.submenus.values(): sm.draw()
def line(x, y, size, angle, color=(1, 0, 0, 1), thickness=1): x1, y1 = x, y x2, y2 = x1 + cos(angle) * size, y1 + sin(angle) * size glColor4f(*color) glLineWidth(thickness) glBegin(GL_LINES) glVertex2f(x1, y1) glVertex2f(x2, y2) glEnd()
def draw(self): ray = L('c-ray') glPushMatrix() glRotatef(self.angle, 0., 0., 1.) glScalef(self.scale, 1., 1.) glTranslatef(0., -ray.height/2, 0.) glColor4f(1., 1., 1., self.alpha) ray.blit(0, 0) glPopMatrix()
def draw(self): if self.window.debug and not self.hidden: gl.glColor4f(*self.color) graphics.draw(4, gl.GL_QUADS, ('v2f', self.rectangle)) if not self.fg_batch: for l in self.stat_labels_l: l.draw() for l in self.stat_labels_r: l.draw()
def init_points(self): self.points_lock.acquire() try: from pyglet.gl import ( glGenLists, glNewList, GL_COMPILE, glBegin, GL_LINE_STRIP, GL_LINES, glColor4f, glVertex2f, glEnd, glEndList, glEnable, ) self.server.clear_each_frame = False self.server.iteration = 0 # initial state/parameters self.point = CobwebPoint(tool=self) # create display list for first iterate of function self.iterate_list = glGenLists(1) glNewList(self.iterate_list, GL_COMPILE) glBegin(GL_LINE_STRIP) glColor4f(217 / 255.0, 115 / 255.0, 56 / 255.0, 0.9) p = CobwebPoint(tool=self) state_index = self.state_indices[0] for i in numpy.arange(self.state_ranges[state_index][0], self.state_ranges[state_index][1], 0.001): p.state[state_index] = i state_new = self.system.iterate(p.state, p.parameters) glVertex2f(i, state_new[state_index]) glEnd() glEndList() # create display list for axis of reflection self.reflection_list = glGenLists(1) glNewList(self.reflection_list, GL_COMPILE) glBegin(GL_LINES) glColor4f(217 / 255.0, 88 / 255.0, 41 / 255.0, 0.9) glVertex2f(self.state_ranges[state_index][0], self.state_ranges[state_index][0]) glVertex2f(self.state_ranges[state_index][1], self.state_ranges[state_index][1]) glEnd() glEndList() except Exception, detail: print "init_points()", type(detail), detail
def draw(self): #print self.body.postion s = self.size # just a shorthand gl.glColor4f(*(self.colour + (self.opacity,))) with shiftView(Vec2d(self.body.position)): gl.glRotatef(degrees(self.body.angle), 0.1,0.2,1.0) gl.glBegin(gl.GL_POLYGON) for vertex in self.verticies: gl.glVertex2f(*vertex) gl.glEnd()
def draw(self): gl.glColor4f(*self.color) x, y = director.get_window_size() gl.glBegin(gl.GL_QUADS) gl.glVertex2f( 0, 0 ) gl.glVertex2f( 0, y ) gl.glVertex2f( x, y ) gl.glVertex2f( x, 0 ) gl.glEnd() gl.glColor4f(1,1,1,1)
def _display_movements(self, mode_2d=False): self.vertex_buffer.bind() has_vbo = isinstance(self.vertex_buffer, VertexBufferObject) if has_vbo: glVertexPointer(3, GL_FLOAT, 0, None) else: glVertexPointer(3, GL_FLOAT, 0, self.vertex_buffer.ptr) self.vertex_color_buffer.bind() if has_vbo: glColorPointer(4, GL_FLOAT, 0, None) else: glColorPointer(4, GL_FLOAT, 0, self.vertex_color_buffer.ptr) # Prevent race condition by using the number of currently loaded layers max_layers = self.layers_loaded start = 0 if self.num_layers_to_draw <= max_layers: end_prev_layer = self.layer_stops[self.num_layers_to_draw - 1] else: end_prev_layer = -1 end = self.layer_stops[min(self.num_layers_to_draw, max_layers)] glDisableClientState(GL_COLOR_ARRAY) glColor4f(*self.color_printed) # Draw printed stuff until end or end_prev_layer cur_end = min(self.printed_until, end) if not self.only_current: if 0 <= end_prev_layer <= cur_end: glDrawArrays(GL_LINES, start, end_prev_layer) elif cur_end >= 0: glDrawArrays(GL_LINES, start, cur_end) glEnableClientState(GL_COLOR_ARRAY) # Draw nonprinted stuff until end_prev_layer start = max(cur_end, 0) if end_prev_layer >= start: if not self.only_current: glDrawArrays(GL_LINES, start, end_prev_layer - start) cur_end = end_prev_layer # Draw current layer if end_prev_layer >= 0: glDisableClientState(GL_COLOR_ARRAY) # Backup & increase line width orig_linewidth = (GLfloat)() glGetFloatv(GL_LINE_WIDTH, orig_linewidth) glLineWidth(2.0) glColor4f(*self.color_current_printed) if cur_end > end_prev_layer: glDrawArrays(GL_LINES, end_prev_layer, cur_end - end_prev_layer) glColor4f(*self.color_current) if end > cur_end: glDrawArrays(GL_LINES, cur_end, end - cur_end) # Restore line width glLineWidth(orig_linewidth) glEnableClientState(GL_COLOR_ARRAY) # Draw non printed stuff until end (if not ending at a given layer) start = max(self.printed_until, 0) end = end - start if end_prev_layer < 0 and end > 0 and not self.only_current: glDrawArrays(GL_LINES, start, end) self.vertex_buffer.unbind() self.vertex_color_buffer.unbind()
def _draw_rects(shape_list: List[Sprite], vertex_vbo_id: gl.GLuint, texture_coord_vbo_id: gl.GLuint, change_x: float, change_y: float): """ Draw a set of rectangles using vertex buffers. This is more efficient than drawing them individually. """ if len(shape_list) == 0: return gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_TEXTURE_2D ) # As soon as this happens, can't use drawing commands # 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.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, gl.GL_NICEST) gl.glHint(gl.GL_PERSPECTIVE_CORRECTION_HINT, gl.GL_NICEST) # gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) # gl.glMatrixMode(gl.GL_MODELVIEW) # gl.glDisable(gl.GL_BLEND) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vertex_vbo_id) gl.glEnableClientState(gl.GL_TEXTURE_COORD_ARRAY) gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glVertexPointer(2, gl.GL_FLOAT, 0, 0) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, texture_coord_vbo_id) last_alpha = shape_list[0].alpha gl.glColor4f(1, 1, 1, last_alpha) gl.glLoadIdentity() # gl.glLoadIdentity() gl.glTranslatef(change_x, change_y, 0) # Ideally, we want to draw these in "batches." # We seek to find groups of squares with the same texture. Then draw # them all at once. last_texture_id = None last_alpha = 1 batch_count = 0 offset = 0 batch_offset = 0 texture_coord_vbo_id = None for shape in shape_list: if shape.texture.texture_id != last_texture_id or shape.alpha != last_alpha: # Ok, if the 'if' triggered above, we are now looking at a different # texture than we looked at with the last loop. So draw the last # "batch" of squares. We'll start a new batch with the current # square but not draw it yet if batch_count > 0: gl.glColor4f(1, 1, 1, last_alpha) _render_rect_filled(batch_offset, last_texture_id, texture_coord_vbo_id, batch_count) batch_count = 0 batch_offset = offset last_texture_id = shape.texture.texture_id last_alpha = shape.alpha batch_count += 4 offset += 4 # Draw the last batch, if it exists _render_rect_filled(batch_offset, last_texture_id, texture_coord_vbo_id, batch_count) gl.glDisable(gl.GL_TEXTURE_2D)
def render(self, mode='human', close=False, RENDER_LIDAR=True, lidar_scan_override=None, goal_override=None, save_to_file=False, show_score=False, robocentric=False): if close: if self.viewer is not None: self.viewer.close() return if self.lidar_scan is None: # check that reset has been called return if mode == 'traj': self.soadrl_sim.render('traj') elif mode in ['human', 'rings']: # Window and viewport size WINDOW_W = 256 WINDOW_H = 256 VP_W = WINDOW_W VP_H = WINDOW_H from gym.envs.classic_control import rendering import pyglet from pyglet import gl # Create viewer if self.viewer is None: self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H) self.transform = rendering.Transform() self.transform.set_scale(10, 10) self.transform.set_translation(128, 128) self.score_label = pyglet.text.Label('0000', font_size=12, x=20, y=WINDOW_H * 2.5 / 40.00, anchor_x='left', anchor_y='center', color=(255, 255, 255, 255)) # self.transform = rendering.Transform() self.currently_rendering_iteration = 0 self.image_lock = threading.Lock() def make_circle(c, r, res=10): thetas = np.linspace(0, 2 * np.pi, res + 1)[:-1] verts = np.zeros((res, 2)) verts[:, 0] = c[0] + r * np.cos(thetas) verts[:, 1] = c[1] + r * np.sin(thetas) return verts # Render in pyglet with self.image_lock: self.currently_rendering_iteration += 1 self.viewer.draw_circle(r=10, color=(0.3, 0.3, 0.3)) win = self.viewer.window win.switch_to() win.dispatch_events() win.clear() gl.glViewport(0, 0, VP_W, VP_H) # colors bgcolor = np.array([0.4, 0.8, 0.4]) obstcolor = np.array([0.3, 0.3, 0.3]) goalcolor = np.array([1., 1., 0.3]) goallinecolor = 0.9 * bgcolor nosecolor = np.array([0.3, 0.3, 0.3]) lidarcolor = np.array([1., 0., 0.]) agentcolor = np.array([0., 1., 1.]) # Green background gl.glBegin(gl.GL_QUADS) gl.glColor4f(bgcolor[0], bgcolor[1], bgcolor[2], 1.0) gl.glVertex3f(0, VP_H, 0) gl.glVertex3f(VP_W, VP_H, 0) gl.glVertex3f(VP_W, 0, 0) gl.glVertex3f(0, 0, 0) gl.glEnd() # Transform rx = self.soadrl_sim.robot.px ry = self.soadrl_sim.robot.py rth = self.soadrl_sim.robot.theta if robocentric: # sets viewport = robocentric a.k.a T_sim_in_viewport = T_sim_in_robocentric from pose2d import inverse_pose2d T_sim_in_robot = inverse_pose2d(np.array([rx, ry, rth])) # T_robot_in_robocentric is trans(128, 128), scale(10), rot(90deg) # T_sim_in_robocentric = T_sim_in_robot * T_robot_in_robocentric rot = np.pi / 2. scale = 20 trans = (WINDOW_W / 2., WINDOW_H / 2.) T_sim_in_robocentric = [ trans[0] + scale * (T_sim_in_robot[0] * np.cos(rot) - T_sim_in_robot[1] * np.sin(rot)), trans[1] + scale * (T_sim_in_robot[0] * np.sin(rot) + T_sim_in_robot[1] * np.cos(rot)), T_sim_in_robot[2] + rot, ] self.transform.set_translation(T_sim_in_robocentric[0], T_sim_in_robocentric[1]) self.transform.set_rotation(T_sim_in_robocentric[2]) self.transform.set_scale(scale, scale) # self.transform.set_scale(20, 20) self.transform.enable( ) # applies T_sim_in_viewport to below coords (all in sim frame) # Map closed obstacles --- for poly in self.soadrl_sim.obstacle_vertices: gl.glBegin(gl.GL_LINE_LOOP) gl.glColor4f(obstcolor[0], obstcolor[1], obstcolor[2], 1) for vert in poly: gl.glVertex3f(vert[0], vert[1], 0) gl.glEnd() # LIDAR if RENDER_LIDAR: px = self.soadrl_sim.robot.px py = self.soadrl_sim.robot.py angle = self.soadrl_sim.robot.theta # LIDAR rays scan = lidar_scan_override if scan is None: scan = self.lidar_scan lidar_angles = self.lidar_angles x_ray_ends = px + scan * np.cos(lidar_angles) y_ray_ends = py + scan * np.sin(lidar_angles) is_in_fov = np.cos(lidar_angles - angle) >= 0.78 for ray_idx in range(len(scan)): end_x = x_ray_ends[ray_idx] end_y = y_ray_ends[ray_idx] gl.glBegin(gl.GL_LINE_LOOP) if is_in_fov[ray_idx]: gl.glColor4f(1., 1., 0., 0.1) else: gl.glColor4f(lidarcolor[0], lidarcolor[1], lidarcolor[2], 0.1) gl.glVertex3f(px, py, 0) gl.glVertex3f(end_x, end_y, 0) gl.glEnd() # Agent body for n, agent in enumerate([self.soadrl_sim.robot] + self.soadrl_sim.humans): px = agent.px py = agent.py angle = agent.theta r = agent.radius # Agent as Circle poly = make_circle((px, py), r) gl.glBegin(gl.GL_POLYGON) if n == 0: color = np.array([1., 1., 1.]) else: color = agentcolor gl.glColor4f(color[0], color[1], color[2], 1) for vert in poly: gl.glVertex3f(vert[0], vert[1], 0) gl.glEnd() # Direction triangle xnose = px + r * np.cos(angle) ynose = py + r * np.sin(angle) xright = px + 0.3 * r * -np.sin(angle) yright = py + 0.3 * r * np.cos(angle) xleft = px - 0.3 * r * -np.sin(angle) yleft = py - 0.3 * r * np.cos(angle) gl.glBegin(gl.GL_TRIANGLES) gl.glColor4f(nosecolor[0], nosecolor[1], nosecolor[2], 1) gl.glVertex3f(xnose, ynose, 0) gl.glVertex3f(xright, yright, 0) gl.glVertex3f(xleft, yleft, 0) gl.glEnd() # Goal xgoal = self.soadrl_sim.robot.gx ygoal = self.soadrl_sim.robot.gy r = self.soadrl_sim.robot.radius if goal_override is not None: xgoal, ygoal = goal_override # Goal markers gl.glBegin(gl.GL_TRIANGLES) gl.glColor4f(goalcolor[0], goalcolor[1], goalcolor[2], 1) triangle = make_circle((xgoal, ygoal), r, res=3) for vert in triangle: gl.glVertex3f(vert[0], vert[1], 0) gl.glEnd() # Goal line gl.glBegin(gl.GL_LINE_LOOP) gl.glColor4f(goallinecolor[0], goallinecolor[1], goallinecolor[2], 1) gl.glVertex3f(rx, ry, 0) gl.glVertex3f(xgoal, ygoal, 0) gl.glEnd() # -- self.transform.disable() # Text self.score_label.text = "" if show_score: self.score_label.text = "R {}".format(self.episode_reward) self.score_label.draw() win.flip() if save_to_file: pyglet.image.get_buffer_manager().get_color_buffer().save( "/tmp/navreptrainenv{:05}.png".format( self.total_steps)) return self.viewer.isopen else: raise NotImplementedError
def draw_cartpole(cartpole, screen_width, screen_height): world_width = cartpole.x_threshold*2 scale = screen_width/world_width carty = 100 # TOP OF CART polewidth = 10.0 polelen = scale * cartpole._pole_length # target pole position is relative to the center of the screen targetpos = scale * (cartpole._target_pole_position + world_width/2) cartwidth = 50.0 cartheight = 30.0 # Draw track glColor4f(0,0,0,1.0) glLineWidth(1.0) glBegin(gl.GL_LINES) glVertex2f(0, carty) glVertex2f(screen_width, carty) glEnd() # Draw target position gray = 0.4 glColor4f(gray,gray,gray,1.0) glLineWidth(1.0) glBegin(gl.GL_LINES) glVertex2f(targetpos, 0) glVertex2f(targetpos, screen_height) glEnd() # Draw Cart l, r, t, b = -cartwidth/2, cartwidth/2, cartheight/2, -cartheight/2 cartx = cartpole._cart_position*scale+screen_width/2.0 # MIDDLE OF CART glColor4f(0.,0.,0.,1.0) glPushMatrix() # Push Translation glTranslatef(cartx, carty, 0) glBegin(gl.GL_QUADS) glVertex3f(l, b, 0) glVertex3f(l, t, 0) glVertex3f(r, t, 0) glVertex3f(r, b, 0) glEnd() # Draw Pole l, r, t, b = ( -polewidth/2, polewidth/2, polelen-polewidth/2, -polewidth/2) glColor4f(.8, .6, .4, 1.0) glPushMatrix() # Push Rotation glRotatef(RAD2DEG * -cartpole._pole_angle, 0, 0, 1.0) glBegin(gl.GL_QUADS) glVertex3f(l, b, 0) glVertex3f(l, t, 0) glVertex3f(r, t, 0) glVertex3f(r, b, 0) glEnd() glPopMatrix() # Pop Rotation # Draw Axle radius = polewidth/2 glColor4f(0.5, 0.5, 0.8, 1.0) glBegin(gl.GL_POLYGON) for i in range(12): ang = 2 * math.pi * i / 12 x=math.cos(ang)*radius y=math.sin(ang)*radius glVertex3f(x, y, 0) glEnd() glPopMatrix() # Pop Translation
def draw_board(self): # Draw the green background. gl.glBegin(gl.GL_QUADS) gl.glColor4f(0.4, 0.8, 0.4, 1.0) gl.glVertex3f(-BOARDFIELD, +BOARDFIELD, 0) gl.glVertex3f(+BOARDFIELD, +BOARDFIELD, 0) gl.glVertex3f(+BOARDFIELD, -BOARDFIELD, 0) gl.glVertex3f(-BOARDFIELD, -BOARDFIELD, 0) gl.glEnd() # Draw the grid. gl.glBegin(gl.GL_LINES) gl.glColor4f(0, 0, 0, 1.0) grid_width = BOARDFIELD / self.board_size for i in range(1, self.board_size): offset = grid_width * i gl.glVertex2f(offset, 0) gl.glVertex2f(offset, BOARDFIELD) gl.glVertex2f(0, offset) gl.glVertex2f(BOARDFIELD, offset) gl.glEnd() # Draw disks. half_grid_width = grid_width / 2 for i in range(self.board_size): for j in range(self.board_size): if self.board_state[i][j] == WHITE_DISK: gl.glColor4f(1, 1, 1, 1.) elif self.board_state[i][j] == BLACK_DISK: gl.glColor4f(0, 0, 0, 1.) if self.board_state[i][j] != NO_DISK: disk = make_disk_at( x=i * grid_width + half_grid_width, y=j * grid_width + half_grid_width, radius=half_grid_width - 3) disk.render1() # Draw possible positions. if self.player_turn == WHITE_DISK: gl.glColor4f(1, 1, 1, 1.) font_color = (255, 255, 255, 255) else: gl.glColor4f(0, 0, 0, 1.) font_color = (0, 0, 0, 255) for p in self.possible_moves: i = p // self.board_size j = p % self.board_size x = i * grid_width + half_grid_width y = j * grid_width + half_grid_width disk = make_disk_at( x=x, y=y, radius=half_grid_width - 3, filled=False) disk.render1() label = pyglet.text.Label('{}'.format(i * self.board_size + j), font_name='Times New Roman', font_size=10, color=font_color, x=x, y=y, anchor_x='center', anchor_y='center') label.draw()
def _render_rings(self, close, save_to_file=False): if close: self.viewer.close() return # rendering if self.backend in ["VAE1DLSTM", "GPT1D", "VAE1D_LSTM"]: return False else: last_rings_obs = self.last_lidar_obs.reshape((_64, _64)) last_rings_pred = self.vae.decode(self.lidar_z.reshape((1,self._Z))).reshape((_64, _64)) # Window and viewport size ring_size = _64 # grid cells padding = 4 # grid cells grid_size = 1 # px per grid cell WINDOW_W = (2 * ring_size + 3 * padding) * grid_size WINDOW_H = (1 * ring_size + 2 * padding) * grid_size VP_W = WINDOW_W VP_H = WINDOW_H from gym.envs.classic_control import rendering import pyglet from pyglet import gl # Create viewer if self.viewer is None: self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H) self.rendering_iteration = 0 # Render in pyglet win = self.viewer.window win.switch_to() win.dispatch_events() win.clear() gl.glViewport(0, 0, VP_W, VP_H) # colors bgcolor = np.array([0.4, 0.8, 0.4]) # Green background gl.glBegin(gl.GL_QUADS) gl.glColor4f(bgcolor[0], bgcolor[1], bgcolor[2], 1.0) gl.glVertex3f(0, VP_H, 0) gl.glVertex3f(VP_W, VP_H, 0) gl.glVertex3f(VP_W, 0, 0) gl.glVertex3f(0, 0, 0) gl.glEnd() # rings - observation w_offset = 0 for rings in [last_rings_obs, last_rings_pred]: for i in range(ring_size): for j in range(ring_size): cell_color = 1 - rings[i, j] cell_y = (padding + i) * grid_size # px cell_x = (padding + j + w_offset) * grid_size # px gl.glBegin(gl.GL_QUADS) gl.glColor4f(cell_color, cell_color, cell_color, 1.0) gl.glVertex3f(cell_x+ 0, cell_y+grid_size, 0) # noqa gl.glVertex3f(cell_x+grid_size, cell_y+grid_size, 0) # noqa gl.glVertex3f(cell_x+grid_size, cell_y+ 0, 0) # noqa gl.glVertex3f(cell_x+ 0, cell_y+ 0, 0) # noqa gl.glEnd() w_offset += ring_size + padding if save_to_file: pyglet.image.get_buffer_manager().get_color_buffer().save( "/tmp/encodeder_rings{:04d}.png".format(self.rendering_iteration)) # actualize win.flip() self.rendering_iteration += 1 return self.viewer.isopen
def render_road(self): # Painting entire field in white: gl.glBegin(gl.GL_QUADS) gl.glColor4f(0, 0.5, 0, 1.0) #gl.glColor4f(0.4, 0.8, 0.4, 1.0) gl.glVertex3f(-PLAYFIELD, PLAYFIELD, 0) gl.glVertex3f(PLAYFIELD, PLAYFIELD, 0) gl.glVertex3f(PLAYFIELD, -PLAYFIELD, 0) gl.glVertex3f(-PLAYFIELD, -PLAYFIELD, 0) # Drawing road: gl.glColor4f(*ROAD_COLOR, 1) for poly in self.road_poly: gl.glVertex3f(*poly, 0) gl.glEnd() # # Drawing tiles: # def draw_circle(x, y, r): # gl.glColor4f(0, 0, 1, 1) # gl.glBegin(gl.GL_LINE_LOOP) # theta = 2*np.pi/10 # for i in range(10): # gl.glVertex3f(x+np.cos(theta*i)*r, y+np.sin(theta*i)*r, 0) # gl.glEnd() # # gl.glColor4f(0, 0, 0, 1) # for tile in self.tiles_poly: # draw_circle(*tile, 0.5) # Drawing a sidewalk: gl.glColor4f(0.66, 0.66, 0.66, 1) for sw in self.all_sidewalks: gl.glBegin(gl.GL_POLYGON) for v in sw: gl.glVertex3f(*v, 0) gl.glEnd() # Drawing road crossings: gl.glColor4f(1, 1, 1, 1) for cros in crossings: for temp in cros: gl.glBegin(gl.GL_QUADS) for v in temp: gl.glVertex3f(*v, 0) gl.glEnd() for line in cross_line: gl.glBegin(gl.GL_LINES) for v in line: gl.glVertex3f(*v, 0) gl.glEnd() # # Drawing a rock: # gl.glBegin(gl.GL_QUADS) # gl.glColor4f(0,0,0,1) # gl.glVertex3f(10, 30, 0) # gl.glVertex3f(10, 10, 0) # gl.glVertex3f(30, 10, 0) # gl.glVertex3f(30, 30, 0) # gl.glEnd() # Drawing target destination for car: gl.glBegin(gl.GL_QUADS) gl.glColor4f(*self.car.hull.color, 1) for v in self.car_goal_poly: gl.glVertex3f(*v, 0) gl.glEnd()
def enable(self) -> None: glColor4f(*self.vec4)
def draw(self): gl.glColor4f(*self.color) self.image.blit(self.x, self.y)
def enable(self): glColor4f(*self.vec4)
def render(self, mode="human", close=False): if close: if self.viewer is not None: self.viewer.close() return # get last z decoding rings_pred = ( self.vae.decode(self.prev_z.reshape(1, _Z + _G)[:, :_Z]) * self.rings_def["rings_to_bool"]) predicted_ranges = self.rings_def["rings_to_lidar"](rings_pred, 1080) goal_pred = self.prev_z.reshape((_Z + _G, ))[_Z:] * MAX_GOAL_DIST if mode == "rgb_array": raise NotImplementedError elif mode == "human": # Window and viewport size WINDOW_W = 256 WINDOW_H = 256 M_PER_PX = 25.6 / WINDOW_H VP_W = WINDOW_W VP_H = WINDOW_H from gym.envs.classic_control import rendering import pyglet from pyglet import gl # Create viewer if self.viewer is None: self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H) self.score_label = pyglet.text.Label( "0000", font_size=12, x=20, y=WINDOW_H * 2.5 / 40.00, anchor_x="left", anchor_y="center", color=(255, 255, 255, 255), ) # self.transform = rendering.Transform() self.currently_rendering_iteration = 0 self.image_lock = threading.Lock() # Render in pyglet def make_circle(c, r, res=10): thetas = np.linspace(0, 2 * np.pi, res + 1)[:-1] verts = np.zeros((res, 2)) verts[:, 0] = c[0] + r * np.cos(thetas) verts[:, 1] = c[1] + r * np.sin(thetas) return verts with self.image_lock: self.currently_rendering_iteration += 1 self.viewer.draw_circle(r=10, color=(0.3, 0.3, 0.3)) win = self.viewer.window win.switch_to() win.dispatch_events() win.clear() gl.glViewport(0, 0, VP_W, VP_H) # colors bgcolor = np.array([0.4, 0.8, 0.4]) nosecolor = np.array([0.3, 0.3, 0.3]) lidarcolor = np.array([1.0, 0.0, 0.0]) # Green background gl.glBegin(gl.GL_QUADS) gl.glColor4f(bgcolor[0], bgcolor[1], bgcolor[2], 1.0) gl.glVertex3f(0, VP_H, 0) gl.glVertex3f(VP_W, VP_H, 0) gl.glVertex3f(VP_W, 0, 0) gl.glVertex3f(0, 0, 0) gl.glEnd() # LIDAR i = WINDOW_W / 2.0 j = WINDOW_H / 2.0 angle = np.pi / 2.0 scan = np.squeeze(predicted_ranges) lidar_angles = np.linspace(0, 2 * np.pi, len(scan) + 1)[:-1] lidar_angles = lidar_angles + np.pi / 2. # make robot face up i_ray_ends = i + scan / M_PER_PX * np.cos(lidar_angles) j_ray_ends = j + scan / M_PER_PX * np.sin(lidar_angles) is_in_fov = np.cos(lidar_angles - angle) >= 0.78 for ray_idx in range(len(scan)): end_i = i_ray_ends[ray_idx] end_j = j_ray_ends[ray_idx] gl.glBegin(gl.GL_LINE_LOOP) if is_in_fov[ray_idx]: gl.glColor4f(1.0, 1.0, 0.0, 0.1) else: gl.glColor4f(lidarcolor[0], lidarcolor[1], lidarcolor[2], 0.1) gl.glVertex3f(i, j, 0) gl.glVertex3f(end_i, end_j, 0) gl.glEnd() # Agent body i = WINDOW_W / 2.0 j = WINDOW_H / 2.0 r = 0.3 / M_PER_PX angle = np.pi / 2.0 poly = make_circle((i, j), r) gl.glBegin(gl.GL_POLYGON) color = np.array([1.0, 1.0, 1.0]) gl.glColor4f(color[0], color[1], color[2], 1) for vert in poly: gl.glVertex3f(vert[0], vert[1], 0) gl.glEnd() # Direction triangle inose = i + r * np.cos(angle) jnose = j + r * np.sin(angle) iright = i + 0.3 * r * -np.sin(angle) jright = j + 0.3 * r * np.cos(angle) ileft = i - 0.3 * r * -np.sin(angle) jleft = j - 0.3 * r * np.cos(angle) gl.glBegin(gl.GL_TRIANGLES) gl.glColor4f(nosecolor[0], nosecolor[1], nosecolor[2], 1) gl.glVertex3f(inose, jnose, 0) gl.glVertex3f(iright, jright, 0) gl.glVertex3f(ileft, jleft, 0) gl.glEnd() # Goal goalcolor = np.array([1., 1., 0.3]) px_goal = goal_pred / M_PER_PX igoal = i - px_goal[1] # rotate 90deg to face up jgoal = j + px_goal[0] # Goal line gl.glBegin(gl.GL_LINE_LOOP) gl.glColor4f(goalcolor[0], goalcolor[1], goalcolor[2], 1) gl.glVertex3f(i, j, 0) gl.glVertex3f(igoal, jgoal, 0) gl.glEnd() # Goal markers gl.glBegin(gl.GL_TRIANGLES) gl.glColor4f(goalcolor[0], goalcolor[1], goalcolor[2], 1) triangle = make_circle((igoal, jgoal), r / 3., res=3) for vert in triangle: gl.glVertex3f(vert[0], vert[1], 0) gl.glEnd() # Text self.score_label.text = "A {:.1f} {:.1f} {:.1f} S {}".format( self.prev_action[0], self.prev_action[1], self.prev_action[2], self.episode_step, ) self.score_label.draw() win.flip() return self.viewer.isopen
def horiz_ind(place, val, color): gl.glColor4f(color[0], color[1], color[2], 1) gl.glVertex3f((place + 0) * s, 4 * h, 0) gl.glVertex3f((place + val) * s, 4 * h, 0) gl.glVertex3f((place + val) * s, 2 * h, 0) gl.glVertex3f((place + 0) * s, 2 * h, 0)
def vertical_ind(place, val, color): gl.glColor4f(color[0], color[1], color[2], 1) gl.glVertex3f((place + 0) * s, h + h * val, 0) gl.glVertex3f((place + 1) * s, h + h * val, 0) gl.glVertex3f((place + 1) * s, h, 0) gl.glVertex3f((place + 0) * s, h, 0)
def _render_indicators(self, W, H): s = W / 40.0 h = H / 40.0 boatw = 1.3 * 25 gl.glBegin(gl.GL_QUADS) gl.glColor4f(0, 0, 0, 1) gl.glVertex3f(W, 0, 0) gl.glVertex3f(W, 5 * h, 0) gl.glVertex3f(0, 5 * h, 0) gl.glVertex3f(0, 0, 0) gl.glEnd() def vertical_ind(place, val, color): gl.glBegin(gl.GL_QUADS) gl.glColor3f(*color) gl.glVertex3f((place + 0) * s, 2 * h + h * val, 0) gl.glVertex3f((place + 1) * s, 2 * h + h * val, 0) gl.glVertex3f((place + 1) * s, 2 * h, 0) gl.glVertex3f((place + 0) * s, 2 * h, 0) gl.glEnd() def horiz_ind(place, val, color): gl.glBegin(gl.GL_QUADS) gl.glColor4f(color[0], color[1], color[2], 1) gl.glVertex3f((place + 0) * s, 4 * h, 0) gl.glVertex3f((place + val) * s, 4 * h, 0) gl.glVertex3f((place + val) * s, 2 * h, 0) gl.glVertex3f((place + 0) * s, 2 * h, 0) gl.glEnd() def gl_boat(x, y): # Draw boat shape gl.glBegin(gl.GL_LINES) gl.glColor3f(0.9, 0.9, 0.9) gl.glVertex2f(x, y) gl.glVertex2f(x + boatw, y) gl.glVertex2f(x + boatw, y) gl.glVertex2f(x + boatw, y + 2 * h) gl.glVertex2f(x + boatw, y + 2 * h) gl.glVertex2f(x + boatw / 2, y + 2.5 * h) gl.glVertex2f(x + boatw / 2, y + 2.5 * h) gl.glVertex2f(x, y + 2 * h) gl.glVertex2f(x, y + 2 * h) gl.glVertex2f(x, y) gl.glEnd() def gl_arrow(x, y, angle, length, color=(0.9, 0.9, 0.9)): L = 50 T = np.clip(7 * length, 0, 7) hx, hy = x + length * L * cos(angle), y + length * L * sin(angle) gl.glEnable(gl.GL_LINE_SMOOTH) gl.glLineWidth(2) gl.glBegin(gl.GL_LINES) gl.glColor3f(*color) gl.glVertex2f(x, y) gl.glVertex2f(hx, hy) gl.glEnd() gl.glBegin(gl.GL_TRIANGLES) gl.glVertex2f(hx + T * cos(angle), hy + T * sin(angle)) gl.glVertex2f(hx + T * cos(angle + 2 * pi / 3), hy + T * sin(angle + 2 * pi / 3)) gl.glVertex2f(hx + T * cos(angle + 4 * pi / 3), hy + T * sin(angle + 4 * pi / 3)) gl.glEnd() def obst_ind(place): gl_boat(place * s, h) static_obstacle_obs = self.last_obs[NS + NR:NS + NR + 2 * STATIC_OBST_SLOTS] dynamic_obstacle_obs = self.last_obs[NS + NR + 2 * STATIC_OBST_SLOTS:NS + NR + 2 * STATIC_OBST_SLOTS + 4 * DYNAMIC_OBST_SLOTS] for i in range(STATIC_OBST_SLOTS): heading = pi * static_obstacle_obs[2 * i] closeness = static_obstacle_obs[2 * i + 1] gl_arrow(place * s + boatw / 2, 2 * h, angle=heading + pi / 2, length=np.clip(closeness, 0.1, 1), color=(np.clip(1.2 * closeness, 0, 1), 0.5, 0.1)) for i in range(DYNAMIC_OBST_SLOTS): heading = pi * dynamic_obstacle_obs[4 * i] closeness = dynamic_obstacle_obs[4 * i + 1] gl_arrow(place * s + boatw / 2, 2 * h, angle=heading + pi / 2, length=np.clip(closeness, 0.1, 1), color=(np.clip(1.2 * closeness, 0, 1), 0.5, 0.1)) scale = 3 R = self.ship.ref[0] true_speed = np.sqrt( np.square(self.ship.linearVelocity[0]) + np.square(self.ship.linearVelocity[1])) if NR == 2: ref_speed_error = self.last_obs[0] vertical_ind(6, -scale * ref_speed_error, color=(np.clip(R / MAX_SURGE, 0, 1), 0.5, 0.1)) state_speed_error = self.last_obs[NR + 0] vertical_ind(7, -scale * state_speed_error, color=(np.clip(true_speed / MAX_SURGE, 0, 1), 0.6, 0.1)) # Visualise the obstacles as seen by the ship obst_ind(place=20) self.score_label.text = "{:2.2f}".format(self.reward) self.score_label.draw()
def _set_gl_color(color): """Convenience function for setting the GL color to a 3- or 4-tuple.""" if len(color) == 3: gl.glColor3f(*color) if len(color) == 4: gl.glColor4f(*color)
def set_state(self): gl.glPushAttrib(gl.GL_CURRENT_BIT) gl.glColor4f(*self.hotspot.colour)
def draw(self): glClearColor(1.0, 1.0, 1.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) glColor4f(1, 1, 1, self.bg_alpha.value) self.bg.blit(0, 0) self.draw_subcontrols()
def on_draw(self): gl.glClearColor(1,1,1,1) self.window.clear() gl.glColor4f(1,1,1,1) w,h = self.image.width, self.image.height self.image.blit(x=0,y=0,width=w,height=h)
def training_status(self, mode='human'): if self.viewer is None: from gym.envs.classic_control import rendering self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H) self.transform = rendering.Transform() if "t" not in self.__dict__: return # reset() not called yet zoom = ZOOM * SCALE #0.1*SCALE*max(1-self.t, 0) + ZOOM*SCALE*min(self.t, 1) # Animate zoom first second zoom_state = ZOOM * SCALE * STATE_W / WINDOW_W zoom_video = ZOOM * SCALE * VIDEO_W / WINDOW_W scroll_x = 0 #self.car.hull.position[0] #0 scroll_y = 0 #self.car.hull.position[1] #-30 angle = 0 #-self.car.hull.angle #0 vel = 0 #self.car.hull.linearVelocity #0 self.transform.set_scale(zoom, zoom) self.transform.set_translation(WINDOW_W / 2, WINDOW_H / 2) # self.transform.set_translation( # WINDOW_W/2 - (scroll_x*zoom*math.cos(angle) - scroll_y*zoom*math.sin(angle)), # WINDOW_H/4 - (scroll_x*zoom*math.sin(angle) + scroll_y*zoom*math.cos(angle)) ) # self.transform.set_rotation(angle) arr = None win = self.viewer.window if mode != 'state_pixels' and mode != 'rgb_array': win.switch_to() win.dispatch_events() if mode == "rgb_array" or mode == "state_pixels": win.clear() t = self.transform self.transform.set_translation(0, 0) self.transform.set_scale(0.0167, 0.0167) if mode == 'rgb_array': VP_W = VIDEO_W VP_H = VIDEO_H else: VP_W = WINDOW_W // 2 #STATE_W VP_H = WINDOW_H // 2 #STATE_H gl.glViewport(0, 0, VP_W, VP_H) t.enable() self.render_road() for geom in self.viewer.onetime_geoms: geom.render() t.disable() # self.render_indicators(WINDOW_W, WINDOW_H) # TODO: find why 2x needed, wtf image_data = pyglet.image.get_buffer_manager().get_color_buffer( ).get_image_data() arr = np.fromstring(image_data.data, dtype=np.uint8, sep='') arr = arr.reshape(VP_H, VP_W, 4) arr = arr[::-1, :, 0:3] if mode == "rgb_array" and not self.human_render: # agent can call or not call env.render() itself when recording video. win.flip() if mode == 'human': self.human_render = True win.clear() t = self.transform gl.glViewport(0, 0, WINDOW_W, WINDOW_H) t.enable() self.render_road() for geom in self.viewer.onetime_geoms: geom.render() with open("training_positions.csv", 'r') as fin: line_number = sum(1 for _ in fin) with open("training_positions.csv", 'r') as fin: gl.glPointSize(10) for i, line in enumerate(fin): epoch, angle, coord_x, coord_y = list( map(float, line.strip().split(","))) new_coord = (angle, coord_x, coord_y) gl.glBegin(gl.GL_POINTS) alpha = (i + 1) / line_number gl.glColor4f(alpha, 0, 1 - alpha, 0.8) gl.glVertex3f(coord_x, coord_y, 0) gl.glEnd() t.disable() # self.render_indicators(WINDOW_W, WINDOW_H) win.flip() # # Drawing a rock: # gl.glBegin(gl.GL_QUADS) # gl.glColor4f(0,0,0,1) # gl.glVertex3f(10, 30, 0) # gl.glVertex3f(10, 10, 0) # gl.glVertex3f(30, 10, 0) # gl.glVertex3f(30, 30, 0) # gl.glEnd() self.viewer.onetime_geoms = [] return arr
def enable(self): """Apply color""" gl.glColor4f(self.red, self.green, self.blue, self.alpha)
def draw(self): self.bar.draw() self.frame.draw() self.update_viewport() gl.glColor4f(*self.border_color) gu.draw_rect(1, 0, self.width - 1, self.height - 1, gl.GL_LINE_LOOP)
def render(self, mode="human", close=False, lidar_scan_override=None, save_to_file=False, draw_score=True): if close: if self.viewer is not None: self.viewer.close() return # get last obs goal_pred = self.data["robotstates"][self.current_iteration - 1][:2] action = self.data["actions"][self.current_iteration - 1] scan = self.data["scans"][self.current_iteration - 1] scan[scan == 0] = MAX_LIDAR_DIST # render 0 returns as inf if lidar_scan_override is not None: scan = lidar_scan_override if mode == "rgb_array": raise NotImplementedError elif mode in ["human", "rings"]: # Window and viewport size WINDOW_W = 256 WINDOW_H = 256 M_PER_PX = 13.6 / WINDOW_H VP_W = WINDOW_W VP_H = WINDOW_H from gym.envs.classic_control import rendering import pyglet from pyglet import gl # enable this to render for hg_archivenv visual if False: draw_score = False save_to_file = True WINDOW_W = 512 WINDOW_H = 512 M_PER_PX = 51.2 / WINDOW_H # Create viewer if self.viewer is None: self.viewer = rendering.Viewer(WINDOW_W, WINDOW_H) self.score_label = pyglet.text.Label( "0000", font_size=12, x=20, y=WINDOW_H * 2.5 / 40.00, anchor_x="left", anchor_y="center", color=(255, 255, 255, 255), ) # self.transform = rendering.Transform() self.currently_rendering_iteration = 0 self.image_lock = threading.Lock() # Render in pyglet def make_circle(c, r, res=10): thetas = np.linspace(0, 2 * np.pi, res + 1)[:-1] verts = np.zeros((res, 2)) verts[:, 0] = c[0] + r * np.cos(thetas) verts[:, 1] = c[1] + r * np.sin(thetas) return verts with self.image_lock: self.currently_rendering_iteration += 1 self.viewer.draw_circle(r=10, color=(0.3, 0.3, 0.3)) win = self.viewer.window win.switch_to() win.dispatch_events() win.clear() gl.glViewport(0, 0, VP_W, VP_H) # colors # bgcolor = np.array([0.4, 0.8, 0.4]) bgcolor = np.array([0.7, 0.75, 0.86]) nosecolor = np.array([0.3, 0.3, 0.3]) # lidarcolor = np.array([1.0, 0.0, 0.0]) lidarcolor = np.array([1., 0.3, 0.0]) # fovcolor = np.array([1., 1., 0.]) fovcolor = np.array([0.8, 0.8, 0.2]) # Green background gl.glBegin(gl.GL_QUADS) gl.glColor4f(bgcolor[0], bgcolor[1], bgcolor[2], 1.0) gl.glVertex3f(0, VP_H, 0) gl.glVertex3f(VP_W, VP_H, 0) gl.glVertex3f(VP_W, 0, 0) gl.glVertex3f(0, 0, 0) gl.glEnd() # LIDAR i = WINDOW_W / 2.0 j = WINDOW_H / 2.0 angle = np.pi / 2.0 lidar_angles = np.linspace(0, 2 * np.pi, len(scan) + 1)[:-1] lidar_angles = lidar_angles + np.pi / 2. # make robot face up i_ray_ends = i + scan / M_PER_PX * np.cos(lidar_angles) j_ray_ends = j + scan / M_PER_PX * np.sin(lidar_angles) is_in_fov = np.cos(lidar_angles - angle) >= 0.78 for ray_idx in range(len(scan)): end_i = i_ray_ends[ray_idx] end_j = j_ray_ends[ray_idx] gl.glBegin(gl.GL_LINE_LOOP) if is_in_fov[ray_idx]: gl.glColor4f(fovcolor[0], fovcolor[1], fovcolor[2], 0.1) else: gl.glColor4f(lidarcolor[0], lidarcolor[1], lidarcolor[2], 0.1) gl.glVertex3f(i, j, 0) gl.glVertex3f(end_i, end_j, 0) gl.glEnd() # Agent body i = WINDOW_W / 2.0 j = WINDOW_H / 2.0 r = 0.3 / M_PER_PX angle = np.pi / 2.0 poly = make_circle((i, j), r) gl.glBegin(gl.GL_POLYGON) color = np.array([1.0, 1.0, 1.0]) gl.glColor4f(color[0], color[1], color[2], 1) for vert in poly: gl.glVertex3f(vert[0], vert[1], 0) gl.glEnd() # Direction triangle inose = i + r * np.cos(angle) jnose = j + r * np.sin(angle) iright = i + 0.3 * r * -np.sin(angle) jright = j + 0.3 * r * np.cos(angle) ileft = i - 0.3 * r * -np.sin(angle) jleft = j - 0.3 * r * np.cos(angle) gl.glBegin(gl.GL_TRIANGLES) gl.glColor4f(nosecolor[0], nosecolor[1], nosecolor[2], 1) gl.glVertex3f(inose, jnose, 0) gl.glVertex3f(iright, jright, 0) gl.glVertex3f(ileft, jleft, 0) gl.glEnd() # Goal goalcolor = np.array([1., 1., 0.3]) px_goal = goal_pred / M_PER_PX igoal = i - px_goal[1] # rotate 90deg to face up jgoal = j + px_goal[0] # Goal line gl.glBegin(gl.GL_LINE_LOOP) gl.glColor4f(goalcolor[0], goalcolor[1], goalcolor[2], 1) gl.glVertex3f(i, j, 0) gl.glVertex3f(igoal, jgoal, 0) gl.glEnd() # Goal markers gl.glBegin(gl.GL_TRIANGLES) gl.glColor4f(goalcolor[0], goalcolor[1], goalcolor[2], 1) triangle = make_circle((igoal, jgoal), r, res=3) for vert in triangle: gl.glVertex3f(vert[0], vert[1], 0) gl.glEnd() # Text self.score_label.text = "File {} It {} a {:.1f} {:.1f} {:.1f}".format( self.current_iteration // 1000, self.current_iteration % 1000, action[0], action[1], action[2], ) if draw_score: self.score_label.draw() win.flip() if save_to_file: pyglet.image.get_buffer_manager().get_color_buffer().save( "/tmp/archivenv{:05}.png".format( self.currently_rendering_iteration)) return self.viewer.isopen
def render_lidar_batch(batch_ranges, min_angle, max_angle, min_range=0.3, mode="human", viewer=None): if mode == "human": N_COL_WINDOWS = 10 N_ROW_WINDOWS = 10 N_WINDOWS = N_COL_WINDOWS * N_ROW_WINDOWS # Window and viewport size WINDOW_W = 64 WINDOW_H = 64 WINDOW_H_METERS = 10.0 RESOLUTION_M_PER_PX = WINDOW_H_METERS / WINDOW_H VP_W = WINDOW_W * N_COL_WINDOWS VP_H = WINDOW_H * N_ROW_WINDOWS # Create viewer if viewer is None: viewer = rendering.Viewer(VP_W, VP_H) viewer.score_label = pyglet.text.Label( "0000", font_size=36, x=20, y=WINDOW_H * 2.5 / 40.00, anchor_x="left", anchor_y="center", color=(255, 255, 255, 255), ) viewer.draw_circle(r=10, color=(0.3, 0.3, 0.3)) win = viewer.window win.switch_to() win.dispatch_events() win.clear() gl.glViewport(0, 0, VP_W, VP_H) # colors bgcolor = np.array([0.9, 0.9, 1.0]) lidarcolor = np.array([1.0, 0.0, 0.0]) # Green background gl.glBegin(gl.GL_QUADS) gl.glColor4f(bgcolor[0], bgcolor[1], bgcolor[2], 1.0) gl.glVertex3f(0, VP_H, 0) gl.glVertex3f(VP_W, VP_H, 0) gl.glVertex3f(VP_W, 0, 0) gl.glVertex3f(0, 0, 0) gl.glEnd() # LIDAR assert len(batch_ranges) == 100 for n, ranges in enumerate(batch_ranges): col = n % N_COL_WINDOWS row = n // N_COL_WINDOWS window_offset_i = row * WINDOW_W window_offset_j = col * WINDOW_H sensor_i = window_offset_i + WINDOW_W / 2.0 sensor_j = window_offset_j + WINDOW_H / 2.0 angles = np.linspace(min_angle, max_angle, len(ranges)) ijranges = np.array(ranges) / RESOLUTION_M_PER_PX for th, r in zip(angles, ijranges): ray_start_i = np.clip( sensor_i + min_range * np.cos(th), window_offset_i, window_offset_i + WINDOW_H - 1, ) ray_start_j = np.clip( sensor_j + min_range * np.sin(th), window_offset_j, window_offset_j + WINDOW_W - 1, ) ray_end_i = np.clip( sensor_i + r * np.cos(th), window_offset_i, window_offset_i + WINDOW_H - 1, ) ray_end_j = np.clip( sensor_j + r * np.sin(th), window_offset_j, window_offset_j + WINDOW_W - 1, ) gl.glBegin(gl.GL_LINE_LOOP) gl.glColor4f(lidarcolor[0], lidarcolor[1], lidarcolor[2], 0.1) gl.glVertex3f(ray_start_i, ray_start_j, 0) gl.glVertex3f(ray_end_i, ray_end_j, 0) gl.glEnd() # Text # viewer.score_label.text = "{}m".format(WINDOW_H_METERS) # viewer.score_label.draw() win.flip() return viewer
def draw(self): gl.glLineWidth(1.5) phys_comp_list = self.manager.comps[phys.PhysicsEcsComponent.name()] grav_comp_list = self.manager.comps[phys.GravityEcsComponent.name()] coll_comp_list = self.manager.comps[coll.CollisionEcsComponent.name()] planet_comp_list = self.manager.comps[planet.PlanetEcsComponent.name()] ship_comp_list = self.manager.comps[ship.ShipEcsComponent.name()] base_comp_list = self.manager.comps[base.BaseEcsComponent.name()] aster_comp_list = self.manager.comps[ asteroid.AsteroidEcsComponent.name()] rend_plan_comp_list = self.manager.comps[ planet.RenderPlanetEcsComponent.name()] rend_ship_comp_list = self.manager.comps[ ship.RenderShipEcsComponent.name()] rend_base_comp_list = self.manager.comps[ base.RenderBaseEcsComponent.name()] rend_aster_comp_list = self.manager.comps[ asteroid.RenderAsteroidEcsComponent.name()] rend_anim_comp_list = self.manager.comps[ RenderAnimationEcsComponent.name()] entities = self.manager.entities player_alive = False if self.player_entity_id in entities: player_alive = True ppc = self.manager.get_entity_comp(self.player_entity_id, phys.PhysicsEcsComponent.name()) psc = self.manager.get_entity_comp(self.player_entity_id, ship.ShipEcsComponent.name()) if ppc: self.tx = ppc.pos.x - const.WIDTH / 2 self.ty = ppc.pos.y - const.HEIGHT / 2 tx = self.tx ty = self.ty area = (tx, ty, const.WIDTH, const.HEIGHT) #img.get(img.IMG_BG).blit(0, 0) gl.glPointSize(1) self.starfield.draw(tx, ty) gl.glPushMatrix() gl.glLoadIdentity() gl.glTranslatef(-tx, -ty, 0.0) # predraw (lines, areas etc) for idx, eid in enumerate(entities): basec = base_comp_list[idx] physc = phys_comp_list[idx] if basec: rbc = rend_base_comp_list[idx] if basec.crew_load > 0: draw_circle(physc.pos.x, physc.pos.y, basec.radius, None, gl.GL_LINES, (1, 0, 0, 1)) for idx, eid in enumerate(entities): shipc = ship_comp_list[idx] basec = base_comp_list[idx] asterc = aster_comp_list[idx] planetc = planet_comp_list[idx] physc = phys_comp_list[idx] collc = coll_comp_list[idx] if not physc: continue #if eid == self.player_entity_id: # print physc.pos.x, physc.pos.y, collc.radius, tx, tx # print circle_rect_intersect(physc.pos.x, physc.pos.y, collc.radius, tx, tx, const.WIDTH, const.HEIGHT) #clipping if not circle_rect_intersect(physc.pos.x, physc.pos.y, collc.radius, tx, ty, const.WIDTH, const.HEIGHT): continue if shipc: rsc = rend_ship_comp_list[idx] rsc.process() ship_sprite = rsc.spr ship_sprite.x = physc.pos.x ship_sprite.y = physc.pos.y ship_sprite.rotation = -shipc.rotation ship_sprite.draw() if rsc.thrust_cooldown: thrust_sprite = rsc.thrust_spr thrust_sprite.x = physc.pos.x thrust_sprite.y = physc.pos.y thrust_sprite.rotation = -shipc.rotation thrust_sprite.draw() #draw_circle(physc.pos.x, physc.pos.y, collc.radius, None, gl.GL_POLYGON, (1, 1, 0, 1)) #dir_radians = math.radians(shipc.rotation) #dirv = vec2d.vec2d(math.cos(dir_radians), math.sin(dir_radians)) #dirv.length = collc.radius #gl.glColor3f(1, 0, 0, 1) #gl.glBegin(gl.GL_LINES) #gl.glVertex2f(physc.pos.x, physc.pos.y) #gl.glVertex2f(physc.pos.x + dirv.x, physc.pos.y + dirv.y) #gl.glEnd() elif basec: rbc = rend_base_comp_list[idx] base_sprite = rbc.spr if base_sprite: base_sprite.x = physc.pos.x base_sprite.y = physc.pos.y base_sprite.draw() else: draw_circle(physc.pos.x, physc.pos.y, collc.radius, None, gl.GL_POLYGON, (1, 0, 0, 1)) elif asterc: rac = rend_aster_comp_list[idx] aster_sprite = rac.spr if aster_sprite: aster_sprite.x = physc.pos.x aster_sprite.y = physc.pos.y aster_sprite.draw() else: draw_circle(physc.pos.x, physc.pos.y, collc.radius, None, gl.GL_POLYGON, (0, 1, 0, 1)) elif planetc: rpc = rend_plan_comp_list[idx] planet_sprite = rpc.spr if planet_sprite: planet_sprite.x = physc.pos.x planet_sprite.y = physc.pos.y planet_sprite.draw() else: draw_circle(physc.pos.x, physc.pos.y, collc.radius) if planetc.pname: label = pyglet.text.Label( planetc.pname, font_name=font.FONT_MONO.name, font_size=12, x=physc.pos.x, y=physc.pos.y, # + collc.radius + 5 anchor_x='center', anchor_y='center', color=(0, 0, 255, 255)) label.draw() #gc = grav_comp_list[idx] #if gc and gc.gravity_radius: # draw_circle(physc.pos.x, physc.pos.y, gc.gravity_radius, None, gl.GL_LINE_LOOP) for anim in rend_anim_comp_list: if not anim: continue #print 'we have an anim to show!' a = anim.anim a.draw() if player_alive and not self.manager.victory: for idx, eid in enumerate(entities): shipc = ship_comp_list[idx] if shipc: if shipc.messages: pos_mod = 0.0 for message in shipc.messages: label = message[5] if not label: label = pyglet.text.Label( message[0], font_name=font.FONT_MONO.name, font_size=12, x=message[2], y=message[3] + pos_mod, anchor_x='left', anchor_y='bottom', color=message[4]) message[5] = label label.draw() pos_mod += 25 gl.glPopMatrix() # interface if player_alive and not self.manager.victory: if self.manager._navigation: gl.glLineWidth(1) nav_circle_radius = (const.HEIGHT - 100) // 2 draw_circle(const.WIDTH // 2, const.HEIGHT // 2, nav_circle_radius, None, gl.GL_LINE_LOOP, (1, 1, 0, 0.4)) for idx, eid in enumerate(entities): basec = base_comp_list[idx] physc = phys_comp_list[idx] if not physc: continue distance = ppc.pos.get_distance(physc.pos) / 50 if distance > 3 and distance < nav_circle_radius: gl.glEnable(gl.GL_BLEND) gl.glColor4f(1, 1, 0, 0.4) if basec and basec.crew_load > 0: cpo = get_circle_closest_point( physc.pos, ppc.pos, nav_circle_radius) cpi = get_circle_closest_point( physc.pos, ppc.pos, nav_circle_radius - distance) gl.glBegin(gl.GL_LINES) gl.glVertex2f(cpi.x - self.tx, cpi.y - self.ty) gl.glVertex2f(cpo.x - self.tx, cpo.y - self.ty) gl.glEnd() show_bar(130, const.HEIGHT - 32, psc.fuel, psc.fuel_max, width=100., height=15., border_color=(255, 255, 255), progress=False) show_bar(485, const.HEIGHT - 32, psc.health, psc.health_max, width=100., height=15., border_color=(255, 255, 255), progress=False) show_bar(730, const.HEIGHT - 32, psc.passengers, self.manager.crew_to_rescue, width=100., height=15., border_color=(255, 255, 255), progress=False) seconds_remaining = self.manager.get_system( player.PlayerEscSystem.name( )).time_limit / director.director.fps self.time_label.text = 'TIME %.2f' % seconds_remaining self.speed_label.text = 'SPEED %.2f' % ppc.vel.length self.fuel_label.draw() self.health_label.draw() self.rescued_label.draw() self.time_label.draw() self.speed_label.draw() self.controls_label.draw()
def draw(self): hla = self.hl_alpha if hla and not self.disable_click: x, y, tex = self.hldraw glColor4f(1, 1, 1, hla) tex.blit(x, y)
def _render_obstacles(self): #Can only be called inside a glBegin!!! for poly, color in self.obstacles_poly: # drawing road old way gl.glColor4f(color[0], color[1], color[2], 1) for p in poly: gl.glVertex3f(p[0], p[1], 0)
def draw(self, win=None): #set the window to draw to if win == None: win = self.win if win.winType == 'pyglet': win.winHandle.switch_to() #work out next default depth if self.depth == 0: thisDepth = self.win._defDepth self.win._defDepth += _depthIncrements[self.win.winType] else: thisDepth = self.depth GL.glPushMatrix() #scale and rotate prevScale = self.win.setScale(self._winScale) GL.glTranslatef(self._posRendered[0], self._posRendered[1], thisDepth) #NB depth is set already GL.glRotatef(self.ori, 0.0, 0.0, 1.0) self.win.setScale('pix', None, prevScale) if self._useShaders: #then rgb needs to be set as glColor #setup color desiredRGB = (self.rgb * self.contrast + 1) / 2.0 #RGB in range 0:1 and scaled for contrast if numpy.any(desiredRGB**2.0 > 1.0): desiredRGB = [0.6, 0.6, 0.4] GL.glColor4f(desiredRGB[0], desiredRGB[1], desiredRGB[2], self.opacity) else: #color is set in texture, so set glColor to white GL.glColor4f(1, 1, 1, 1) GL.glDisable( GL.GL_DEPTH_TEST) #should text have a depth or just on top? #update list if necss and then call it if self.win.winType == 'pyglet': #and align based on x anchor if self.alignHoriz == 'right': GL.glTranslatef(-self.width, 0, 0) #NB depth is set already if self.alignHoriz in ['center', 'centre']: GL.glTranslatef(-self.width / 2, 0, 0) #NB depth is set already #unbind the mask texture regardless GL.glActiveTexture(GL.GL_TEXTURE1) GL.glEnable(GL.GL_TEXTURE_2D) GL.glBindTexture(GL.GL_TEXTURE_2D, 0) #unbind the main texture GL.glActiveTexture(GL.GL_TEXTURE0) GL.glEnable(GL.GL_TEXTURE_2D) #then allow pyglet to bind and use texture during drawing self.glyphStr.draw() GL.glDisable(GL.GL_TEXTURE_2D) else: #for pygame we should (and can) use a drawing list if self.needUpdate: self._updateList() GL.glCallList(self._listID) GL.glEnable(GL.GL_DEPTH_TEST) # Enables Depth Testing GL.glPopMatrix()