def onRender(self): gl.glDepthMask(gl.GL_TRUE) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluPerspective(45, self.width / self.height, 0.01, 80.0) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glTranslated(0.0, 0.0, -self.camPosZ) # apply camera zooming gl.glRotated(self.angleX, 1.0, 0.0, 0.0) # apply camera rotation gl.glRotated(self.angleY, 0.0, 1.0, 0.0) # draw fountain if self.renderEnv: gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE) gl.glCallList(self.DISPLAY_LIST_OBJECT) gl.glMatrixMode(gl.GL_TEXTURE) # scroll water texture angle = self.totalTime * 2.0 * math.pi / 12000.0 sinA = math.sin(angle) * 0.2 cosA = math.cos(angle) * 0.2 gl.glRotatef(angle, 0.0, 0.0, 1.0) gl.glTranslatef(sinA, cosA, 1.0) gl.glScalef(1.0 + sinA * 0.2, 1.0 + cosA * 0.2, 1.0) # draw bounding box(F2 key) drawBoundingBox(self.group, 1.0, 0.0, 0.0) # draw fountain water if self.renderEnv: gl.glCallList(self.DISPLAY_LIST_WATER) gl.glLoadIdentity() # draw particles self.system.render() # draw texts(F1 key) if not notext and self.text != 0: gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluOrtho2D(0, self.width, 0, self.height) gl.glDisable(gl.GL_DEPTH_TEST) gl.glColor3d(1.0, 1.0, 1.0) if self.text == 2: self.drawText(self.nbParticles, 4.0, 40.0) self.drawText(self.fps, 4.0, 8.0) # refresh sdl2.SDL_GL_SwapWindow(self.window)
def render(self, scene_state): """Render a new frame. Parameters ---------- scene_state : hienoi.renderer.SceneState Scene state. """ renderer_state = hienoi.renderer.State( window_size=self.get_window_size(), view_position=self.view_position, view_zoom=self._view_zoom, origin=self.world_to_screen(Vector2f(0.0, 0.0)), initial_view_aperture_x=self._initial_view_aperture_x, view_aperture=self.get_view_aperture(), grid_density=self.grid_density, grid_adaptive_threshold=self._grid_adaptive_threshold, background_color=self.background_color, grid_color=self.grid_color, grid_origin_color=self.grid_origin_color, show_grid=self.show_grid, particle_display=self.particle_display, point_size=self.point_size, edge_feather=self.edge_feather, stroke_width=self.stroke_width, ) self._renderer.render(renderer_state, scene_state) if hienoi.renderer.get_info().api == GraphicsAPI.OPENGL: sdl2.SDL_GL_SwapWindow(self._handles.window)
def _draw(self): """Draw the next frame.""" GL.glClear(GL.GL_STENCIL_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_COLOR_BUFFER_BIT) # self._menu.draw() self._game.draw() sdl2.SDL_GL_SwapWindow(self._window.window)
def onRender(self): gl.glEnable(gl.GL_DEPTH_TEST) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluPerspective(45, self.width / self.height, 0.01, 80.0) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glTranslated(0.0, 0.0, -self.camPosZ) # apply camera zooming gl.glRotated(self.angleY, 0.0, 1.0, 0.0) # apply camera rotation # draw particles for system in self.systems: system.render() # draw texts(F1 key) if not notext and self.text != 0: gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluOrtho2D(0, self.width, 0, self.height) gl.glDisable(gl.GL_DEPTH_TEST) gl.glColor3d(1.0, 1.0, 1.0) if self.text == 2: self.drawText(self.nbParticles, 4.0, 40.0) self.drawText(self.fps, 4.0, 8.0) # refresh sdl2.SDL_GL_SwapWindow(self.window)
def swap_buffers(self): """ Swap buffers, set viewport, trigger events and increment frame counter """ sdl2.SDL_GL_SwapWindow(self._window) self.set_default_viewport() self.process_events() self._frames += 1
def render(self): try: glViewport(0, 0, self.width, self.height) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glBindVertexArray(self.vaoID) glDrawArrays(GL_TRIANGLES, 0, 3) except OpenGL.error.GLError: print('error') sdl2.SDL_GL_SwapWindow(self.window)
def onRender(self): gl.glEnable(gl.GL_DEPTH_TEST) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluPerspective(45, self.width / self.height, 0.01, 80.0) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glTranslated(0.0, 0.0, -self.camPosZ) # apply camera zooming gl.glRotated(self.angleX, 1.0, 0.0, 0.0) # apply camera rotation gl.glRotated(self.angleY, 0.0, 1.0, 0.0) # draw obstacles if self.renderEnv: gl.glDisable(gl.GL_BLEND) gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE) gl.glCallList(self.DISPLAY_LIST_WORLD) # draw bounding box(F2 key) drawBoundingBox(self.group, 1.0, 0.0, 0.0) # draw outlines of the boxes(F6 key) if self.enableBoxDrawing: for box in self.boxes: # blue for crates drawBox(box.getPosition() - box.getDimension() * 0.5, box.getPosition() + box.getDimension() * 0.5, 0.0, 0.0, 1.0) for box in self.partitions: # green for partitions drawBox(box.getPosition() - box.getDimension() * 0.5, box.getPosition() + box.getDimension() * 0.5, 0.0, 1.0, 0.0) # draw particles gl.glDisable(gl.GL_LIGHTING) self.system.render() # draw texts(F1 key) if not notext and self.text != 0: gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluOrtho2D(0, self.width, 0, self.height) gl.glDisable(gl.GL_DEPTH_TEST) gl.glColor3d(1.0, 1.0, 1.0) if self.text == 2: self.drawText(self.nbParticles, 4.0, 40.0) self.drawText(self.fps, 4.0, 8.0) # refresh sdl2.SDL_GL_SwapWindow(self.window)
def end_update(self): if len(self._pp_steps) > 0: if len(self._pp_steps) > 1: for x in range(1, len(self._pp_steps)): self._pp_steps[x].fbo.bind() self._pp_steps[x - 1].draw(self) self._pp_steps[-1].fbo.unbind() self._pp_steps[-1].draw(self) sdl2.SDL_GL_SwapWindow(self._window)
def _on_update(self, *args): events = sdl2.ext.get_events() for event in events: if event.type == sdl2.SDL_QUIT: self._loop.stop() return # Clear context GL.glClearColor(0, 0, 0, 1) GL.glClear(GL.GL_COLOR_BUFFER_BIT) self.render() sdl2.SDL_GL_SwapWindow(self._window)
def run(): if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 window = sdl2.SDL_CreateWindow(b"OpenGL demo", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 800, 600, sdl2.SDL_WINDOW_OPENGL) if not window: print(sdl2.SDL_GetError()) return -1 context = sdl2.SDL_GL_CreateContext(window) GL.glMatrixMode(GL.GL_PROJECTION | GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glOrtho(-400, 400, 300, -300, 0, 1) x = 0.0 y = 30.0 event = sdl2.SDL_Event() running = True while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False GL.glClearColor(0, 0, 0, 1) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glRotatef(10.0, 0.0, 0.0, 1.0) GL.glBegin(GL.GL_TRIANGLES) GL.glColor3f(1.0, 0.0, 0.0) GL.glVertex2f(x, y + 90.0) GL.glColor3f(0.0, 1.0, 0.0) GL.glVertex2f(x + 90.0, y - 90.0) GL.glColor3f(0.0, 0.0, 1.0) GL.glVertex2f(x - 90.0, y - 90.0) GL.glEnd() sdl2.SDL_GL_SwapWindow(window) sdl2.SDL_Delay(10) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def main(): global rend if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return 0 x, y = 0, 0 # window = sdl2.ext.Window("ekkek", 600,600, sdl2.SDL_WINDOW_OPENGL) window = sdl2.SDL_CreateWindow(TITLE, sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 600, 600, sdl2.SDL_WINDOW_OPENGL) context = sdl2.SDL_GL_CreateContext(window) rend = Renderer() time = sdl2.SDL_GetTicks() prev_time = sdl2.SDL_GetTicks() frame_time = 0 e = ioproc(sdl2.SDL_Event()) dt = 1000. / 60. #while sdl2.SDL_WaitEvent(ctypes.byref(sdl2.SDL_QUIT)): while e.checkEvents(): # time = sdl2.SDL_GetTicks() # frame_time = time - prev_time # prev_time = time # while sdl2.SDL_PollEvent(ctypes.byref(e)) !=0: # if(e.type == sdl2.SDL_QUIT): # running = False time += dt frame_time = time - sdl2.SDL_GetTicks() if (frame_time <= 0): frame_time = 1 tms.sleep(frame_time / 1000.) # update shit here # ... rend.doShit() rend.draw() sdl2.SDL_GL_SwapWindow(window) # rend.unload() #Unload assimp imports sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_Quit()
def update_screen(self): """ Updates what is on the screen. """ gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) # This renders the filters into an orho view to allow # scaling and offseting for preview tar_tex = self.target_texture if self.filters else self.texture_ids[ 'img'] gl.glBindTexture(gl.GL_TEXTURE_2D, tar_tex) self.final_filter.render(self.view.offset, self.view.zoom, self.window_dimensions, self.img_dimensions) # This renders the console if self.console_enabled: self.console.render(self.window_dimensions) sdl2.SDL_GL_SwapWindow(self.window)
def run(): if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 window = sdl2.SDL_CreateWindow(b"OpenGL demo", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 800, 600, sdl2.SDL_WINDOW_OPENGL) if not window: print(sdl2.SDL_GetError()) return -1 # Force OpenGL 3.3 'core' context. # Must set *before* creating GL context! video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK, video.SDL_GL_CONTEXT_PROFILE_CORE) context = sdl2.SDL_GL_CreateContext(window) # Setup GL shaders, data, etc. initialize() event = sdl2.SDL_Event() running = True while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_ESCAPE): running = False render() sdl2.SDL_GL_SwapWindow(window) sdl2.SDL_Delay(10) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def drawParticles(self, particles): # normalize scalar scalarNormalizer = GL.glGetUniformLocation(self.shaderProgram, b"scalarNormalizer") GL.glUniform1f(scalarNormalizer, 1.0) posAttrib = GL.glGetAttribLocation(self.shaderProgram, b"position") GL.glEnableVertexAttribArray(posAttrib) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.particles) GL.glBufferData(GL.GL_ARRAY_BUFFER, float_size * particles.size, particles.astype('float32'), GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(posAttrib, 2, GL.GL_FLOAT, False, 2 * float_size, ctypes.c_voidp(0)) GL.glPointSize(3) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glDrawArrays(GL.GL_POINTS, 0, particles.size) sdl2.SDL_GL_SwapWindow(self.window)
def render(self): gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) # Draw stuff here shaders.glUseProgram(self.shader) # (location, count, transpose, value) gl.glUniformMatrix4fv(self.uniforms['mat_ModelView'], 1, True, self.mat_model) try: self.vbo1.bind() try: gl.glEnableClientState(gl.GL_VERTEX_ARRAY) gl.glVertexPointerf(self.vbo1) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 9) finally: self.vbo1.unbind() gl.glDisableClientState(gl.GL_VERTEX_ARRAY) finally: shaders.glUseProgram(0) # Double buffering sdl.SDL_GL_SwapWindow(self.window)
def drawField(self, field): scalarAttrib = GL.glGetAttribLocation(self.shaderProgram, b"scalarVal") GL.glEnableVertexAttribArray(scalarAttrib) # do scalar value GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.scalars) GL.glBufferData(GL.GL_ARRAY_BUFFER, float_size * field.size, field.astype('float32'), GL.GL_STATIC_DRAW) GL.glVertexAttribPointer(scalarAttrib, 1, GL.GL_FLOAT, False, float_size, ctypes.c_voidp(0)) # normalize scalar scalarNormalizer = GL.glGetUniformLocation(self.shaderProgram, b"scalarNormalizer") GL.glUniform1f(scalarNormalizer, np.max(field)) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glDrawElements(GL.GL_TRIANGLES, self.elements.size, GL.GL_UNSIGNED_INT, ctypes.c_voidp(0)) sdl2.SDL_GL_SwapWindow(self.window)
def onRender(self): gl.glDepthMask(gl.GL_TRUE) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluPerspective(45, self.width / self.height, 0.01, 33.0) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glTranslated(0.0, 0.0, -self.camPosZ) # apply camera zooming gl.glRotated(self.angleX, 1.0, 0.0, 0.0) # apply camera rotation gl.glRotated(self.angleY, 0.0, 1.0, 0.0) # draw particles self.galaxySystem.render() if self.renderEnv: self.starSystem.render() # draw bounding box(F2 key) gl.glDisable(gl.GL_BLEND) drawBoundingBox(self.galaxyGroup, 1.0, 0.0, 0.0) # draw texts(F1 key) if not notext and self.text != 0: gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluOrtho2D(0, self.width, 0, self.height) gl.glDisable(gl.GL_DEPTH_TEST) gl.glColor3d(1.0, 1.0, 1.0) if self.text == 2: self.drawText(self.nbParticles, 4.0, 40.0) self.drawText(self.fps, 4.0, 8.0) # refresh sdl2.SDL_GL_SwapWindow(self.window)
def mainLoop(self): if not hasattr(self, "renderDelegate"): raise Exception("GLWindow's render delegate not set!") dtime = 0 event = sdl2.SDL_Event() running = True startTime = sdl2.SDL_GetTicks() while running: stopTime = sdl2.SDL_GetTicks() dtime += stopTime - startTime startTime = stopTime if self.printFPS: self.periodTime += dtime self.fpsDelay -= dtime self.numFrames += 1 if self.fpsDelay <= 0: self.fpsDelay = self.fpsPeriod print("FPS:", (self.numFrames / (self.periodTime / 1000.0))) self.numFrames = 0 self.periodTime = 0 while sdl2.SDL_PollEvent(byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False else: pass # self.renderDelegate.addEvent(event) while dtime >= self.timeStep: dtime -= self.timeStep self.renderDelegate.update(self.timeStep) self.renderDelegate.render() sdl2.SDL_GL_SwapWindow(self.window) self.cleanup()
def flip(): """Displays the contents of the display buffer on the screen. Because the screen is only redrawn at certain intervals (every 16.7 ms for a typical 60 Hz LCD), this function will not return until the next redraw event occurs. When in development mode, this function will print a warning in the console if the screen takes longer than a single refresh to redraw. If this occurs often, it might indicate an issue with your graphics driver or display computer and suggests that you shouldn't rely on that setup for timing-sensitive experiments. For more information on how drawing works in KLibs, please refer to the documentation page explaining the graphics system. """ from klibs.KLEnvironment import exp if exp: exp.before_flip() try: window = exp.window.window except AttributeError: raise ValueError( "flip() cannot be called outside of the KLibs experiment runtime.") # Note: On some systems, redrawing the screen will sometimes take longer than expected (up to # 100ms in some cases). Since this is obviously a problem for timing-sensitive research, we # time how long each flip takes, and print a warning whenever it takes longer than expected # (with a threshold of 1ms). flip_start = precise_time() sdl2.SDL_GL_SwapWindow(window) flip_time = (precise_time() - flip_start) * 1000 # convert to ms if P.development_mode: if flip_time > (P.refresh_time + 1): warn = "Warning: Screen refresh took {0} ms (expected {1} ms)" print(warn.format("%.2f" % flip_time, "%.2f" % P.refresh_time))
def swap(self): sdl2.SDL_GL_SwapWindow(self._native_window)
def main(): if len(sys.argv) != 2: print("usage: 3dwf.py REMOTE_ADDRESS", file=sys.stderr) sys.exit(1) nbins = 256 overlap = 192 rem_address = (sys.argv[1], 3731) conn = socket.create_connection(rem_address) sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO | sdl2.SDL_INIT_AUDIO) window = sdl2.SDL_CreateWindow(b"3D Waterfall", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, 800, 600, sdl2.SDL_WINDOW_RESIZABLE | sdl2.SDL_WINDOW_OPENGL) context = sdl2.SDL_GL_CreateContext(window) wf = WFViewer(nbins) wf.init(800, 600) wf.shift = 0 filt = interp_fir_filter(lowpass(np.pi / 4, 512) * np.hamming(512), 4) freqx = freq_translator((0.8/8.0) * np.pi) headlen = max(filt.nhistory, overlap) ringbuf = RingBuf(headlen, np.zeros(headlen + (nbins - overlap) * 512, dtype=np.complex64)) # FIXME global audio_edge audio_edge = 0 def callback(unused, buf, buflen): global audio_edge bufbuf = pybuf_from_memory(buf, buflen, 0x200) # PyBUF_WRITE array = np.frombuffer(bufbuf, np.float32) assert len(array) % filt.interp == 0 # TODO nreqframes = len(array) // filt.interp loc_ringbuf_edge = ringbuf.fill_edge if loc_ringbuf_edge < 0 or (loc_ringbuf_edge - audio_edge) % len(ringbuf) < nreqframes: print("audio underrun", file=sys.stderr) array.fill(0) return # TODO if audio_edge + nreqframes > len(ringbuf): audio_edge = 0 slic = ringbuf.slice(audio_edge - filt.nhistory, audio_edge + nreqframes) array[:] = np.real(freqx(filt(slic))) * wf.volume audio_edge += nreqframes sdl2.SDL_PushEvent(UPDATE_EVENT) audio_spec = sdl2.SDL_AudioSpec(8000, sdl2.AUDIO_F32, 1, 512, sdl2.SDL_AudioCallback(callback)) audio_dev = sdl2.SDL_OpenAudioDevice(None, 0, audio_spec, None, 0) if audio_dev == 0: raise Error('could not open audio device') err_queue = queue.Queue() def readfunc(nbytes): bytes = b'' while len(bytes) < nbytes: ret = conn.recv(nbytes - len(bytes)) if not ret: raise Exception('end of stream') bytes += ret return bytes def thread_target(): try: input_thread(readfunc, ringbuf, nbins, overlap, wf) except Exception as e: err_queue.put(e) event = sdl2.SDL_Event() event.type = sdl2.SDL_QUIT sdl2.SDL_PushEvent(event) other_thread = threading.Thread(target=thread_target) other_thread.setDaemon(True) other_thread.start() sdl2.SDL_PauseAudioDevice(audio_dev, 0) running = True event = sdl2.SDL_Event() while running: sdl2.SDL_WaitEvent(ctypes.byref(event)) while True: if event.type == sdl2.SDL_QUIT: running = False break wf.event(event) if sdl2.SDL_PollEvent(ctypes.byref(event)) == 0: break # FIXME wf.shift = ((ringbuf.fill_edge - audio_edge) % len(ringbuf)) / (nbins - overlap) wf.draw() sdl2.SDL_GL_SwapWindow(window) try: for exc in iter(err_queue.get_nowait, None): sdl2.SDL_ShowSimpleMessageBox(sdl2.SDL_MESSAGEBOX_ERROR, b"Exception", str(exc).encode("ascii"), None) except queue.Empty: pass sdl2.SDL_CloseAudioDevice(audio_dev) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit()
def onRender(self): gl.glDepthMask(gl.GL_TRUE) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluPerspective(45, self.width / self.height, 0.01, 20.0) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glRotated(self.angleX, 1.0, 0.0, 0.0) # apply camera rotation gl.glRotated(self.angleY, 0.0, 1.0, 0.0) gl.glTranslated(-self.posX, -1.0, -self.posZ) if self.renderEnv: c = self.param_f(0.8, 0.2) gl.glFogfv(gl.GL_FOG_COLOR, [c, c, c, 1.0]) dist = self.param_f(20.0, 5.0) gl.glFogf(gl.GL_FOG_DENSITY, 2.0 / dist) # Renders floor gl.glDisable(gl.GL_BLEND) gl.glEnable(gl.GL_TEXTURE_2D) gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE) gl.glBindTexture(gl.GL_TEXTURE_2D, self.txPaving) gl.glBegin(gl.GL_QUADS) gl.glColor3f(self.param_f(1.0, 0.3), self.param_f(1.0, 0.3), self.param_f(1.0, 0.3)) gl.glTexCoord2f(dist + self.posX, dist + self.posZ) gl.glVertex3f(dist + self.posX, 0.0, dist + self.posZ) gl.glTexCoord2f(dist + self.posX, -dist + self.posZ) gl.glVertex3f(dist + self.posX, 0.0, -dist + self.posZ) gl.glTexCoord2f(-dist + self.posX, -dist + self.posZ) gl.glVertex3f(-dist + self.posX, 0.0, -dist + self.posZ) gl.glTexCoord2f(-dist + self.posX, dist + self.posZ) gl.glVertex3f(-dist + self.posX, 0.0, dist + self.posZ) gl.glEnd() gl.glDisable(gl.GL_TEXTURE_2D) # draw bounding box(F2 key) gl.glLineWidth(1.0) drawBoundingBox(self.rainGroup, 1.0, 0.0, 0.0) drawBoundingBox(self.dropGroup, 0.0, 1.0, 0.0) drawBoundingBox(self.splashGroup, 0.0, 0.0, 1.0) # draw particles self.system.render() # draw texts(F1 key) if not notext and self.text != 0: gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluOrtho2D(0, self.width, 0, self.height) gl.glDisable(gl.GL_DEPTH_TEST) gl.glColor3d(1.0, 1.0, 1.0) if self.text == 2: self.drawText(self.strRainRate, 4.0, 72.0) self.drawText(self.nbParticles, 4.0, 40.0) self.drawText(self.fps, 4.0, 8.0) # refresh sdl2.SDL_GL_SwapWindow(self.window)
def run(self) -> int: """ Run scene. This is a complex function and needs some refactoring. Here is the logic and flow behind this function: 1. Initialize SDL 2. Create SDL window with given parameters enabling OpenGL Pipeline 3. Create and set active context as OpenGL Context 4. Set running flag. 5. Fix aspect ratios of observers *aka cameras* in the scene. 6. Start scene loop. 1. Poll for SDL events 2. React to SDL events *(quit, key press, key up, mouse motion etc)* 3. Render scene, turn to step 6.1 if not quit 7. Destroy objects and clear memory. 8. Destroy window and such. """ if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: return -1 sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION, 3) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION, 3) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK, sdl2.SDL_GL_CONTEXT_PROFILE_CORE) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLEBUFFERS, 1) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLESAMPLES, 16) self.window = sdl2.SDL_CreateWindow( b"Payton Scene", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, int(self.window_width), int(self.window_height), sdl2.SDL_WINDOW_OPENGL, ) # type: ignore if not self.window: return -1 self._context = sdl2.SDL_GL_CreateContext(self.window) self.event = sdl2.SDL_Event() self.running = True # Fix aspect ratios of observers for observer in self.observers: observer.aspect_ratio = (self.window_width / self.window_height * 1.0) for clock in self.clocks: self.clocks[clock].start() while self.running: while sdl2.SDL_PollEvent(ctypes.byref(self.event)) != 0: self.controller.keyboard(self.event, self) self.controller.mouse(self.event, self) self._render() sdl2.SDL_GL_SwapWindow(self.window) sdl2.SDL_Delay(1) for obj in self.objects: self.objects[obj].destroy() for clock in self.clocks: self.clocks[clock].kill() sdl2.SDL_GL_DeleteContext(self._context) sdl2.SDL_DestroyWindow(self.window) self.window = None sdl2.SDL_Quit() return 0
def refresh(self): sdl2.SDL_GL_SwapWindow(self.window)
def run(): if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 window = sdl2.SDL_CreateWindow(b"OpenGL demo", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 800, 600, sdl2.SDL_WINDOW_OPENGL) if not window: print(sdl2.SDL_GetError()) return -1 # Force OpenGL 3.3 'core' context. # Must set *before* creating GL context! video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK, video.SDL_GL_CONTEXT_PROFILE_CORE) context = sdl2.SDL_GL_CreateContext(window) quad = [ -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, -0.5, 0.5, 0.0, 1.0, 1.0, 1.0 ] quad = numpy.array(quad, dtype=numpy.float32) indices = [0, 1, 2, 2, 3, 0] indices = numpy.array(indices, dtype=numpy.uint32) # Setup GL shaders, data, etc. vertex_shader = shaders.compileShader( """ #version 330 in vec3 position; in vec3 color; out vec3 newColor; void main() { gl_Position = vec4(position, 1.0f); newColor = color; } """, GL.GL_VERTEX_SHADER) fragment_shader = shaders.compileShader( """ #version 330 in vec3 newColor; out vec4 outColor; void main() { outColor = vec4(newColor, 1.0f); } """, GL.GL_FRAGMENT_SHADER) shaderProgram = shaders.compileProgram(vertex_shader, fragment_shader) GL.glUseProgram(shaderProgram) VAO = GL.glGenVertexArrays(1) GL.glBindVertexArray(VAO) # Need VBO for triangle vertices and colours VBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO) GL.glBufferData(GL.GL_ARRAY_BUFFER, 96, quad, GL.GL_STATIC_DRAW) EBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, EBO) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, 24, indices, GL.GL_STATIC_DRAW) position = GL.glGetAttribLocation(shaderProgram, "position") GL.glVertexAttribPointer(position, 3, GL.GL_FLOAT, GL.GL_FALSE, 24, ctypes.c_void_p(0)) GL.glEnableVertexAttribArray(position) color = GL.glGetAttribLocation(shaderProgram, "color") GL.glVertexAttribPointer(color, 3, GL.GL_FLOAT, GL.GL_FALSE, 24, ctypes.c_void_p(12)) GL.glEnableVertexAttribArray(color) event = sdl2.SDL_Event() running = True GL.glClearColor(0, 0, 0, 1) while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False try: GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glDrawElements(GL.GL_TRIANGLES, 6, GL.GL_UNSIGNED_INT, None) finally: GL.glUseProgram(0) sdl2.SDL_GL_SwapWindow(window) sdl2.SDL_Delay(10) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def render(self): GL.glClearColor(0.0, 0.0, 0.0, 1.0) super(context, self).render() sdl2.SDL_GL_SwapWindow(self.window)
def main(): ######################## class Opts(object): pass opts = Opts() opts.verbose = True opts.windowed = True opts.vsync = False ######################## if opts.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info("Initializing") sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) dm = sdl2.SDL_DisplayMode() sdl2.SDL_GetDesktopDisplayMode(0, dm) if not opts.windowed: width = dm.w height = dm.h else: width = round(dm.w * .8) height = round(dm.h * .8) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK, sdl2.SDL_GL_CONTEXT_PROFILE_ES) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION, 3) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION, 0) window_flags = sdl2.SDL_WINDOW_OPENGL | (sdl2.SDL_WINDOW_FULLSCREEN if not opts.windowed else 0) window = sdl2.SDL_CreateWindow(TITLE.encode('utf-8'), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, width, height, window_flags) context = sdl2.SDL_GL_CreateContext(window) fbo = None # fbo = gllib.framebuffer.MultisampledFramebuffer(8, (width, height)) if opts.vsync: if sdl2.SDL_GL_SetSwapInterval(-1) == -1: logger.warning("Adaptive vsync not available") sdl2.SDL_GL_SetSwapInterval(1) else: sdl2.SDL_GL_SetSwapInterval(0) main_scene = scene.Scene((width, height)) frames = 0 frame_count_time = time.monotonic() ev = sdl2.SDL_Event() running = True while running: while True: if (sdl2.SDL_PollEvent(ev) == 0): break if ev.type == sdl2.SDL_QUIT: running = False elif ev.type == sdl2.SDL_KEYUP and ev.key.keysym.sym == sdl2.SDLK_ESCAPE: running = False main_scene.update() if fbo is not None: with fbo: main_scene.render() fbo.activate_for_read() fbo.blit() else: main_scene.render() sdl2.SDL_GL_SwapWindow(window) frames += 1 now = time.monotonic() if now - frame_count_time > FPS_PRINT_TIME: fps = frames / (now - frame_count_time) frames = 0 frame_count_time = now logger.debug("%.3f FPS", fps) main_scene.shutdown() sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit()
def show_model(tsdf): WINDOW_WIDTH = 640 WINDOW_HEIGHT = 480 # Init sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION, 3) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION, 2) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK, sdl2.SDL_GL_CONTEXT_PROFILE_CORE) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_DOUBLEBUFFER, 1) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_DEPTH_SIZE, 24) sdl2.SDL_GL_SetSwapInterval(1) window = sdl2.SDL_CreateWindow( b"Python/SDL2/OpenGL", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, sdl2.SDL_WINDOW_OPENGL | sdl2.SDL_WINDOW_SHOWN) if not window: sys.stderr.write("Error: Could not create window\n") exit(1) glcontext = sdl2.SDL_GL_CreateContext(window) # gl.glClampColor(gl.GL_CLAMP_FRAGMENT_COLOR, False) # gl.glClampColor(gl.GL_CLAMP_VERTEX_COLOR, False) # gl.glClampColor(gl.GL_CLAMP_READ_COLOR, False) viewer = Viewer() viewer.set_s2w(tsdf.intrinsic_inv) viewer.set_c(np.zeros([3])) viewer.set_vol_dim(tsdf.vol_dim) viewer.set_vol_start(tsdf.vol_start) viewer.set_vol_end(tsdf.vol_end) tex = gl.glGenTextures(2) gl.glBindTexture(gl.GL_TEXTURE_2D, tex[0]) # print(tsdf.tsdf_color.dtype) fused = np.concatenate([tsdf.tsdf_color.astype(np.float32) / 255, np.expand_dims(tsdf.tsdf_diff, -1)], axis=-1) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA32F, fused.shape[1], fused.shape[0], 0, gl.GL_RGBA, gl.GL_FLOAT, fused) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) gl.glBindTexture(gl.GL_TEXTURE_2D, tex[1]) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_R16I, tsdf.tsdf_cls.shape[1], tsdf.tsdf_cls.shape[0], 0, gl.GL_RED_INTEGER, gl.GL_INT, tsdf.tsdf_cls) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) running = True event = sdl2.SDL_Event() angle = 0 while running: angle += 0.01 while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False if event.type == sdl2.events.SDL_KEYDOWN: print("SDL_KEYDOWN") if event.key.keysym.sym == sdl2.SDLK_ESCAPE: running = False # if event.type == sdl2.SDL_MOUSEMOTION: # print("SDL_MOUSEMOTION") # if event.type == sdl2.SDL_MOUSEBUTTONDOWN: # print("SDL_MOUSEBUTTONDOWN") mean_depth = tsdf.mean_depth rot = np.array([[math.cos(angle), 0, -math.sin(angle), mean_depth * math.sin(angle)], [0, 1, 0, 0], [math.sin(angle), 0, math.cos(angle), mean_depth - mean_depth * math.cos(angle)], [0, 0, 0, 1]]) viewer.set_s2w(np.matmul(rot, tsdf.intrinsic_inv)) viewer.set_c(np.array([(mean_depth + 0.5) * math.sin(angle), 0, (mean_depth + 0.5) - (mean_depth + 0.5) * math.cos(angle)])) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT) gl.glUseProgram(viewer.program) gl.glBindVertexArray(viewer.vao) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, tex[0]) gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(gl.GL_TEXTURE_2D, tex[1]) gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4) # gl.glBindTexture(gl.GL_TEXTURE_2D, 0) gl.glUseProgram(0) sdl2.SDL_GL_SwapWindow(window)
glEnable(GL_TEXTURE_2D) glEnable(GL_MULTISAMPLE) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) glClearColor(0.,0.,0.,1.) gluPerspective(45,800.0/600.0,0.1,200.0) glTranslatef(0.0,0.0,-60) running = True event = sdl2.SDL_Event() while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False if event.type == sdl2.events.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_ESCAPE: running = False if event.key.keysym.sym == sdl2.SDLK_DOWN: ax += 5 if event.key.keysym.sym == sdl2.SDLK_UP: ax -= 5 if event.key.keysym.sym == sdl2.SDLK_LEFT: ay += 5 if event.key.keysym.sym == sdl2.SDLK_RIGHT: ay -= 5 if (event.type == sdl2.SDL_MOUSEMOTION): ax, ay = getPosicaoPonteiro() desenha() sdl2.SDL_GL_SwapWindow(window)
def _vispy_swap_buffers(self): if self._id is None: return # Swap front and back buffer sdl2.SDL_GL_SwapWindow(self._id.window)