def start_md(): '''Manage Motion Detector.''' conf = json.load(open("config.json")) print("[INFO]Starting Camera...") vs = Camera(src=0).start() print("[INFO]Warming Up...") time.sleep(conf["camera_warmup"]) print("[INFO]Initializing motion detectors...") camMotion = MotionDetector(conf["min_area"], conf["delta_thresh"]) while True: frame = vs.read() frame = np.array(frame) frame = imutils.resize(frame, width=500) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) locs = camMotion.update(gray) if len(locs) > 0: (minX, minY) = (np.inf, np.inf) (maxX, maxY) = (-np.inf, -np.inf) for l in locs: (x, y, w, h) = cv2.boundingRect(l) (minX, maxX) = (min(minX, x), max(maxX, x + w)) (minY, maxY) = (min(minY, y), max(maxY, y + h)) cv2.rectangle(frame, (minX, minY), (maxX, maxY), (0, 0, 255), 3) timestamp = datetime.now() ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p") cv2.putText(frame, "Perimeter Satus: {}".format(camMotion.status), (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) cv2.putText(frame, ts, (10, np.shape(frame)[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1) if camMotion.status == "Breached": t = Thread(target=alert, args=( conf, frame, )) t.start() if conf["is_streaming"] == True: cv2.imshow("Security Feed", frame) key = cv2.waitKey(1) & 0xFF if key == ord("q"): print("[INFO]Exitting...") break cv2.destroyAllWindows() vs.stop()
def request_img(): camera = Camera() controller = Controller() D1 = DD(27) D2 = DD(4) print("request_img") while (1): if (camera.test() > 0.2 and D2 == False and D1 == True): controller.Forward()
def __init__(self, width=1280, height=700): self.win_w = width self.win_h = height self.asteroids = deque() self.light = Light([0, -3, 3]) self.skybox = Skybox(self.win_w, self.win_h) self.center = Sphere(0.1, [1.0, 0.0, 1.0], [1, 1, 1]) self.paused = False self.score = 0 self.camera = Camera() self.isRoaming = False
def __init__(self, lines): self.camera = None self.settings = None self.materials = [] self.planes = [] self.spheres = [] self.boxes = [] self.lights = [] for line in lines: if line[0] != '#' and not line.isspace(): split_line = line.split() if split_line[0] == 'cam': self.camera = Camera(split_line[1:]) elif split_line[0] == 'set': self.settings = Settings(split_line[1:]) elif split_line[0] == 'mtl': material = Material(split_line[1:], len(self.materials) + 1) self.materials.append(material) elif split_line[0] == 'pln': self.planes.append(Plane(split_line[1:], self.materials)) elif split_line[0] == 'sph': self.spheres.append(Sphere(split_line[1:], self.materials)) elif split_line[0] == 'box': self.boxes.append(Box(split_line[1:], self.materials)) elif split_line[0] == 'lgt': self.lights.append(Light(split_line[1:])) self.objects = self.spheres + self.planes + self.boxes
def main(): if not args.game: argparser.print_help() print print "Available games:" list_games() exit(0) inipath = profiledir + args.game + ".ini" if not isfile(inipath): print "File %s not found." % inipath exit(2) gameconfig = ConfigParser.ConfigParser() gameconfig.read(inipath) print "Starting with game profile '%s'... Press Ctrl+C to stop" % args.game camera = Camera(gameconfig) xml_event_stream = get_xml_event_stream() for event in parser.make_gaze_event_stream(xml_event_stream): camera.tick(event)
parser.add_argument("-r", "--resolution", type=int, default=720, help='Resolution (width) of the webcam') parser.add_argument("-d", "--show_fps", dest='show_fps', action='store_true', help='Whether to show FPS or not') parser.add_argument("-a", "--assets_path", type=str, default=assets_path, help='Path of the assets') args = parser.parse_args() camera = Camera(assets_path=args.assets_path, cam_number=args.cam_number, resolution=args.resolution, show_fps=args.show_fps, n_frames=args.n_frames, seconds_to_be_recorded=args.predictions_delta) asl_recognizer = ASLRecognizer(camera=camera, assets_path=assets_path, predictions_delta=args.predictions_delta) camera.start() asl_recognizer.start() print(f"Press ESC to quit")
class Game(object): """Main game class""" def __init__(self, width=1280, height=700): self.win_w = width self.win_h = height self.asteroids = deque() self.light = Light([0, -3, 3]) self.skybox = Skybox(self.win_w, self.win_h) self.center = Sphere(0.1, [1.0, 0.0, 1.0], [1, 1, 1]) self.paused = False self.score = 0 self.camera = Camera() self.isRoaming = False def init_properties(self): """Initialization of game properties""" self.isplaying = False self.fps_view = False self.shield = HARD_INIT_SHIELD self.ast_speed = HARD_AST_INIT self.ship_speed = HARD_SHIP_INIT self.lean_speed = HARD_TILT_INIT def init_screen(self): self.init_properties() """Creating screen and initializing objects""" pygame.init() size = [self.win_w, self.win_h] pygame.display.set_mode(size, pygame.OPENGL | pygame.DOUBLEBUF) pygame.display.set_caption("Skywalker") pygame.mouse.set_visible(False) gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_CULL_FACE) self.light.enable() """ Load model """ os.chdir('./materials/spaceship/') self.ship = Model("spaceship.obj", 0.4, [0, 0, 0], -270, 0, -180) os.chdir('../../') # os.chdir('./materials/Starship/') # self.ship = Model("Starship.obj", 0.01, [0, 0, 0], 90, 0, 180) # os.chdir('../../') # os.chdir('./materials/NCC-1701/') # self.ship = Model("NCC-1701_modified.obj", 1.2, [0, 0, 0], 90, 0, 180) # os.chdir('../../') # os.chdir('./materials/millenium-falcon/') # self.ship = Model("millenium-falcon_modified.obj", 1, [0, 0, 0], 90, 0, 0, using_left=True) # os.chdir('../../') for i in range(MAX_DISPLAY_AST): self.add_ast(isInit=True) self.ship_collider = Sphere(self.ship.radius, [0.0, 0.0, 0.0], [1, 1, 1], False) self.skybox.init_sky() def main_loop(self): """Main game loop""" self.init_screen() pygame.time.set_timer(pygame.USEREVENT + 1, HARD_ACC_TIME_SEP) # accelerate pygame.time.set_timer(pygame.USEREVENT + 2, 1000) # score++ # pygame.time.set_timer(pygame.USEREVENT + 3, 1000) # refresh asts has_played = False clock = pygame.time.Clock() while True: delta_time = clock.tick(60) / 10 fps = int(clock.get_fps()) event_list = pygame.event.get() for e in event_list: if e.type == pygame.QUIT: pygame.quit() quit() elif e.type == pygame.KEYDOWN: """ Keyboard(Not Controller) """ if e.key == pygame.K_ESCAPE or e.key == pygame.K_q: method.quit_program() elif e.key == pygame.K_r: self.isRoaming = not self.isRoaming elif e.key == pygame.K_v: self.fps_view = not self.fps_view elif e.key == pygame.K_p: self.paused = not self.paused elif e.key == pygame.K_SPACE and not self.isplaying: self.score = 0 self.isplaying = True has_played = True # elif e.type == pygame.MOUSEMOTION: elif e.type == pygame.USEREVENT + 1 and self.isplaying and not self.paused: self.ast_speed += HARD_AST_ACC self.ship_speed += HARD_SHIP_ACC self.lean_speed += HARD_TILT_ACC elif e.type == pygame.USEREVENT + 2 and self.isplaying and not self.paused: self.score += 1 # elif e.type == pygame.USEREVENT + 3 and self.isplaying and fps > 24 and not self.paused: # self.add_ast() """ Control & Display update """ if not self.paused: if self.isplaying: for ast in self.asteroids: if method.collision_detection(self.ship_collider, ast): self.shield -= 1 if self.shield <= 0: # GAME OVER self.init_properties() self.ship.pos = [0, 0, 0] if ast.pos[1] < -20: # Reset Ast Pos ast.pos[0] = random.uniform( self.ship.pos[0] - AST_RANGE, self.ship.pos[0] + AST_RANGE) ast.pos[1] = random.randint(AST_Y_MIN, AST_Y_MAX) ast.pos[2] = random.uniform( self.ship.pos[2] - AST_RANGE, self.ship.pos[2] + AST_RANGE) else: ast.pos[1] -= HARD_AST_INIT * delta_time if ENABLE_AST_MOVING: ast.pos[0] += ast.jiggle_speed[0] ast.pos[1] += ast.jiggle_speed[1] ast.pos[2] += ast.jiggle_speed[2] ast.rotate() method.ship_update(self.ship, self.ship_speed, self.lean_speed, delta_time) self.ship_collider.pos = self.ship.pos[:] self.display(delta_time) method.draw_text([40, self.win_h - 50], str(self.score), 30) method.draw_text([self.win_w - 130, self.win_h - 50], "FPS: " + str(fps), 30) method.draw_text( [int(self.win_w / 2 - 200), self.win_h - 60], "Shield: " + ">" * self.shield, 30, False, (92, 207, 230)) else: # Start or Game Over self.start_screen(delta_time, self.ast_speed) method.draw_text([40, 40], "Esc to exit", 25, False, (255, 0, 0)) if has_played: # Game Over method.draw_text( [int(self.win_w / 2), int(self.win_h / 3 * 2)], "Game Over", 60, True, (255, 174, 87)) method.draw_text( [int(self.win_w / 2), int(self.win_h / 3)], "You scored: " + str(self.score), 40, True) method.draw_text( [int(self.win_w / 2), int(self.win_h / 2)], "Press space to start", 50, True) clock.tick(CLK_TICK) pygame.display.flip() else: if self.isRoaming: # Paused and Roaming self.camera.roam(event_list) self.display(delta_time) method.draw_text( [int(self.win_w / 2), int(self.win_h / 5 * 4)], "Roaming...", 40, True, (255, 174, 87)) clock.tick(CLK_TICK) pygame.display.flip() else: # Just paused method.draw_text( [int(self.win_w / 2), int(self.win_h / 3 * 2)], "Paused", 60, True, (255, 174, 87)) def display(self, delta_time): """Refreshing screen, clearing buffers, and redrawing objects""" # Ciscenje medjuspremnika i ponovno crtanje objekata gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluPerspective(VIEW_ANGLE, self.win_w / self.win_h, 0.1, 10000) if self.isRoaming: ctx = self.camera.eyex + sin(self.camera.polarAngle * D2R) * cos( self.camera.azimuthAngle * D2R) cty = self.camera.eyey + sin(self.camera.polarAngle * D2R) * sin( self.camera.azimuthAngle * D2R) ctz = self.camera.eyez + cos(self.camera.polarAngle * D2R) upx = -cos(self.camera.polarAngle * D2R) * cos( self.camera.azimuthAngle * D2R) upy = -cos(self.camera.polarAngle * D2R) * sin( self.camera.azimuthAngle * D2R) upz = sin(self.camera.polarAngle * D2R) glu.gluLookAt(self.camera.eyex, self.camera.eyey, self.camera.eyez, ctx, cty, ctz, upx, upy, upz) else: self.camera.update(self.ship) if self.fps_view: glu.gluLookAt(self.ship.pos[0], self.ship.pos[1], self.ship.pos[2], self.ship.pos[0], self.ship.pos[1] + 100, self.ship.pos[2], 0, 0, 1) else: glu.gluLookAt(self.camera.eyex, self.camera.eyey, self.camera.eyez + 3, self.ship.pos[0], self.ship.pos[1] + 100, self.ship.pos[2], 0, 0, 1) self.skybox.sky_pos = self.ship.pos gl.glMatrixMode(gl.GL_MODELVIEW) gl.glLoadIdentity() """ Skybox """ self.light.disable() self.skybox.render(self.camera) self.light.enable() """ Ship """ self.light.enable() self.center.pos = (self.ship.pos[0], self.ship.pos[1], self.ship.pos[2]) if not self.fps_view: self.light.disable() self.ship.render() self.light.enable() else: self.center.render() self.ship_collider.render() self.light.render() """ Ast """ for ast in self.asteroids: ast.render() self.light.render() def start_screen(self, delta_time, speed): """Updating a welcome screen (like a screensaver)""" gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() glu.gluPerspective(80, self.win_w / self.win_h, 0.1, 10000) glu.gluLookAt(0, 0, 0, 0, 100, 0, 0, 0, 1) self.skybox.sky_pos = self.ship.pos self.light.disable() self.skybox.render(self.camera) self.light.enable() for ast in self.asteroids: if ast.pos[2] < -CAMERA_DIST - 10: ast.pos[0] = random.randint( (int)(self.ship.pos[0]) - AST_RANGE, (int)(self.ship.pos[0]) + AST_RANGE) ast.pos[1] = random.randint( (int)(self.ship.pos[1]) + AST_Y_MIN_INIT, (int)(self.ship.pos[1]) + AST_Y_MAX_INIT) ast.pos[2] = random.randint( (int)(self.ship.pos[2]) - AST_RANGE, (int)(self.ship.pos[2]) + AST_RANGE) else: ast.pos[1] -= speed * delta_time * 0.1 ast.render() self.light.render() def add_ast(self, isInit=False): """Adding asteroids to a random pos near the ship""" size = random.randint(AST_MIN_SIZE, AST_MAX_SIZE) pos_x = random.randint(self.ship.pos[0] - AST_RANGE, self.ship.pos[0] + AST_RANGE) pos_y = random.randint(self.ship.pos[1]+AST_Y_MIN_INIT, self.ship.pos[1]+AST_Y_MAX_INIT) if isInit \ else random.randint(self.ship.pos[1]+AST_Y_MIN, self.ship.pos[1]+AST_Y_MAX) pos_z = random.randint(self.ship.pos[2] - AST_RANGE, self.ship.pos[2] + AST_RANGE) self.asteroids.append( Model("materials/ast_lowpoly2/ast_lowpoly2.obj", size, [pos_x, pos_y, pos_z], random.randint(0, 360), random.randint(0, 360), random.randint(0, 360), False, [ random.randint(-AST_MOVE_RANGE, AST_MOVE_RANGE), random.randint(-AST_MOVE_RANGE, AST_MOVE_RANGE), random.randint(-AST_MOVE_RANGE, AST_MOVE_RANGE) ], random.randint(-AST_ROT_RANGE, AST_ROT_RANGE))) if len(self.asteroids) > MAX_DISPLAY_AST: self.asteroids.popleft()
def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame')
def main(): pygame.init() pygame.key.set_repeat(1, 25) pygame.display.set_caption('ColdLine Manhattan') start_screen(screen, HEIGHT) start_time = pygame.time.get_ticks() running = True t = pygame.time.get_ticks() player = generate_level(level_map, player_image, enemy_image) for enemy in enemies_group: enemy.player = player camera = Camera() pygame.mixer.music.load(music['song2']) pygame.mixer.music.queue(music['song1']) pygame.mixer.music.set_volume(VOLUME + 0.05) pygame.mixer.music.play(-1) while running: # Делает курсор прицелом try: pygame.mouse.set_cursor(pygame.cursors.broken_x) except: # pygame.mouse.set_cursor(pygame.cursors.arrow) pass # wasd_arrows_keys = [pygame.K_w, pygame.K_a, pygame.K_s, pygame.K_d, # pygame.K_LEFT, pygame.K_RIGHT, pygame.K_DOWN, pygame.K_UP] # keys = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False terminate() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False terminate() if event.type == pygame.KEYUP: player.state = player.IDLE player.move() for enemy in enemies_group: enemy.move() if enemy.state == enemy.WALKING: now = pygame.time.get_ticks() if now - enemy.time > 250: enemy.time = now sound = random.choice(sounds['footsteps']) sound.set_volume(VOLUME) sound.play() if player.state == player.WALKING: now = pygame.time.get_ticks() if now - t > 250: t = now sound = random.choice(sounds['footsteps']) sound.set_volume(VOLUME) sound.play() screen.fill(pygame.Color(82, 0, 89)) # Сдвиг камеры camera.update(player) for sprite in all_sprites: if isinstance(sprite, Player): player.hitbox.x += camera.dx player.hitbox.y += camera.dy elif isinstance(sprite, Enemy): sprite.hitbox.x += camera.dx sprite.hitbox.y += camera.dy else: camera.apply(sprite) camera.apply_rect(level_map_rect) screen.blit(level_map_img, level_map_rect) hits = pygame.sprite.groupcollide(enemies_group, player_bullets_group, False, True) for hit in hits: hit.kill() hits = pygame.sprite.groupcollide(player_group, enemies_bullets_group, False, True) if hits: running = False game_over_screen(screen, WIDTH, HEIGHT) break if len(enemies_group) == 0: running = False finish_time = pygame.time.get_ticks() all_time = finish_time - start_time win_screen(screen, WIDTH, HEIGHT, all_time) # Отрисовка спрайтов player_group.draw(screen) enemies_group.draw(screen) player_bullets_group.draw(screen) enemies_bullets_group.draw(screen) # Обновление спрайтов player.update(pygame.mouse.get_pos()) enemies_group.update(player.rect.center) player_bullets_group.update() enemies_bullets_group.update() obstacles_group.update() # Фпс в углу экрана font = pygame.font.Font(None, 30) fps = font.render(f'FPS: {int(clock.get_fps())}', 1, pygame.Color('red')) fps_rect = fps.get_rect() screen.blit(fps, fps_rect) # Время font = pygame.font.Font(None, 75) now = pygame.time.get_ticks() time = font.render(f'Time: {round((now - start_time) / 1000, 1)}s', 1, pygame.Color('white')) time_rect = time.get_rect() time_rect = time_rect.move(WIDTH - time_rect.width - 20, 10) time_shadow = font.render( f'Time: {round((now - start_time) / 1000, 1)}s', 1, pygame.Color('black')) time_shadow_rect = time_shadow.get_rect() time_shadow_rect = time_shadow_rect.move(time_rect.x + 2, time_rect.y + 2) screen.blit(time_shadow, time_shadow_rect) screen.blit(time, time_rect) pygame.display.flip() clock.tick(FPS)
from modules.servo import ServoMotor from modules.mic import Mic from modules.camera import Camera from modules.vector import vector_to_value, convert_to_servo_value import random, time import numpy as np if __name__ == "__main__": # Camera path = "./modules/data/shape_predictor_68_face_landmarks.dat" cam0 = Camera(0, path) cam1 = Camera(2, path) cams = [cam0, cam1] # Mic mic0 = Mic(0) mic1 = Mic(2) mics = [mic0, mic1] sound_level = 0 level_count = 0 level_count_limit = 10 # Servo servoMotors = [] servoMotors.append(ServoMotor(Channel=3, ZeroOffset=0)) servoMotors.append(ServoMotor(Channel=0, ZeroOffset=0)) servoMotors.append(ServoMotor(Channel=1, ZeroOffset=0)) servoMotors.append(ServoMotor(Channel=2, ZeroOffset=0)) # intialize servo angle for i, servoMotor in enumerate(servoMotors):
# Configuration Parameters for Camera rpiCam = True cameraNum = 0 width = 800 height = 480 fps = 30 # Configuration Parameters for Video # Video File Path: VidPath = "./app/data/videos/example_01.mp4" # Initialization Stage of the program: if cam_feed: # Initialize the setup for Camera. # Import only in case of Camera to avoid conflicts on other machines. from modules.camera import Camera feed = Camera(rpiCam, cameraNum, width, height, fps) # Camera parameters are hard coded at this stage. else: # Initialize setup for video feed = cv2.VideoCapture(VidPath) # Sanity check and Initialization of "snapshots" folder in the data folder if not os.path.isdir("./app/data/snapshots"): os.mkdir("./app/data/snapshots") # First Program Cycle Declarations/Initializations: #Frame Number imgno = 1 #Initializing the motion detector module md = MotionDetector() #Configuring the motion detector
if len(sys.argv) != 2 or not (sys.argv[1] != 'text' or sys.argv[1] != 'speech'): print('Usage: python3 {} speech/text'.format(sys.argv[0])) exit(-1) import RPi.GPIO as gpio from flask import Flask from flask import jsonify from modules.camera import Camera from modules.controller import Controller from rfid_thread import rfid_thread mode = sys.argv[1] SUBSCRIPTION_KEY = 'PUT SUBSCRIPTION KEY HERE' if mode == 'text': camera = Camera(SUBSCRIPTION_KEY) app = Flask(__name__) controller = Controller(23, 18) # motor_pin, servo_pin @app.route('/') def root(): return 'woooow' @app.route('/forward') def forward(): controller.forward() return jsonify(success=True)
def stream_v2(): stream_mime = 'multipart/x-mixed-replace; boundary=frame' camera = Camera() camera.start() return Response(gen(camera), mimetype=stream_mime)
from modules.vector import Point from modules.color import Color from modules.blackhole import BlackHole from modules.disk import Disk from modules.camera import Camera from modules.scene import Scene from modules.engine import Engine c_origin = Point(0, 0.7, -9.0) c_focus = Point(0, 0, 0.0) bh = BlackHole(c_focus, 80) # You can specify a texture file for the accretion disk with `texture='filename.png'` or a color by `color=Color('#ffffff') (default)` disk = Disk(c_focus, 4.5*bh.radius, 16.2*bh.radius) scene = Scene( width = 500, height = 250, camera = Camera(c_origin, c_focus-c_origin, 1.2), blackhole = bh, disk = disk ) engine = Engine(scene) engine.render() engine.save('images/blackhole.png')
GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) CFG = read_conf("global") stepper = Stepper(CFG['PORTE_STEPPER_1'], CFG['PORTE_STEPPER_2'], CFG['PORTE_STEPPER_3'], CFG['PORTE_STEPPER_4']) porte = Porte(stepper, CFG['PORTE_PIN_BAS'], CFG['PORTE_PIN_HAUT']) abreuvoir = Abreuvoir(CFG['ABREUVOIR_PIN_VIDE'], CFG['ABREUVOIR_PIN_MEDIUM'], CFG['ABREUVOIR_PIN_PLEIN']) batterie = Batterie() luminosite = Luminosite() temp_ext = Temperature(CFG['TEMP_ID_EXT']) temp_int = Temperature(CFG['TEMP_ID_INT']) camera = Camera(CFG['CAMERA_WIDTH'], CFG['CAMERA_HEIGHT']) camera_usb = Camera_usb(CFG['CAMERA_WIDTH'], CFG['CAMERA_HEIGHT']) # page par defaut, redirection vers la page principale @app.route('/') def index(): return redirect(url_for('board')) # page principale @app.route('/board') def board(): return render_template('board.html')
# Get a list of all folders in the /pi/home/Music folder and set player to the first playList = musicFolder.getPlayList(0) if shuffle: playList.shuffle() indexMediaFolder = 0 player.switchMedia(playList) player.togglePlayPause() # Set up camera object camera = Camera(player, logger) # Subcribe to state received event so that when the Arduino updates us with state we update controls camera.events.onQRDataReceived += qrDataReceived camera.start() player.playFile(MediaFile(os.path.join(os.getcwd(), 'assets', 'audio', 'player-ready.ogg'))) quit = False while quit == False: # Work out position and duration and loop to start if at end pos = player.position() dur = player.duration()
def main(): if len(sys.argv) != 2: print "Wring number of args!" return CURRENT_POINT_SIZE = 4.0 CURRENT_STEP = 0.001 pygame.init() display_info = pygame.display.Info() screen = pygame.display.set_mode( (display_info.current_w, display_info.current_h), HWSURFACE | OPENGL | DOUBLEBUF | FULLSCREEN ) clock = pygame.time.Clock() resize(display_info.current_w, display_info.current_h) projection_matrix = Matrix44.perspective_projection_fov( 60.0 / 180.0 * 3.14159265358, float(display_info.current_w) / display_info.current_h, 0.1, 1000.0 ) gl_init() movement_speed = 5.0 look_around_speed = 0.005 pygame.mouse.set_visible(False) pygame.event.set_grab(True) sequence_iterations = int(sys.argv[1]) vbo3 = VertexBuffer() vbo3.bind(GL_ARRAY_BUFFER) with open("../generator/gen/v" + str(sequence_iterations) + ".gen") as f: v3 = f.read() with open("../generator/gen/c" + str(sequence_iterations) + ".gen") as f: c4 = f.read() with open("../generator/gen/n" + str(sequence_iterations) + ".gen") as f: n4 = f.read() with open("../generator/gen/f" + str(sequence_iterations) + ".gen") as f: f4 = f.read() vbo3.setBinaryData(v3 + c4 + n4, GL_STATIC_DRAW) vbo3.unBind() faces_vbo = VertexBuffer() faces_vbo.bind(GL_ARRAY_BUFFER) with open("../generator/gen/f" + str(sequence_iterations) + ".gen") as f: f4 = f.read() faces_vbo.setBinaryData(f4, GL_STATIC_DRAW) faces_vbo.unBind() light_angle_phi = 0.0 light_angle_theta = 0.0 print "Rendering ", len(c4) / 12, " points" print "GLSL Version: ", glGetString(GL_SHADING_LANGUAGE_VERSION) simple = Shader() simple.loadFromFile("shaders/simplest.txt") camera = Camera() clock.tick() pygame.mouse.get_rel() first_mouse_event_skipped = False while True: pressed = pygame.key.get_pressed() finished = False for event in pygame.event.get(): if event.type == QUIT: finished = True break if event.type == KEYUP and event.key == K_ESCAPE: finished = True break if event.type == KEYUP and event.key == K_RIGHTBRACKET: if CURRENT_POINT_SIZE < 10.0: CURRENT_POINT_SIZE += 1.0 if event.type == KEYUP and event.key == K_LEFTBRACKET: if CURRENT_POINT_SIZE > 1.0: CURRENT_POINT_SIZE -= 1.0 if event.type == KEYUP and event.key == K_p: normal = list(camera._dir) print normal if event.type == KEYUP: if event.key == K_9: CURRENT_STEP /= 10.0 if event.key == K_0: CURRENT_STEP *= 10.0 if event.key == K_y: normal[0] -= CURRENT_STEP if event.key == K_u: normal[0] += CURRENT_STEP if event.key == K_h: normal[1] -= CURRENT_STEP if event.key == K_j: normal[1] += CURRENT_STEP if event.key == K_n: normal[2] -= CURRENT_STEP if event.key == K_m: normal[2] += CURRENT_STEP if finished: break time_passed = clock.tick() time_passed_seconds = time_passed / 1000.0 light_angle_phi += time_passed_seconds * 0.3 light_angle_theta += time_passed_seconds * 0.1 while light_angle_phi > 2 * pi: light_angle_phi -= 2 * pi while light_angle_theta > 2 * pi: light_angle_theta -= 2 * pi ## handling camera movement_direction = 0.0 strafe_direction = 0.0 if pressed[K_w]: movement_direction = 1.0 if pressed[K_s]: movement_direction = -1.0 if pressed[K_d]: strafe_direction = 1.0 if pressed[K_a]: strafe_direction = -1.0 camera.move(time_passed_seconds * movement_speed * movement_direction) camera.strafeRight(time_passed_seconds * movement_speed * strafe_direction) dx, dy = pygame.mouse.get_rel() if not first_mouse_event_skipped: if dx != 0 or dy != 0: dx = 0 dy = 0 first_mouse_event_skipped = True camera.rotateHoriz(-dx * look_around_speed) camera.rotateVert(-dy * look_around_speed) ## now render glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glPointSize(CURRENT_POINT_SIZE) glMatrixMode(GL_PROJECTION) glLoadIdentity() glLoadMatrixd(projection_matrix.to_opengl()) glMatrixMode(GL_MODELVIEW) glLoadIdentity() # glTranslatef(0.0, 0.0, -5.0) glLoadMatrixd(camera.getLookAtMatrix().to_opengl()) draw_coordinate_system() MVP = projection_matrix * camera.getLookAtMatrix() ### 4D simple shader render simple.bind() simple.enableAttrArray("pos", True) simple.enableAttrArray("col", True) simple.enableAttrArray("nrm", True) simple.setUniformMat4("MVP", MVP) light_dir = Vector3( cos(light_angle_phi) * cos(light_angle_theta), sin(light_angle_theta), sin(light_angle_phi) * sin(light_angle_theta), ) simple.setUniformVec3("light_dir", light_dir) # print Vector3(cos(light_angle), 0.0, sin(light_angle)) vbo3.bind(GL_ARRAY_BUFFER) glVertexAttribPointer(simple.getAttribLocation("pos"), 3, GL_FLOAT, GL_FALSE, 0, c_void_p(0)) glVertexAttribPointer(simple.getAttribLocation("col"), 3, GL_FLOAT, GL_FALSE, 0, c_void_p(len(v3))) glVertexAttribPointer(simple.getAttribLocation("nrm"), 3, GL_FLOAT, GL_FALSE, 0, c_void_p(len(v3) + len(c4))) glDrawArrays(GL_POINTS, 0, len(v3) / 12) vbo3.unBind() faces_vbo.bind(GL_ARRAY_BUFFER) stride = 9 * 4 # nine floats glVertexAttribPointer(simple.getAttribLocation("pos"), 3, GL_FLOAT, GL_FALSE, stride, c_void_p(0)) glVertexAttribPointer(simple.getAttribLocation("col"), 3, GL_FLOAT, GL_FALSE, stride, c_void_p(3 * 4)) glVertexAttribPointer(simple.getAttribLocation("nrm"), 3, GL_FLOAT, GL_FALSE, stride, c_void_p(6 * 4)) glDrawArrays(GL_TRIANGLES, 0, len(f4) / 9 / 4) faces_vbo.unBind() simple.unBind() # glPointSize(25.0) glLineWidth(15.0) glBegin(GL_LINES) glColor3f(1.0, 1.0, 1.0) light_R1 = 4.0 light_R2 = 3.0 glVertex3f(light_R1 * light_dir.x, light_R1 * light_dir.y, light_R1 * light_dir.z) glVertex3f(light_R2 * light_dir.x, light_R2 * light_dir.y, light_R2 * light_dir.z) glEnd() ### final flip pygame.display.flip() pygame.event.set_grab(False) pygame.mouse.set_visible(True)
def main(): points = calculate_lorenz() CURRENT_POINT_SIZE = 2.0 CURRENT_STEP = 0.001 pygame.init() display_info = pygame.display.Info() screen = pygame.display.set_mode((display_info.current_w, display_info.current_h), HWSURFACE|OPENGL|DOUBLEBUF|FULLSCREEN) clock = pygame.time.Clock() resize(display_info.current_w, display_info.current_h) projection_matrix = Matrix44.perspective_projection_fov(60.0/180.0*3.14159265358, float(display_info.current_w)/display_info.current_h, .1, 1000.) gl_init() movement_speed = 5.0 look_around_speed = 0.005 pygame.mouse.set_visible(False) pygame.event.set_grab(True) print "GLSL Version: ", glGetString(GL_SHADING_LANGUAGE_VERSION) camera = Camera() clock.tick() pygame.mouse.get_rel() first_mouse_event_skipped = False while True: pressed = pygame.key.get_pressed() finished = False for event in pygame.event.get(): if event.type == QUIT: finished = True break if event.type == KEYUP and event.key == K_ESCAPE: finished = True break if event.type == KEYUP and event.key == K_RIGHTBRACKET: if CURRENT_POINT_SIZE < 10.0: CURRENT_POINT_SIZE += 1.0 if event.type == KEYUP and event.key == K_LEFTBRACKET: if CURRENT_POINT_SIZE > 1.0: CURRENT_POINT_SIZE -= 1.0 if event.type == KEYUP and event.key == K_p: normal = list(camera._dir) print normal if event.type == KEYUP: if event.key == K_9: CURRENT_STEP /= 10.0 if event.key == K_0: CURRENT_STEP *= 10.0 if event.key == K_y: normal[0] -= CURRENT_STEP if event.key == K_u: normal[0] += CURRENT_STEP if event.key == K_h: normal[1] -= CURRENT_STEP if event.key == K_j: normal[1] += CURRENT_STEP if event.key == K_n: normal[2] -= CURRENT_STEP if event.key == K_m: normal[2] += CURRENT_STEP if finished: break movement_direction = 0.0 strafe_direction = 0.0 if pressed[K_w]: movement_direction = 1.0 if pressed[K_s]: movement_direction = -1.0 if pressed[K_d]: strafe_direction = 1.0 if pressed[K_a]: strafe_direction = -1.0 time_passed = clock.tick() time_passed_seconds = time_passed / 1000.0 camera.move (time_passed_seconds * movement_speed * movement_direction) camera.strafeRight(time_passed_seconds * movement_speed * strafe_direction) dx, dy = pygame.mouse.get_rel() if not first_mouse_event_skipped: if dx != 0 or dy != 0: dx = 0 dy = 0 first_mouse_event_skipped = True camera.rotateHoriz(-dx * look_around_speed) camera.rotateVert (-dy * look_around_speed) ## now render glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glPointSize(CURRENT_POINT_SIZE) glMatrixMode(GL_PROJECTION) glLoadMatrixd(projection_matrix.to_opengl()) glMatrixMode(GL_MODELVIEW) glLoadMatrixd(camera.getLookAtMatrix().to_opengl()) draw_coordinate_system() glLineWidth(1.0) glBegin(GL_LINE_STRIP) #glBegin(GL_POINTS) for i, point in enumerate(points): offset = 1.0 * i / len(points) glColor3f(1.0 - offset, 0.0, offset) glVertex3f(*point) glEnd() pygame.display.flip() pygame.event.set_grab(False) pygame.mouse.set_visible(True)
import os, sys, time from datetime import datetime import threading from modules.camera import Camera from modules.body import Body from modules.config import Config from modules.sensors import Sensors body = Body() camera = Camera() config = Config() sensors = Sensors() sensors.daemon = True sensors.start() try: while True: time.sleep(0.1) Config.read_config(config) # Keep reading config for changes Body.move(body, Config.retrieve(config, 'Body', 'direction'), Sensors.retrieve(sensors), config) Camera.move(camera, Config.retrieve(config, 'Head', 'x'), Config.retrieve(config, 'Head', 'y')) except KeyboardInterrupt: Sensors.__exit__(sensors) Body.__exit__(body) Camera.__exit__(camera)
from modules.camera import Camera from screens.mainscreen import MainScreen from ui.ui import UserInterface def read_config(filepath): # read configuration file config = {} with codecs.open('config.yml', 'r', encoding='utf8') as f: yml_dict = yaml.safe_load(f) for k in yml_dict: config[k] = yml_dict[k] return config if __name__ == "__main__": config = read_config('config.yml') cam = Camera(rpiCam=config['rpi_camera'], cameraNum=config['camera_number'], width=config['camera_width'], height=config['camera_height'], fps=config['camera_fps']) screen = MainScreen(config, cam) ui = UserInterface(screen, (800, 480), True, 60, True) while True: image = cam.grabFrame() if (image != None): screen.setImage(image) ui.tick() cam.cleanup()