def display(self): now = time.time() timedelt = now-self.timestamp self.timestamp = now self.current_fps = 1.0/timedelt hid_js.read_js(self.camera) view = self.camera.matrix() # updating shared variables in shader data block. Also see # timer() self.shader_data_block.map() self.shader_data_block.set('u_view', view) self.shader_data_block.set("camera_position", np.array(self.camera.loc, dtype=np.float32)) self.light_count += 1 if self.light_count == 2: self.light_count = 0 self.lights = self.get_lights() self.shader_data_block.set("light_diffuse", np.array(self.lights, dtype=np.float32)) self.shader_data_block.unmap() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) for drawable in self.drawables: drawable.draw() glut.glutSwapBuffers()
def on_display( ): global shader gl.glClearColor(1,1,1,1) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) gl.glEnable(gl.GL_BLEND) gl.glColor(0,0,0,1) shader.bind() radius = 255.0 theta, dtheta = 0, 5.5/180.0*math.pi support = 0.75 thickness = 1.0 for i in range(500): x = 256+radius*math.cos(theta); y = 32+256+radius*math.sin(theta); r = 10.1-i*0.02 circle( (x,y,r), thickness=thickness, support=support ) radius -= 0.45 theta += dtheta for i in range(0,39): r = 4 thickness = (i+1)/10.0 x = 20+i*12.5 - r y = 16 circle( (x,y,r), thickness=thickness, support=support ) glut.glutSwapBuffers( )
def draw(): """skeleton function""" gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) #clear screen gl.glLoadIdentity() #reset postition glut.glutSwapBuffers() #allows doouble buffering
def drawGLScene(): gl.glLoadIdentity() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) cube.drawCube() glut.glutSwapBuffers()
def solve(num): actions = globals()['actions'] if len(actions) > 0: cube.doAction(actions[0], True, drawGLScene) globals()['actions'] = actions[1:] glut.glutTimerFunc(500, solve, 0) drawGLScene()
def keyboard_press_event(self, key, x, y): if key == chr(27): glut.glutDestroyWindow(self.window) sys.exit(0) self.key_state[ord(key)] = True
def draw(self): self.execute() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() #handle mouse transformations gl.glTranslatef(self.initrans[0], self.initrans[1], self.initrans[2]) gl.glRotatef(self.rotate[0], 1, 0, 0) gl.glRotatef(self.rotate[1], 0, 1, 0) #we switched around the axis so make this rotate_z gl.glTranslatef(self.translate[0], self.translate[1], self.translate[2]) gl.glEnable(gl.GL_POINT_SMOOTH) gl.glPointSize(5) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) self.arrvbo.bind() gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glEnableClientState(gl.GL_COLOR_ARRAY) gl.glVertexPointer(4, gl.GL_FLOAT, 0, self.arrvbo) self.colvbo.bind() gl.glColorPointer(4, gl.GL_FLOAT, 0, self.colvbo) gl.glDrawArrays(gl.GL_POINTS, 0, self.size**3) gl.glDisableClientState(gl.GL_VERTEX_ARRAY) gl.glDisableClientState(gl.GL_COLOR_ARRAY) self.arrvbo.unbind() self.colvbo.unbind() glut.glutSwapBuffers() if self.makeMovie: gl.glReadPixels(0,0,800,600,gl.GL_RGB, gl.GL_UNSIGNED_BYTE, array=self.curimage) fname = '_tmp%05d.png'%self.curindex scipy.misc.imsave(fname, self.curimage) self.curindex += 1
def mouseButton( self, button, mode, x, y ): """Callback function for mouse button. http://stackoverflow.com/questions/14378/using-the-mouse-scrollwheel-in-glut """ #print button, mode if button == 3 and mode == 1: #scroll up #tZ = deltaY * self.scalingFactorTranslation tZ=5*self.scalingFactorTranslation self.translationMatrix.addTranslation(0, 0, -tZ) if button == 4 and mode == 1: #scroll down #tZ = deltaY * self.scalingFactorTranslation tZ=5 * self.scalingFactorTranslation self.translationMatrix.addTranslation(0, 0, tZ) if mode == glut.GLUT_DOWN: self.mouseButtonPressed = button else: self.mouseButtonPressed = None self.oldMousePos[0], self.oldMousePos[1] = x, y glut.glutPostRedisplay( )
def InitPyGame(): GLUT.glutInit(()) pygame.init() disp_no = os.getenv("DISPLAY") if disp_no: print "I'm running under X display = {0}".format(disp_no) drivers = ['fbcon', 'directfb', 'svgalib'] found = False for driver in drivers: if not os.getenv('SDL_VIDEODRIVER'): os.putenv('SDL_VIDEODRIVER', driver) try: pygame.display.init() except pygame.error: print 'Driver: {0} failed.'.format(driver) continue found = True break if not found: raise Exception('No suitable video driver found!') size = (pygame.display.Info().current_w, pygame.display.Info().current_h) print "Framebuffer size: %d x %d" % (size[0], size[1]) if config.full_screen: s = pygame.display.set_mode(size, locals.DOUBLEBUF | locals.OPENGL | locals.FULLSCREEN) else: s = pygame.display.set_mode(size, locals.DOUBLEBUF | locals.OPENGL) return s
def display(): update_from_http_control() gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) camera() gl.glTranslate(cam_x, cam_y, cam_z) sphere() glut.glutSwapBuffers()
def on_display(): global cube, theta, phi, frame, time, timebase frame += 1 time = glut.glutGet( glut.GLUT_ELAPSED_TIME ) if (time - timebase > 1000): print frame*1000.0/(time-timebase) timebase = time; frame = 0; gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glPushMatrix() gl.glRotatef(theta, 0,0,1) gl.glRotatef(phi, 0,1,0) gl.glDisable( gl.GL_BLEND ) gl.glEnable( gl.GL_LIGHTING ) gl.glEnable( gl.GL_DEPTH_TEST ) gl.glEnable( gl.GL_POLYGON_OFFSET_FILL ) gl.glPolygonMode( gl.GL_FRONT_AND_BACK, gl.GL_FILL ) cube.draw( gl.GL_QUADS, 'pnc' ) gl.glDisable( gl.GL_POLYGON_OFFSET_FILL ) gl.glEnable( gl.GL_BLEND ) gl.glDisable( gl.GL_LIGHTING ) gl.glPolygonMode( gl.GL_FRONT_AND_BACK, gl.GL_LINE ) gl.glDepthMask( gl.GL_FALSE ) gl.glColor( 0.0, 0.0, 0.0, 0.5 ) cube.draw( gl.GL_QUADS, 'p' ) gl.glDepthMask( gl.GL_TRUE ) gl.glPopMatrix() glut.glutSwapBuffers()
def draw(self): gl.glPushMatrix() # get global points point1 = self.body1.convert_to_global(self.__contact_point1) point2 = self.body2.convert_to_global(self.__contact_point2) current_length = la.norm(point1 - point2) # draw contact points as spheres gl.glColor3f(self.color[0], self.color[1], self.color[2]) gl.glPushMatrix() gl.glTranslatef(point1[0], point1[1], point1[2]) glut.glutSolidSphere(0.2, 8, 8) gl.glPopMatrix() gl.glPushMatrix() gl.glTranslatef(point2[0], point2[1], point2[2]) glut.glutSolidSphere(0.2, 8, 8) gl.glPopMatrix() # draw a line between them if current_length < self.length: gl.glColor3f(0.0, 1.0, 0.0) else: gl.glColor3f(1.0, 0.0, 0.0) gl.glBegin(gl.GL_LINES) gl.glVertex3f(point1[0], point1[1], point1[2]) gl.glVertex3f(point2[0], point2[1], point2[2]) gl.glEnd() gl.glPopMatrix()
def display(): global phi, theta gl.glDepthMask(gl.GL_TRUE) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) # Filled cube gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_POLYGON_OFFSET_FILL) gl.glUniform4f(gpu["uniform"]["u_color"], 1, 1, 1, 1) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, gpu["buffer"]["filled"]) gl.glDrawElements(gl.GL_TRIANGLES, len(f_indices), gl.GL_UNSIGNED_INT, None) # Outlined cube gl.glDisable(gl.GL_POLYGON_OFFSET_FILL) gl.glEnable(gl.GL_BLEND) gl.glDepthMask(gl.GL_FALSE) gl.glUniform4f(gpu["uniform"]["u_color"], 0, 0, 0, 0.5) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, gpu["buffer"]["outline"]) gl.glDrawElements(gl.GL_LINES, len(o_indices), gl.GL_UNSIGNED_INT, None) gl.glDepthMask(gl.GL_TRUE) # Rotate cube theta += 0.5 # degrees phi += 0.5 # degrees model = np.eye(4, dtype=np.float32) rotate(model, theta, 0, 0, 1) rotate(model, phi, 0, 1, 0) gl.glUniformMatrix4fv(gpu["uniform"]["u_model"], 1, False, model) glut.glutSwapBuffers()
def timer(fps): global clock global data global phi, theta clock += 0.005 * 1000.0/fps # for scaling #loc = gl.glGetUniformLocation(program, "scale") #gl.glUniform1f(loc, (1+np.cos(clock))/2.0) loc = gl.glGetUniformLocation(program, "transform") # transform['transform'] = [ # (np.cos(clock),np.sin(clock),0,0), # (-np.sin(clock),np.cos(clock),0,0), # (0,0,1,0), (0,0,0,1) ] # gl.glUniformMatrix4fv(loc, 1, False, transform['transform']) # Rotate cube theta += 0.5 # degrees phi += 0.5 # degrees model = np.eye(4, dtype=np.float32) rotate(model, theta, 0, 0, 1) rotate(model, phi, 0, 1, 0) gl.glUniformMatrix4fv(loc, 1, False, model) glut.glutTimerFunc(1000/fps, timer, fps) glut.glutPostRedisplay()
def draw(self, coordslinear, index, subtract_com=True): """ tell the gui how to represent your system using openGL objects Parameters ---------- coords : array index : int we can have more than one molecule on the screen at one time. index tells which one to draw. They are viewed at the same time, so they should be visually distinct, e.g. different colors. accepted values are 1 or 2 """ from OpenGL import GL,GLUT coords = coordslinear.reshape([-1, 3]) if subtract_com: com = np.mean(coords, axis=0) else: com = np.zeros(3) size = 0.5 * self.r0 for xx in coords: x=xx-com GL.glPushMatrix() GL.glTranslate(x[0],x[1],x[2]) GLUT.glutSolidSphere(size, 30, 30) GL.glPopMatrix()
def mouseWheel(self, wheel, direction, x, y): if direction > 0: self.camera.rad = max(0.1, self.camera.rad - 0.1) elif direction < 0: self.camera.rad = min(100, self.camera.rad + 0.1) GLUT.glutPostRedisplay()
def display_sphere(self): GL.glPointSize(1); GL.glLineWidth(0.5); GL.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, [1, 1, 1, 0.1]) GLUT.glutWireSphere(0.97, 20, 20) GL.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, [1, 1, 1, 0.5]) GLUT.glutSolidSphere(0.98, 20, 20)
def update(): global position, orientation t0 = time.time() orientation = (rotator**-1) * orientation go = np.array((orientation** -1) * np.matrix([[0], [0], [.2]])).flatten() position[0] += go[0] position[1] += go[1] position[2] += go[2] draw() t1 = time.time() if heightfunc(-position[2], -position[0]) > -position[1]: print("dead") time.sleep(5) position = [0.1, -27, -1.5] makeTea() orientation = np.matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype = np.float) for i, pot in enumerate(teapots): if ((pot[0] + position[0])**2 + (pot[1] + position[1])**2 + (pot[2] + position[2])**2 < 4): teapots[i][3] = True #print position GLUT.glutSetWindowTitle(str(1 / (t1 - t0)))
def draw(self, rbcoords, index): from OpenGL import GL,GLUT coords = self.aasystem.to_atomistic(rbcoords) com=np.mean(coords, axis=0) i=0 for xx in coords: if(i%3 == 0): color = [1.0, 0.0, 0.0] radius = 0.35 else: color = [1.0, 1.0, 1.0] radius = 0.3 if index == 2: color = [0.5, 1.0, .5] i+=1 GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, color) x=xx-com GL.glPushMatrix() GL.glTranslate(x[0],x[1],x[2]) GLUT.glutSolidSphere(radius,30,30) GL.glPopMatrix() for i in xrange(self.nrigid): color = [1.0, 0.0, 0.0] if index == 2: color = [0.5, 1.0, .5] GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, color) self.drawCylinder(coords[3*i]-com, coords[3*i+1]-com) self.drawCylinder(coords[3*i]-com, coords[3*i+2]-com)
def glInit(): OGLUT.glutInit() # initialize the GLUT library. OGLUT.glutInitDisplayMode(OGLUT.GLUT_DOUBLE | OGLUT.GLUT_RGB |OGLUT.GLUT_DEPTH) # initial display mode OGL.glShadeModel(OGL.GL_SMOOTH) # Enable Smooth Shading OGL.glClearColor(0.0, 0.0, 0.0, 0.0) # Black Background OGL.glClearDepth(1.0) # Depth Buffer Setup OGL.glEnable(OGL.GL_DEPTH_TEST) # Enables Depth Testing OGL.glDepthFunc(OGL.GL_LEQUAL) # The Type Of Depth Testing To Do OGL.glHint(OGL.GL_PERSPECTIVE_CORRECTION_HINT, OGL.GL_NICEST) # Really Nice Perspective Calculations objCamera.Position_Camera(10, 4, 12, 9, 4, 12, 0, 1, 0) # Set Camera Position LoadVertices() OGL.glViewport(0,0,SCREEN_SIZE[0],SCREEN_SIZE[1]) # Reset The Current Viewport OGL.glMatrixMode(OGL.GL_PROJECTION) OGL.glLoadIdentity() # Calculate The Aspect Ratio Of The Window OGLU.gluPerspective(45.0, SCREEN_SIZE[0]/SCREEN_SIZE[1], 0.1, 100.0) OGL.glMatrixMode(OGL.GL_MODELVIEW) OGL.glCullFace(OGL.GL_BACK) # Don't draw the back sides of polygons OGL.glEnable(OGL.GL_CULL_FACE) # Turn on culling
def display(self): """ Render the scene. """ start = time.time() GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) GL.glPushMatrix() cam_x = self.zoom * math.sin(self.cam_lat) * math.cos(self.cam_long) cam_y = self.zoom * math.sin(self.cam_lat) * math.sin(self.cam_long) cam_z = self.zoom * math.cos(self.cam_lat) GLU.gluLookAt(cam_x, cam_y, cam_z, 0, 0, 0, 0, 0, 2) self.display_box() self.display_points() self.display_segments() self.display_circles() self.display_polygons() self.display_regions() self.display_sphere() GL.glPopMatrix() GLUT.glutSwapBuffers() render_time = time.time() - start GLUT.glutSetWindowTitle("%.3f" % render_time)
def stop(self): '''Exit mainloop''' if (glut.glutLeaveMainLoop): glut.glutLeaveMainLoop() else: raise RuntimeError( '''Your GLUT implementation does not allow to stops the main loop''')
def _vispy_get_native_app(self): # HiDPI support for retina display # This requires glut from # http://iihm.imag.fr/blanch/software/glut-macosx/ if sys.platform == 'darwin': try: glutInitDisplayString = platform.createBaseFunction( 'glutInitDisplayString', dll=platform.GLUT, resultType=None, argTypes=[ ctypes.c_char_p], doc='glutInitDisplayString( ) -> None', argNames=()) text = ctypes.c_char_p("rgba stencil double samples=8 hidpi") glutInitDisplayString(text) except: pass if not self._initialized: glut.glutInit() # todo: maybe allow user to give args? glut.glutInitDisplayMode(glut.GLUT_RGBA | glut.GLUT_DOUBLE | glut.GLUT_STENCIL | glut.GLUT_DEPTH) self._initialized = True return glut
def draw(self, coordslinear, index): """ tell the gui how to represent your system using openGL objects Parameters ---------- coords : array index : int we can have more than one molecule on the screen at one time. index tells which one to draw. They are viewed at the same time, so they should be visually distinct, e.g. different colors. accepted values are 1 or 2 """ # index = 1 or 2 from OpenGL import GL,GLUT coords = coordslinear.reshape(coordslinear.size/3, 3) com=np.mean(coords, axis=0) size = 0.5 if index == 1: color = [0.65, 0.0, 0.0, 1.] else: color = [0.00, 0.65, 0., 1.] GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, color) for i,xx in enumerate(coords): if i == self.ntypeA: size *= 0.88 #this should be dependent on lj parameters if index == 1: color = [0.25, 0.00, 0., 1.] else: color = [0.00, 0.25, 0., 1.] GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, color) x=xx-com GL.glPushMatrix() GL.glTranslate(x[0],x[1],x[2]) GLUT.glutSolidSphere(size,30,30) GL.glPopMatrix()
def display(): gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) program.draw(gl.GL_TRIANGLES, indices) glut.glutSwapBuffers() # Take screenshot in every display() screenshot()
def run(self): self.interval_ms = 0 if self.limit_fps <= 0 else 1000 / self.limit_fps if self.show_fps: self.previous_update_time = utils.current_time_ms() self.previous_fps_print = -1 glut.glutTimerFunc(self.interval_ms, self.update, 0) glut.glutMainLoop()
def display(): global projection, view global theta, phi theta += .43 phi += .37 gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) model = np.eye(4, dtype=np.float32) rotate(model, theta, 0,0,1) rotate(model, phi, 0,1,0) shader.bind() shader.uniformf('u_color', 1.0, 1.0, 1.0, 1.0 ) shader.uniform_matrixf('u_view', view) shader.uniform_matrixf('u_projection', projection) shader.uniform_matrixf('u_model', model) gl.glDisable( gl.GL_BLEND ) gl.glEnable( gl.GL_DEPTH_TEST ) gl.glEnable( gl.GL_POLYGON_OFFSET_FILL ) obj.draw( gl.GL_TRIANGLES ) gl.glDisable( gl.GL_POLYGON_OFFSET_FILL ) gl.glEnable( gl.GL_BLEND ); gl.glDepthMask( gl.GL_FALSE ); shader.uniformf('u_color', 0.0, 0.0, 0.0, 0.25 ) outline.draw( gl.GL_LINES ) gl.glDepthMask( gl.GL_TRUE ) gl.glUseProgram( 0 ) glut.glutSwapBuffers()
def visibility_cb(vis): # stop drawing if window not visible if vis: game.reset_timer() GLUT.glutIdleFunc(idle_cb) else: GLUT.glutIdleFunc(None)
def draw_sphere(xyz, radius=0.5, color=None): if color is not None: change_color(color) GL.glPushMatrix() GL.glTranslate(xyz[0], xyz[1], xyz[2]) GLUT.glutSolidSphere(radius, 30, 30) GL.glPopMatrix()
def display(): #zadane tocke grupiraju se u grupe po 4 i tumace kao vrhovi cetverokuta koje treba nacrtati gl.glBegin(gl.GL_QUADS) gl.glColor3f(1,0,0); gl.glVertex2f( 1.0,-1.0) gl.glColor3f(1,1,0); gl.glVertex2f(-1.0,-1.0) gl.glColor3f(1,1,1); gl.glVertex2f(-1.0, 1.0) gl.glColor3f(1,0,1); gl.glVertex2f( 1.0, 1.0) gl.glEnd() gl.glBegin(gl.GL_QUADS) gl.glColor3f(1,0,0); gl.glVertex2f( -0.85,0.85) gl.glColor3f(1,1,1); gl.glVertex2f(0.85,0.85) gl.glColor3f(0,1,1); gl.glVertex2f(0.85, -0.85) gl.glColor3f(0,1,0); gl.glVertex2f( -0.85, -0.85) gl.glEnd() gl.glBegin(gl.GL_QUADS) gl.glColor3f(0,1,1); gl.glVertex2f( 0.5,-0.5) gl.glColor3f(1,0,1); gl.glVertex2f(-0.5,-0.5) gl.glColor3f(1,1,1); gl.glVertex2f(-0.5, 0.5) gl.glColor3f(1,0,0); gl.glVertex2f( 0.5, 0.5) gl.glEnd() glut.glutSwapBuffers()
def bootstrap(glVersion=None): """Imports modules appropriate to the specified OpenGL version. The available OpenGL API version can only be queried once an OpenGL context is created, and a canvas is available to draw on. This makes things a bit complicated, because it means that we are only able to choose how to draw things when we actually need to draw them. This function should be called after an OpenGL context has been created, and a canvas is available for drawing, but before any attempt to draw anything. It will figure out which version-dependent package needs to be loaded, and will attach all of the modules contained in said package to the :mod:`~fsleyes.gl` package. The version-independent modules may then simply access these version-dependent modules through this module. After the :func:`boostrap` function has been called, the following package-level attributes will be available on the ``gl`` package: ====================== ==================================================== ``GL_VERSION`` A string containing the target OpenGL version, in the format ``major.minor``, e.g. ``2.1``. ``GL_RENDERER`` A string containing the name of the OpenGL renderer. ``glvolume_funcs`` The version-specific module containing functions for rendering :class:`.GLVolume` instances. ``glrgbvector_funcs`` The version-specific module containing functions for rendering :class:`.GLRGBVector` instances. ``gllinevector_funcs`` The version-specific module containing functions for rendering :class:`.GLLineVector` instances. ``glmesh_funcs`` The version-specific module containing functions for rendering :class:`.GLMesh` instances. ``gllabel_funcs`` The version-specific module containing functions for rendering :class:`.GLLabel` instances. ``gltensor_funcs`` The version-specific module containing functions for rendering :class:`.GLTensor` instances. ``glsh_funcs`` The version-specific module containing functions for rendering :class:`.GLSH` instances. ====================== ==================================================== This function also sets the :attr:`.Platform.glVersion` and :attr:`.Platform.glRenderer` properties of the :attr:`fsl.utils.platform.platform` instance. :arg glVersion: A tuple containing the desired (major, minor) OpenGL API version to use. If ``None``, the best possible API version will be used. """ import sys import OpenGL.GL as gl import OpenGL.extensions as glexts from . import gl14 from . import gl21 thismod = sys.modules[__name__] if hasattr(thismod, '_bootstrapped'): return if glVersion is None: glVer = gl.glGetString(gl.GL_VERSION).decode('ascii').split()[0] major, minor = [int(v) for v in glVer.split('.')][:2] else: major, minor = glVersion glVersion = major + minor / 10.0 glpkg = None if glVersion >= 2.1: verstr = '2.1' glpkg = gl21 elif glVersion >= 1.4: verstr = '1.4' glpkg = gl14 else: raise RuntimeError('OpenGL 1.4 or newer is required ' '(detected version: {:0.1f}'.format(glVersion)) # The gl21 implementation depends on a # few extensions - if they're not present, # fall back to the gl14 implementation if glpkg == gl21: # List any GL21 extensions here exts = ['GL_EXT_framebuffer_object', 'GL_ARB_instanced_arrays', 'GL_ARB_draw_instanced'] if not all(map(glexts.hasExtension, exts)): log.warning('One of these OpenGL extensions is ' 'not available: [{}]. Falling back ' 'to an older OpenGL implementation.' .format(', '.join(exts))) verstr = '1.4' glpkg = gl14 # If using GL14, and the ARB_vertex_program # and ARB_fragment_program extensions are # not present, we're screwed. if glpkg == gl14: exts = ['GL_EXT_framebuffer_object', 'GL_ARB_vertex_program', 'GL_ARB_fragment_program', 'GL_ARB_texture_non_power_of_two'] if not all(map(glexts.hasExtension, exts)): raise RuntimeError('One of these OpenGL extensions is ' 'not available: [{}]. This software ' 'cannot run on the available graphics ' 'hardware.'.format(', '.join(exts))) # Tensor/SH overlays are not available in GL14 import fsleyes.displaycontext as dc dc.ALL_OVERLAY_TYPES .remove('tensor') dc.ALL_OVERLAY_TYPES .remove('sh') dc.OVERLAY_TYPES['DTIFitTensor'].remove('tensor') dc.OVERLAY_TYPES['Image'] .remove('sh') dc.OVERLAY_TYPES['Image'] .remove('tensor') renderer = gl.glGetString(gl.GL_RENDERER).decode('ascii') log.debug('Using OpenGL {} implementation with renderer {}'.format( verstr, renderer)) # If on linux, we need to call glutInit. # If on OSX, we don't need to bother. # # note: GLUT is only required for text # rendering. The GLUT requirement # means that true off-screen (i.e. # headless) rendering is not # currently possible, although # would be if we removed GLUT # as a requirement. Off-screen # rendering is possible via other # means (e.g. xvfb-run). if fslplatform.os == 'Linux': import OpenGL.GLUT as GLUT GLUT.glutInit() # Populate this module, and set # the fsl.utils.platform GL fields thismod.GL_VERSION = verstr thismod.GL_RENDERER = renderer thismod.glvolume_funcs = glpkg.glvolume_funcs thismod.glrgbvector_funcs = glpkg.glrgbvector_funcs thismod.gllinevector_funcs = glpkg.gllinevector_funcs thismod.glmesh_funcs = glpkg.glmesh_funcs thismod.gllabel_funcs = glpkg.gllabel_funcs thismod.gltensor_funcs = glpkg.gltensor_funcs thismod.glsh_funcs = glpkg.glsh_funcs thismod._bootstrapped = True fslplatform.glVersion = thismod.GL_VERSION fslplatform.glRenderer = thismod.GL_RENDERER # If we're using a software based renderer, # reduce the default performance settings # # But SVGA3D/llvmpipe are super fast, so if # we're using either of them, pretend that # we're on hardware if fslplatform.glIsSoftwareRenderer and \ 'llvmpipe' not in fslplatform.glRenderer.lower() and \ 'svga3d' not in fslplatform.glRenderer.lower(): log.debug('Software-based rendering detected - ' 'lowering default performance settings.') import fsleyes.displaycontext as dc dc.SceneOpts.performance.setAttribute(None, 'default', 1)
def enable(self, app=None): """Enable event loop integration with GLUT. Parameters ---------- app : ignored Ignored, it's only a placeholder to keep the call signature of all gui activation methods consistent, which simplifies the logic of supporting magics. Notes ----- This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to integrate with terminal based applications like IPython. Due to GLUT limitations, it is currently not possible to start the event loop without first creating a window. You should thus not create another window but use instead the created one. See 'gui-glut.py' in the docs/examples/lib directory. The default screen mode is set to: glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH """ import OpenGL.GLUT as glut from IPython.lib.inputhookglut import glut_display_mode, \ glut_close, glut_display, \ glut_idle, inputhook_glut if GUI_GLUT not in self.manager.apps: glut.glutInit(sys.argv) glut.glutInitDisplayMode(glut_display_mode) # This is specific to freeglut if bool(glut.glutSetOption): glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE, glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS) glut.glutCreateWindow(sys.argv[0]) glut.glutReshapeWindow(1, 1) glut.glutHideWindow() glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) else: glut.glutWMCloseFunc(glut_close) glut.glutDisplayFunc(glut_display) glut.glutIdleFunc(glut_idle) self.manager.set_inputhook(inputhook_glut) self.manager.apps[GUI_GLUT] = True
frames = frames + 1 if t-t0 > 2500: print "FPS : %.2f (%d frames in %.2f second)" % (frames*1000.0/(t-t0), frames, (t-t0)/1000.0) t0, frames = t,0 glut.glutPostRedisplay() # ----------------------------------------------------------------------------- if __name__ == '__main__': import sys import OpenGL.GLUT as glut from glagg import curve4_bezier from glagg import PathCollection t0, frames = glut.glutGet(glut.GLUT_ELAPSED_TIME), 0 glut.glutInit(sys.argv) glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB | glut.GLUT_DEPTH) glut.glutInitWindowSize(800, 800) glut.glutCreateWindow("Shapes") glut.glutDisplayFunc(on_display) glut.glutReshapeFunc(on_reshape) glut.glutKeyboardFunc(on_keyboard) glut.glutIdleFunc(on_idle) collection = PathCollection() def heart(): vertices = curve4_bezier( (0.0,-0.5), (0.75,+0.25), (.75,+1.0), (0.0,+0.5) ) n = len(vertices) V = np.zeros((2*n,2)) V[:n] = vertices
def paintGL(self): self.loadScene() glut.glutWireSphere(2, 13, 13)
def set_title(self, title): self.activate() glut.glutSetWindowTitle(title) self._title = title
def update(self): GLUT.glutPostRedisplay()
def on_display(): gl.glClearColor(1, 1, 1, 1) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) collection.draw() glut.glutSwapBuffers()
def drawHeatMapScale(self, field): GL.glMatrixMode(GL.GL_PROJECTION) GL.glPushMatrix() GL.glLoadIdentity() GL.glOrtho(-60, 60, -60, 60, 0, 200) # GL.glPopMatrix() GL.glMatrixMode(GL.GL_MODELVIEW) GL.glPushMatrix() GL.glLoadIdentity() GL.glDisable(GL.GL_LIGHTING) if bool(GLUT.glutBitmapString): GL.glColor3f(0.0, 0.0, 0.0) GL.glRasterPos2i(26, -58) GLUT.glutBitmapString(GLUT.GLUT_BITMAP_HELVETICA_12, f"{max(field) : .2f}".encode()) GL.glRasterPos2i(-32, -58) GLUT.glutBitmapString(GLUT.GLUT_BITMAP_HELVETICA_12, f"{min(field) : .2f}".encode()) GL.glRasterPos2i(-5, -58) GLUT.glutBitmapString(GLUT.GLUT_BITMAP_HELVETICA_12, "dA/dt (V/m)".encode()) top = -50 bot = -55 GL.glBegin(GL.GL_QUAD_STRIP) GL.glColor3f(0, 0, 0.5) GL.glVertex2f(-30, top) GL.glVertex2f(-30, bot) GL.glColor3f(0, 0, 1) GL.glVertex2f(-22.5, top) GL.glVertex2f(-22.5, bot) GL.glColor3f(0, 1, 1) GL.glVertex2f(-7.5, top) GL.glVertex2f(-7.5, bot) GL.glColor3f(0.5, 1, 0.5) GL.glVertex2f(0, top) GL.glVertex2f(0, bot) GL.glColor3f(1, 1, 0) GL.glVertex2f(7.5, top) GL.glVertex2f(7.5, bot) GL.glColor3f(1, 0, 0) GL.glVertex2f(22, top) GL.glVertex2f(22, bot) GL.glColor3f(0.5, 0, 0) GL.glVertex2f(30, top) GL.glVertex2f(30, bot) GL.glEnd() GL.glEnable(GL.GL_LIGHTING) GL.glPopMatrix() GL.glMatrixMode(GL.GL_PROJECTION) GL.glPopMatrix() GL.glMatrixMode(GL.GL_MODELVIEW)
def timer(self, val): if GrContext.print_fps: sys.stderr.write("{} display fps: {}\n".format( self._title, self.framecount / 2.)) self.framecount = 0 GLUT.glutTimerFunc(2000, lambda val: self.timer(val), 0)
def mouse_button_handler(self, button, state, x, y): if button == GLUT.GLUT_RIGHT_BUTTON: GLUT.glutSetWindow(self.window) if state == GLUT.GLUT_UP: # sys.stderr.write("RMB up: forward={}\n up={}\n".format(self._forward, self._up)) # sys.stderr.write(" θ={:.2f}, φ={:.2f}, upθ={:.2f}, upφ={:.2f}\n" # .format(self._theta, self._phi, self._uptheta, self._upphi)) GLUT.glutMotionFunc(None) elif state == GLUT.GLUT_DOWN: # sys.stderr.write("RMB down\n") self._mousex0 = x self._mousey0 = y self._origtheta = math.acos( -self._forward[1] / math.sqrt(self._forward[0]**2 + self._forward[1]**2 + self._forward[2]**2)) self._origphi = math.atan2(-self._forward[0], -self._forward[2]) # sys.stderr.write("origθ = {:.2f}, origφ = {:.2f}\n".format(self._origtheta, self._origphi)) GLUT.glutMotionFunc(lambda x, y: self.rmb_moved(x, y)) if button == GLUT.GLUT_MIDDLE_BUTTON: GLUT.glutSetWindow(self.window) if state == GLUT.GLUT_UP: # sys.stderr.write("MMB up\n") GLUT.glutMotionFunc(None) elif state == GLUT.GLUT_DOWN: # sys.stderr.write("MMB down\n") self._mousex0 = x self._mousey0 = y self._origrange = self._range GLUT.glutMotionFunc(lambda x, y: self.mmb_moved(x, y)) if button == GLUT.GLUT_LEFT_BUTTON: GLUT.glutSetWindow(self.window) if state == GLUT.GLUT_UP: # sys.stderr.write("LMB up: self._center={}\n".format(self._center)) GLUT.glutMotionFunc(None) if state == GLUT.GLUT_DOWN: # sys.stderr.write("LMB down\n") keys = GLUT.glutGetModifiers() if keys & GLUT.GLUT_ACTIVE_SHIFT: self._mouseposx0 = x self._mouseposy0 = y self._origcenter = self._center self._upinscreen = self._up - self._forward * ( numpy.sum(self._up * self._forward) / math.sqrt( self._up[0]**2 + self._up[1]**2 + self._up[2]**2)) self._upinscreen /= math.sqrt(self._upinscreen[0]**2 + self._upinscreen[1]**2 + self._upinscreen[2]**2) self._rightinscreen = numpy.array([ self._forward[1] * self._upinscreen[2] - self._forward[2] * self._upinscreen[1], self._forward[2] * self._upinscreen[0] - self._forward[0] * self._upinscreen[2], self._forward[0] * self._upinscreen[1] - self._forward[1] * self._upinscreen[0] ]) self._rightinscreen /= math.sqrt( self._rightinscreen[0]**2 + self._rightinscreen[1]**2 + self._rightinscreen[2]**2) GLUT.glutMotionFunc(lambda x, y: self.lmb_moved(x, y)) if (state == GLUT.GLUT_UP) and (button == 3 or button == 4): # wheel up/down GLUT.glutSetWindow(self.window) if button == 3: self._range *= 0.9 else: self._range *= 1.1 self.update_cam_posrot_gl()
def gottaresize(self): GLUT.glutSetWindow(self.window) GLUT.glutReshapeWindow(self._width, self._height)
def glsetup(self, widget=None): GLUT.glutInit() GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DOUBLE | \ GLUT.GLUT_DEPTH | GLUT.GLUT_MULTISAMPLE | GLUT.GLUT_ALPHA | \ GLUT.GLUT_ACCUM) if self.core.get("view_shadow"): # TODO: implement shadowing (or remove the setting) pass # use vertex normals for smooth rendering GL.glShadeModel(GL.GL_SMOOTH) bg_col = self.core.get("color_background") GL.glClearColor(bg_col["red"], bg_col["green"], bg_col["blue"], 0.0) GL.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST) GL.glMatrixMode(GL.GL_MODELVIEW) # enable blending/transparency (alpha) for colors GL.glEnable(GL.GL_BLEND) # see http://wiki.delphigl.com/index.php/glBlendFunc GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glEnable(GL.GL_DEPTH_TEST) # "less" is OpenGL's default GL.glDepthFunc(GL.GL_LESS) # slightly improved performance: ignore all faces inside the objects GL.glCullFace(GL.GL_BACK) GL.glEnable(GL.GL_CULL_FACE) # enable antialiasing GL.glEnable(GL.GL_LINE_SMOOTH) #GL.glEnable(GL.GL_POLYGON_SMOOTH) GL.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST) GL.glHint(GL.GL_POLYGON_SMOOTH_HINT, GL.GL_NICEST) # TODO: move to toolpath drawing GL.glLineWidth(0.8) #GL.glEnable(GL.GL_MULTISAMPLE_ARB) GL.glEnable(GL.GL_POLYGON_OFFSET_FILL) GL.glPolygonOffset(1.0, 1.0) # ambient and diffuse material lighting is defined in OpenGLViewModel GL.glMaterial(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, (1.0, 1.0, 1.0, 1.0)) GL.glMaterial(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, (100.0)) if self.core.get("view_polygon"): GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL) else: GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GL.glViewport(0, 0, self.area.allocation.width, self.area.allocation.height) # lighting GL.glLightModeli(GL.GL_LIGHT_MODEL_LOCAL_VIEWER, GL.GL_TRUE) # Light #1 # setup the ambient light GL.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, (0.3, 0.3, 0.3, 1.0)) # setup the diffuse light GL.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, (0.8, 0.8, 0.8, 1.0)) # setup the specular light GL.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, (0.1, 0.1, 0.1, 1.0)) # enable Light #1 GL.glEnable(GL.GL_LIGHT0) # Light #2 # spotlight with small light cone (like a desk lamp) #GL.glLightfv(GL.GL_LIGHT1, GL.GL_SPOT_CUTOFF, 10.0) # ... directed at the object v = self.camera.view GL.glLightfv(GL.GL_LIGHT1, GL.GL_SPOT_DIRECTION, (v["center"][0], v["center"][1], v["center"][2])) GL.glLightfv(GL.GL_LIGHT1, GL.GL_AMBIENT, (0.3, 0.3, 0.3, 1.0)) # and dark outside of the light cone #GL.glLightfv(GL.GL_LIGHT1, GL.GL_SPOT_EXPONENT, 100.0) #GL.glLightf(GL.GL_LIGHT1, GL.GL_QUADRATIC_ATTENUATION, 0.5) # setup the diffuse light GL.glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, (0.9, 0.9, 0.9, 1.0)) # setup the specular light GL.glLightfv(GL.GL_LIGHT1, GL.GL_SPECULAR, (1.0, 1.0, 1.0, 1.0)) # enable Light #2 GL.glEnable(GL.GL_LIGHT1) if self.core.get("view_light"): GL.glEnable(GL.GL_LIGHTING) else: GL.glDisable(GL.GL_LIGHTING) GL.glEnable(GL.GL_NORMALIZE) GL.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE) GL.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR) #GL.glColorMaterial(GL.GL_FRONT_AND_BACK, GL.GL_EMISSION) GL.glEnable(GL.GL_COLOR_MATERIAL)
# ------------------------------------- def on_reshape(width, height): gl.glViewport(0, 0, width, height) # ------------------------------------- def on_keyboard(key, x, y): if key == '\033': sys.exit() if key == ' ': fbo.save(on_display, "gl-lines.png") # ----------------------------------------------------------------------------- if __name__ == '__main__': from glagg import PathCollection glut.glutInit(sys.argv) glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGB) glut.glutCreateWindow("OpenGL antialiased lines") glut.glutReshapeWindow(512, 512 + 32) glut.glutDisplayFunc(on_display) glut.glutReshapeFunc(on_reshape) glut.glutKeyboardFunc(on_keyboard) vertices = np.array([(+0.0, +0.5), (+0.0, -0.5)]) collection = PathCollection() for i in range(500): theta = i * (5.5 / 180.0 * np.pi) radius = 255 - i * 0.45 x = 256 + np.cos(theta) * radius y = 256 + np.sin(theta) * radius + 32 scale = 20 - 15 * i / float(500)
def thread_main(instance): # sys.stderr.write("Starting thread_main\n") GLUT.glutInit(sys.argv) GLUT.glutInitContextVersion(3, 3) GLUT.glutInitContextFlags(GLUT.GLUT_FORWARD_COMPATIBLE) GLUT.glutInitContextProfile(GLUT.GLUT_CORE_PROFILE) GLUT.glutSetOption(GLUT.GLUT_ACTION_ON_WINDOW_CLOSE, GLUT.GLUT_ACTION_GLUTMAINLOOP_RETURNS) GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DOUBLE | GLUT.GLUT_DEPTH) # sys.stderr.write("Making default GLUT window.\n") GLUT.glutInitWindowSize(instance.width, instance.height) GLUT.glutInitWindowPosition(0, 0) instance.window = GLUT.glutCreateWindow( bytes(instance._title, encoding='UTF-8')) # Urgh.... according to the docs, I'm MUST register a display function # for any GLUT window I create. But... I don't want to do this until # later (in self.__init__). So, register a null function now, # and hope that registering a new function is an OK thing to do. GLUT.glutDisplayFunc(lambda: None) # Not sure if I want this as a timer or an idle func GLUT.glutIdleFunc(lambda: GLUTContext.class_idle()) # GLUT.glutTimerFunc(10, lambda val : GLUTContext.class_idle(), 0) sys.stderr.write("Going into GLUT.GLUT main loop.\n") GLUTContext._class_init = True GLUT.glutMainLoop()
def display(): gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4) glut.glutSwapBuffers()
def gl_init(self): # sys.stderr.write("Starting GLUTContext.gl_init\n") if self is not GLUTContext._default_instance: # sys.stderr.write("Making a GLUT window.\n") GLUT.glutInitWindowSize(self._width, self._height) GLUT.glutInitWindowPosition(0, 0) self.window = GLUT.glutCreateWindow( bytes(self._title, encoding="UTF-8")) GLUT.glutSetWindow(self.window) GLUT.glutMouseFunc(lambda button, state, x, y: self. mouse_button_handler(button, state, x, y)) GLUT.glutReshapeFunc( lambda width, height: self.resize2d(width, height)) GLUT.glutDisplayFunc(lambda: self.draw()) GLUT.glutVisibilityFunc( lambda state: self.window_visibility_handler(state)) # Right now, the timer just prints FPS GLUT.glutTimerFunc(0, lambda val: self.timer(val), 0) GLUT.glutCloseFunc(lambda: self.cleanup()) for coltype in object_collection.GLObjectCollection.collection_classes: self.object_collections.append( object_collection.GLObjectCollection. collection_classes[coltype](self)) # self.object_collections.append(object_collection.SimpleObjectCollection(self)) # self.object_collections.append(object_collection.CurveCollection(self)) self.window_is_initialized = True GLUTContext._instances.append(self)
def activate(self): glut.glutSetWindow(self._native_window)
def main(): global particle_count global particle_position # GLUT init # -------------------------------------- glut.glutInit() glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA) glut.glutCreateWindow('Awesome fluid simulation') glut.glutReshapeWindow(screen_x, screen_y) glut.glutReshapeFunc(reshape) glut.glutDisplayFunc(display) glut.glutIdleFunc(display) glut.glutKeyboardFunc(keyboard) # Build data # -------------------------------------- data = np.zeros(4, [("position", np.float32, 2), ("color", np.float32, 4)]) data['position'] = (-1, +1), (+1, +1), (-1, -1), (+1, -1) data['color'] = (1, 1, 0, 1), (1, 0, 0, 1), (0, 0, 1, 1), (0, 1, 0, 1) # Build & activate program # -------------------------------------- # Request a program and shader slots from GPU global program program = gl.glCreateProgram() vertex = gl.glCreateShader(gl.GL_VERTEX_SHADER) fragment = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) vertex_code = read_shader('shader.vert') fragment_code = read_shader('shader.frag') # Set shaders source gl.glShaderSource(vertex, vertex_code) gl.glShaderSource(fragment, fragment_code) # Compile shaders gl.glCompileShader(vertex) if not gl.glGetShaderiv(vertex, gl.GL_COMPILE_STATUS): error = gl.glGetShaderInfoLog(vertex).decode() print(error) raise RuntimeError("Shader compilation error") gl.glCompileShader(fragment) gl.glCompileShader(fragment) if not gl.glGetShaderiv(fragment, gl.GL_COMPILE_STATUS): error = gl.glGetShaderInfoLog(fragment).decode() print(error) raise RuntimeError("Shader compilation error") # Attach shader objects to the program gl.glAttachShader(program, vertex) gl.glAttachShader(program, fragment) # Build program gl.glLinkProgram(program) if not gl.glGetProgramiv(program, gl.GL_LINK_STATUS): print(gl.glGetProgramInfoLog(program)) raise RuntimeError('Linking error') # Get rid of shaders (no more needed) gl.glDetachShader(program, vertex) gl.glDetachShader(program, fragment) # Make program the default program gl.glUseProgram(program) # Build buffer # -------------------------------------- # Request a buffer slot from GPU buffer = gl.glGenBuffers(1) # Make this buffer the default one gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffer) # Upload data gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, gl.GL_DYNAMIC_DRAW) # Bind attributes # -------------------------------------- stride = data.strides[0] offset = ctypes.c_void_p(0) loc = gl.glGetAttribLocation(program, "position") gl.glEnableVertexAttribArray(loc) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffer) gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, stride, offset) offset = ctypes.c_void_p(data.dtype["position"].itemsize) loc = gl.glGetAttribLocation(program, "color") gl.glEnableVertexAttribArray(loc) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, buffer) gl.glVertexAttribPointer(loc, 4, gl.GL_FLOAT, False, stride, offset) # Bind uniforms # -------------------------------------- loc = gl.glGetUniformLocation(program, "scale") gl.glUniform1f(loc, 1.0) # Enter mainloop # -------------------------------------- glut.glutMainLoop()
def get_position(self): glut.glutSetWindow(self._native_window) self._x = glut.glutGet(glut.GLUT_WINDOW_W) self._y = glut.glutGet(glut.GLUT_WINDOW_Y) return self._x, self._y
gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4) glut.glutSwapBuffers() def reshape(width, height): gl.glViewport(0, 0, width, height) def keyboard(key, x, y): if key == b'\x1b': sys.exit() # GLUT init # -------------------------------------- glut.glutInit() glut.glutInitDisplayMode(glut.GLUT_DOUBLE | glut.GLUT_RGBA) glut.glutCreateWindow('Hello world!') glut.glutReshapeWindow(512, 512) glut.glutReshapeFunc(reshape) glut.glutDisplayFunc(display) glut.glutKeyboardFunc(keyboard) # Build data # -------------------------------------- data = np.zeros(4, [("position", np.float32, 2), ("color", np.float32, 4)]) data['position'] = (-1, +1), (+1, +1), (-1, -1), (+1, -1) data['color'] = (1, 1, 0, 1), (1, 0, 0, 1), (0, 0, 1, 1), (0, 1, 0, 1) # Build & activate program # --------------------------------------
def show(self): self.activate() glut.glutShowWindow() self.dispatch_event('on_show')
def swap(self): glut.glutSwapBuffers()
def get_size(self): self.activate() self._width = glut.glutGet(glut.GLUT_WINDOW_WIDTH) self._height = glut.glutGet(glut.GLUT_WINDOW_HEIGHT) return self._width, self._height
def set_position(self, x, y): glut.glutPositionWindow(x, y)
def _reshape(self, width, height): self._width = glut.glutGet(glut.GLUT_WINDOW_WIDTH) self._height = glut.glutGet(glut.GLUT_WINDOW_HEIGHT) self.dispatch_event('on_resize', self._width, self._height)
def set_size(self, width, height): self.activate() glut.glutReshapeWindow(width, height)
def main(self, neuronObject, displaysize=(800, 600), radius=5, poly=True, fast=False, multisample=True, graph=True): self.poly = poly self.displaysize = displaysize self.graph = graph title = 'btmorph OpenGL Viewer' GLUT.glutInit(sys.argv) if multisample: GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DOUBLE) else: GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DOUBLE | GLUT.GLUT_MULTISAMPLE) GLUT.glutInitWindowSize(self.displaysize[0], self.displaysize[1]) GLUT.glutInitWindowPosition(50, 50) GLUT.glutCreateWindow(title) GLUT.glutDisplayFunc(self.display) GLUT.glutReshapeFunc(self.reshape) GLUT.glutMouseFunc(self.mouse) GLUT.glutMotionFunc(self.mouseMove) GLUT.glutMouseWheelFunc(self.mouseWheel) GLUT.glutKeyboardFunc(self.keyDown) GLUT.glutKeyboardUpFunc(self.keyUp) mb = modelbuilder() self.root, self.vertices_gl, self.colors_gl, self.Neuron = \ mb.build(neuronObject, self.poly, 100, fast) if graph: self.gb = graphbuilder() self.Graph, mid = \ self.gb.build(neuronObject, scalefactor=100) self.initGL(multisample) self.camera.rad = radius self.camera.focus = mid while self.running: GLUT.glutMainLoopEvent() GLUT.glutDestroyWindow(GLUT.glutGetWindow())
def RenderText(self, text, x, y): GL.glColor3f(1.0, 0.0, 0.0) GL.glWindowPos2f(x, y) GLUT.glutBitmapString(GLUT.GLUT_BITMAP_HELVETICA_10, text)
def gottasettitle(self): GLUT.glutSetWindow(self.window) GLUT.glutSetWindowTitle(self._title)
def hide(self): self.activate() glut.glutHideWindow() self.dispatch_event('on_hide')