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 handle_mouse_button(self, window, button, act, mods): # update button state self._button_left_pressed = \ glfw.get_mouse_button(window, glfw.MOUSE_BUTTON_LEFT) == glfw.PRESS self._button_middle_pressed = \ glfw.get_mouse_button(window, glfw.MOUSE_BUTTON_MIDDLE) == glfw.PRESS self._button_right_pressed = \ glfw.get_mouse_button(window, glfw.MOUSE_BUTTON_RIGHT) == glfw.PRESS # update mouse position x, y = glfw.get_cursor_pos(window) self._last_mouse_x = int(self._scale * x) self._last_mouse_y = int(self._scale * y) if not self.model: return self.gui_lock.acquire() # save info if act == glfw.PRESS: self._last_button = button self._last_click_time = glfw.get_time() self.gui_lock.release()
def render(shader, vao, tex, tex2): gl.glClearColor(0.2, 0.3, 0.3, 0.4) gl.glClear(gl.GL_COLOR_BUFFER_BIT|gl.GL_DEPTH_BUFFER_BIT) gl.glBindTexture(gl.GL_TEXTURE_2D, tex) gl.glUseProgram(shader) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, tex) gl.glUniform1i(gl.glGetUniformLocation(shader, "ourTexture1"), 0) gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(gl.GL_TEXTURE_2D, tex2) gl.glUniform1i(gl.glGetUniformLocation(shader, "ourTexture2"), 1) view = gl.glGetUniformLocation(shader, "view") view_matrix = array([ [0.8, 0, 0, 0], [0, 0.8, 0, 0], [0, 0, 0.8, -4], [0, 0, 0, 1], ]) gl.glUniformMatrix4fv(view, 1, gl.GL_TRUE, view_matrix) projection = gl.glGetUniformLocation(shader, "projection") projection_matrix = get_projection_matrix(45, WINDOW_WIDTH/WINDOW_HEIGHT, 0.1, 100) gl.glUniformMatrix4fv(projection, 1, gl.GL_FALSE, projection_matrix) gl.glBindVertexArray(vao) for idx in range(0, len(CUBEPOSITIONS)): model = gl.glGetUniformLocation(shader, "model") angel = glfw.get_time()%360 model_matrix = get_model_matrix(idx, angel) gl.glUniformMatrix4fv(model, 1, gl.GL_TRUE, model_matrix) gl.glDrawArrays(gl.GL_TRIANGLES, 0, VERTEXS.size) gl.glBindVertexArray(0) gl.glUseProgram(0)
def __init__(self, width=800, height=600, title="aiv"): glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) self.window = glfw.create_window(width, height, title, None, None) glfw.make_context_current(self.window) glfw.swap_interval(1) self.time = glfw.get_time() self.delta_time = 0 self.aspect_ratio = float(width) / float(height)
def render(self): rendertime = time.time() GL.glClearColor(0, 0, 0, 1) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) # active shader program GL.glUseProgram(self.window.shader) # Bind Texture GL.glBindTexture(GL.GL_TEXTURE_2D, self.window.texture); # Create transformations # transform = pyrr.Matrix44().identity() rad = numpy.radians(glfw.get_time() * 50.0) tr_translate = pyrr.matrix44.create_from_translation([0.5, -0.5, 0.0]) tr_scale = pyrr.Matrix44().from_scale([1.5, 1.5, 0.5]) tr_rotation = pyrr.matrix44.create_from_axis_rotation([0.0, 0.0, 1.0], rad) # Applies right to left transform = tr_scale * tr_rotation * tr_translate loc = GL.glGetUniformLocation(self.window.shader, 'transform') GL.glUniformMatrix4fv(loc, 1, GL.GL_FALSE, transform) try: GL.glBindVertexArray(self.VAO) # Draw a triangle # GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3) # draw triangle, starting index of the vertex array, # of vertices (6 = indexData.size), # EBO indexes remain the same (accounts for stride of extra data GL.glDrawElements(GL.GL_TRIANGLES, self.index_size, GL.GL_UNSIGNED_INT, None) finally: # Unbind when we finish GL.glBindVertexArray(0) GL.glUseProgram(0) self.rendertime = 1000 * (time.time() - rendertime)
def main(): glfw.init() window = glfw.create_window( 640, 480, "glfw triangle", None, None ) glfw.make_context_current( window ) glfw.swap_interval( 1 ) glfw.set_key_callback( window, on_key ) while not glfw.window_should_close( window ): # set up model view width, height = glfw.get_framebuffer_size( window ) ratio = width / float(height) gl.glViewport( 0, 0, width, height ) gl.glClear( gl.GL_COLOR_BUFFER_BIT ) gl.glMatrixMode( gl.GL_PROJECTION ) gl.glLoadIdentity() gl.glOrtho( -ratio, ratio, -1.0, 1.0, 1.0, -1.0 ) gl.glMatrixMode( gl.GL_MODELVIEW ) gl.glLoadIdentity() gl.glRotatef( float(glfw.get_time()) * 50.0, 0.0, 0.0, 1.0 ) # draw triangle gl.glBegin(gl.GL_TRIANGLES); gl.glColor3f( 1.0, 0.0, 0.0 ) gl.glVertex3f( -0.6, -0.4, 0.0 ) gl.glColor3f( 0.0, 1.0, 0.0 ) gl.glVertex3f( 0.6, -0.4, 0.0 ) gl.glColor3f( 0.0, 0.0, 1.0 ) gl.glVertex3f( 0.0, 0.6, 0.0 ) gl.glEnd() # swap buffers glfw.swap_buffers(window) # poll for events glfw.poll_events() glfw.destroy_window(window) glfw.terminate()
def animate(): np.matrix('1,0,0,0; 0,1,0,0; 0,0,1,0;0,0,0,1', np.float32) time.actual_time = glfw.get_time() delta = time.actual_time - time.prev_time x_trans = 0 y_trans = 0 if(delta > 0.01): time.prev_time=time.actual_time cartesian.angle+=1 x_trans = cartesian.radius * np.cos(cartesian.angle*np.pi/180.0) y_trans = cartesian.radius * np.sin(cartesian.angle*np.pi/180.0) trans = tr.translate(x_trans,y_trans,0.0) trans = tr.rotate(0,cartesian.angle,0,trans,True) return trans
async def startmainloop(self) -> None: newtime = glfw.get_time() self.layercontext.dt = newtime - self.layercontext.time self.layercontext.time = newtime self.layermanager: LayerManager = LayerManager(self.programconfig, self.layercontext) ## Async Loop self.asyncloop = asyncio.get_running_loop() self.asyncloop.set_debug(True) ## OSC setup self.oscserver = pythonosc.osc_server.AsyncIOOSCUDPServer( (self.programconfig.oscserveraddress, self.programconfig.oscserverport), self.oscdispatcher, self.asyncloop) self.transport, protocol = await self.oscserver.create_serve_endpoint() while (not glfw.window_should_close(self.window)): self.mainLoop() await asyncio.sleep(0) # Give other tasks a chance self.transport.close()
def main(): if not glfw.init(): return window = glfw.create_window(480, 480, "2015005078-3-1", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) while not glfw.window_should_close(window): glfw.poll_events() th = glfw.get_time() R = np.array([[np.cos(th), -np.sin(th), 0.], [np.sin(th), np.cos(th), 0.], [0., 0., 1.]]) T = np.array([[1., 0., .5], [0., 1., 0.], [0., 0., 1.]]) render(R @ T) glfw.swap_buffers(window) glfw.terminate()
def main(): global gVertexArrayIndexed, gIndexArray if not glfw.init(): return window = glfw.create_window(640,640,'2019061721', None,None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) glfw.swap_interval(1) gVertexArrayIndexed, gIndexArray = createVertexAndIndexArrayIndexed() while not glfw.window_should_close(window): glfw.poll_events() t = glfw.get_time() render(t*50) glfw.swap_buffers(window) glfw.terminate()
def actualizar(window): global tiempo_anterior global carrito global obstaculos global obstaculos1 tiempo_actual = glfw.get_time() tiempo_delta = tiempo_actual - tiempo_anterior carrito.actualizar(window, tiempo_delta) for obstaculo in obstaculos: if obstaculo.vivo: carrito.checar_colisiones(obstaculo) if carrito.colisionando: break for obstaculo1 in obstaculos1: if obstaculo1.vivo: carrito.checar_colisiones1(obstaculo1) if carrito.colisionando: break tiempo_anterior = tiempo_actual
def run(self): # initializer timer glfw.set_time(0.0) time = 0.0 while not glfw.window_should_close(self.window) and not self.exit_now: # update every x seconds now = glfw.get_time() if now - time > 1.0 / self.frame_rate: # update time time = now # clear glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) self.scene.render() glfw.swap_buffers(self.window) # Poll for and process events glfw.poll_events() # end glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(480, 480, "2019061721", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.swap_interval(1) while not glfw.window_should_close(window): glfw.poll_events() t = glfw.get_time() T = np.array([[np.cos(t), -np.sin(t), 0], [np.sin(t), np.cos(t), 0], [0, 0, 1]]) S = np.array([[np.cos(0.5), -np.sin(0.5), .4], [np.sin(0.5), np.cos(0.5), .4], [0., 0., 0.]]) render(T @ S) glfw.swap_buffers(window) glfw.terminate()
def run(self): # initializer timer glfw.set_time(0.0) t = 0.0 self.scene.readObject() while not glfw.window_should_close(self.window) and not self.exitNow: # update every x seconds currT = glfw.get_time() if currT - t > 1.0 / self.frame_rate: # update time t = currT # clear glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # render scene self.scene.render() glfw.swap_buffers(self.window) # Poll for and process events glfw.poll_events() # end glfw.terminate()
def main(): global gComposedM if not glfw.init(): return window = glfw.create_window(480, 480, "2018008395", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.swap_interval(1) while not glfw.window_should_close(window): glfw.poll_events() th = glfw.get_time() R = np.array([[np.cos(th), -np.sin(th), 0.], [np.sin(th), np.cos(th), 0.], [0., 0., 1.]]) render(R) glfw.swap_buffers(window) glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(800, 800, 'my_dog', None, None) if not window: glfw.terminate() return glfw.set_key_callback(window, key_callback) glfw.set_mouse_button_callback(window, button_callback) glfw.make_context_current(window) glfw.set_scroll_callback(window, scroll_callback) global time, speed glfw.swap_interval(1) while not glfw.window_should_close(window): time = glfw.get_time() * 3 * speed glfw.poll_events() render() glfw.swap_buffers(window) glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(640, 640, "2D Trans", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.swap_interval(1) while not glfw.window_should_close(window): glfw.poll_events() t = glfw.get_time() # non uniform scale s = np.sin(t) US = np.array([[s, 0.], [0., s]]) # rotate th = t R = np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]]) # shear a = np.sin(t) S = np.array([[1., a], [0., 1.]]) # identity matrix I = np.identity(2) # render(R @ S) render(S @ R) glfw.swap_buffers(window) glfw.terminate()
def poll_event(self, window): flag = False cur_time = glfw.get_time() del_time = cur_time - self.last_time march = sidle = dive = 0. if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: march = self.speed * del_time elif glfw.get_key(window, glfw.KEY_S) == glfw.PRESS: march = - self.speed * del_time if glfw.get_key(window, glfw.KEY_D) == glfw.PRESS: sidle = self.speed * del_time elif glfw.get_key(window, glfw.KEY_A) == glfw.PRESS: sidle = - self.speed * del_time if glfw.get_key(window, glfw.KEY_SPACE) == glfw.PRESS: dive = self.speed * del_time elif glfw.get_key(window, glfw.KEY_V) == glfw.PRESS: dive = - self.speed * del_time if march or sidle or dive: self.translate(march, sidle, dive) flag = True cur_mx, cur_my = glfw.get_cursor_pos(window) if glfw.get_mouse_button(window, glfw.MOUSE_BUTTON_RIGHT) == glfw.PRESS: del_mx, del_my = cur_mx - self.last_mx, cur_my - self.last_my spin = tilt = 0. if del_mx: spin = self.rev * del_mx * del_time # self.spin += self.rev * del_mx if del_my: tilt = self.rev * del_my * del_time if spin or tilt: self.rotate(spin, tilt) flag = True self.last_mx, self.last_my = cur_mx, cur_my self.last_time = cur_time if flag: self._update_orientation() self._update_view_mat()
def run(self): # Enable depth test glEnable(GL_DEPTH_TEST) # Accept fragment if it closer to the camera than the former one #glDepthFunc(GL_LESS) # Cull triangles which normal is not towards the camera #glEnable(GL_CULL_FACE) lastFrame = 0 while not glfw.window_should_close(self.window): # Render here, e.g. using pyOpenGL glClearColor(0, 0, 0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) for shader in self._shaders: self.render(shader) # Swap front and back buffers glfw.swap_buffers(self.window) # Poll for and process events #glfw.poll_events() if self.event: currentFrame = glfw.get_time() deltaTime = currentFrame - lastFrame lastFrame = currentFrame # Poll for and process events glfw.poll_events() self.event.do_movement(deltaTime) else: glfw.poll_events() glBindVertexArray(0) glUseProgram(0) glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(640, 640, "2D Trans", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.swap_interval(1) while not glfw.window_should_close(window): glfw.poll_events() t = glfw.get_time() s = np.sin(t) T = np.array([[s, 0.], [0., s]]) render(T) glfw.swap_buffers(window) glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(480, 480, "2016025105", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.swap_interval(1) while not glfw.window_should_close(window): glfw.poll_events() t = glfw.get_time() s = np.sin(t) c = np.cos(t) M = np.array([[c, -s, 0.], [s, c, 0.], [0., 0., 1.]]) S = np.array([[1., 0., 0.5], [0., 1., 0.], [0., 0., 1.]]) render(M @ S) glfw.swap_buffers(window) glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(480, 480, "학번-5-1", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.swap_interval(1) while not glfw.window_should_close(window): glfw.poll_events() t = glfw.get_time() th = t T = np.array([[np.cos(th), -np.sin(th), 0.], [np.sin(th), np.cos(th), 0.], [0., 0., 1.]]) R = np.array([[1, 0., 0.5], [0., 1., 0], [0., 0., 1]]) render(T @ R) glfw.swap_buffers(window) glfw.terminate()
def window_main_loop(self): glClearColor(*self.background_color.get_value()) # glClearDepth(1.0) # glPointSize(5) if self.depth_mode: glEnable(GL_DEPTH_TEST) if self.alpha_mode: glEnable(GL_BLEND) # 使透明生效 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # 使透明生效 if self.stencil_mode: glEnable(GL_STENCIL_TEST) self.last_time = glfw.get_time() self.mouse_scroll_value = 0 for function_name in self.start: if not function_name(): raise RuntimeError('Start Function: ' + function_name.__name__ + ' runtime error') while not glfw.window_should_close(self.window): self.draw() glfw.swap_buffers(self.window) glfw.poll_events() glfw.terminate() # 终止 glfw
def draw(): gl.glClearColor(0.2, 0.3, 0.3, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) shaderProgram.use() vao.bind() # update shader uniform timeValue = glfw.get_time() greenValue = np.sin(timeValue) / 2.0 + 0.5 vertexColorLocation = gl.glGetUniformLocation(shaderProgram.Program, "ourColor") vertexOffsetLocation = gl.glGetUniformLocation(shaderProgram.Program, "offset") gl.glUniform4f(vertexColorLocation, 0.0, greenValue, 0.0, 1.0) gl.glUniform1f(vertexOffsetLocation, 0.3) gl.glDrawElements(gl.GL_TRIANGLES, 3 * indices.shape[0], gl.GL_UNSIGNED_INT, None) vao.unbind() glfw.swap_buffers(window)
def main(): if not glfw.init(): return window = glfw.create_window(480, 480, "2017029570-5-1", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.swap_interval(1) while not glfw.window_should_close(window): glfw.poll_events() t = glfw.get_time() M = np.array([[np.cos(t), -np.sin(t)], [np.sin(t), np.cos(t)]]) render(M) glfw.swap_buffers(window) glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(480, 480, "2017029807-3-2", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) # set the number of screen refresh to wait before calling glfw.swap_buffer(). # if your monitor refresh rate is 60Hz, the while loop is repeated every 1/60 sec glfw.swap_interval(1) while not glfw.window_should_close(window): glfw.poll_events() # get the current time, in seconds t = glfw.get_time() render(gComposedM) glfw.swap_buffers(window) glfw.terminate()
def key_callback(window, key, scancode, action, mods): last_frame_time = glfw.get_time() if key == glfw.KEY_W: acceleration_input = 2 lateral_friction_factor = 10 backwards_friction_factor = 10 rightVector = pyrr.vector3.cross(car.headVector, car.upVector) lateral_velocity = rightVector * pyrr.vector3.dot(car.velocityVector, rightVector) lateral_friction = -lateral_velocity * lateral_friction_factor backwards_friction = -car.velocityVector * backwards_friction_factor car.velocityVector = car.velocityVector + (backwards_friction + lateral_friction) * (glfw.get_time() - last_frame_time) car.accelerationVector = car.headVector * acceleration_input car.velocityVector = car.velocityVector + car.accelerationVector * (glfw.get_time() - last_frame_time) car.positionVector = car.positionVector + car.velocityVector + (glfw.get_time() - last_frame_time) if key == glfw.KEY_S: acceleration_input = -2 lateral_friction_factor = 1000 backwards_friction_factor = 1000 rightVector = pyrr.vector3.cross(car.headVector, car.upVector) lateral_velocity = rightVector * pyrr.vector3.dot(car.velocityVector, rightVector) lateral_friction = -lateral_velocity * lateral_friction_factor backwards_friction = -car.velocityVector * backwards_friction_factor car.velocityVector = car.velocityVector + (backwards_friction + lateral_friction) * ( glfw.get_time() - last_frame_time) car.accelerationVector = car.headVector * acceleration_input car.velocityVector = car.velocityVector + car.accelerationVector * (glfw.get_time() - last_frame_time) car.positionVector = car.positionVector + car.velocityVector + (glfw.get_time() - last_frame_time) if key == glfw.KEY_D: car.turn_right() if key == glfw.KEY_A: car.turn_left()
def __init__(self, address, camera, space, width, height, lock): # Create GLFW window if not glfw.init(): raise RuntimeError('Failed to initialize GLFW!') 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) self.window = glfw.create_window(width, height, 'Axuy', None, None) if not self.window: glfw.terminate() raise RuntimeError('Failed to create GLFW window!') self.camera = camera self.picos = {address: camera} self.colors = {address: choice(COLOR_NAMES)} self.last_time = glfw.get_time() self.lock = lock # Window's rendering and event-handling configuration glfw.set_window_icon(self.window, 1, Image.open(abspath('icon.png'))) glfw.make_context_current(self.window) glfw.swap_interval(1) glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.set_input_mode(self.window, glfw.STICKY_KEYS, True) glfw.set_cursor_pos_callback(self.window, self.camera.look) self.fov = FOV_INIT glfw.set_scroll_callback(self.window, self.zoom) glfw.set_mouse_button_callback(self.window, self.shoot) # Create OpenGL context self.context = context = moderngl.create_context() context.enable(moderngl.BLEND) context.enable(moderngl.DEPTH_TEST) self.space, vertices = space, [] for (x, y, z), occupied in np.ndenumerate(self.space): if self.space[x][y][z - 1] ^ occupied: vertices.extend(i + j for i, j in product(neighbors(x, y, z), OXY)) if self.space[x - 1][y][z] ^ occupied: vertices.extend(i + j for i, j in product(neighbors(x, y, z), OYZ)) if self.space[x][y - 1][z] ^ occupied: vertices.extend(i + j for i, j in product(neighbors(x, y, z), OZX)) self.maprog = context.program(vertex_shader=MAP_VERTEX, fragment_shader=MAP_FRAGMENT) self.maprog['bg'].write(color('Background').tobytes()) self.maprog['color'].write(color('Aluminium').tobytes()) mapvb = context.buffer(np.stack(vertices).astype(np.float32).tobytes()) self.mapva = context.simple_vertex_array(self.maprog, mapvb, 'in_vert') self.prog = context.program(vertex_shader=PICO_VERTEX, fragment_shader=PICO_FRAGMENT) pvb = [(context.buffer(TETRAVERTICES.tobytes()), '3f', 'in_vert')] pib = context.buffer(TETRAINDECIES.tobytes()) self.pva = context.vertex_array(self.prog, pvb, pib) svb = [(context.buffer(OCTOVERTICES.tobytes()), '3f', 'in_vert')] sib = context.buffer(OCTOINDECIES.tobytes()) self.sva = context.vertex_array(self.prog, svb, sib)
g_shadowShader = shadow.buildShadowShader() treeSample = random.sample(g_terrain.treeLocations, 25) rockSample = random.sample(g_terrain.rockLocations, 25) g_racer = Racer() g_racer.load("data/racer_02.obj", g_terrain, g_renderingSystem) propManager = PropManager(g_terrain) for t in treeSample: g_props.append(propManager.createTreeProp(g_terrain, g_renderingSystem, t)) for r in rockSample: g_props.append(propManager.createRockProp(g_terrain, g_renderingSystem, r)) # here we'll implement the grass texture loading//etc.. # I may place this code in a helper function in the future currentTime = glfw.get_time() prevMouseX, prevMouseY = glfw.get_cursor_pos(window) while not glfw.window_should_close(window): prevTime = currentTime currentTime = glfw.get_time() dt = currentTime - prevTime keyStateMap = {} for name, id in g_glfwKeymap.items(): keyStateMap[name] = glfw.get_key(window, id) == glfw.PRESS for name, id in g_glfwMouseMap.items(): keyStateMap[name] = glfw.get_mouse_button(window, id) == glfw.PRESS imgui.new_frame()
def main(): # initialize glfw if not glfw.init(): return window = glfw.create_window(1000, 1000, "My OpenGL window", None, None) #window.visible = False if not window: glfw.terminate() return glfw.make_context_current(window) # positions colors texture coords cube = [ -0.5, -0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, -0.5, -0.5, -0.5, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -0.5, 0.5, -0.5, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.5, -0.5, -0.5, 1.0, 1.0, 1.0, 0.0, 0.0, 2.0, 0.5, 0.5, -0.5, 1.0, 1.0, 1.0, 1.0, 0.0, 2.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 0.5, -0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0, 2.0, -0.5, 0.5, -0.5, 1.0, 1.0, 1.0, 0.0, 0.0, 3.0, -0.5, -0.5, -0.5, 1.0, 1.0, 1.0, 1.0, 0.0, 3.0, -0.5, -0.5, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 3.0, -0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0, 3.0, -0.5, -0.5, -0.5, 1.0, 1.0, 1.0, 0.0, 0.0, 4.0, 0.5, -0.5, -0.5, 1.0, 1.0, 1.0, 1.0, 0.0, 4.0, 0.5, -0.5, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 4.0, -0.5, -0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0, 4.0, 0.5, 0.5, -0.5, 1.0, 1.0, 1.0, 0.0, 0.0, 5.0, -0.5, 0.5, -0.5, 1.0, 1.0, 1.0, 1.0, 0.0, 5.0, -0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 5.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 0.0, 1.0, 5.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) vec3 color; in layout(location = 2) vec2 textureCoords; in layout(location = 3) float textureid; uniform mat4 transform; uniform mat4 proj; out vec3 newColor; out vec2 newTexture; out float newtextureid; void main() { gl_Position = proj * transform * vec4(position, 1.0f); newColor = color; newTexture = textureCoords; newtextureid = textureid; } """ fragment_shader = """ #version 330 #extension GL_EXT_texture_array : enable in vec3 newColor; in vec2 newTexture; in float newtextureid; uniform sampler2DArray samplerTexture; out vec3 outColor; void main() { outColor = (texture(samplerTexture, vec3(newTexture, newtextureid)) * vec4(newColor, 1.0f)).rgb; //outColor = texture(samplerTexture, newTexture) * 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, 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 * 9, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #color glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 9, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) #texture glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 9, ctypes.c_void_p(24)) glEnableVertexAttribArray(2) #textureid glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, cube.itemsize * 9, ctypes.c_void_p(32)) glEnableVertexAttribArray(3) loadTextures() """ texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) # Set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) # Set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) # load image image = Image.open("res/crate.jpg") img_data = numpy.array(list(image.getdata()), numpy.uint8) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data) """ glUseProgram(shader) glClearColor(0.2, 0.2, 0.2, 1.0) glShadeModel(GL_SMOOTH) glEnable(GL_DEPTH_TEST) LightAmbient = [0.5, 0.5, 0.5, 1.0] LightDiffuse = [0.5, 0.5, 0.5, 1.0] LightPosition = [5.0, 25.0, 15.0, 1.0] glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient) glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse) glLightfv(GL_LIGHT1, GL_POSITION, LightPosition) glEnable(GL_LIGHTING) glEnable(GL_LIGHT1) #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) (xa, ya, za) = (0, 0, 0) while not glfw.window_should_close(window): (w, h) = glfw.get_window_size(window) glfw.poll_events() #time.sleep(0.2) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #(xa,ya,za) = (12,45,77) #(xa,ya,za) = numpy.random.uniform(size=3)*360.0 (xa, ya, za) = numpy.array([0.8, 0.3, 0.2]) * glfw.get_time() (xa, ya, za) = (xa % 2 * math.pi, ya % 2 * math.pi, za % 2 * math.pi) rot_x = pyrr.Matrix44.from_x_rotation(xa) rot_y = pyrr.Matrix44.from_y_rotation(ya) rot_z = pyrr.Matrix44.from_z_rotation(za) rot = rot_x * rot_y * rot_z (dx, dy, dz) = (0.0, 0.0, -2.0) #(dx,dy,dz) = numpy.random.uniform(-0.5,0.5,size=3) trans = pyrr.matrix44.create_from_translation([dx, dy, dz]) proj = pyrr.matrix44.create_perspective_projection_matrix( 80.0, 1.0, 0.01, 1000.0) transf = numpy.array(rot.dot(trans)) transformLoc = glGetUniformLocation(shader, "transform") projLoc = glGetUniformLocation(shader, "proj") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, transf) glUniformMatrix4fv(projLoc, 1, GL_FALSE, proj) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glfw.swap_buffers(window) pixels = glReadPixelsui(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE) im = numpy.frombuffer(pixels, dtype='uint8').reshape(h, w, 3) im = cv2.flip(im, 0) pm = numpy.array([[w, 0, w / 2], [0, h, h / 2], [0, 0, 1]]) dist = numpy.array([0.0, 0.0, 0.0, 0.0]).reshape(4, 1) ra = numpy.array([xa, ya, za]) * 360.0 / math.pi detectTag(im, pm, dist, ra) glfw.terminate()
def draw(self, projection, view, model, **param): """ When redraw requested, interpolate our node transform from keys """ self.transform = self.keyframes.value(glfw.get_time()) super().draw(projection, view, model, **param)
def main(): # comenzar glfw if not glfw.init(): return aspect_ratio = wwidth / wheight #creamos la ventana window = glfw.create_window(wwidth, wheight, "ProyectoGraficas", None, None) #terminar ventana if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_window_size_callback(window, window_resize) glfw.set_key_callback(window, key_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) #carbamos el primer ObjLoader casa = ObjLoader() #buscamos el objeto en nuestras carpetas casa.load_model("obj/casa2.obj") #buscamos la textura en nuestras carpetas casa_tex = TextureLoader.load_texture("obj/pared.jpg") #calculamos casa_texture_offset = len(casa.vertex_index) * 12 #cargamos el segundo objeto monster = ObjLoader() #buscamos el obj en nuestras carpetas monster.load_model("obj/monster.obj") #buscamos la textura en nuestras carpetas monster_tex = TextureLoader.load_texture("obj/monster.jpg") #calculamos monster_texture_offset = len(monster.vertex_index) * 12 #obtenemos los shaders de nuestras carpetas. generic_shader = ShaderLoader.compile_shader( "shaders/generic_vertex_shader.vs", "shaders/generic_fragment_shader.fs") #------------------------------------casa--------------------------------------------------------------------------# #generamos nestras variaml casavao = glGenVertexArrays(1) glBindVertexArray(casavao) casavbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, casavbo) glBufferData(GL_ARRAY_BUFFER, casa.model.itemsize * len(casa.model), casa.model, GL_STATIC_DRAW) #posicion glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, casa.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #Texturas glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, casa.model.itemsize * 2, ctypes.c_void_p(casa_texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) #-------------------------------------------------------------------------------------------------------------------- #-------------------------------------------------------monstruo------------------------------------------------------# monster_vao = glGenVertexArrays(1) glBindVertexArray(monster_vao) monster_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, monster_vbo) glBufferData(GL_ARRAY_BUFFER, monster.model.itemsize * len(monster.model), monster.model, GL_STATIC_DRAW) #position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monster.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #textures glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monster.model.itemsize * 2, ctypes.c_void_p(monster_texture_offset)) glEnableVertexAttribArray(1) glBindVertexArray(0) #-----------------------------------------------------------------------------------------------------------------------# #colocamos el color negro glClearColor(0, 0, 0, 0) glEnable(GL_DEPTH_TEST) projection = matrix44.create_perspective_projection_matrix( 45.0, aspect_ratio, 0.1, 100.0) #traslacion del vector a la casa2 #colocar en el lugar casaModelo = matrix44.create_from_translation(Vector3([0.0, 0.0, -3.0])) #traslacion en el vectro3 al monstruo #colocar en el lugar monster_model = matrix44.create_from_translation(Vector3([0.0, 0.0, -10.0])) #shaders glUseProgram(generic_shader) model_loc = glGetUniformLocation(generic_shader, "model") view_loc = glGetUniformLocation(generic_shader, "view") proj_loc = glGetUniformLocation(generic_shader, "proj") glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) #mientras la ventana while not glfw.window_should_close(window): glfw.poll_events() do_movement() #colocar la ventada de un color especifico glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) #rotaciones rot_y = Matrix44.from_y_rotation(glfw.get_time() * 0.5) #--------------------------------------casa--------------------------------------# glBindVertexArray(casavao) glBindTexture(GL_TEXTURE_2D, casa_tex) glUniformMatrix4fv(model_loc, 1, GL_FALSE, casaModelo) glDrawArrays(GL_TRIANGLES, 0, len(casa.vertex_index)) glBindVertexArray(0) #--------------------------------------------------------------------------------# #---------------------------------------monstruo----------------------------------# glBindVertexArray(monster_vao) glBindTexture(GL_TEXTURE_2D, monster_tex) glUniformMatrix4fv(model_loc, 1, GL_FALSE, monster_model) glDrawArrays(GL_TRIANGLES, 0, len(monster.vertex_index)) glBindVertexArray(0) #-------------------------------------------------------------------------------------- #buffer de la ventana glfw.swap_buffers(window) #finalizamos glfw.terminate()
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, img_data) glUseProgram(shader) glClearColor(0, 0.2, 0.2, 1) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) #(field of view, aspect ratio,near,far) projection = pyrr.matrix44.create_perspective_projection_matrix( 45, 1280 / 720, 0.1, 100) glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) translation = pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 0, -3])) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) #make rotation matrix 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, translation) #(handle to load to, no. of matrices, transposed # matrix) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) #(mode,no of indices,data_type,offset) glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def init_input(self, window): self.last_mx, self.last_my = glfw.get_cursor_pos(window) self.last_time = glfw.get_time() self.activate_mouse = False
def update(self): glfw.swap_buffers(self.window) glfw.poll_events() time = glfw.get_time() self.delta_time = time - self.time self.time = time
def computeMatricesFromInputs(window): global lastTime global position global horizontalAngle global verticalAngle global initialFoV global ViewMatrix global ProjectionMatrix # glfwGetTime is called only once, the first time this function is called if lastTime == None: lastTime = glfw.get_time() # Compute time difference between current and last frame currentTime = glfw.get_time() deltaTime = currentTime - lastTime # Get mouse position xpos,ypos = glfw.get_cursor_pos(window) # Reset mouse position for next frame glfw.set_cursor_pos(window, 1024/2, 768/2); # Compute new orientation horizontalAngle += mouseSpeed * float(1024.0/2.0 - xpos ); verticalAngle += mouseSpeed * float( 768.0/2.0 - ypos ); # Direction : Spherical coordinates to Cartesian coordinates conversion direction = vec3( mathf.cos(verticalAngle) * mathf.sin(horizontalAngle), mathf.sin(verticalAngle), mathf.cos(verticalAngle) * mathf.cos(horizontalAngle) ) # Right vector right = vec3( mathf.sin(horizontalAngle - 3.14/2.0), 0.0, mathf.cos(horizontalAngle - 3.14/2.0) ) # Up vector up = vec3.cross( right, direction ) # Move forward if glfw.get_key( window, glfw.KEY_UP ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_W ) == glfw.PRESS: position += direction * deltaTime * speed; # Move backward if glfw.get_key( window, glfw.KEY_DOWN ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_S ) == glfw.PRESS: position -= direction * deltaTime * speed # Strafe right if glfw.get_key( window, glfw.KEY_RIGHT ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_D ) == glfw.PRESS: position += right * deltaTime * speed # Strafe left if glfw.get_key( window, glfw.KEY_LEFT ) == glfw.PRESS or glfw.get_key( window, glfw.KEY_A ) == glfw.PRESS: position -= right * deltaTime * speed FoV = initialFoV# - 5 * glfwGetMouseWheel(); # Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead. # Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units ProjectionMatrix = mat4.perspective(FoV, 4.0 / 3.0, 0.1, 100.0) # Camera matrix ViewMatrix = mat4.lookat( position, # Camera is here position+direction, # and looks here : at the same position, plus "direction" up # Head is up (set to 0,-1,0 to look upside-down) ) # For the next frame, the "last time" will be "now" lastTime = currentTime
paddle1.rotation -= 0.1 if glfw.get_key(window, glfw.KEY_J) == glfw.PRESS: paddle2.rotation += 0.1 if glfw.get_key(window, glfw.KEY_L) == glfw.PRESS: paddle2.rotation -= 0.1 square_vertices = np.array( [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]], dtype=np.float32, ) TARGET_FRAMERATE = 60 # fps # to try to standardize on 60 fps, compare times between frames time_at_beginning_of_previous_frame = glfw.get_time() # Loop until the user closes the window while not glfw.window_should_close(window): # poll the time to try to get a constant framerate while (glfw.get_time() < time_at_beginning_of_previous_frame + 1.0 / TARGET_FRAMERATE): pass # set for comparison on the next frame time_at_beginning_of_previous_frame = glfw.get_time() # Poll for and process events glfw.poll_events() width, height = glfw.get_framebuffer_size(window) glViewport(0, 0, width, height)
openvr.VRCompositor().submit(openvr.Eye_Left, hmd.vTex, hmd.boundLeft) openvr.VRCompositor().submit(openvr.Eye_Right, hmd.vTex, hmd.boundRight) # swap if window is double-buffered, flush just in case if ctx.con.windowDoublebuffer: glfw.swap_buffers(window) gl.glFlush() if __name__ == '__main__': filename = os.path.join(mujoco_path, 'model', 'humanoid.xml') v_initPre() initMuJoCo(filename, hmd.width * 2, hmd.height) v_initPost() FPS = 90.0 lasttm = glfw.get_time() frametime = sim.data.time viewFull = PyMjrRect() viewFull.width, viewFull.height = 2 * hmd.width, hmd.height nullCam = PyMjvCamera() while not glfw.window_should_close(window): if sim.data.time - frametime > 1 / FPS or sim.data.time < frametime: functions.mjv_updateScene(sim.model, sim.data, ctx.vopt, ctx.pert, nullCam, CAT_ALL, ctx.scn) v_update() functions.mjr_setBuffer(FB_OFFSCREEN, ctx.con) functions.mjr_render(viewFull, ctx.scn, ctx.con) FPS = .9 * FPS + .1 / (glfw.get_time() - lasttm) lasttm = glfw.get_time() functions.mjr_overlay(FONT_BIG, GRID_BOTTOMLEFT, viewFull, 'FPS %.1f' % FPS, '', ctx.con) v_render()
def main(): # initialize glfw if not glfw.init(): return window = glfw.create_window(800, 800, "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); } """ 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) glUseProgram(shader) glClearColor(0.2, 0.3, 0.2, 1.0) #color 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()) transformLoc = glGetUniformLocation(shader, "transform") glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y) glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, None) glfw.swap_buffers(window) 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 VAO = glGenVertexArrays(3) VBO = glGenBuffers(3) EBO = glGenBuffers(2) # Cube VAO glBindVertexArray(VAO[0]) shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # Cube Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, cube_vertices.nbytes, cube_vertices, GL_STATIC_DRAW) # Cube Element Buffer Object glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[0]) 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)) # Quad VAO glBindVertexArray(VAO[1]) # Quad Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[1]) glBufferData(GL_ARRAY_BUFFER, quad_vertices.nbytes, quad_vertices, GL_STATIC_DRAW) # Quad Element Buffer Object glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO[1]) 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)) # Triangle VAO glBindVertexArray(VAO[2]) # Triangle Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[2]) 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)) 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(VAO[0]) 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(VAO[1]) 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(VAO[2]) 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 handle_movement_of_paddles(): global paddle1, paddle2 if glfw.get_key(window, glfw.KEY_S) == glfw.PRESS: paddle1.input_offset_y -= 0.1 if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: paddle1.input_offset_y += 0.1 if glfw.get_key(window, glfw.KEY_K) == glfw.PRESS: paddle2.input_offset_y -= 0.1 if glfw.get_key(window, glfw.KEY_I) == glfw.PRESS: paddle2.input_offset_y += 0.1 TARGET_FRAMERATE = 60 # fps # to try to standardize on 60 fps, compare times between frames time_at_beginning_of_previous_frame = glfw.get_time() # Loop until the user closes the window while not glfw.window_should_close(window): # poll the time to try to get a constant framerate while glfw.get_time() < time_at_beginning_of_previous_frame + 1.0/TARGET_FRAMERATE: pass # set for comparison on the next frame time_at_beginning_of_previous_frame = glfw.get_time() # Poll for and process events glfw.poll_events() width, height = glfw.get_framebuffer_size(window) glViewport(0, 0, width, height) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
def clearColorSetViewport(r,g,b,a=1.0): glClearColor(r, g, b, a); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, window_width, window_height); if __name__=='__main__': glfw.init() window_width = 640 window_height = 480 win = glfw.create_window(window_width , window_height,"GL", None, None) setGLFWOptions(win) matrixScene.window_width = window_width matrixScene.window_height = window_height time.actual_time = time.previous_time = glfw.get_time() showInfoAboutGl() app = Obj('./models/Cat.obj', 'shaders/13_vertex_shader.glsl', 'shaders/13_fragment_shader.glsl') app.setTexFiltering() while not glfw.window_should_close(win): time.previous_time = time.actual_time; time.actual_time = glfw.get_time(); clearColorSetViewport(0.5,0.1,0.2) app.render() glfw.swap_buffers(win) glfw.poll_events()
# Telling OpenGL to use our shader program glUseProgram(shaderProgram) # Setting up the clear screen color glClearColor(0.85, 0.85, 0.85, 1.0) # Creating shapes on GPU memory gpuQuadBlack = createQuad([0, 0, 0]) gpuQuadWhite = createQuad([1, 1, 1]) # Fill mode Polygon glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) # Get initial time t0 = glfw.get_time() while not glfw.window_should_close(window): # Getting the time difference from the previous iteration t1 = glfw.get_time() dt = t1 - t0 t0 = t1 # Using GLFW to check for input events glfw.poll_events() # Filling or not the shapes depending on the controller state if controller.fillPolygon: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) else: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
def main(): # Initialize GLFW and open a window if not opengl_init(): return # Enable key events glfw.set_input_mode(window,glfw.STICKY_KEYS,GL_TRUE) glfw.set_cursor_pos(window, 1024/2, 768/2) # 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) # Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE) vertex_array_id = glGenVertexArrays(1) glBindVertexArray( vertex_array_id ) # Create and compile our GLSL program from the shaders program_id = common.LoadShaders( "Shaders/Tutorial8/StandardShading.vertexshader", "Shaders/Tutorial8/StandardShading.fragmentshader" ) # Get a handle for our "MVP" uniform matrix_id = glGetUniformLocation(program_id, "MVP") view_matrix_id = glGetUniformLocation(program_id, "V") model_matrix_id = glGetUniformLocation(program_id, "M") # Load the texture texture = load_image("Content/uvmap_suzanne.bmp") # Get a handle for our "myTextureSampler" uniform texture_id = glGetUniformLocation(program_id, "myTextureSampler") # Read our OBJ file vertices,faces,uvs,normals,colors = objloader.load("Content/suzanne.obj") vertex_data,uv_data,normal_data = objloader.process_obj( vertices,faces,uvs,normals,colors) # Our OBJ loader uses Python lists, convert to ctype arrays before sending to OpenGL vertex_data = objloader.generate_2d_ctypes(vertex_data) uv_data = objloader.generate_2d_ctypes(uv_data) normal_data = objloader.generate_2d_ctypes(normal_data) # Load OBJ in to a VBO vertex_buffer = glGenBuffers(1); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer) glBufferData(GL_ARRAY_BUFFER, len(vertex_data) * 4 * 3, vertex_data, GL_STATIC_DRAW) uv_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, uv_buffer) glBufferData(GL_ARRAY_BUFFER, len(uv_data) * 4 * 2, uv_data, GL_STATIC_DRAW) normal_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, normal_buffer) glBufferData(GL_ARRAY_BUFFER, len(normal_data) * 4 * 3, normal_data, GL_STATIC_DRAW) # vsync and glfw do not play nice. when vsync is enabled mouse movement is jittery. common.disable_vsyc() # Get a handle for our "LightPosition" uniform glUseProgram(program_id); light_id = glGetUniformLocation(program_id, "LightPosition_worldspace"); last_time = glfw.get_time() frames = 0 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) current_time = glfw.get_time() if current_time - last_time >= 1.0: glfw.set_window_title(window,"Tutorial 8. FPS: %d"%(frames)) frames = 0 last_time = current_time glUseProgram(program_id) controls.computeMatricesFromInputs(window) ProjectionMatrix = controls.getProjectionMatrix(); ViewMatrix = controls.getViewMatrix(); ModelMatrix = mat4.identity(); mvp = ProjectionMatrix * ViewMatrix * ModelMatrix; # Send our transformation to the currently bound shader, # in the "MVP" uniform glUniformMatrix4fv(matrix_id, 1, GL_FALSE,mvp.data) glUniformMatrix4fv(model_matrix_id, 1, GL_FALSE, ModelMatrix.data); glUniformMatrix4fv(view_matrix_id, 1, GL_FALSE, ViewMatrix.data); lightPos = vec3(4,4,4) glUniform3f(light_id, lightPos.x, lightPos.y, lightPos.z) # 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 1. No particular reason for 1, 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*) ) # 3rd attribute buffer : normals glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normal_buffer); glVertexAttribPointer( 2, # attribute 3, # size GL_FLOAT, # type GL_FALSE, # ormalized? 0, # stride null # array buffer offset (c_type == void*) ) # Draw the triangles, vertex data now contains individual vertices # so use array length glDrawArrays(GL_TRIANGLES, 0, len(vertex_data)) # Not strictly necessary because we only have glDisableVertexAttribArray(0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(2) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() frames += 1 # !Note braces around vertex_buffer and uv_buffer. # glDeleteBuffers expects a list of buffers to delete glDeleteBuffers(1, [vertex_buffer]) glDeleteBuffers(1, [uv_buffer]) glDeleteBuffers(1, [normal_buffer]) glDeleteProgram(program_id) glDeleteTextures([texture_id]) glDeleteVertexArrays(1, [vertex_array_id]) glfw.terminate()