def draw(self): planes = self.planes assert len(planes) <= len(GL_CLIP_PLANE_table), \ "no more than %d clipping planes are permitted" % \ len(GL_CLIP_PLANE_table) # even if your OpenGL driver supports more -- no sense writing an expr that not everyone can draw! # WARNING: this ignores the issue of nested Clipped constructs! # In fact, it assumes nothing in thing or above self uses any clipping planes. # (Not merely "assumes no more than 6 in all", because we hardcode which specific planes to use!) # Worse, we don't even detect the error. Fixing the behavior is just as easy # (let graphical dynenv (self.env) know which planes are still available to any drawing-kid), so do that instead. ##e # Note that we might need to work inside a display list, and therefore we'd need to get the "next plane to use" # from an env which stays fixed (or from an env var which is changedtracked), not just from each draw call's caller # (i.e. a glpane attr). # enable the planes for i, plane in zip(range(len(planes)), planes): assert len(plane) == 4 glEnable( GL_CLIP_PLANE_table[i] ) glClipPlane( GL_CLIP_PLANE_table[i], plane) # draw thing self.drawkid( self.thing) # disable the planes for i in range(len(planes)): glDisable( GL_CLIP_PLANE_table[i] ) return
def __init__(self, title, width=1024, height=768, background_color=color.Smoke): self.base_width = width self.base_height = height glutInit(sys.argv) glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH) glutInitWindowSize(width, height) glutInitWindowPosition((self.screen_width - width) // 2, (self.screen_height - height) // 2) glutCreateWindow(title) glutKeyboardFunc(self.handle_key) glutDisplayFunc(self._draw) glutIdleFunc(self.handle_idle) glutMouseFunc(self.handle_mouse) glutSpecialFunc(self.handle_special_key) glutReshapeFunc(self.handle_reshape) glEnable(GL_DEPTH_TEST) if background_color is not None: self.fill_color(*color.Smoke, 1.)
def render(self): """ The render pass for the scene """ self.init_view() # Enable lighting and color glEnable(GL_LIGHTING) glClearColor(0.4, 0.4, 0.4, 0.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Load the modelview matrix from the current state of the trackball glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() loc = self.interaction.translation glTranslated(-loc[0], -loc[1], -loc[2]) glMultMatrixf(self.interaction.trackball.matrix) # store the inverse of the current modelview. currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX)) self.modelView = numpy.transpose(currentModelView) self.inverseModelView = inv(numpy.transpose(currentModelView)) # render the scene. This will call the render function for each object in the scene self.scene.render() # draw the grid glDisable(GL_LIGHTING) glCallList(G_OBJ_PLANE) glPopMatrix() # flush the buffers so that the scene can be drawn glFlush()
def draw_glpane_label_text(self, text): """ Draw a text label for the glpane as a whole. @note: called indirectly from GLPane.paintGL shortly after it calls _do_graphicsMode_Draw(), via GraphicsMode.draw_glpane_label """ #bruce 090219 moved this here from part of Part.draw_text_label # (after a temporary stop in the short-lived class PartDrawer); # the other part is now our caller GraphicsMode.draw_glpane_label. # (note: caller catches exceptions, so we don't have to bother) glDisable(GL_LIGHTING) glDisable(GL_DEPTH_TEST) # Note: disabling GL_DEPTH_TEST properly affects 2d renderText # (as used here), but not 3d renderText. For more info see # today's comments in Guides.py. [bruce 081204 comment] glPushMatrix() # REVIEW: needed? [bruce 081204 question] font = QFont(QString("Helvetica"), 24, QFont.Bold) self.qglColor(Qt.red) # this needs to be impossible to miss -- not nice-looking! #e tho it might be better to pick one of several bright colors # by hashing the partname, so as to change the color when the part changes. # this version of renderText uses window coords (0,0 at upper left) # rather than model coords (but I'm not sure what point on the string-image # we're setting the location of here -- guessing it's bottom-left corner): self.renderText(25,40, QString(text), font) glPopMatrix() glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) return
def _setup_lighting(self): """ [private method] Set up lighting in the model. [Called from both initializeGL and paintGL.] """ # note: there is some duplicated code in this method # in GLPane_lighting_methods (has more comments) and ThumbView, # but also significant differences. Should refactor sometime. # [bruce 060415/080912 comment] glEnable(GL_NORMALIZE) glMatrixMode(GL_PROJECTION) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glLoadIdentity() #bruce 060415 moved following from ThumbView.initializeGL to this split-out method... #bruce 051212 revised lighting code to share prefs and common code with GLPane # (to fix bug 1200 and mitigate bugs 475 and 1158; # fully fixing those would require updating lighting in all ThumbView widgets # whenever lighting prefs change, including making .update calls on them, # and is not planned for near future since it's easy enough to close & reopen them) try: lights = self.shareWidget._lights #bruce 060415 shareWidget --> self.shareWidget; presumably always failed before that ###@@@ will this fix some bugs about common lighting prefs?? except: lights = _default_lights setup_standard_lights( lights, self.glprefs) return
def draw( self, camera_matrix: numpy.ndarray, camera_position: PointCoordinatesAny = None ): """ Draw the selection box :param camera_matrix: 4x4 transformation matrix for the camera :param camera_position: The position of the camera. Used to flip draw direction if camera inside box. :return: """ self._setup() if self._rebuild: self._create_geometry() self._draw_mode = GL_TRIANGLES transformation_matrix = numpy.matmul(camera_matrix, self.transformation_matrix) if camera_position is not None and camera_position in self: glCullFace(GL_FRONT) else: glCullFace(GL_BACK) self.draw_start = 0 self.draw_count = 36 super()._draw(transformation_matrix) glCullFace(GL_BACK) # draw the lines around the boxes glDisable(GL_DEPTH_TEST) self._draw_mode = GL_LINE_STRIP super()._draw(transformation_matrix) glEnable(GL_DEPTH_TEST)
def render_planar_update(self, rx, ry, rw, rh, x_scale=1, y_scale=1): log("%s.render_planar_update%s pixel_format=%s", self, (rx, ry, rw, rh, x_scale, y_scale), self.pixel_format) if self.pixel_format not in ("YUV420P", "YUV422P", "YUV444P", "GBRP"): #not ready to render yet return if self.pixel_format == "GBRP": self.set_rgbP_paint_state() self.gl_marker("painting planar update, format %s", self.pixel_format) divs = get_subsampling_divs(self.pixel_format) glEnable(GL_FRAGMENT_PROGRAM_ARB) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) tw, th = self.texture_size log("%s.render_planar_update(..) texture_size=%s, size=%s", self, self.texture_size, self.size) glBegin(GL_QUADS) for x,y in ((0, 0), (0, rh), (rw, rh), (rw, 0)): ax = min(tw, x) ay = min(th, y) for texture, index in ((GL_TEXTURE0, 0), (GL_TEXTURE1, 1), (GL_TEXTURE2, 2)): (div_w, div_h) = divs[index] glMultiTexCoord2i(texture, ax//div_w, ay//div_h) glVertex2i(int(rx+ax*x_scale), int(ry+ay*y_scale)) glEnd() if self.pixel_format == "GBRP": self.unset_rgbP_paint_state()
def drawline_worker(params): """ Draw a line. Receive parameters through a sequence so that this function and its parameters can be passed to another function for deferment. Right now this is only ColorSorter.schedule (see below) """ (endpt1, endpt2, dashEnabled, stipleFactor, width, isSmooth) = params ###glDisable(GL_LIGHTING) ###glColor3fv(color) if dashEnabled: glLineStipple(stipleFactor, 0xAAAA) glEnable(GL_LINE_STIPPLE) if width != 1: glLineWidth(width) if isSmooth: glEnable(GL_LINE_SMOOTH) glBegin(GL_LINES) glVertex(endpt1[0], endpt1[1], endpt1[2]) glVertex(endpt2[0], endpt2[1], endpt2[2]) glEnd() if isSmooth: glDisable(GL_LINE_SMOOTH) if width != 1: glLineWidth(1.0) # restore default state if dashEnabled: glDisable(GL_LINE_STIPPLE) ###glEnable(GL_LIGHTING) return
def draw_lines(self): """ draw our line segments, using our current style attrs [which are partly nim] """ # find variables which determine our GL state color = self.fix_color(self.linecolor) dashEnabled = self.dashed width = self.linewidth # set temporary GL state (code copied from drawer.drawline) glDisable(GL_LIGHTING) glColor3fv(color) if dashEnabled: glLineStipple(1, 0xAAAA) glEnable(GL_LINE_STIPPLE) if width != 1: glLineWidth(width) # draw the lines if self._closed_state: glBegin(GL_LINE_LOOP) else: glBegin(GL_LINE_STRIP) for pos in self.points: glVertex3fv(pos) # [note from old code: could be pos + origin if that can matter] glEnd() # restore default GL state [some of this might be moved up to callers] if width != 1: glLineWidth(1.0) if dashEnabled: glDisable(GL_LINE_STIPPLE) glEnable(GL_LIGHTING) return
def draw(self): '''Draw the mesh on screen (using display list if compiled)''' if self.list: glCallList(self.list) return glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT) glEnable(GL_CULL_FACE) glCullFace(GL_BACK) for group in self.groups: if group.material: group.material.apply() if group.array is None: if group.material and group.material.texture: if group.material.texture.rectangle: # texture is a rectangle texture # that's mean we need to adjust the range of texture # coordinate from original 0-1 to 0-width/0-height group.vertices[0::8] = map( lambda x: x * group.material.texture.width, group.vertices[0::8] ) group.vertices[1::8] = map( lambda x: x * group.material.texture.height, group.vertices[1::8] ) group.array = (GLfloat * len(group.vertices))(*group.vertices) group.triangles = len(group.vertices) / 8 glInterleavedArrays(GL_T2F_N3F_V3F, 0, group.array) glDrawArrays(GL_TRIANGLES, 0, group.triangles) if group.material: group.material.unapply() glPopAttrib() glPopClientAttrib()
def render_planar_update(self, rx, ry, rw, rh, x_scale=1, y_scale=1): log("%s.render_planar_update%s pixel_format=%s", self, (rx, ry, rw, rh, x_scale, y_scale), self.pixel_format) if self.pixel_format not in ("YUV420P", "YUV422P", "YUV444P", "GBRP"): #not ready to render yet return if self.pixel_format == "GBRP": # Set GL state for planar RGB: change fragment program glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[RGBP2RGB_SHADER]) self.gl_marker("painting planar update, format %s", self.pixel_format) divs = get_subsampling_divs(self.pixel_format) glEnable(GL_FRAGMENT_PROGRAM_ARB) for texture, index in ((GL_TEXTURE0, TEX_Y), (GL_TEXTURE1, TEX_U), (GL_TEXTURE2, TEX_V)): glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[index]) tw, th = self.texture_size log("%s.render_planar_update(..) texture_size=%s, size=%s", self, self.texture_size, self.size) glBegin(GL_QUADS) for x,y in ((0, 0), (0, rh), (rw, rh), (rw, 0)): ax = min(tw, x) ay = min(th, y) for texture, index in ((GL_TEXTURE0, TEX_Y), (GL_TEXTURE1, TEX_U), (GL_TEXTURE2, TEX_V)): (div_w, div_h) = divs[index] glMultiTexCoord2i(texture, ax//div_w, ay//div_h) glVertex2i(int(rx+ax*x_scale), int(ry+ay*y_scale)) glEnd() for texture in (GL_TEXTURE0, GL_TEXTURE1, GL_TEXTURE2): glActiveTexture(texture) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0) glDisable(GL_FRAGMENT_PROGRAM_ARB) if self.pixel_format == "GBRP": # Reset state to our default (YUV painting) glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, self.shaders[YUV2RGB_SHADER]) glActiveTexture(GL_TEXTURE0)
def render(self) -> None: """Render chamber to canvas.""" if not self.init(): return glDisable(GL_LINE_SMOOTH) proj = self.parent.projection_matrix modelview = self.parent.modelview_matrix glUseProgram(self.parent.shaders['default']) glUniformMatrix4fv(0, 1, GL_FALSE, glm.value_ptr(proj)) glUniformMatrix4fv(1, 1, GL_FALSE, glm.value_ptr(modelview)) if self._grid_shown: self._render_gridlines() if self._axes_shown: self._render_axes() if self._bbox_shown: self._render_bounding_box() glBindVertexArray(0) glUseProgram(0) glEnable(GL_LINE_SMOOTH)
def _do_paint_rgb24(self, img_data, x, y, w, h, rowstride, options, callbacks): log("do_paint_rgb24(%s bytes, %s, %s, %s, %s, %s, %s, %s)", len(img_data), x, y, w, h, rowstride, options, callbacks) ww, wh = self.size if x+w>ww or y+h>wh: log("do_paint_rgb24: ignoring paint which would overflow the backing area") return drawable = self.gl_init() if not drawable: log("do_paint_rgb24: cannot paint yet..") return try: #cleanup if we were doing yuv previously: if self.pixel_format!=GLPixmapBacking.RGB24: self.remove_shader() self.pixel_format = GLPixmapBacking.RGB24 glEnable(GL_TEXTURE_RECTANGLE_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstride/3) for texture in (GL_TEXTURE1, GL_TEXTURE2): glActiveTexture(texture) glDisable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, w, h, GL_RGB, GL_UNSIGNED_BYTE, img_data) glBegin(GL_QUADS) for rx,ry in ((x, y), (x, y+h), (x+w, y+h), (x+w, y)): glTexCoord2i(rx, ry) glVertex2i(rx, ry) glEnd() finally: self.gl_end(drawable)
def draw(self): '''Draw the mesh on screen (using display list if compiled)''' if self.list: glCallList(self.list) return glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) glPushAttrib(GL_CURRENT_BIT | GL_ENABLE_BIT | GL_LIGHTING_BIT) glEnable(GL_CULL_FACE) glCullFace(GL_BACK) for group in self.groups: if group.material: group.material.apply() if group.array is None: if group.material and group.material.texture: if group.material.texture.rectangle: # texture is a rectangle texture # that's mean we need to adjust the range of texture # coordinate from original 0-1 to 0-width/0-height group.vertices[0::8] = map( lambda x: x * group.material.texture.width, group.vertices[0::8]) group.vertices[1::8] = map( lambda x: x * group.material.texture.height, group.vertices[1::8]) group.array = (GLfloat * len(group.vertices))(*group.vertices) group.triangles = len(group.vertices) / 8 glInterleavedArrays(GL_T2F_N3F_V3F, 0, group.array) glDrawArrays(GL_TRIANGLES, 0, group.triangles) if group.material: group.material.unapply() glPopAttrib() glPopClientAttrib()
def draw(self): """ Draws each frame. """ print("draw()") # DRAW STUFF HERE glDisable(GL_TEXTURE_RECTANGLE_ARB) glColor4f(1.0, 0.8, 0.2, 1.0) glPushMatrix() glScale(0.5, 0.5, 1.0) draw_square() glPopMatrix() glColor4f(1.0, 1.0, 0.0, 0.8) num = 64 for i in range(num): x = (i / float(num)) * 4 - 2 draw_line(float(x), -2.0, float(x), 2.0) draw_line(-2.0, float(x), 2.0, float(x)) if self.texture_id is not None: glColor4f(1.0, 1.0, 1.0, 1.0) glEnable(GL_TEXTURE_RECTANGLE_ARB) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.texture_id) glPushMatrix() glScale(0.4, 0.3, 1.0) draw_textured_square(320, 240) glPopMatrix() else: print "No texture to draw"
def leftDown(self, event): """ Compute the rubber band window starting point, which lies on the near clipping plane, projecting into the same point that current cursor points at on the screen plane. """ self.pWxy = (event.pos().x(), self.glpane.height - event.pos().y()) p1 = A(gluUnProject(self.pWxy[0], self.pWxy[1], 0.005)) self.pStart = p1 self.pPrev = p1 self.firstDraw = True self.command.glStatesChanged = True # this warns our exit code to undo the following OpenGL state changes: self.glpane.redrawGL = False glDisable(GL_DEPTH_TEST) glDisable(GL_LIGHTING) rbwcolor = self.command.rbwcolor glColor3d(rbwcolor[0], rbwcolor[1], rbwcolor[2]) glEnable(GL_COLOR_LOGIC_OP) glLogicOp(GL_XOR) return
def draw_lines(self): "draw our line segments, using our current style attrs [which are partly nim]" # find variables which determine our GL state color = self.fix_color(self.linecolor) dashEnabled = self.dashed width = self.linewidth # set temporary GL state (code copied from drawer.drawline) glDisable(GL_LIGHTING) glColor3fv(color) if dashEnabled: glLineStipple(1, 0xAAAA) glEnable(GL_LINE_STIPPLE) if width != 1: glLineWidth(width) # draw the lines if self._closed_state: glBegin(GL_LINE_LOOP) else: glBegin(GL_LINE_STRIP) for pos in self.points: glVertex3fv( pos ) # [note from old code: could be pos + origin if that can matter] glEnd() # restore default GL state [some of this might be moved up to callers] if width != 1: glLineWidth(1.0) if dashEnabled: glDisable(GL_LINE_STIPPLE) glEnable(GL_LIGHTING) return
def draw(self): t1 = time.time() glClearColor(0.0, 0.0, 0.0, 0.0) glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) glLoadIdentity () horizonY = 1 * 2.2 - .6 + .5 GLU.gluLookAt(self.eyeX.x, horizonY, 8.0, self.lookX.x, horizonY, 0.0, 0.0, 1.0, 0.0) glEnable(GL.GL_TEXTURE_2D) if 0: with pushMatrix(): glColor3f(1,0,0) glTranslatef(*self.ball) glScalef(.2, .2, 1) imageCard("sample.jpg") with pushMatrix(): with mode(disable=[GL.GL_LIGHTING]): for card in self.cards: card.draw(self.eyeX.x, horizonY, self.cardList) glFlush() pygame.display.flip()
def render(self): #初始化投影矩阵 self.init_view() #启动光照 glEnable(GL_LIGHTING) #清空颜色缓存与深度缓存 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #设置模型视图矩阵,这节课先用单位矩阵就行了。 glMatrixMode(GL_MODELVIEW) glPushMatrix() glLoadIdentity() glMultMatrixf(self.interaction.trackball.matrix) # 存储ModelView矩阵与其逆矩阵之后做坐标系转换用 currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX)) self.modelView = numpy.transpose(currentModelView) self.inverseModelView = inv(numpy.transpose(currentModelView)) #渲染场景 self.scene.render() #每次渲染后复位光照状态 glDisable(GL_LIGHTING) glCallList(G_OBJ_PLANE) glPopMatrix() #把数据刷新到显存上 glFlush()
def draw_filled_rect(origin, dx, dy, color): ## print 'draw_filled_rect',(origin, dx, dy, color) #####@@@@@ glDisable(GL_LIGHTING) # this allows the specified color to work. Otherwise it doesn't work (I always get dark blue). Why??? # guess: if i want lighting, i have to specify a materialcolor, not just a regular color. (and vertex normals) try: len(color) except: print "following exception in len(color) for color = %r" % (color,) # 061212 -- why didn't caller's fix_color catch it? ##k raise if len(color) == 4: glColor4fv(color) if 0 and color[3] != 1.0: print "color has alpha",color ####@@@@ else: glColor3fv(color) ## glRectfv(origin, origin + dx + dy) # won't work for most coords! also, ignores Z. color still not working. glBegin(GL_QUADS) glVertex3fv(origin) #glColor3fv(white)# glVertex3fv(origin + dx) # glColor3fv(white) # hack, see if works - yes! #glColor3fv(color)# glVertex3fv(origin + dx + dy) #glColor3fv(white)# glVertex3fv(origin + dy) glEnd() glEnable(GL_LIGHTING) # should be outside of glEnd! when inside, i got infloop! (not sure that was why; quit/reran after that)
def render(self,mode='OPAQUE'): opaque_pieces = self._style.get('opaque-pieces',()) if opaque_pieces == True or not self._has_transparent: opaque_pieces = self.pieces glEnable(GL_CULL_FACE) if mode == 'OPAQUE': if self._has_transparent: return # can't guarantee opaque render pieces = opaque_pieces glCullFace(GL_BACK) self.tnv.prepare() for piece in pieces: self.tnv.drawpiece(piece) elif mode == 'TRANSPARENT': glEnable(GL_BLEND) # just make sure pieces = list(set(self.pieces) - set(opaque_pieces)) glCullFace(GL_FRONT) # draw backfaces first self.tnv.prepare() for piece in pieces: self.tnv.drawpiece(piece) glCullFace(GL_BACK) # draw front faces over back faces for piece in pieces: self.tnv.drawpiece(piece) elif mode == 'PICK': #PICK glCullFace(GL_BACK) pieces = self.pieces self.tnv.prepare() for piece in pieces: picking.label((self.__class__.__name__, self._name, piece)) self.tnv.drawpiece(piece) picking.nolabel() else: raise ValueError("render mode %s?" % mode)
def initializeGL(self): """ Initialize GL """ GL.glClearColor(1., 1., 1., 1.) GL.glShadeModel(GL.GL_SMOOTH) glEnable(GL.GL_CULL_FACE) glEnable(GL.GL_DEPTH_TEST) glEnable(GL.GL_LIGHTING) lightZeroPosition = [-800., 500., 1500., 1.] lightZeroColor = [1.0, 1., 1., 1.0] #green tinged glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, lightZeroPosition) glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, lightZeroColor) glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, [0.5, 0.5, 0.5, 1.0]) GL.glLightf(GL.GL_LIGHT0, GL.GL_CONSTANT_ATTENUATION, 1.000) #glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.01) glEnable(GL.GL_LIGHT0) glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, [100., 200., -20., 1.]) glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, [1., 1., 1., 1.0]) glLightfv(GL.GL_LIGHT1, GL.GL_SPECULAR, [1.0, 1.0, 1.0, 1.0]) glLightfv(GL.GL_LIGHT1, GL.GL_AMBIENT, [0., 0., 0., 1.0]) GL.glLightf(GL.GL_LIGHT1, GL.GL_CONSTANT_ATTENUATION, 1) #glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, 0.01) glEnable(GL.GL_LIGHT1) GL.glShadeModel(GL.GL_SMOOTH) GL.glMatrixMode(GL.GL_PROJECTION) GLU.gluPerspective(40., 1., 1., 40.) GL.glMatrixMode(GL.GL_MODELVIEW) GLU.gluLookAt(0, 0, 10, 0, 0, 0, 0, 1, 0) GL.glPushMatrix()
def save_FBO(self): bw, bh = self.size glEnable(GL_TEXTURE_RECTANGLE_ARB) glBindFramebuffer(GL_READ_FRAMEBUFFER, self.offscreen_fbo) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO]) glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_RECTANGLE_ARB, self.textures[TEX_FBO], 0) glReadBuffer(GL_COLOR_ATTACHMENT0) glViewport(0, 0, bw, bh) size = bw*bh*4 data = numpy.empty(size) img_data = glGetTexImage(GL_TEXTURE_RECTANGLE_ARB, 0, GL_BGRA, GL_UNSIGNED_BYTE, data) img = Image.frombuffer("RGBA", (bw, bh), img_data, "raw", "BGRA", bw*4) img = ImageOps.flip(img) kwargs = {} if SAVE_BUFFERS=="jpeg": kwargs = { "quality" : 0, "optimize" : False, } t = time.time() tstr = time.strftime("%H-%M-%S", time.localtime(t)) filename = "./W%i-FBO-%s.%03i.%s" % (self.wid, tstr, (t*1000)%1000, SAVE_BUFFERS) log("do_present_fbo: saving %4ix%-4i pixels, %7i bytes to %s", bw, bh, size, filename) img.save(filename, SAVE_BUFFERS, **kwargs) glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0) glDisable(GL_TEXTURE_RECTANGLE_ARB)
def gl_init_debug(self): #ensure python knows which scope we're talking about: global glInitStringMarkerGREMEDY, glStringMarkerGREMEDY global glInitFrameTerminatorGREMEDY, glFrameTerminatorGREMEDY # Ask GL to send us all debug messages if GL_DEBUG_OUTPUT and gl_debug_callback and glInitDebugKHR() == True: glEnable(GL_DEBUG_OUTPUT) glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS) glDebugMessageCallback(gl_debug_callback, None) glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, None, GL_TRUE) # Initialize string_marker GL debugging extension if available if glInitStringMarkerGREMEDY and glInitStringMarkerGREMEDY() == True: log.info("Extension GL_GREMEDY_string_marker available. Will output detailed information about each frame.") else: # General case - running without debugger, extension not available glStringMarkerGREMEDY = None #don't bother trying again for another window: glInitStringMarkerGREMEDY = None # Initialize frame_terminator GL debugging extension if available if glInitFrameTerminatorGREMEDY and glInitFrameTerminatorGREMEDY() == True: log.info("Enabling GL frame terminator debugging.") else: glFrameTerminatorGREMEDY = None #don't bother trying again for another window: glInitFrameTerminatorGREMEDY = None
def __init__(self, view): self.clock = pg.time.Clock() self.view = view glEnable(GL_DEPTH_TEST) self.ADDENEMY = pg.USEREVENT + 1 # pylint: disable=no-member pg.time.set_timer(self.ADDENEMY, randint(500, 750)) self.NEWTORNADO = pg.USEREVENT + 2 # pylint: disable=no-member pg.time.set_timer(self.NEWTORNADO, randint(5000, 20000)) self.enemies = [] self.splats = [] self.splats_collect = [] self.bullets = [] self.tornados = [] self.all_sprites = [] self.player = Player() self.splat_count = [0] self.background = Background(desert_road_png) self.loot_button = Hud_Button(treasure_png, (-.85, -.8)) self.loot = ui.Window('Loot', self.splat_count, self.view, self.player) self.loot.paint_select[0].active = True self.loot.paint_select[0].owned = True self.isRunning = True
def compile_total_list(self): if self.total_list is not None: glNewList(self.total_list, GL_COMPILE) # reset a few things glDisable(GL_DEPTH_TEST) glDisable(GL_LIGHTING) glMatrixMode(GL_PROJECTION) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glLoadIdentity() # change the modelview to camera coordinates viewport = glGetIntegerv(GL_VIEWPORT) width = viewport[2] - viewport[0] height = viewport[3] - viewport[1] if width > height: w = float(width) / float(height) h = 1.0 else: w = 1.0 h = float(height) / float(width) glScalef(2/w, 2/h, 1.0) glCallList(self.draw_list) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glEndList()
def draw_vertices(self): # Draw all the vbo defined in set_atoms if self.transparent: glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glDepthMask(GL_FALSE) if self.wireframe: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) glEnableClientState(GL_VERTEX_ARRAY) self._vbo_v.bind_vertexes(3, GL_FLOAT) glEnableClientState(GL_NORMAL_ARRAY) self._vbo_n.bind_normals(GL_FLOAT) glEnableClientState(GL_COLOR_ARRAY) self._vbo_c.bind_colors(4, GL_UNSIGNED_BYTE) glDrawArrays(GL_TRIANGLES, 0, self._n_triangles) self._vbo_v.unbind() self._vbo_n.unbind() self._vbo_c.unbind() if self.transparent: glDisable(GL_BLEND) #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glDepthMask(GL_TRUE) if self.wireframe: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
def draw_conf_corner_bg_image(self, pos = None): #bruce 070626 (pos argument is just for development & debugging) """ Redraw the previously grabbed conf_corner_bg_image, in the same place from which it was grabbed, or in the specified place (lower left corner of pos, in OpenGL window coords). Note: this modifies the OpenGL raster position. """ if not self._conf_corner_bg_image_data: print "self._conf_corner_bg_image_data not yet assigned" else: subwidth, subheight, width, height, gl_format, gl_type, image = self._conf_corner_bg_image_data if width != self.width or height != self.height: # I don't know if this can ever happen; if it can, caller might need # to detect this itself and do a full redraw. # (Or we might make this method return a boolean to indicate it.) print "can't draw self._conf_corner_bg_image_data -- glpane got resized" ### else: if pos is None: pos = (width - subwidth, height - subheight) x, y = pos self._set_raster_pos(x, y) glDisable(GL_DEPTH_TEST) # otherwise it can be obscured by prior drawing into depth buffer # Note: doing more disables would speed up glDrawPixels, # but that doesn't matter unless we do it many times per frame. glDrawPixels(subwidth, subheight, gl_format, gl_type, image) glEnable(GL_DEPTH_TEST) pass return
def stencilPush(): '''Create a new stack in stencil stack. All the next draw will be done in stencil buffer until stencilUse() will be called.''' global __stencil_stack glPushAttrib(GL_STENCIL_BUFFER_BIT | GL_STENCIL_TEST) # enable stencil test if not yet enabled if not glIsEnabled(GL_STENCIL_TEST): glClearStencil(0) glClear(GL_STENCIL_BUFFER_BIT) glEnable(GL_STENCIL_TEST) # increment the draw buffer glStencilFunc(GL_NEVER, 0x0, 0x0) glStencilOp(GL_INCR, GL_INCR, GL_INCR) glColorMask(0, 0, 0, 0) # save model view m = glGetFloatv(GL_MODELVIEW_MATRIX) __stencil_stack_view.append(m) # start recording GL operation dl = GlDisplayList() dl.start() __stencil_stack_dl.append(dl) __stencil_stack += 1
def _render(self) -> None: """ Render the whole scene here. Note that, this is a private function and should not be overriden unless you really know what you are dealing with. """ # Disable Depth Test to draw background at the very back of the scene glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # type: ignore self.background.render() glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) proj, view = self.active_observer.render() self.grid.render(proj, view, self.lights) self._render_lock = True for object in self.objects: self.objects[object].render(proj, view, self.lights) for object in self.huds: self.huds[object].render(proj, view, self.lights) self._render_lock = False for test in self._collision_detectors: test.check() self.__fps_counter += 1 if self.__timer == -1: self.__timer = time.time() diff = time.time() - self.__timer if diff > 1: self.__timer = time.time() self.fps = self.__fps_counter self.__fps_counter = 0
def update_texture_rgb24(self, img_data, x, y, width, height, rowstride): drawable = self.glarea.get_gl_drawable() context = self.glarea.get_gl_context() if not drawable.gl_begin(context): raise Exception("** Cannot create OpenGL rendering context!") assert self.textures is not None glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstride/3) if self.current_mode == GLClientWindow.MODE_YUV: raise Exception("** YUV -> RGB mode change unimplemented!") elif self.current_mode == GLClientWindow.MODE_UNINITIALIZED: log("Creating new RGB texture") w, h = self.get_size() # First time we draw must be full image assert w == width and h == height glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0) self.current_mode = GLClientWindow.MODE_RGB log("Updating RGB texture") glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, img_data) drawable.gl_end() self.render_image()
def initialise_glfw(): """Initialises the GLFW window and world UI""" if not glfw.init(): sys.exit(1) # glfw.window_hint(glfw.OPENGL_DEBUG_CONTEXT, 1) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) # This can be used to turn on multisampling AA for the default render target. # glfw.window_hint(glfw.SAMPLES, g_currentMsaaSamples) window = glfw.create_window(START_WIDTH, START_HEIGHT, "The Mega-racer world", None, None) if not window: glfw.terminate() sys.exit(1) glfw.make_context_current(window) print( "{}\nOpenGL\n Vendor: {}\n Renderer: {}\n Version: {}\n{}\n".format( ''.center(38, '-'), glGetString(GL_VENDOR).decode("utf8"), glGetString(GL_RENDERER).decode("utf8"), glGetString(GL_VERSION).decode("utf8"), ''.center(38, '-')), flush=True) # Enable some much-needed hardware functions that are off by default. glEnable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) return window
def drawwiresphere_worker(params): """ Draw a wireframe sphere. Receive parameters through a sequence so that this function and its parameters can be passed to another function for deferment. Right now this is only ColorSorter.schedule (see below) """ (color, pos, radius, detailLevel) = params ## assert detailLevel == 1 # true, but leave out for speed from utilities.debug_prefs import debug_pref, Choice_boolean_True #bruce 060415 experiment, re iMac G4 wiresphere bug; fixes it! newway = debug_pref("new wirespheres?", Choice_boolean_True) oldway = not newway # These objects want a constant line color even if they are selected or # highlighted. glColor3fv(color) glDisable(GL_LIGHTING) if oldway: glPolygonMode(GL_FRONT, GL_LINE) glPushMatrix() glTranslatef(pos[0], pos[1], pos[2]) glScale(radius, radius, radius) if oldway: glCallList(drawing_globals.sphereList[detailLevel]) else: glCallList(drawing_globals.wiresphere1list) glEnable(GL_LIGHTING) glPopMatrix() if oldway: glPolygonMode(GL_FRONT, GL_FILL) return
def _setup_lighting(self): """ [private method] Set up lighting in the model (according to self._lights). [Called from both initializeGL and paintGL.] """ # note: there is some duplicated code in this method # in GLPane_lighting_methods (has more comments) and ThumbView, # but also significant differences. Should refactor sometime. # [bruce 060415/080912 comment] glEnable(GL_NORMALIZE) # bruce comment 050311: I don't know if this relates to lighting or not # grantham 20051121: Yes, if NORMALIZE is not enabled (and normals # aren't unit length or the modelview matrix isn't just rotation) # then the lighting equation can produce unexpected results. #bruce 050413 try to fix bug 507 in direction of lighting: ##k might be partly redundant now; not sure whether projection matrix needs to be modified here [bruce 051212] glMatrixMode(GL_PROJECTION) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glLoadIdentity() #bruce 051212 moved most code from this method into new function, setup_standard_lights setup_standard_lights( self._lights, self.glprefs) # record what glprefs data was used by that, for comparison to see when we need to call it again # (not needed for _lights since another system tells us when that changes) self._last_glprefs_data_used_by_lights = glprefs_data_used_by_setup_standard_lights( self.glprefs) return
def update_texture_rgb24(self, img_data, x, y, width, height, rowstride): drawable = self.glarea.get_gl_drawable() context = self.glarea.get_gl_context() if not drawable.gl_begin(context): raise Exception("** Cannot create OpenGL rendering context!") assert self.textures is not None glBindTexture(GL_TEXTURE_RECTANGLE_ARB, self.textures[0]) glPixelStorei(GL_UNPACK_ROW_LENGTH, rowstride / 3) if self.current_mode == GLClientWindow.MODE_YUV: raise Exception("** YUV -> RGB mode change unimplemented!") elif self.current_mode == GLClientWindow.MODE_UNINITIALIZED: log("Creating new RGB texture") w, h = self.get_size() # First time we draw must be full image assert w == width and h == height glEnable(GL_TEXTURE_RECTANGLE_ARB) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0) self.current_mode = GLClientWindow.MODE_RGB log("Updating RGB texture") glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, img_data) drawable.gl_end() self.render_image()
def drawFullWindow(vtColors): """ Draw gradient background color. <vtColors> is a 4 element list specifying colors for the left-down, right-down, right-up, left-up window corners. To draw the full window, the modelview and projection should be set in identity. """ from utilities.constants import GL_FAR_Z glDisable(GL_LIGHTING) glBegin(GL_QUADS) glColor3fv(vtColors[0]) glVertex3f(-1, -1, GL_FAR_Z) glColor3fv(vtColors[1]) glVertex3f(1, -1, GL_FAR_Z) glColor3fv(vtColors[2]) glVertex3f(1, 1, GL_FAR_Z) glColor3fv(vtColors[3]) glVertex3f(-1, 1, GL_FAR_Z) glEnd() glEnable(GL_LIGHTING) return
def drawFilledCircle(color, center, radius, normal): """ Scale, rotate/translate the unit circle properly. Added a filled circle variant, piotr 080405 """ glMatrixMode(GL_MODELVIEW) glPushMatrix() glColor3fv(color) glDisable(GL_LIGHTING) glTranslatef(center[0], center[1], center[2]) rQ = Q(V(0, 0, 1), normal) rotAngle = rQ.angle*180.0/pi #This may cause problems as proved before in Linear motor display. #rotation around (0, 0, 0) #if vlen(V(rQ.x, rQ.y, rQ.z)) < 0.00005: # rQ.x = 1.0 glRotatef(rotAngle, rQ.x, rQ.y, rQ.z) glScalef(radius, radius, 1.0) glCallList(drawing_globals.filledCircleList) glEnable(GL_LIGHTING) glPopMatrix() return
def drawRotateSign(color, pos1, pos2, radius, rotation = 0.0): """Rotate sign on top of the caps of the cylinder """ glPushMatrix() glColor3fv(color) vec = pos2-pos1 axis = norm(vec) glTranslatef(pos1[0], pos1[1], pos1[2]) ##Huaicai 1/17/05: To avoid rotate around (0, 0, 0), which causes ## display problem on some platforms angle = -acos(axis[2])*180.0/pi if (axis[2]*axis[2] >= 1.0): glRotate(angle, 0.0, 1.0, 0.0) else: glRotate(angle, axis[1], -axis[0], 0.0) glRotate(rotation, 0.0, 0.0, 1.0) #bruce 050518 glScale(radius,radius,Numeric.dot(vec,vec)**.5) glLineWidth(2.0) glDisable(GL_LIGHTING) glCallList(drawing_globals.rotSignList) glEnable(GL_LIGHTING) glLineWidth(1.0) glPopMatrix() return
def draw_conf_corner_bg_image( self, pos=None ): #bruce 070626 (pos argument is just for development & debugging) """ Redraw the previously grabbed conf_corner_bg_image, in the same place from which it was grabbed, or in the specified place (lower left corner of pos, in OpenGL window coords). Note: this modifies the OpenGL raster position. """ if not self._conf_corner_bg_image_data: print "self._conf_corner_bg_image_data not yet assigned" else: subwidth, subheight, width, height, gl_format, gl_type, image = self._conf_corner_bg_image_data if width != self.width or height != self.height: # I don't know if this can ever happen; if it can, caller might need # to detect this itself and do a full redraw. # (Or we might make this method return a boolean to indicate it.) print "can't draw self._conf_corner_bg_image_data -- glpane got resized" ### else: if pos is None: pos = (width - subwidth, height - subheight) x, y = pos self._set_raster_pos(x, y) glDisable( GL_DEPTH_TEST ) # otherwise it can be obscured by prior drawing into depth buffer # Note: doing more disables would speed up glDrawPixels, # but that doesn't matter unless we do it many times per frame. glDrawPixels(subwidth, subheight, gl_format, gl_type, image) glEnable(GL_DEPTH_TEST) pass return
def drawArrowHead(color, basePoint, drawingScale, unitBaseVector, unitHeightVector): arrowBase = drawingScale * 0.08 arrowHeight = drawingScale * 0.12 glDisable(GL_LIGHTING) glPushMatrix() glTranslatef(basePoint[0],basePoint[1],basePoint[2]) point1 = V(0, 0, 0) point1 = point1 + unitHeightVector * arrowHeight point2 = unitBaseVector * arrowBase point3 = - unitBaseVector * arrowBase #Draw the arrowheads as filled triangles glColor3fv(color) glBegin(GL_POLYGON) glVertex3fv(point1) glVertex3fv(point2) glVertex3fv(point3) glEnd() glPopMatrix() glEnable(GL_LIGHTING)
def drawwiresphere_worker(params): """ Draw a wireframe sphere. Receive parameters through a sequence so that this function and its parameters can be passed to another function for deferment. Right now this is only ColorSorter.schedule (see below) """ (color, pos, radius, detailLevel) = params ## assert detailLevel == 1 # true, but leave out for speed from utilities.debug_prefs import debug_pref, Choice_boolean_True #bruce 060415 experiment, re iMac G4 wiresphere bug; fixes it! newway = debug_pref("new wirespheres?", Choice_boolean_True) oldway = not newway # These objects want a constant line color even if they are selected or # highlighted. glColor3fv(color) glDisable(GL_LIGHTING) if oldway: glPolygonMode(GL_FRONT, GL_LINE) glPushMatrix() glTranslatef(pos[0], pos[1], pos[2]) glScale(radius,radius,radius) if oldway: glCallList(drawing_globals.sphereList[detailLevel]) else: glCallList(drawing_globals.wiresphere1list) glEnable(GL_LIGHTING) glPopMatrix() if oldway: glPolygonMode(GL_FRONT, GL_FILL) return
def drawPoint(color, point, pointSize = 3.0, isRound = True): """ Draw a point using GL_POINTS. @param point: The x,y,z coordinate array/ vector of the point @type point: A or V @param pointSize: The point size to be used by glPointSize @type pointSize: float @param isRound: If True, the point will be drawn round otherwise square @type isRound: boolean """ glDisable(GL_LIGHTING) glColor3fv(color) glPointSize(float(pointSize)) if isRound: glEnable(GL_POINT_SMOOTH) glBegin(GL_POINTS) glVertex3fv(point) glEnd() if isRound: glDisable(GL_POINT_SMOOTH) glEnable(GL_LIGHTING) if pointSize != 1.0: glPointSize(1.0) return
def draw(self, line_width=1, color=(1.0, 0.0, 0.0)): glEnable(GL_DEPTH_TEST) glEnable(GL_LINE_SMOOTH) glShadeModel(GL_FLAT) glPushMatrix() glLineWidth(line_width) glColor3f(*color) glBegin(GL_LINES) glVertex3f(-1.0, 0.0, 0.0) glVertex3f(1.0, 0.0, 0.0) glEnd() glPushMatrix() glTranslated(1.0, 0.0, 0.0) glRotated(90, 0.0, 1.0, 0.0) glutSolidCone(0.05, 0.2, 16, 16) glPopMatrix() glBegin(GL_LINES) glVertex3f(0.0, -1.0, 0.0) glVertex3f(0.0, 1.0, 0.0) glEnd() glPushMatrix() glTranslated(0.0, 1.0, 0.0) glRotated(-90, 1.0, 0.0, 0.0) glutSolidCone(0.05, 0.2, 16, 16) glPopMatrix() glBegin(GL_LINES) glVertex3f(0.0, 0.0, -1.0) glVertex3f(0.0, 0.0, 1.0) glEnd() glPushMatrix() glTranslated(0.0, 0.0, 1.0) glutSolidCone(0.05, 0.2, 16, 16) glPopMatrix() glPopMatrix()
def drawrectangle(pt1, pt2, rt, up, color): """ Draws a (hollow) rectangle outline of the given I{color}. @param pt1: First corner of the rectangle. @type pt1: Point @param pt1: Opposite corner of the rectangle. @type pt1: Point @param rt: Right vector of the glpane. @type rt: Unit vector @param up: Right vector of the glpane. @type up: Unit vector @param color: Color @type color: color """ glColor3f(color[0], color[1], color[2]) glDisable(GL_LIGHTING) c2 = pt1 + rt * Numeric.dot(rt, pt2 - pt1) c3 = pt1 + up * Numeric.dot(up, pt2 - pt1) glBegin(GL_LINE_LOOP) glVertex(pt1[0], pt1[1], pt1[2]) glVertex(c2[0], c2[1], c2[2]) glVertex(pt2[0], pt2[1], pt2[2]) glVertex(c3[0], c3[1], c3[2]) glEnd() glEnable(GL_LIGHTING)
def drawbrick(color, center, axis, l, h, w, opacity = 1.0): if len(color) == 3: color = (color[0], color[1], color[2], opacity) if opacity != 1.0: glDepthMask(GL_FALSE) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) apply_material(color) glPushMatrix() glTranslatef(center[0], center[1], center[2]) ##Huaicai 1/17/05: To avoid rotate around (0, 0, 0), which causes ## display problem on some platforms angle = -acos(axis[2])*180.0/pi if (axis[2]*axis[2] >= 1.0): glRotate(angle, 0.0, 1.0, 0.0) else: glRotate(angle, axis[1], -axis[0], 0.0) glScale(h, w, l) #bruce 060302 revised the contents of solidCubeList while fixing bug 1595 glCallList(drawing_globals.solidCubeList) if opacity != 1.0: glDisable(GL_BLEND) glDepthMask(GL_TRUE) glPopMatrix() return
def drawCubeCell(color): sp0 = drawing_globals.sp0 sp4 = drawing_globals.sp4 vs = [[sp0, sp0, sp0], [sp4, sp0, sp0], [sp4, sp4, sp0], [sp0, sp4, sp0], [sp0, sp0, sp4], [sp4, sp0, sp4], [sp4, sp4, sp4], [sp0, sp4, sp4]] glDisable(GL_LIGHTING) glColor3fv(color) glBegin(GL_LINE_LOOP) for ii in range(4): glVertex3fv(vs[ii]) glEnd() glBegin(GL_LINE_LOOP) for ii in range(4, 8): glVertex3fv(vs[ii]) glEnd() glBegin(GL_LINES) for ii in range(4): glVertex3fv(vs[ii]) glVertex3fv(vs[ii+4]) glEnd() glEnable(GL_LIGHTING) return
def wrapper(self, *args, **kvargs): glEnable(GL_TEXTURE_2D) try: return func(self, *args, **kvargs) finally: glDisable(GL_TEXTURE_2D)
def draw(self): t1 = time.time() glClearColor(0.0, 0.0, 0.0, 0.0) glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) glLoadIdentity() horizonY = 1 * 2.2 - .6 + .5 GLU.gluLookAt(self.eyeX.x, horizonY, 8.0, self.lookX.x, horizonY, 0.0, 0.0, 1.0, 0.0) glEnable(GL.GL_TEXTURE_2D) if 0: with pushMatrix(): glColor3f(1, 0, 0) glTranslatef(*self.ball) glScalef(.2, .2, 1) imageCard("sample.jpg") with pushMatrix(): with mode(disable=[GL.GL_LIGHTING]): for card in self.cards: card.draw(self.eyeX.x, horizonY, self.cardList) glFlush() pygame.display.flip()
def drawcylinder_wireframe(color, end1, end2, radius): #bruce 060608 """ Draw a wireframe cylinder (not too pretty, definitely could look nicer, but it works.) """ # display polys as their edges (see drawer.py's drawwirecube or Jig.draw for # related code) (probably we should instead create a suitable lines display # list, or even use a wire-frame-like texture so various lengths work well) glPolygonMode(GL_FRONT, GL_LINE) glPolygonMode(GL_BACK, GL_LINE) glDisable(GL_LIGHTING) # This makes motors look too busy, but without it, they look too weird # (which seems worse.) glDisable(GL_CULL_FACE) try: ##k Not sure if this color will end up controlling the edge color; we ## hope it will. drawcylinder(color, end1, end2, radius) except: debug.print_compact_traceback("bug, ignored: ") # The following assumes that we are never called as part of a jig's drawing # method, or it will mess up drawing of the rest of the jig if it's # disabled. glEnable(GL_CULL_FACE) glEnable(GL_LIGHTING) glPolygonMode(GL_FRONT, GL_FILL) glPolygonMode(GL_BACK, GL_FILL) # could probably use GL_FRONT_AND_BACK return
def compile_total_list(self): if self.total_list is not None: glNewList(self.total_list, GL_COMPILE) # reset a few things glDisable(GL_DEPTH_TEST) glDisable(GL_LIGHTING) glMatrixMode(GL_PROJECTION) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glLoadIdentity() # change the modelview to camera coordinates viewport = glGetIntegerv(GL_VIEWPORT) width = viewport[2] - viewport[0] height = viewport[3] - viewport[1] if width > height: w = float(width) / float(height) h = 1.0 else: w = 1.0 h = float(height) / float(width) glScalef(2 / w, 2 / h, 1.0) glCallList(self.draw_list) glEnable(GL_DEPTH_TEST) glEnable(GL_LIGHTING) glEndList()
def _setup_lighting(self): """ [private method] Set up lighting in the model. [Called from both initializeGL and paintGL.] """ # note: there is some duplicated code in this method # in GLPane_lighting_methods (has more comments) and ThumbView, # but also significant differences. Should refactor sometime. # [bruce 060415/080912 comment] glEnable(GL_NORMALIZE) glMatrixMode(GL_PROJECTION) glLoadIdentity() glMatrixMode(GL_MODELVIEW) glLoadIdentity() #bruce 060415 moved following from ThumbView.initializeGL to this split-out method... #bruce 051212 revised lighting code to share prefs and common code with GLPane # (to fix bug 1200 and mitigate bugs 475 and 1158; # fully fixing those would require updating lighting in all ThumbView widgets # whenever lighting prefs change, including making .update calls on them, # and is not planned for near future since it's easy enough to close & reopen them) try: lights = self.shareWidget._lights #bruce 060415 shareWidget --> self.shareWidget; presumably always failed before that ###@@@ will this fix some bugs about common lighting prefs?? except: lights = _default_lights setup_standard_lights(lights, self.glprefs) return
def render(self): #init shadow matrix self.init_view() #open light glEnable(GL_LIGHTING) #clear color and depth caches glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #set model view matrix(danwei matrix is ok) #set trackball's rotate matrix as Modelview glMatrixMode(GL_MODELVIEW) glPushMatrix() #replace now-matrix with hengdeng matrix glLoadIdentity() glMultMatrixf(self.interaction.trackball.matrix) #save Modelview matrix, later change system with anti-matrix currentModelView = numpy.array(glGetFloatv(GL_MODELVIEW_MATRIX)) self.modelView = numpy.transpose(currentModelView) self.inverseModelView = inv(numpy.transpose(currentModelView)) #rend the scene self.scene.render() #after each shadow , huifu light state glDisable(GL_LIGHTING) glPopMatrix() glFlush()