def run(): sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) window = sdl2.SDL_CreateWindow(b"Hello World", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, 592, 460, sdl2.SDL_WINDOW_SHOWN) fname = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "hello.bmp") image = sdl2.SDL_LoadBMP(fname.encode("utf-8")) windowsurface = sdl2.SDL_GetWindowSurface(window) sdl2.SDL_BlitSurface(image, None, windowsurface, None) sdl2.SDL_UpdateWindowSurface(window) sdl2.SDL_FreeSurface(image) running = True event = sdl2.SDL_Event() while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False break sdl2.SDL_Delay(10) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def blitSurf(srcSurf, dst, dstSurf, xOffset=0, yOffset=0): x = dst.size[0] / 2 + xOffset - srcSurf.w / 2 y = dst.size[1] / 2 + yOffset - srcSurf.h / 2 sdl2.SDL_BlitSurface(srcSurf, None, dstSurf, sdl2.SDL_Rect(x, y, srcSurf.w, srcSurf.h)) sdl2.SDL_UpdateWindowSurface( dst.window ) #should this really be here? (will it cause immediate update?)
def update(self): último = self.time self.time = time.perf_counter() # desenha cinza sdlx.fill(self.win.get_surface(), sdlx.string_to_color('#555')) sdl.SDL_UpdateWindowSurface(self.win.window) # e soma o tempo total self.tempoTotal += self.time - último self.i += 1
def refresh(self, image): bytes_io = io.BytesIO() size = image.size image.resize((size[0] * self.scale, size[1] * self.scale)).save(bytes_io, "PPM") image_bytes = bytes_io.getvalue() rw_ops = sdl2.SDL_RWFromMem(image_bytes, len(image_bytes)) sdl_image = sdl2.sdlimage.IMG_Load_RW(rw_ops, 1) sdl2.SDL_BlitSurface(sdl_image, None, self.window_surface, None) sdl2.SDL_UpdateWindowSurface(self.window) sdl2.SDL_FreeSurface(sdl_image)
def _do_flip(self): """Draw the canvas to the screen.""" sdl2.SDL_FillRect(self.work_surface, None, self.border_attr) if self.composite_artifacts: self.work_pixels[:] = video_graphical.apply_composite_artifacts( self.pixels[self.vpagenum], 4 // self.bitsperpixel) sdl2.SDL_SetSurfacePalette(self.work_surface, self.composite_palette) else: self.work_pixels[:] = self.pixels[self.vpagenum] sdl2.SDL_SetSurfacePalette(self.work_surface, self.show_palette[self.blink_state]) # apply cursor to work surface self._show_cursor(True) # convert 8-bit work surface to (usually) 32-bit display surface format pixelformat = self.display_surface.contents.format conv = sdl2.SDL_ConvertSurface(self.work_surface, pixelformat, 0) # scale converted surface and blit onto display if not self.smooth: sdl2.SDL_BlitScaled(conv, None, self.display_surface, None) else: # smooth-scale converted surface w, h = self.window_width, self.window_height zoomx = ctypes.c_double(w / (self.size[0] + 2.0 * self.border_x)) zoomy = ctypes.c_double(h / (self.size[1] + 2.0 * self.border_y)) # only free the surface just before zoomSurface needs to re-allocate # so that the memory block is highly likely to be easily available # this seems to avoid unpredictable delays sdl2.SDL_FreeSurface(self.zoomed) self.zoomed = sdl2.sdlgfx.zoomSurface(conv, zoomx, zoomy, sdl2.sdlgfx.SMOOTHING_ON) # blit onto display sdl2.SDL_BlitSurface(self.zoomed, None, self.display_surface, None) # create clipboard feedback if self.clipboard.active(): rects = (sdl2.SDL_Rect(r[0] + self.border_x, r[1] + self.border_y, r[2], r[3]) for r in self.clipboard.selection_rect) sdl_rects = (sdl2.SDL_Rect * len(self.clipboard.selection_rect))(*rects) sdl2.SDL_FillRect( self.overlay, None, sdl2.SDL_MapRGBA(self.overlay.contents.format, 0, 0, 0, 0)) sdl2.SDL_FillRects( self.overlay, sdl_rects, len(sdl_rects), sdl2.SDL_MapRGBA(self.overlay.contents.format, 128, 0, 128, 0)) sdl2.SDL_BlitScaled(self.overlay, None, self.display_surface, None) # flip the display sdl2.SDL_UpdateWindowSurface(self.display) # destroy the temporary surface sdl2.SDL_FreeSurface(conv)
def __init__(self, input_queue, video_queue, **kwargs): """Initialise SDL2 interface.""" if not sdl2: logging.debug('PySDL2 module not found.') raise base.InitFailed() if not numpy: logging.debug('NumPy module not found.') raise base.InitFailed() video_graphical.VideoGraphical.__init__(self, input_queue, video_queue, **kwargs) # display & border # border attribute self.border_attr = 0 # palette and colours # composite colour artifacts self.composite_artifacts = False # update cycle # refresh cycle parameters self._cycle = 0 self.last_cycle = 0 self._cycle_time = 120 self.blink_cycles = 5 # cursor # current cursor location self.last_row = 1 self.last_col = 1 # cursor is visible self.cursor_visible = True # load the icon self.icon = kwargs['icon'] # mouse setups buttons = {'left': sdl2.SDL_BUTTON_LEFT, 'middle': sdl2.SDL_BUTTON_MIDDLE, 'right': sdl2.SDL_BUTTON_RIGHT, 'none': None} copy_paste = kwargs.get('copy-paste', ('left', 'middle')) self.mousebutton_copy = buttons[copy_paste[0]] self.mousebutton_paste = buttons[copy_paste[1]] self.mousebutton_pen = buttons[kwargs.get('pen', 'right')] # keyboard setup self.f11_active = False self.altgr = kwargs['altgr'] if not self.altgr: scan_to_scan[sdl2.SDL_SCANCODE_RALT] = scancode.ALT mod_to_scan[sdl2.KMOD_RALT] = scancode.ALT # keep params for enter self.kwargs = kwargs # we need a set_mode call to be really up and running self._has_window = False # ensure the correct SDL2 video driver is chosen for Windows # since this gets messed up if we also import pygame if platform.system() == 'Windows': os.environ['SDL_VIDEODRIVER'] = 'windows' # initialise SDL if sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING): # SDL not initialised correctly logging.error('Could not initialise SDL2: %s', sdl2.SDL_GetError()) raise base.InitFailed() display_mode = sdl2.SDL_DisplayMode() sdl2.SDL_GetCurrentDisplayMode(0, ctypes.byref(display_mode)) self.physical_size = display_mode.w, display_mode.h # create the window initially as 640*400 black # "NOTE: You should not expect to be able to create a window, render, or receive events on any thread other than the main one" # https://wiki.libsdl.org/CategoryThread # http://stackoverflow.com/questions/27751533/sdl2-threading-seg-fault self.display = None self.work_surface = None self._do_create_window(*self._find_display_size(640, 400, self.border_width)) # pop up as black rather than background, looks nicer sdl2.SDL_UpdateWindowSurface(self.display)
# upload rgb data buf = pkt.swsFrame.contents.data[0] surface = sdl2.SDL_CreateRGBSurfaceFrom( buf, size[0], size[1], 24, size[0] * 3, rmask, gmask, bmask, amask) #print sdl2.SDL_GetPixelFormatName(surface.contents.format.contents.format) if useTexture: texture = sdl2.SDL_CreateTextureFromSurface( renderer, surface) res = sdl2.SDL_RenderCopy(renderer, texture, None, None) if res < 0: raise RuntimeError(sdl2.SDL_GetError()) sdl2.SDL_RenderPresent(renderer) else: sdl2.SDL_BlitSurface(surface, None, windowSurface, None) sdl2.SDL_UpdateWindowSurface(window) sdl2.SDL_FreeSurface(surface) sdl2.SDL_Delay(10) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit()
def drawText(myText, myFont, textColor, textWidth=.9): lineHeight = sdl2.sdlttf.TTF_RenderText_Blended( myFont, 'T', textColor).contents.h textWidthMax = int(stimDisplay.size[0]) paragraphs = myText.splitlines() renderList = [] textHeight = 0 for thisParagraph in paragraphs: words = thisParagraph.split(' ') if len(words) == 1: renderList.append(words[0]) if (thisParagraph != paragraphs[len(paragraphs) - 1]): renderList.append(' ') textHeight = textHeight + lineHeight else: thisWordIndex = 0 while thisWordIndex < (len(words) - 1): lineStart = thisWordIndex lineWidth = 0 while (thisWordIndex < (len(words) - 1)) and (lineWidth <= textWidthMax): thisWordIndex = thisWordIndex + 1 lineWidth = sdl2.sdlttf.TTF_RenderText_Blended( myFont, ' '.join(words[lineStart:(thisWordIndex + 1)]), textColor).contents.w if thisWordIndex < (len(words) - 1): #last word went over, paragraph continues renderList.append(' '.join( words[lineStart:(thisWordIndex - 1)])) textHeight = textHeight + lineHeight thisWordIndex = thisWordIndex - 1 else: if lineWidth <= textWidthMax: #short final line renderList.append(' '.join( words[lineStart:(thisWordIndex + 1)])) textHeight = textHeight + lineHeight else: #full line then 1 word final line renderList.append(' '.join( words[lineStart:thisWordIndex])) textHeight = textHeight + lineHeight renderList.append(words[thisWordIndex]) textHeight = textHeight + lineHeight #at end of paragraph, check whether a inter-paragraph space should be added if (thisParagraph != paragraphs[len(paragraphs) - 1]): renderList.append(' ') textHeight = textHeight + lineHeight numLines = len(renderList) * 1.0 for thisLine in range(len(renderList)): thisRender = sdl2.sdlttf.TTF_RenderText_Blended( myFont, renderList[thisLine], textColor).contents x = int(stimDisplay.size[0] / 2.0 - thisRender.w / 2.0) y = int(stimDisplay.size[1] / 2.0 - thisRender.h / 2.0 + 1.0 * thisLine / numLines * textHeight) sdl2.SDL_BlitSurface( thisRender, None, stimDisplaySurf, sdl2.SDL_Rect(x, y, thisRender.w, thisRender.h)) sdl2.SDL_UpdateWindowSurface( stimDisplay.window ) #should this really be here? (will it cause immediate update?)
#!/usr/bin/env python import sdl2 as sdl import sdl2.ext as sdlx import time win = sdlx.Window ('Direto', (800, 600)) win.show () tempo = time.perf_counter () done = False tempoTotal = 0 i = 0 while not done: events = sdlx.get_events () for ev in events: if ev.type == sdl.SDL_QUIT: done = True break; # desenha =P sdlx.fill (win.get_surface (), sdlx.string_to_color ('#555')) sdl.SDL_UpdateWindowSurface (win.window) último = tempo tempo = time.perf_counter () tempoTotal += tempo - último i += 1 print ('Média de FPS:', 1 / (tempoTotal / i))