def main(): this.sbg = this.neutral #tex_load("textures/eyes/neutral.png") mykeys = pi3d.Keyboard() #queue = Queue() # reader() reads from queue #reader_p = Process(target=reader, args=((queue),)) #reader_p.daemon = True #reader_p.start() # Launch reader() as a separate python process while DISPLAY.loop_running(): if (this.mode == "EYE") or (this.mode == "SLEEP"): eyeDraw() sfg = this.sbg # foreground Slide set to old background canvas.set_draw_details( canvas.shader, [sfg.tex, this.sbg.tex]) # reset two textures canvas.set_2d_size(this.sbg.dimensions[0], this.sbg.dimensions[1], this.sbg.dimensions[2], this.sbg.dimensions[3]) canvas.unif[48:54] = canvas.unif[ 42:48] #need to pass shader dimensions for both textures canvas.set_2d_size(this.sfg.dimensions[0], this.sfg.dimensions[1], this.sfg.dimensions[2], this.sfg.dimensions[3]) canvas.draw() if mykeys.read() == 27: mykeys.close() DISPLAY.destroy() listener.close() break
def __init__(self, controller): self.__logger = logging.getLogger("interface_kbd.InterfaceKbd") self.__logger.info('creating an instance of InterfaceKbd') self.__controller = controller self.__keyboard = pi3d.Keyboard() self.__keep_looping = True t = threading.Thread(target=self.__loop) t.start()
def run(self): if pi3d.PLATFORM == PLATFORM_ANDROID: #***************************** self.DISPLAY.android.set_loop(self.pi3dloop) self.DISPLAY.android.run() else: # Fetch key presses self.mykeys = pi3d.Keyboard() self.mymouse = pi3d.Mouse(restrict=False) self.mymouse.start() self.omx, self.omy = self.mymouse.position() while self.pi3dloop(0.0): pass self.mykeys.close() self.mymouse.stop() self.DISPLAY.stop()
def run(self): if PLATFORM == PLATFORM_ANDROID: # android <<<<<<<<<<<<<<<<<<<<<<<<< self.DISPLAY.android.set_loop(self.pi3dloop) self.DISPLAY.android.run() else: # other platforms >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # Fetch key presses self.keys = pi3d.Keyboard() self.mouse = pi3d.Mouse(restrict=False) self.mouse.start() self.omx, self.omy = self.mouse.position() while self.pi3dloop(0.0): # not using the argument kivy passes pass self.keys.close() self.mouse.stop() self.DISPLAY.stop()
def __init__(self): self.DISPLAY = pi3d.Display.create(0, 0, w=preview_W, h=preview_H, layer=1, frames_per_second=max_fps) self.DISPLAY.set_background(0.0, 0.0, 0.0, 0.0) # transparent self.keybd = pi3d.Keyboard() self.txtshader = pi3d.Shader("uv_flat") self.linshader = pi3d.Shader('mat_flat') self.CAMERA = pi3d.Camera(is_3d=False) self.font = pi3d.Font("fonts/FreeMono.ttf", font_size=30, color=(0, 255, 0, 255)) # blue green 1.0 alpha self.model_path = "/home/pi/python-tflite-source/edgetpu/test_data/mobilenet_ssd_v2_face_quant_postprocess_edgetpu.tflite" self.engine = edgetpu.detection.engine.DetectionEngine(self.model_path) self.camera = PiCamera() self.camera.resolution = (320, 320) self.camera.framerate = 24 #self.rawCapture = PiRGBArray(self.camera, size=(320, 320)) self.rawCapture = bytearray(self.camera.resolution[0] * self.camera.resolution[1] * 3) self.camera.start_preview(fullscreen=False, layer=0, window=(0, 0, 320, 320)) time.sleep(2) #camera warm-up self.stream = io.BytesIO() #self.stream = self.camera.capture_continuous(self.rawCapture, format="bgr", use_video_port=True) self.frame = None self.frame_buf_val = None self.output = None self.stopped = False self.max_obj = 10 self.X_OFF = np.array([0, 0, -1, -1, 0, 0, 1, 1]) self.Y_OFF = np.array([-1, -1, 0, 0, 1, 1, 0, 0]) self.X_IX = np.array([0, 1, 1, 1, 1, 0, 0, 0]) self.Y_IX = np.array([0, 0, 0, 1, 1, 1, 1, 0]) self.verts = [[0.0, 0.0, 1.0] for i in range(8 * self.max_obj) ] # need a vertex for each end of each side self.bbox = pi3d.Lines(vertices=self.verts, material=(1.0, 0.8, 0.05), closed=False, strip=False, line_width=4) self.bbox.set_shader(self.linshader)
def pi_3d(inHeightmap, inWidth, inDepth, inHeight, inTextureMap, inBumpMap): rads = 0.017453292512 # degrees to radians # helpful messages # Esc to quit, W to go forward, Mouse to steer # At the edge you will turn into a ghost and be able to fly and pass through rocks! # Setup display and initialise pi3d DISPLAY = pi3d.Display.create(x=100, y=100, background=(0.4, 0.8, 0.8, 1), use_pygame=True) shader = pi3d.Shader("uv_bump") flatsh = pi3d.Shader("uv_flat") light = pi3d.Light((1, 1, 1), (400.0, 400.0, 350.0), (0.03, 0.03, 0.05), True) # sun = pi3d.Light((0.0, 1000.0, 0.0), (0.5, 1.0, 0.7), (0.3, 0.1, 0.1), is_point=True) # load Textures rockimg1 = pi3d.Texture("textures/techy1.jpg") rockimg2 = pi3d.Texture("textures/rocktile2.jpg") shineimg = pi3d.Texture("textures/stars.jpg") # environment cube ectex = pi3d.Texture("textures/ecubes/skybox_stormydays.jpg") myecube = pi3d.EnvironmentCube(size=900.0, maptype="CROSS") myecube.set_draw_details(flatsh, ectex) # Create elevation map # inWidth = Width of Map (i.e. 1024.0) # inDepth = Depth of Map (i.e. 1024.0) # inHeight = Height of Map (i.e 0.5) mapwidth = inWidth mapdepth = inDepth mapheight = inHeight bumpsh = pi3d.Shader('uv_bump') # inHeightmap = Maps/seed_XXXXX_grayscale.png # inTextureMap = Maps/seed_XXXXX_elevation.png # inBumpMap = Maps/seed_XXXXX_normal.png mymap = pi3d.ElevationMap(inHeightmap, width=mapwidth, depth=mapdepth, height=mapheight, divx=199, divy=199, name="sub") mymap.set_draw_details(shader, [rockimg1, rockimg2, shineimg], 128.0, 0.05) redplanet = pi3d.Texture(inTextureMap) bumpimg = pi3d.Texture(inBumpMap) mymap.set_draw_details(bumpsh, [redplanet, bumpimg], 128.0, 0.0) mymap.set_fog((0.3, 0.15, 0.1, 0.0), 1000.0) rot = 0.0 tilt = 0.0 avhgt = 3.0 xm, oxm = 0.0, -1.0 zm, ozm = 0.0, -1.0 ym = mymap.calcHeight(xm, zm) + avhgt # Fetch key presses mykeys = pi3d.Keyboard() mymouse = pi3d.Mouse(restrict=False) mymouse.start() omx, omy = mymouse.position() fly = False walk = True CAMERA = pi3d.Camera.instance() print ('at line 71 - Code3D') while DISPLAY.loop_running(): # movement of camera mx, my = mymouse.position() rot -= (mx - omx) * 0.2 tilt += (my - omy) * 0.1 dx = -math.sin(rot * rads) dz = math.cos(rot * rads) dy = math.sin(tilt * rads) if walk: if fly: xm += dx * 3 zm += dz * 3 ym += dy * 3 else: dy = mymap.calcHeight(xm + dx * 1.5, zm + dz * 1.5) + avhgt - ym if dy < 1.2: # limit steepness so can't climb up walls xm += dx * 0.5 zm += dz * 0.5 ym += dy * 0.5 if xm < -490 or xm > 490 or zm < -490 or zm > 490: fly = True # reached the edge if not (mx == omx and my == omy and oxm == xm and ozm == zm): CAMERA.reset() CAMERA.rotate(tilt, 0, 0) CAMERA.rotate(0, rot, 0) CAMERA.position((xm, ym, zm)) omx = mx omy = my oxm = xm ozm = zm light.position((xm, ym + 15.0, zm)) light.is_point = True mymap.set_light(light) myecube.position(xm, ym, zm) myecube.draw() mymap.draw() # key presses (ESCAPE to terminate) k = mykeys.read() if k > -1: if k == 119: # W Key toggle walk = not walk elif k == 115: # S Key walk = False dy = -(mymap.calcHeight(xm - dx, zm - dz) + avhgt) - ym if dy > -1.0: xm -= dx zm -= dz ym += dy elif k == 27: # ESCAPE key DISPLAY.destroy() mykeys.close() mymouse.stop() break # this will save a little time each loop if the camera is not moved CAMERA.was_moved = False quit()
included in the pi3d.sprites.Ball class """ import random import sys import math import demo import pi3d MAX_BALLS = 15 MIN_BALL_SIZE = 5 MAX_BALL_SIZE = 100 MAX_BALL_VELOCITY = 10.0 KEYBOARD = pi3d.Keyboard() LOGGER = pi3d.Log.logger(__name__) BACKGROUND_COLOR = (1.0, 1.0, 1.0, 0.0) DISPLAY = pi3d.Display.create(background=BACKGROUND_COLOR) WIDTH, HEIGHT = DISPLAY.width, DISPLAY.height ZPLANE = 1000 fov = 2.0 * math.degrees(math.atan(HEIGHT / 2.0 / ZPLANE)) CAMERA = pi3d.Camera((0, 0, 0), (0, 0, -1.0), (1, 1100, fov, WIDTH / float(HEIGHT))) SHADER = pi3d.Shader('shaders/uv_flat') TEXTURE_NAMES = [ 'textures/red_ball.png', 'textures/grn_ball.png', 'textures/blu_ball.png' ]
def __get_keyboard(self) -> typing.Optional["pi3d.Keyboard"]: if self.__input_type == "keyboard": return pi3d.Keyboard()
vmult=-5) # NB vmult -ve to flip texture ''' Lines for edges ''' edges = pi3d.PolygonLines(camera=camera, vertices=edge_path, closed=True, line_width=5.0, z=-1.0) edges.set_material((0.0, 0.0, 0.0)) edges.set_shader(lineshader) ''' or try using texture and uv_flat shader ''' #tex2 = pi3d.Texture("textures/PATRN.PNG") #edges.set_draw_details(shader, [tex2]) ''' add edges as child of poly ''' poly.add_child(edges) kb = pi3d.Keyboard() sc = 1.0 while display.loop_running(): poly.draw() # only draw, rotate, scale parent Shape poly.rotateIncZ(0.05) k = kb.read() if k != -1: if k == 27: break elif k == ord('w'): # w and s scale bigger and smaller sc *= 1.02 poly.scale(sc, sc, sc) elif k == ord('s'): sc /= 1.02 poly.scale(sc, sc, sc)
def __init__(self, config): # noinspection PyBroadException try: locale.setlocale(locale.LC_TIME, config.local) except Exception as e: log.warning("error trying to set local to {}".format(config.local), e) self._display = pi3d.Display.create( x=config.display_x, y=config.display_y, w=config.display_w, h=config.display_h, frames_per_second=config.fps, display_config=pi3d.DISPLAY_CONFIG_HIDE_CURSOR, background=config.background, ) self._camera = pi3d.Camera(is_3d=False) shader = pi3d.Shader(config.shader) self._slide = pi3d.Sprite( camera=self._camera, w=self._display.width, h=self._display.height, z=5.0 ) self._slide.set_shader(shader) self._slide.unif[47] = config.edge_alpha self._slide.unif[54] = config.blend_type self._slide.unif[55] = 1.0 # brightness used by shader [18][1] if config.keyboard: self.keyboard = pi3d.Keyboard() grid_size = math.ceil(len(config.codepoints) ** 0.5) font = pi3d.Font( config.font_file, codepoints=config.codepoints, grid_size=grid_size ) self._text = pi3d.PointText( font, self._camera, max_chars=200, point_size=config.show_text_sz ) self._textblock = pi3d.TextBlock( x=0, y=-self._display.height // 2 + (config.show_text_sz // 2) + 20, z=0.1, rot=0.0, char_count=199, text_format="{}".format(" "), size=0.99, spacing="F", justify=0.5, space=0.02, colour=(1.0, 1.0, 1.0, 1.0), ) self._text.add_text_block(self._textblock) bkg_ht = self._display.height // 4 text_bkg_array = np.zeros((bkg_ht, 1, 4), dtype=np.uint8) text_bkg_array[:, :, 3] = np.linspace(0, 170, bkg_ht).reshape(-1, 1) text_bkg_tex = pi3d.Texture(text_bkg_array, blend=True, free_after_load=True) self._text_bkg = pi3d.Plane( w=self._display.width, h=bkg_ht, y=-self._display.height // 2 + bkg_ht // 2, z=4.0, ) back_shader = pi3d.Shader("uv_flat") self._text_bkg.set_draw_details(back_shader, [text_bkg_tex]) self._foreground_slide = None self._background_slide = None
def main( startdir, # Root folder for images, with recursive search config_file, # File with list of file names (for fast restart) interval, # Seconds between images shuffle, # True or False geonamesuser, # User name for GeoNames server www.geonames.org check_dirs # Interval between checking folders in seconds ) : global backup_dir,paused,geoloc,last_file_change,kb_up,FIT,BLUR_EDGES # backup_dir = os.path.abspath(os.path.join(startdir,config.BKUP_DIR)) backup_dir = config.BKUP_DIR print(startdir) #print(config.BKUP_DIR) #print(backup_dir) if config.BUTTONS: pause_button = Button(8, hold_time=5) back_button = Button(9, hold_time=5) forward_button = Button(4,hold_time=5) pause_button.when_pressed = handle_press back_button.when_pressed = handle_press pause_button.when_held=handle_hold back_button.when_held=handle_hold forward_button.when_pressed=handle_press forward_button.when_held=handle_hold rotate_button = Button(5, hold_time=5) rotate_button.when_pressed= handle_press rotate_button.when_held=handle_hold paused=False next_check_tm=time.time()+check_dirs time_dot=True ############################################## # Create GeoNames locator object www.geonames.org geoloc=None try: geoloc=GeoNames(username=geonamesuser) except: print("Geographic information server not available") print("Setting up display") DISPLAY = pi3d.Display.create(x=0, y=0, frames_per_second=FPS,display_config=pi3d.DISPLAY_CONFIG_HIDE_CURSOR, background=BACKGROUND) CAMERA = pi3d.Camera(is_3d=False) print(DISPLAY.opengl.gl_id) shader = pi3d.Shader(config.PI3DDEMO + "/shaders/blend_new") #shader = pi3d.Shader("/home/patrick/python/pi3d_demos/shaders/blend_new") slide = pi3d.Sprite(camera=CAMERA, w=DISPLAY.width, h=DISPLAY.height, z=5.0) slide.set_shader(shader) slide.unif[47] = config.EDGE_ALPHA if KEYBOARD: kbd = pi3d.Keyboard() # images in iFiles list nexttm = 0.0 iFiles, nFi = get_files(startdir,config_file,shuffle) next_pic_num = 0 sfg = None # slide for foreground sbg = None # slide for background if nFi == 0: print('No files selected!') exit() # PointText and TextBlock. #font = pi3d.Font(FONT_FILE, codepoints=CODEPOINTS, grid_size=7, shadow_radius=4.0,shadow=(128,128,128,12)) grid_size = math.ceil(len(config.CODEPOINTS) ** 0.5) font = pi3d.Font(config.FONT_FILE, codepoints=config.CODEPOINTS, grid_size=grid_size, shadow_radius=4.0,shadow=(0,0,0,128)) text = pi3d.PointText(font, CAMERA, max_chars=200, point_size=50) text2 = pi3d.PointText(font, CAMERA, max_chars=8, point_size=50) #text = pi3d.PointText(font, CAMERA, max_chars=200, point_size=50) textblock = pi3d.TextBlock(x=-DISPLAY.width * 0.5 + 20, y=-DISPLAY.height * 0.4, z=0.1, rot=0.0, char_count=199, text_format="{}".format(" "), size=0.65, spacing="F", space=0.02, colour=(1.0, 1.0, 1.0, 1.0)) text.add_text_block(textblock) timeblock = pi3d.TextBlock(x=DISPLAY.width*0.5 - 150, y=DISPLAY.height * 0.5 - 50, z=0.1, rot=0.0, char_count=6, text_format="{}".format(" "), size=0.65, spacing="F", space=0.02, colour=(1.0, 1.0, 1.0, 1.0)) text2.add_text_block(timeblock) #Retrieve last image number to restart the slideshow from config.num file #Retrieve next directory check time cacheddata=(0,0,last_file_change,next_check_tm) try: with open(config_file+".num",'r') as f: cacheddata=json.load(f) num_run_through=cacheddata[0] next_pic_num=cacheddata[1] last_file_change=cacheddata[2] next_check_tm=cacheddata[3] except: num_run_through=0 next_pic_num=0 if (next_check_tm < time.time()) : #if stored check time is in the past, make it "now" next_check_tm = time.time() print("Start time ",time.strftime(config.TIME_FORMAT,time.localtime())) print("Next Check time ",time.strftime(config.TIME_FORMAT,time.localtime(next_check_tm))) print("Starting with round number ",num_run_through) print("Starting with picture number ",next_pic_num) tm=time.time() pic_num=next_pic_num # Main loop while DISPLAY.loop_running(): previous = tm # record previous time value, used to make cursor blink tm = time.time() if (time.localtime(previous).tm_sec < time.localtime(tm).tm_sec) : #blink dot time_dot = not(time_dot) #check if there are file to display if nFi > 0: # If needed, display new photo if (tm > nexttm and not paused) or (tm - nexttm) >= 86400.0: # this must run first iteration of loop print("tm es ",tm," nexttm es ", nexttm, " la resta ", tm-nexttm) nexttm = tm + interval a = 0.0 # alpha - proportion front image to back sbg = sfg sfg = None while sfg is None: # keep going through until a usable picture is found TODO break out how? # Calculate next picture index to be shown pic_num = next_pic_num next_pic_num += 1 if next_pic_num >= nFi: num_run_through += 1 next_pic_num = 0 #update persistent cached data for restart cacheddata=(num_run_through,pic_num,last_file_change,next_check_tm) with open(config_file+".num","w") as f: json.dump(cacheddata,f,separators=(',',':')) # File Open and texture build try: temp=time.time() im = Image.open(iFiles[pic_num]) print("foto numero ",pic_num," time ",time.time()) except: print("Error Opening File",iFiles[pic_num]) continue # EXIF data and geolocation analysis # define some default values orientation = 1 # unrotated dt=None # will hold date from EXIF datestruct=None # will hold formatted date # Format metadata try: exif_data = im._getexif() except: exif_data=None try: orientation = int(exif_data[config.EXIF_ORIENTATION]) except: orientation = 1 try: dt = time.mktime(time.strptime(exif_data[config.EXIF_DATID], '%Y:%m:%d %H:%M:%S')) datestruct=time.localtime(dt) except: datestruct=None try: location = get_geo_name(exif_data) except Exception as e: # NB should really check error print('Error preparing geoname: ', e) location = None # Load and format image try: sfg = tex_load(im, orientation, (DISPLAY.width, DISPLAY.height)) except: next_pic_num += 1 # skip to next photo continue nexttm = tm+interval #Time points to next interval # Image Rendering if sbg is None: # first time through sbg = sfg slide.set_textures([sfg, sbg]) slide.unif[45:47] = slide.unif[42:44] # transfer front width and height factors to back slide.unif[51:53] = slide.unif[48:50] # transfer front width and height offsets wh_rat = (DISPLAY.width * sfg.iy) / (DISPLAY.height * sfg.ix) if (wh_rat > 1.0 and FIT) or (wh_rat <= 1.0 and not FIT): sz1, sz2, os1, os2 = 42, 43, 48, 49 else: sz1, sz2, os1, os2 = 43, 42, 49, 48 wh_rat = 1.0 / wh_rat slide.unif[sz1] = wh_rat slide.unif[sz2] = 1.0 slide.unif[os1] = (wh_rat - 1.0) * 0.5 slide.unif[os2] = 0.0 #transition if KENBURNS: xstep, ystep = (slide.unif[i] * 2.0 / interval for i in (48, 49)) slide.unif[48] = 0.0 slide.unif[49] = 0.0 kb_up = not kb_up # Prepare the different texts to be shown overlay_text= "" #this will host the text on screen if SHOW_LOCATION: #(and/or month-year) if location is not None: overlay_text += tidy_name(str(location)) #print(overlay_text) if datestruct is not None : overlay_text += " " + tidy_name(config.MES[datestruct.tm_mon - 1]) + "-" + str(datestruct.tm_year) #print(overlay_text) try: textblock.set_text(text_format="{}".format(overlay_text)) text.regen() except : #print("Wrong Overlay_text Format") textblock.set_text(" ") # print time on screen, blink separator every second if not paused : timetext=timetostring(time_dot,tm) else : timetext="PAUSA" timeblock.set_text(text_format="{}".format(timetext)) # manages transition if KENBURNS: t_factor = nexttm - tm if kb_up: t_factor = interval - t_factor slide.unif[48] = xstep * t_factor slide.unif[49] = ystep * t_factor if a <= 1.0: # transition is happening a += delta_alpha slide.unif[44] = a else: # Check if image files list has to be rebuilt (no transition on going, so no harm to image slide.set_textures([sfg, sfg]) if (num_run_through > config.NUMBEROFROUNDS) or (time.time() > next_check_tm) : #re-load images after running through them or exceeded time print("Refreshing Files list") next_check_tm = time.time() + check_dirs # Set up the next interval try: if check_changes(startdir): #rebuild files list if changes happened print("Re-Fetching images files, erase config file") with open(config_file,'w') as f : json.dump('',f) # creates an empty config file, forces directory reload iFiles, nFi = get_files(startdir,config_file,shuffle) next_pic_num = 0 else : print("No directory changes: do nothing") except: print("Error refreshing file list, keep old one") num_run_through = 0 #render the image slide.draw() #render the text text.draw() text2.draw() else: textblock.set_text("NO IMAGES SELECTED") textblock.colouring.set_colour(alpha=1.0) text.regen() text.draw() # Keyboard and button handling #delta=time.time()-86400.0 delta=0 if KEYBOARD: k = kbd.read() if k != -1: print("Key pressed", tm-nexttm) #nexttm = delta # print(tm - nexttm) if k==27 or quit: #ESC break if k==ord(' '): paused = not paused if k==ord('s'): # go back a picture nexttm = 0 next_pic_num -= 2 if next_pic_num < -1: next_pic_num = -1 nexttm = delta if k==ord('q'): #go forward nexttm = delta if k==ord('r') and paused: # rotate picture (only if paused) nexttm = delta im.close() #close file on disk try: with open(iFiles[pic_num],'rb') as tmp_file: #open file again to be used in exif context tmp_im = exif.Image(tmp_file) tmp_file.close() if (tmp_im.has_exif) : # If it has exif data, rotate it if it does not, do nothing save_file(iFiles[pic_num]) # Copy file to Backup folder tmp_im.orientation = rotate90CW(tmp_im.orientation) # changes EXIF data orientation parameter with open(iFiles[pic_num],'wb') as tmp_file: # Write the file with new exif orientation tmp_file.write(tmp_im.get_file()) next_pic_num -=1 # force reload on screen except: print("Error when rotating photo") # nexttm = delta if config.BUTTONS: #Handling of config.BUTTONS goes here if paused and (rotate_button.estado == 1 or rotate_button.estado == 2): # Need to be on pause rotate_button.estado = 0 nexttm = delta im.close() #close file on disk try: with open(iFiles[pic_num],'rb') as tmp_file: #open file again to be used in exif context tmp_im = exif.Image(tmp_file) tmp_file.close() if (tmp_im.has_exif) : # If it has exif data, rotate it if it does not, do nothing save_file(iFiles[pic_num]) # Copy file to Backup folder tmp_im.orientation = rotate90CW(tmp_im.orientation) # changes EXIF data orientation parameter with open(iFiles[pic_num],'wb') as tmp_file: # Write the file with new exif orientation tmp_file.write(tmp_im.get_file()) next_pic_num -=1 # force reload on screen except: print("Error when rotating photo") if pause_button.estado == 1 or pause_button.estado == 2 : # button was pressed #nexttm = delta paused = not paused pause_button.estado = 0 if back_button.estado == 1 or back_button.estado == 2 : nexttm = delta next_pic_num -= 2 if next_pic_num < -1: next_pic_num = -1 #nexttm = 0 #force reload back_button.estado = 0 if forward_button.estado == 1 or forward_button.estado == 2 : nexttm = delta forward_button.estado = 0 # All config.BUTTONS go to idle after processing them, regardless of state # WHILE LOOP ends here try: DISPLAY.loop_stop() except Exception as e: print("this was going to fail if previous try failed!") if KEYBOARD: kbd.close() DISPLAY.destroy()
def start_picframe(): global date_from, date_to, quit, paused, nexttm, next_pic_num, iFiles, nFi, monitor_status, pcache, w_show_now if cfg['KENBURNS']: kb_up = True cfg['FIT'] = False cfg['BLUR_EDGES'] = False if cfg['BLUR_ZOOM'] < 1.0: cfg['BLUR_ZOOM'] = 1.0 sfg = None # slide for background sbg = None # slide for foreground delta_alpha = 1.0 / (cfg['FPS'] * cfg['FADE_TIME']) # delta alpha # Initialize pi3d system DISPLAY = pi3d.Display.create(x=0, y=0, frames_per_second=cfg['FPS'], display_config=pi3d.DISPLAY_CONFIG_HIDE_CURSOR, background=cfg['BACKGROUND']) CAMERA = pi3d.Camera(is_3d=False) shader = pi3d.Shader(cfg['SHADER']) slide = pi3d.Sprite(camera=CAMERA, w=DISPLAY.width, h=DISPLAY.height, z=5.0) slide.set_shader(shader) slide.unif[47] = cfg['EDGE_ALPHA'] slide.unif[54] = cfg['BLEND_TYPE'] if cfg['KEYBOARD']: kbd = pi3d.Keyboard() # PointText and TextBlock. If INFO_TXT_TIME <= 0 then this is just used for no images message grid_size = math.ceil(len(cfg['CODEPOINTS']) ** 0.5) font = pi3d.Font(cfg['FONT_FILE'], codepoints=cfg['CODEPOINTS'], grid_size=grid_size, shadow_radius=5.0, shadow=(0,0,0,128)) text = pi3d.PointText(font, CAMERA, max_chars=1000, point_size=cfg['TEXT_POINT_SIZE']) textlines = [] textlines.append( pi3d.TextBlock(x=-DISPLAY.width * 0.5 + 50, y=DISPLAY.height * 0.45, text_format=" ", z=0.1, rot=0.0, char_count=100, size=0.8, spacing="F", space=0.0, colour=(1.0, 1.0, 1.0, 1.0)) ) textlines.append( pi3d.TextBlock(x=-DISPLAY.width * 0.5 + 50, y=DISPLAY.height * 0.45 - 40, text_format=" ", z=0.1, rot=0.0, char_count=100, size=0.8, spacing="F", space=0.0, colour=(1.0, 1.0, 1.0, 1.0)) ) textlines.append( pi3d.TextBlock(x=-DISPLAY.width * 0.5 + 50, y=-DISPLAY.height * 0.4, text_format=" ", z=0.1, rot=0.0, char_count=100, size=0.99, spacing="F", space=0.0, colour=(1.0, 1.0, 1.0, 1.0)) ) textlines.append( pi3d.TextBlock(x=-DISPLAY.width * 0.5 + 50, y=-DISPLAY.height * 0.4 - 50, text_format=" ", z=0.1, rot=0.0, char_count=100, size=0.99, spacing="F", space=0.0, colour=(1.0, 1.0, 1.0, 1.0)) ) for item in textlines: text.add_text_block(item) # prepare to display weather info weather_interstitial = 'OFF' next_weather_tm = 0.0 weatherinfo = pi3d.PointText(font, CAMERA, max_chars=2000, point_size=cfg['W_POINT_SIZE']) weatherobj = weatherscreen.weather_obj_create(DISPLAY.width, DISPLAY.height) for _, obj in weatherobj['current'].items(): weatherinfo.add_text_block( obj ) for item in weatherobj['forecast']: for key, obj in item.items(): if key != 'icon': weatherinfo.add_text_block( obj ) weatherscreen.weather_set_alpha(weatherobj=weatherobj, alpha=0) next_check_tm = time.time() + cfg['CHECK_DIR_TM'] # check for new files or directory in image dir every n seconds next_monitor_check_tm = 0.0 num_run_through = 0 # here comes the main loop while DISPLAY.loop_running(): tm = time.time() if (tm > nexttm and not paused) or (tm - nexttm) >= 86400.0: if nFi > 0: nexttm = tm + cfg['TIME_DELAY'] sbg = sfg sfg = None if (w_show_now or (cfg['W_SKIP_CNT'] > 0 and next_pic_num > 0 and (next_pic_num % cfg['W_SKIP_CNT'] == 0))) and weather_interstitial == 'OFF': # show weather interstitial weather_interstitial = 'ON' sfg = tex_load(cfg['W_BACK_IMG'], 1, (DISPLAY.width, DISPLAY.height)) if w_show_now: w_show_now = False for item in textlines: item.colouring.set_colour(alpha=0) else: # continue with next picture if weather_interstitial == 'ON': weather_interstitial = 'FADE' start_pic_num = next_pic_num while sfg is None: # keep going through until a usable picture is found pic_num = next_pic_num sfg = tex_load(pic_num, iFiles, (DISPLAY.width, DISPLAY.height)) next_pic_num += 1 if next_pic_num >= nFi: num_run_through += 1 next_pic_num = 0 if next_pic_num == start_pic_num: nFi = 0 break # set description if cfg['INFO_TXT_TIME'] > 0.0: set_text_overlay(iFiles, pic_num, textlines) else: # could have a NO IMAGES selected and being drawn for item in textlines: item.colouring.set_colour(alpha=0.0) mqtt_publish_status( status="running", pic_num=pic_num ) if sfg is None: sfg = tex_load(cfg['NO_FILES_IMG'], 1, (DISPLAY.width, DISPLAY.height)) sbg = sfg mqtt_publish_status( status="no pictures found" ) a = 0.0 # alpha - proportion front image to back name_tm = tm + cfg['INFO_TXT_TIME'] if sbg is None: # first time through sbg = sfg slide.set_textures([sfg, sbg]) slide.unif[45:47] = slide.unif[42:44] # transfer front width and height factors to back slide.unif[51:53] = slide.unif[48:50] # transfer front width and height offsets wh_rat = (DISPLAY.width * sfg.iy) / (DISPLAY.height * sfg.ix) if (wh_rat > 1.0 and cfg['FIT']) or (wh_rat <= 1.0 and not cfg['FIT']): sz1, sz2, os1, os2 = 42, 43, 48, 49 else: sz1, sz2, os1, os2 = 43, 42, 49, 48 wh_rat = 1.0 / wh_rat slide.unif[sz1] = wh_rat slide.unif[sz2] = 1.0 slide.unif[os1] = (wh_rat - 1.0) * 0.5 slide.unif[os2] = 0.0 if cfg['KENBURNS']: xstep, ystep = (slide.unif[i] * 2.0 / cfg['TIME_DELAY'] for i in (48, 49)) slide.unif[48] = 0.0 slide.unif[49] = 0.0 kb_up = not kb_up if cfg['KENBURNS']: t_factor = nexttm - tm if kb_up: t_factor = cfg['TIME_DELAY'] - t_factor slide.unif[48] = xstep * t_factor slide.unif[49] = ystep * t_factor transition_happening = False if monitor_status.startswith("ON"): if a < 1.0: # image transition is happening transition_happening = True a += delta_alpha if a > 1.0: a = 1.0 slide.unif[44] = a * a * (3.0 - 2.0 * a) if weather_interstitial == 'ON': # fade in weather weatherscreen.weather_set_alpha(weatherobj=weatherobj, alpha=a) else: # fade in picture -> fade in text for item in textlines: item.colouring.set_colour(alpha=a) if weather_interstitial == 'FADE': # fade out weather weatherscreen.weather_set_alpha(weatherobj=weatherobj, alpha=1-a) if a==1: weather_interstitial = 'OFF' if nFi <= 0: textlines[0].set_text("NO IMAGES SELECTED") textlines[0].colouring.set_colour(alpha=1.0) next_check_tm = tm + 10.0 text.regen() elif tm > name_tm and tm < name_tm + 2.0 and weather_interstitial != 'ON': # fade out text alpha = 1- (tm - name_tm)/2.0 for item in textlines: item.colouring.set_colour(alpha=alpha) transition_happening = True text.regen() slide.draw() text.draw() if weather_interstitial != 'OFF': weatherinfo.regen() weatherinfo.draw() for item in weatherobj['forecast']: item['icon'].draw() for _, obj in weatherobj['static'].items(): obj.draw() else: # monitor OFF -> minimize system activity to reduce power consumption time.sleep(10) if not transition_happening: # no transition effect safe to reshuffle etc if tm > next_monitor_check_tm: # Check if it's time to switch monitor status scheduled_status = check_monitor_status(tm) if monitor_status != scheduled_status and not monitor_status.endswith("-MANUAL"): switch_HDMI(scheduled_status) paused = True if scheduled_status.startswith("OFF") else False monitor_status = scheduled_status mqtt_publish_status( fields="monitor_status" ) next_monitor_check_tm = tm + 60 # check every minute if monitor_status.startswith("ON"): if tm > next_check_tm: # time to check picture directory if pcache.refresh_cache() or (cfg['SHUFFLE'] and num_run_through >= cfg['RESHUFFLE_NUM']): # refresh file list required if cfg['RECENT_DAYS'] > 0 and not cfg['DATE_FROM']: # reset data_from to reflect that time is proceeding date_from = datetime.datetime.now() - datetime.timedelta(cfg['RECENT_DAYS']) date_from = (date_from.year, date_from.month, date_from.day) iFiles, nFi = get_files(date_from, date_to) num_run_through = 0 next_pic_num = 0 next_check_tm = tm + cfg['CHECK_DIR_TM'] # next check if tm > next_weather_tm: # refresh weather info weatherscreen.weather_refresh( weatherobj ) next_weather_tm = tm + cfg['W_REFRESH_DELAY'] # next check if cfg['KEYBOARD']: k = kbd.read() if k != -1: nexttm = time.time() if k==27: #ESC break if k==ord(' '): paused = not paused if k==ord('b'): # go back a picture next_pic_num -= 2 if next_pic_num < -1: next_pic_num = -1 if quit or show_camera: # set by MQTT break if cfg['KEYBOARD']: kbd.close() DISPLAY.destroy()
class Slide(object): def __init__(self): self.tex = None self.dimensions = None # Setup display and initialise pi3d DISPLAY = pi3d.Display.create(background=(0.3, 0.3, 0.3, 1.0), frames_per_second=FPS, tk=TK) if TK: win = DISPLAY.tkwin win.update() else: mykeys = pi3d.Keyboard( ) # don't need this for picture frame but useful for testing shader = [ pi3d.Shader("shaders/blend_star"), pi3d.Shader("shaders/blend_holes"), pi3d.Shader("shaders/blend_false"), pi3d.Shader("shaders/blend_burn"), pi3d.Shader("shaders/blend_bump") ] num_sh = len(shader) iFiles, nFi = get_files() fade = 0.0 pic_num = nFi - 1 canvas = pi3d.Canvas()
if W is None or H is None: (W, H) = (display.width, display.height) print('setting display size to ' + str(W) + ' ' + str(H)) ## shadertoy shader stuff ## sprite = pi3d.Triangle(corners=((-1.0, -1.0), (-1.0, 3.0), (3.0, -1.0))) shader = pi3d.Shader('cloud') sprite.set_shader(shader) ## offscreen texture stuff ## cam = pi3d.Camera(is_3d=False) postsh = pi3d.Shader('post_vanilla') post = pi3d.PostProcess(camera=cam, shader=postsh, scale=SCALE) ## interactive inputs ## kbd = pi3d.Keyboard() mouse = pi3d.Mouse() # pi3d.Mouse(restrict = True) # changes input coordinates mouse.start() MX, MY = mouse.position() MXC, MYC = mouse.position() MC = mouse.button_status( ) # 8 = hover, 9 = right Click down, 10 = left C, 12 = middle C MouseClicked = False ## set up time ## iTIME = 0 iTIMEDELTA = 0 iFRAME = 0 iDate = datetime.datetime.now() #print ("The current local date time is ", iDate) (YR, MTH, DAY) = (iDate.year, iDate.month, iDate.day)
rightEye.set_textures([scleraMap]) rightEye.set_shader(shader) reAxis(rightEye, 0.5) # Image map offset = 180 degree rotation leftEyeBackOfEye = pi3d.Lathe(path=ptsBackOfEye, sides=64) leftEyeBackOfEye.set_textures([scleraMapBackOfEye]) leftEyeBackOfEye.set_shader(shader) reAxis(leftEyeBackOfEye, 0) rightEyeBackOfEye = pi3d.Lathe(path=ptsBackOfEye, sides=64) rightEyeBackOfEye.set_textures([scleraMapBackOfEye]) rightEyeBackOfEye.set_shader(shader) reAxis(rightEyeBackOfEye, 0.5) # Image map offset = 180 degree rotation # Init global stuff -------------------------------------------------------- mykeys = pi3d.Keyboard() # For capturing key presses startX = random.uniform(-30.0, 30.0) n = math.sqrt(900.0 - startX * startX) startY = random.uniform(-n, n) destX = startX destY = startY curX = startX curY = startY moveDuration = random.uniform(0.075, 0.175) holdDuration = random.uniform(0.1, 1.1) startTime = 0.0 isMoving = False startXR = random.uniform(-30.0, 30.0) n = math.sqrt(900.0 - startX * startX)
root = tkinter.Tk() screen_W = root.winfo_screenwidth() screen_H = root.winfo_screenheight() preview_W = mdl_dims preview_H = mdl_dims preview_mid_X = int(screen_W / 2 - preview_W / 2) preview_mid_Y = int(screen_H / 2 - preview_H / 2) DISPLAY = pi3d.Display.create(0, 0, w=preview_W, h=preview_H, layer=1, frames_per_second=max_fps) DISPLAY.set_background(0.0, 0.0, 0.0, 0.0) # transparent keybd = pi3d.Keyboard() txtshader = pi3d.Shader("uv_flat") linshader = pi3d.Shader('mat_flat') CAMERA = pi3d.Camera(is_3d=False) font = pi3d.Font("fonts/FreeMono.ttf", font_size=30, color=(0, 255, 0, 255)) # blue green 1.0 alpha elapsed_ms = 1000 ms = str(elapsed_ms) ms_txt = pi3d.String(camera=CAMERA, is_3d=False, font=font, string=ms, x=0, y=preview_H / 2 - 30,
# Generate sclera for eye...start with a 2D shape for lathing... angle1 = zangle(eye_ScleraFrontPoints, eye_Radius)[1] # Sclera front angle angle2 = zangle(eye_ScleraBackPoints, eye_Radius)[1] # " back angle aRange = 180 - angle1 - angle2 pts = [] for i in range(24): ca, sa = pi3d.Utility.from_polar((90 - angle1) - aRange * i / 23) pts.append((ca * eye_Radius, sa * eye_Radius)) eyeLathe = pi3d.Lathe(path=pts, sides=64) eyeLathe.set_textures([eye_SCLERA_MAP]) eyeLathe.set_shader(shader) reAxis(eyeLathe, 0.0) # Init global stuff -------------------------------------------------------- thisKeyboard = pi3d.Keyboard() # For capturing key presses startX = random.uniform(-30.0, 30.0) n = math.sqrt(900.0 - startX * startX) startY = random.uniform(-n, n) destX = startX destY = startY curX = startX curY = startY moveDuration = random.uniform(0.075, 0.175) holdDuration = random.uniform(0.1, 1.1) startTime = 0.0 isMoving = False frames = 0 beginningTime = time.time()
SPRITES = load_sprites() # Load Asteroid models ASTEROIDS = load_asteroids() # Load sounds SOUNDS = init_sounds() # Setup I/O setup_io() # Initialize the IMU IMU = init_imu() # Fetch key presses KEYS = pi3d.Keyboard() # Read the current high scores try: high_score = int(file(HIGH_SCORE_FILENAME).readline()) except: high_score = 0 you_lose_screen = EndingScreen('you_lost.png', SOUNDS['lose']) high_score_screen = EndingScreen('new_high_scores.png') opening = OpeningScreen() while (True): # Wait until the user presses "start" opening.start()
flatsh = pi3d.Shader("uv_flat") asteroidShader = pi3d.Shader("uv_light") spaceShipTexture = pi3d.Texture('spaceshipTexture.jpg') asteroidSmall = pi3d.Texture('asteroidSmall.jpg') asteroidBig = pi3d.Texture('asteroidBig.jpg') asteroidMed = pi3d.Texture('asteroidM.jpg') backgroundTexture = pi3d.Texture('background.png') dangerZoneTexture = pi3d.Texture('dangerZone.jpg') safeZoneTexture = pi3d.Texture('safeZone.jpg') ship = pi3d.Sphere(z=20.0) asteroid = pi3d.Sphere(radius=50, z=520) spaceRocket = pi3d.Model(file_string='ship.obj', name='rocket', z=500.0) #spaceRocket.set_shader(flatsh) background = pi3d.Plane(w=1920, h=1080, name="stars", z=800) escapeSimulation = pi3d.Keyboard() newCoordinates = {'x': 4, 'y': 0, 'z': 1} flashGreen = "./FlashGreen" flashRed = "./FlashRed" pressure = './ReadPressure' sensorDataText = "./PrintSensorData" temp = './ReadTemperature' humidity = './PrintHumidityData' timeStamps = './TimeStamps' readOrientation = './ReadOrientation' health8 = './Health8' health7 = './Health7' health6 = './Health6' health5 = './Health5' health4 = './Health4'
def pi3d_model(): from sense_hat import SenseHat import math import pi3d sense = SenseHat() display = pi3d.Display.create() cam = pi3d.Camera.instance() shader = pi3d.Shader("mat_light") model = pi3d.Model( file_string="CS294.obj", name="model", x=0, y=-1, z=40, sx=7.5, sy=7.5, sz=7.5) model.set_shader(shader) cam.position((0, 20, 0)) cam.point_at((0, -1, 40)) keyb = pi3d.Keyboard() compass = gyro = accel = True sense.set_imu_config(compass, gyro, accel) yaw_offset = 133 while display.loop_running(): orientation = sense.get_orientation_radians() if orientation is None: pass pitch = orientation["pitch"] roll = orientation["roll"] yaw = orientation["yaw"] yaw_total = yaw + math.radians(yaw_offset) sin_y = math.sin(yaw_total) cos_y = math.cos(yaw_total) sin_p = math.sin(pitch) cos_p = math.cos(pitch) sin_r = math.sin(roll) cos_r = math.cos(roll) abs_roll = math.degrees(math.asin(sin_p * cos_y + cos_p * sin_r * sin_y)) abs_pitch = math.degrees(math.asin(sin_p * sin_y - cos_p * sin_r * cos_y)) model.rotateToZ(abs_roll) model.rotateToX(abs_pitch) model.rotateToY(math.degrees(yaw_total)) model.draw() keypress = keyb.read() if keypress == 27: keyb.close() display.destroy() break elif keypress == ord('m'): compass = not compass sense.set_imu_config(compass, gyro, accel) elif keypress == ord('g'): gyro = not gyro sense.set_imu_config(compass, gyro, accel) elif keypress == ord('a'): accel = not accel sense.set_imu_config(compass, gyro, accel) elif keypress == ord('='): yaw_offset += 1 elif keypress == ord('-'): yaw_offset -= 1
#!/usr/bin/python from __future__ import absolute_import, division, print_function, unicode_literals ''' Uses the pi3d.Graph class added to pi3d develop branch on Friday 13th Oct 2017 ''' import pi3d,smbus import numpy as np import pyaudio import time LINES = True # change this to see bar graph display = pi3d.Display.create(w=800, h=480, background=(0,0,0,1), frames_per_second=60) font = pi3d.Font("opensans.ttf") key = pi3d.Keyboard() if LINES: x_vals = np.linspace(0, 100, 100) y_vals = np.zeros((2,100)) W, H = 800, 480 xpos = (display.width - W) / 2 ypos = (display.height - H) / 2 graph = pi3d.Graph(x_vals, y_vals, W, H, font, title='Audio Peak Demo', line_width=3, xpos=xpos, ypos=ypos, axes_desc=['TIME', 'PEAK'], legend = [' ', ' '], ymax=20000,ymin=0)
else: self.menu_row_state += 1 self.menu_struct[self.menu_column_state][previous_menu_row_state].no_highlight() self.menu_struct[self.menu_column_state][self.menu_row_state].highlight() if __name__ == "__main__": # Load display screen DISPLAY = pi3d.Display.create(x=200, y=200) flatsh = pi3d.Shader("uv_flat") CAMERA2D = pi3d.Camera(is_3d=False) game_menu = GameMenu() MyKeys = pi3d.Keyboard() while DISPLAY.loop_running(): for column in game_menu.menu_struct: for row in column: row.fixed_string.draw() k = MyKeys.read() if k > -1: if k == 27: # Esc key MyKeys.close() DISPLAY.destroy() break elif k == 119: # up (w key)d game_menu.up() elif k == 115: # down (s key)
menu2 = pi3d.Menu(parent_item=mi1, menuitems=[mi11, mi12], horiz=False, position='below') menu3 = pi3d.Menu(parent_item=mi11, menuitems=[mi111, mi112], horiz=False, position='right') menu4 = pi3d.Menu(parent_item=mi12, menuitems=[mi121, mi122], horiz=False, position='right') textbox = pi3d.TextBox(gui, "type here", 100, -180, callback=cb, label='TextBox (KEY t to edit)', shortcut='t') mx, my = 0, 0 #inputs = pi3d.InputEvents() mouse = pi3d.Mouse(use_x=True, restrict=True) if pi3d.PLATFORM == pi3d.PLATFORM_PI: x_off = -DISPLAY.left - DISPLAY.width / 2 y_off = DISPLAY.top + DISPLAY.height / 2 - DISPLAY.max_height #inputs.get_mouse_movement() mouse.start() keyboard = pi3d.Keyboard() shifted = False caps = False while DISPLAY.loop_running(): #and not inputs.key_state("KEY_ESC"): mx, my = mouse.position() if pi3d.PLATFORM == pi3d.PLATFORM_PI: mx += x_off my += y_off buttons = mouse.button_status() model.draw() gui.draw(mx, my) if buttons == mouse.LEFT_BUTTON: gui.check(mx, my) kc = keyboard.read_code() if len(kc) > 0:
def world3dA(inHeightmap, inWidth, inDepth, inHeight, inTextureMap, inBumpMap): from PIL import Image import numpy as np DISPLAY = pi3d.Display.create(x=50, y=50, far=5000, near=0.5) CAMERA = pi3d.Camera.instance() base_tex = np.array(Image.open(inTextureMap)) # texture for land base_gr = base_tex.copy() ix = np.where(base_gr[:,:,2] > 20) # i.e. was blue base_gr[ix[0], ix[1], 1] += 50 # increase green base_gr[ix[0], ix[1], 2] = 0 # reduce blue texg = pi3d.Texture(base_gr) # texture for water base_bl = base_tex.copy() base_bl[:,:] = [0, 0, 60, 170] # uniform slightly transparrent texb = pi3d.Texture(base_bl) grass_tex = pi3d.Texture('/home/patrick/raspberry_pi/pi3d_demos/textures/grasstile_n.jpg') w_norm = pi3d.Texture('/home/patrick/raspberry_pi/pi3d_demos/textures/water/n_norm000.png') shader = pi3d.Shader("uv_bump") rshader = pi3d.Shader("uv_reflect") mapwidth = inWidth mapdepth = inDepth mapheight = inHeight mymap = pi3d.ElevationMap(inHeightmap, width=mapwidth, depth=mapdepth, height=mapheight, divx=199, divy=199, ntiles=1, name="sub", y=-0.0) mymap.set_draw_details(shader, [texg, grass_tex], 200.0) wmap = pi3d.ElevationMap(inHeightmap, width=mapwidth, depth=mapdepth, height=mapheight * 0.1, divx=40, divy=40, ntiles=1, name="water", y=25.0) wmap.set_draw_details(rshader, [texb, w_norm, texg], 500.0, 0.2) rot = 0.0 tilt = 0.0 height = 20.0 viewHeight = 1.5 sky = 2000 xm, ym, zm = 0.0, height, 0.0 onGround = False mykeys = pi3d.Keyboard() mymouse = pi3d.Mouse(restrict=False) mymouse.start() omx, omy = mymouse.position() fr = 0 while DISPLAY.loop_running(): mx, my = mymouse.position() rot -= (mx - omx) * 0.2 tilt -= (my - omy) * 0.2 omx = mx omy = my CAMERA.reset() CAMERA.rotate(-tilt, rot, 0) CAMERA.position((xm, ym, zm)) mymap.draw() wmap.draw() k = mykeys.read() if k > -1: if k == 48: # ESCAPE key - '0' Key DISPLAY.destroy() mykeys.close() mymouse.stop() break elif k == 87 or k == 119: # if inputs.key_state("KEY_W"): xm -= sin(radians(rot)) * 2.0 zm += cos(radians(rot)) * 2.0 elif k == 83 or k == 115: # elif inputs.key_state("KEY_S"): xm += sin(radians(rot)) * 2.0 zm -= cos(radians(rot)) * 2.0 elif k == 82 or k == 114: # elif inputs.key_state("KEY_R"): ym += 4 onGround = False elif k == 84 or k == 116: # elif inputs.key_state("KEY_T"): ym -= 4 ym -= 0.2 xm = limit(xm, -(mapwidth / 2), (mapwidth / 2)) zm = limit(zm, -(mapdepth / 2), (mapdepth / 2)) if ym >= sky: ym = sky ground = max(mymap.calcHeight(xm, zm), wmap.calcHeight(xm, zm)) + viewHeight if (onGround is True) or (ym <= ground): ym = ground onGround = True pi3d.screenshot("/home/patrick/Downloads/Untitled Folder/scr_caps/world{:04d}.jpg".format(fr)) fr += 1
def main(fname="assets/dictionaries/words.txt", N=12): # create display DISPLAY = pi3d.Display.create(background=(0.7, 0.3, 0.9, 1)) # create camera and move it back a bit CAM = pi3d.Camera(at=(0.5, N / 2, 0.0), eye=(0.25, N / 2, -1.5 * N)) letter_matrix = create_letter_matrix(N) cubeMap = [] heightMap = gen_heightMap(N) draw_cubeMap(cubeMap, heightMap, N) # create keyboard listener keys = pi3d.Keyboard() # load shaders shader = pi3d.Shader("uv_bump") lshader = pi3d.Shader('uv_light') shinesh = pi3d.Shader("uv_reflect") matsh = pi3d.Shader("mat_reflect") #Place the words in the matrix placeWords(fname, letter_matrix, N) randomize_empty_cells(letter_matrix, N) print(letter_matrix) r = 0 light = pi3d.Light(lightpos=(-3, -10, 5), lightcol=(0.5, 0.5, 0.5), lightamb=(0.5, 0.5, 0.5), is_point=False) # set cube details for i, cuberow in enumerate(cubeMap): for j, cube in enumerate(cuberow): string1 = pi3d.FixedString(camera=CAM, font="fonts/FreeSans.ttf", font_size=12, string=letter_matrix[i][j] + ("\n" * int(math.ceil(cube.height))), color="#FFFFFF", justify="C", f_type="SMOOTH", background_color="#000000" ) # EMBOSS, CONTOUR, BLUR, SMOOTH, BUMP cube.set_draw_details(lshader, [string1], 1.0) cube.set_light(light, 0) # display loop try: while DISPLAY.loop_running(): CAM.relocate(rot=r, distance=[-5, -5, -5]) #draw loop for cuberow in cubeMap: for cube in cuberow: cube.draw() # take a screenshot every 90 degree rotation if r % 90 == 0: pi3d.util.Screenshot.screenshot("screen_" + str(r) + ".png") r += 1 # only do one rotation if r == 360: break # handle escape if keys.read() == 27: break finally: # can also except KeyboardInterrup: for ctrl c specific things keys.close() DISPLAY.destroy()
#screenshot number scshots = 1 #avatar camera rot = 0.0 tilt = 0.0 avhgt = 7.0 xm = 0.0 zm = 0.0 ym = mymap.calcHeight(xm, zm) + avhgt myshadows = pi3d.ShadowCaster(position=[xm, ym, zm], light=mylight) # Fetch key presses mykeys = pi3d.Keyboard() mymouse = pi3d.Mouse(restrict = False) mymouse.start() omx, omy = mymouse.position() # main loop while DISPLAY.loop_running(): CAMERA.reset() CAMERA.rotate(tilt, rot, 0) CAMERA.position((xm, ym, zm)) xrot += dxrot yrot += dyrot zrot += dzrot angle += rotn
def pi3d_model(): from sense_hat import SenseHat import math import pi3d sense = SenseHat() display = pi3d.Display.create() cam = pi3d.Camera.instance() shader = pi3d.Shader("mat_light") # .obj file is read in and x,y,z size(s) are determined model = pi3d.Model(file_string="apollo-soyuz.obj", name="model", x=0, y=-1, z=40, sx=1.5, sy=1.5, sz=1.5) model.set_shader(shader) cam.position((0, 20, 0)) cam.point_at((0, -1, 40)) keyb = pi3d.Keyboard() compass = gyro = accel = True sense.set_imu_config(compass, gyro, accel) yaw_offset = 133 # This offset aligns the model with the Pi while display.loop_running(): orientation = sense.get_orientation_radians() if orientation is None: pass pitch = orientation["pitch"] roll = orientation["roll"] yaw = orientation["yaw"] yaw_total = yaw + math.radians(yaw_offset) # Maths! sin_y = math.sin(yaw_total) cos_y = math.cos(yaw_total) sin_p = math.sin(pitch) cos_p = math.cos(pitch) sin_r = math.sin(roll) cos_r = math.cos(roll) abs_roll = math.degrees( math.asin(sin_p * cos_y + cos_p * sin_r * sin_y)) abs_pitch = math.degrees( math.asin(sin_p * sin_y - cos_p * sin_r * cos_y)) model.rotateToZ(abs_roll) model.rotateToX(abs_pitch) model.rotateToY(math.degrees(yaw_total)) model.draw() keypress = keyb.read() if keypress == 27: keyb.close() display.destroy() break elif keypress == ord('m'): # Toggles Magnetometer compass = not compass sense.set_imu_config(compass, gyro, accel) elif keypress == ord('g'): # Toggles Gyroscope gyro = not gyro sense.set_imu_config(compass, gyro, accel) elif keypress == ord('a'): # Toggles Accelerometer accel = not accel sense.set_imu_config(compass, gyro, accel) elif keypress == ord('='): # Increases yaw offset yaw_offset += 1 elif keypress == ord('-'): # Decreases yaw offset yaw_offset -= 1