def main(): # Initialize the library if not glfw.init(): return glfw.set_error_callback(error_callback) # Create a windowed mode window and its OpenGL context window = glfw.create_window(640, 480, "Hello World", None, None) if not window: glfw.terminate() return # Make the window's context current glfw.make_context_current(window) program = common2d.init_shader_program() # Loop until the user closes the window while not glfw.window_should_close(window): # Render here common2d.display(program) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(): window = init_window() if not window: return shader = get_shader() vao = get_vertex() tex = bind_texture("wall.png") tex2 = bind_texture("wall2.jpg") gl.glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT) gl.glEnable(gl.GL_DEPTH_TEST) # Loop until the user closes the window while not glfw.window_should_close(window): # Poll for and process events glfw.poll_events() # Render here, e.g. using pyOpenGL render(shader, vao, tex, tex2) # Swap front and back buffers glfw.swap_buffers(window) time.sleep(0.05) gl.glDeleteVertexArrays(1, vao) glfw.terminate()
def run(self): # Initialize the library if not glfw.init(): return # Create a windowed mode window and its OpenGL context self.window = glfw.create_window(640, 480, "Hello World", None, None) if not self.window: glfw.terminate() return renderer = RiftGLRendererCompatibility() # Paint a triangle in the center of the screen renderer.append(TriangleDrawerCompatibility()) # Make the window's context current glfw.make_context_current(self.window) # Initialize Oculus Rift renderer.init_gl() renderer.rift.recenter_pose() glfw.set_key_callback(self.window, self.key_callback) # Loop until the user closes the window while not glfw.window_should_close(self.window): # Render here, e.g. using pyOpenGL renderer.display_rift_gl() # Swap front and back buffers glfw.swap_buffers(self.window) # Poll for and process events glfw.poll_events() glfw.terminate()
def _init_framebuffer_object(self): """ returns a Framebuffer Object to support offscreen rendering. http://learnopengl.com/#!Advanced-OpenGL/Framebuffers """ fbo = gl.glGenFramebuffers(1) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, fbo) rbo = gl.glGenRenderbuffers(1) gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, rbo) gl.glRenderbufferStorage( gl.GL_RENDERBUFFER, gl.GL_RGBA, self.init_width, self.init_height ) gl.glFramebufferRenderbuffer( gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_RENDERBUFFER, rbo) gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, 0) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) fbo_status = gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER) if fbo_status != gl.GL_FRAMEBUFFER_COMPLETE: gl.glDeleteFramebuffers([fbo]) glfw.terminate() raise Exception('Framebuffer failed status check: %s' % fbo_status) self._fbo = fbo self._rbo = rbo
def dispose_gl(self): if self.window is not None: glfw.make_context_current(self.window) if self.renderer is not None: self.renderer.dispose_gl() glfw.terminate() self._is_initialized = False
def run(self): while not glfw.window_should_close(self.window): if self.redisplay: self.redisplay = False self.drawScene() glfw.wait_events() glfw.terminate()
def main(): # Initialize the library if not glfw.init(): return # Create a windowed mode window and its OpenGL context window = glfw.create_window(window_width, window_height, "Hello World", None, None) if not window: glfw.terminate() return # Make the window's context current glfw.make_context_current(window) glfw.set_window_size_callback(window, on_window_size) initGL(window) # Loop until the user closes the window while not glfw.window_should_close(window): # Render here, e.g. using pyOpenGL display() # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(): glfw.setErrorCallback(error_callback) glfw.init() glfw.windowHint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.windowHint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.windowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # glfw.windowHint(glfw.RESIZABLE, gl.FALSE) glfw.windowHint(glfw.OPENGL_FORWARD_COMPAT, 1) window = glfw.createWindow(800, 600, "LearnOpenGL") if window is None: print('could not open window.') glfw.terminate() sys.exit() window.makeContextCurrent() window.setKeyCallback(key_callback) gl.init() gl.clearColor(0.2, 0.3, 0.3, 1.0) while not window.shouldClose(): framebuffer_width, framebuffer_height = window.getFramebufferSize() gl.viewport(0, 0, framebuffer_width, framebuffer_height) gl.clear(gl.COLOR_BUFFER_BIT) glfw.pollEvents() window.swapBuffers()
def opengl_init(): global window # Initialize the library if not glfw.init(): print("Failed to initialize GLFW\n",file=sys.stderr) return False # Open Window and create its OpenGL context window = glfw.create_window(1024, 768, "VAO Test", None, None) #(in the accompanying source code this variable will be global) glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) if not window: print("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n",file=sys.stderr) glfw.terminate() return False # Initialize GLEW glfw.make_context_current(window) glewExperimental = True # !!NOTE: The most recent GLEW package for python is 8 years old, ARB functionality # is available in Pyopengl natively. if glewInit() != GLEW_OK: print("Failed to initialize GLEW\n",file=sys.stderr); return False return True
def __init__(self, objects=[], options={}): super().__init__() self.parseOptions(options) self.cameraCursor = [0.0, 0.0] self.cameraMove = False self.cameraRotate = False self.redisplay = True self.titleText = 'OpenGL 4.1 render' glfw.init() try: self.window = glfw.create_window(*self.viewport, self.titleText, None, None) glfw.make_context_current(self.window) except: print('Window initialization failed') glfw.terminate() exit() self.initGraphics() self.updateMatrix(self.viewport) glfw.set_key_callback(self.window, self.handleKeyEvent) glfw.set_mouse_button_callback(self.window, self.handleMouseButtonEvent) glfw.set_cursor_pos_callback(self.window, self.handleCursorMoveEvent) glfw.set_scroll_callback(self.window, self.handleScrollEvent) glfw.set_window_refresh_callback(self.window, self.handleResizeEvent) self.objects = set() self.appendRenderObjects(self.makeRenderObjects(objects))
def main(): if not glfw.init(): return window = glfw.create_window(640, 480, "ラララ", None, None) if not window: glfw.terminate() return #init glfw.make_context_current(window) gluOrtho2D(0.0, 640, 0.0, 480) #where is this in glfw? # loop while not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT) randomWidth() drawLine(100.0, 400.0, 200.0, 400.0) drawLine(440.0, 400.0, 540.0, 400.0) drawLine(320.0, 350.0, 320.0, 330.0) drawLine(100.0, 400.0, 200.0, 400.0) drawLine(300.0, 200.0, 340.0, 200.0) glfw.swap_buffers(window) glfw.poll_events() glfw.swap_interval(2) glfw.terminate()
def main(): global R, T if not glfw.init(): return window = glfw.create_window(480, 480, "2015004584", None, None) if not window: glfw.terminate() return glfw.set_key_callback(window, key_callback) glfw.make_context_current(window) glfw.swap_interval(0) while not glfw.window_should_close(window): glfw.poll_events() clear() axis() glMultMatrixf(R.T) glMultMatrixf(T.T) render() glfw.swap_buffers(window) glfw.terminate()
def main(): global window initLogger() Utils.init() # Create a windowed mode window and its OpenGL context window = glfw.create_window(640, 480, "Hello World", None, None) if not window: glfw.terminate() print("fail Window") return # Make the window's context current glfw.make_context_current(window) vertexPos, vertexColor, triangle = tmf.load("testData.tmf") #define input inputHandler.addEvent(KillProgram, "Esc") inputHandler.addEvent(Culling, "c") print vertexPos VAO, VertexSize, indexs = Utils.createVAO(vertexPos, vertexColor, triangle, 4) shaderProgram = ShaderM.compileShaderFromFile("shaders/basic.vert", "shaders/basic.frag") objectToRender = { "Indexs" : indexs, "VAO" : VAO, "VertexCount" : VertexSize, "ShaderProgram" : shaderProgram} mainLoop(objectToRender,window) glfw.terminate()
def main(): global angles, angley, anglez, scale, carcass, sphere if not glfw.init(): return window = glfw.create_window(640, 640, "Lab2", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) glfw.set_framebuffer_size_callback(window, resize_callback) glfw.set_window_pos_callback(window, drag_callback) l_cube = Cube(0, 0, 0, 1) # r_cube = Cube(0, 0, 0, 1) sphere.recount(parts) while not glfw.window_should_close(window): glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) set_projection() glLoadIdentity() sphere.draw(scale, angles, [0.3, 0.0, 0.4], carcass) # r_cube.draw(scale, angles, [0.3, 0.2, 0.4], carcass) l_cube.draw(0.5, [0, 0, 0], [-0.5, 0.0, -0.25], False) glfw.swap_buffers(window) glfw.poll_events() glfw.destroy_window(window) glfw.terminate()
def __init__(self): self.dir = Dir.empty self.run = True self.snake = Player() if not glfw.init(): return self.window = glfw.create_window(400, 300, "Hello, World!", None, None) if not self.window: glfw.terminate() return glfw.make_context_current(self.window) glfw.set_key_callback(self.window, self.key_callback) while self.run and not glfw.window_should_close(self.window): # Update player's position self.snake.play(self.dir) sleep(0.075) self.draw() glfw.swap_buffers(self.window) glfw.poll_events() if self.snake.alive is False: sleep(1.075) self.run = False glfw.terminate()
def run(self): # initializer timer glfw.set_time(0.0) t = 0.0 while not glfw.window_should_close(self.win) and not self.exitNow: # update every x seconds currT = glfw.get_time() if currT - t > 0.1: # update time t = currT # clear glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # build projection matrix pMatrix = glutils.perspective(45.0, self.aspect, 0.1, 100.0) mvMatrix = glutils.lookAt([0.0, 0.0, -2.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]) # render self.scene.render(pMatrix, mvMatrix) # step self.scene.step() glfw.swap_buffers(self.win) # Poll for and process events glfw.poll_events() # end glfw.terminate()
def init(self): if not glfw.init(): raise Exception('glfw failed to initialize') glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) self.window = glfw.create_window( self.initial_width, self.initial_height, self.title, None, None ) if not self.window: glfw.terminate() raise Exception('glfw failed to create a window') glfw.make_context_current(self.window) glfw.set_framebuffer_size_callback(self.window, self._reshape_callback) glfw.set_key_callback(self.window, self._key_callback) glfw.set_mouse_button_callback(self.window, self._mouse_button_callback) GL.glEnable(GL.GL_CULL_FACE) GL.glCullFace(GL.GL_BACK) GL.glFrontFace(GL.GL_CW) GL.glEnable(GL.GL_DEPTH_TEST) GL.glDepthMask(GL.GL_TRUE) GL.glDepthFunc(GL.GL_LEQUAL) GL.glDepthRange(0.0, 1.0) GL.glEnable(depth_clamp.GL_DEPTH_CLAMP)
def main(): global vertices, window_height, window_width, to_redraw if not glfw.init(): return window = glfw.create_window(400, 400, "Lab4", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) glfw.set_framebuffer_size_callback(window, resize_callback) glfw.set_mouse_button_callback(window, mouse_button_callback) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LESS) glClearColor(0, 0, 0, 0) while not glfw.window_should_close(window): # print(vertices) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) draw() glfw.swap_buffers(window) glfw.poll_events() glfw.destroy_window(window) glfw.terminate()
def main(): init() window = create_window(500, 500, "Hi", None, None) make_context_current(window) initial_setup() colors = { "front": (1, 0, 0), "back": (0, 1, 0), "left": (1, 1, 0), "right": (1, 0, 1), "up": (0, 0, 1), "down": (0, 1, 1), } glClearColor(1, 1, 1, 1) glEnable(GL_DEPTH_TEST) set_lightning() while not window_should_close(window): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glRotate(1, 0, 1, 0) draw_cube(0, 0, 0, 5, colors) swap_buffers(window) poll_events() terminate()
def opengl_init(): global window # Initialize the library if not glfw.init(): print("Failed to initialize GLFW\n",file=sys.stderr) return False glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # Open Window and create its OpenGL context window = glfw.create_window(1024, 768, "Tutorial 04", None, None) #(in the accompanying source code this variable will be global) if not window: print("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n",file=sys.stderr) glfw.terminate() return False # Initialize GLEW glfw.make_context_current(window) glewExperimental = True # GLEW is a framework for testing extension availability. Please see tutorial notes for # more information including why can remove this code. if glewInit() != GLEW_OK: print("Failed to initialize GLEW\n",file=sys.stderr); return False return True
def draw_a_triangle(): if not glfw.init(): return -1; # Create a windowed mode window and its OpenGL context glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(1024, 768, "Triangle", None, None); if window == None: glfw.terminate() return -1 # Make the window's context current glfw.make_context_current(window) # glfw.Experimental = True glClearColor(0.0, 0.1, 0.2, 1.0) flatten = lambda l: [u for t in l for u in t] vertices = [(-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), (0.0, 1.0, 0.0)] indices = range(3) vao_handle = glGenVertexArrays(1) glBindVertexArray(vao_handle) program_handle = tools.load_program("../shader/simple.v.glsl", "../shader/simple.f.glsl") f_vertices = flatten(vertices) c_vertices = (c_float*len(f_vertices))(*f_vertices) v_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, v_buffer) glBufferData(GL_ARRAY_BUFFER, c_vertices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, v_buffer) glVertexAttribPointer(0, #glGetAttribLocation(program_handle, "vertexPosition_modelspace"), 3, GL_FLOAT, False, 0, None) # Loop until the user closes the window while not glfw.window_should_close(window): # Render here glClear(GL_COLOR_BUFFER_BIT) glUseProgram(program_handle) glDrawArrays(GL_TRIANGLES, 0, 3) glDisableVertexAttribArray(vao_handle) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate(); pass
def show(molecule, width=500, height=500, show_bonds=True, bonds_method='radii', bonds_param=None, camera=None, title='mogli'): """ Interactively show the given molecule with OpenGL. By default, bonds are drawn, if this is undesired the show_bonds parameter can be set to False. For information on the bond calculation, see Molecule.calculate_bonds. If you pass a tuple of camera position, center of view and an up vector to the camera parameter, the camera will be set accordingly. Otherwise the molecule will be viewed in the direction of the z axis, with the y axis pointing upward. """ global _camera molecule.positions -= np.mean(molecule.positions, axis=0) max_atom_distance = np.max(la.norm(molecule.positions, axis=1)) if show_bonds: molecule.calculate_bonds(bonds_method, bonds_param) # If GR3 was initialized earlier, it would use a different context, so # it will be terminated first. gr3.terminate() # Initialize GLFW and create an OpenGL context glfw.init() glfw.window_hint(glfw.SAMPLES, 16) window = glfw.create_window(width, height, title, None, None) glfw.make_context_current(window) glEnable(GL_MULTISAMPLE) # Set up the camera (it will be changed during mouse rotation) if camera is None: camera_distance = -max_atom_distance*2.5 camera = ((0, 0, camera_distance), (0, 0, 0), (0, 1, 0)) camera = np.array(camera) _camera = camera # Create the GR3 scene gr3.setbackgroundcolor(255, 255, 255, 0) _create_gr3_scene(molecule, show_bonds) # Configure GLFW glfw.set_cursor_pos_callback(window, _mouse_move_callback) glfw.set_mouse_button_callback(window, _mouse_click_callback) glfw.swap_interval(1) # Start the GLFW main loop while not glfw.window_should_close(window): glfw.poll_events() width, height = glfw.get_window_size(window) glViewport(0, 0, width, height) _set_gr3_camera() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) gr3.drawimage(0, width, 0, height, width, height, gr3.GR3_Drawable.GR3_DRAWABLE_OPENGL) glfw.swap_buffers(window) glfw.terminate() gr3.terminate()
def main(): # Initialize the library if not glfw.init(): return # Create a windowed mode window and its OpenGL context window = glfw.create_window(640, 480, "Hello World", None, None) if not window: glfw.terminate() return # Make the window's context current glfw.make_context_current(window) # Loop until the user closes the window while not glfw.window_should_close(window): # Render here, e.g. using pyOpenGL # Swap front and back buffers glfw.swap_buffers(window) gl_begin( GL_TRIANGLES ) glColor3f( 1.0, 0.0, 0.0 ) glVertex3f( 0.0, 1.0, 0.0 ) glColor3f( 0.0, 1.0, 0.0 ) glVertex3f( -1.0, -1.0, 1.0 ) glColor3f( 0.0, 0.0, 1.0 ) glVertex3f( 1.0, -1.0, 1.0) glColor3f( 1.0, 0.0, 0.0 ) glVertex3f( 0.0, 1.0, 0.0) glColor3f( 0.0, 1.0, 0.0 ) glVertex3f( -1.0, -1.0, 1.0) glColor3f( 0.0, 0.0, 1.0 ) glVertex3f( 0.0, -1.0, -1.0) #glColor3f( 1.0f, 0.0f, 0.0f ) #glVertex3f( 0.0f, 1.0f, 0.0f) #glColor3f( 0.0f, 1.0f, 0.0f ) #glVertex3f( 0.0f, -1.0f, -1.0f) #glColor3f( 0.0f, 0.0f, 1.0f ) #glVertex3f( 1.0f, -1.0f, 1.0f) #glColor3f( 1.0f, 0.0f, 0.0f ) #glVertex3f( -1.0f, -1.0f, 1.0f) #glColor3f( 0.0f, 1.0f, 0.0f ) #glVertex3f( 0.0f, -1.0f, -1.0f) #glColor3f( 0.0f, 0.0f, 1.0f ) #glVertex3f( 1.0f, -1.0f, 1.0f) glEnd() # Poll for and process events glfw.poll_events() glfw.terminate()
def finish(self): glfw.terminate() if gl.glIsFramebuffer(self._fbo): gl.glDeleteFramebuffers(int(self._fbo)) if gl.glIsRenderbuffer(self._rbo): gl.glDeleteRenderbuffers(1, int(self._rbo)) mjlib.mjr_freeContext(byref(self.con)) mjlib.mjv_freeObjects(byref(self.objects)) self.running = False
def run(self): # This is the main game loop self.init() while not glfw.window_should_close(self.window): self.poll() self.tick() self.render() assert(gl.glGetError()==0) # Remove this in prod glfw.terminate() os._exit(0)
def __init__(self, **kwargs): super().__init__(**kwargs) if not glfw.init(): raise ValueError("Failed to initialize glfw") # Configure the OpenGL context glfw.window_hint(glfw.CONTEXT_CREATION_API, glfw.NATIVE_CONTEXT_API) glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, self.gl_version[0]) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, self.gl_version[1]) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.RESIZABLE, self.resizable) glfw.window_hint(glfw.DOUBLEBUFFER, True) glfw.window_hint(glfw.DEPTH_BITS, 24) glfw.window_hint(glfw.SAMPLES, self.samples) monitor = None if self.fullscreen: # Use the primary monitors current resolution monitor = glfw.get_primary_monitor() mode = glfw.get_video_mode(monitor) self.width, self.height = mode.size.width, mode.size.height # Make sure video mode switching will not happen by # matching the desktops current video mode glfw.window_hint(glfw.RED_BITS, mode.bits.red) glfw.window_hint(glfw.GREEN_BITS, mode.bits.green) glfw.window_hint(glfw.BLUE_BITS, mode.bits.blue) glfw.window_hint(glfw.REFRESH_RATE, mode.refresh_rate) self.window = glfw.create_window(self.width, self.height, self.title, monitor, None) if not self.window: glfw.terminate() raise ValueError("Failed to create window") if not self.cursor: glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED) self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(self.window) glfw.make_context_current(self.window) if self.vsync: glfw.swap_interval(1) glfw.set_key_callback(self.window, self.key_event_callback) glfw.set_cursor_pos_callback(self.window, self.mouse_event_callback) glfw.set_mouse_button_callback(self.window, self.mouse_button_callback) glfw.set_window_size_callback(self.window, self.window_resize_callback) self.ctx = moderngl.create_context(require=self.gl_version_code) self.print_context_info() self.set_default_viewport()
def __init__(self, name, width, height, fullscreen=False): if not glfw.init(): raise GlfwError("Could not initialize GLFW") monitor = glfw.get_primary_monitor() if fullscreen else None self.win = glfw.create_window(width, height, name, monitor, None) if not self.win: glfw.terminate() raise GlfwError("Could not create GLFW window") glfw.make_context_current(self.win) glfw.set_key_callback(self.win, self.key_cb) self.key_callbacks = []
def main(): # Initialize the library if not glfw.init(): return # Set some window hints glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3); glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3); glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE); glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE); glfw.window_hint(glfw.SAMPLES, 16) # This works as expected glfw.window_hint(glfw.RESIZABLE, 0) # These should work, but don't :( # could control focus w/ http://crunchbang.org/forums/viewtopic.php?id=22226 # ended up using xdotool, see run.py glfw.window_hint(glfw.FOCUSED, 0) # I've set 'shader-*' to raise in openbox-rc as workaround # Looking at the code and confirming version 3.1.2 and it should work glfw.window_hint(glfw.FLOATING, 1) # Create a windowed mode window and its OpenGL context window = glfw.create_window(300, 300, "shader-test", None, None) if not window: glfw.terminate() return # Move Window glfw.set_window_pos(window, 1600, 50) # Make the window's context current glfw.make_context_current(window) # vsync glfw.swap_interval(1) # Setup GL shaders, data, etc. initialize() # Loop until the user closes the window while not glfw.window_should_close(window): # Render here, e.g. using pyOpenGL render() # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def start(self): if not glfw.init(): return glfw.window_hint(glfw.SAMPLES, 4) # try stereo if refresh rate is at least 100Hz window = None stereo_available = False _, _, refresh_rate = glfw.get_video_mode(glfw.get_primary_monitor()) if refresh_rate >= 100: glfw.window_hint(glfw.STEREO, 1) window = glfw.create_window(500, 500, "Simulate", None, None) if window: stereo_available = True # no stereo: try mono if not window: glfw.window_hint(glfw.STEREO, 0) window = glfw.create_window(500, 500, "Simulate", None, None) if not window: glfw.terminate() return self.running = True # Make the window's context current glfw.make_context_current(window) width, height = glfw.get_framebuffer_size(window) width1, height = glfw.get_window_size(window) self._scale = width * 1.0 / width1 self.window = window mjlib.mjv_makeObjects(byref(self.objects), 1000) mjlib.mjv_defaultCamera(byref(self.cam)) mjlib.mjv_defaultOption(byref(self.vopt)) mjlib.mjr_defaultOption(byref(self.ropt)) mjlib.mjr_defaultContext(byref(self.con)) if self.model: mjlib.mjr_makeContext(self.model.ptr, byref(self.con), 150) self.autoscale() else: mjlib.mjr_makeContext(None, byref(self.con), 150) glfw.set_cursor_pos_callback(window, self.handle_mouse_move) glfw.set_mouse_button_callback(window, self.handle_mouse_button) glfw.set_scroll_callback(window, self.handle_scroll)
def main(): if not glfw.init(): return window = glfw.create_window(640, 480, "Lab2", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) while not glfw.window_should_close(window) and not ex: draw() glfw.swap_buffers(window) glfw.poll_events() glfw.terminate()
def main(pipeline_path, connection_addresses, shared_dic, log_path, debug_mode): log_level = log.DEBUG if debug_mode else log.INFO setup_logging(log_path, log_level) log.info('DEBUG MODE: {}'.format(debug_mode)) # Trying to change process prioriy in Linux seems to hang Malt for some users if sys.platform == 'win32': import psutil psutil.Process().nice(psutil.REALTIME_PRIORITY_CLASS) log.info('CONNECTIONS:') connections = {} for name, address in connection_addresses.items(): log.info('Name: {} Adress: {}'.format(name, address)) connections[name] = connection.Client(address) glfw.ERROR_REPORTING = True glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) window = glfw.create_window(256, 256, 'Malt', None, None) glfw.make_context_current(window) # Don't hide for better OS/Drivers schedule priority #glfw.hide_window(window) # Minimize instead: glfw.iconify_window(window) glfw.swap_interval(0) log_system_info() log.info('INIT PIPELINE: ' + pipeline_path) pipeline_dir, pipeline_name = os.path.split(pipeline_path) if pipeline_dir not in sys.path: sys.path.append(pipeline_dir) module_name = pipeline_name.split('.')[0] module = __import__(module_name) pipeline_class = module.PIPELINE pipeline_class.SHADER_INCLUDE_PATHS.append(pipeline_dir) pipeline = pipeline_class() params = pipeline.get_parameters() connections['PARAMS'].send(params) viewports = {} last_exception = '' repeated_exception = 0 while glfw.window_should_close(window) == False: try: profiler = cProfile.Profile() profiling_data = io.StringIO() global PROFILE if PROFILE: profiler.enable() start_time = time.perf_counter() glfw.poll_events() while connections['MATERIAL'].poll(): msg = connections['MATERIAL'].recv() log.debug('COMPILE MATERIAL : {}'.format(msg)) path = msg['path'] search_paths = msg['search_paths'] material = Bridge.Material.Material(path, pipeline, search_paths) connections['MATERIAL'].send(material) while connections['MESH'].poll(): msg = connections['MESH'].recv() msg_log = copy.copy(msg) msg_log['data'] = None log.debug('LOAD MESH : {}'.format(msg_log)) load_mesh(msg) while connections['TEXTURE'].poll(): msg = connections['TEXTURE'].recv() log.debug('LOAD TEXTURE : {}'.format(msg)) name = msg['name'] resolution = msg['resolution'] channels = msg['channels'] buffer_name = msg['buffer_name'] sRGB = msg['sRGB'] w,h = resolution size = w*h*channels buffer = ipc.SharedMemoryRef(buffer_name, size*ctypes.sizeof(ctypes.c_float)) float_buffer = (ctypes.c_float*size).from_address(buffer.c.data) load_texture(name, resolution, channels, float_buffer, sRGB) connections['TEXTURE'].send('COMPLETE') while connections['GRADIENT'].poll(): msg = connections['GRADIENT'].recv() msg_log = copy.copy(msg) msg_log['pixels'] = None log.debug('LOAD GRADIENT : {}'.format(msg_log)) name = msg['name'] pixels = msg['pixels'] nearest = msg['nearest'] load_gradient(name, pixels, nearest) #TODO: Bad workaround to make sure the scene assets are loaded if connections['RENDER'].poll(): needs_loading = False for key in ['MATERIAL','MESH','TEXTURE','GRADIENT']: if connections[key].poll(): needs_loading = True if needs_loading: continue setup_viewports = {} while connections['RENDER'].poll(): msg = connections['RENDER'].recv() log.debug('SETUP RENDER : {}'.format(msg)) setup_viewports[msg['viewport_id']] = msg for msg in setup_viewports.values(): viewport_id = msg['viewport_id'] resolution = msg['resolution'] scene = msg['scene'] scene_update = msg['scene_update'] buffer_names = msg['buffer_names'] w,h = resolution buffers = {} for key, buffer_name in buffer_names.items(): if buffer_name: buffers[key] = ipc.SharedMemoryRef(buffer_name, w*h*4*4) if viewport_id not in viewports: viewports[viewport_id] = Viewport(pipeline_class(), viewport_id == 0) viewports[viewport_id].setup(buffers, resolution, scene, scene_update) shared_dic[(viewport_id, 'FINISHED')] = False active_viewports = {} render_finished = True for v_id, v in viewports.items(): if v.needs_more_samples: active_viewports[v_id] = v has_finished = v.render() if has_finished == False: render_finished = False shared_dic[(v_id, 'READ_RESOLUTION')] = v.read_resolution if has_finished and shared_dic[(v_id, 'FINISHED')] == False: shared_dic[(v_id, 'FINISHED')] = True if render_finished: glfw.swap_interval(1) else: glfw.swap_interval(0) glfw.swap_buffers(window) if len(active_viewports) > 0: stats = '' for v_id, v in active_viewports.items(): stats += "Viewport ({}):\n{}\n\n".format(v_id, v.get_print_stats()) shared_dic['STATS'] = stats log.debug('STATS: {} '.format(stats)) if PROFILE: profiler.disable() stats = pstats.Stats(profiler, stream=profiling_data) stats.strip_dirs() stats.sort_stats(pstats.SortKey.CUMULATIVE) stats.print_stats() if active_viewports: log.debug(profiling_data.getvalue()) except (ConnectionResetError, EOFError): #Connection Lost break except: import traceback exception = traceback.format_exc() if exception != last_exception: log.error(exception) repeated_exception = 0 last_exception = exception else: if repeated_exception in (1,10,100,1000,10000,100000): log.error('(Repeated {}+ times)'.format(repeated_exception)) repeated_exception += 1 glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return 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, True) window = glfw.create_window(800, 600, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) # positions colors cube = [ -0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, 1.0, 1.0, 1.0, -0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 0.0, 1.0, -0.5, 0.5, -0.5, 1.0, 1.0, 1.0 ] cube = numpy.array(cube, dtype=numpy.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 4, 5, 1, 1, 0, 4, 6, 7, 3, 3, 2, 6, 5, 6, 2, 2, 1, 5, 7, 4, 0, 0, 3, 7 ] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in vec3 position; in vec3 color; uniform mat4 transform; out vec3 newColor; void main() { gl_Position = transform * vec4(position, 1.0f); newColor = color; } """ fragment_shader = """ #version 330 in vec3 newColor; out vec4 outColor; void main() { outColor = vec4(newColor, 1.0f); } """ VAO = glGenVertexArrays(1) glBindVertexArray(VAO) shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, 192, cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, 144, indices, GL_STATIC_DRAW) position = glGetAttribLocation(shader, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) color = glGetAttribLocation(shader, "color") glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glEnableVertexAttribArray(color) glBindVertexArray(0) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) glBindBuffer(GL_ARRAY_BUFFER, 0) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time()) rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time()) glUseProgram(shader) transformLoc = glGetUniformLocation(shader, "transform") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y) glBindVertexArray(VAO) glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, None) glBindVertexArray(0) glUseProgram(0) glfw.swap_buffers(window) glDeleteProgram(shader) glDeleteVertexArrays(1, [VAO]) glDeleteBuffers(2, [VBO, EBO]) glfw.terminate()
def eye( timebase, is_alive_flag, ipc_pub_url, ipc_sub_url, ipc_push_url, user_dir, version, eye_id, overwrite_cap_settings=None, hide_ui=False, debug=False, pub_socket_hwm=None, parent_application="capture", ): """reads eye video and detects the pupil. Creates a window, gl context. Grabs images from a capture. Streams Pupil coordinates. Reacts to notifications: ``eye_process.should_stop``: Stops the eye process ``recording.started``: Starts recording eye video ``recording.stopped``: Stops recording eye video ``frame_publishing.started``: Starts frame publishing ``frame_publishing.stopped``: Stops frame publishing ``start_eye_plugin``: Start plugins in eye process Emits notifications: ``eye_process.started``: Eye process started ``eye_process.stopped``: Eye process stopped Emits data: ``pupil.<eye id>``: Pupil data for eye with id ``<eye id>`` ``frame.eye.<eye id>``: Eye frames with id ``<eye id>`` """ # We deferr the imports becasue of multiprocessing. # Otherwise the world process each process also loads the other imports. import zmq import zmq_tools zmq_ctx = zmq.Context() ipc_socket = zmq_tools.Msg_Dispatcher(zmq_ctx, ipc_push_url) pupil_socket = zmq_tools.Msg_Streamer(zmq_ctx, ipc_pub_url, pub_socket_hwm) notify_sub = zmq_tools.Msg_Receiver(zmq_ctx, ipc_sub_url, topics=("notify", )) # logging setup import logging logging.getLogger("OpenGL").setLevel(logging.ERROR) logger = logging.getLogger() logger.handlers = [] logger.setLevel(logging.NOTSET) logger.addHandler(zmq_tools.ZMQ_handler(zmq_ctx, ipc_push_url)) # create logger for the context of this function logger = logging.getLogger(__name__) if is_alive_flag.value: # indicates eye process that this is a duplicated startup logger.warning("Aborting redundant eye process startup") return with Is_Alive_Manager(is_alive_flag, ipc_socket, eye_id, logger): # general imports import traceback import numpy as np import cv2 from OpenGL.GL import GL_COLOR_BUFFER_BIT # display import glfw from gl_utils import GLFWErrorReporting GLFWErrorReporting.set_default() from pyglui import ui, graph, cygl from pyglui.cygl.utils import draw_points, RGBA, draw_polyline from pyglui.cygl.utils import Named_Texture import gl_utils from gl_utils import basic_gl_setup, adjust_gl_view, clear_gl_screen from gl_utils import make_coord_system_pixel_based from gl_utils import make_coord_system_norm_based from gl_utils import is_window_visible, glViewport # monitoring import psutil # Plug-ins from plugin import Plugin_List # helpers/utils from uvc import get_time_monotonic from file_methods import Persistent_Dict from version_utils import parse_version from methods import normalize, denormalize, timer from av_writer import JPEG_Writer, MPEG_Writer, NonMonotonicTimestampError from ndsi import H264Writer from video_capture import source_classes, manager_classes from roi import Roi from background_helper import IPC_Logging_Task_Proxy from pupil_detector_plugins import available_detector_plugins, EVENT_KEY IPC_Logging_Task_Proxy.push_url = ipc_push_url def interrupt_handler(sig, frame): import traceback trace = traceback.format_stack(f=frame) logger.debug(f"Caught signal {sig} in:\n" + "".join(trace)) # NOTE: Interrupt is handled in world/service/player which are responsible for # shutting down the eye process properly signal.signal(signal.SIGINT, interrupt_handler) # UI Platform tweaks if platform.system() == "Linux": scroll_factor = 10.0 window_position_default = (600, 300 * eye_id + 30) elif platform.system() == "Windows": scroll_factor = 10.0 window_position_default = (600, 90 + 300 * eye_id) else: scroll_factor = 1.0 window_position_default = (600, 300 * eye_id) icon_bar_width = 50 window_size = None content_scale = 1.0 # g_pool holds variables for this process g_pool = SimpleNamespace() # make some constants avaiable g_pool.debug = debug g_pool.user_dir = user_dir g_pool.version = version g_pool.app = parent_application g_pool.eye_id = eye_id g_pool.process = f"eye{eye_id}" g_pool.timebase = timebase g_pool.camera_render_size = None g_pool.zmq_ctx = zmq_ctx g_pool.ipc_pub = ipc_socket g_pool.ipc_pub_url = ipc_pub_url g_pool.ipc_sub_url = ipc_sub_url g_pool.ipc_push_url = ipc_push_url def get_timestamp(): return get_time_monotonic() - g_pool.timebase.value g_pool.get_timestamp = get_timestamp g_pool.get_now = get_time_monotonic def load_runtime_pupil_detection_plugins(): from plugin import import_runtime_plugins from pupil_detector_plugins.detector_base_plugin import PupilDetectorPlugin plugins_path = os.path.join(g_pool.user_dir, "plugins") for plugin in import_runtime_plugins(plugins_path): if not isinstance(plugin, type): continue if not issubclass(plugin, PupilDetectorPlugin): continue if plugin is PupilDetectorPlugin: continue yield plugin available_detectors = available_detector_plugins() runtime_detectors = list(load_runtime_pupil_detection_plugins()) plugins = (manager_classes + source_classes + available_detectors + runtime_detectors + [Roi]) g_pool.plugin_by_name = {p.__name__: p for p in plugins} preferred_names = [ f"Pupil Cam3 ID{eye_id}", f"Pupil Cam2 ID{eye_id}", f"Pupil Cam1 ID{eye_id}", ] if eye_id == 0: preferred_names += ["HD-6000"] default_capture_name = "UVC_Source" default_capture_settings = { "preferred_names": preferred_names, "frame_size": (192, 192), "frame_rate": 120, } default_plugins = [ # TODO: extend with plugins (default_capture_name, default_capture_settings), ("UVC_Manager", {}), *[(p.__name__, {}) for p in available_detectors], ("NDSI_Manager", {}), ("HMD_Streaming_Manager", {}), ("File_Manager", {}), ("Roi", {}), ] def consume_events_and_render_buffer(): glfw.make_context_current(main_window) clear_gl_screen() if all(c > 0 for c in g_pool.camera_render_size): glViewport(0, 0, *g_pool.camera_render_size) for p in g_pool.plugins: p.gl_display() glViewport(0, 0, *window_size) # render graphs fps_graph.draw() cpu_graph.draw() # render GUI try: clipboard = glfw.get_clipboard_string(main_window).decode() except (AttributeError, glfw.GLFWError): # clipboard is None, might happen on startup clipboard = "" g_pool.gui.update_clipboard(clipboard) user_input = g_pool.gui.update() if user_input.clipboard != clipboard: # only write to clipboard if content changed glfw.set_clipboard_string(main_window, user_input.clipboard) for button, action, mods in user_input.buttons: x, y = glfw.get_cursor_pos(main_window) pos = gl_utils.window_coordinate_to_framebuffer_coordinate( main_window, x, y, cached_scale=None) pos = normalize(pos, g_pool.camera_render_size) if g_pool.flip: pos = 1 - pos[0], 1 - pos[1] # Position in img pixels pos = denormalize(pos, g_pool.capture.frame_size) for plugin in g_pool.plugins: if plugin.on_click(pos, button, action): break for key, scancode, action, mods in user_input.keys: for plugin in g_pool.plugins: if plugin.on_key(key, scancode, action, mods): break for char_ in user_input.chars: for plugin in g_pool.plugins: if plugin.on_char(char_): break # update screen glfw.swap_buffers(main_window) # Callback functions def on_resize(window, w, h): nonlocal window_size nonlocal content_scale is_minimized = bool(glfw.get_window_attrib(window, glfw.ICONIFIED)) if is_minimized: return # Always clear buffers on resize to make sure that there are no overlapping # artifacts from previous frames. gl_utils.glClear(GL_COLOR_BUFFER_BIT) gl_utils.glClearColor(0, 0, 0, 1) active_window = glfw.get_current_context() glfw.make_context_current(window) content_scale = gl_utils.get_content_scale(window) framebuffer_scale = gl_utils.get_framebuffer_scale(window) g_pool.gui.scale = content_scale window_size = w, h g_pool.camera_render_size = w - int( icon_bar_width * g_pool.gui.scale), h g_pool.gui.update_window(w, h) g_pool.gui.collect_menus() for g in g_pool.graphs: g.scale = content_scale g.adjust_window_size(w, h) adjust_gl_view(w, h) glfw.make_context_current(active_window) # Minimum window size required, otherwise parts of the UI can cause openGL # issues with permanent effects. Depends on the content scale, which can # potentially be dynamically modified, so we re-adjust the size limits every # time here. min_size = int(2 * icon_bar_width * g_pool.gui.scale / framebuffer_scale) glfw.set_window_size_limits( window, min_size, min_size, glfw.DONT_CARE, glfw.DONT_CARE, ) # Needed, to update the window buffer while resizing consume_events_and_render_buffer() def on_window_key(window, key, scancode, action, mods): g_pool.gui.update_key(key, scancode, action, mods) def on_window_char(window, char): g_pool.gui.update_char(char) def on_iconify(window, iconified): g_pool.iconified = iconified def on_window_mouse_button(window, button, action, mods): g_pool.gui.update_button(button, action, mods) def on_pos(window, x, y): x, y = gl_utils.window_coordinate_to_framebuffer_coordinate( window, x, y, cached_scale=None) g_pool.gui.update_mouse(x, y) pos = x, y pos = normalize(pos, g_pool.camera_render_size) if g_pool.flip: pos = 1 - pos[0], 1 - pos[1] # Position in img pixels pos = denormalize(pos, g_pool.capture.frame_size) for p in g_pool.plugins: p.on_pos(pos) def on_scroll(window, x, y): g_pool.gui.update_scroll(x, y * scroll_factor) def on_drop(window, paths): for plugin in g_pool.plugins: if plugin.on_drop(paths): break # load session persistent settings session_settings = Persistent_Dict( os.path.join(g_pool.user_dir, "user_settings_eye{}".format(eye_id))) if parse_version(session_settings.get("version", "0.0")) != g_pool.version: logger.info( "Session setting are from a different version of this app. I will not use those." ) session_settings.clear() camera_is_physically_flipped = eye_id == 0 g_pool.iconified = False g_pool.capture = None g_pool.flip = session_settings.get("flip", camera_is_physically_flipped) g_pool.display_mode = session_settings.get("display_mode", "camera_image") g_pool.display_mode_info_text = { "camera_image": "Raw eye camera image. This uses the least amount of CPU power", "roi": "Click and drag on the blue circles to adjust the region of interest. The region should be as small as possible, but large enough to capture all pupil movements.", "algorithm": "Algorithm display mode overlays a visualization of the pupil detection parameters on top of the eye video. Adjust parameters within the Pupil Detection menu below.", } def set_display_mode_info(val): g_pool.display_mode = val g_pool.display_mode_info.text = g_pool.display_mode_info_text[val] def toggle_general_settings(collapsed): # this is the menu toggle logic. # Only one menu can be open. # If no menu is open the menubar should collapse. g_pool.menubar.collapsed = collapsed for m in g_pool.menubar.elements: m.collapsed = True general_settings.collapsed = collapsed # Initialize glfw glfw.init() glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE) if hide_ui: glfw.window_hint(glfw.VISIBLE, 0) # hide window title = "Pupil Capture - eye {}".format(eye_id) # Pupil Cam1 uses 4:3 resolutions. Pupil Cam2 and Cam3 use 1:1 resolutions. # As all Pupil Core and VR/AR add-ons are shipped with Pupil Cam2 and Cam3 # cameras, we adjust the default eye window size to a 1:1 content aspect ratio. # The size of 500 was chosen s.t. the menu still fits. default_window_size = 500 + icon_bar_width, 500 width, height = session_settings.get("window_size", default_window_size) main_window = glfw.create_window(width, height, title, None, None) window_position_manager = gl_utils.WindowPositionManager() window_pos = window_position_manager.new_window_position( window=main_window, default_position=window_position_default, previous_position=session_settings.get("window_position", None), ) glfw.set_window_pos(main_window, window_pos[0], window_pos[1]) glfw.make_context_current(main_window) cygl.utils.init() # gl_state settings basic_gl_setup() g_pool.image_tex = Named_Texture() g_pool.image_tex.update_from_ndarray( np.ones((1, 1), dtype=np.uint8) + 125) # setup GUI g_pool.gui = ui.UI() g_pool.menubar = ui.Scrolling_Menu("Settings", pos=(-500, 0), size=(-icon_bar_width, 0), header_pos="left") g_pool.iconbar = ui.Scrolling_Menu("Icons", pos=(-icon_bar_width, 0), size=(0, 0), header_pos="hidden") g_pool.gui.append(g_pool.menubar) g_pool.gui.append(g_pool.iconbar) general_settings = ui.Growing_Menu("General", header_pos="headline") def set_window_size(): # Get current capture frame size f_width, f_height = g_pool.capture.frame_size # Eye camera resolutions are too small to be used as default window sizes. # We use double their size instead. frame_scale_factor = 2 f_width *= frame_scale_factor f_height *= frame_scale_factor # Get current display scale factor content_scale = gl_utils.get_content_scale(main_window) framebuffer_scale = gl_utils.get_framebuffer_scale(main_window) display_scale_factor = content_scale / framebuffer_scale # Scale the capture frame size by display scale factor f_width *= display_scale_factor f_height *= display_scale_factor # Increas the width to account for the added scaled icon bar width f_width += icon_bar_width * display_scale_factor # Set the newly calculated size (scaled capture frame size + scaled icon bar width) glfw.set_window_size(main_window, int(f_width), int(f_height)) general_settings.append(ui.Button("Reset window size", set_window_size)) general_settings.append( ui.Switch("flip", g_pool, label="Flip image display")) general_settings.append( ui.Selector( "display_mode", g_pool, setter=set_display_mode_info, selection=["camera_image", "roi", "algorithm"], labels=["Camera Image", "ROI", "Algorithm"], label="Mode", )) g_pool.display_mode_info = ui.Info_Text( g_pool.display_mode_info_text[g_pool.display_mode]) general_settings.append(g_pool.display_mode_info) g_pool.menubar.append(general_settings) icon = ui.Icon( "collapsed", general_settings, label=chr(0xE8B8), on_val=False, off_val=True, setter=toggle_general_settings, label_font="pupil_icons", ) icon.tooltip = "General Settings" g_pool.iconbar.append(icon) plugins_to_load = session_settings.get("loaded_plugins", default_plugins) if overwrite_cap_settings: # Ensure that overwrite_cap_settings takes preference over source plugins # with incorrect settings that were loaded from session settings. plugins_to_load.append(overwrite_cap_settings) # Add runtime plugins to the list of plugins to load with default arguments, # if not already restored from session settings plugins_to_load_names = set(name for name, _ in plugins_to_load) for runtime_detector in runtime_detectors: runtime_name = runtime_detector.__name__ if runtime_name not in plugins_to_load_names: plugins_to_load.append((runtime_name, {})) g_pool.plugins = Plugin_List(g_pool, plugins_to_load) if not g_pool.capture: # Make sure we always have a capture running. Important if there was no # capture stored in session settings. g_pool.plugins.add(g_pool.plugin_by_name[default_capture_name], default_capture_settings) toggle_general_settings(True) g_pool.writer = None g_pool.rec_path = None # Register callbacks main_window glfw.set_framebuffer_size_callback(main_window, on_resize) glfw.set_window_iconify_callback(main_window, on_iconify) glfw.set_key_callback(main_window, on_window_key) glfw.set_char_callback(main_window, on_window_char) glfw.set_mouse_button_callback(main_window, on_window_mouse_button) glfw.set_cursor_pos_callback(main_window, on_pos) glfw.set_scroll_callback(main_window, on_scroll) glfw.set_drop_callback(main_window, on_drop) # load last gui configuration g_pool.gui.configuration = session_settings.get("ui_config", {}) # If previously selected plugin was not loaded this time, we will have an # expanded menubar without any menu selected. We need to ensure the menubar is # collapsed in this case. if all(submenu.collapsed for submenu in g_pool.menubar.elements): g_pool.menubar.collapsed = True # set up performance graphs pid = os.getpid() ps = psutil.Process(pid) ts = g_pool.get_timestamp() cpu_graph = graph.Bar_Graph() cpu_graph.pos = (20, 50) cpu_graph.update_fn = ps.cpu_percent cpu_graph.update_rate = 5 cpu_graph.label = "CPU %0.1f" fps_graph = graph.Bar_Graph() fps_graph.pos = (140, 50) fps_graph.update_rate = 5 fps_graph.label = "%0.0f FPS" g_pool.graphs = [cpu_graph, fps_graph] # set the last saved window size on_resize(main_window, *glfw.get_framebuffer_size(main_window)) should_publish_frames = False frame_publish_format = "jpeg" frame_publish_format_recent_warning = False # create a timer to control window update frequency window_update_timer = timer(1 / 60) def window_should_update(): return next(window_update_timer) logger.warning("Process started.") frame = None if platform.system() == "Darwin": # On macOS, calls to glfw.swap_buffers() deliberately take longer in case of # occluded windows, based on the swap interval value. This causes an FPS drop # and leads to problems when recording. To side-step this behaviour, the swap # interval is set to zero. # # Read more about window occlusion on macOS here: # https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/WorkWhenVisible.html glfw.swap_interval(0) # Event loop window_should_close = False while not window_should_close: if notify_sub.new_data: t, notification = notify_sub.recv() subject = notification["subject"] if subject.startswith("eye_process.should_stop"): if notification["eye_id"] == eye_id: break elif subject == "recording.started": if notification["record_eye"] and g_pool.capture.online: g_pool.rec_path = notification["rec_path"] raw_mode = notification["compression"] start_time_synced = notification["start_time_synced"] logger.info( f"Will save eye video to: {g_pool.rec_path}") video_path = os.path.join(g_pool.rec_path, "eye{}.mp4".format(eye_id)) if raw_mode and frame and g_pool.capture.jpeg_support: g_pool.writer = JPEG_Writer( video_path, start_time_synced) elif hasattr(g_pool.capture._recent_frame, "h264_buffer"): g_pool.writer = H264Writer( video_path, g_pool.capture.frame_size[0], g_pool.capture.frame_size[1], g_pool.capture.frame_rate, ) else: g_pool.writer = MPEG_Writer( video_path, start_time_synced) elif subject == "recording.stopped": if g_pool.writer: logger.info("Done recording.") try: g_pool.writer.release() except RuntimeError: logger.error("No eye video recorded") else: # TODO: wrap recording logic into plugin g_pool.capture.intrinsics.save( g_pool.rec_path, custom_name=f"eye{eye_id}") finally: g_pool.writer = None elif subject.startswith("meta.should_doc"): ipc_socket.notify({ "subject": "meta.doc", "actor": "eye{}".format(eye_id), "doc": eye.__doc__, }) elif subject.startswith("frame_publishing.started"): should_publish_frames = True frame_publish_format = notification.get("format", "jpeg") elif subject.startswith("frame_publishing.stopped"): should_publish_frames = False frame_publish_format = "jpeg" elif (subject.startswith("start_eye_plugin") and notification["target"] == g_pool.process): try: g_pool.plugins.add( g_pool.plugin_by_name[notification["name"]], notification.get("args", {}), ) except KeyError as err: logger.error(f"Attempt to load unknown plugin: {err}") elif (subject.startswith("stop_eye_plugin") and notification["target"] == g_pool.process): try: plugin_to_stop = g_pool.plugin_by_name[ notification["name"]] except KeyError as err: logger.error(f"Attempt to load unknown plugin: {err}") else: plugin_to_stop.alive = False g_pool.plugins.clean() for plugin in g_pool.plugins: plugin.on_notify(notification) event = {} for plugin in g_pool.plugins: plugin.recent_events(event) frame = event.get("frame") if frame: if should_publish_frames: try: if frame_publish_format == "jpeg": data = frame.jpeg_buffer elif frame_publish_format == "yuv": data = frame.yuv_buffer elif frame_publish_format == "bgr": data = frame.bgr elif frame_publish_format == "gray": data = frame.gray assert data is not None except (AttributeError, AssertionError, NameError): if not frame_publish_format_recent_warning: frame_publish_format_recent_warning = True logger.warning( '{}s are not compatible with format "{}"'. format(type(frame), frame_publish_format)) else: frame_publish_format_recent_warning = False pupil_socket.send({ "topic": "frame.eye.{}".format(eye_id), "width": frame.width, "height": frame.height, "index": frame.index, "timestamp": frame.timestamp, "format": frame_publish_format, "__raw_data__": [data], }) t = frame.timestamp dt, ts = t - ts, t try: fps_graph.add(1.0 / dt) except ZeroDivisionError: pass if g_pool.writer: try: g_pool.writer.write_video_frame(frame) except NonMonotonicTimestampError as e: logger.error( "Recorder received non-monotonic timestamp!" " Stopping the recording!") logger.debug(str(e)) ipc_socket.notify({"subject": "recording.should_stop"}) ipc_socket.notify({ "subject": "recording.should_stop", "remote_notify": "all" }) for result in event.get(EVENT_KEY, ()): pupil_socket.send(result) # GL drawing if window_should_update(): cpu_graph.update() if is_window_visible(main_window): consume_events_and_render_buffer() glfw.poll_events() window_should_close = glfw.window_should_close(main_window) # END while running # in case eye recording was still runnnig: Save&close if g_pool.writer: logger.info("Done recording eye.") g_pool.writer.release() g_pool.writer = None session_settings["loaded_plugins"] = g_pool.plugins.get_initializers() # save session persistent settings session_settings["flip"] = g_pool.flip session_settings["display_mode"] = g_pool.display_mode session_settings["ui_config"] = g_pool.gui.configuration session_settings["version"] = str(g_pool.version) if not hide_ui: glfw.restore_window(main_window) # need to do this for windows os session_settings["window_position"] = glfw.get_window_pos( main_window) session_window_size = glfw.get_window_size(main_window) if 0 not in session_window_size: f_width, f_height = session_window_size if platform.system() in ("Windows", "Linux"): # Store unscaled window size as the operating system will scale the # windows appropriately during launch on Windows and Linux. f_width, f_height = ( f_width / content_scale, f_height / content_scale, ) session_settings["window_size"] = int(f_width), int(f_height) session_settings.close() for plugin in g_pool.plugins: plugin.alive = False g_pool.plugins.clean() glfw.destroy_window(main_window) g_pool.gui.terminate() glfw.terminate() logger.info("Process shutting down.")
def main(): if not glfw.init(): return window = glfw.create_window(720, 600, "Pyopengl Rotating Cube", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) cube = [ -0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, 1.0, 1.0, 1.0, -0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 0.0, 1.0, -0.5, 0.5, -0.5, 1.0, 1.0, 1.0 ] # convert to 32bit float cube = np.array(cube, dtype=np.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 4, 5, 1, 1, 0, 4, 6, 7, 3, 3, 2, 6, 5, 6, 2, 2, 1, 5, 7, 4, 0, 0, 3, 7 ] indices = np.array(indices, dtype=np.uint32) VERTEX_SHADER = """ #version 330 in vec3 position; in vec3 color; out vec3 newColor; uniform mat4 transform; void main() { gl_Position = transform * vec4(position, 1.0f); newColor = color; } """ FRAGMENT_SHADER = """ #version 330 in vec3 newColor; out vec4 outColor; void main() { outColor = vec4(newColor, 1.0f); } """ # Compile The Program and shaders shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(VERTEX_SHADER, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(FRAGMENT_SHADER, GL_FRAGMENT_SHADER)) # Create Buffer object in gpu VBO = glGenBuffers(1) # Bind the buffer glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, 192, cube, GL_STATIC_DRAW) #Create EBO EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, 144, indices, GL_STATIC_DRAW) # get the position from shader position = glGetAttribLocation(shader, 'position') glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) # get the color from shader color = glGetAttribLocation(shader, 'color') glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glEnableVertexAttribArray(color) glUseProgram(shader) glClearColor(0.0, 0.0, 0.0, 1.0) glEnable(GL_DEPTH_TEST) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time()) rot_y = pyrr.Matrix44.from_y_rotation(0.1 * glfw.get_time()) transformLoc = glGetUniformLocation(shader, "transform") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y) # Draw Cube glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 1280, 720 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) glfw.set_cursor_pos_callback(window, cursor_pos_callback) glfw.set_mouse_button_callback(window, mouse_button_callback) # positions texture coordinates cube = [-0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 1.0, -0.5, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0] cube = numpy.array(cube, dtype=numpy.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in layout(location = 0) vec3 position; in layout(location = 1) vec2 texture_cords; uniform mat4 vp; uniform mat4 model; out vec2 textures; void main() { gl_Position = vp * model * vec4(position, 1.0f); textures = texture_cords; } """ fragment_shader = """ #version 330 out vec4 outColor; in vec2 textures; uniform sampler2D tex_sampler; uniform ivec3 icolor; uniform int switcher; void main() { if(switcher == 0){ outColor = texture(tex_sampler, textures); }else{ outColor = vec4(icolor.r/255.0, icolor.g/255.0, icolor.b/255.0, 1.0); } } """ shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) # vertex buffer object and element buffer object VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW) # position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) crate = TextureLoader.load_texture("res/crate.jpg") metal = TextureLoader.load_texture("res/metal.jpg") brick = TextureLoader.load_texture("res/brick.jpg") ###################################################################################### # picking texture and a frame buffer object pick_texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, pick_texture) FBO = glGenFramebuffers(1) glBindFramebuffer(GL_FRAMEBUFFER, FBO) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1280, 720, 0, GL_RGB, GL_FLOAT, None) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pick_texture, 0) glBindFramebuffer(GL_FRAMEBUFFER, 0) glBindTexture(GL_TEXTURE_2D, 0) ###################################################################################### glUseProgram(shader) glEnable(GL_DEPTH_TEST) view = matrix44.create_from_translation(Vector3([0.0, 0.0, -4.0])) projection = matrix44.create_perspective_projection_matrix(45.0, aspect_ratio, 0.1, 100.0) vp = matrix44.multiply(view, projection) vp_loc = glGetUniformLocation(shader, "vp") model_loc = glGetUniformLocation(shader, "model") icolor_loc = glGetUniformLocation(shader, "icolor") switcher_loc = glGetUniformLocation(shader, "switcher") cube_positions = [(-2.0, 0.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0)] pick_colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp) while not glfw.window_should_close(window): glfw.poll_events() glClearColor(0.2, 0.3, 0.2, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) rot_y = Matrix44.from_y_rotation(glfw.get_time() * 2) # draw to the default frame buffer glUniform1i(switcher_loc, 0) for i in range(len(cube_positions)): model = matrix44.create_from_translation(cube_positions[i]) if i == 0: glBindTexture(GL_TEXTURE_2D, crate) if red_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) elif i == 1: glBindTexture(GL_TEXTURE_2D, metal) if green_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) else: glBindTexture(GL_TEXTURE_2D, brick) if blue_rot: glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model) else: glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) # draw to the custom frame buffer object glUniform1i(switcher_loc, 1) glBindFramebuffer(GL_FRAMEBUFFER, FBO) glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) for i in range(len(cube_positions)): pick_model = matrix44.create_from_translation(cube_positions[i]) glUniform3iv(icolor_loc, 1, pick_colors[i]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, pick_model) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) if pick: picker() glBindFramebuffer(GL_FRAMEBUFFER, 0) glfw.swap_buffers(window) glfw.terminate()
def cleanup(self): vulkan.vkDestroyInstance(self.instance, None) glfw.destroy_window(self.window) glfw.terminate()
def key_callback(window, key, scancode, action, mods): if key == glfw.KEY_ESCAPE and action == glfw.PRESS: glfw.destroy_window(window) glfw.terminate()
def __init__( self, module, width, height, caption, scale, palette, fps, border_width, border_color, ): if glfw.get_version() < tuple(map(int, GLFW_VERSION.split("."))): raise RuntimeError( "glfw version is lower than {}".format(GLFW_VERSION)) if width > APP_SCREEN_MAX_SIZE or height > APP_SCREEN_MAX_SIZE: raise ValueError("screen size is larger than {}x{}".format( APP_SCREEN_MAX_SIZE, APP_SCREEN_MAX_SIZE)) global pyxel pyxel = module self._palette = palette[:] self._fps = fps self._border_width = border_width self._border_color = border_color self._next_update_time = 0 self._one_frame_time = 1 / fps self._key_state = {} self._is_mouse_visible = False self._update = None self._draw = None self._capture_start = 0 self._capture_count = 0 self._capture_images = [None] * APP_GIF_CAPTURE_COUNT self._perf_monitor_is_enabled = False self._perf_fps_count = 0 self._perf_fps_start_time = 0 self._perf_fps = 0 self._perf_update_count = 0 self._perf_update_total_time = 0 self._perf_update_time = 0 self._perf_draw_count = 0 self._perf_draw_total_time = 0 self._perf_draw_time = 0 # exports variables pyxel._app = self pyxel.width = width pyxel.height = height pyxel.mouse_x = 0 pyxel.mouse_y = 0 pyxel.frame_count = 0 # initialize window if not glfw.init(): exit() monitor = glfw.get_primary_monitor() display_width, display_height = glfw.get_video_mode(monitor)[0] if scale == 0: scale = max( min( (display_width // width) - APP_SCREEN_SCALE_CUTDOWN, (display_height // height) - APP_SCREEN_SCALE_CUTDOWN, ), APP_SCREEN_SCALE_MINIMUM, ) window_width = width * scale + border_width window_height = height * scale + border_width self._window = glfw.create_window(window_width, window_height, caption, None, None) if not self._window: glfw.terminate() exit() glfw.set_window_pos( self._window, (display_width - window_width) // 2, (display_height - window_height) // 2, ) glfw.make_context_current(self._window) glfw.set_window_size_limits(self._window, width, height, glfw.DONT_CARE, glfw.DONT_CARE) self._hidpi_scale = (glfw.get_framebuffer_size(self._window)[0] / glfw.get_window_size(self._window)[0]) self._update_viewport() glfw.set_key_callback(self._window, self._key_callback) glfw.set_mouse_button_callback(self._window, self._mouse_button_callback) glfw.set_window_icon(self._window, 1, [get_icon_image()]) glfw.set_input_mode(self._window, glfw.CURSOR, glfw.CURSOR_HIDDEN) # initialize renderer self._renderer = Renderer(width, height) # initialize audio player self._audio_player = AudioPlayer() # export module functions pyxel.btn = self.btn pyxel.btnp = self.btnp pyxel.btnr = self.btnr pyxel.mouse = self.mouse pyxel.run = self.run pyxel.run_with_profiler = self.run_with_profiler pyxel.quit = self.quit pyxel.save = self.save pyxel.load = self.load pyxel.image = self._renderer.image pyxel.tilemap = self._renderer.tilemap pyxel.clip = self._renderer.draw_command.clip pyxel.pal = self._renderer.draw_command.pal pyxel.cls = self._renderer.draw_command.cls pyxel.pix = self._renderer.draw_command.pix pyxel.line = self._renderer.draw_command.line pyxel.rect = self._renderer.draw_command.rect pyxel.rectb = self._renderer.draw_command.rectb pyxel.circ = self._renderer.draw_command.circ pyxel.circb = self._renderer.draw_command.circb pyxel.blt = self._renderer.draw_command.blt pyxel.bltm = self._renderer.draw_command.bltm pyxel.text = self._renderer.draw_command.text pyxel.sound = self._audio_player.sound pyxel.music = self._audio_player.music pyxel.play = self._audio_player.play pyxel.playm = self._audio_player.playm pyxel.stop = self._audio_player.stop # initialize mouse cursor pyxel.image(3, system=True).set(MOUSE_CURSOR_IMAGE_X, MOUSE_CURSOR_IMAGE_Y, MOUSE_CURSOR_DATA)
if action == glfw.PRESS or action == glfw.REPEAT: if key == glfw.KEY_ESCAPE or key == glfw.KEY_Q: glfw.set_window_should_close(self.win, True) if key == glfw.KEY_W: GL.glPolygonMode(GL.GL_FRONT_AND_BACK, next(self.fill_modes)) if key == glfw.KEY_SPACE: glfw.set_time(0) # -------------- main program and scene setup -------------------------------- def main(): """ create a window, add scene objects, then run rendering loop """ viewer = Viewer() if len(sys.argv) < 2: print('Cylinder skinning demo.') print('Note:\n\t%s [3dfile]*\n\n3dfile\t\t the filename of a model in' ' format supported by pyassimp.' % sys.argv[0]) viewer.add(SkinnedCylinder()) else: viewer.add(*[m for file in sys.argv[1:] for m in load_skinned(file)]) # start rendering loop viewer.run() if __name__ == '__main__': glfw.init() # initialize window system glfw main() # main function keeps variables locally scoped glfw.terminate() # destroy all glfw windows and GL contexts
def main(): # initialize glfw if not glfw.init(): return w_width, w_height = 1280, 720 aspect_ratio = w_width / w_height window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) # positions texture_coords cube = [ -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 1.0, -0.5, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0 ] cube = numpy.array(cube, dtype=numpy.float32) indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20 ] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in layout(location = 0) vec3 position; in layout(location = 1) vec2 texture_cords; uniform mat4 model; uniform mat4 view; uniform mat4 proj; out vec2 textures; void main() { gl_Position = proj * view * model * vec4(position, 1.0f); textures = texture_cords; } """ fragment_shader = """ #version 330 in vec2 textures; out vec4 color; uniform sampler2D tex_sampler; void main() { color = texture(tex_sampler, textures); } """ shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW) # position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) crate = TextureLoader.load_texture( "resources/images/planks_brown_10_diff_1k.jpg") metal = TextureLoader.load_texture( "resources/images/green_metal_rust_diff_1k.jpg") brick = TextureLoader.load_texture( "resources/images/castle_brick_07_diff_1k.jpg") glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) projection = matrix44.create_perspective_projection_matrix( 45.0, aspect_ratio, 0.1, 100.0) model_loc = glGetUniformLocation(shader, "model") view_loc = glGetUniformLocation(shader, "view") proj_loc = glGetUniformLocation(shader, "proj") cube_positions = [(0.0, 0.0, 0.0), (2.0, 2.0, -5.0), (1.5, -1.2, -2.5), (8.8, -2.0, -12.3), (-2.0, 2.0, -5.5), (-4.0, 2.0, -3.0)] glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) cam = Camera() while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) camX = sin(glfw.get_time()) * 10 camZ = cos(glfw.get_time()) * 10 view = cam.look_at(Vector3([camX, 5.0, camZ]), Vector3([0.0, 0.0, 0.0]), Vector3([0.0, 1.0, 0.0])) glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) for i in range(len(cube_positions)): model = matrix44.create_from_translation(cube_positions[i]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) if i < 2: glBindTexture(GL_TEXTURE_2D, crate) elif i == 2 or i == 3: glBindTexture(GL_TEXTURE_2D, metal) else: glBindTexture(GL_TEXTURE_2D, brick) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def main(): # initialize glfw if not glfw.init(): return window = glfw.create_window(800, 600, "My OpenGL window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) # positions colors texture quad = [ -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0 ] quad = numpy.array(quad, dtype=numpy.float32) indices = [0, 1, 2, 2, 3, 0] indices = numpy.array(indices, dtype=numpy.uint32) vertex_shader = """ #version 330 in layout(location = 0) vec3 position; in layout(location = 1) vec3 color; in layout(location = 2) vec2 inTexCoords; out vec3 newColor; out vec2 outTexCoords; void main() { gl_Position = vec4(position, 1.0f); newColor = color; outTexCoords = inTexCoords; } """ fragment_shader = """ #version 330 in vec3 newColor; in vec2 outTexCoords; uniform sampler2D samplerTex; out vec4 outColor; void main() { outColor = texture(samplerTex, outTexCoords) * vec4(newColor, 1.0f); } """ shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, quad.itemsize * len(quad), quad, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW) # position = glGetAttribLocation(shader, "position") glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, quad.itemsize * 8, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) # color = glGetAttribLocation(shader, "color") glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, quad.itemsize * 8, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) # texture_coords = glGetAttribLocation(shader, "inTexCoords") glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, quad.itemsize * 8, ctypes.c_void_p(24)) glEnableVertexAttribArray(2) texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) # texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = Image.open("resources/images/windowpainting.PNG") image = image.transpose(Image.FLIP_TOP_BOTTOM) #image_data = numpy.asarray(image.getdata(), numpy.uint8) image_data = image.convert("RGBA").tobytes() glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data) glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT) glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
from model import * from controller import Controller if __name__ == '__main__' : if not glfw.init(): sys.exit() grilla = int(sys.argv[1]) width = 800 height = 800 window = glfw.create_window(width,height, 'Snake', None, None) if not window: glfw.terminate() sys.exit() glfw.make_context_current(window) controlador = Controller() glfw.set_key_callback(window, controlador.on_key) pipeline = es.SimpleTransformShaderProgram() pipelineTexturas = es.SimpleTextureTransformShaderProgram() glUseProgram(pipeline.shaderProgram) glClearColor(0, 0.85, 0, 1.0) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
def main(): res = (2600,1800) n_particles = 1500 # Number of bodies. My computer runs 2000 pretty comfortably. cam = Camera(fov=80, aspect_ratio=res[0]/res[1], xyz=(0,0,-10)) torch_nbody = torch_NBody(n_particles, damping=0.10, # Prevent bodies from hitting lightspeed when they get too close G=.05, # Gravity strength spread=3.0, # Place bodies in a normal distribution with this standard deviation mass_pareto=1.9, # The masses of the bodies follow this Pareto distribution velocity_spread=0.5, # Initial velocity vectors are normally distributed with this standard deviation dtype=torch.cuda.FloatTensor) if not glfw.init(): return window = glfw.create_window(res[0], res[1], "", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glEnable(GL_DEPTH_TEST) glClearColor(0.0,0.0,0.0,1.0) shader = Shader() shader.use() shader.view = cam.matrix model = Model("sphere.obj", center=True) model.use(shader.position) m = model.n_indices buffer_translate = glGenBuffers(1) buffer_scale = glGenBuffers(1) buffer_brightness = glGenBuffers(1) glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer_scale) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, shader.obj_scale, buffer_scale) scale = np.array(0.03 * (torch_nbody.mass.cpu().view(-1) * .75 / np.pi).pow(1/3).to(torch.float32).numpy()) glBufferData(GL_SHADER_STORAGE_BUFFER, 4 * n_particles, scale, GL_DYNAMIC_DRAW) glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffer_translate) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, shader.obj_translate, buffer_translate) exposure = 200.0 while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) torch_nbody.step(0.01) glBindBufferBase(GL_SHADER_STORAGE_BUFFER, shader.obj_translate, buffer_translate) translate = torch_nbody.position.cpu().view(-1).to(torch.float32).numpy() glBufferData(GL_SHADER_STORAGE_BUFFER, 4 * len(translate), translate, GL_DYNAMIC_DRAW) # Example visualization brightness = torch_nbody.a.norm(dim=1) exposure = exposure * 0.98 + brightness.max() * 0.02 brightness /= exposure brightness = 0.2 + 0.9 * brightness brightness = brightness.cpu().view(-1).to(torch.float32).numpy() glBindBufferBase(GL_SHADER_STORAGE_BUFFER, shader.obj_brightness, buffer_brightness) glBufferData(GL_SHADER_STORAGE_BUFFER, 4 * len(brightness), brightness, GL_DYNAMIC_DRAW) glDrawElementsInstanced(GL_TRIANGLES, 3 * m, GL_UNSIGNED_INT, None, n_particles) glfw.swap_buffers(window) glfw.terminate()
def mainLoop(self): while not glfw.window_should_close(self.m_Window): glfw.swap_buffers(self.m_Window) glfw.poll_events() glfw.terminate()
def main(): global view, score translate_cube_z = pyrr.Vector3([0.0, 0.0, 0.1]) pygame.init() music = pygame.mixer.music.load('music/music.mp3') pygame.mixer.music.play(-1) hitSound = pygame.mixer.Sound('./music/hit.wav') glfw.set_input_mode(main_window.win, glfw.STICKY_KEYS, GL_TRUE) # Enable key event callback glfw.set_key_callback(main_window.win, main_window.key_event) # The main aplication loop while glfw.get_key( main_window.win, glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close( main_window.win): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) # Drawing the ground model = matrix_ground_position glBindVertexArray(main_shader.quad_VAO[0]) glBindTexture(GL_TEXTURE_2D, ground.id_texture) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(quad_indices), GL_UNSIGNED_INT, None) # Drawing the sky model = matrix_sky_position glBindVertexArray(main_shader.quad_VAO[1]) glBindTexture(GL_TEXTURE_2D, sky.id_texture) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(quad_indices), GL_UNSIGNED_INT, None) for i in range(n + m): # We will translate every object, except the main character if i < n: cube_position[i] += translate_cube_z if cube_position[i][2] >= 20.0: cube_position[i] = pyrr.Vector3([ random.randrange(-5.0, 5.0), 1.5, random.randrange(-100, -40) ]) # Scale the objects that aren't obstacles escala = pyrr.matrix44.create_from_scale([1, 4, 1]) else: # Obtaining the values of the scale previously defined escala = pyrr.matrix44.create_from_scale(gato_escala[i - n]) # Calculating the resulting model by multiplying the scale and translation model = np.dot(escala, matrix_cube_translation[i]) glBindVertexArray(main_shader.cube_VAO[i]) glBindTexture(GL_TEXTURE_2D, my_cubes[i].id_texture) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(cube_indices), GL_UNSIGNED_INT, None) matrix_cube_translation[i] = pyrr.matrix44.create_from_translation( cube_position[i]) for i in range(m): for j in range(n): # Condition for a crash if abs(cube_position[i + n][2] - cube_position[j][2]) < .1 and abs( cube_position[i + n][0] - cube_position[j][0]) < 1: hitSound.play() cube_position[j] = pyrr.Vector3([ random.randrange(-5.0, 5.0), 1.5, random.randrange(-100, -40) ]) score += 1 os.system("clear") print("Your actual escore is:", score) glfw.swap_buffers(main_window.win) # Terminate glfw, free alocated resources glfw.terminate()
def cleanup(self): glfw.destroy_window(self.app.window) glfw.terminate()
def main(): # Initialize the library if not glfw.init(): raise RuntimeError("Failed to initialize GLFW") glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # To make MacOS happy; should not be needed glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # Create a windowed mode window and its OpenGL context window = glfw.create_window(1024, 768, "Tutorial 05 - Textured Cube", None, None) if not window: glfw.terminate() raise RuntimeError("Failed to open GLFW window.") # Make the window's context current glfw.make_context_current(window) # Ensure we can capture the escape key being pressed below glfw.set_input_mode(window, glfw.STICKY_KEYS, True) # Dark blue background glClearColor(0.0, 0.0, 0.4, 0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) vao = glGenVertexArrays(1) glBindVertexArray(vao) # Create and compile our GLSL program from the shaders shader = Shader( "TransformVertexShader2.vertexshader", "TextureFragmentShader.fragmentshader") shader.compile() # Projection matrix : 45 deg Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units Projection = glm_perspective(45.0*np.pi/180., 4.0 / 3.0, 0.1, 100.0) # Camera matrix View = glm_lookAt( [4,3,3], # Camera is at (4,3,3), in World Space [0,0,0], # and looks at the origin [0,1,0] # Head is up (set to 0,-1,0 to look upside-down) ) # Model matrix : an identity matrix (model will be at the origin) Model = np.eye(4) # Our ModelViewProjection : multiplication of our 3 matrices # (convert to 32-bit now that computations are done) MVP = np.array( np.dot(np.dot(Model, View), Projection), dtype=np.float32 ) # Load the texture using any two methods #Texture = loadBMP("uvtemplate.bmp") Texture = loadDDS("uvtemplate.DDS") # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices g_vertex_buffer_data = np.array([ -1.0,-1.0,-1.0, -1.0,-1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0, 1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0,-1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0, 1.0,-1.0, 1.0, 1.0, 1.0, -1.0, 1.0,-1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0,-1.0, 1.0 ],dtype=np.float32) g_uv_buffer_data = np.array([ 0.000059, 1.0-0.000004, 0.000103, 1.0-0.336048, 0.335973, 1.0-0.335903, 1.000023, 1.0-0.000013, 0.667979, 1.0-0.335851, 0.999958, 1.0-0.336064, 0.667979, 1.0-0.335851, 0.336024, 1.0-0.671877, 0.667969, 1.0-0.671889, 1.000023, 1.0-0.000013, 0.668104, 1.0-0.000013, 0.667979, 1.0-0.335851, 0.000059, 1.0-0.000004, 0.335973, 1.0-0.335903, 0.336098, 1.0-0.000071, 0.667979, 1.0-0.335851, 0.335973, 1.0-0.335903, 0.336024, 1.0-0.671877, 1.000004, 1.0-0.671847, 0.999958, 1.0-0.336064, 0.667979, 1.0-0.335851, 0.668104, 1.0-0.000013, 0.335973, 1.0-0.335903, 0.667979, 1.0-0.335851, 0.335973, 1.0-0.335903, 0.668104, 1.0-0.000013, 0.336098, 1.0-0.000071, 0.000103, 1.0-0.336048, 0.000004, 1.0-0.671870, 0.336024, 1.0-0.671877, 0.000103, 1.0-0.336048, 0.336024, 1.0-0.671877, 0.335973, 1.0-0.335903, 0.667969, 1.0-0.671889, 1.000004, 1.0-0.671847, 0.667979, 1.0-0.335851 ],dtype=np.float32) # Create the vertex buffer object vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, g_vertex_buffer_data.nbytes, g_vertex_buffer_data, GL_STATIC_DRAW) # Create the vertex uv buffer object uvbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uvbo) glBufferData(GL_ARRAY_BUFFER, g_uv_buffer_data.nbytes, g_uv_buffer_data, GL_STATIC_DRAW) # Loop until the user closes the window while( glfw.get_key(window, glfw.KEY_ESCAPE ) != glfw.PRESS and glfw.window_should_close(window) == 0 ): # Clear the screen glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) # Use our shader shader.enable() # Send our transformation to the currently bound shader, # in the "MVP" uniform shader.setUniform("MVP", "mat4", MVP) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, Texture) # Set our "myTextureSampler" sampler to user Texture Unit 0 shader.setUniform("myTextureSampler","sampler2D",0) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo) glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # size GL_FLOAT, # type GL_FALSE, # normalized? 0, # stride None # array buffer offset ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uvbo) glVertexAttribPointer( 1, # attribute. No particular reason for 1, but must match the layout in the shader. 2, # size GL_FLOAT, # type GL_FALSE, # normalized? 0, # stride None # array buffer offset ) # Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 12*3) # 3 indices starting at 0 -> 1 triangle glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(): # inicia glfw if not glfw.init(): return # crea la ventana, # independientemente del SO que usemos window = glfw.create_window(800, 800, "Mi ventana", None, None) # Configuramos OpenGL glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # Validamos que se cree la ventana if not window: glfw.terminate() return # Establecemos el contexto glfw.make_context_current(window) # Activamos la validación de # funciones modernas de OpenGL glewExperimental = True # Inicializar GLEW if glewInit() != GLEW_OK: print("No se pudo inicializar GLEW") return # Obtenemos versiones de OpenGL y Shaders version = glGetString(GL_VERSION) print(version) version_shaders = glGetString(GL_SHADING_LANGUAGE_VERSION) print(version_shaders) glfw.set_key_callback(window, key_callback) while not glfw.window_should_close(window): # Establece regiond e dibujo glViewport(0, 0, 800, 800) # Establece color de borrado glClearColor(0.4, 0.8, 0.1, 1) # Borra el contenido de la ventana glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Dibujar actualizar(window) dibujar() # Preguntar si hubo entradas de perifericos # (Teclado, mouse, game pad, etc.) glfw.poll_events() # Intercambia los buffers glfw.swap_buffers(window) # Se destruye la ventana para liberar memoria glfw.destroy_window(window) # Termina los procesos que inició glfw.init glfw.terminate()
def main(): # Initialize the library if not glfw.init(): raise RuntimeError("Failed to initialize GLFW") glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # To make MacOS happy; should not be needed glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # Create a windowed mode window and its OpenGL context window = glfw.create_window(1024, 768, "Tutorial 16 - Shadows", None, None) if not window: glfw.terminate() raise RuntimeError("Failed to open GLFW window.") # Make the window's context current glfw.make_context_current(window) # We would expect width and height to be 1024 and 768 windowWidth = 1024 windowHeight = 768 # But on MacOS X with a retina screen it'll be 1024*2 and 768*2, # so we get the actual framebuffer size: windowWidth, windowHeight = glfw.get_framebuffer_size(window) # Ensure we can capture the escape key being pressed below glfw.set_input_mode(window, glfw.STICKY_KEYS, True) # Hide the mouse and enable unlimited mouvement glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # Set the mouse at the center of the screen glfw.poll_events() glfw.set_cursor_pos(window, 1024 / 2, 768 / 2) # Dark blue background glClearColor(0.0, 0.0, 0.4, 0.0) # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS) vao = glGenVertexArrays(1) glBindVertexArray(vao) # Create and compile our GLSL program from the shaders depth_shader = Shader("DepthRTT.vertexshader", "DepthRTT.fragmentshader") depth_shader.compile() # Create Controls object controls = Controls(window) # Load the texture using any two methods Texture = loadDDS("uvmap3.DDS") # Read our .obj file vertices, uvs, normals = loadOBJ("room_thickwalls.obj", invert_v=True) indices, indexed_vertices, indexed_uvs, indexed_normals = indexVBO( vertices, uvs, normals) # Create the vertex buffer object vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, vbo) glBufferData(GL_ARRAY_BUFFER, indexed_vertices.nbytes, indexed_vertices, GL_STATIC_DRAW) # Create the uv buffer object uvbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uvbo) glBufferData(GL_ARRAY_BUFFER, indexed_uvs.nbytes, indexed_uvs, GL_STATIC_DRAW) # Create normal buffer object nbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, nbo) glBufferData(GL_ARRAY_BUFFER, indexed_normals.nbytes, indexed_normals, GL_STATIC_DRAW) # Generate a buffer for the indices as well ibo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, ibo) glBufferData(GL_ARRAY_BUFFER, indices.nbytes, indices, GL_STATIC_DRAW) # --------------------------------------------- # Render to Texture - specific code begins here # --------------------------------------------- # The framebuffer, which regroups 0, 1, or more textures, and 0 or 1 depth buffer. fbo = glGenFramebuffers(1) glBindFramebuffer(GL_FRAMEBUFFER, fbo) # Depth texture. Slower than a depth buffer, but you can sample it later in your shader depthTexture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, depthTexture) glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_FLOAT, np.zeros((1024, 1024), dtype=np.uint16)) #glTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT16,1024,1024,0,GL_DEPTH_COMPONENT,GL_FLOAT,0) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE) glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture, 0) # No color output in the bound framebuffer, only depth. glDrawBuffer(GL_NONE) # Always check that our framebuffer is ok if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE: raise RuntimeError("Framebuffer not OK!") # Create and compile our GLSL program from the shaders shader = Shader("ShadowMapping.vertexshader", "ShadowMapping.fragmentshader") shader.compile() # For speed computation lastTime = glfw.get_time() nbFrames = 0 # Loop until the user closes the window while (glfw.get_key(window, glfw.KEY_ESCAPE) != glfw.PRESS and glfw.window_should_close(window) == 0): # Measure speed currentTime = glfw.get_time() nbFrames += 1 if currentTime - lastTime >= 1.0: # If last prinf() was more than 1sec ago # printf and reset print("{:.5f} ms/frame".format(1000.0 / float(nbFrames))) nbFrames = 0 lastTime += 1.0 # Render to our framebuffer glBindFramebuffer(GL_FRAMEBUFFER, fbo) glViewport(0, 0, 1024, 1024) # Render on the whole framebuffer, complete from the lower left corner to the upper right # We don't use bias in the shader, but instead we draw back faces, # which are already separated from the front faces by a small distance # (if your geometry is made this way) glEnable(GL_CULL_FACE) glCullFace( GL_BACK ) # Cull back-facing triangles -> draw only front-facing triangles # Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Use our shader depth_shader.enable() lightInvDir = np.array([0.5, 2, 2]) depthProjectionMatrix = glm_ortho(-10., 10., -10., 10., -10., 20.) depthViewMatrix = glm_lookAt(lightInvDir, [0., 0., 0.], [0., 1., 0.]) depthModelMatrix = np.eye(4) depthMVP = np.array(np.dot(np.dot(depthModelMatrix, depthViewMatrix), depthProjectionMatrix), dtype=np.float32) # Send our transformation to the currently bound shader, # in the "MVP" uniform depth_shader.setUniform("depthMVP", "mat4", depthMVP) # 1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo) glVertexAttribPointer( 0, # The attribute we want to configure 3, # size GL_FLOAT, # type GL_FALSE, # normalized? 0, # stride None # array buffer offset ) # Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo) # Draw the triangles ! glDrawElements( GL_TRIANGLES, # mode len(indices), # count GL_UNSIGNED_SHORT, # type None # element array buffer offset ) glDisableVertexAttribArray(0) # Render to the screen glBindFramebuffer(GL_FRAMEBUFFER, 0) glViewport(0, 0, windowWidth, windowHeight) # Render on the whole framebuffer, complete from the lower left corner to the upper right glEnable(GL_CULL_FACE) glCullFace(GL_BACK) # Cull back-facing triangles -> draw only front-facing triangles # Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # Use our shader shader.enable() # Compute the MVP matrix from keyboard and mouse input controls.update() biasMatrix = np.array([[0.5, 0.0, 0.0, 0.0], [0.0, 0.5, 0.0, 0.0], [0.0, 0.0, 0.5, 0.0], [0.5, 0.5, 0.5, 1.0]]) depthBiasMVP = np.array(np.dot(depthMVP, biasMatrix), dtype=np.float32) # Send our transformation to the currently bound shader, # in the "MVP" uniform shader.setUniform("V", "mat4", np.array(controls.ViewMatrix, dtype=np.float32)) shader.setUniform("M", "mat4", np.array(controls.ModelMatrix, dtype=np.float32)) shader.setUniform("MVP", "mat4", controls.MVP) shader.setUniform("DepthBiasMVP", "mat4", depthBiasMVP) shader.setUniform("LightInvDirection_worldspace", "vec3", np.array(lightInvDir, dtype=np.float32)) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, Texture) # Set our "myTextureSampler" sampler to user Texture Unit 0 shader.setUniform("myTextureSampler", "sampler2D", 0) glActiveTexture(GL_TEXTURE1) glBindTexture(GL_TEXTURE_2D, depthTexture) shader.setUniform("shadowMap", "sampler2DShadow", 1) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vbo) glVertexAttribPointer( 0, # attribute 0. 3, # size GL_FLOAT, # type GL_FALSE, # normalized? 0, # stride None # array buffer offset ) # 2nd attribute buffer : UVs glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uvbo) glVertexAttribPointer( 1, # attribute. 2, # size GL_FLOAT, # type GL_FALSE, # normalized? 0, # stride None # array buffer offset ) # 3rd attribute buffer : UVs glEnableVertexAttribArray(2) glBindBuffer(GL_ARRAY_BUFFER, nbo) glVertexAttribPointer( 2, # attribute. 3, # size GL_FLOAT, # type GL_FALSE, # normalized? 0, # stride None # array buffer offset ) # Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo) # Draw the triangles ! glDrawElements( GL_TRIANGLES, # mode len(indices), # count GL_UNSIGNED_SHORT, # type None # element array buffer offset ) glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(): glfw.init() 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) window = glfw.create_window(800, 600, "LearnOpenGL", None, None) if not window: print("Window Creation failed!") glfw.terminate() glfw.make_context_current(window) glfw.set_window_size_callback(window, on_resize) shader = Shader(CURDIR / 'shaders/4.2.texture.vs', CURDIR / 'shaders/4.2.texture.fs') vertices = [ # positions colors tex_coords 0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, # top right 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, # bottom right -0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, # bottom left -0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, # top left ] vertices = (c_float * len(vertices))(*vertices) indices = [0, 1, 3, 1, 2, 3] indices = (c_uint * len(indices))(*indices) vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(vao) vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices, gl.GL_STATIC_DRAW) ebo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, ebo) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(3 * sizeof(c_float))) gl.glEnableVertexAttribArray(1) gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(6 * sizeof(c_float))) gl.glEnableVertexAttribArray(2) # -- load texture 1 texture1 = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture1) # -- texture wrapping gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) # -- texture filterting gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) img = Image.open(Tex('container.jpg')).transpose(Image.FLIP_TOP_BOTTOM) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img.tobytes()) gl.glGenerateMipmap(gl.GL_TEXTURE_2D) # -- load texture 2 texture2 = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture2) # -- texture wrapping gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT) # -- texture filterting gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) img = Image.open(Tex('awesomeface.png')).transpose(Image.FLIP_TOP_BOTTOM) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, img.tobytes()) gl.glGenerateMipmap(gl.GL_TEXTURE_2D) shader.use() shader.set_int("texture1", 0) shader.set_int("texture2", 1) while not glfw.window_should_close(window): process_input(window) gl.glClearColor(.2, .3, .3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, texture1) gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture2) shader.use() gl.glBindVertexArray(vao) gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, c_void_p(0)) glfw.poll_events() glfw.swap_buffers(window) gl.glDeleteVertexArrays(1, id(vao)) gl.glDeleteBuffers(1, id(vbo)) gl.glDeleteBuffers(1, id(ebo)) glfw.terminate()
def tearDownClass(cls): glfw.terminate()
def main(): if not glfw.init(): return glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(800, 600, "My OpenGL Window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) # Verts Colors Texture quad = [ -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0 ] quad = numpy.array(quad, dtype=numpy.float32) indicies = [0, 1, 2, 2, 3, 0] print(quad.itemsize * len(quad)) print(indicies.itemsize * len(indicies)) print(quad.itemsize * 8) indicies = numpy.array(indicies, dtype=numpy.uint32) vertex_shader = """ #version 410 core in vec3 position; in vec3 color; in vec2 inTexCoords; out vec3 newcolor; out vec2 outTexCoords; void main() { gl_Position = vec4(position, 1.0f); newcolor = color; outTexCoords = inTexCoords; } """ fragment_shader = """ #version 410 core in vec3 newcolor; in vec2 outTexCoords; out vec4 outcolor; uniform sampler2D samplerTex; void main() { outcolor = texture(samplerTex, outTexCoords); } """ glfw.make_context_current(window) VAO = glGenVertexArrays(1) glBindVertexArray(VAO) shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, quad.itemsize * len(quad), quad, GL_STATIC_DRAW) EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicies.itemsize * len(indicies), indicies, GL_STATIC_DRAW) position = glGetAttribLocation(shader, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, quad.itemsize * 8, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) color = glGetAttribLocation(shader, "color") glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, quad.itemsize * 8, ctypes.c_void_p(12)) glEnableVertexAttribArray(color) texture_coords = glGetAttribLocation(shader, "inTexCoords") glVertexAttribPointer(texture_coords, 2, GL_FLOAT, GL_FALSE, quad.itemsize * 8, ctypes.c_void_p(24)) glEnableVertexAttribArray(texture_coords) texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = Image.open("crate.jpg") img_data = numpy.array(list(image.getdata()), numpy.uint8) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data) glGenerateMipmap(GL_TEXTURE_2D) glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT) glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def image_server(evtQueue, resultQueue): # resource-taking objects resObjs = [] # initialize glfw glfw.init() # set glfw config glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.RESIZABLE, GL_FALSE) if pyPlatform.system().lower() == 'darwin': glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) # create window theWindow = glfw.create_window(windowSize[0], windowSize[1], 'Spherical Projection', None, None) # make window the current context glfw.make_context_current(theWindow) # enable z-buffer glEnable(GL_DEPTH_TEST) # set resizing callback function # glfw.set_framebuffer_size_callback(theWindow, window_resize_callback) #glfw.set_key_callback(theWindow, window_keypress_callback) # disable cursor #glfw.set_input_mode(theWindow, glfw.CURSOR, glfw.CURSOR_DISABLED) #glfw.set_cursor_pos_callback(theWindow, window_cursor_callback) # initialize cursor position cursorPos = glfw.get_cursor_pos(theWindow) # glfw.set_scroll_callback(theWindow, window_scroll_callback) vbo = VBO(vertices, 'GL_STATIC_DRAW') vbo.create_buffers() resObjs.append(vbo) vao = glGenVertexArrays(1) glBindVertexArray(vao) vbo.bind() vbo.copy_data() glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * ctypes.sizeof(ctypes.c_float), ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindVertexArray(0) # compile program renderProgram = GLProgram(rayTracingVertexShaderSource, rayTracingFragmentShaderSource) renderProgram.compile_and_link() uniformInfos = [ ('backColor', 'vec3f'), ('ambientColor', 'vec3f'), ('o_c', 'vec3f'), ('o_p', 'vec3f'), ('x_c', 'vec3f'), ('y_c', 'vec3f'), ('x_p', 'vec3f'), ('y_p', 'vec3f'), ('c_c', 'vec3f'), ('c_p', 'vec3f'), ('winSize', 'vec2f') ] uniforms = create_uniform(renderProgram.get_program_id(), uniformInfos) # keep rendering until the window should be closed while not glfw.window_should_close(theWindow): # set background color glClearColor(*windowBackgroundColor) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) renderProgram.use() # update uniforms o_c, c_c, x_c, y_c = get_camera_vectors(camera) o_p, c_p, x_p, y_p = get_camera_vectors(projector) uniforms['o_c'].update(o_c) uniforms['x_c'].update(x_c) uniforms['y_c'].update(y_c) uniforms['c_c'].update(c_c) uniforms['o_p'].update(o_p) uniforms['x_p'].update(x_p) uniforms['y_p'].update(y_p) uniforms['c_p'].update(c_p) uniforms['backColor'].update(backColor) uniforms['ambientColor'].update(ambientColor) uniforms['winSize'].update(windowSize.astype(np.float32)) try: newImage = evtQueue.get(timeout=0.05) except Exception as e: # tell glfw to poll and process window events glfw.poll_events() # swap frame buffer glfw.swap_buffers(theWindow) continue texture = create_texture(newImage) glBindVertexArray(vao) glActiveTexture(GL_TEXTURE0) texture.bind() glDrawArrays(GL_TRIANGLES, 0, 6) texture.unbind() glBindVertexArray(0) texture.delete() # respond key press keyboard_respond_func() # tell glfw to poll and process window events glfw.poll_events() # swap frame buffer glfw.swap_buffers(theWindow) result = get_screenshot(windowSize) resultQueue.put(result) for obj in resObjs: obj.delete() # terminate glfw glfw.terminate()
def main(): if not glfw.init(): raise Exception("glfw nt initialized") window = glfw.create_window(512, 512, "B117021 - OpenGL", None, None) if not window: glfw.terminate() raise Exception("glfw window not created") w, h = glfw.get_framebuffer_size(window) print("width: {}, height:{}".format(w, h)) glfw.set_window_pos(window, 400, 200) glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) glfw.set_window_size_callback(window, reshape_callback) gluOrtho2D(0, 512, 512, 0) while not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT) glClearColor(0.0, 0.0, 0.0, 1.0) a = (20, 500) b = (40, 500) c = (40, 355) d = (20, 355) quad_(a, b, c, d) T = (95, 0) a_ = translate2D(a, T) b_ = translate2D(b, T) c_ = translate2D(c, T) d_ = translate2D(d, T) quad_(a_, b_, c_, d_) p = (40, 415) q = (135, 415) r = (135, 435) s = (40, 435) quad_(p, q, r, s) e = (160, 220) f = (220, 250) g = (220, 165) h = (160, 150) quad_(e, f, g, h) i = (128, 150) j = (150, 155) k = (150, 175) l = (125, 165) quad_(i, j, k, l) m = (115, 205) n = (115, 140) o = (55, 125) o_ = (55, 175) quad_(m, n, o, o_) u = (230, 250) v = (330, 190) w = (330, 130) x = (230, 165) quad_(u, v, w, x) p1 = (330, 125) p2 = (295, 95) p3 = (235, 155) glBegin(GL_TRIANGLES) glColor3f(1, 1, 1) #white glVertex2fv(p1) glVertex2fv(p2) glVertex2fv(p3) glEnd() p5 = (120, 60) p6 = (290, 90) p7 = (225, 155) p8 = (60, 113) quad_(p5, p6, p7, p8) glfw.swap_buffers(window) glfw.poll_events() glfw.terminate()
def main(): if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) # Set opengl clear color to something other than red (color used by the fragment shader) glClearColor(0.0,0.0,0.4,0.0) # Enable depth test glEnable(GL_DEPTH_TEST); # Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) program_id = common.LoadShaders( ".\\shaders\\Tutorial5\\TransformVertexShader.vertexshader", ".\\shaders\\Tutorial5\\TextureFragmentShader.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP"); # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units projection = mat4.perspective(45.0, 4.0 / 3.0, 0.1, 100.0) # Camera matrix view = mat4.lookat(vec3(4,3,-3), # Camera is at (4,3,3), in World Space vec3(0,0,0), # and looks at the origin vec3(0,1,0)) # Model matrix : an identity matrix (model will be at the origin) model = mat4.identity() # Our ModelViewProjection : multiplication of our 3 matrices mvp = projection * view * model texture = load_image(".\\content\\uvtemplate.bmp") texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. # A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices vertex_data = [ -1.0,-1.0,-1.0, -1.0,-1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0, 1.0,-1.0, 1.0,-1.0, 1.0, -1.0,-1.0, 1.0, -1.0,-1.0,-1.0, -1.0, 1.0, 1.0, -1.0,-1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0,-1.0, 1.0, 1.0,-1.0, 1.0,-1.0,-1.0, 1.0, 1.0, 1.0, 1.0,-1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,-1.0, -1.0, 1.0,-1.0, 1.0, 1.0, 1.0, -1.0, 1.0,-1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0,-1.0, 1.0] # Two UV coordinatesfor each vertex. They were created withe Blender. uv_data = [ 0.000059, 1.0-0.000004, 0.000103, 1.0-0.336048, 0.335973, 1.0-0.335903, 1.000023, 1.0-0.000013, 0.667979, 1.0-0.335851, 0.999958, 1.0-0.336064, 0.667979, 1.0-0.335851, 0.336024, 1.0-0.671877, 0.667969, 1.0-0.671889, 1.000023, 1.0-0.000013, 0.668104, 1.0-0.000013, 0.667979, 1.0-0.335851, 0.000059, 1.0-0.000004, 0.335973, 1.0-0.335903, 0.336098, 1.0-0.000071, 0.667979, 1.0-0.335851, 0.335973, 1.0-0.335903, 0.336024, 1.0-0.671877, 1.000004, 1.0-0.671847, 0.999958, 1.0-0.336064, 0.667979, 1.0-0.335851, 0.668104, 1.0-0.000013, 0.335973, 1.0-0.335903, 0.667979, 1.0-0.335851, 0.335973, 1.0-0.335903, 0.668104, 1.0-0.000013, 0.336098, 1.0-0.000071, 0.000103, 1.0-0.336048, 0.000004, 1.0-0.671870, 0.336024, 1.0-0.671877, 0.000103, 1.0-0.336048, 0.336024, 1.0-0.671877, 0.335973, 1.0-0.335903, 0.667969, 1.0-0.671889, 1.000004, 1.0-0.671847, 0.667979, 1.0-0.335851] vertex_buffer = glGenBuffers(1); array_type = GLfloat * len(vertex_data) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4, array_type(*vertex_data), GL_STATIC_DRAW) uv_buffer = glGenBuffers(1); array_type = GLfloat * len(uv_data) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4, array_type(*uv_data), GL_STATIC_DRAW) while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT) glUseProgram(program_id) # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) # Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); # Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(texture_id, 0); #1rst attribute buffer : vertices glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glVertexAttribPointer( 0, # attribute 0. No particular reason for 0, but must match the layout in the shader. 3, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # 2nd attribute buffer : colors glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer); glVertexAttribPointer( 1, # attribute 0. No particular reason for 0, but must match the layout in the shader. 2, # len(vertex_data) GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangle ! glDrawArrays(GL_TRIANGLES, 0, 12*3) #3 indices starting at 0 -> 1 triangle # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() # note braces around vertex_buffer and vertex_array_id. # These 2 functions expect arrays of values glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()
def main(): global shader vertex_src = """ # version 330 layout(location = 0) in vec3 a_position; layout(location = 1) in vec2 a_texture; layout(location = 2) in vec3 a_color; uniform mat4 model; uniform mat4 projection; uniform mat4 view; out vec3 v_color; out vec2 v_texture; void main() { gl_Position = projection * view * model * vec4(a_position, 1.0); v_texture = a_texture; v_color = a_color; } """ fragment_src = """ # version 330 in vec2 v_texture; in vec3 v_color; out vec4 out_color; uniform int switcher; uniform sampler2D s_texture; void main() { if (switcher == 0){ out_color = texture(s_texture, v_texture); } else if (switcher == 1){ out_color = vec4(v_color, 1.0); } } """ # initializing glfw library if not glfw.init(): raise Exception("glfw can not be initialized!") if "Windows" in pltf.platform(): glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) else: glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # creating the window window = glfw.create_window(1280, 720, "My OpenGL window", None, None) # check if window was created if not window: glfw.terminate() raise Exception("glfw window can not be created!") # set window's position glfw.set_window_pos(window, 100, 100) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize) # make the context current glfw.make_context_current(window) cube_vertices = [ -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 1.0, -0.5, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0 ] cube_indices = [ 0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14, 14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20 ] cube_vertices = np.array(cube_vertices, dtype=np.float32) cube_indices = np.array(cube_indices, dtype=np.uint32) quad_vertices = [ -0.5, -0.5, 0, 0.0, 0.0, 0.5, -0.5, 0, 1.0, 0.0, 0.5, 0.5, 0, 1.0, 1.0, -0.5, 0.5, 0, 0.0, 1.0 ] quad_indices = [0, 1, 2, 2, 3, 0] quad_vertices = np.array(quad_vertices, dtype=np.float32) quad_indices = np.array(quad_indices, dtype=np.uint32) triangle_vertices = [ -0.5, -0.5, 0, 1, 0, 0, 0.5, -0.5, 0, 0, 1, 0, 0.0, 0.5, 0, 0, 0, 1 ] triangle_vertices = np.array(triangle_vertices, dtype=np.float32) # Cube VAO cube_VAO = glGenVertexArrays(1) glBindVertexArray(cube_VAO) shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # Cube Vertex Buffer Object cube_VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, cube_VBO) glBufferData(GL_ARRAY_BUFFER, cube_vertices.nbytes, cube_vertices, GL_STATIC_DRAW) # Cube Element Buffer Object cube_EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cube_EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, cube_indices.nbytes, cube_indices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube_vertices.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube_vertices.itemsize * 5, ctypes.c_void_p(12)) # glBindVertexArray(0) # Quad VAO quad_VAO = glGenVertexArrays(1) glBindVertexArray(quad_VAO) # Quad Vertex Buffer Object quad_VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, quad_VBO) glBufferData(GL_ARRAY_BUFFER, quad_vertices.nbytes, quad_vertices, GL_STATIC_DRAW) # Quad Element Buffer Object quad_EBO = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, quad_EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, quad_indices.nbytes, quad_indices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube_vertices.itemsize * 5, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube_vertices.itemsize * 5, ctypes.c_void_p(12)) # glBindVertexArray(0) # Triangle VAO triangle_VAO = glGenVertexArrays(1) glBindVertexArray(triangle_VAO) # Triangle Vertex Buffer Object triangle_VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, triangle_VBO) glBufferData(GL_ARRAY_BUFFER, triangle_vertices.nbytes, triangle_vertices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, triangle_vertices.itemsize * 6, ctypes.c_void_p(0)) glEnableVertexAttribArray(2) glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, triangle_vertices.itemsize * 6, ctypes.c_void_p(12)) # glBindVertexArray(0) textures = glGenTextures(2) cube_texture = load_texture("textures/crate.jpg", textures[0]) quad_texture = load_texture("textures/cat.png", textures[1]) glUseProgram(shader) glClearColor(0, 0.1, 0.1, 1) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) projection = pyrr.matrix44.create_perspective_projection_matrix( 45, 1280 / 720, 0.1, 100) cube_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([1, 0, 0])) quad_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([-1, 0, 0])) triangle_pos = pyrr.matrix44.create_from_translation( pyrr.Vector3([0, 1, -1])) # eye, target, up view = pyrr.matrix44.create_look_at(pyrr.Vector3([0, 0, 3]), pyrr.Vector3([0, 0, 0]), pyrr.Vector3([0, 1, 0])) model_loc = glGetUniformLocation(shader, "model") proj_loc = glGetUniformLocation(shader, "projection") view_loc = glGetUniformLocation(shader, "view") switcher_loc = glGetUniformLocation(shader, "switcher") glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) glUseProgram(0) # the main application loop while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glUseProgram(shader) glUniform1i(switcher_loc, 0) rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time()) rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time()) rotation = pyrr.matrix44.multiply(rot_x, rot_y) model = pyrr.matrix44.multiply(rotation, cube_pos) glBindVertexArray(cube_VAO) glBindTexture(GL_TEXTURE_2D, textures[0]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(cube_indices), GL_UNSIGNED_INT, None) model = pyrr.matrix44.multiply(rot_x, quad_pos) glBindVertexArray(quad_VAO) glBindTexture(GL_TEXTURE_2D, textures[1]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawElements(GL_TRIANGLES, len(quad_indices), GL_UNSIGNED_INT, None) model = pyrr.matrix44.multiply(rot_y, triangle_pos) glBindVertexArray(triangle_VAO) glUniform1i(switcher_loc, 1) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawArrays(GL_TRIANGLES, 0, 3) glUseProgram(0) glfw.swap_buffers(window) # terminate glfw, free up allocated resources glfw.terminate()
def main(): if not glfw.init(): print('Failed to initialize glfw!') return glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 0) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) win = glfw.create_window(640, 480, 'bezier', None, None) if not win: print('Failed to create glfw window!') glfw.terminate() return glfw.make_context_current(win) ctx = moderngl.create_context() prog = ctx.program(vertex_shader=''' #version 400 core in vec2 in_pos; void main() { gl_Position = vec4(in_pos, 0.0, 1.0); } ''', tess_control_shader=''' #version 400 core layout(vertices = 4) out; void main() { // set tesselation levels, TODO compute dynamically gl_TessLevelOuter[0] = 1; gl_TessLevelOuter[1] = 32; // pass through vertex positions gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; } ''', tess_evaluation_shader=''' #version 400 core layout(isolines, fractional_even_spacing, ccw) in; // compute a point on a bezier curve with the points p0, p1, p2, p3 // the parameter u is in [0, 1] and determines the position on the curve vec3 bezier(float u, vec3 p0, vec3 p1, vec3 p2, vec3 p3) { float B0 = (1.0 - u) * (1.0 - u) * (1.0 - u); float B1 = 3.0 * (1.0 - u) * (1.0 - u) * u; float B2 = 3.0 * (1.0 - u) * u * u; float B3 = u * u * u; return B0 * p0 + B1 * p1 + B2 * p2 + B3 * p3; } void main() { float u = gl_TessCoord.x; vec3 p0 = vec3(gl_in[0].gl_Position); vec3 p1 = vec3(gl_in[1].gl_Position); vec3 p2 = vec3(gl_in[2].gl_Position); vec3 p3 = vec3(gl_in[3].gl_Position); gl_Position = vec4(bezier(u, p0, p1, p2, p3), 1.0); } ''', fragment_shader=''' #version 400 core out vec4 frag_color; void main() { frag_color = vec4(1.0); } ''') # four vertices define a cubic Bézier curve; has to match the shaders ctx.patch_vertices = 4 ctx.line_width = 5.0 vertices = np.array([ [-1.0, 0.0], [-0.5, 1.0], [0.5, -1.0], [1.0, 0.0], ]) vbo = ctx.buffer(vertices.astype('f4').tobytes()) vao = ctx.simple_vertex_array(prog, vbo, 'in_pos') while not glfw.window_should_close(win): width, height = glfw.get_window_size(win) ctx.viewport = (0, 0, width, height) ctx.clear(0.2, 0.4, 0.7) vao.render(mode=moderngl.PATCHES) glfw.swap_buffers(win) glfw.poll_events() glfw.terminate()
def close(self): self.alive=False glfw.terminate()
def __init__(self, simulator, snapshot, nlines, window_name, width, height, font_path="microsim/opencl/fonts/RobotoMono.ttf"): """Create the window, imgui renderer, and all background renderers. Args: nplaces: Number of places being simulated. npeople: Number of people being simulated. nlines: Number of connection lines to draw per person (recommend low, must be < nslots). window_name: The name to display on the application window. width: Initial width of the window in screen coordinates. height: Initial height of the window in screen coordinates. font_path: Path the the .ttf file to use for text in imgui. """ nplaces = simulator.nplaces npeople = simulator.npeople device = simulator.device_name() platform = simulator.platform_name() if not glfw.init(): raise OSError("Could not initialize window") 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, glfw.TRUE) window = glfw.create_window(width, height, window_name, None, None) if not window: glfw.terminate() raise OSError("Could not initialize window") glfw.make_context_current(window) imgui.create_context() impl = GlfwRenderer(window) glfw.set_framebuffer_size_callback(window, self.resize_callback) glfw.set_key_callback(window, self.key_callback) font = imgui.get_io().fonts.add_font_from_file_ttf(font_path, 56) impl.refresh_font_texture() # vertices representing corners of the screen quad_vertices = np.array([ -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, -1.0, ], dtype=np.float32) # Create vertex buffers on the GPU quad_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, quad_vbo) glBufferData(GL_ARRAY_BUFFER, 4 * 2 * 6, quad_vertices, GL_STATIC_DRAW) locations_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, locations_vbo) glBufferData(GL_ARRAY_BUFFER, 4 * 2 * nplaces, None, GL_STATIC_DRAW) hazards_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, hazards_vbo) glBufferData(GL_ARRAY_BUFFER, 4 * nplaces, None, GL_DYNAMIC_DRAW) links_ebo = glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, links_ebo) glBufferData(GL_ELEMENT_ARRAY_BUFFER, 4 * 2 * npeople * nlines, None, GL_STATIC_DRAW) # Set up the vao for the point shader point_vao = glGenVertexArrays(1) glBindVertexArray(point_vao) glBindBuffer(GL_ARRAY_BUFFER, locations_vbo) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * 4, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, hazards_vbo) glVertexAttribIPointer(1, 1, GL_UNSIGNED_INT, 4, None) glEnableVertexAttribArray(1) # Set up the vao for the line shader line_vao = glGenVertexArrays(1) glBindVertexArray(line_vao) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, links_ebo) glBindBuffer(GL_ARRAY_BUFFER, locations_vbo) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * 4, None) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, hazards_vbo) glVertexAttribIPointer(1, 1, GL_UNSIGNED_INT, 4, None) glEnableVertexAttribArray(1) # Set up the vao for the quad quad_vao = glGenVertexArrays(1) glBindVertexArray(quad_vao) glBindBuffer(GL_ARRAY_BUFFER, quad_vbo) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * 4, None) glEnableVertexAttribArray(0) glBindVertexArray(0) # Load and compile shaders places_program = load_shader("places") grid_program = load_shader("grid") # Enable OpenGL features glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # Initialise Camera position position = np.array([0.0, 0.0, 0.05], dtype=np.float32) # Imgui styling style = imgui.get_style() set_styles(style) # Make a guess on font size font_scale = 0.5 self.update_font_scale(font_scale) # Initialise viewport based on framebuffer width, height = glfw.get_framebuffer_size(window) glViewport(0, 0, width, height) self.simulator = simulator self.snapshot = snapshot self.initial_state_snapshot = copy.deepcopy(snapshot) self.params = Params.fromarray(snapshot.buffers.params) self.nplaces = nplaces self.npeople = npeople self.nlines = nlines self.width = width self.height = height self.platform = platform self.device = device self.window = window self.first = True self.impl = impl self.font = font self.font_scale = font_scale self.simulation_active = False self.do_lockdown = False self.point_size = 2.0 self.show_grid = True self.show_points = True self.show_lines = False self.show_parameters = False self.show_saveas = False self.spacing = 40.0 self.move_sensitivity = 10.0 self.zoom_multiplier = 1.01 self.position = position self.snapshot_dir = "microsim/opencl/snapshots" self.snapshots = [ f for f in os.listdir(self.snapshot_dir) if f.endswith(".npz") ] self.current_snapshot = self.snapshots.index(f"{snapshot.name}.npz") self.selected_snapshot = self.current_snapshot self.saveas_file = self.snapshots[self.current_snapshot] self.summary = Summary(snapshot, store_detailed_counts=False) self.quad_vbo = quad_vbo self.locations_vbo = locations_vbo self.hazards_vbo = hazards_vbo self.links_ebo = links_ebo self.point_vao = point_vao self.line_vao = line_vao self.quad_vao = quad_vao self.places_program = places_program self.grid_program = grid_program self.upload_hazards(self.snapshot.buffers.place_hazards) self.upload_locations(self.snapshot.buffers.place_coords) self.upload_links(self.snapshot.buffers.people_place_ids)
def __init__(self, file): # save current working directory cwd = os.getcwd() # Initialize the library if not glfw.init(): return # restore cwd os.chdir(cwd) # buffer hints glfw.window_hint(glfw.DEPTH_BITS, 32) # define desired frame rate self.frame_rate = 100 # make a window self.width, self.height = 800, 800 self.aspect = self.width / float(self.height) self.window = glfw.create_window(self.width, self.height, "2D Graphics", None, None) if not self.window: glfw.terminate() return # Make the window's context current glfw.make_context_current(self.window) # create 3D self.scene = Scene(self.width, self.height, file) # initialize GL glViewport(0, 0, self.width, self.height) glEnable(GL_DEPTH_TEST) glEnable(GL_NORMALIZE) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) glLightfv(GL_LIGHT0, GL_POSITION, self.scene.l0_pos) #glShadeModel(GL_FLAT) glClearColor(1.0, 1.0, 0.5, 0.0) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(-1, 1, -1, 1, -100, 100) glMatrixMode(GL_MODELVIEW) gluLookAt(0, 1, 3, 0, self.scene.obj.delta_y, 0, 0, 1, 0) # set window callbacks glfw.set_mouse_button_callback(self.window, self.on_mouse_button) glfw.set_scroll_callback(self.window, self.on_scroll) glfw.set_cursor_pos_callback(self.window, self.mouse_moved) glfw.set_key_callback(self.window, self.on_keyboard) glfw.set_window_size_callback(self.window, self.on_size) self.rotation_speed = 50 self.translation_speed = 20 self.zoom_speed = 100 # exit flag self.exitNow = False # animation flag self.animation = False # rotation flag self.do_rotation = False # translation flag self.do_translate = False # zoom flag self.do_zoom = False # shift flag self.left_shift_pressed = False