Exemplo n.º 1
0
 def __init__(self, world, initial_option=0):
     Scene.__init__(self, world)
     items=[]
     for name,level in levels.levels:
         items.append( (name, runner(self.game, level) ) )
     items.append( ("back", self.on_back) )
     self.menu = Menu(self, items, initial_option)
Exemplo n.º 2
0
 def __init__(self, line_num, *args, **kwargs):
     self.line_num = line_num
     self.anim_kwargs = {
         "run_time" : 4.0,
     }
     self.line_num_to_method = {
         0  : self.line0,
         1  : self.line1,
         2  : self.line2,
         3  : self.line3,
         4  : self.line4,
         5  : self.line5,
         6  : self.line6,
         7  : self.line7,
         8  : self.line8,
         9  : self.line9,
         10 : self.line10,
         11 : self.line11,
         12 : self.line12,
         13 : self.line13,
         14 : self.line14,
         15 : self.line15,
         16 : self.line16,
         17 : self.line17,
         18 : self.line18,
         19 : self.line19,
     }
     Scene.__init__(self, *args, **kwargs)
Exemplo n.º 3
0
def main():
	import scene
	from scene import Scene
	game = Scene()
	grassBackground = Grass()
	game.sprites = [grassBackground]
	game.start()
Exemplo n.º 4
0
 def __init__(self):
     #Initialisation de la scene
     Scene.__init__(self)
     #Chargement de l'image de fond de la scene
     self.fond = fonction.charger_image("fond.jpg")
     #Chargement des objets
     self.bulles = bulles.Bulles() 
     self.pointeur = pointeur.Pointeur(15,24) 
     #self.pointeur.positionner(15,3) 
     self.poisson_1 = poisson.Poisson()
     self.poisson_2 = poisson.Poisson()
     self.poisson_3 = poisson.Poisson()
     self.poisson_4 = poisson.Poisson()
     
     #Chargement de la musique de fond 
     #self.musique = pygame.mixer.music.load("./sons/bouge.ogg")
     #self.musique.set_volume(0.5)
     #self.musique.fadeout(400) 
 
     #Chargement des textes à afficher
     self.texte_titre = fonction.Texte("Aquarium", 50, constante.noir)
     self.texte_stitre = fonction.Texte("Credits", 20, constante.gris)
     self.credis = credis.lire_credis()
     self.texte_credis = fonction.Texte_multiligne( (self.credis) )
     self.texte_credis.position(0, 0, 380, 65)
     self.texte_retour = fonction.Texte(" > Retour [R]",30, constante.bleufonce)
Exemplo n.º 5
0
 def __init__(self):
     #Initialisation de la scene
     Scene.__init__(self)
     #Chargement de l'image de fond de la scene
     self.fond = fonction.charger_image("fond.jpg")
     #Chargement des objets
     self.bulles = bulles.Bulles()
     self.pointeur = pointeur.Pointeur(14,3) 
     self.poisson_1 = poisson.Poisson()
     self.poisson_2 = poisson.Poisson()
     self.poisson_3 = poisson.Poisson()
     self.poisson_4 = poisson.Poisson()
     
     #Chargement de la musique de fond 
     #self.musique = pygame.mixer.music.load("./sons/bouge.ogg")
     #self.musique.set_volume(0.5)
     #self.musique.fadeout(400) 
 
     #Chargement des textes à afficher
     self.texte_titre = fonction.Texte("Aquarium", 50, constante.noir)
     #Menu
     self.texte_menu_jouer = fonction.Texte(" > Jouer [J]",30, constante.bleufonce)
     self.texte_menu_credis = fonction.Texte(" > Credits [C]",30, constante.noir)
     self.texte_menu_quitter = fonction.Texte(" > Quitter [Q]",30, constante.noir)
     #joystick
     self.nb_joysticks = pygame.joystick.get_count()
     if self.nb_joysticks > 0:
         self.texte_joystick = fonction.Texte("Joystick ok", 20, constante.gris)
     else:
         self.texte_joystick = fonction.Texte("Pas de joystick", 20, constante.gris)
Exemplo n.º 6
0
class PyAgar(object):
    title = "PyAgar"
    def __init__(self, args):
        self.args = args

        pyglet.resource.path.append(os.path.join(dname,'resources'))
        pyglet.resource.reindex()
        pyglet.font.add_file('resources/DejaVuSans.ttf')
        pyglet.font.add_file('resources/unifont.ttf')

        director.set_show_FPS(False)
        w = director.init(fullscreen=True, caption=self.title, visible=True, resizable=True)

        # width = director.window.width
        # height = director.window.height
        # wnew, hnew = int(width * .75), int(height * .75)
        # director.window.set_fullscreen(False)
        # director.window.set_size(wnew, hnew)
        # w.set_location((width-wnew)/2, (height-hnew)/2)

        director.window.pop_handlers()
        director.window.push_handlers(Handler())

        self.gameScene = Scene()
        self.gameLayer = AgarLayer()
        self.gameScene.add(self.gameLayer)

        director.replace(self.gameScene)

        director.window.set_visible(True)
Exemplo n.º 7
0
 def test_each_player_is_positioned_on_a_different_block(self):
     scene = Scene(self.get_surface())
     # Add as many player as the number of blocks scene has
     for player in [Player() for _ in range(scene.block_count)]:
         scene.add_player(player)
     self.assertEqual(len(scene.player_positions), scene.block_count)
     self.assertEqual(len(set(scene.player_positions)), scene.block_count)
Exemplo n.º 8
0
 def __init__(self):
   Scene.__init__(self)
   self._screen = Screen()
   self._player = PlayerCharacter()
   self._floor = CurrentFloor()
   self._sight = Sight(self._player)
   self._floor.put_monster(Monster())
Exemplo n.º 9
0
def parseconfig(config):
    data = json.loads(config)
    objectlist, lights = [], []
    for conf in data["objects"]:
        if conf["type"] == "sphere":
            posx, posy, posz = conf["position"]
            r = conf["radius"]
            col = conf["color"]
            roughness = conf["roughness"]
            obj = objects.CollidableSphere(
                position=euclid.Point3(posx, posy, posz), radius=r, color=col, roughness=roughness
            )
        elif conf["type"] == "plane":
            orix, oriy, oriz = conf["origin"]
            normx, normy, normz = conf["normal"]
            roughness = conf["roughness"]
            obj = objects.CollidablePlane(
                origin=euclid.Point3(orix, oriy, oriz), normal=euclid.Vector3(normx, normy, normz), roughness=roughness
            )
        objectlist.append(obj)
    for conf in data["lights"]:
        x, y, z = conf
        lights.append(objects.Light(position=euclid.Point3(x, y, z)))
    conf = data["camera"]
    imgw, imgh = conf["imageDim"]
    scrw, scrh = conf["screenDim"]
    focal = conf["focallength"]
    camera = Camera(imageDim=(imgw, imgh), focallength=focal, screenDim=(scrw, scrh))
    scene = Scene(camera=camera, objects=objectlist, lights=lights)
    scene.skycolor = tuple(data["skycolor"])
    depth = data["depth"]

    return camera, depth, lights, objectlist, scene
Exemplo n.º 10
0
    def __init__(self, game):
        Scene.__init__(self, game, ORTHOGONAL)
        self.centerMouse()
        self.ceilings = None
        self.lastPut = None
        self.horEnergy = True #riq's preferences
        self.world = world.World()
        self.ballsAtGoal = 0
        self.lost = 0
        self.llss = [] #limited life segments
        self.attractors = []
        self.root_node.background_color = CELESTE_CIELO
        self._energy = 2000
        self.cameraArea = self.CAMERA_AREA
        self.maxEnergy=3000
        import sound
        sound.playRandomSong()
        
        self.setup_level()
             
        mountainsGroup = qgl.scene.Group()
        mountainsTexture = qgl.scene.state.Texture(data.filepath("montagnas.png"))
        FACTOR= 5.5
        mountainsQuad = qgl.scene.state.Quad((2403/FACTOR,427/FACTOR))
        mountainsGroup.scale = (self.mountainScale, self.mountainScale, 0.0)
        mountainsGroup.translate = (0,-55.-70.0*(self.cameraArea[3])/500.,0)
        mountainsGroup.add(mountainsTexture, mountainsQuad)
        self.group.add(mountainsGroup)

        self.initLineGhost()
        self.group.scale = (5.0,5.0,0.0)
        self.initScores()
        self.updateScores()
        self.accept()
Exemplo n.º 11
0
 def __init__(self, nrows, *args, **kwargs):
     Scene.__init__(self, *args, **kwargs)
     self.nrows            = nrows
     self.diagram_height   = 2*SPACE_HEIGHT - 1
     self.diagram_width    = 1.5*SPACE_WIDTH
     self.cell_height      = self.diagram_height / nrows
     self.cell_width       = self.diagram_width / nrows
     self.portion_to_fill  = 0.7
     self.bottom_left      = np.array(
         (-self.cell_width * nrows / 2.0, -self.cell_height * nrows / 2.0, 0)
     )
     num_to_num_mob   = {} 
     self.coords_to_mobs   = {}
     self.coords = [(n, k) for n in range(nrows) for k in range(n+1)]    
     for n, k in self.coords:
         num = choose(n, k)              
         center = self.coords_to_center(n, k)
         if num not in num_to_num_mob:
             num_to_num_mob[num] = TexMobject(str(num))
         num_mob = num_to_num_mob[num].copy()
         scale_factor = min(
             1,
             self.portion_to_fill * self.cell_height / num_mob.get_height(),
             self.portion_to_fill * self.cell_width / num_mob.get_width(),
         )
         num_mob.center().scale(scale_factor).shift(center)
         if n not in self.coords_to_mobs:
             self.coords_to_mobs[n] = {}
         self.coords_to_mobs[n][k] = num_mob
     self.add(*[self.coords_to_mobs[n][k] for n, k in self.coords])
Exemplo n.º 12
0
 def __init__(self, nextScene, text="press enter...", *a):
     Scene.__init__(self, *a)
     self.nextScene = nextScene
     font = data.filepath('You Are Loved.ttf')
     figure = leafs.TextoAlineado(text, font, size=1000, alignx=0.5, aligny=0.5)
     self.group.add(figure)
     self.accept()
Exemplo n.º 13
0
    def __init__(self, gurls, bg_surf=None, back_color=(234,45,30), back_pos=(40,500),
                 back_size=(70,40), back_font=None):
        Scene.__init__(self)
        self.gurls = gurls  # expect three
        self.bg_surf = bg_surf
        self.done = False
        self.choice = None

        def finish():
            self.done = True
        self.buttons.add(BlockButton(finish, back_color, back_size, back_pos,
                                     text="Back", font=back_font))
        self.gurl_sprites = pygame.sprite.Group()
        gurl_pos = [(100, 100), (300, 100), (500, 100)]

        def make_choice(gurl):
            self.done = True
            self.choice = gurl

        def make_gurl_sprite(gurl):
            pos = gurl_pos.pop(0)
            sprite = GurlSprite(gurl, pos)
            sprite.on_click = lambda: make_choice(gurl)
            self.gurl_sprites.add(sprite)

        make_gurl_sprite(Kanaya())
        make_gurl_sprite(Isadora())

        self.buttons.add(self.gurl_sprites)
        self.all_sprites.add(self.buttons, self.gurl_sprites)
        self.main_surface = pygame.display.get_surface()
Exemplo n.º 14
0
 def dither(self, time = 1, blink = True):
     while time > 0:
         if blink and time%2 == 1:
             self.play(Blink(self.randy))
         else:
             Scene.dither(self, time)
         time -= 1
     return self
Exemplo n.º 15
0
 def __init__(self, world, game):
     Scene.__init__(self, world)
     self.game = game
     self.step = 0
     self._create_sprites()
     self.text = text.History("Good bye robot city...")
     self.texts = []
     pyglet.clock.schedule_once(self._create_text, 3)
Exemplo n.º 16
0
 def test_render(self):
   renderer = LuxRenderer(samples_per_pixel=1000)
   scene = Scene()
   scene.camera = Camera(loc=(0, -10, 0), to=(0, 0, 0))
   scene.objects.append(Sphere())
   scene.objects.append(Sphere(center=(1, -1, 0.5), radius=0.5,
                               light=AreaLight(color=(1, 1, 1))))
   renderer.render(scene, generate_only=True)
Exemplo n.º 17
0
    def __init__(self, world):
        Scene.__init__(self, world)
        self.step = 0
        self._load_background()
        self.name = text.AboutText()
        self._create_sprites()

        pyglet.clock.schedule_once(self.show_losersjuegos_logo, 4 + 3 * 2)
Exemplo n.º 18
0
    def __init__(self, game, last_option_in_main):
        Scene.__init__(self, game)
        items = [
                ("Fullscreen", self.game.fullscreen),
                ("Return", self.on_return)
                ]

        self.menu = Menu(self, items)
        self.last_option_in_main = last_option_in_main
Exemplo n.º 19
0
 def dither(self, time = 1, blink = True):
     while time > 0:
         if blink and self.total_dither_time%2 == 1:
             self.play(Blink(self.pi_creature))
         else:
             Scene.dither(self, time)
         time -= 1
         self.total_dither_time += 1
     return self
Exemplo n.º 20
0
    def __init__(self, world, start_music=True):
        Scene.__init__(self, world)
        self.step = 0
        self._create_sprites()
        self.background = common.load_image('black.png')
        self.text = text.Text(MSG_START, 170, 10)

        if start_music:
            self.world.audio.play_music('intro')
Exemplo n.º 21
0
 def __init__(self):
     #Initialisation de la scene
     Scene.__init__(self)
     #Chargement de l'image de fond de la scene
     self.fond = fonction.charger_image("fond.jpg")
     #Creation des objets.
     self.bulles = bulles.Bulles()
     self.nourriture = nourriture.Nourriture()
     self.poissons = poissons.Poissons()
Exemplo n.º 22
0
class Game(engine.State):
    def init(self):
        self.image = load_image('bg_800x600.png')
        self.screen.blit(self.image[0], (0,0))

        self.speed = Speed()

        self.player = objects.PigOnTractor((250, 300), self.speed)

        self.police = objects.Police((-300, 300), self.speed)

        self.scene = Scene(self.player)

        for i in range(200):
            self.do_scene()

    def do_scene(self):
        self.scene.generate()
        self.scene.bias()
        self.scene.clean()  

    def event(self, events):
        for event in events:
            if event.type == pygame.QUIT:
                return engine.Quit(self.game, self.debug)

            elif event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_ESCAPE:
                    return MainMenu(self.game, self.debug)
                elif event.key == pygame.K_LEFT:
                    self.speed.down()
                elif event.key == pygame.K_RIGHT:
                    self.speed.up()

            elif event.type == UPDATESCENE:
                self.do_scene()
                self.player.consume_gas()

        self.player.event(events)

    def update(self, passed_time):
        self.player.update()
        self.scene.update()
        self.police.update()
        if self.police.status == 'arrest':
            return GameOver(self.game, self.debug, 'game_over_arrested.png', self.player.get_score())
        if self.player.status() == 'arrested':
            return GameOver(self.game, self.debug, 'game_over_arrested.png', self.player.get_score())
        elif self.player.status() == 'died':
            return GameOver(self.game, self.debug, 'game_over_die.png', self.player.get_score())

    def paint(self):
        self.screen.blit(self.image[0], (0,0))
        self.scene.draw(self.screen)
        self.player.draw(self.screen)
        self.police.draw(self.screen)
Exemplo n.º 23
0
 def dither(self, time = 1, blink = True):
     while time > 0:
         time_to_blink = self.total_dither_time%self.seconds_to_blink == 0
         if blink and self.any_pi_creatures_on_screen() and time_to_blink:
             self.blink()
         else:
             Scene.dither(self)
         time -= 1
         self.total_dither_time += 1
     return self
Exemplo n.º 24
0
 def __init__(self, director, background_name, continue_scene):
     '''
     Constructor
     '''
     Scene.__init__(self, director, background_name)
     for buttom in self.common_buttoms.itervalues():
         buttom.is_visible = True
     
     self.continue_scene = continue_scene         
     self.next_btn = Buttom((config.width/2, (config.height/2 + 150)), config.b_size, 'continue_pressed'+PNG_EXT, 'continue_release'+PNG_EXT, True) 
Exemplo n.º 25
0
    def render(self):
        scene = Scene(self.width, self.height)

        start = time.time()

        for x, y, pixel in scene.render():
            self.surface.set_at((x, y), pixel)

        end = time.time()
        print('Rendered in {0}s'.format(end - start))
Exemplo n.º 26
0
 def __init__(self, director, page_number = False, previous = False, follow = False):
     '''
     Constructor
     '''
     Scene.__init__(self, director, False, page_number)
     self.previous = previous
     self.follow = follow
     self.prev_init = False          
     self.buttoms = {}
     self.buttoms[GO_SCHEME] = Buttom(config.page_btn_go_scheme_pos, config.page_btn_size, 'go_scheme_pressed'+PNG_EXT, 'go_scheme_release'+PNG_EXT, True)
Exemplo n.º 27
0
 def __init__(self, director, background_match):
     '''
     Constructor
     '''
     Scene.__init__(self, director, background_match)        
     self.definitions = Definitions()
     
     
     for buttom in self.common_buttoms.itervalues():
         buttom.is_visible = True
Exemplo n.º 28
0
    def __init__(self, world, score=0):
        Scene.__init__(self, world)
        self.score = score

        self.root_node.background_color = view.CELESTE_CIELO
        am = self.actionManager = Manager()
        am.do( None,
            delay(10) +
            call(self.next)        
            )
Exemplo n.º 29
0
 def test_generated_block_heights_are_within_limits(self):
     scene = Scene(self.get_surface())
     h_max = scene.max_block_height * 600
     # The initializer should have generated block heights
     # but we will randomize a few more times just to be sure.
     for _ in range(100):
         for h in scene.get_block_heights():
             self.assert_(h >= 0.0)
             self.assert_(h <= h_max)
         scene.generate_blocks()
Exemplo n.º 30
0
 def __init__(self, world, game):
     Scene.__init__(self, world)
     self.game = game
     self.step = 0
     self._load_images()
     self.are_showing_message = False
     self.texts = []
     self.layer = common.load_image('game_over_layer.png')
     self.show_layer = False
     pyglet.clock.schedule_once(self._create_game_over_text, 3)
Exemplo n.º 31
0
 def add(self, *mobjects):
     Scene.add(self, *list(mobjects)+self.foreground_mobjects)
Exemplo n.º 32
0
 def separate_moving_and_static_mobjects(self, *animations):
     moving, static = Scene.separate_moving_and_static_mobjects(self, *animations)
     if self.camera.position_mobject in moving:
         return moving + static, []
     return moving, static
Exemplo n.º 33
0
def generateData():
    sc = Scene(recordData=True)
    sp = ScenePlot(sc)
    #sc.occupancyMapType = sc.OCCUPANCY_MAP_THREE_CHANNEL
    sc.occupancyMapType = sc.OCCUPANCY_MAP_BINARY
    sc.dynamics = sc.DYNAMICS_MODEL_BASED_LINEAR  # robot dynamics
    try:
        sc.addRobot(np.float32([[-2, 0, 0], [0.0, 0.0, 0.0]]),
                    role=sc.ROLE_LEADER)
        sc.addRobot(np.float32([[1, 3, 0], [-1.0, 0.0, 0.0]]),
                    role=sc.ROLE_FOLLOWER)
        #        sc.addRobot(np.float32([[1, 3, 0], [-1.0, 0.0, 0.0]]), role = sc.ROLE_FOLLOWER, learnedController = fcl.test)
        #==============================================================================
        #         sc.addRobot(np.float32([[1, 3, 0], [0, -1, 0]]),
        #                     dynamics = sc.DYNAMICS_LEARNED,
        #                     learnedController = fcl.test)
        #==============================================================================

        # No leader
        sc.setADjMatrix(np.uint8([[0, 0], [1, 0]]))
        # Set robot 0 as the leader.

        # vrep related
        sc.initVrep()
        # Choose sensor type
        sc.SENSOR_TYPE = "VPL16"  # None, 2d, VPL16, kinect
        #sc.SENSOR_TYPE = "None" # None, 2d, VPL16, kinect
        sc.objectNames = [
            'Pioneer_p3dx', 'Pioneer_p3dx_leftMotor', 'Pioneer_p3dx_rightMotor'
        ]

        if sc.SENSOR_TYPE == "None":
            sc.setVrepHandles(0, '')
            sc.setVrepHandles(1, '#0')
        elif sc.SENSOR_TYPE == "2d":
            sc.objectNames.append('LaserScanner_2D_front')
            sc.objectNames.append('LaserScanner_2D_rear')
            sc.setVrepHandles(0, '')
            sc.setVrepHandles(1, '#0')
        elif sc.SENSOR_TYPE == "VPL16":
            sc.objectNames.append('velodyneVPL_16')  # _ptCloud
            sc.setVrepHandles(0, '')
            sc.setVrepHandles(1, '#0')
        elif sc.SENSOR_TYPE == "kinect":
            sc.objectNames.append('kinect_depth')
            sc.objectNames.append('kinect_rgb')
            sc.setVrepHandles(0, '')
            sc.setVrepHandles(1, '#0')

        #sc.renderScene(waitTime = 3000)
        tf = 40  # must be greater than 1
        sc.resetPosition()
        sp.plot(3, tf)

        while sc.simulate():
            #sc.renderScene(waitTime = int(sc.dt * 1000))
            sc.showOccupancyMap(waitTime=int(sc.dt * 1000))

            #print("---------------------")
            #print("t = %.3f" % sc.t, "s")

            if sc.t > 1:
                maxAbsError = sc.getMaxFormationError()
                if maxAbsError < 0.01:
                    pass  #tf = sc.t - 0.01

            #sp.plot(0, tf)
            sp.plot(2, tf)
            #sp.plot(1, tf)
            sp.plot(3, tf)
            sp.plot(4, tf)
            sp.plot(6, tf)

            if sc.t > tf:
                print('maxAbsError = ', maxAbsError)
                break

            #print('robot 0: ', sc.robots[0].xi.x, ', ', sc.robots[0].xi.y, ', ', sc.robots[0].xi.theta)
            #print('robot 1: ', sc.robots[1].xi.x, ', ', sc.robots[1].xi.y, ', ', sc.robots[1].xi.theta)
            #print('robot 2: ', sc.robots[2].xi.x, ', ', sc.robots[2].xi.y, ', ', sc.robots[2].xi.theta)
            #print('y01: ' + str(sc.robots[1].xi.y - sc.robots[0].xi.y))
            #print('x02: ' + str(sc.robots[2].xi.x - sc.robots[0].xi.x))
        sc.deallocate()
    except KeyboardInterrupt:
        x = input('Quit?(y/n)')
        sc.deallocate()
        if x == 'y' or x == 'Y':
            tf = sc.t - 0.01

            sp.plot(2, tf)
            sp.plot(3, tf)
            sp.plot(4, tf)
            sp.plot(6, tf)

            raise Exception('Aborted.')

    except:
        sc.deallocate()
        raise

    if True:  #maxAbsError < 0.01:
        return sc
    else:
        return None
Exemplo n.º 34
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        self.file = None
        self.resize(500, 300)
        self.setWindowTitle("Paint")
        self.create_scene()
        self.create_actions()
        # self.create_ContextMenu()
        self.create_menus()
        self.connect_actions()
        self.create_status_bar()
        #to check default tools and styles
        self.action_line.setChecked(True)
        self.action_brush_solid.setChecked(True)
        self.action_solid.setChecked(True)
        self.action_pen_width_3.setChecked(True)


##        textEdit = QtGui.QTextEdit()
##        self.setCentralWidget(textEdit)

    def create_scene(self):
        view = QtWidgets.QGraphicsView()
        self.scene = Scene(self)
        view.setScene(self.scene)
        self.setCentralWidget(view)

    def create_actions(self):
        #File
        self.action_new = QtWidgets.QAction(QtGui.QIcon('icons/new.png'),
                                            'New', self)
        self.action_new.setShortcut('Ctrl+N')
        self.action_new.setStatusTip('Open a New File')
        self.action_save = QtWidgets.QAction(QtGui.QIcon('icons/save.png'),
                                             'Save', self)
        self.action_save.setShortcut('Ctrl+S')
        self.action_save.setStatusTip('Save to file')
        self.action_save_as = QtWidgets.QAction(
            QtGui.QIcon('icons/save_as.png'), 'Save as', self)
        self.action_save_as.setShortcut('Ctrl+Shift+S')
        self.action_save_as.setStatusTip('Save to file as')
        self.action_open = QtWidgets.QAction(QtGui.QIcon('icons/open.png'),
                                             'Open', self)
        self.action_open.setShortcut('Ctrl+O')
        self.action_open.setStatusTip('Open file')
        self.action_exit = QtWidgets.QAction(QtGui.QIcon('icons/exit.png'),
                                             'Exit', self)
        self.action_exit.setShortcut('Ctrl+Q')
        self.action_exit.setStatusTip('Exit application')
        self.group_action_tools = QtWidgets.QActionGroup(self)
        #Tools
        self.action_line = QtWidgets.QAction(
            QtGui.QIcon('icons/tool_line.png'), self.tr("&Line"), self)
        self.action_line.setCheckable(True)
        self.action_line.setChecked(False)

        self.action_rectangle = QtWidgets.QAction(
            QtGui.QIcon('icons/tool_rectangle.png'), self.tr("&Rectangle"),
            self)
        self.action_rectangle.setCheckable(True)
        self.action_rectangle.setChecked(False)

        self.action_ellipse = QtWidgets.QAction(
            QtGui.QIcon('icons/tool_ellipse.png'), self.tr("&Ellipse"), self)
        self.action_ellipse.setCheckable(True)
        self.action_ellipse.setChecked(False)

        self.action_polygon = QtWidgets.QAction(
            QtGui.QIcon('icons/tool_polygon.png'), self.tr("&Polygon"), self)
        self.action_polygon.setCheckable(True)
        self.action_polygon.setChecked(False)

        self.action_text = QtWidgets.QAction(
            QtGui.QIcon('icons/tool_text.png'), self.tr("&Text"), self)
        self.action_text.setCheckable(True)
        self.action_text.setChecked(False)

        self.group_action_tools.addAction(self.action_line)
        self.group_action_tools.addAction(self.action_rectangle)
        self.group_action_tools.addAction(self.action_ellipse)
        self.group_action_tools.addAction(self.action_polygon)
        self.group_action_tools.addAction(self.action_text)
        #Style
        self.action_pen_color = QtWidgets.QAction(self.tr("Color"), self)
        self.action_pen_line = QtWidgets.QAction(self.tr("Line"), self)
        self.action_pen_width = QtWidgets.QAction(self.tr("Width"), self)
        self.action_brush_color = QtWidgets.QAction(self.tr("Color"), self)
        self.action_brush_fill = QtWidgets.QAction(self.tr("Fill"), self)
        self.action_font = QtWidgets.QAction(self.tr("Font"), self)

        self.action_solid = QtWidgets.QAction(
            QtGui.QIcon('icons/qpen-solid1.png'), self.tr("&SolidLine"), self)
        self.action_solid.setCheckable(True)
        self.action_solid.setChecked(False)
        self.group_action_tools.addAction(self.action_solid)
        self.action_dot = QtWidgets.QAction(QtGui.QIcon('icons/qpen-dot1.png'),
                                            self.tr("&DotLine"), self)
        self.action_dot.setCheckable(True)
        self.action_dot.setChecked(False)
        self.group_action_tools.addAction(self.action_dot)
        self.action_dash = QtWidgets.QAction(
            QtGui.QIcon('icons/qpen-dash1.png'), self.tr("&DashLine"), self)
        self.action_dash.setCheckable(True)
        self.action_dash.setChecked(False)
        self.group_action_tools.addAction(self.action_dash)
        self.action_dashdot = QtWidgets.QAction(
            QtGui.QIcon('icons/qpen-dashdot1.png'), self.tr("&DashDotLine"),
            self)
        self.action_dashdot.setCheckable(True)
        self.action_dashdot.setChecked(False)
        self.group_action_tools.addAction(self.action_dashdot)
        self.action_dashdotdot = QtWidgets.QAction(
            QtGui.QIcon('icons/qpen-dashdotdot1.png'),
            self.tr("&DashDotDotLine"), self)
        self.action_dashdotdot.setCheckable(True)
        self.action_dashdotdot.setChecked(False)
        self.group_action_tools.addAction(self.action_dashdotdot)

        self.action_pen_width_1 = QtWidgets.QAction(self.tr("&1"), self)
        self.action_pen_width_1.setCheckable(True)
        self.action_pen_width_1.setChecked(False)
        self.group_action_tools.addAction(self.action_pen_width_1)
        self.action_pen_width_2 = QtWidgets.QAction(self.tr("&2"), self)
        self.action_pen_width_2.setCheckable(True)
        self.action_pen_width_2.setChecked(False)
        self.group_action_tools.addAction(self.action_pen_width_2)
        self.action_pen_width_3 = QtWidgets.QAction(self.tr("&3"), self)
        self.action_pen_width_3.setCheckable(True)
        self.action_pen_width_3.setChecked(False)
        self.group_action_tools.addAction(self.action_pen_width_3)
        self.action_pen_width_4 = QtWidgets.QAction(self.tr("&4"), self)
        self.action_pen_width_4.setCheckable(True)
        self.action_pen_width_4.setChecked(False)
        self.group_action_tools.addAction(self.action_pen_width_4)
        self.action_pen_width_5 = QtWidgets.QAction(self.tr("&5"), self)
        self.action_pen_width_5.setCheckable(True)
        self.action_pen_width_5.setChecked(False)
        self.group_action_tools.addAction(self.action_pen_width_5)
        self.action_pen_width_6 = QtWidgets.QAction(self.tr("&6"), self)
        self.action_pen_width_6.setCheckable(True)
        self.action_pen_width_6.setChecked(False)
        self.group_action_tools.addAction(self.action_pen_width_6)

        self.action_brush_no = QtWidgets.QAction(
            QtGui.QIcon('icons/nobrush.png'), self.tr("&No"), self)
        self.action_brush_no.setCheckable(True)
        self.action_brush_no.setChecked(False)
        self.group_action_tools.addAction(self.action_brush_no)
        self.action_brush_solid = QtWidgets.QAction(
            QtGui.QIcon('icons/brush_solid.png'), self.tr("&Solid"), self)
        self.action_brush_solid.setCheckable(True)
        self.action_brush_solid.setChecked(False)
        self.group_action_tools.addAction(self.action_brush_solid)
        self.action_brush_dense3 = QtWidgets.QAction(
            QtGui.QIcon('icons/brush_dense3.png'), self.tr("&Dense3"), self)
        self.action_brush_dense3.setCheckable(True)
        self.action_brush_dense3.setChecked(False)
        self.group_action_tools.addAction(self.action_brush_dense3)
        self.action_brush_dense5 = QtWidgets.QAction(
            QtGui.QIcon('icons/brush_dense5.png'), self.tr("&Dense5"), self)
        self.action_brush_dense5.setCheckable(True)
        self.action_brush_dense5.setChecked(False)
        self.group_action_tools.addAction(self.action_brush_dense5)
        self.action_brush_dense7 = QtWidgets.QAction(
            QtGui.QIcon('icons/brush_dense7.png'), self.tr("&Dense7"), self)
        self.action_brush_dense7.setCheckable(True)
        self.action_brush_dense7.setChecked(False)
        self.group_action_tools.addAction(self.action_brush_dense7)
        self.action_brush_cross = QtWidgets.QAction(
            QtGui.QIcon('icons/brush_cross.png'), self.tr("&Cross"), self)
        self.action_brush_cross.setCheckable(True)
        self.action_brush_cross.setChecked(False)
        self.group_action_tools.addAction(self.action_brush_cross)
        self.action_brush_diag = QtWidgets.QAction(
            QtGui.QIcon('icons/brush_diag.png'), self.tr("&Diag"), self)
        self.action_brush_diag.setCheckable(True)
        self.action_brush_diag.setChecked(False)
        self.group_action_tools.addAction(self.action_brush_diag)
        self.action_brush_diag_cross = QtWidgets.QAction(
            QtGui.QIcon('icons/brush_diag_cross.png'), self.tr("&Diag Cross"),
            self)
        self.action_brush_diag_cross.setCheckable(True)
        self.action_brush_diag_cross.setChecked(False)
        self.group_action_tools.addAction(self.action_brush_diag_cross)
        # self.action_brush_gradient = QtWidgets.QAction(QtGui.QIcon('icons/brush_gradient.png'),self.tr("&Gradient"), self)
        # self.action_brush_gradient.setCheckable(True)
        # self.action_brush_gradient.setChecked(False)
        # self.group_action_tools.addAction(self.action_brush_gradient)

    def create_menus(self):
        #       statusbar=self.statusBar()
        menubar = self.menuBar()

        #File
        menu_file = menubar.addMenu('&File')
        menu_file.addAction(self.action_new)
        menu_file.addAction(self.action_open)
        menu_file.addAction(self.action_save)
        menu_file.addAction(self.action_save_as)
        menu_file.addSeparator()
        menu_file.addAction(self.action_exit)

        #Tools
        self.menu_tools = menubar.addMenu('&Tools')
        self.menu_tools.addAction(self.action_line)
        self.menu_tools.addAction(self.action_rectangle)
        self.menu_tools.addAction(self.action_ellipse)
        self.menu_tools.addAction(self.action_polygon)
        self.menu_tools.addSeparator()
        self.menu_tools.addAction(self.action_text)

        #Style
        self.menu_style = menubar.addMenu('&Style')
        self.menu_style_pen = self.menu_style.addMenu('Pen')
        self.menu_style_pen.addAction(self.action_pen_color)
        self.menu_style_pen_line = self.menu_style_pen.addMenu('Line')
        self.menu_style_pen_line.addAction(self.action_solid)
        self.menu_style_pen_line.addAction(self.action_dot)
        self.menu_style_pen_line.addAction(self.action_dash)
        self.menu_style_pen_line.addAction(self.action_dashdot)
        self.menu_style_pen_line.addAction(self.action_dashdotdot)

        menu_style_pen_width = self.menu_style_pen.addMenu('Width (px)')
        menu_style_pen_width.addAction(self.action_pen_width_1)
        menu_style_pen_width.addAction(self.action_pen_width_2)
        menu_style_pen_width.addAction(self.action_pen_width_3)
        menu_style_pen_width.addAction(self.action_pen_width_4)
        menu_style_pen_width.addAction(self.action_pen_width_5)
        menu_style_pen_width.addAction(self.action_pen_width_6)

        self.menu_style_brush = self.menu_style.addMenu('Brush')
        self.menu_style_brush.addAction(self.action_brush_color)
        self.menu_style_brush_fill = self.menu_style_brush.addMenu('Fill')
        self.menu_style_brush_fill.addAction(self.action_brush_no)
        self.menu_style_brush_fill.addAction(self.action_brush_solid)
        self.menu_style_brush_fill.addAction(self.action_brush_dense3)
        self.menu_style_brush_fill.addAction(self.action_brush_dense5)
        self.menu_style_brush_fill.addAction(self.action_brush_dense7)
        self.menu_style_brush_fill.addAction(self.action_brush_cross)
        self.menu_style_brush_fill.addAction(self.action_brush_diag)
        self.menu_style_brush_fill.addAction(self.action_brush_diag_cross)
        # self.menu_style_brush_fill.addAction(self.action_brush_gradient)

        self.menu_style.addAction(self.action_font)

        #Help
        menu_help = self.menuBar().addMenu(self.tr("&Help"))
        self.action_about_us = menu_help.addAction(self.tr("&Abut Us"))
        self.action_about_qt = menu_help.addAction(self.tr("&About Qt"))
        self.action_about_app = menu_help.addAction(
            self.tr("&About the Application"))

        toolbarExit = self.addToolBar('Exit')
        toolbarExit.addAction(self.action_open)
        toolbarExit.addAction(self.action_save)
        toolbarExit.addAction(self.action_exit)
        toolbarTools = self.addToolBar('Tools')
        toolbarTools.addAction(self.action_line)
        toolbarTools.addAction(self.action_rectangle)
        toolbarTools.addAction(self.action_polygon)
        toolbarTools.addAction(self.action_ellipse)
        toolbarTools.addAction(self.action_text)

    def create_status_bar(self):

        # setting status bar message
        self.statusBar().showMessage("Status Bar")

        # creating a label widget
        self.label_1 = QtWidgets.QLabel("Label 1")

        # adding label to status bar
        self.statusBar().addPermanentWidget(self.label_1)

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.MouseMove:
            pos = event.pos()
            self.label_1.setText("x :%d, y :%d" % (pos.x(), pos.y()))
        return super(MainWindow, self).eventFilter(source, event)

    def connect_actions(self):
        self.action_new.triggered.connect(self.file_new)
        self.action_open.triggered.connect(self.file_open)
        self.action_save.triggered.connect(self.file_save)
        self.action_save_as.triggered.connect(self.file_save_as)
        self.action_exit.triggered.connect(self.file_exit)
        self.action_about_us.triggered.connect(self.help_about_us)
        self.action_about_qt.triggered.connect(self.help_about_qt)
        self.action_about_app.triggered.connect(self.help_about_app)
        self.action_pen_color.triggered.connect(self.pen_color_selection)
        self.action_brush_color.triggered.connect(self.brush_color_selection)
        self.action_font.triggered.connect(self.font_selection)

        self.action_line.triggered.connect(
            lambda checked, tool="line": self.set_action_tool(checked, tool))
        self.action_rectangle.triggered.connect(
            lambda checked, tool="rectangle": self.set_action_tool(
                checked, tool))
        self.action_ellipse.triggered.connect(
            lambda checked, tool="ellipse": self.set_action_tool(
                checked, tool))
        self.action_polygon.triggered.connect(
            lambda checked, tool="polygon": self.set_action_tool(
                checked, tool))
        self.action_text.triggered.connect(
            lambda checked, tool="text": self.set_action_tool(checked, tool))

        self.action_pen_width_1.triggered.connect(
            lambda checked, width="1": self.set_action_width(checked, width))
        self.action_pen_width_2.triggered.connect(
            lambda checked, width="2": self.set_action_width(checked, width))
        self.action_pen_width_3.triggered.connect(
            lambda checked, width="3": self.set_action_width(checked, width))
        self.action_pen_width_4.triggered.connect(
            lambda checked, width="4": self.set_action_width(checked, width))
        self.action_pen_width_5.triggered.connect(
            lambda checked, width="5": self.set_action_width(checked, width))
        self.action_pen_width_6.triggered.connect(
            lambda checked, width="6": self.set_action_width(checked, width))

        self.action_solid.triggered.connect(
            lambda checked, pen="SolidLine": self.set_action_pen(checked, pen))
        self.action_dot.triggered.connect(
            lambda checked, pen="DotLine": self.set_action_pen(checked, pen))
        self.action_dash.triggered.connect(
            lambda checked, pen="DashLine": self.set_action_pen(checked, pen))
        self.action_dashdot.triggered.connect(
            lambda checked, pen="DashDotLine": self.set_action_pen(
                checked, pen))
        self.action_dashdotdot.triggered.connect(
            lambda checked, pen="DashDotDotLine": self.set_action_pen(
                checked, pen))

        self.action_brush_no.triggered.connect(
            lambda checked, brush="No": self.set_action_brush(checked, brush))
        self.action_brush_solid.triggered.connect(
            lambda checked, brush="Solid": self.set_action_brush(
                checked, brush))
        self.action_brush_dense3.triggered.connect(
            lambda checked, brush="Dense3": self.set_action_brush(
                checked, brush))
        self.action_brush_dense5.triggered.connect(
            lambda checked, brush="Dense5": self.set_action_brush(
                checked, brush))
        self.action_brush_dense7.triggered.connect(
            lambda checked, brush="Dense7": self.set_action_brush(
                checked, brush))
        self.action_brush_cross.triggered.connect(
            lambda checked, brush="Cross": self.set_action_brush(
                checked, brush))
        self.action_brush_diag.triggered.connect(
            lambda checked, brush="Diag": self.set_action_brush(
                checked, brush))
        self.action_brush_diag_cross.triggered.connect(
            lambda checked, brush="Diag Cross": self.set_action_brush(
                checked, brush))
        # self.action_brush_gradient.triggered.connect(lambda checked, brush="Gradient": self.set_action_brush(checked,brush))

    def set_action_tool(self, checked, tool):
        print("lamda checked, tool : ", checked, tool)
        self.scene.set_tool(tool)
        self.statusBar().showMessage("Tool used : " + tool)

    def set_action_pen(self, checked, pen):
        print("lamda checked, pen : ", checked, pen)
        self.scene.set_pen(pen)
        self.statusBar().showMessage("Pen used : " + pen)

    def set_action_width(self, checked, width):
        print("lamda checked, width : ", checked, width)
        self.scene.set_width(width)
        self.statusBar().showMessage("Width of the pen used : " + width)

    def set_action_brush(self, checked, brush):
        print("lamda checked, brush : ", checked, brush)
        self.scene.set_brush(brush)
        self.statusBar().showMessage("Brush used : " + brush)

    def file_exit(self):
        msgBox = QtWidgets.QMessageBox(self)
        msgBox.setWindowTitle("Exit")
        msgBox.setText("Are you sure you want to exit?")
        msgBox.setInformativeText("Your file will may be not save !")
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ignore
                                  | QtWidgets.QMessageBox.Save
                                  | QtWidgets.QMessageBox.Cancel)
        msgBox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
        msgBox.exec_()
        buttonI = msgBox.button(QtWidgets.QMessageBox.Ignore)
        buttonS = msgBox.button(QtWidgets.QMessageBox.Save)
        buttonC = msgBox.button(QtWidgets.QMessageBox.Cancel)
        if msgBox.clickedButton() == msgBox.button(
                QtWidgets.QMessageBox.Ignore):
            #Ignore was clicked
            exit(0)
        elif msgBox.clickedButton() == msgBox.button(
                QtWidgets.QMessageBox.Cancel):
            #Cancel was clicked
            msgBox.close()
        elif msgBox.clickedButton() == msgBox.button(
                QtWidgets.QMessageBox.Save):
            #Save was clicked
            self.file_save()
            exit(0)

    def file_new(self):
        msgBox = QtWidgets.QMessageBox(self)
        msgBox.setWindowTitle("New File")
        msgBox.setText("Are you sure you want create a new file ?")
        msgBox.setInformativeText(
            "This action will may not save your current file!")
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Yes
                                  | QtWidgets.QMessageBox.Save
                                  | QtWidgets.QMessageBox.Cancel)
        msgBox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
        msgBox.button(QtWidgets.QMessageBox.Yes).setText("New Without Saving")
        msgBox.button(QtWidgets.QMessageBox.Save).setText("Save and New")
        msgBox.exec_()
        if msgBox.clickedButton() == msgBox.button(QtWidgets.QMessageBox.Yes):
            #Ignore was clicked
            self.scene.clear()
            self.statusBar().showMessage("Scene cleared")
        elif msgBox.clickedButton() == msgBox.button(
                QtWidgets.QMessageBox.Cancel):
            #Cancel was clicked
            msgBox.close()
        elif msgBox.clickedButton() == msgBox.button(
                QtWidgets.QMessageBox.Save):
            #Save was clicked
            self.file_save()
            self.scene.clear()
            self.statusBar().showMessage("Scene cleared")
            self.file = None

    def file_open(self):
        filename = QtWidgets.QFileDialog.getOpenFileName(
            self, 'Open File', os.getcwd())
        # print(filename[0])
        if len(filename[0]) > 0:
            fileopen = QtCore.QFile(filename[0])
            if fileopen.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
                data = json.loads(fileopen.readAll().data().decode('utf-8'))
                print(data)
                self.scene.clear()
                self.scene.data_to_items(data)
                self.file = fileopen
                print("File opened !")
                self.statusBar().showMessage("File Opened")
            else:
                print("Can't open this file !")
                self.statusBar().showMessage("Can't open this file !")

            fileopen.close()

    def file_save(self):
        if (self.file):
            if self.file.open(QtCore.QIODevice.WriteOnly):
                data = self.scene.items_to_data()
                print(data)
                self.file.write(json.dumps(data).encode("utf-8"))
                self.file.close()
                print("File saved !")
                self.statusBar().showMessage("File Saved")
            else:
                print("Can't save this file !")
                self.statusBar().showMessage("Can't save this file !")
        else:
            filename = QtWidgets.QFileDialog.getSaveFileName(
                self, 'Save File', os.getcwd())
            if len(filename[0]) > 0:
                if (filename[0][len(filename[0]) - 5:] == ".json"):
                    file = filename[0]
                else:
                    file = filename[0] + ".json"
                filesave = QtCore.QFile(file)
                if filesave.open(QtCore.QIODevice.WriteOnly):
                    data = self.scene.items_to_data()
                    print(data)
                    filesave.write(json.dumps(data).encode("utf-8"))
                    filesave.close()
                    self.file = filesave
                    print("File saved !")
                    self.statusBar().showMessage("File Saved")
                else:
                    print("Can't save this file !")
                    self.statusBar().showMessage("Can't save this file !")

    def file_save_as(self):
        filename = QtWidgets.QFileDialog.getSaveFileName(
            self, 'Save File As', os.getcwd())
        # print(filename[0][len(filename[0])-5:])
        if len(filename[0]) > 0:
            if (filename[0][len(filename[0]) - 5:] == ".json"):
                file = filename[0]
            else:
                file = filename[0] + ".json"
            filesave = QtCore.QFile(file)
            if filesave.open(QtCore.QIODevice.WriteOnly):
                data = self.scene.items_to_data()
                print(data)
                filesave.write(json.dumps(data).encode("utf-8"))
                filesave.close()
                self.file = filesave
                print("File saved !")
                self.statusBar().showMessage("File Saved")
            else:
                print("Can't save this file !")
                self.statusBar().showMessage("Can't save this file !")

    def pen_color_selection(self):
        color = QtWidgets.QColorDialog.getColor(QtCore.Qt.yellow, self)
        if color.isValid():
            print("Color Chosen : ", color.name())
            self.scene.set_pen_color(color)
        else:
            print("color is not a valid one !")

    def brush_color_selection(self):
        color = QtWidgets.QColorDialog.getColor(QtCore.Qt.yellow, self)
        if color.isValid():
            self.scene.set_brush_color(color)
            print("Color Chosen : ", color.name())
        else:
            print("color is not a valid one !")

    def font_selection(self):
        (font, ok) = QtWidgets.QFontDialog.getFont(QtGui.QFont("serif", 11),
                                                   self)
        print(ok)
        if ok:
            print("Font Chosen : ")
            self.scene.set_font(font)
        else:
            print("Serif 11 is chosen by default")

    def help_about_us(self):
        QtWidgets.QMessageBox.information(
            self, self.tr("About Us"),
            self.tr("Corentin Régné et Lénaël Jagline\n copyright ENIB 2020"))

    def help_about_qt(self):
        QtWidgets.QMessageBox.information(
            self, self.tr("About Qt"),
            self.tr("Qt is a visual module for C++ and Python"))

    def help_about_app(self):
        text = open('README.txt').read()
        QtWidgets.QMessageBox.information(self,
                                          self.tr("About the Application"),
                                          self.tr(text))

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()
Exemplo n.º 35
0
cam = Camera(0., np.array([0.,0.,-300.]), np.array([0.,0.,-500.]),
             pixel_dims=(nx,ny),pixel_len=0.8)
cam.create_rays()
rays = cam.get_rays()

# create a bunch of spheres and add to scene
nsphere = 300
rad = 10.
xrnd = 1200.*(np.random.rand(nsphere)-0.5)
yrnd = 1200.*(np.random.rand(nsphere)-0.5)
zrnd = 1000.*np.random.rand(nsphere)+50.
spheres = []

for i in range(nsphere):
    spheres.append(Sphere(np.array([xrnd[i],yrnd[i],zrnd[i]]), 10.))
scene = Scene(spheres)

# render initial scene
px, py,_ = cam.get_pixel_grid()
cam.set_scene(scene)
shade = cam.render()
plt.imshow(shade[:,::-1].T, cmap='Greys_r')
plt.savefig(f'shade_motion_000.png', dpi=375./(2400./nx))
plt.close()

# render images in time as particles move
ntime = 50
dt = 0.004
mot_vec = np.zeros([3,nsphere])
mot_vec[1,:] = -1.2e3
mot_vec[0,:] = -0.3e3
Exemplo n.º 36
0
import sys
sys.path = ['', 'pyglet-1.1.4'] + sys.path

import pyglet

window = pyglet.window.Window(width=800,
                              height=600,
                              caption="You are the Hero")

from pyglet.window import key

from scene import Scene
import script

scene = Scene(window.width, window.height)
script.start(scene)

keymap = {
    key.E: "up",
    key.S: "left",
    key.D: "down",
    key.F: "right",
    key.UP: "up",
    key.DOWN: "down",
    key.LEFT: "left",
    key.RIGHT: "right",
    key.SPACE: "blink",
}

pyglet.gl.glClearColor(255, 255, 255, 255)
Exemplo n.º 37
0
def main():
    """Main function, it implements the application loop"""
    # Initialize pygame, with the default parameters
    pygame.init()

    # Define the size/resolution of our window
    res_x = 1280
    res_y = 720

    # Create a window and a display surface
    screen = pygame.display.set_mode((res_x, res_y))

    # Create a scene
    scene = Scene("TestScene")
    scene.camera = Camera(False, res_x, res_y)

    # Moves the camera back 2 units
    scene.camera.position -= Vector3(0, 0, 4)
    scene.camera.rotation = Quaternion.AngleAxis(Vector3(1, 0, 0),
                                                 math.radians(-15))

    # Creates the terrain meshes and materials
    terrain_meshes, terrain_materials = create_terrain()

    # Create container object for all the terrain sub-objects
    master_object = Object3d("TerrainObject")
    master_object.position = Vector3(0, -1, 0)
    scene.add_object(master_object)

    # Create the terrain objects and place it in a scene, at position (0,0,0)
    for _, (mesh, material) in enumerate(zip(terrain_meshes,
                                             terrain_materials)):
        obj = Object3d("TerrainObject")
        obj.scale = Vector3(1, 1, 1)
        obj.position = Vector3(0, 0, 0)
        obj.mesh = mesh
        obj.material = material
        master_object.add_child(obj)

    # Specify the rotation of the object. It will rotate 15 degrees around the axis given,
    # every second
    angle = 15
    axis = Vector3(0, 1, 0)
    axis.normalize()

    # Timer
    delta_time = 0
    prev_time = time.time()

    # Show mouse cursor
    pygame.mouse.set_visible(True)
    # Don't lock the mouse cursor to the game window
    pygame.event.set_grab(False)

    # Game loop, runs forever
    while True:
        # Process OS events
        for event in pygame.event.get():
            # Checks if the user closed the window
            if event.type == pygame.QUIT:
                # Exits the application immediately
                return
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return

        # Clears the screen with a very dark blue (0, 0, 20)
        screen.fill((0, 0, 0))

        # Rotates the object, considering the time passed (not linked to frame rate)
        q = Quaternion.AngleAxis(axis, math.radians(angle) * delta_time)
        master_object.rotation = q * master_object.rotation

        #Commented code serves to make benchmarks
        Mesh.stat_vertex_count = 0
        Mesh.stat_transform_time = 0
        Mesh.stat_render_time = 0

        scene.render(screen)

        #Writes the benchmarks results
        print("Frame stats:")
        print(f"Vertex count = {Mesh.stat_vertex_count}")
        print(f"Transform time = {Mesh.stat_transform_time}s")
        print(f"Render time = {Mesh.stat_render_time}s")

        # Swaps the back and front buffer, effectively displaying what we rendered
        pygame.display.flip()

        # Updates the timer, so we we know how long has it been since the last frame
        delta_time = time.time() - prev_time
        prev_time = time.time()

        print(f"Frame time = {delta_time}s")
Exemplo n.º 38
0
from material import Material
from shader_lambertiantint import LambertianTintShader

from meanfilter import MeanFilter
from kernelfilter import KernelFilter

import numpy as np

try:
    range = xrange
except NameError:
    pass

total_sphere = random.randint(1,15)

scene_test = Scene()
scene_test.background_color = Color.random()

light = Light(Color(1.0, 1.0, 1.0, 1.0), 1.0)
light.transform.position = Vector3(1.0, 2.0, 1.0)
scene_test.set_light(light)

lambertianTintMaterial = Material()
lambertianTintMaterial.albedo = Color(1.0, 1.0, 1.0, 1.0)
lambertianTintMaterial.shader = LambertianTintShader()

# s1 = Sphere(0.6)
# s1.transform.position = Vector3(0, 2.4, 4)
# s1.material = lambertianTintMaterial
# scene_test.add_objects(s1)
Exemplo n.º 39
0
def interpolate(q1, q2, ndist, graph, steps):
    """
        Returns an interpolated local path between two given configurations.
        It can be used to determine whether an edge between vertices is collision-free.
    """
    x1, y1 = q1.q
    x2, y2 = q2.q
    n = steps

    for i in range(n):
        j = n - i
        x = (i*x2 + j * x1)/(i+j)
        y = (i * y2 + j * y1) / (i + j)
        coll = collision((x, y))
        if coll:
            break
    if not coll:
        graph.addEdge(q1, q2, ndist)

    return None


if __name__ == "__main__":
    from scene import Scene
    import tkinter as tk

    win = tk.Tk()
    Scene('prm_obstacles.csv', disk_robot, (build_roadmap, find_path), win)
    win.mainloop()
Exemplo n.º 40
0
 def update_frame(self, *args, **kwargs):
     for val in self.ranging_values:
         self.remove(val.mobject)
         val.update_mobject()
         self.add(val.mobject)
     return Scene.update_frame(self, *args, **kwargs)
Exemplo n.º 41
0
    return ship, sprites


def start():
    return time.time()


def end(var):
    return (time.time() - var) * 1000


if __name__ == '__main__':

    # Create scene and input
    scene = Scene()
    st.CURRENT_SCENE = scene
    ii = Input()
    st.CURRENT_INPUT = ii

    # Create crosshair
    crosshair = Sprite()
    crosshair.set_image(load_image("crosshair.png"))

    text_sprite = Sprite()
    text_sprite.ui = True
    text1_sprite = Sprite()
    text1_sprite.ui = True
    # Initialize everything and add to scene
    ship, allobjects = initialize()
    scene.objects.add(allobjects)
Exemplo n.º 42
0
class Renderer:
    def __init__(self, config):
        self.config = config

        self.prepare_log_and_dir()
        self.prepare_basic_settings()
        self.load_scene()
        self.prepare_sampler()

    def prepare_log_and_dir(self):
        self.log_dir = Path(self.config.output_log_dir).expanduser().joinpath(
            '{}_{}_{}'.format(self.config.problem, self.config.start,
                              self.config.start + self.config.n_sample - 1))
        self.logger = utils.get_logger(__name__,
                                       log_dir=self.log_dir,
                                       use_tqdm=True)

        self.output_dir = Path(
            self.config.output_data_dir).expanduser().joinpath(
                self.config.problem)
        self.image_dir = self.output_dir.joinpath('image')
        self.blend_dir = self.output_dir.joinpath('blend')
        self.info_dir = self.output_dir.joinpath('info')
        self.seg_dir = self.output_dir.joinpath('seg')

        directories = [self.image_dir, self.seg_dir, self.info_dir]

        if self.config.output_blend:
            directories.append(self.blend_dir)
        if self.config.output_log:
            directories.append(self.log_dir)
        for directory in directories:
            directory.mkdir(exist_ok=True, parents=True)

    def prepare_basic_settings(self):
        self.recorder = Recorder()

        self.global_seed = utils.hash_seed(self.config.problem,
                                           self.config.seed)

        self.start = config.start
        self.end = config.start + config.n_sample
        self.current_idx = self.start
        self.current_stage = 0

        self.scene_reload_time = 10

    def load_scene(self):
        self.logger.info('Loading scene into blender...')
        self.scene = Scene(self.config.base_scene_file, self.config.shape_dir,
                           self.config.material_dir,
                           self.config.properties_json)
        self.scene.set_render_args(
            resolution_x=self.config.width,
            resolution_y=self.config.height,
            tile_x=self.config.render_tile_size,
            tile_y=self.config.render_tile_size,
            gpu=self.config.gpu,
            render_num_samples=self.config.render_num_samples,
            transparent_min_bounces=self.config.transparent_min_bounces,
            transparent_max_bounces=self.config.transparent_max_bounces,
            min_bounces=self.config.min_bounces,
            max_bounces=self.config.max_bounces)

        self.valid_cameras = self.scene.cameras.keys()
        self.initial_cameras = list(
            set(self.valid_cameras) & set(self.config.initial_cameras))
        self.final_cameras = list(
            set(self.valid_cameras) & set(self.config.final_cameras))
        self.logger.info('Available cameras for initial state: {}'.format(
            self.initial_cameras))
        self.logger.info('Available cameras for final state: {}'.format(
            self.final_cameras))

    def prepare_sampler(self):
        valid_pairs = [
            pair for pair in self.scene.option.pairs
            if pair.startswith(tuple(self.config.valid_attr))
        ]
        assert config.min_init_vis <= config.max_init_vis <= config.total_obj
        self.sample_manager = SampleManager(
            valid_init_vis=range(config.min_init_vis, config.max_init_vis + 1),
            total_obj=config.total_obj,
            valid_steps=range(config.min_trans, config.max_trans + 1),
            valid_pairs=valid_pairs,
            valid_move_type=['inner', 'out', 'in'],
            pair_split=self.scene.option.SPLIT)

    @property
    def str_stage(self):
        if self.current_stage == 0:
            return 'initial'
        elif self.current_stage == self.num_step:
            return 'final'
        else:
            return '{:02d}'.format(self.current_stage)

    @property
    def images_path(self):
        cameras = self.initial_cameras \
            if self.current_stage == 0 else self.final_cameras
        return {
            cam: os.path.join(
                str(self.image_dir),
                '{}_{}_img_{:06d}-{}.{}.png'.format(self.config.dataset_prefix,
                                                    self.config.problem,
                                                    self.current_idx,
                                                    self.str_stage, cam))
            for cam in cameras
        }

    @property
    def segs_path(self):
        return {
            cam: os.path.join(
                str(self.seg_dir),
                '{}_{}_seg_{:06d}-{}.{}.png'.format(self.config.dataset_prefix,
                                                    self.config.problem,
                                                    self.current_idx,
                                                    self.str_stage, cam))
            for cam in self.final_cameras
        }

    @property
    def blend_path(self):
        return os.path.join(
            str(self.blend_dir),
            '{}_{}_{:06d}-{}.blend'.format(self.config.dataset_prefix,
                                           self.config.problem,
                                           self.current_idx, self.str_stage))

    @property
    def json_path(self):
        return os.path.join(
            str(self.info_dir),
            '{}_{}_{:06d}.json'.format(self.config.dataset_prefix,
                                       self.config.problem, self.current_idx))

    @property
    def prefix(self):
        return '#{}-{} '.format(self.current_idx, self.current_stage)

    def info(self, message):
        self.logger.info(self.prefix + message)

    def warning(self, message):
        self.logger.warning(self.prefix + message)

    def error(self, message):
        self.logger.error(self.prefix + message, exc_info=True)

    def exclude_output_dir(self, path_dict):
        return {key: os.path.basename(path) for key, path in path_dict.items()}

    def set_seed(self):
        seed = [self.global_seed, self.current_idx]
        random.seed(str(seed))
        np.random.seed(seed)

    def run(self, replace_start=-1):
        for self.current_idx in tqdm.trange(self.start, self.end, ncols=80):
            # Reload to avoiding the unknown issue of slowing down.
            if self.current_idx % self.scene_reload_time == 0:
                self.load_scene()

            # Skip existing samples.
            if os.path.isfile(self.json_path):
                info = self.sample_manager.record_json(self.json_path)
                if self.current_idx >= replace_start:
                    self.render_from_json(info)
                continue

            self.logger.info('---')
            self.set_seed()
            while True:
                try:
                    if self.build_sample():
                        self.sample_manager.sample_success()
                        self.summary()
                        break
                    else:
                        self.sample_manager.sample_fail()
                        self.clear_history()
                except KeyboardInterrupt:
                    self.warning('Keyboard Interrupted.')
                    sys.exit(1)
                except Exception as e:
                    self.error(str(e))

    """
    Rule A: no overlapping.
    Rule B: transformation must be observable
    1. occluded objects can not be transformmed (visible in initial states)
    2. transformed objects can not be moved out (visible in final states)
    3. transformed objects can not be occluded (visible in final states)
    """

    def build_sample(self):
        # Sample the initial state.
        self.current_stage = 0
        if not self.sample_init_state():
            return False
        self.record()

        # Decide the number of steps.
        self.num_step = self.sample_manager.random_step()
        self.logger.info('Number of atomic transformations: {}.'.format(
            self.num_step))

        # Apply randomly sampled atomic transformations one by one.
        for _ in range(self.num_step):
            self.current_stage += 1
            while True:
                pair = self.sample_manager.random_pair()
                if pair is None:
                    return False
                response = self.try_pair(pair)
                if response is None:
                    self.warning(
                        '[Fair] ({}/{}) {} -> no feasible object.'.format(
                            len(self.sample_manager.tried_pairs),
                            self.sample_manager.top_pair, pair))
                    self.sample_manager.stage_fail()
                else:
                    self.record(trans_response=response)
                    self.sample_manager.stage_success()
                    break

        # Show the sequence of transformation.
        for i, trans_info in enumerate(self.recorder.info['transformations']):
            self.logger.info('[{}] {} -> {}{}'.format(
                i, trans_info['pair'], trans_info['obj_idx'],
                ' ({})'.format(trans_info['type'])
                if trans_info['attr'] == 'position' else ''))

        # Save the information about the sample into a json file.
        self.info('Saveing info...')
        if not self.recorder.save(self.json_path, self.config.json_indent):
            return False

        with open(self.json_path, 'r') as f:
            info = json.load(f)
        self.render_from_json(info)

        return True

    def render_from_json(self, info):
        cameras = info['cameras']
        lamps = info['lamps']
        self.num_step = len(info['states']) - 1
        render_stages = list(range(self.num_step + 1))
        if not self.config.render_intermediate:
            render_stages = [render_stages[0], render_stages[-1]]
        for s in render_stages:
            self.current_stage = s
            for _, path in self.images_path.items():
                if not os.path.isfile(path):
                    objects = info['states'][s]['objects']
                    self.scene.set_scene(objects, cameras, lamps)
                    if not self.render_main():
                        return False
                    break
        return True

    def sample_init_state(self):
        self.info('Start to building initial state.')

        # Reset & initialize blender environment.
        self.info('Reset environment.')
        self.scene.reset()
        self.scene.perturb_camera(self.config.camera_jitter)
        self.scene.perturb_lamp(self.config.lamp_jitter)

        # Reset recorder.
        self.info('Reset recorder')
        self.recorder.init(self.scene, self.current_idx)

        # Decide the visibilities of objects.
        self.num_init_visible = self.sample_manager.random_init()
        visible_choices = [True] * self.num_init_visible \
            + [False] * (self.config.total_obj - self.num_init_visible)
        random.shuffle(visible_choices)

        # Randomly create and place objects.
        self.info('Creating {} random objects, {} visible...'.format(
            self.config.max_init_vis, self.num_init_visible))
        for i, visible in enumerate(visible_choices):
            obj = self.scene.create_random_object(visible=visible)
            if obj is None:
                self.warning('{} No enough space for {} objects.'.format(
                    i, 'visible' if visible else 'invisible'))
                self.warning('Failed to build initial state. Retry...')
                return False
            else:
                self.info('{} ({:^9s}) Put a {:6s} {:6s} {:6s} {:8s}'
                          ' at ({:3d}, {:3d})'.format(
                              i, 'visible' if visible else 'invisible',
                              obj['size'], obj['color'], obj['material'],
                              obj['shape'], *obj['position']))

        self.info('* Successfully build initial state.')
        return True

    def try_pair(self, pair):
        # Try sampled atomic transformations on objects.
        while True:
            move_type = self.sample_manager.random_move_type() \
                if pair.startswith('position') else None
            if pair.startswith('position') and move_type is None:
                return None
            objs = self.get_valid_objs(pair, move_type=move_type)
            self.info('Valid objects for {}: {}'.format(pair, objs))
            while len(objs) > 0:
                obj_idx = self.sample_manager.random_obj(valid_objs=objs)
                objs.remove(obj_idx)
                is_success, response = self.transform(
                    self.scene.objects[obj_idx], pair, move_type)
                if is_success:
                    return response
            if not pair.startswith('position'):
                return None
            else:
                self.warning('[Fail] ({}/{}) move {}'.format(
                    len(self.sample_manager.tried_move_type),
                    self.sample_manager.top_move_type, move_type))

    def get_valid_objs(self, pair, move_type=None):
        # Rule 1. Occluded objects can not be transformmed.
        if move_type == 'in':
            choices = self.scene.invisible_objects
        else:
            choices = self.get_non_occluded_objs()

        choices = [self.scene.get_index(obj) for obj in choices]

        return choices

    def transform(self, obj, pair, move_type=None):
        trans = [obj, *pair.split(self.scene.option.SPLIT)]
        attr = trans.pop(1)

        trans_info = {
            'pair': pair,
            'obj_name': self.scene.get_name(obj),
            'obj_idx': self.scene.get_index(obj)
        }
        trans_func = getattr(self, 't_{}'.format(attr))
        args = trans + [move_type] if move_type else trans
        self.info('{} <- {}'.format(trans_info['obj_name'], pair))
        is_success, response = trans_func(*args)

        response.update(trans_info)

        return is_success, response

    def t_position(self, obj, direction, step, move_type):
        step = int(step)
        response = {
            'attr': 'position',
            'old': self.scene.get_position(obj),
            'new': '',
            'target': (direction, step),
            'type': '',
            'options': [],
        }

        x, y = response['old']
        dx, dy = self.scene.option.get_delta_position(direction, step)
        new_x = x + dx
        new_y = y + dy

        response['new'] = (new_x, new_y)

        if not self.scene.option.is_position_valid(new_x, new_y):
            self.warning('[Fail] position ({}, {}) is invalid.'.format(
                new_x, new_y))
            return False, response

        vis_old = self.scene.option.is_visible(x, y)
        vis_new = self.scene.option.is_visible(new_x, new_y)

        if vis_old and vis_new:
            response['type'] = 'inner'
        elif vis_old and (not vis_new):
            response['type'] = 'out'
        elif (not vis_old) and vis_new:
            response['type'] = 'in'
        else:
            self.warning('[Fail] move object inside invisible area.')
            return False, response

        if response['type'] != move_type:
            self.warning('[Fail] move type ({} vs. {}) not match.'.format(
                response['type'], move_type))
            return False, response

        # Rule 2. Transformed objects can not be moved out.
        if response['type'] == 'out' and self.was_transformed(obj):
            self.warning('[Fail] Modified objects can not be moved out.')
            return False, response

        self.scene.set_position(obj, new_x, new_y)

        if self.scene.is_overlapped(obj):
            self.warning('[Fail] Overlap.')
        # Rule 3. Transformed objects can not be occluded.
        elif self.cause_occlusion(obj):
            self.warning('[Fail] Cause occlusion.')
        else:
            if response['type'] == 'out':
                response['options'].extend(
                    self.scene.option.get_move_options(x, y)['invisible'])
            else:
                response['options'].append((direction, step))
            return True, response

        # Revert.
        self.scene.set_position(obj, x, y)
        return False, response

    def t_shape(self, obj, new_shape):
        response = {
            'attr': 'shape',
            'old': self.scene.get_shape(obj),
            'new': None,
            'target': None,
        }
        old_shape = response['old']
        if new_shape == old_shape:
            self.warning('[Fail] no change.')
            return False, response
        obj = self.scene.set_shape(obj, new_shape)
        response['new'] = response['target'] = new_shape

        return True, response

    def t_size(self, obj, new_size):
        response = {
            'attr': 'size',
            'old': self.scene.get_size(obj),
            'new': new_size,
            'target': new_size,
        }
        old_size = response['old']
        if new_size == old_size:
            self.warning('[Fail] no change.')
            return False, response

        self.scene.set_size(obj, new_size)

        if self.scene.option.is_bigger(new_size, old_size) and \
                self.scene.is_overlapped(obj):
            self.warning('[Fail] Overlap.')
        # Rule 3. transformed objects can not be occluded (visible in final states)
        elif self.cause_occlusion(obj):
            self.warning('[Fail] Cause occlusion.')
        else:
            return True, response

        self.scene.set_size(obj, old_size)
        return False, response

    def t_material(self, obj, new_material):
        response = {
            'attr': 'material',
            'old': self.scene.get_material(obj),
            'new': new_material,
            'target': new_material,
        }
        old_material = response['old']
        if new_material == old_material:
            self.warning('[Fail] no change.')
            return False, response

        self.scene.set_material(obj, new_material)
        return True, response

    def t_color(self, obj, new_color):
        response = {
            'attr': 'color',
            'old': self.scene.get_color(obj),
            'new': new_color,
            'target': new_color,
        }
        old_color = response['old']
        if new_color == old_color:
            self.warning('[Fail] no change.')
            return False, response

        self.scene.set_color(obj, new_color)
        return True, response

    def render_main(self):
        if not self.config.no_render:
            self.info('[Render] main ({})...'.format(self.current_stage))
            for key, image_path in self.images_path.items():
                if not os.path.isfile(image_path):
                    time_used = self.scene.render(image_path,
                                                  self.scene.cameras[key],
                                                  config.width, config.height)
                    self.info('- {}: {}'.format(key,
                                                utils.time2str(time_used)))
                    if not os.path.isfile(image_path):
                        return False
        return True

    def render_seg(self):
        self.info('[Render] seg ({})...'.format(self.current_stage))
        for key, seg_path in self.segs_path.items():
            time_seg_used = self.scene.render_shadeless(
                seg_path, self.scene.cameras[key], config.seg_width,
                config.seg_height)
            self.info('- {}: {}'.format(key, utils.time2str(time_seg_used)))
            if not os.path.isfile(seg_path):
                return False
        return True

    def record(self, trans_response=None):
        status = self.get_objs_status()

        self.recorder.record_scene(self.scene, self.current_stage,
                                   self.exclude_output_dir(self.images_path),
                                   self.exclude_output_dir(self.segs_path),
                                   status['n_pixels'], status['status'])
        if trans_response is not None:
            self.recorder.record_trans(self.current_stage - 1,
                                       self.current_stage, trans_response)

        if self.config.output_blend:
            self.info('[Save] Blender file.')
            self.scene.save(self.blend_path)

    def get_objs_status(self, stage=None):
        if stage is None:
            stage = self.current_stage
        states = self.recorder.info['states']
        assert -len(states) <= stage <= len(states), (
            'stage {} is out of range'.format(stage))
        if -len(states) <= stage < len(states):
            return {
                'status': states[stage]['status'],
                'n_pixels': states[stage]['n_pixels']
            }
        else:
            assert self.render_seg(), '[Error] render seg failed.'
            n_pixels = {}
            cams = list(set(self.initial_cameras) | set(self.final_cameras))
            for cam in cams:
                image_path = self.segs_path[cam]
                n_pixels[cam] = self.count_pixels(image_path)
            status = self.pixels2status(n_pixels)
            return {'status': status, 'n_pixels': n_pixels}

    def count_pixels(self, seg_path):
        assert os.path.isfile(seg_path), '[Error] {} doesn\'t exist.'.format(
            seg_path)
        pixels = {}
        colors = utils.count_color(seg_path)
        for n, color in sorted(colors):
            obj = self.scene.option.get_seg_object(color)
            if obj is not None:
                pixels[obj] = n
        return pixels

    def pixels2status(self, n_pixels):
        status = defaultdict(dict)
        min_pixels = self.config.occlusion_threshold
        for cam, val in n_pixels.items():
            for obj in self.scene.objects:
                if obj in self.scene.invisible_objects:
                    status[cam][obj.name] = 'invisible'
                elif obj.name not in val or val[obj.name] < min_pixels:
                    status[cam][obj.name] = 'occluded'
                else:
                    status[cam][obj.name] = 'visible'
        return status

    def cause_occlusion(self, obj):
        status = self.get_objs_status(stage=self.current_stage)['status']
        for x in self.scene.objects:
            if x == obj or self.was_transformed(x):
                x_name = self.scene.get_name(x)
                for cam in self.final_cameras:
                    if status[cam][x_name] == 'occluded':
                        return self.scene.get_index(x)
        return None

    def get_non_occluded_objs(self):
        status = self.get_objs_status(stage=0)['status']
        objects = self.scene.visible_objects.copy()
        for cam in self.initial_cameras:
            for obj_name, state in status[cam].items():
                obj = self.scene.b_objects[obj_name]
                if state == 'occluded' and obj in objects:
                    objects.remove(obj)
        return objects

    def was_transformed(self, obj, attr=None):
        for trans_info in self.recorder.info['transformations']:
            if obj.name == trans_info['obj_name'] and (
                    attr is None or trans_info['attr'] == attr):
                return True
        return False

    def clear_history(self):
        self.logger.info('Removing files after failed...')
        for scene in self.recorder.info['states']:
            for image in scene['images'].values():
                img_path = self.image_dir / image
                if img_path.exists():
                    img_path.unlink()
            for seg in scene['segs'].values():
                seg_path = self.seg_dir / seg
                if seg_path.exists():
                    seg_path.unlink()

    def summary(self):
        self.logger.info('---')
        self.logger.info('Data dir: {}'.format(self.output_dir.resolve()))
        if self.config.output_log:
            self.logger.info('Log dir: {}'.format(self.log_dir.resolve()))

        self.logger.info('---')
        state = self.sample_manager.state()
        self.logger.info('Progress: {} (load: {})'.format(
            state['sample_success'] + state['sample_load'],
            state['sample_load']))
        self.logger.info('Sample success: {} ({:.4f})'.format(
            state['sample_success'], state['rate_sample_success']))
        self.logger.info('Stage success: {} ({:.4f})'.format(
            state['stage_success'], state['rate_stage_success']))
        self.logger.info('Total time: {}'.format(utils.time2str(
            state['time'])))
        self.logger.info('Average sample time: {}'.format(
            utils.time2str(state['time_avg_sample'])))
        self.logger.info('Average stage time: {}'.format(
            utils.time2str(state['time_avg_stage'])))

        self.logger.info('---')
        self.logger.info('Initial Visible Object:')
        for init_vis, num in sorted(self.sample_manager.n_init_vis.items()):
            self.logger.info('- {}: {}'.format(init_vis, num))

        self.logger.info('---')
        self.logger.info('Steps:')
        for key, num in sorted(self.sample_manager.n_step.items()):
            self.logger.info('- {}: {}'.format(key, num))

        self.logger.info('---')
        self.logger.info('Object:')
        for key, num in sorted(self.sample_manager.n_obj.items()):
            self.logger.info('- {}: {}'.format(key, num))

        self.logger.info('---')
        self.logger.info('Pair:')
        for key, num in sorted(self.sample_manager.n_pair['gram_1'].items()):
            self.logger.info('- {}: {}'.format(key, num))

        self.logger.info('---')
        self.logger.info('Move Type:')
        for key, num in sorted(self.sample_manager.n_move_type.items()):
            self.logger.info('- {}: {}'.format(key, num))

        self.logger.info('---')
        self.logger.info('Balance State')
        for key, state in sorted(self.sample_manager.balance_state.items()):
            self.logger.info('# {}'.format(key))
            for k, v in sorted(state.items()):
                self.logger.info('- {}: {}'.format(k, v))
Exemplo n.º 43
0
 def non_blink_dither(self, time=1):
     Scene.dither(self, time)
     return self
Exemplo n.º 44
0
import process_data
from scene import Scene
from sys import argv
if len(argv) > 1:
    folder = argv[1]
else:
    folder = '../annotations/coupa/video2/'
if len(argv) > 2:
    fname = argv[2]
else:
    fname = "test"
print "Initializing a scene from " + folder
BB_ts_list, width, height = process_data.get_BB_ts_list(folder,label="Biker")
kf = KFold(n_splits = 10)
train_set, test_set = train_test_split( BB_ts_list, random_state = 0 )
test_scene = Scene( train_set, width, height )
#print "Display clusters"
#for k in range( test_scene.num_nl_classes ):
#    from visualization_routines import visualize_cluster
#    visualize_cluster( test_scene, k )

print "P(k) = "
print test_scene.P_of_c

print "\sum_k P(k) = {}".format( test_scene.P_of_c.sum())
print "Pickling scene and test set."
with open("{}_scene.pkl".format(fname), "w") as f:
    pickle.dump( test_scene, f)
    print "Pickled scene"

with open("{}_set.pkl".format(fname), "w") as f:
Exemplo n.º 45
0
 def handlePlayerJoined(message):
     id = message['user_id']
     Scene.Get().AddPlayer(id)
Exemplo n.º 46
0
if (len(sys.argv) > 2):
    print("input only one .obj file to command line")
    sys.exit()

filename = sys.argv[1]  #get the filename from terminal

if filename.split(".")[
        1] != "obj":  # if file type is not .obj print error message and exit
    print("please input .obj file type to command line")
    sys.exit()

my_obj = DividableObject(
    filename)  #instantiate obj with the filename from terminal

grid = Grid()
scene = Scene()
scene.addObject(my_obj)
scene.addObject(grid)

camera = Camera(Vec3d(0, 0, 8), Vec3d(0, 0, -1))

# Some api in the chain is translating the keystrokes to this octal string
# so instead of saying: ESCAPE = 27, we use the following.
ESCAPE = b'\033'

# Number of the glut window.
window = 0


# A general OpenGL initialization function.  Sets all of the initial parameters.
def InitGL(Width,
Exemplo n.º 47
0
 def create_scene(self):
     view = QtWidgets.QGraphicsView()
     self.scene = Scene(self)
     view.setScene(self.scene)
     self.setCentralWidget(view)
Exemplo n.º 48
0
 def get_frame(self):
     frame = Scene.get_frame(self)
     if self.zoom_activated:
         (up, left), (down, right) = self.zoomed_canvas_pixel_indices
         frame[left:right, up:down, :] = self.zoomed_camera.get_image()
     return frame
Exemplo n.º 49
0
import sys
import pygame
from pygame.locals import *
sys.path.insert(0, "../scene")
from scene import Scene

pygame.init()
pantalla = pygame.display.set_mode((800, 600))
tile = pygame.image.load(
    "/home/david/Documentos/cuarto/CIIE/videojoco2d/res/tiles/grass.png")
tile2 = pygame.image.load(
    "/home/david/Documentos/cuarto/CIIE/videojoco2d/res/tiles/desert.png")
map = [[tile, tile2], [tile2, tile]]
level = Scene("test", 2, 2, map, 16)
clock = pygame.time.Clock()

while True:
    clock.tick(60)
    for evento in pygame.event.get():
        if evento.type == KEYDOWN and evento.key == K_ESCAPE:
            pygame.quit()
            sys.exit()
        level.draw(pantalla)
        pygame.display.update()
Exemplo n.º 50
0
 def update_frame(self, *args, **kwargs):
     Scene.update_frame(self, *args, **kwargs)
     if self.zoom_activated:
         self.zoomed_camera.reset()
         self.zoomed_camera.capture_mobjects(self.mobjects)
Exemplo n.º 51
0
class Viewer(object):
    def __init__(self):
        """Initialize the viewer"""
        #初始化接口,创建窗口并注册渲染函数
        self.init_interface()
        #初始化opengl的配置
        self.init_opengl()
        #初始化3D场景
        self.init_scene()
        #初始化交互操作相关的代码
        self.init_interaction()
        init_primitives()

    def init_interface(self):
        """ 初始化窗口并注册渲染函数 """
        glutInit()
        glutInitWindowSize(640,480)
        glutCreateWindow("3D Modeller")
        glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
        #注册窗口渲染函数
        glutDisplayFunc(self.render)

    def init_opengl(self):
        """ 初始化opengl的配置 """
        #模型视图矩阵
        self.inverseModelView = numpy.identity(4)
        #模型视图矩阵的逆矩阵
        self.modelView = numpy.identity(4)

        #开启剔除操作效果
        glEnable(GL_CULL_FACE)
        #取消对多边形背面进行渲染的计算(看不到的部分不渲染)
        glCullFace(GL_BACK)
        #开启深度测试
        glEnable(GL_DEPTH_TEST)
        #测试是否被遮挡,被遮挡的物体不予渲染
        glDepthFunc(GL_LESS)
        #启用0号光源
        glEnable(GL_LIGHT0)
        #设置光源的位置
        glLightfv(GL_LIGHT0, GL_POSITION, GLfloat_4(0, 0, 1, 0))
        #设置光源的照射方向
        glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, GLfloat_3(0, 0, -1))
        #设置材质颜色
        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
        glEnable(GL_COLOR_MATERIAL)
        #设置清屏的颜色
        glClearColor(0.4, 0.4, 0.4, 0.0)

    #初始化场景,之后实现
    def init_scene(self):
        #创建一个场景实例
        self.scene = Scene()
        #初始化场景内的对象
        self.create_sample_scene()

    def create_sample_scene(self):
        """
        #创建一个球体
        sphere_node = Sphere()
        #设置球体的颜色
        sphere_node.color_index = 2
        #将球体放进场景中,默认在正中央
        self.scene.add_node(sphere_node)
        """

        cube_node = Cube()
        cube_node.translate(0, 0, 0)
        cube_node.scale(3)
        cube_node.color_index = 1
        self.scene.add_node(cube_node)

        sphere_node = Sphere()
        sphere_node.translate(-2, 0, 2)
        sphere_node.color_index = 3
        self.scene.add_node(sphere_node)

        hierarchical_node = SnowFigure()
        hierarchical_node.translate(-2, 0, -2)
        self.scene.add_node(hierarchical_node)

    def init_interaction(self):
        #初始化交互操作相关的代码,之后实现
        pass

    def main_loop(self):
        #程序主循环开始
        glutMainLoop()

    #程序进入主循环后每一次循环调用的渲染函数
    def render(self):
        #初始化投影矩阵
        self.init_view()
    
        #启动光照
        glEnable(GL_LIGHTING)
        #清空颜色缓存与深度缓存
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    
        #设置模型视图矩阵,目前为止用单位矩阵就行了。
        glMatrixMode(GL_MODELVIEW)
        glPushMatrix()
        glLoadIdentity()

        glRotatef(10,0,1,0);
        #渲染场景
        self.scene.render()
    
        #每次渲染后复位光照状态
        glDisable(GL_LIGHTING)
        glCallList(G_OBJ_PLANE)
        glPopMatrix()
        #把数据刷新到显存上
        glFlush()
    
    def init_view(self):
        """ 初始化投影矩阵 """
        xSize, ySize = glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)
        #得到屏幕宽高比
        aspect_ratio = float(xSize) / float(ySize)
    
        #设置投影矩阵
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
    
        #设置视口,应与窗口重合
        glViewport(0, 0, xSize, ySize)
        #设置透视,摄像机上下视野幅度70度
        #视野范围到距离摄像机1000个单位为止。
        gluPerspective(70, aspect_ratio, 0.1, 1000.0)
        #摄像机镜头从原点后退15个单位
        glTranslated(0, 0, -15)
Exemplo n.º 52
0
 def init_scene(self):
     #创建一个场景实例
     self.scene = Scene()
     #初始化场景内的对象
     self.create_sample_scene()
Exemplo n.º 53
0
 def play(self, *animations, **kwargs):
     Scene.play(
         self,
         *list(animations)+map(Animation, self.foreground_mobjects),
         **kwargs
     )
Exemplo n.º 54
0
 def __init__(self, caller, msg, img):
     Scene.__init__(self)
     self.msg = msg
     self.caller = caller
     self.img = SpriteNode(Texture(img))
Exemplo n.º 55
0
 def add_foreground_mobjects(self, *mobjects):
     self.foreground_mobjects += list(mobjects)
     Scene.add(self, *mobjects)
Exemplo n.º 56
0
import sys
sys.path.append('..')
from scene import Scene
from sphere import Sphere
from material import Material
from light import Spotlight
from rayon import raytracer_render
from camera import Camera
import numpy as np
import matplotlib.pyplot as plt

this_scene = Scene()
some_material = Material(
    np.array([106., 102., 163.]) / 255, 0.5, 0.7, 0.1, 0.3, 0.4)
red_material = Material(
    np.array([255., 151., 112.]) / 255, 0.8, 0.4, 0.2, 0.4, 0.7)

light1 = Spotlight(np.array([1., 1., 0.]), np.array([252., 236., 201.]) / 255)
#red_light = Spotlight(np.array([-1,2,1]),np.array([1,1,0]))
#other_light = Spotlight(np.array([0,-1,1.5]),np.array([1,0,1]))
blue_sphere = Sphere(np.array([0., 0., 3.]), 0.8, some_material)
red_sphere = Sphere(np.array([0.4, 0.4, 1.8]), 0.1, red_material)

this_scene.add_object(blue_sphere)
this_scene.add_object(red_sphere)
this_scene.add_light(light1)
#this_scene.add_light(red_light)
#this_scene.add_light(other_light)

this_camera = Camera(1500, 1500, 2.2)
Exemplo n.º 57
0
 def __init__(self, graph, *args, **kwargs):
     #See CubeGraph() above for format of graph
     self.graph = graph
     Scene.__init__(self, *args, **kwargs)
                if (0 <= tx1 <= 1 and 0 <= ty1 <= 1) or (
                        0 <= tx2 <= 1 and 0 <= ty2 <= 1
                ) or (0 <= tx3 <= 1 and 0 <= ty3 <= 1) or (0 <= tx4 <= 1
                                                           and 0 <= ty4 <= 1):
                    obstacle_clash += 1
                else:
                    pass
            if obstacle_clash == 0:
                vertices[k[1]].connetedComponentNr = 1
                graph.addEdge(i, vertices[k[1]], k[0])
                edge_path.append(vertices[k[1]])
        else:
            pass


def interpolate(q1, q2, stepsize):
    """
        Returns an interpolated local path between two given configurations.
        It can be used to determine whether an edge between vertices is collision-free.
    """

    return None


if __name__ == "__main__":
    from scene import Scene
    import tkinter as tk

    win = tk.Tk()
    Scene('prm1.csv', disk_robot, (build_roadmap, find_path), win)
    win.mainloop()
Exemplo n.º 59
0
 def set_scene(self,scene):
     self._set_states({"scene":Scene.find_by_name(scene)})
Exemplo n.º 60
0
#background_image = utils.load_image(["backgrounds"], "background3-720.png", size=(config.SCREEN_WIDTH_PX, config.SCREEN_HEIGHT_PX))
spotlight_mask = utils.load_image([],
                                  "spotlight_mask.png",
                                  size=(config.SPOTLIGHT_RADIUS * 2,
                                        config.SPOTLIGHT_RADIUS * 2))
mask = pygame.Surface((config.SCREEN_WIDTH_PX, config.SCREEN_HEIGHT_PX),
                      flags=pygame.SRCALPHA)

# Load the scenes
scenes = []
current_scene = args.initial_scene
with os.scandir(config.scene_folder) as it:
    for entry in it:
        if entry.name.endswith(".json") and entry.is_file():
            scenes.append(Scene(entry.path, screen))


def next_scene(new_scene):
    global current_scene
    frame_timer.frame_timer_del_all()
    print("Moving to scene {}".format(new_scene))
    if new_scene >= len(scenes):
        # Game over
        exit()
    player.start_scene(scenes[new_scene])
    scenes[current_scene].add_player(None)
    scenes[new_scene].reset()
    scenes[new_scene].add_player(player)
    current_scene = new_scene