MIN_BALL_SIZE = 15 # z value is used to determine point size MAX_BALL_SIZE = 75 MAX_BALL_VELOCITY = 3.0 min_dist = 1.001 max_dist = 0.001 + float(MAX_BALL_SIZE) / MIN_BALL_SIZE LOGGER = pi3d.Log.logger(__name__) BACKGROUND_COLOR = (0.0, 0.0, 0.0, 0.0) DISPLAY = pi3d.Display.create(background=BACKGROUND_COLOR) HWIDTH, HHEIGHT = DISPLAY.width / 2.0, DISPLAY.height / 2.0 KEYBOARD = pi3d.Keyboard() CAMERA = pi3d.Camera(is_3d=False) shader = pi3d.Shader("shaders/uv_sprite") ballimg = [ pi3d.Texture("textures/red_ball.png"), pi3d.Texture("textures/blu_ball.png"), pi3d.Texture("textures/grn_ball.png") ] loc = np.zeros((MAX_BALLS, 3)) loc[:, 0] = np.random.uniform(-HWIDTH, HWIDTH, MAX_BALLS) loc[:, 1] = np.random.uniform(-HHEIGHT, HHEIGHT, MAX_BALLS) loc[:, 2] = np.random.uniform(min_dist, max_dist, MAX_BALLS) vel = np.random.uniform(-MAX_BALL_VELOCITY, MAX_BALL_VELOCITY, (MAX_BALLS, 2)) dia = (MIN_BALL_SIZE + (max_dist - loc[:, 2]) / (max_dist - min_dist) * (MAX_BALL_SIZE - MIN_BALL_SIZE)) mass = dia * dia
button1_pressed = False button2_pressed = False button3_pressed = False button4_pressed = False explosion = False # Has the explosion occured? overloading = 0 # We're in overload mode # Set up the environment DISPLAY = pi3d.Display.create() #DISPLAY = pi3d.Display.create(w=800, h=600) # For debugging DISPLAY.set_background(0.0, 0.0, 0.0, 1) # Black CAM = pi3d.Camera(eye=(0.0, 0.0, -7.0)) CAM2D = pi3d.Camera(is_3d=False) lights = pi3d.Light(lightamb=(0.8, 0.8, 0.9)) shader = pi3d.Shader('uv_light') flatshader = pi3d.Shader("uv_flat") fontfile = '/home/pi/pi3d_demos-master/fonts/NotoSans-Regular.ttf' font = pi3d.Font(fontfile, font_size=32, color=(255, 255, 255, 255)) font.blend = True xmargin = DISPLAY.width * 0.05 ymargin = DISPLAY.height * 0.05 topleftx = DISPLAY.width / -2 + xmargin # Top left corner starting X coordinate for stuff toplefty = DISPLAY.height / 2 - ymargin # Top left corner starting Y coordinate for stuff backplaneZ = 0 # Mining "Stats" num_stations = 120 num_online_stations = num_stations
winw, winh, bord = 1200, 600, 0 #64MB GPU memory setting #winw,winh,bord = 1920,1080,0 #128MB GPU memory setting DISPLAY = pi3d.Display.create(tk=True, window_title='Mars Station demo in Pi3D', w=winw, h=winh - bord, far=2200.0, background=(0.4, 0.8, 0.8, 1), frames_per_second=20) #inputs = InputEvents() win = DISPLAY.tkwin shader = pi3d.Shader("uv_reflect") bumpsh = pi3d.Shader("uv_bump") flatsh = pi3d.Shader("uv_flat") shade2d = pi3d.Shader('2d_flat') #======================================== # create splash screen and draw it splash = pi3d.ImageSprite("textures/pi3d_splash.jpg", shade2d, w=10, h=10, z=0.2) splash.draw() DISPLAY.swap_buffers() ############################# ectex = pi3d.loadECfiles("textures/ecubes/RedPlanet", "redplanet_256", "png",
sc = Server(hostname=hostIP, port=9090) # used for volume and play/pause scNP = Server(hostname=hostIP, port=9090) # used only to get Now Playing cover.jpg sleep(60) # allow time for LMS to start, otherwise get ConnectionError 111 sc.connect() scNP.connect() sq = sc.get_player(player_id) sqNP = scNP.get_player( player_id ) # UGLY KLUDGE! Avoids conflict with volume routine which caused bad refresh on album cover.jpg DISPLAY = pi3d.Display.create(use_pygame=True, samples=4) DISPLAY.set_background(0, 0, 0, 1) #r,g,b and alpha shader = pi3d.Shader("uv_flat") CAMERA = pi3d.Camera(is_3d=False) # Radio Dial Sprites radio_needle = pi3d.ImageSprite("/home/pi/miniz/textures/needle.png", shader, w=64.0, h=288.0, x=0.0, y=-30.0, z=4.0) # dial below was named miniZ_Full_simple_dial_v2_metal_ring.png in dev radio_dial = pi3d.ImageSprite("/home/pi/miniz/textures/dial.png", shader, w=320.0,
def _prepare(self) -> None: self.should_prepare = False import numpy as np # pi3d has to be imported in the same thread that it will draw in # Thus, import it here instead of at the top of the file import pi3d from pi3d.util.OffScreenTexture import OffScreenTexture from pi3d.constants import opengles, GL_CLAMP_TO_EDGE, GL_ALWAYS # used for reimplementing the draw call with instancing from pi3d.constants import ( GLsizei, GLint, GLboolean, GL_FLOAT, GLuint, GL_ARRAY_BUFFER, GL_STATIC_DRAW, GLfloat, ) from PIL import Image # Setup display and initialise pi3d self.display = pi3d.Display.create( w=self.width, h=self.height, window_title="Raveberry" # , use_glx=True ) # error 0x500 after Display create # error = opengles.glGetError() # Set a pink background color so mistakes are clearly visible # self.display.set_background(1, 0, 1, 1) # with an alpha value of 1 flat glx renders the window transparently for some reason # so instead we use a value slightly smaller than 1 # self.display.set_background(0, 0, 0, 0.999) self.display.set_background(0, 0, 0, 1) # print OpenGL Version, useful for debugging # import ctypes # from pi3d.constants import GL_VERSION # def print_char_p(addr): # g = (ctypes.c_char * 32).from_address(addr) # i = 0 # while True: # try: # c = g[i] # except IndexError: # break # if c == b"\x00": # break # sys.stdout.write(c.decode()) # i += 1 # sys.stdout.write("\n") # print_char_p(opengles.glGetString(GL_VERSION)) # Visualization is split into five parts: # The background, the particles, the spectrum, the logo and after effects. # * The background is a vertical gradient that cycles through HSV color space, # speeding up with strong bass. # * Particles are multiple sprites that are created at a specified x,y-coordinate # and fly towards the camera. # Due to the projection into screenspace they seem to move away from the center. # * The spectrum is a white circle that represents the fft-transformation of the # currently played audio. It is smoothed to avoid strong spikes. # * The logo is a black circle on top of the spectrum containing the logo. # * After effects add a vignette. # Each of these parts is represented with pi3d Shapes. # They have their own shader and are ordered on the z-axis to ensure correct overlapping. background_shader = pi3d.Shader( os.path.join(settings.BASE_DIR, "core/lights/circle/background")) self.background = pi3d.Sprite(w=2, h=2) self.background.set_shader(background_shader) self.background.positionZ(0) self.particle_shader = pi3d.Shader( os.path.join(settings.BASE_DIR, "core/lights/circle/particle")) # create one sprite for all particles self.particle_sprite = pi3d.Sprite(w=self.PARTICLE_SIZE, h=self.PARTICLE_SIZE) self.particle_sprite.set_shader(self.particle_shader) self.particle_sprite.positionZ(0) # this array containes the position and speed for all particles particles = self._initial_particles() # This part was modified from https://learnopengl.com/Advanced-OpenGL/Instancing self.instance_vbo = GLuint() opengles.glGenBuffers(GLsizei(1), ctypes.byref(self.instance_vbo)) opengles.glBindBuffer(GL_ARRAY_BUFFER, self.instance_vbo) particles_raw = particles.ctypes.data_as(ctypes.POINTER(GLfloat)) opengles.glBufferData(GL_ARRAY_BUFFER, particles.nbytes, particles_raw, GL_STATIC_DRAW) opengles.glBindBuffer(GL_ARRAY_BUFFER, GLuint(0)) attr_particle = opengles.glGetAttribLocation( self.particle_shader.program, b"particle") opengles.glEnableVertexAttribArray(attr_particle) opengles.glBindBuffer(GL_ARRAY_BUFFER, self.instance_vbo) opengles.glVertexAttribPointer(attr_particle, GLint(4), GL_FLOAT, GLboolean(0), 0, 0) opengles.glBindBuffer(GL_ARRAY_BUFFER, GLuint(0)) opengles.glVertexAttribDivisor(attr_particle, GLuint(1)) spectrum_shader = pi3d.Shader( os.path.join(settings.BASE_DIR, "core/lights/circle/spectrum")) # use the ratio to compute small sizes for the sprites ratio = self.width / self.height self.spectrum = pi3d.Sprite(w=2 / ratio, h=2) self.spectrum.set_shader(spectrum_shader) self.spectrum.positionZ(0) # initialize the spectogram history with zeroes self.fft = np.zeros( (self.FFT_HIST, self.cava.bars - 2 * self.SPECTRUM_CUT), dtype=np.uint8) logo_shader = pi3d.Shader( os.path.join(settings.BASE_DIR, "core/lights/circle/logo")) self.logo = pi3d.Sprite(w=1.375 / ratio, h=1.375) self.logo.set_shader(logo_shader) self.logo.positionZ(0) logo_image = Image.open( os.path.join(settings.BASE_DIR, "core/lights/circle/raveberry.png")) self.logo_array = np.frombuffer(logo_image.tobytes(), dtype=np.uint8) self.logo_array = self.logo_array.reshape( (logo_image.size[1], logo_image.size[0], 3)) # add space for the spectrum self.logo_array = np.concatenate( ( self.logo_array, np.zeros( (self.FFT_HIST, logo_image.size[0], 3), dtype=np.uint8), ), axis=0, ) # add alpha channel self.logo_array = np.concatenate( ( self.logo_array, np.ones( (self.logo_array.shape[0], self.logo_array.shape[1], 1), dtype=np.uint8, ), ), axis=2, ) # In order to save memory, the logo and the spectrum share one texture. # The upper 256x256 pixels are the raveberry logo. # Below are 256xFFT_HIST pixels for the spectrum. # The lower part is periodically updated every frame while the logo stays static. self.dynamic_texture = pi3d.Texture(self.logo_array) # Prevent interpolation from opposite edge self.dynamic_texture.m_repeat = GL_CLAMP_TO_EDGE self.spectrum.set_textures([self.dynamic_texture]) self.logo.set_textures([self.dynamic_texture]) after_shader = pi3d.Shader( os.path.join(settings.BASE_DIR, "core/lights/circle/after")) self.after = pi3d.Sprite(w=2, h=2) self.after.set_shader(after_shader) self.after.positionZ(0) # create an OffscreenTexture to allow scaling. # By first rendering into a smaller Texture a lot of computation is saved. # This OffscreenTexture is then drawn at the end of the draw loop. self.post = OffScreenTexture("scale") self.post_sprite = pi3d.Sprite(w=2, h=2) post_shader = pi3d.Shader( os.path.join(settings.BASE_DIR, "core/lights/circle/scale")) self.post_sprite.set_shader(post_shader) self.post_sprite.set_textures([self.post]) self.total_bass = 0 self.last_loop = time.time() self.time_elapsed = 0 opengles.glDepthFunc(GL_ALWAYS)
import demo import pi3d # Setup display and initialise pi3d DISPLAY = pi3d.Display.create(x=200, y=200) DISPLAY.set_background(0.4, 0.8, 0.8, 1) # r,g,b,alpha # yellowish directional light blueish ambient light pi3d.Light(lightpos=(1, -1, -3), lightcol=(1.0, 1.0, 0.8), lightamb=(0.25, 0.2, 0.3)) #======================================== # load shader shader = pi3d.Shader("uv_bump") shinesh = pi3d.Shader("uv_reflect") flatsh = pi3d.Shader("uv_flat") tree2img = pi3d.Texture("textures/tree2.png") tree1img = pi3d.Texture("textures/tree1.png") hb2img = pi3d.Texture("textures/hornbeam2.png") bumpimg = pi3d.Texture("textures/grasstile_n.jpg") reflimg = pi3d.Texture("textures/stars.jpg") floorimg = pi3d.Texture("textures/floor_nm.jpg") FOG = ((0.3, 0.3, 0.4, 0.8), 650.0) TFOG = ((0.2, 0.24, 0.22, 1.0), 150.0) #myecube = pi3d.EnvironmentCube(900.0,"HALFCROSS") ectex = pi3d.loadECfiles("textures/ecubes", "sbox")
""" Example showing what can be left out. ESC to quit""" import demo import pi3d DISPLAY = pi3d.Display.create(x=150, y=150) shader = pi3d.Shader("shaders/2d_flat") sprite = pi3d.ImageSprite("textures/PATRN.PNG", shader, w=10.0, h=10.0, z=1.0) mykeys = pi3d.Keyboard() while DISPLAY.loop_running(): sprite.draw() if mykeys.read() == 27: mykeys.close() DISPLAY.destroy() break
#a default camera is created automatically but we might need a 2nd 2D camera #for displaying the instruments etc. Also, because the landscape is large #we need to set the far plane to 10,000 CAMERA = pi3d.Camera(lens=(1.0, 10000.0, 55.0, 1.6)) CAMERA2D = pi3d.Camera(is_3d=False) print("""=================================== == W increase power, S reduce power == V view mode, C control mode == B brakes == mouse movement joystick == Left button fire! == X jumps to location of 1st enemy in list ================================""") SHADER = pi3d.Shader("uv_bump") #for objects to look 3D ELEVSH = pi3d.Shader("uv_elev_map") # for multi textured terrain FLATSH = pi3d.Shader("uv_flat") #for 'unlit' objects like the background GRAVITY = 9.8 #m/s**2 LD = 10 #lift/drag ratio DAMPING = 0.95 #reduce roll and pitch rate each update_variables BOOSTER = 1.5 #extra manoevreability boost to defy 1st Low of Thermodynamics. #load bullet images BULLET_TEX = [] #list to hold Texture refs iFiles = glob.glob(sys.path[0] + "/textures/biplane/bullet??.png") iFiles.sort() # order is vital to animation! for f in iFiles: BULLET_TEX.append(pi3d.Texture(f)) DAMAGE_FACTOR = 50 #dived by distance of shoot() NR_TM = 1.0 #check much less frequently until something comes back
print('RPi.GPIO not here you can simulate pulses with the w key. Ex={}'.format(e)) from pi3d.util.Scenery import Scene, SceneryItem # Setup display and initialise pi3d DISPLAY = pi3d.Display.create() DISPLAY.set_background(0.5, 0.4, 0.6,1.0) # r,g,b,alpha # yellowish directional light blueish ambient light pi3d.Light(lightpos=(1, -1, -3), lightcol =(0.7, 0.7, 0.6), lightamb=(0.4, 0.3, 0.5)) MSIZE = 1000 NX = 5 NZ = 5 # load shaders flatsh = pi3d.Shader("uv_flat") FOG = ((0.3, 0.3, 0.41, 0.99), 500.0) TFOG = ((0.3, 0.3, 0.4, 0.95), 300.0) from alpine import * try: f = open(sc.path + '/map00.pkl', 'r') #do this once to create the pickled objects f.close() except IOError: sc.do_pickle(FOG) #myecube = pi3d.EnvironmentCube(900.0,"HALFCROSS") ectex = pi3d.loadECfiles("textures/ecubes","sbox") myecube = pi3d.EnvironmentCube(size=7000.0, maptype="FACES", name="cube")
MAX_CAM_TILT = 90 MAX_V_CUE = 40 # Load display screen DISPLAY = pi3d.Display.create(x=100, y=100, samples=2) # Initial Game Type table.BilliardTable.set_detail_auto(table_type=table.TableType.POOL, table_size=table.TableSize.EIGHT_FT, game_type=table.GameType.POOL_9_BALL) calculate.BilliardBall.set_r(table.BilliardTable.r) calculate.BilliardBall.set_mass(common.DEF_BALL_MASS, common.DEF_CUE_MASS) calculate.CalConst.initial_constant() # Create Shader BallShader = pi3d.Shader("mat_reflect") TableShader = BallShader ShadowShader = pi3d.Shader("uv_flat") Normtex = pi3d.Texture("media/textures/grasstile_n.jpg") Shinetex = pi3d.Texture("media/textures/photosphere_small.jpg") Shadowtex = pi3d.Texture("media/textures/shadow.png") # Create Light light_source = pi3d.Light( lightpos=(10, -(table.BilliardTable.table_height + calculate.BilliardBall.r) * common.DIM_RATIO * 5.2, 1), lightcol=(0.9, 0.9, 0.8), lightamb=(0.3, 0.3, 0.3), is_point=False)
import math,random import demo import pi3d # Setup display and initialise pi3d DISPLAY = pi3d.Display.create(x=200, y=200) DISPLAY.set_background(0.4,0.8,0.8,1) # r,g,b,alpha # yellowish directional light blueish ambient light pi3d.Light(lightpos=(1, -1, -3), lightcol =(1.0, 1.0, 0.8), lightamb=(0.25, 0.2, 0.3)) #======================================== # load shader shader = pi3d.Shader("shaders/uv_reflect") flatsh = pi3d.Shader("shaders/uv_flat") tree2img = pi3d.Texture("textures/tree2.png") tree1img = pi3d.Texture("textures/tree1.png") hb2img = pi3d.Texture("textures/hornbeam2.png") bumpimg = pi3d.Texture("textures/grasstile_n.jpg") reflimg = pi3d.Texture("textures/stars.jpg") rockimg = pi3d.Texture("textures/rock1.jpg") FOG = ((0.3, 0.3, 0.4, 0.5), 650.0) TFOG = ((0.2, 0.24, 0.22, 0.3), 150.0) #myecube = pi3d.EnvironmentCube(900.0,"HALFCROSS") ectex=pi3d.loadECfiles("textures/ecubes","sbox") myecube = pi3d.EnvironmentCube(size=900.0, maptype="FACES", name="cube")
display = pi3d.Display.create(window_title='shader', w=W, h=H, frames_per_second=fps, background=BACKGROUND_COLOR, display_config=pi3d.DISPLAY_CONFIG_HIDE_CURSOR | pi3d.DISPLAY_CONFIG_MAXIMIZED, use_glx=True) print(display.opengl.gl_id) if W is None or H is None: (W, H) = (display.width, display.height) # make shader sprite = pi3d.Triangle(corners=((-1.0, -1.0), (-1.0, 3.0), (3.0, -1.0))) shader = pi3d.Shader('shadertoy01') sprite.set_shader(shader) ## offscreen texture stuff ## cam = pi3d.Camera(is_3d=False) flatsh = pi3d.Shader('post_vanilla') post = pi3d.PostProcess(camera=cam, shader=flatsh, scale=SCALE) ## set up time ## iTIME = 0 iTIMEDELTA = 0 ## pass shadertoy uniforms into our base shader from shadertoy ## sprite.unif[0:2] = [W, H] # iResolution sprite.unif[2] = iTIME # iTime - shader playback time sprite.unif[
per = int(self.freq * self.size) for o in range(self.octs): val += 0.5**o * self.noise(xy * 2**o, per * 2**o) return val DISPLAY = pi3d.Display.create(x=50, y=50, frames_per_second=20, background=(0.6, 0.5, 0.0, 1.0)) opengles.glDisable( GL_CULL_FACE ) # do this as it will be possible to look under terrain, has to done after Display.create() shader = pi3d.Shader("mat_light") flatsh = pi3d.Shader("mat_flat") perlin = Noise3D(PSIZE, PFREQ, POCT) # size of grid, frequency of noise, # number of octaves, use 5 octaves as reasonable balance #### generate terrain norms = [] tex_coords = [] idx = [] wh = hh = W / 2.0 # half size ws = hs = W / (IX - 1.0) # dist between each vert tx = tz = 1.0 / IX verts = np.zeros((IZ, IX, 3), dtype=float) # c order arrays xy = np.array([[[x, y] for x in range(IX)] for y in range(IZ)])
npa[:, :, 3] = 255 # fill alpha value npa[:, :, 0:3] = output.array # copy in rgb bytes new_pic = True time.sleep(0.05) t = threading.Thread(target=get_pics) # set up and start capture thread t.daemon = True t.start() while not new_pic: # wait for array to be filled first time time.sleep(0.1) ######################################################################## DISPLAY = pi3d.Display.create(x=150, y=150, frames_per_second=30) shader = pi3d.Shader("shaders/night_vision") CAMERA = pi3d.Camera(is_3d=False) tex = pi3d.Texture(npa) rim = pi3d.Texture('textures/snipermode.png') noise = pi3d.Texture('textures/Roof.png') sprite = pi3d.Sprite(w=DISPLAY.height * tex.ix / tex.iy, h=DISPLAY.height, z=5.0) sprite.set_draw_details(shader, [tex, rim, noise]) mykeys = pi3d.Keyboard() lum_threshold = 0.2 lum_amplification = 4.0 while DISPLAY.loop_running():
h=H, frames_per_second=fps, background=BACKGROUND_COLOR, display_config=pi3d.DISPLAY_CONFIG_HIDE_CURSOR | pi3d.DISPLAY_CONFIG_MAXIMIZED, use_glx=True) print(display.opengl.gl_id) # the type of glsl your pi is running 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') #shader = pi3d.Shader('shadertoy01') 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(
#!/usr/bin/python from __future__ import absolute_import, division, print_function, unicode_literals import pi3d from picamera import PiCamera DISPLAY = pi3d.Display.create(x=0, y=0, background=(0.0,0.0,0.0,0.0), layer=3) CAMERA = pi3d.Camera(at=(0, 0, 1), eye=(0, 0, 0)) TEXT_CAMERA = pi3d.Camera(is_3d=False) piCamera = PiCamera() piCamera.start_preview() # Shaders shader = pi3d.Shader("uv_light") shinesh = pi3d.Shader("uv_reflect") flatsh = pi3d.Shader("uv_flat") matsh = pi3d.Shader("mat_reflect") ################################# # Textures patimg = pi3d.Texture("textures/PATRN.PNG") shapebump = pi3d.Texture("textures/floor_nm.jpg") shapshine = pi3d.Texture("textures/stars.jpg") light = pi3d.Light(lightpos=(-1.0, 0.0, 10.0), lightcol=(3.0, 3.0, 2.0), lightamb=(0.02, 0.01, 0.03), is_point=True) # Create shape cylinder = pi3d.EnvironmentCube(light=light, size=1, name="Cylinder", x=0, y=0, z=5) cylinder.set_line_width(2) # Text arialFont = pi3d.Font("fonts/FreeMonoBoldOblique.ttf", (221,0,170,255)) delta = 1
# Setup display and initialise pi3d DISPLAY = pi3d.Display.create(x=0, y=0, background=(0.0, 0.0, 0.0, 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) flatsh = pi3d.Shader('uv_flat') iFiles, nFi = get_files() fade = 0.0 pic_num = nFi - 1 canvas = pi3d.Canvas() canvas.set_shader(shader[0]) CAMERA = pi3d.Camera(is_3d=False)
#!/usr/bin/python from __future__ import absolute_import, division, print_function, unicode_literals """ Wavefront obj model loading. Material properties set in mtl file. Uses the import pi3d method to load *everything* """ import demo import pi3d # Setup display and initialise pi3d DISPLAY = pi3d.Display.create(x=100, y=100, background=(0.2, 0.4, 0.6, 1), frames_per_second=30) shader = pi3d.Shader("uv_reflect") #======================================== # this is a bit of a one off because the texture has transparent parts # comment out and google to see why it's included here. pi3d.opengles.glDisable(pi3d.GL_CULL_FACE) #======================================== # load bump and reflection textures bumptex = pi3d.Texture("textures/floor_nm.jpg") shinetex = pi3d.Texture("textures/stars.jpg") # load model_loadmodel mymodel = pi3d.Model(file_string='models/teapot.obj', name='teapot', z=4.0) mymodel.set_shader(shader) mymodel.set_normal_shine(bumptex, 16.0, shinetex, 0.5) # Fetch key presses mykeys = pi3d.Keyboard() while DISPLAY.loop_running(): mymodel.draw() mymodel.rotateIncY(0.41)
screen_W = root.winfo_screenwidth() screen_H = root.winfo_screenheight() preview_W = 320 preview_H = 320 preview_mid_X = int(screen_W / 2 - preview_W / 2) preview_mid_Y = int(screen_H / 2 - preview_H / 2) DISPLAY = pi3d.Display.create(preview_mid_X, preview_mid_Y, 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 x1 = x2 = x3 = x4 = x5 = y1 = y2 = y3 = y4 = y5 = z = 1 bbox_vertices = [[x1, y1, z], [x2, y2, z], [x3, y3, z], [x4, y4, z]] bbox = pi3d.Lines(vertices=bbox_vertices, material=(1.0, 0.8, 0.05), closed=True, line_width=4) bbox.set_shader(linshader) fps = "00.00FPS" N = 10 fps_txt = pi3d.String(camera=CAMERA, is_3d=False,
import pi3d from vrzero import engine engine.show_stats = True # Uncomment these if using a HDMI screen. #engine.use_simple_display=True #engine.use_crosseyed_method=True # Change the eye seperation setting: #engine.hmd_eye_seperation=0.6 # VR Zero init, must be done *before* Pi3D setup. engine.init() # Pi3D scene setup... shader = pi3d.Shader("uv_light") flatsh = pi3d.Shader("uv_flat") ectex = pi3d.loadECfiles("textures/ecubes", "sbox") myecube = pi3d.EnvironmentCube(size=900.0, maptype="FACES", name="bfa", y=50.0) myecube.set_draw_details(flatsh, ectex) mymodel = pi3d.Model(name="Abbey", file_string="models/Buckfast Abbey/BuckfastAbbey.egg", rx=90, sx=0.03, sy=0.03, sz=0.03) mymodel.set_shader(shader) # VR Zero config and main loop with Pi3D drawing
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()
DISPLAY.set_background(0, 0, 0, 1) # r,g,b,alpha # eyeRadius is the size, in pixels, at which the whole eye will be rendered. if DISPLAY.width <= (DISPLAY.height * 2): # For WorldEye, eye size is -almost- full screen height eyeRadius = DISPLAY.height / 2.1 else: eyeRadius = DISPLAY.height * 2 / 5 # A 2D camera is used, mostly to allow for pixel-accurate eye placement, # but also because perspective isn't really helpful or needed here, and # also this allows eyelids to be handled somewhat easily as 2D planes. # Line of sight is down Z axis, allowing conventional X/Y cartesion # coords for 2D positions. cam = pi3d.Camera(is_3d=False, at=(0, 0, 0), eye=(0, 0, -1000)) shader = pi3d.Shader("uv_light") light = pi3d.Light(lightpos=(0, -500, -500), lightamb=(0.2, 0.2, 0.2)) # Load texture maps -------------------------------------------------------- irisMap = pi3d.Texture("graphics/dragon-iris.jpg", mipmap=False, filter=pi3d.GL_LINEAR) scleraMap = pi3d.Texture("graphics/dragon-sclera.png", mipmap=False, filter=pi3d.GL_LINEAR, blend=True) lidMap = pi3d.Texture("graphics/lid.png", mipmap=False, filter=pi3d.GL_LINEAR, blend=True)
npa[:, :, 3] = 255 npa[:, :, 0:3] = output.array new_pic = True time.sleep(0.05) t = threading.Thread(target=get_pics) t.daemon = True t.start() while not new_pic: time.sleep(0.1) # Setup display and initialise pi3d DISPLAY = pi3d.Display.create(x=100, y=100, background=(0.2, 0.4, 0.6, 1)) shader = pi3d.Shader("uv_reflect") flatsh = pi3d.Shader('uv_flat') #======================================== # this is a bit of a one off because the texture has transparent parts # comment out and google to see why it's included here. from pi3d import opengles, GL_CULL_FACE opengles.glDisable(GL_CULL_FACE) #======================================== # load bump and reflection textures bumptex = pi3d.Texture("textures/floor_nm.jpg") shinetex = pi3d.Texture(npa) # load model_loadmodel mymodel = pi3d.Model(file_string='models/teapot.obj', name='teapot') mymodel.set_shader(shader) mymodel.set_normal_shine(bumptex, 0.0, shinetex, 0.7)
class Main(object): # Setup display and initialise pi3d DISPLAY = pi3d.Display.create() pi3d.Light(lightpos=(1, -1, -3), lightcol=(1.0, 1.0, 0.8), lightamb=(0.25, 0.2, 0.3)) # load shader shader = pi3d.Shader("uv_bump") shinesh = pi3d.Shader("uv_reflect") flatsh = pi3d.Shader("uv_flat") tree2img = pi3d.Texture("textures/tree2.png") tree1img = pi3d.Texture("textures/tree1.png") hb2img = pi3d.Texture("textures/hornbeam2.png") bumpimg = pi3d.Texture("textures/grasstile_n.jpg") reflimg = pi3d.Texture("textures/stars.jpg") rockimg = pi3d.Texture("textures/rock1.jpg") FOG = ((0.3, 0.3, 0.4, 0.8), 650.0) TFOG = ((0.2, 0.24, 0.22, 1.0), 150.0) #myecube = pi3d.EnvironmentCube(900.0,"HALFCROSS") ectex = pi3d.loadECfiles("textures/ecubes", "sbox") myecube = pi3d.EnvironmentCube(size=900.0, maptype="FACES", name="cube") myecube.set_draw_details(flatsh, ectex) # Create elevation map mapsize = 1000.0 mapheight = 60.0 mountimg1 = pi3d.Texture("textures/mountains3_512.jpg") mymap = pi3d.ElevationMap("textures/mountainsHgt.png", name="map", width=mapsize, depth=mapsize, height=mapheight, divx=32, divy=32) mymap.set_draw_details(shader, [mountimg1, bumpimg, reflimg], 128.0, 0.0) mymap.set_fog(*FOG) #Create tree models treeplane = pi3d.Plane(w=4.0, h=5.0) treemodel1 = pi3d.MergeShape(name="baretree") treemodel1.add(treeplane.buf[0], 0, 0, 0) treemodel1.add(treeplane.buf[0], 0, 0, 0, 0, 90, 0) treemodel2 = pi3d.MergeShape(name="bushytree") treemodel2.add(treeplane.buf[0], 0, 0, 0) treemodel2.add(treeplane.buf[0], 0, 0, 0, 0, 60, 0) treemodel2.add(treeplane.buf[0], 0, 0, 0, 0, 120, 0) #Scatter them on map using Merge shape's cluster function mytrees1 = pi3d.MergeShape(name="trees1") mytrees1.cluster(treemodel1.buf[0], mymap, 0.0, 0.0, 200.0, 200.0, 20, "", 8.0, 3.0) mytrees1.set_draw_details(flatsh, [tree2img], 0.0, 0.0) mytrees1.set_fog(*TFOG) mytrees2 = pi3d.MergeShape(name="trees2") mytrees2.cluster(treemodel2.buf[0], mymap, 0.0, 0.0, 200.0, 200.0, 20, "", 6.0, 3.0) mytrees2.set_draw_details(flatsh, [tree1img], 0.0, 0.0) mytrees2.set_fog(*TFOG) mytrees3 = pi3d.MergeShape(name="trees3") mytrees3.cluster(treemodel2, mymap, 0.0, 0.0, 300.0, 300.0, 20, "", 4.0, 2.0) mytrees3.set_draw_details(flatsh, [hb2img], 0.0, 0.0) mytrees3.set_fog(*TFOG) #Create monument monument = pi3d.Model(file_string="models/pi3d.obj", name="monument") monument.set_shader(shinesh) monument.set_normal_shine(bumpimg, 16.0, reflimg, 0.4) monument.set_fog(*FOG) monument.translate(100.0, -mymap.calcHeight(100.0, 235) + 12.0, 235.0) monument.scale(20.0, 20.0, 20.0) monument.rotateToY(65) #avatar camera rot = 0.0 tilt = 0.0 avhgt = 3.5 xm = 0.0 zm = 0.0 ym = mymap.calcHeight(xm, zm) + avhgt go_flag = False go_speed = 0.2 CAMERA = pi3d.Camera.instance() def pi3dloop(self, dt): self.DISPLAY.loop_running() self.CAMERA.reset() self.CAMERA.rotate(self.tilt, self.rot, 0) self.CAMERA.position((self.xm, self.ym, self.zm)) self.myecube.position(self.xm, self.ym, self.zm) # for opaque objects it is more efficient to draw from near to far as the # shader will not calculate pixels already concealed by something nearer self.myecube.draw() self.mymap.draw() dx = math.copysign(self.mapsize, self.xm) dz = math.copysign(self.mapsize, self.zm) mid = 0.3 * self.mapsize if abs(self.xm) > mid: #nearing edge self.mymap.position(dx, 0.0, 0.0) self.mymap.draw() if abs(self.zm) > mid: #other edge self.mymap.position(0.0, 0.0, dz) self.mymap.draw() if abs(self.xm) > mid: #i.e. in corner, both edges self.mymap.position(dx, 0.0, dz) self.mymap.draw() self.mymap.position(0.0, 0.0, 0.0) self.monument.draw() self.mytrees1.draw() self.mytrees2.draw() self.mytrees3.draw() if pi3d.PLATFORM == PLATFORM_ANDROID: #***************************** if self.DISPLAY.android.screen.moved: self.rot -= self.DISPLAY.android.screen.touch.dx * 0.25 self.tilt += self.DISPLAY.android.screen.touch.dy * 0.25 self.DISPLAY.android.screen.moved = False self.DISPLAY.android.screen.tapped = False elif self.DISPLAY.android.screen.tapped: self.go_speed *= 1.5 self.DISPLAY.android.screen.tapped = False elif self.DISPLAY.android.screen.double_tapped: self.go_flag = not self.go_flag self.DISPLAY.android.screen.double_tapped = False else: mx, my = self.mymouse.position() #if mx>display.left and mx<display.right and my>display.top and my<display.bottom: self.rot -= (mx - self.omx) * 0.2 self.tilt += (my - self.omy) * 0.2 self.omx = mx self.omy = my #Press ESCAPE to terminate k = self.mykeys.read() if k > -1: if k == ord('w'): #key W self.go_flag = not self.go_flag elif k == 27: #Escape key return False if self.go_flag: self.xm -= math.sin(math.radians(self.rot)) * self.go_speed self.zm += math.cos(math.radians(self.rot)) * self.go_speed self.ym = self.mymap.calcHeight(self.xm, self.zm) + self.avhgt halfmap = self.mapsize / 2.0 # save doing this four times! self.xm = (self.xm + halfmap) % self.mapsize - halfmap self.zm = (self.zm + halfmap) % self.mapsize - halfmap else: self.go_speed = 0.2 return True 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()
h=H, frames_per_second=fps, background=BACKGROUND_COLOR, display_config=pi3d.DISPLAY_CONFIG_HIDE_CURSOR | pi3d.DISPLAY_CONFIG_MAXIMIZED, use_glx=True) print(display.opengl.gl_id) # the type of glsl your pi is running 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') # cloud shader sprite.set_shader(shader) ## offscreen texture stuff ## cam = pi3d.Camera(is_3d=False) postsh = pi3d.Shader('post_pixelize') 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
import sys sys.path.insert(1,'/home/pi/pi3d') # to use local 'develop' branch version import pi3d import numpy as np import math import random RANGE = 100.0 HIT_DIST = 5.0 MODEL_PATH = '{}' display = pi3d.Display.create(background=(0.0, 0.0, 0.0, 0.0)) # option 1 move near plane away (default is 1.0) #_di = display.INSTANCE camera = pi3d.Camera()#lens=(15.0, display.far, display.fov, display.width/float(display.height))) shader = pi3d.Shader('uv_light_nearfade') laser_shader = pi3d.Shader('mat_flat') # pod, base and gun pod = pi3d.Model(file_string=MODEL_PATH.format('pod_2.obj'), z=20.0) laser_base = pi3d.Model(file_string=MODEL_PATH.format('laser_base_2.obj'), y=3.15) laser_gun = pi3d.Model(file_string=MODEL_PATH.format('laser_gun_2.obj'), y=0.4, z=-0.4) laser_base.add_child(laser_gun) pod.add_child(laser_base) pod.set_shader(shader) # all use uv_light shader # laser beam itself not a child laser_tip = pi3d.Cuboid(w=0.05, h=0.05, d=5.0) laser_tip.set_material((1.0, 0.0, 0.0)) laser_tip.set_alpha(0.8) laser_tip.set_shader(laser_shader)
import demo import pi3d print("=====================================================") print("press escape to escape") print("move this terminal window to top of screen to see FPS") print("=====================================================") # Setup display and initialise pi3d DISPLAY = pi3d.Display.create(x=200, y=150, frames_per_second=25.0) DISPLAY.set_background(0.4, 0.6, 0.8, 0.5) # r,g,b,alpha #setup textures, light position and initial model position pi3d.Light((5, -5, 8)) #create shaders shader = pi3d.Shader("uv_reflect") matsh = pi3d.Shader("mat_reflect") flatsh = pi3d.Shader("uv_flat") #Create textures shapeimg = pi3d.Texture("textures/straw1.jpg") shapebump = pi3d.Texture("textures/mudnormal.jpg") waterbump = [] iFiles = glob.glob("textures/water/n_norm???.png") iFiles.sort() # order is vital to animation! for f in iFiles: waterbump.append(pi3d.Texture(f)) num_n = len(waterbump) shapeshine = pi3d.Texture("textures/stars.jpg") #Create shape
elif AVATAR_3 == 'toad': avatar3 = avatars.toad() avatar3_3 = avatars.goombaD() if MAP == 'forest': map1 = maps.forest() elif MAP == 'moon': map1 = maps.moon() elif MAP == 'temple': map1 = maps.templeoftime() elif MAP == 'kokiri': map1 = maps.kokiri() bulle = objects.object() TEXTURE = pi3d.Texture('../textures/Raspi256x256.png') SHADER = pi3d.Shader('uv_flat') #size = random.uniform(0.5, 2.5) life = [ pi3d.ImageSprite(texture=TEXTURE, shader=SHADER, w=1, h=1), pi3d.ImageSprite(texture=TEXTURE, shader=SHADER, w=1, h=1), pi3d.ImageSprite(texture=TEXTURE, shader=SHADER, w=1, h=1), pi3d.ImageSprite(texture=TEXTURE, shader=SHADER, w=1, h=1), pi3d.ImageSprite(texture=TEXTURE, shader=SHADER, w=1, h=1) ] life_pos = [-1.2, -0.6, 0, 0.6, 1.2] #life.position(5, 5, 0) #DISPLAY.add_sprites(life) # variables synchro_serial = 0