def __init__(self): # Basics ShowBase.__init__(self) base.disableMouse() base.setFrameRateMeter(True) self.accept("escape", sys.exit) self.camera.set_pos(-10, -10, 10) self.camera.look_at(0, 0, 0) # A light plight = PointLight('plight') plight.setColor(VBase4(0.5, 0.5, 0.5, 1)) plnp = render.attachNewNode(plight) plnp.setPos(10, 10, 10) render.setLight(plnp) # Create the geometry self.sidelength = 30 self.map_a = self.create_map(self.sidelength) self.map_b = self.map_a geom = self.create_geom(self.sidelength) np = NodePath(geom) np.reparent_to(self.render) # Start the task to interpolate the geometry each frame self.last_time = 0.0 self.need_to_swap_maps = True self.taskMgr.add(self.swap_maps, 'swap_geometry', sort = 5) self.taskMgr.add(self.interpolate_maps, 'interpolate_geometry', sort = 10)
def __init__(self): ShowBase.__init__(self) # Load the environment model. self.environ = self.loader.loadModel("models/environment") self.environ.reparentTo(self.render) self.environ.setScale(0.25, 0.25, 0.25) self.environ.setPos(-8, 42, 0) # Disable default mouse/camera task self.disableMouse() self.accept("w", self.startMoveForward) self.accept("w-up", self.stopMoveForward) self.accept("a", self.startMoveLeft) self.accept("a-up", self.stopMoveLeft) self.accept("d", self.startMoveRight) self.accept("d-up", self.stopMoveRight) self.accept("s", self.startMoveBack) self.accept("s-up", self.stopMoveBack) self.accept("escape", sys.exit) self.taskMgr.add(self.playerControlTask, "playerControlTask") # self.User is a dummy node to attach camera to self.Player = render.attachNewNode('Player') self.camera.reparentTo(self.Player) #default movement setting self.movingForward = False self.movingLeft = False self.movingRight = False self.movingBack = False
def __init__(self): # The basics ShowBase.__init__(self) base.disableMouse() base.setBackgroundColor(0.1, 0.1, 0.1) base.setFrameRateMeter(True) self.accept("escape", sys.exit) # Camera self.camera_orbit = base.render.attach_new_node("Camera orbit") self.camera_pitch = self.camera_orbit.attach_new_node("Camera pitch") base.camera.reparent_to(self.camera_pitch) base.camera.set_pos(0, -5, 0) # Camera control self.camera_movement = (0, 0) self.accept("arrow_up", self.change_camera_movement, [ 0, -1]) self.accept("arrow_up-up", self.change_camera_movement, [ 0, 1]) self.accept("arrow_down", self.change_camera_movement, [ 0, 1]) self.accept("arrow_down-up", self.change_camera_movement, [ 0, -1]) self.accept("arrow_left", self.change_camera_movement, [-1, 0]) self.accept("arrow_left-up", self.change_camera_movement, [ 1, 0]) self.accept("arrow_right", self.change_camera_movement, [ 1, 0]) self.accept("arrow_right-up", self.change_camera_movement, [-1, 0]) base.taskMgr.add(self.move_camera, "Move camera") # Object self.model = loader.loadModel("models/smiley") self.model.reparent_to(base.render) shader = Shader.make( Shader.SL_GLSL, vertex = vertex_shader, fragment = fragment_shader, ) self.model.set_shader(shader)
def __init__(self): load_prc_file_data("", """ textures-power-2 none window-type offscreen win-size 100 100 gl-coordinate-system default notify-level-display error print-pipe-types #f """) ShowBase.__init__(self) dest_tex = Texture() dest_tex.setup_2d_texture(2048, 2048, Texture.T_unsigned_byte, Texture.F_rgba8) cshader = Shader.load_compute(Shader.SL_GLSL, "grain.compute.glsl") node = NodePath("") node.set_shader(cshader) node.set_shader_input("DestTex", dest_tex) attr = node.get_attrib(ShaderAttrib) self.graphicsEngine.dispatch_compute( (2048 // 16, 2048 // 16, 1), attr, self.win.get_gsg()) base.graphicsEngine.extract_texture_data(dest_tex, base.win.get_gsg()) # Convert to single channel img = PNMImage(2048, 2048, 1, 255) dest_tex.store(img) img.set_num_channels(1) tex = Texture() tex.load(img) tex.write("grain.txo.pz")
def __init__(self): ShowBase.__init__(self) self.setupInput() self.setupStates() taskMgr.add(self.update,"update")
def __init__(self): ShowBase.__init__(self) base.disableMouse()#mouse disabled #rocky terrain load self.environ=loader.loadModel("models/environment") self.environ.reparentTo(render) self.environ.setScale(0.15,0.15,0.15) self.environ.setPos(0,-10,0) #loading the sky background self.sky=loader.loadModel("models/farmsky") self.sky.reparentTo(render) self.sky.setScale(0.3,0.3,0.3) self.sky.setPos(0,350,0) #baby dinosaur model self.babyd = Actor("babyd", {"sit": "babydani"}) self.babyd.reparentTo(render) self.babyd.setPos(Vec3(25,-150, 3)) self.babyd.loop("sit") #big dinosaur model self.bigd = Actor("bigd", {"roar": "bigdani"}) self.bigd.reparentTo(render) self.bigd.setPos(Vec3(30, -110, 0)) self.bigd.loop("roar") #trex model self.trex = Actor("trex", {"run": "trex-eat"}) self.trex.reparentTo(render) self.trex.loop("run") self.trex.setHpr(270,0,0) self.cam.setPos(-20, -200, 22) #trex animation trexPosInterval1 = self.trex.posInterval(3, Point3(-60,-120, 0), startPos = Point3( -10,-120, 0)) trexPosInterval2 = self.trex.posInterval(3, Point3(-60,0, 0), startPos = Point3( -60,-120, 0)) trexPosInterval3 = self.trex.posInterval(3, Point3(-10,0, 0), startPos = Point3( -60,0, 0)) trexPosInterval4 = self.trex.posInterval(3, Point3(-10,-120, 0), startPos = Point3( -10,0, 0)) trexHprInterval1 = self.trex.hprInterval(0.5, Point3(180, 0, 0), startHpr = Point3(270, 0, 0)) trexHprInterval2 = self.trex.hprInterval(0.5, Point3(90, 0, 0), startHpr = Point3(180, 0, 0)) trexHprInterval3 = self.trex.hprInterval(0.5, Point3(0, 0, 0), startHpr = Point3(90, 0, 0)) trexHprInterval4 = self.trex.hprInterval(0.5, Point3(-90, 0, 0), startHpr = Point3(0, 0, 0)) # Create and play the sequence that coordinates the intervals. self.pandaPace = Sequence(trexPosInterval1, trexHprInterval1, trexPosInterval2, trexHprInterval2,trexPosInterval3,trexHprInterval3,trexPosInterval4,trexHprInterval4, name="pandaPace") self.pandaPace.loop()
def __init__(self): ShowBase.__init__(self) self.camera.setPosHpr(0, -12, 8, 0, -35, 0) self.disableMouse() self.tableau = [[0 for i in range(3)]for i in range(3)] for i in range(9): self.environ = self.loader.loadModel("bois") self.environ.reparentTo(self.render) self.environ.setScale(0.25, 0.25, 0.25) #Echelle self.environ.setColor(MARRON) self.environ.setPos(position(i)) self.environ = [None for i in range(9)] self.tourBlanc = True self.accept('1',self.addCercle0) self.accept('2',self.addCercle1) self.accept('3',self.addCercle2) self.accept('4',self.addCercle3) self.accept('5',self.addCercle4) self.accept('6',self.addCercle5) self.accept('7',self.addCercle6) self.accept('8',self.addCercle7) self.accept('9',self.addCercle8) self.accept('r',self.reset) self.accept('t',self.test)
def __init__(self): # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) base.disableMouse() # Allow manual positioning of the camera camera.setPos(0, -10, 1) # Set the cameras' position camera.setHpr(0, 0, 0) # and orientation self.keyMap = { "left": 0, "right": 0, "up": 0, "down": 0} taskMgr.add(self.startCarousel, "moveTask") imageObject = OnscreenImage(image = 'env_sky.jpg', pos = (-10,0,-10)) imageObject.setImage('env_sky.jpg') imageObject.setTransparency(TransparencyAttrib.MAlpha) self.loadModels() # Load and position our models self.setupLights() # Add some basic lighting self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["up", True]) self.accept("arrow_down", self.setKey, ["down", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["up", False]) self.accept("arrow_down-up", self.setKey, ["down", False])
def __init__(self): ShowBase.__init__(self) self.seeNode = self.render.attachNewNode("see") self.cam.reparentTo(self.seeNode) self.cam.setPos(0, 0, 5) self.fpscamera = fpscontroller.FpsController(self, self.seeNode) self.fpscamera.setFlyMode(True) self.prevPos = self.fpscamera.getPos() self.prevInto = None self.info = self.genLabelText("Position: <unknown>", 4) self.makeInstructions() self.initCollisions() self.leftColor = LVecBase4i(224, 224, 64, 255) self.rightColor = LVecBase4i(64, 224, 224, 255) self.isDrawing = False self.toggleDrawing() self.accept("escape", sys.exit) # Escape quits self.accept("enter", self.toggleDrawing)
def __init__(self): ShowBase.__init__(self) #This code puts the standard title and instruction text on screen self.title = OnscreenText(text="Precipice", style=1, fg=(1,1,0,1), pos=(0.8,-0.95), scale = .07) #OnscreenText(parent=base.a2dBottomLeft, font=loader.loadFont('cmss12'), text='press\nSPACE\nto cycle', fg=(0,0,0,1),shadow=(1,1,1,1), scale=.045) #NodePath(ost).setPos(card.getBounds().getCenter()-ost.getBounds().getCenter()) dummyParent=NodePath('') textParent=dummyParent.attachNewNode('') textParent.setDepthTest(0) textParent.setDepthWrite(0) textParent.reparentTo(render) textParent.posInterval(50,Point3(0,12,0),Point3(0,-1.05,0)).start() self.gameTitleText = OnscreenText(text = 'StarCruiser', pos = (-1.3, .75), fg=(1,1,0,1), align = TextNode.ALeft, scale = .15) self.gameTitleText.flattenLight() self.gameTitleText.setP(-40) self.leftkeyText = onScreenTextCreate("[Left Arrow]: Turn Left (CCW)", 1) self.rightkeyText = onScreenTextCreate("[Right Arrow]: Turn Right (CW)", 2) self.upkeyText = onScreenTextCreate("[Up Arrow]: Accelerate", 3) self.spacekeyText = onScreenTextCreate("[Space Bar]: Fire", 4) #self.stars = loadObject("stars", scale = 146, depth = 200, # transparency = False) #Load the background starfield self.gameTask = taskMgr.add(self.gameLoop, "gameLoop")
def __init__(self): ShowBase.__init__(self) self.decisions = [] self.isReady = False self.red = 0 self.messageNode = TextNode("Message") self.choiceOneNode = TextNode("ChoiceOne") self.choiceTwoNode = TextNode("ChoiceTwo") self.instructionsNode = TextNode("Instructions") self.messageNode.setText('"Antigone, stop screaming!"') self.choiceOneNode.setText("[stop]") self.choiceTwoNode.setText("[scream louder]") self.instructionsNode.setText("Use the arrow keys to make a choice.") base.setBackgroundColor(self.red, 0, 0) base.disableMouse() props = WindowProperties() props.setTitle("Antigo Me") base.win.requestProperties(props) self.textDisplay() self.showText() self.isReady = True self.accept("arrow_left", self.decision, [0]) self.accept("arrow_right", self.decision, [1])
def __init__(self): ShowBase.__init__(self) #Disable standard mouse camera movement #base.disableMouse() #Exit app on escape key base.accept("escape", sys.exit) #Get the location of MainGame.py projectdir = os.path.abspath(sys.path[0]) #convert it to Panda's unix-style notation. projectdir = Filename.fromOsSpecific(projectdir).getFullpath() #TODO - Load the level model here #base.wireframeOn() #self.environ = self.loader.loadModel(projectdir + "/models/levels/ThePlayground") #Load the default environment model from the panda Tutorial self.environ = self.loader.loadModel(projectdir + "/models/levels/environment") #Reparent the model to the root of the Scenegraph, aka the "render" node #this allows for the object to actually appear on screen self.environ.reparentTo(self.render) #Scale and position the level/environment model self.environ.setScale(0.25, 0.25, 0.25) self.environ.setPos(-8, 42, 0) #TODO add camera controls to a function that can be added to the taskMgr #Handle camera controls here controls = BasicControls() #controls.startMovement() self.taskMgr.add(controls.movement, 'movement') self.taskMgr.add(controls.walk, 'walk')
def create(self): """ This creates the pipeline, and setups all buffers. It also constructs the showbase. The settings should have been loaded before calling this, and also the base and write path should have been initialized properly (see MountManager). """ start_time = time.time() if not self._mount_mgr.is_mounted: self.debug("Mount manager was not mounted, mounting now ...") self._mount_mgr.mount() if not self._settings.is_file_loaded(): self.debug("No settings loaded, loading from default location") self._settings.load_from_file("$$Config/pipeline.yaml") # Check if the pipeline was properly installed, before including anything else if not isfile("Data/install.flag"): DebugObject.global_error("CORE", "You didn't setup the pipeline yet! Please run setup.py.") sys.exit(1) # Load the default prc config load_prc_file("$$Config/configuration.prc") # Construct the showbase and init global variables ShowBase.__init__(self._showbase) self._init_globals() # Create the loading screen self._loading_screen.create() self._adjust_camera_settings() self._create_managers() # Init the onscreen debugger self._init_debugger() # Load plugins and daytime settings self._plugin_mgr.load_plugins() self._daytime_mgr.load_settings() self._com_resources.write_config() # Setup common defines self._create_common_defines() # Let the plugins setup their stages self._plugin_mgr.trigger_hook("on_stage_setup") self._setup_managers() self._plugin_mgr.trigger_hook("on_pipeline_created") # Set the default effect on render self.set_effect(Globals.render, "Effects/Default.yaml", {}, -10) # Hide the loading screen self._loading_screen.remove() self._start_listener() # Measure how long it took to initialize everything init_duration = int((time.time() - start_time) * 1000.0) self.debug("Finished initialization in {} ms".format(init_duration))
def __init__(self): ShowBase.__init__(self) self.Clock = ClockObject.getGlobalClock() self._alive = True self._connected = False self._display_region = self.cam.getNode(0).getDisplayRegion(0) # Main menu and environment. self.LOBBY = Lobby(self) # <- self.ENV = Environment(self) # <- self.PRE_VIEW = Pre_View(self) # <- self.DISPLAY = self.LOBBY self.SYS = None self.SIM = Simulator(_sim.MAX_LOCAL_BODIES) self.servers = [] self.sys_recipes = self.__refresh_Sys_Recipes() # Player and main objects. ## self.PLAYER = Player() # <- self.UEH = Default_UEH() # <- self.setBackgroundColor(0,0,0) self.disableMouse() # Network. '''self.host = socket.gethostbyname(socket.gethostname()) self.tcp_addr = (self.host, CLIENT_TCP_PORT) self.udp_addr = (self.host, CLIENT_UDP_PORT) ## self.tcp_req_addr = (self.host, CLIENT_REQUEST_PORT) self.proxy_tcp_addr = None ## self.client_proxy_tcp_addr''' # Main loop. taskMgr.add(self._main_loop_, "main_loop", appendTask=True, sort=0) # <- taskMgr.doMethodLater(1/_net.BROADCAST_HZ, self._state_, "state_loop")
def __init__(self): ShowBase.__init__(self) #load background image self.__image = OnscreenImage(image='../../resources/images/main_menu.jpg', pos=(0, 0, 0), scale=1) self.__image.setSx(self.getAspectRatio()) self.__image.setTransparency(TransparencyAttrib.MAlpha) #Three main opertaions self.__newGameButton = DirectButton(pos=(-0.9, 0, 0.5,), text=("新的游戏"), scale=0.1, command=self.new_game,frameColor=(0,0,0,0), image=("../../resources/images/main_menu.jpg","../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg")) self.__selectArchiveButton = DirectButton(pos=(-0.9, 0, 0.3,), text="选择存档", scale=0.1,text_fg=(1,1,1,1), command=self.select_archives, frameColor=(0, 0, 0, 0), image=("../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg")) self.__exitGameButton = DirectButton(pos=(-0.9, 0, 0.1,), text="退出游戏", scale=0.1,text_fg=(1,1,1,1), command=self.exit_game, frameColor=(0, 0, 0, 0), image=("../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg", "../../resources/images/main_menu.jpg")) #add task to update background-image scale self.taskMgr.add(self.example_task, 'exampleTask') self.__rm=ResourcesManager()
def __init__(self): ShowBase.__init__(self) ambLight = AmbientLight("ambient") ambLight.setColor(Vec4(0.1,0.11,0.12,1.0)) ambNode = render.attachNewNode(ambLight) render.setLight(ambNode) dirLight = DirectionalLight("directional") dirLight.setColor(Vec4(0.7,0.7,0.68,1.0)) dirNode = render.attachNewNode(dirLight) dirNode.setHpr(60,-40,90) render.setLight(dirNode) sptLight = Spotlight("spot") sptLens = PerspectiveLens() sptLight.setLens(sptLens) sptLight.setColor(Vec4(0.6,0.6,0.6,1.0)) sptLight.setShadowCaster(True) sptNode = render.attachNewNode(sptLight) sptNode.setPos(0,0,20) sptNode.lookAt(0,0,0) render.setLight(sptNode) render.setShaderAuto() base.camLens.setFov(70) base.camLens.setNear(0.1) base.camLens.setFar(50) self.cam.setPos(-1,-4,4) self.cam.lookAt(0,-1,1)
def __init__(self): FixedTimeStepManager.__init__(self) ShowBase.__init__(self) self.register_signals() # Todo: Copy Panda data WorldInfo.tick_rate = 60 self.use_tick_rate = True self.animation_rate = 24 self.use_animation_rate = True # Create sub systems self.network_system = self.create_network() self.input_manager = PandaInputManager() self.physics_system = PandaPhysicsSystem() # Timing information self.last_sent_time = 0 self.current_time = 0 self.network_tick_rate = 25 self.metric_interval = 0.10 # Load world self.pending_exit = False print("Network initialised")
def __init__(self, width, height, model_path, animation_path): ShowBase.__init__(self) globalClock.setMode(ClockObject.MNonRealTime) globalClock.setDt(0.02) # 20ms per frame self.cam.setPos(0, -300, 100) self.cam.lookAt(0, 0, 100) self.cam.node().setLens(self.createLens(width / height)) if animation_path: self.animation = ExposedJointRig(model_path, { 'animation': animation_path }) self.animation.play('animation') else: self.animation = ExposedJointRig(model_path, {}) self.animation.createLines(VBase4(1.0, 0.75, 0.5, 1.0)) self.animation.reparentTo(self.render) self.canonical = ExposedJointRig(model_path, { 'animation': 'models/walking-animation.egg' }) self.canonical.play('animation') self.canonical.reparentTo(self.render) self.canonical.createLines(VBase4(0.5, 0.75, 1.0, 1.0)) self.num_frames = self.canonical.getNumFrames('animation') self.setAnimationFrame(0) self.accept('escape', sys.exit) self.taskMgr.add(self.update, 'update')
def __init__(self): ShowBase.__init__(self) self.camera_control() self.REGION_MAP = "maps/italy_provs.png" self.TEXTURE_MAP = "maps/italy_terrain2.png" self.WORLD_MAP = "maps/italy_map.xml" self.SCENARIO_MAP = "scenarios/italy_scen.xml" self.terrainScale = 1 # Currently Broken self.keyboard_setup() self.drawTerrain() self.xml_load_map(self.WORLD_MAP,"WorldMap") self.xml_load_map(self.SCENARIO_MAP,"Scenario") self.init_collisions() self.pickingEnabledObject = None self.taskMgr.add(self.camera_update, "UpdateCameraTask") self.generate_models() self.txtBox = OnscreenText("<No province>") self.setup_collision_calcs() taskMgr.add(self.rayUpdate, "updatePicker") taskMgr.doMethodLater(0.2,self.task_calendar, "calendar") self.init_variables() self.interface()
def __init__(self): ShowBase.__init__(self) base.disableMouse() with open("models.txt") as f: self.model_names = f.readlines() print("Loading models...") self.loadModels("/misc/lmbraid17/tatarchm/datasets/ShapeNet/3d_models/egg_cars") print("Done.") self.scene = NodePath("Scene") self.scene.reparentTo(self.render) self.scene.setScale(1, 1, 1) self.scene.setTwoSided(True) self.scene.setPos(0, 0, 0) self.scene.setHpr(0, 0, 0) self.setUpLight() #create depth texture base.depth_tex = Texture() self.depth_tex.setFormat(Texture.FDepthComponent) self.depth_buffer=base.win.makeTextureBuffer('depthmap', 128, 128, self.depth_tex, to_ram=True) self.depth_cam = self.makeCamera(self.depth_buffer) self.depth_cam.reparentTo(base.render) self.generateData()
def __init__(self, port, backlog = 1000, compress = False): ShowBase.__init__(self) self.compress = compress self.cManager = QueuedConnectionManager() self.cListener = QueuedConnectionListener(self.cManager, 0) self.cReader = QueuedConnectionReader(self.cManager, 0) self.cWriter = ConnectionWriter(self.cManager,0) self.clientdb = ClientDataBase() if not self.clientdb.connected: self.clientdb = None print 'Login Server failed to start...' else: # This is for pre-login self.tempConnections = [] # This is for authed clients self.activeClients = [] # This is for authed servers self.activeServers = [] # This is for authed chat servers self.activeChats = [] self.connect(port, backlog) self.startPolling() self.taskMgr.doMethodLater(0.5, self.lobbyLoop, 'Lobby Loop') print 'Login Server operating...'
def __init__(self): ShowBase.__init__(self) ########## Window configuration ######### wp = WindowProperties() wp.setSize(1024, 860) self.win.requestProperties(wp) ########## Gameplay settings ######### self.GAME_MODE = PLAY self.play_mode = SPACE self.level = 1.5 self.mode_initialized = False ######### Camera ######### self.disableMouse() self.mainCamera = Camera(self.camera) self.mainCamera.camObject.setHpr(0, 0, 0) #Trigger game chain self.loadLevel(LEVEL) ######### Events ######### self.taskMgr.add(self.gameLoop, "gameLoop", priority = 35) self.keys = {"w" : 0, "s" : 0, "a" : 0, "d" : 0, "space" : 0} self.accept("w", self.setKey, ["w", 1]) self.accept("w-up", self.setKey, ["w", 0]) self.accept("s", self.setKey, ["s", 1]) self.accept("s-up", self.setKey, ["s", 0]) self.accept("a", self.setKey, ["a", 1]) self.accept("a-up", self.setKey, ["a", 0]) self.accept("d", self.setKey, ["d", 1]) self.accept("d-up", self.setKey, ["d", 0]) self.accept("space", self.setKey, ["space", 1]) self.accept("space-up", self.setKey, ["space", 0]) self.accept("wheel_up", self.zoomCamera, [-1]) self.accept("wheel_down", self.zoomCamera, [1]) self.accept("escape", self.switchGameMode, [IN_GAME_MENU]) self.accept("window-event", self.handleWindowEvent) self.accept("playerGroundRayJumping-in", self.avatar.handleCollisionEvent, ["in"]) self.accept("playerGroundRayJumping-out", self.avatar.handleCollisionEvent, ["out"]) ######### GUI ######### self.gui_elements = []
def __init__(self): # The basics ShowBase.__init__(self) base.disableMouse() # Camera / Audio listener node self.cam_node = self.render.attachNewNode("Camera node") self.camera.reparentTo(self.cam_node) self.audio3d = Audio3DManager.Audio3DManager(base.sfxManagerList[0], self.camera) self.cam_node.set_pos(0, -10, 0) # Add the model self.m = self.loader.loadModel("models/smiley") self.m.reparentTo(self.render) self.m.setPos(0, 0, 0) s = self.audio3d.loadSfx('knocking.ogg') s.setLoop(True) s.play() self.audio3d.attachSoundToObject(s, self.m) # Bookkeeping for the rotation around the model self.angle = 0.0 self.adjust_angle = 0 # Initial camera setup self.camera.look_at(self.m) # Key events and camera movement task self.accept("arrow_left", self.adjust_turning, [-1.0]) self.accept("arrow_left-up", self.adjust_turning, [1.0]) self.accept("arrow_right", self.adjust_turning, [1.0]) self.accept("arrow_right-up", self.adjust_turning, [-1.0]) self.accept("escape", sys.exit) self.taskMgr.add(self.update_camera, 'adjust camera', sort = 10)
def __init__(self): ShowBase.__init__(self) base.disableMouse() self.accept("escape", sys.exit) # base.setBackgroundColor(0, 0, 0) # The scene to be rendered to texture myscene = NodePath("My Scene") twisted = loader.loadModel("twisted") twisted.reparent_to(myscene) # A model that the twisted-scene is rendered to model = loader.loadModel("plane") model.reparent_to(self.render) model.set_pos(0, 0, 0) t1 = self.add_texcam(myscene, 0, -30, 10) model.setTexture(t1, 1) # A second model to the left model = loader.loadModel("plane") model.reparent_to(self.render) model.set_pos(-2.5, 0, 0) t2 = self.add_texcam(myscene, -20, -30, 10) model.setTexture(t2, 1) # A third one to the right model = loader.loadModel("plane") model.reparent_to(self.render) model.set_pos(2.5, 0, 0) t3 = self.add_texcam(myscene, 20, -30, 10) model.setTexture(t3, 1) # Main camera camera.set_pos(0, -10, 0) camera.look_at(0, 0, 0)
def __init__(self): ## Init panda ShowBase.__init__(self) ## Init client sql connection self.clientConn = clientConnection.clientConnection() ## Init world self.world = world.world()
def __init__(self, width, height, model_path, animation_path): ShowBase.__init__(self) globalClock.setMode(ClockObject.MNonRealTime) globalClock.setDt(0.02) # 20ms per frame self.cam.setPos(0, -200, 100) self.cam.lookAt(0, 0, 100) self.cam.node().setLens(self.createLens(width / height)) self.animated_rig = ExposedJointRig(model_path, {'animation': animation_path}) self.animated_rig.reparentTo(self.render) self.animated_rig.createLines(VBase4(0.5, 0.75, 1.0, 1.0)) self.control_rig = ControlJointRig(model_path) self.control_rig.reparentTo(self.render) self.control_rig.createLines(VBase4(1.0, 0.75, 0.5, 1.0)) self.fbx_manager = FBXManager() self.fbx_manager.setupJoints(self.control_rig.control_joints) self.num_frames = self.animated_rig.getNumFrames('animation') self.setAnimationFrame(0) self.accept('escape', sys.exit) self.taskMgr.add(self.update, 'update')
def __init__(self, windowType = None): self.wantEnviroDR = False ShowBase.__init__(self, windowType = windowType) if config.GetBool('want-phase-checker', 0): Loader = Loader import direct.showbase Loader.phaseChecker = self.loaderPhaseChecker self.errorAccumulatorBuffer = '' taskMgr.add(self.delayedErrorCheck, 'delayedErrorCheck', priority = 10000) self.idTags = config.GetBool('want-id-tags', 0) if not self.idTags: del self.idTags self.wantNametags = self.config.GetBool('want-nametags', 1) self.slowCloseShard = self.config.GetBool('slow-close-shard', 0) self.slowCloseShardDelay = self.config.GetFloat('slow-close-shard-delay', 10.0) self.fillShardsToIdealPop = self.config.GetBool('fill-shards-to-ideal-pop', 1) self.logPrivateInfo = self.config.GetBool('log-private-info', __dev__) self.wantDynamicShadows = 1 self.stereoEnabled = False self.enviroDR = None self.enviroCam = None self.pixelZoomSetup = False self.gameOptionsCode = '' self.locationCode = '' self.locationCodeChanged = time.time() if base.cam: if self.wantEnviroDR: base.cam.node().setCameraMask(OTPRender.MainCameraBitmask) else: base.cam.node().setCameraMask(OTPRender.MainCameraBitmask | OTPRender.EnviroCameraBitmask) taskMgr.setupTaskChain('net')
def __init__(self): ShowBase.__init__(self) #Load the enviroment model self.environ = self.loader.loadModel("models/environment") #Reparent the model to render self.environ.reparentTo(self.render) #Apply scale and position transforms on the model self.environ.setScale(0.25, 0.25, 0.25) self.environ.setPos(-8, 42, 0) #Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") #Load and transform panda actor self.pandaActor = Actor("models/panda-model", {"walk": "models/panda-walk4"}) self.pandaActor.setScale(0.005, 0.005, 0.005) self.pandaActor.reparentTo(self.render) #Loop its animation self.pandaActor.loop("walk") # Create the four lerp intervals needed for the panda to # walk back and forth pandaPosInterval1 = self.pandaActor.posInterval(13, Point3(0,-10,0), startPos=Point3(0,10,0)) pandaPosInterval2 = self.pandaActor.posInterval(13, Point3(0,10,0), startPos=Point3(0,-10,0)) pandaHprInterval1 = self.pandaActor.hprInterval(3, Point3(180, 0, 0), startHpr = Point3(0,0,0)) pandaHprInterval2 = self.pandaActor.hprInterval(3, Point3(0,0,0), startHpr=Point3(180,0,0)) #Create and play the sequence that coordinates the intervals. self.pandaPace = Sequence(pandaHprInterval1, pandaHprInterval1, pandaPosInterval2, pandaHprInterval2, name = "pandaPace") self.pandaPace.loop()
def __init__(self): ShowBase.__init__(self) base.setFrameRateMeter(True) m = loader.loadModel("models/smiley") m.reparent_to(render) m.set_pos(0, 5, 0) x_size, y_size = 640, 480 xy_ratio = float(y_size) / float(x_size) self.plot = Plot(x_size, y_size) self.input_img = PNMImage(x_size, y_size) self.input_tex = Texture() self.input_tex.load(self.input_img) self.card = CardMaker('pygame_card') self.card.setUvRange(Point2(0, 1), # ll Point2(1, 1), # lr Point2(1, 0), # ur Point2(0, 0)) # ul self.screen = render.attach_new_node(self.card.generate()) self.screen.set_scale(1, 1, xy_ratio) self.screen.set_pos(-0.5, 2, -0.5 * xy_ratio) self.screen.setTexture(self.input_tex) # FIXME: Apparently mpl's print_to_buffer() doesn't write # alpha values properly. self.screen.setTransparency(TransparencyAttrib.MAlpha) taskMgr.add(self.update, "update plot")
def __init__(self): ShowBase.__init__(self) self.InitRenderPipeline() self.recenterMouse() self.taskMgr.add(self.updateCamera, "Update Camera")
def __init__(self): ShowBase.__init__(self)
def __init__(self,PAIRS,BEATS,tend=None,movie=False,renderType=True,tracetype=0): """ When initialising a new Simulation class a new bullet physics environment is created. Input: PAIRS (list(dict)) list of dict objects that specify the pairs which will be created by the simulation BEATS (list(float)) list of seconds corrsponding to every first beat of the 3/4 times waltz music TEND (float) endtime of the simulation (seconds) can be None in order to make the sim stop at the last beat of the loaded music movie (bool) if True, the engine will render an image of the simulation per frame into the Images folder renderType (bool) if True, the 3D engine will render the current status of the simulation tracetype (int) 0 - no trace is drawn 1 - the trace is drawn every beat (draws the direct path of the couple) 2 - the trace is drawn every frame (draws all swirls of every couple) """ ShowBase.__init__(self) self.PAIRINFOS=PAIRS self.PAIRNUMBER=len(PAIRS) self.dt = 0.025 #length of a time-step self.BEATS=BEATS self.BEATFRAMES=[int(x/self.dt) for x in self.BEATS] if tend==None: self.TEND=BEATS[-1] else: self.TEND=tend #print(self.BEATS) self.tracetype=tracetype self.movie=movie self.renderType=renderType if self.renderType==False: self.render.hide() self.SCENARIO='Ballroom' self.disableMouse() #only use keybord to navigate the camera! self.setAspectRatio(16.0/9.0) #image ratio to make a nice movie self.world = BulletWorld() self.world.setGravity(Vec3(0, 0, -9.81)) self.setBackgroundColor(0,0,0.2,1) #very dark blue background #initialise some defaults self.defaultangle=70.0 #default angle that couples aim to dance, if they dont know any better self.bodyradius=0.5 #size of one dancer #some default textures that are applied later to some elements (arrows, boxes etc) self.texwhite=self.loader.loadTexture('Sources/tex/white.png') self.texblack=self.loader.loadTexture('Sources/tex/black.png') self.texgrey=self.loader.loadTexture('Sources/tex/grey.png') self.texred=self.loader.loadTexture('Sources/tex/red.png') #reset some numbers self.time = 0 # simulation time [s] self.frames = 0 # frames (time-steps) of the simulation self.turn=0 # the man starts "spinning" self.spinnumber=0 # it is the first spin self.imagenumber=0 # it creates the first image self.currentbeatlength=0 # length of the beat self.Keys=Controls() #initialise keyboard keys to turn, zoom etc. self.Keys.MakeKeys(self) self.ballroomsize=[40.0,20.0] self.MakeFloor() #create the ballroom floor self.InitialisePairsRandom() self.InitialiseLight() self.InitialiseCam() debugging=False if debugging==True: debugNode = BulletDebugNode('Debug') debugNode.showWireframe(True) debugNode.showConstraints(False) debugNode.showBoundingBoxes(True) debugNode.showNormals(True) debugNP = self.render.attachNewNode(debugNode) self.world.setDebugNode(debugNP.node()) debugNP.show()
def __init__(self): ShowBase.__init__(self) self.base = self self.font = loader.loadFont('1.ttf') self.buttonget= base.loader.loadSfx("buttonget.mp3") self.buttondown= base.loader.loadSfx("buttondown.mp3") self.victorymusic= base.loader.loadSfx("victory.mp3") self.falsemusic= base.loader.loadSfx("false.mp3") self.jiechu1 = 0 self.jiechu2 = 0 self.down = 0 self.menuon = 0 # ESC退出 self.accept("escape", self.caidan) self.accept("q", self.victory) self.accept("w", self.false) # 背景 self.beijing = OnscreenImage( image='1.jpg', pos=(0, 0, 0.02), scale=(1.4, 1, 1.02)) # 开始游戏碰之前图片 self.a1 = OnscreenImage(image='buttontemp2.png', pos=(0.8, 0, -0.5), scale=(0.2, 0.1, 0.065)) self.a1.setTransparency(TransparencyAttrib.MAlpha) # 碰到开始游戏后显示的按钮 self.zjmkaishi = DirectButton(text=('', '', '', 'disabled'), image='button2.png', frameColor=(255, 255, 255, 0), image_scale=(1.8, 1, 0.6), pos=(0.8, 0, -0.5), scale=0.1, rolloverSound=self.buttonget,clickSound=self.buttondown, command=self.putdown) #(2, 1, 0.7) self.zjmkaishi.hide() self.b1 = OnscreenImage(image='buttontemp1.png', pos=(0.8, 0, -0.5), scale=(0.25, 0.1, 0.13)) self.b1.setTransparency(TransparencyAttrib.MAlpha) self.b1.hide() # 点击开始游戏后图片 self.c1 = OnscreenImage(image='buttontemp3.png', pos=(0.8, 0, -0.5), scale=(0.2, 0.1, 0.065)) self.c1.setTransparency(TransparencyAttrib.MAlpha) self.c1.hide() # 开始游戏显示的文字 self.textObjectstart1 = OnscreenText( text='开始游戏', pos=(0.8, -0.51, 0), scale=0.05, fg=(255, 255, 255, 1)) self.textObjectstart2 = OnscreenText( text='开始游戏', pos=(0.8, -0.51, 0), scale=0.055, fg=(255, 255, 255, 1)) self.textObjectstart2.hide() self.textObjectstart3 = OnscreenText( text='开始游戏', pos=(0.8, -0.51, 0), scale=0.06, fg=(255, 255, 255, 1)) self.textObjectstart3.hide() self.textObjectstart1.setFont(self.font) self.textObjectstart2.setFont(self.font) self.textObjectstart3.setFont(self.font) # 退出游戏碰之前图片 self.a2 = OnscreenImage(image='buttontemp2.png', pos=(0.8, 0, -0.7), scale=(0.2, 0.1, 0.065)) self.a2.setTransparency(TransparencyAttrib.MAlpha) # 碰到退出游戏后显示的按钮 self.zjmkaishi2 = DirectButton(text=('', '', '', 'disabled'), image='button2.png', frameColor=(255, 255, 255, 0), image_scale=(1.8, 1, 0.6), pos=(0.8, 0, -0.7), scale=0.1, command=self.quit, rolloverSound=self.buttonget,clickSound=self.buttondown) self.zjmkaishi2.hide() self.b2 = OnscreenImage(image='buttontemp1.png', pos=(0.8, 0, -0.7), scale=(0.25, 0.1, 0.13)) self.b2.setTransparency(TransparencyAttrib.MAlpha) self.b2.hide() # 点击退出游戏后图片 self.c2 = OnscreenImage(image='buttontemp3.png', pos=(0.8, 0, -0.7), scale=(0.2, 0.1, 0.071)) self.c2.setTransparency(TransparencyAttrib.MAlpha) self.c2.hide() # 退出游戏显示的文字 self.textObjectstart4 = OnscreenText( text='退出', pos=(0.8, -0.71, 0), scale=0.05, fg=(255, 255, 255, 1)) self.textObjectstart5 = OnscreenText( text='退出', pos=(0.8, -0.71, 0), scale=0.055, fg=(255, 255, 255, 1)) self.textObjectstart5.hide() self.textObjectstart6 = OnscreenText( text='退出', pos=(0.8, -0.71, 0), scale=0.06, fg=(255, 255, 255, 1)) self.textObjectstart6.hide() self.textObjectstart4.setFont(self.font) self.textObjectstart5.setFont(self.font) self.textObjectstart6.setFont(self.font) # ESC菜单 self.caidanjiemian = OnscreenImage( image='caidan.jpg', pos=(0, 0, 0), scale=(0.5, 0.1, 0.41)) self.caidanjiemian.hide() self.bangzhu1button = DirectButton(text=('', '', '', 'disabled'), image='button1.png', frameColor=(255, 255, 255, 0), image_scale=(2.2, 1, 0.7), pos=(0, 0, 0.23), scale=0.1, command=self.putdown1, rolloverSound=self.buttonget,clickSound=self.buttondown) self.bangzhu1button.hide() self.bangzhu1 = OnscreenText(text='游戏帮助', pos=( 0, 0.21, 0), scale=0.05, fg=(255, 255, 255, 1)) self.bangzhu1.setFont(self.font) self.bangzhu1.hide() self.bangzhu2button = DirectButton(text=('', '', '', 'disabled'), image='button1.png', frameColor=(255, 255, 255, 0), image_scale=(2.2, 1, 0.7), pos=(0, 0, 0.03), scale=0.1, command=self.putdown2, rolloverSound=self.buttonget,clickSound=self.buttondown) self.bangzhu2button.hide() self.bangzhu2 = OnscreenText(text='继续游戏', pos=( 0, 0.01, 0), scale=0.05, fg=(255, 255, 255, 1)) self.bangzhu2.setFont(self.font) self.bangzhu2.hide() self.bangzhu3button = DirectButton(text=('', '', '', 'disabled'), image='button1.png', frameColor=(255, 255, 255, 0), image_scale=(2.2, 1, 0.7), pos=(0, 0, -0.18), scale=0.1, command=self.putdown3, rolloverSound=self.buttonget,clickSound=self.buttondown) self.bangzhu3button.hide() self.bangzhu3 = OnscreenText(text='退出游戏', pos=( 0, -0.2, 0), scale=0.05, fg=(255, 255, 255, 1)) self.bangzhu3.setFont(self.font) self.bangzhu3.hide() self.bangzhujiemian = OnscreenImage( image='caidan.jpg', pos=(-0, 0, 0), scale=(1, 0.1, 0.81)) self.bangzhujiemian.hide() self.bangzhuxinxi = OnscreenText( text='coooooooooooooooool', pos=(0, 0, 0), scale=0.1) self.bangzhuxinxi.hide() self.bangzhuxinxibutton = DirectButton(text=('', '', '', 'disabled'), image='button1.png', frameColor=(255, 255, 255, 0), image_scale=(2.2, 1, 0.7), pos=(0.55, 0, -0.55), scale=0.1, command=self.help1, rolloverSound=self.buttonget,clickSound=self.buttondown) self.bangzhuxinxibutton.hide() self.bangzhuxinxi1 = OnscreenText( text='返回', pos=(0.55, -0.56, 0), scale=0.05, fg=(255, 255, 255, 1)) self.bangzhuxinxi1.setFont(self.font) self.bangzhuxinxi1.hide() # 游戏胜利 self.victorypic = OnscreenImage( image='victory.jpg', pos=(0, 0, 0.02), scale=(1.4, 1, 1.02)) self.victorypic.hide() # 游戏失败 self.falsepic = OnscreenImage( image='false.jpg', pos=(0, 0, 0.02), scale=(1.4, 1, 1.02)) self.falsepic.hide() self.rebornbutton = DirectButton(text=('', '', '', 'disabled'), image='button1.png', frameColor=(255, 255, 255, 0), image_scale=(2.2, 1, 0.7), pos=(0.75, 0, -0.75), scale=0.1, command=self.reborn, rolloverSound=self.buttonget,clickSound=self.buttondown) self.rebornbutton.hide() self.reborntext = OnscreenText( text='返回主菜单', pos=(0.75, -0.76, 0), scale=0.05, fg=(255, 255, 255, 1)) self.reborntext.setFont(self.font) self.reborntext.hide() #事件队列 taskMgr.add(self.example, 'MyTaskName')
def __init__(self): ShowBase.__init__(self) self.worldsize = 1024 self.camLens.setFov(60) game_world = World(self) ship = Ship(self)
def __init__(self, TENSORBOARD_PREFIX, WRITE_SUMMARY_EVERY, MODEL_SAVE_PREFIX, WRITE_TF_MODEL_EVERY, MODEL_RESTORE): ShowBase.__init__(self) self.taskMgr.add(self.renderNlearnTask, "renderNlearnTask") #changing camera poses self.taskMgr.add(self.putAxesTask, "putAxesTask") #draw co-ordinate axis self.taskMgr.add(self.putTrainingBox, "putTrainingBox") # Note params self.PARAM_TENSORBOARD_PREFIX = TENSORBOARD_PREFIX self.PARAM_MODEL_SAVE_PREFIX = MODEL_SAVE_PREFIX self.PARAM_MODEL_RESTORE = MODEL_RESTORE self.PARAM_WRITE_SUMMARY_EVERY = WRITE_SUMMARY_EVERY self.PARAM_WRITE_TF_MODEL_EVERY = WRITE_TF_MODEL_EVERY # Misc Setup self.render.setAntialias(AntialiasAttrib.MAuto) self.setFrameRateMeter(True) self.tcolor = TerminalColors.bcolors() # # Set up Mesh (including load, position, orient, scale) self.setupMesh() self.positionMesh() # Custom Render # Important Note: self.render displays the low_res and self.scene0 is the images to retrive self.scene0 = NodePath("scene0") # cytX = copy.deepcopy( cyt ) self.low_res.reparentTo(self.render) self.cyt.reparentTo(self.scene0) self.cyt2.reparentTo(self.scene0) # # Make Buffering Window bufferProp = FrameBufferProperties().getDefault() props = WindowProperties() props.setSize(1280, 960) win2 = self.graphicsEngine.makeOutput( pipe=self.pipe, name='wine1', sort=-1, fb_prop=bufferProp, win_prop=props, flags=GraphicsPipe.BFRequireWindow) #flags=GraphicsPipe.BFRefuseWindow) # self.window = win2#self.win #dr.getWindow() self.win2 = win2 # self.win2.setupCopyTexture() # Adopted from : https://www.panda3d.org/forums/viewtopic.php?t=3880 # # Set Multiple Cameras self.cameraList = [] for i in range(4 * 4): print 'Create camera#', i self.cameraList.append(self.customCamera(str(i))) # Disable default camera # dr = self.camNode.getDisplayRegion(0) # dr.setActive(0) # # Set Display Regions (4x4) dr_list = self.customDisplayRegion(4, 4) # # Setup each camera for i in range(len(dr_list)): dr_list[i].setCamera(self.cameraList[i]) # # Set buffered Queues (to hold rendered images and their positions) # each queue element will be an RGB image of size 240x320x3 self.q_imStack = Queue.Queue() self.q_labelStack = Queue.Queue() # # Set up Caffe (possibly in future TensorFLow) # caffe.set_device(0) # caffe.set_mode_gpu() # self.solver = None # self.solver = caffe.SGDSolver(solver_proto) # self.caffeIter = 0 # self.caffeTrainingLossX = np.zeros(300000) # self.caffeTrainingLossY = np.zeros(300000) # self.caffeTrainingLossZ = np.zeros(300000) # self.caffeTrainingLossYaw = np.zeros(300000) # #Set up TensorFlow through puf (PlutoFlow) puf_obj = puf.PlutoFlow(trainable_on_device='/cpu:0') # have placeholder `x`, label_x, label_y, label_z, label_yaw self.tf_x = tf.placeholder('float', [None, 240, 320, 3], name='x') self.tf_label_x = tf.placeholder('float', [None, 1], name='label_x') self.tf_label_y = tf.placeholder('float', [None, 1], name='label_y') self.tf_label_z = tf.placeholder('float', [None, 1], name='label_z') self.tf_label_yaw = tf.placeholder('float', [None, 1], name='label_yaw') # Define Deep Residual Nets with tf.device('/gpu:0'): self.tf_infer_op = puf_obj.resnet50_inference( self.tf_x, is_training=True ) #TODO: Define these inference ops on all the GPUs # Cost function, SGD, Gradient computer with tf.device('/cpu:0'): self.tf_learning_rate = tf.placeholder('float', shape=[], name='learning_rate') self.tensorflow_optimizer = tf.train.AdamOptimizer( self.tf_learning_rate) with tf.device('/gpu:0'): with tf.variable_scope('loss'): self.tensorflow_cost = self.define_l2_loss( self.tf_infer_op, self.tf_label_x, self.tf_label_y, self.tf_label_z, self.tf_label_yaw) self.tensorflow_grad_compute = self.tensorflow_optimizer.compute_gradients( self.tensorflow_cost) #TODO ideally have the averaged gradients from all GPUS here as arg for apply_grad() self.tensorflow_apply_grad = self.tensorflow_optimizer.apply_gradients( self.tensorflow_grad_compute) # Print all Trainable Variables var_list = tf.trainable_variables() print '--Trainable Variables--', 'length= ', len(var_list) total_n_nums = [] for vr in var_list: shape = vr.get_shape().as_list() n_nums = np.prod(shape) total_n_nums.append(n_nums) print self.tcolor.OKGREEN, vr.name, shape, n_nums, self.tcolor.ENDC print self.tcolor.OKGREEN, 'Total Trainable Params (floats): ', sum( total_n_nums) print 'Not counting the pop_mean and pop_varn as these were set to be non trainable', self.tcolor.ENDC #summary tf.scalar_summary('cost', self.tensorflow_cost) tf.scalar_summary('lr', self.tf_learning_rate) # Model Saver self.tensorflow_saver = tf.train.Saver() # Fire up the TensorFlow-Session self.tensorflow_session = tf.Session(config=tf.ConfigProto( log_device_placement=True, allow_soft_placement=True)) # Initi from scratch or load from model if self.PARAM_MODEL_RESTORE == None: #Start from scratch print self.tcolor.OKGREEN, 'initialize_all_variables() : xavier', self.tcolor.ENDC self.tensorflow_session.run(tf.initialize_all_variables()) else: #Restore model restore_file_name = self.PARAM_MODEL_RESTORE #'tf.models/model-5100' print self.tcolor.OKGREEN, 'restore model', restore_file_name, self.tcolor.ENDC self.tensorflow_saver.restore(self.tensorflow_session, restore_file_name) tf.train.start_queue_runners(sess=self.tensorflow_session) # Holding variables self.tensorflow_iteration = 0 # TensorBoard Writer self.tensorflow_summary_writer = tf.train.SummaryWriter( self.PARAM_TENSORBOARD_PREFIX, graph=tf.get_default_graph()) self.tensorflow_summary_op = tf.merge_all_summaries()
def __init__(self): ShowBase.__init__(self) plane_scale = 0.07 self.xPos = 0.0 self.yPos = 0.0 self.tilt = 0.0 self.lift = 0.0 self.camera_state = "FOLLOW" self.adsb = None self.adsb_states = None self.plane_state = None #camera.setPosHpr(0, 0.5, 20, 0, -100, 0) #Vary this # Disable the camera trackball controls. self.disableMouse() ''' # Load the environment model. self.scene = self.loader.loadModel("models/environment") # Reparent the model to render. self.scene.reparentTo(self.render) # Apply scale and position transforms on the model. self.scene.setScale(0.25, 0.25, 0.25) self.scene.setPos(-8, 42, 0) ''' ''' # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") ''' self.plane = loader.loadModel('./models/plane/boeing707') self.plane.setPos(0, 0, 5) self.plane.reparentTo(render) self.plane.setScale(plane_scale, plane_scale, plane_scale) #self.plane.setPosHpr(self.xPos, self.yPos, 0, DEFAULT_HEADING, self.lift, self.tilt) self.plane.setPosHpr(self.xPos, self.yPos, 0, DEFAULT_HEADING, self.lift, self.tilt) # Create a floater object, which lfoats 2 units above the plane self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.plane) self.floater.setZ(2.0) # Add keymappings # Key mappings ''' self.accept('escape', sys.exit) self.accept(']', self.scaleUp) self.accept('[', self.scaleDown) self.accept('w', self.liftUp) self.accept('s', self.liftDown) self.accept('q', self.stabilizeLift) self.accept('a', self.moveLeft) self.accept('d', self.moveRight) self.accept('e', self.stabilizeTilt) ''' # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "backward": 0, "cam-left": 0, "cam-right": 0, } self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["backward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["backward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) taskMgr.add(self.move, "moveTask") taskMgr.add(self.adsb_task, "adsbTask") self.title = addTitle("Danger Plane") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Plane Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Plane Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Moves Plane Down") self.inst5 = addInstructions(0.30, "[Down Arrow]: Moves Plane Up") self.inst6 = addInstructions(0.36, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.42, "[S]: Rotate Camera Right") self.camera.setPos(self.plane.getX(), self.plane.getY() + 10, 2) self.text_status = OnscreenText(text="Starting...", style=1, fg=(1, 1, 1, 1), scale=.04, parent=base.a2dBottomLeft, align=TextNode.ALeft, pos=(0.08, 0.09), shadow=(0, 0, 0, 1)) '''
def __init__(self): self.cameraMode = 0 ShowBase.__init__(self) self.taskMgr.add(self.spinCameraTask, "spinCameraTask") self.prepareDron() samples = [0] * 9 for i in range(0, 9): samples[i] = [0] * 5 self.samples = samples self.text_lines = { 0: OnscreenText(text=str(0.0), pos=(-1.6, 0.9), scale=.05, fg=(1, 1, 1, 1), align=TextNode.ALeft, mayChange=1), 1: OnscreenText(text=str(0.0), pos=(-1.6, 0.8), scale=.05, fg=(1, 1, 1, 1), align=TextNode.ALeft, mayChange=1), 2: OnscreenText(text=str(0.0), pos=(-1.6, 0.7), scale=.05, fg=(1, 1, 1, 1), align=TextNode.ALeft, mayChange=1), 3: OnscreenText(text=str(0.0), pos=(-1.6, 0.6), scale=.05, fg=(1, 1, 1, 1), align=TextNode.ALeft, mayChange=1), 4: OnscreenText(text=str(0.0), pos=(-1.6, 0.5), scale=.05, fg=(1, 1, 1, 1), align=TextNode.ALeft, mayChange=1), 5: OnscreenText(text=str(0.0), pos=(-1.6, 0.4), scale=.05, fg=(1, 1, 1, 1), align=TextNode.ALeft, mayChange=1), 6: OnscreenText(text=str(0.0), pos=(-1.6, 0.3), scale=.05, fg=(1, 1, 1, 1), align=TextNode.ALeft, mayChange=1), 7: OnscreenText(text=str(0.0), pos=(-1.6, 0.2), scale=.05, fg=(1, 1, 1, 1), align=TextNode.ALeft, mayChange=1), 8: OnscreenText(text=str(0.0), pos=(-1.6, 0.1), scale=.05, fg=(1, 1, 1, 1), align=TextNode.ALeft, mayChange=1) } bounds_bottom = LineSegs("bbottom") bounds_bottom.set_color(1, 0, 0) bounds_bottom.moveTo(0, 0, 0) bounds_bottom.drawTo(4096, 0, 0) bounds_bottom.drawTo(4096, 4096, 0) bounds_bottom.drawTo(0, 4096, 0) bounds_bottom.drawTo(0, 0, 0) NodePath(bounds_bottom.create()).reparentTo(self.render) bounds_mid = LineSegs("mid") bounds_mid.set_color(0, 1, 0) bounds_mid.moveTo(0, 0, 256 / 3) bounds_mid.drawTo(4096, 0, 256 / 3) bounds_mid.drawTo(4096, 4096, 256 / 3) bounds_mid.drawTo(0, 4096, 256 / 3) bounds_mid.drawTo(0, 0, 256 / 3) bounds_mid.moveTo(0, 0, 2 * 256 / 3) bounds_mid.drawTo(4096, 0, 2 * 256 / 3) bounds_mid.drawTo(4096, 4096, 2 * 256 / 3) bounds_mid.drawTo(0, 4096, 2 * 256 / 3) bounds_mid.drawTo(0, 0, 2 * 256 / 3) NodePath(bounds_mid.create()).reparentTo(self.render) bounds_top = LineSegs("btop") bounds_top.set_color(1, 0, 0) bounds_top.moveTo(0, 0, 256) bounds_top.drawTo(4096, 0, 256) bounds_top.drawTo(4096, 0, 0) bounds_top.moveTo(4096, 0, 256) bounds_top.drawTo(4096, 4096, 256) bounds_top.drawTo(4096, 4096, 0) bounds_top.moveTo(4096, 4096, 256) bounds_top.drawTo(0, 4096, 256) bounds_top.drawTo(0, 4096, 0) bounds_top.moveTo(0, 4096, 256) bounds_top.drawTo(0, 0, 256) bounds_top.drawTo(0, 0, 0) bounds_top.moveTo(0, 0, 256) NodePath(bounds_top.create()).reparentTo(self.render) ground_grid = LineSegs("mid") ground_grid.set_color(0.25, 0.38, 0) for x in range(128): ground_grid.moveTo(0, x * 32, 0) ground_grid.drawTo(4096, x * 32, 0) ground_grid.moveTo(x * 32, 0, 0) ground_grid.drawTo(x * 32, 4096, 0) NodePath(ground_grid.create()).reparentTo(self.render) self.terrainLine = LineSegs("terrainLine") self.terrainLine.set_color(1, 1, 1) #bounds_top.drawTo(0,4096,0) #bounds_top.moveTo(0,4096,256) #bounds_top.reparentTo(self.render) self.accept("space-up", self.changeCamera)
def __init__(self): ShowBase.__init__(self) self.win.setClearColor(LVecBase4(0.0, 0.0, 0.0, 1)) self.camera.setPos(0, -15, 5) self.disableMouse() self.recenterMouse() self.SetShaders() # Setup buffers self.gBuffer = self.makeFBO("G-Buffer", 2) self.lightBuffer = self.makeFBO("Light Buffer", 0) self.finalBuffer = self.makeFBO("Final Buffer", 0) self.gBuffer.setSort(1) self.lightBuffer.setSort(2) self.finalBuffer.setSort(3) self.win.setSort(4) # G-Buffer render texture self.tex = {} self.tex['DepthStencil'] = Texture() self.tex['DepthStencil'].setFormat(Texture.FDepthStencil) self.tex['Diffuse'] = Texture() self.tex['Normal'] = Texture() self.tex['Specular'] = Texture() #self.tex['Irradiance'] = Texture() self.tex['Alias'] = Texture() self.tex['Final'] = Texture() self.texScale = LVecBase2f( self.calTexScale(self.win.getProperties().getXSize()), self.calTexScale(self.win.getProperties().getYSize())) self.tranSStoVS = self.calTranSStoVS() self.gBuffer.addRenderTexture(self.tex['DepthStencil'], GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepthStencil) self.gBuffer.addRenderTexture(self.tex['Diffuse'], GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) self.gBuffer.addRenderTexture(self.tex['Normal'], GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) self.gBuffer.addRenderTexture(self.tex['Specular'], GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1) self.lightBuffer.addRenderTexture(self.tex['Alias'], GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) self.finalBuffer.addRenderTexture(self.tex['Final'], GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) self.cam.node().getLens().setNear(1.0) self.cam.node().getLens().setFar(500.0) lens = self.cam.node().getLens() self.modelMask = 1 self.adLightMask = 2 self.psLightMask = 4 self.finalMask = 8 self.gBufferCam = self.makeCamera(self.gBuffer, lens=lens, scene=render, mask=self.modelMask) self.adLightCam = self.makeCamera(self.lightBuffer, lens=lens, scene=render, mask=self.adLightMask) self.psLightCam = self.makeCamera(self.lightBuffer, lens=lens, scene=render, mask=self.psLightMask) self.finalCam = self.makeCamera(self.finalBuffer, lens=lens, scene=render, mask=self.finalMask) self.cam.node().setActive(0) self.adLightCam.node().getDisplayRegion(0).setSort(1) self.psLightCam.node().getDisplayRegion(0).setSort(2) self.gBufferCam.node().getDisplayRegion(0).disableClears() self.adLightCam.node().getDisplayRegion(0).disableClears() self.psLightCam.node().getDisplayRegion(0).disableClears() self.finalCam.node().getDisplayRegion(0).disableClears() self.cam.node().getDisplayRegion(0).disableClears() self.cam2d.node().getDisplayRegion(0).disableClears() self.gBuffer.disableClears() self.win.disableClears() self.gBuffer.setClearColorActive(1) self.gBuffer.setClearDepthActive(1) self.gBuffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) self.gBuffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.gBuffer.setClearColor((0.0, 0.0, 0.0, 1.0)) self.lightBuffer.setClearColorActive(1) self.lightBuffer.setClearColor((0.0, 0.0, 0.0, 1.0)) self.finalBuffer.setClearColorActive(1) self.finalBuffer.setClearColor((0.0, 0.0, 0.0, 1.0)) tmpnode = NodePath(PandaNode("tmp node")) tmpnode.setShader(self.shaders['gBuffer']) self.gBufferCam.node().setInitialState(tmpnode.getState()) tmpnode = NodePath(PandaNode("tmp node")) #tmpnode.setShader(self.shaders['dLight']) tmpnode.setShaderInput("texScale", self.texScale) tmpnode.setShaderInput("TexDepthStencil", self.tex['DepthStencil']) tmpnode.setShaderInput("TexDiffuse", self.tex['Diffuse']) tmpnode.setShaderInput("TexNormal", self.tex['Normal']) tmpnode.setShaderInput("TexSpecular", self.tex['Specular']) tmpnode.setAttrib( ColorBlendAttrib.make(ColorBlendAttrib.MAdd, ColorBlendAttrib.OOne, ColorBlendAttrib.OOne)) tmpnode.setAttrib(DepthWriteAttrib.make(DepthWriteAttrib.MOff)) self.adLightCam.node().setInitialState(tmpnode.getState()) self.psLightCam.node().setInitialState(tmpnode.getState()) tmpnode = NodePath(PandaNode("tmp node")) tmpnode.setShader(self.shaders['fxaa']) tmpnode.setShaderInput("texScale", self.texScale) tmpnode.setShaderInput("TexAlias", self.tex['Alias']) tmpnode.setShaderInput( "fxaaQualityRcpFrame", LVecBase2f(float(1.0 / self.win.getProperties().getXSize()), float(1.0 / self.win.getProperties().getYSize()))) tmpnode.setShaderInput("fxaaConsoleRcpFrameOpt", LVecBase4f(0.0, 0.0, 0.0, 0.0)) tmpnode.setShaderInput("fxaaConsoleRcpFrameOpt2", LVecBase4f(0.0, 0.0, 0.0, 0.0)) tmpnode.setShaderInput("fxaaConsole360RcpFrameOpt2", LVecBase4f(0.0, 0.0, 0.0, 0.0)) tmpnode.setShaderInput("fxaaQualitySubpix", float(0.50)) tmpnode.setShaderInput("fxaaQualityEdgeThreshold", float(0.125)) tmpnode.setShaderInput("fxaaQualityEdgeThresholdMin", float(0.0625)) tmpnode.setShaderInput("fxaaConsoleEdgeSharpness", float(8.0)) tmpnode.setShaderInput("fxaaConsoleEdgeThreshold", float(0.125)) tmpnode.setShaderInput("fxaaConsoleEdgeThresholdMin", float(0.05)) tmpnode.setShaderInput("fxaaConsole360ConstDir", LVecBase4f(1.0, -1.0, 0.25, -0.25)) self.finalCam.node().setInitialState(tmpnode.getState()) render.setState(RenderState.makeEmpty()) # debug self.card = self.lightBuffer.getTextureCard() self.card.setTexture(self.tex['Final']) self.card.reparentTo(render2d) self.skyTex = loader.loadCubeMap("textures/skybox/Twilight_#.jpg") self.makeQuad() self.SetModels() self.SetLights() self.SetKeys() self.taskMgr.add(self.updateCamera, "Update Camera")
def __init__(self, heightfield_fn="heightfield.png"): # Store the heightfield's filename. self.heightfield_fn = heightfield_fn """ Load some configuration variables, it's important for this to happen before ShowBase is initialized """ load_prc_file_data("", """ sync-video #t textures-power-2 none ###gl-coordinate-system default notify-level-gobj warning notify-level-grutil debug notify-level-shader_terrain debug notify-level-bullet debug ### model paths model-path /usr/share/panda3d model-path /home/juzzuj/code/prereq/bullet-samples/bullet-samples """) ShowBase.__init__(self) base.set_background_color(0.1, 0.1, 0.8, 1) base.set_frame_rate_meter(True) # Increase camera Field Of View and set near and far planes base.camLens.set_fov(90) base.camLens.set_near_far(0.1, 50000) # Lights alight = AmbientLight('ambientLight') alight.set_color(LVector4(0.5, 0.5, 0.5, 1)) alightNP = render.attach_new_node(alight) dlight = DirectionalLight('directionalLight') dlight.set_direction(LVector3(1, 1, -1)) dlight.set_color(LVector4(0.7, 0.7, 0.7, 1)) dlightNP = render.attach_new_node(dlight) render.clear_light() render.set_light(alightNP) render.set_light(dlightNP) # Basic game controls self.accept('escape', self.do_exit) self.accept('f1', base.toggle_wireframe) self.accept('f2', base.toggle_texture) self.accept('f3', self.toggle_debug) self.accept('f5', self.do_screenshot) self.accept('r', self.do_reset) # Vehicle controls inputState.watchWithModifiers('forward', 'w') inputState.watchWithModifiers('turnLeft', 'a') inputState.watchWithModifiers('reverse', 's') inputState.watchWithModifiers('turnRight', 'd') inputState.watchWithModifiers('forward', 'arrow_up') inputState.watchWithModifiers('turnLeft', 'arrow_left') inputState.watchWithModifiers('reverse', 'arrow_down') inputState.watchWithModifiers('turnRight', 'arrow_right') self.accept('space', self.reset_vehicle) # Controls to do with the terrain #self.accept('t', self.rise_in_front) self.accept('t', self.deform_terrain, ["raise"]) self.accept('g', self.deform_terrain, ["depress"]) self.accept('b', self.drop_boxes) # Some debugging and miscellaneous controls self.accept('e', self.query_elevation) self.accept('c', self.convert_coordinates) self.accept('p', self.save) self.accept('h', self.hide_terrain) # Task taskMgr.add(self.update, 'updateWorld') self.setup()
def __init__(self): ShowBase.__init__(self) self.calibrated = False self.disableMouse() self.time_total_img = [] self.time_total_sens = [] # ENV SETUP self.env = quad(time_int_step, max_timesteps, direct_control=1, T=T) self.sensor = sensor(self.env) self.aux_dl = dl_in_gen(T, self.env.state_size, self.env.action_size) self.error = [] state_dim = self.aux_dl.deep_learning_in_size self.policy = ActorCritic(state_dim, action_dim=4, action_std=0).to(device) #CONTROLLER SETUP try: self.policy.load_state_dict(torch.load('./controller/PPO_continuous_solved_drone.pth',map_location=device)) print('Saved policy loaded') except: print('Could not load policy') sys.exit(1) n_parameters = sum(p.numel() for p in self.policy.parameters()) print('Neural Network Number of Parameters: %i' %n_parameters) # Load the environment model. self.scene = self.loader.loadModel(mydir + "/models/city.egg") self.scene.reparentTo(self.render) self.scene.setScale(1, 1, 1) self.scene.setPos(0, 0, 0) # Load the skybox self.skybox = self.loader.loadModel(mydir + "/models/skybox.egg") self.skybox.setScale(100,100,100) self.skybox.setPos(0,0,-500) self.skybox.reparentTo(self.render) # Also add an ambient light and set sky color. skycol = panda3d.core.VBase3(135 / 255.0, 206 / 255.0, 235 / 255.0) self.set_background_color(skycol) alight = AmbientLight("sky") alight.set_color(panda3d.core.VBase4(skycol * 0.04, 1)) alight_path = render.attachNewNode(alight) render.set_light(alight_path) # 4 perpendicular lights (flood light) dlight1 = DirectionalLight('directionalLight') dlight1.setColor(panda3d.core.Vec4(0.3,0.3,0.3,0.3)) dlight1NP = render.attachNewNode(dlight1) dlight1NP.setHpr(0,0,0) dlight2 = DirectionalLight('directionalLight') dlight2.setColor(panda3d.core.Vec4(0.3,0.3,0.3,0.3)) dlight2NP = render.attachNewNode(dlight2) dlight2NP.setHpr(-90,0,0) dlight3 = DirectionalLight('directionalLight') dlight3.setColor(panda3d.core.Vec4(0.3,0.3,0.3,0.3)) dlight3NP = render.attachNewNode(dlight3) dlight3NP.setHpr(-180,0,0) dlight4 = DirectionalLight('directionalLight') dlight4.setColor(panda3d.core.Vec4(0.3,0.3,0.3,0.3)) dlight4NP = render.attachNewNode(dlight4) dlight4NP.setHpr(-270,0,0) render.setLight(dlight1NP) render.setLight(dlight2NP) render.setLight(dlight3NP) render.setLight(dlight4NP) # 1 directional light (Sun) dlight = DirectionalLight('directionalLight') dlight.setColor(panda3d.core.Vec4(1, 1, 1, 1)) # directional light is dim green dlight.getLens().setFilmSize(panda3d.core.Vec2(50, 50)) dlight.getLens().setNearFar(-100, 100) dlight.setShadowCaster(True, 4096*2, 4096*2) # dlight.show_frustum() dlightNP = render.attachNewNode(dlight) dlightNP.setHpr(0,-65,0) #Turning shader and lights on render.setShaderAuto() render.setLight(dlightNP) # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.calibrate, 'Camera Calibration') self.taskMgr.add(self.drone_position_task, 'Drone Position') # Load and transform the quadrotor actor. self.quad = self.loader.loadModel(mydir + '/models/quad.egg') self.quad.reparentTo(self.render) self.prop_1 = self.loader.loadModel(mydir + '/models/prop.egg') self.prop_1.setPos(-0.26,0,0) self.prop_1.reparentTo(self.quad) self.prop_2 = self.loader.loadModel(mydir + '/models/prop.egg') self.prop_2.setPos(0,0.26,0) self.prop_2.reparentTo(self.quad) self.prop_3 = self.loader.loadModel(mydir + '/models/prop.egg') self.prop_3.setPos(0.26,0,0) self.prop_3.reparentTo(self.quad) self.prop_4 = self.loader.loadModel(mydir + '/models/prop.egg') self.prop_4.setPos(0,-0.26,0) self.prop_4.reparentTo(self.quad) # Load the checkerboard actor self.checker = self.loader.loadModel(mydir+ '/models/checkerboard.egg') self.checker.reparentTo(self.render) self.checker_scale = 0.5 self.checker_sqr_size = 0.2046 self.checker.setScale(self.checker_scale, self.checker_scale, 1) self.checker.setPos(3*self.checker_scale*self.checker_sqr_size, 2.5*self.checker_scale*self.checker_sqr_size, 0.001) #env cam self.cam.node().getLens().setFilmSize(36, 24) self.cam.node().getLens().setFocalLength(45) self.cam.setPos(5,5,7) self.cam.reparentTo(self.render) self.cam.lookAt(self.quad) if IMG_POS_DETER: self.taskMgr.add(self.pos_deter, 'Position Determination') window_size = (self.win.getXSize(), self.win.getYSize()) self.buffer = self.win.makeTextureBuffer('Buffer', *window_size, None, True) self.tex = self.buffer.getTexture() self.cam_1 = self.makeCamera(self.buffer) self.cam_1.setName('cam_1') self.cam_1.node().getLens().setFilmSize(36, 24) self.cam_1.node().getLens().setFocalLength(45) self.cam_1.reparentTo(self.quad) self.cam_1.setPos(0,0,0.01) self.cam_1.lookAt(self.quad) self.pipe = panda3d.core.GraphicsPipeSelection.get_global_ptr().make_module_pipe('pandagl') input('Start?')
def __init__(self): ShowBase.__init__(self) self.params = Param() self.generate_files() self._admin_task = None self.clock = ClockObject() if self.params("test_3D"): self.earth = Earth(self) # self.moon = Moon(self) self.moon = Moon3D(self) self.sun = Sun(self) # filters = CommonFilters(self.win, self.cam) # filters.setBlurSharpen() self.space_craft = NewSpaceCraft(self, quality=self.params("quality")) self.sound_manager = SoundManager(self) self.sound_manager.play_ambiant_sound() cam = FreeCameraControl(self) cam.look_to_target() cb = CartesianBasis() self.render.attachNewNode(cb) grid = Grid(x_extend=[-10, 10], y_extend=[-10, 10], x_color=(1, 1, 1, 0.1), y_color=(1, 1, 1, 0.1)) self.render.attach_new_node(grid) self.setBackgroundColor(0, 0, 0) # self.sky_sphere = SkyDome(self) # self.sky_sphere.set_color_scale(LVector3f(0.4, 0.4, 0.4)) self.render.setShaderAuto() self.setFrameRateMeter(True) self.render.setAntialias(AntialiasAttrib.MAuto) self.space_craft.show_bounds() self.space_craft.set_hpr(5, -122, 18) self.space_craft.set_solar_panel_angle(125.) # simple linking self.accept('a', self.space_craft.spin, extraArgs=['r', 1]) self.accept('z', self.space_craft.spin, extraArgs=['r', -1]) self.accept('e', self.space_craft.spin, extraArgs=['p', 1]) self.accept('r', self.space_craft.spin, extraArgs=['p', -1]) self.accept('t', self.space_craft.spin, extraArgs=['h', 1]) self.accept('y', self.space_craft.spin, extraArgs=['h', -1]) self.accept('q', self.space_craft.solar_panel_increment, extraArgs=[1]) self.accept('s', self.space_craft.solar_panel_increment, extraArgs=[-1]) self.accept('enter', self.sound_manager.play, extraArgs=['engine_fails']) self.accept('space', self.sound_manager.play, extraArgs=['engine_starts']) else: self.hard_states = dict() self.soft_states = dict() self.init_states() # hardware self.hardware = HardwareHandler(self) # power self.power = PowerHandler(self) self.power.compute_power() # scenario self.scenario = EventHandler(self) # sound manager self.sound_manager = SoundManager(self) # control screen self.control_screen = ControlScreen(self) # environment self.earth = Earth(self) self.moon = Moon(self) self.sun = Sun(self) self.space_craft = NewSpaceCraft(self, quality=self.params("quality")) self.asteroid = Asteroid(self) # initial position and angle self.space_craft.set_hpr(5, -122, 18) self.space_craft.set_solar_panel_angle(125.) # shuttle frame self.shuttle = ShuttleFrame(self) # creating screens self.screens = [] self.generate_spacebus_screens() if self.params("enable_free_camera"): # self.screens.append(Screen3D(self, 1, shuttle_angle=0)) cam = FreeCameraControl(self, self.screens[0].get_camera()) cam.look_to_target() self.shuttle.show_shuttle() else: # disable the standard mouse behavior self.disableMouse() # disabling the normal camera self.cam.node().set_active(0) # other options if self.params("show_basis"): cb = CartesianBasis() self.render.attachNewNode(cb) if self.params("show_grid"): grid = Grid(x_extend=[-10, 10], y_extend=[-10, 10], x_color=(1, 1, 1, 0.1), y_color=(1, 1, 1, 0.1)) self.render.attach_new_node(grid) if self.params("show_ship_bounds"): self.space_craft.show_bounds() if self.params("show_sky_dome"): self.sky_sphere = SkyDome(self) else: self.setBackgroundColor(0, 0, 0) # automatic shader self.render.setShaderAuto() self.sky_sphere.set_luminosity( self.params("background_luminosity")) if self.params("show_frame_rate"): self.setFrameRateMeter(True) if self.params("anti_aliasing"): self.render.setAntialias(AntialiasAttrib.MAuto) if self.params("play_scenario"): self.load_scenario(self.params('scenario')) self.reset_game()
def __init__(self): ShowBase.__init__(self) # Window winprops = WindowProperties() winprops .setSize(640, 360) base.win.requestProperties(winprops ) base.setFrameRateMeter(True) # gamepad self.gamepad = None devices = self.devices.getDevices(InputDevice.DeviceClass.gamepad) if devices: print("Devices founds..." + str(len(devices))) # gamepad yet. if devices[0].device_class == InputDevice.DeviceClass.gamepad and not self.gamepad: print("Found %s" % (devices[0])) self.gamepad = devices[0] # Disable the camera trackball controls. self.disableMouse() # create material myMaterial = Material() myMaterial.setShininess(0.5) #Make this material shiny myMaterial.setSpecular(LColor(255,255,0,0)) #myMaterial.setAmbient((0, 0, 1, 1)) #Make this material blue # load circuit model self.circuitNodePath = self.loader.loadModel("/c/tmp/media/circuit.bam") self.circuitNodePath.reparentTo(self.render) self.circuitNodePath.setScale(1.0, 1.0, 1.0) self.circuitNodePath.setPos(1.0,-5,0) self.circuitNodePath.setHpr(0,90, 270) self.circuitNodePath.setMaterial(myMaterial) # load the environment model. self.scene = self.loader.loadModel("models/environment") self.scene.reparentTo(self.render) self.scene.setScale(1.25, 1.25, 1.25) self.scene.setPos(0,0, -0.1) # Load the environment model. self.car = self.loader.loadModel("models/box") self.car.reparentTo(self.render) self.car.setScale(1.0, 1.0, 1.0) self.car.setPos(0, 40, 0.0) # Lights render.clearLight() alight = AmbientLight('ambientLight') alight.setColor(Vec4(0.2, 0.2, 0.2, 1)) alightNP = render.attachNewNode(alight) render.setLight(alightNP) dlight = DirectionalLight('directionalLight') dlight.setDirection(Vec3(1, 1, -1)) #dlight.setColor(Vec4(1.0, 1.0, 0.8, 1)) dlight.setColorTemperature(6500) dlightNP = render.attachNewNode(dlight) render.setLight(dlightNP) s1light = PointLight('spot1Light') s1light.setColor(Vec4(0.0, 1.0, 0.0, 1.0)) s1light.setPoint((0, 0, 0.3)) s1light.setMaxDistance(4.0) s1light.setAttenuation((0.1,0.01,0.001)) s1lightNP = render.attachNewNode(s1light) render.setLight(s1lightNP) self.circuitNodePath.setLight(s1lightNP) # camera self.camLens.setFov(80) self.camLens.setNear(0.01) self.camera.setPos(0.0,0.1,0.2) self.camera.setHpr(0,0,0) self.camera.setHpr(0,-12,0) self.camera.reparentTo(self.car) # osd self.dr = self.win.makeDisplayRegion() self.dr.setSort(20) myCamera2d = NodePath(Camera('myCam2d')) lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setNearFar(-1000, 1000) myCamera2d.node().setLens(lens) myRender2d = NodePath('myRender2d') myRender2d.setDepthTest(False) myRender2d.setDepthWrite(False) myCamera2d.reparentTo(myRender2d) self.dr.setCamera(myCamera2d) # lines = LineSegs() # lines.moveTo(100,0,0) # lines.drawTo(100,500,0) # lines.setThickness(4) # node = lines.create() # np = NodePath(node) # np.reparentTo(myRender2d) # controls self.quit_button = KeyboardButton.ascii_key('q') self.quit = False self.recording_button = KeyboardButton.ascii_key('r') self.recording = False self.autopilot_button = KeyboardButton.ascii_key('a') self.humanpilot_button = KeyboardButton.ascii_key('m') self.autopilot = True self.autopilot_dir = 0.0 # tasks self.taskMgr.add(self.move_task, 'moveTask')
def __init__(self): try: ShowBase.__init__(self) except: sys.exit("something went wrong: error while loading OpenGL") # ------------------------------- Begin of parameter variables (pretty messy actually) ------------------------------------ #debug self.debug = False #REMEMBER TO TURN THIS OFF WHEN COMMITTING THIS TO GITHUB YOU GODDAM MORRON !!! #debug self.dir = Filename.fromOsSpecific(os.getcwd()) self.timescale = 5 self.worldscale = 0.1 # currently unused self.camera_delta = 0.5 # camera delta displacement self.sensitivity_x, self.sensitivity_y = 20, 20 self.watched = None # watched object (object focused by the cursor) self.state = [ 'paused', 'free', None ] # state of things: [simulation paused/running,camera following object/free,followed object/None] print('free mode on') self.iteration = 0 #iteration for the menu to be drawn once self.collision_status = False # Keep this on False, that's definitely not a setting # currently unused self.u_constant = 6.67408 * 10**(-11) #just a quick reminder self.u_radius = 5.25 #just what I said earlier self.u_radius_margin = 0.1 #a margin added to the generic radius as a safety feature (mountains and stuff, atmosphere) # ------------------------------- End of parameter variables (sry for the mess) -------------------------------------------- # Mouse parameters self.hidden_mouse = True wp = WindowProperties() wp.setCursorHidden(self.hidden_mouse) self.win.requestProperties(wp) # preparing the menu text list: self.menu_text = [] self.menu_text.append( self.showsimpletext('The PyOS project V0.10', (0, 0.4), (0.07, 0.07), None, (1, 1, 1, True))) self.menu_text.append( self.showsimpletext('Resume', (0, 0.3), (0.06, 0.06), None, (1, 1, 1, True))) self.menu_text.append( self.showsimpletext('Quit', (0, 0.2), (0.06, 0.06), None, (1, 1, 1, True))) # btw I found something about energy transmition through thermal radiation. I think it uses some Boltzmann formula stuff. Link here: # https://fr.wikibooks.org/wiki/Plan%C3%A9tologie/La_temp%C3%A9rature_de_surface_des_plan%C3%A8tes#Puissance_re%C3%A7ue_par_la_Terre # Defining important data lists self.sounds = [ self.loader.loadSfx(self.dir + "/Sound/001.mp3"), self.loader.loadSfx(self.dir + "/Sound/002.mp3"), self.loader.loadSfx(self.dir + "/Sound/003.mp3"), self.loader.loadSfx(self.dir + "/Sound/004.mp3"), self.loader.loadSfx(self.dir + "/Sound/005.mp3") ] #buggy self.collision_solids = [ ] #collision related stuff - comments are useless - just RTFM self.light_Mngr = [] self.data = [ [ 0, 0, 0, 0, 0.003, 0, 0.15, 0.15, 0.15, 100000.00, True, [ self.loader.loadModel(self.dir + "/Engine/lp_planet_0.egg"), (0.1, 0, 0), self.loader.loadModel(self.dir + "/Engine/lp_planet_1.egg"), (0.14, 0, 0) ], "lp_planet", False, 0.1 ], [ 40, 0, 0, 0, 0.003, 0, 0.05, 0.05, 0.05, 20.00, True, [ self.loader.loadModel(self.dir + "/Engine/Icy.egg"), (0.05, 0, 0) ], "Ottilia", False, 0.1 ], [ 0, 70, 10, 0, 0.005, 0, 0.1, 0.1, 0.1, 40.00, True, [ self.loader.loadModel(self.dir + "/Engine/asteroid_1.egg"), (0, 0, 0.2) ], "Selena", False, 1 ], [ 100, 0, 10, 0, 0, 0, 5, 5, 5, 1000000, True, [ self.loader.loadModel(self.dir + "/Engine/sun1.egg"), (0.01, 0, 0), self.loader.loadModel(self.dir + "/Engine/sun1_atm.egg"), (0.01, 0, 0) ], "Sun", True, 0.1 ], [ -100, 50, 70, 0, 0, 0.002, 0.15, 0.15, 0.15, 1000.00, True, [ self.loader.loadModel(self.dir + "/Engine/Earth2.egg"), (-0.1, 0, 0), self.loader.loadModel(self.dir + "/Engine/Earth2_atm.egg"), (-0.15, 0, 0) ], "Julius_planet", False, 0.1 ] # insert your 3d models here, following the syntax ] # the correct reading syntax is [x,y,z,l,m,n,scale1,scale2,scale3,mass,static,[file,(H,p,r),file,(H,p,r)...],id,lightsource,brakeforce] for each body - x,y,z: position - l,m,n: speed - scale1,scale2,scale3: obvious (x,y,z) - mass: kg - static: boolean - [files]: panda3d readfiles list - id: str - lightsource: boolean - #if you want the hitbox to be correctly scaled, and your body to have reasonable proportions, your 3d model must be a 5*5 sphere, or at least have these proportions # create the real data list, the one used by the program self.bodies = [] for c in self.data: temp = body() temp.fill_entries(c) self.bodies.append(temp) temp = None #self.bodies.reverse() # Quick presetting self.setBackgroundColor(0, 0, 0, True) # non-body type structures loading if SKYBOX == 'sky': self.isphere = self.loader.loadModel( self.dir + "/Engine/InvertedSphere.egg") #loading skybox structure self.tex = loader.loadCubeMap(self.dir + '/Engine/Skybox4/skybox_#.png') elif SKYBOX == 'arena': self.box = self.loader.loadModel(self.dir + "/Engine/arena.egg") #load shaders (optionnal) ''' sun_shader=Shader.load(Shader.SLGLSL,self.dir+'/Engine/Shaders/flare_v.glsl',self.dir+'/Engine/Shaders/flare_f.glsl') ''' self.orbit_lines = [] #under developement # see https://www.panda3d.org/manual/?title=Collision_Solids for further collision interaction informations base.graphicsEngine.openWindows() try: # filters predefining self.filters = CommonFilters(base.win, base.cam) ''' self.filters.setBlurSharpen(amount=0) # just messing around ''' if not self.debug: self.filters.set_gamma_adjust(1.0) # can be usefull self.filters.set_bloom(intensity=1, size="medium") render.setAntialias(AntialiasAttrib.MAuto) for c in self.bodies: # loading and displaying the preloaded planets and bodies if c.is_lightSource and not self.debug: # VM filtering self.filters.setVolumetricLighting(c.filelist[u], numsamples=50, density=0.5, decay=0.95, exposure=0.035) #c.filelist[u].set_shader(sun_shader) if BLUR: self.filters.setCartoonInk() for u in range(0, len(c.filelist), 2): # loading each sub-file c.filelist[u].reparentTo(self.render) c.filelist[u].setScale(tuple(c.scale)) c.filelist[u].setPos(tuple(c.position)) #setting the collision solid up temp = hitbox() temp.Volume = CollisionSphere(0, 0, 0, self.u_radius) temp.NodePath = c.filelist[0].attachNewNode(CollisionNode( c.id)) temp.CollisionNode = temp.NodePath.node() self.collision_solids.append( temp ) #the radius is calculated by using the average scale + the u_radius # the structure of the collision_solids list will be: [temp1,temp2,...] # asteroids and irregular shapes must be slightly bigger than their hitbox in order to avoid visual glitches self.collision_solids[ len(self.collision_solids) - 1].CollisionNode.addSolid( self.collision_solids[ len(self.collision_solids) - 1].Volume) #I am definitely not explaining that temp = None if self.debug: loadPrcFileData('', 'show-frame-rate-meter true') self.collision_solids[ len(self.collision_solids) - 1].NodePath.show() # debugging purposes only print("collision: ok") print("placing body: done") if c.is_lightSource: self.light_Mngr.append([PointLight(c.id + "_other")]) self.light_Mngr[len(self.light_Mngr) - 1].append( render.attachNewNode( self.light_Mngr[len(self.light_Mngr) - 1][0])) self.light_Mngr[len(self.light_Mngr) - 1][1].setPos( tuple(c.position)) render.setLight(self.light_Mngr[len(self.light_Mngr) - 1][1]) self.light_Mngr.append([AmbientLight(c.id + "_self")]) self.light_Mngr[len(self.light_Mngr) - 1][0].setColorTemperature(3000) self.light_Mngr[len(self.light_Mngr) - 1].append( render.attachNewNode( self.light_Mngr[len(self.light_Mngr) - 1][0])) for u in range(0, len(c.filelist), 2): c.filelist[u].setLight( self.light_Mngr[len(self.light_Mngr) - 1][1]) print("lights: done") print("loaded new body, out: done") if SKYBOX == 'sky': self.isphere.setTexGen( TextureStage.getDefault(), TexGenAttrib.MWorldCubeMap ) # *takes a deep breath* cubemap stuff ! self.isphere.setTexProjector(TextureStage.getDefault(), render, self.isphere) self.isphere.setTexPos(TextureStage.getDefault(), 0, 0, 0) self.isphere.setTexScale(TextureStage.getDefault(), .5) # that's a thing... self.isphere.setTexture( self.tex ) # Create some 3D texture coordinates on the sphere. For more info on this, check the Panda3D manual. self.isphere.setLightOff() self.isphere.setScale(10000) #hope this is enough self.isphere.reparentTo(self.render) elif SKYBOX == 'arena': self.box.setPos(0, 0, 0) self.box.setScale(100) self.box.reparentTo(self.render) # collision traverser and other collision stuff # that's super important, and super tricky to explain so just check the wiki self.ctrav = CollisionTraverser() self.queue = CollisionHandlerQueue() for n in self.collision_solids: self.ctrav.add_collider(n.NodePath, self.queue) # the traverser will be automatically updated, no need to repeat this every frame # debugging only if self.debug: self.ctrav.showCollisions(render) # play a random music self.current_playing = random.randint(0, len(self.sounds) - 1) self.sounds[self.current_playing].play() # task manager stuff comes here self.taskMgr.add(self.intro_loop, 'showIntroPic') except: sys.exit(":( something went wrong: files could not be loaded") ''' self.showsimpletext("All modules loaded, simulation running",(-1.42,0.95),(0.04,0.04),None,(1,1,1,True)) self.showsimpletext("PyOS build V0.10",(-1.5,0.90),(0.04,0.04),None,(1,1,1,True)) self.showsimpletext("By l3alr0g",(-1.68,0.85),(0.04,0.04),None,(1,1,1,True)) ''' # key bindings self.accept('backspace', self.system_break) self.accept('escape', self.toggle_pause) self.accept('mouse1', self.handle_select, [True]) self.accept('wheel_up', self.handle_scrolling, [True]) # center button (just a quick test) self.accept('wheel_down', self.handle_scrolling, [False]) self.accept('z', self.move_camera, [0, True]) self.accept('q', self.move_camera, [1, True]) self.accept('s', self.move_camera, [2, True]) self.accept('d', self.move_camera, [3, True]) self.accept('a', self.move_camera, [4, True]) self.accept('e', self.move_camera, [5, True]) self.accept('z-up', self.move_camera, [0, False]) self.accept('q-up', self.move_camera, [1, False]) self.accept('s-up', self.move_camera, [2, False]) self.accept('d-up', self.move_camera, [3, False]) self.accept('a-up', self.move_camera, [4, False]) self.accept('e-up', self.move_camera, [5, False]) self.keymap = [ 'z', 0, 'q', 0, 's', 0, 'd', 0, 'a', 0, 'e', 0, 'mouse1', 0 ] self.disable_mouse() if self.debug: # draw axis coord = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] axis = [] for c in range(3): axis.append(LineSegs()) axis[c].moveTo(0, 0, 0) axis[c].drawTo(coord[c]) axis[c].setThickness(3) axis[c].setColor( tuple([coord[c][u] * 255 for u in range(len(coord[c]))] + [True])) NodePath(axis[c].create()).reparent_to(render) # camera positionning ------- self.focus_point = [ 0, 0, 0 ] # point focused: can become a body's coordinates if the user tells the program to do so self.zoom_distance = 30 # distance to the focus point in common 3D units (can be modified by scrolling) self.cam_Hpr = [0, 0, 0] # phi, alpha, theta - aka yaw, pitch, roll self.cam_Hpr = [ self.cam_Hpr[n] * pi / 180 for n in range(len(self.cam_Hpr)) ] # convert to rad phi, alpha, theta, zoom, object = self.cam_Hpr[ 0] * pi / 180, self.cam_Hpr[1] * pi / 180, self.cam_Hpr[ 2] * pi / 180, self.zoom_distance, self.state[ 2] # temporary vars if self.state[1] == 'free': self.camera_pos = [0, 0, 0] self.camera.setPos(tuple(self.camera_pos)) elif self.state[1] == 'linked': # find the object (self.state[2]) in the data list list_pos = [ self.bodies[n].filelist[0] for n in range(len(self.bodies)) ].index(object.getParent()) self.focus_point = self.bodies[ list_pos].position # take the focused object's coordinates self.camera_pos = [ self.focus_point[0] + sin(phi) * cos(-alpha) * zoom, self.focus_point[1] - cos(phi) * cos(-alpha) * zoom, self.focus_point[2] + sin(-alpha) * zoom ] #keep it up to date so that it's not hard to find whend switching modes self.camera.setPos(tuple(self.camera_pos)) self.camera.setHpr(self.cam_Hpr) # cursor self.cursor = self.showsimpletext('.', (0, 0), (0.08, 0.08), None, ( 1, 1, 1, True)) # yeah, you can laugh, but this still works so I don't care self.pointerNode = CollisionNode('cursor') self.pointerNP = camera.attachNewNode(self.pointerNode) self.pointerNode.setFromCollideMask( BitMask32.bit(1) ) # separate collisions (in order to avoid mistakes during physical calculations) self.cursor_ray = CollisionRay() # create the mouse control ray self.pointerNode.addSolid(self.cursor_ray) self.ctrav.add_collider(self.pointerNP, self.queue) return None
def __init__(self, id, session, hand, block, mode, wrist): ShowBase.__init__(self) GripStateMachine.__init__(self) base.disableMouse() wp = WindowProperties() wp.setSize(1920,1080) wp.setFullscreen(True) wp.setUndecorated(True) base.win.requestProperties(wp) self.sub_id = str(id) self.sess_id = str(session) self.hand = str(hand) self.block = str(block) self.mode = str(mode) self.wrist = str(wrist) self.prev_blk = os.path.join(self.DATA_DIR,'exp_2',self.sub_id,self.sess_id,self.wrist,self.hand,"B0") self.exp_blk0 = os.path.join(self.DATA_DIR,'exp_1',self.sub_id,self.sess_id,self.wrist,self.hand,"B0") self.table = np.loadtxt('src/tunnel_pinch_task/trialtable_flex.csv',dtype='str',delimiter=',',skiprows=1) indices = {} try: self.prev_table = np.loadtxt(os.path.join(self.prev_blk, 'final_targets.csv'),dtype='str',delimiter=',',skiprows=1) except: try: self.prev_table = np.loadtxt(os.path.join(self.exp_blk0, 'final_targets.csv'),dtype='str',delimiter=',',skiprows=1) except: print('Previous target file not found, results may be suboptimal') try: for i in range(self.prev_table.shape[0]): indices[self.prev_table[i,1]] = int(self.prev_table[i,0])-1 for i in range(self.table.shape[0]): self.table[i,11] = self.prev_table[indices[self.table[i,1].strip()],11] self.table[i,12] = self.prev_table[indices[self.table[i,1].strip()],12] self.table[i,13] = self.prev_table[indices[self.table[i,1].strip()],13] except: print('Invalid target file') self.table = np.array([[item.strip() for item in s] for s in self.table]) ################################################### #only use rows relevant to this block #HARDCODED! NOTE IN LOG SHEET spec_table = [] for i in range(self.table.shape[0]): if int(self.block)%5 == 0: #block 0 to adjust positions if "(p)" in self.table[i,2]: spec_table.append(self.table[i]) elif int(self.block)%5 == 1: if "(L)" in self.table[i,2]: spec_table.append(self.table[i]) elif int(self.block)%5 == 2: if "(L+t)" in self.table[i,2]: spec_table.append(self.table[i]) elif int(self.block)%5 == 3: if "(S)" in self.table[i,2]: spec_table.append(self.table[i]) elif int(self.block)%5 == 4: if "(S+t)" in self.table[i,2]: spec_table.append(self.table[i]) ################################################### self.table = np.array(spec_table) self.session_dir = os.path.join(self.DATA_DIR,'exp_2',self.sub_id,self.sess_id,self.wrist,self.hand) self.subjinfo = self.sub_id + '_' + self.sess_id + '_' + self.hand + '_log.yml' self.p_x,self.p_y,self.p_a = GET_POS(self.session_dir,self.subjinfo,self.hand,self.wrist) self.rotmat = ROT_MAT(self.p_a,self.hand) self.setup_text() self.setup_lights() self.setup_camera() self.trial_counter = 0 self.load_models() self.load_audio() self.update_trial_command() self.countdown_timer = CountdownTimer() self.hold_timer = CountdownTimer() self.cTrav = CollisionTraverser() self.chandler = CollisionHandlerEvent() self.chandler.addInPattern('%fn-into-%in') self.chandler.addOutPattern('%fn-outof-%in') self.chandler.addAgainPattern('%fn-again-%in') self.attachcollnodes() taskMgr.add(self.read_data, 'read') for i in range(5): taskMgr.add(self.move_player, 'move%d' % i, extraArgs = [i], appendTask=True) taskMgr.add(self.log_data, 'log_data') taskMgr.add(self.update_state, 'update_state', sort=1) self.accept('space', self.space_on) self.accept('escape', self.clean_up) self.space = False self.statenum = list() self.max_time = 20 self.med_data = None self.grip_dir = os.path.join(self.DATA_DIR,'exp_2',self.sub_id,self.sess_id,self.wrist,self.hand,"B"+self.block) if not os.path.exists(self.grip_dir): print('Making new folders: ' + self.grip_dir) os.makedirs(self.grip_dir) self.dev = MpDevice(RightHand(calibration_files=['calibs/cal_mat_70_v2.mat', 'calibs/cal_mat_73_v2.mat', 'calibs/cal_mat_56.mat', 'calibs/cal_mat_58_v2.mat', 'calibs/cal_mat_50.mat'], clock=mono_clock.get_time))
def __init__(self): # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) self.stimtype = 'image_sequence' #session_start self.session_start_time = datetime.datetime.now() # self.accept("escape", sys.exit, [0])#don't let the user do this, because then the data isn't saved. self.accept('q', self.close) self.accept('Q', self.close) self.AUTO_REWARD = AUTO_REWARD # disable mouse control so that we can place the camera base.disableMouse() camera.setPosHpr(0, 0, 10, 0, -90, 0) mat = Mat4(camera.getMat()) mat.invertInPlace() base.mouseInterfaceNode.setMat(mat) # base.enableMouse() props = WindowProperties() # props.setFullscreen(True) props.setOrigin(-924, 70) # props.setSize(1880,1040) props.setCursorHidden(True) props.setMouseMode(WindowProperties.M_relative) base.win.requestProperties(props) base.setBackgroundColor(0, 0, 0) # set the background color to black #set up the textures # we now get buffer thats going to hold the texture of our new scene altBuffer = self.win.makeTextureBuffer("hello", 1524, 1024) # altBuffer.getDisplayRegion(0).setDimensions(0.5,0.9,0.5,0.8) # altBuffer = base.win.makeDisplayRegion() # altBuffer.makeDisplayRegion(0,1,0,1) # now we have to setup a new scene graph to make this scene self.dr2 = base.win.makeDisplayRegion(0, 0.1, 0, 0.1) altRender = NodePath("new render") # this takes care of setting up ther camera properly self.altCam = self.makeCamera(altBuffer) self.dr2.setCamera(self.altCam) self.altCam.reparentTo(altRender) self.altCam.setPos(0, -10, 0) self.bufferViewer.setPosition("llcorner") # self.bufferViewer.position = (.1,.4,.1,.4) self.bufferViewer.setCardSize(1.0, 0.0) print(self.bufferViewer.position) self.imagesTexture = MovieTexture("image_sequence") # success = self.imagesTexture.read("models/natural_images.avi") success = self.imagesTexture.read("models/movie_5hz.mpg") self.imagesTexture.setPlayRate(1.0) self.imagesTexture.setLoopCount(10) # self.imageTexture =loader.loadTexture("models/NaturalImages/BSDs_8143.tiff") # self.imagesTexture.reparentTo(altRender) cm = CardMaker("stimwindow") cm.setFrame(-4, 4, -3, 3) # cm.setUvRange(self.imagesTexture) self.card = NodePath(cm.generate()) self.card.reparentTo(altRender) if self.stimtype == 'image_sequence': self.card.setTexture(self.imagesTexture, 1) # self.imagesTexture.play() # self.bufferViewer.setPosition("lrcorner") # self.bufferViewer.setCardSize(1.0, 0.0) self.accept("v", self.bufferViewer.toggleEnable) self.accept("V", self.bufferViewer.toggleEnable) # Load the tunnel self.initTunnel() #initialize some things # for the tunnel construction: self.boundary_to_add_next_segment = -1 * TUNNEL_SEGMENT_LENGTH self.current_number_of_segments = 8 #task flow booleans self.in_waiting_period = False self.stim_started = False self.looking_for_a_cue_zone = True self.in_reward_window = False self.show_stimulus = False #for task control self.interval = 0 self.time_waiting_in_cue_zone = 0 self.wait_time = 1.83 self.stim_duration = 4.0 # in seconds self.max_stim_duration = 6.0 # in seconds self.stim_elapsed = 0.0 # in seconds self.last_position = base.camera.getZ() self.position_on_track = base.camera.getZ() #for reward control self.reward_window = REWARD_WINDOW # in seconds self.reward_elapsed = 0.0 # self.reward_volume = 0.008 # in mL. this is for the hardcoded 0.1 seconds of reward time self.reward_volume = int(REWARD_VOLUME) # in uL, for the stepper motor self.reward_time = 0.1 # in sec, based on volume. hard coded right now but should be modified by the (1) calibration and (2) optionally by the main loop for dynamic reward scheduling # self.lick_buffer = [] #INITIALIZE NIDAQ self.nidevice = 'Dev2' self.encodervinchannel = 1 self.encodervsigchannel = 0 self.invertdo = False self.diport = 1 self.lickline = 0 self.doport = 0 self.rewardline = 0 self.rewardlines = [0] self._setupDAQ() self.do.WriteBit(1, 1) self.do.WriteBit( 3, 1 ) #set reward high, because the logic is flipped somehow. possibly by haphazard wiring of the circuit (12/24/2018 djd) self.previous_encoder_position = self.ai.data[0][ self.encodervsigchannel] self.encoder_gain = 30 #INITIALIZE LICK SENSOR self._lickSensorSetup() #INITIALIZE output data self.lickData = [] self.x = [] self.t = [] self.trialData = [] self.rewardData = [] #INITIALIZE KEY SENSOR, for backup inputs and other user controls self.keys = key.KeyStateHandler() self.accept('r', self._give_reward, [self.reward_volume]) self.accept('l', self._toggle_reward) img_list = glob.glob('models/NaturalImages/*.tiff')[:10] print(img_list) self.imageTextures = [loader.loadTexture(img) for img in img_list] self._setupEyetracking() self._startEyetracking() if AUTO_MODE: self.gameTask = taskMgr.add(self.autoLoop2, "autoLoop2") self.rewardTask = taskMgr.add(self.rewardControl, "reward") self.cue_zone = concatenate((self.cue_zone,arange(\ self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH,\ self.current_number_of_segments*-TUNNEL_SEGMENT_LENGTH-TUNNEL_SEGMENT_LENGTH-80,\ -1))) self.auto_position_on_track = 0 self.auto_restart = False self.auto_running = True self.contTunnel() else: # Now we create the task. taskMgr is the task manager that actually # calls the function each frame. The add method creates a new task. # The first argument is the function to be called, and the second # argument is the name for the task. It returns a task object which # is passed to the function each frame. self.gameTask = taskMgr.add(self.gameLoop, "gameLoop") # self.stimulusTask = taskMgr.add(self.stimulusControl, "stimulus") self.lickTask = taskMgr.add(self.lickControl, "lick") self.rewardTask = taskMgr.add(self.rewardControl, "reward")
def __init__(self): ShowBase.__init__(self) try: concreteBg = OnscreenImage( image="img/startscreen.png", scale=(1.5, 1.5, 1) ) except: print("img/startscreen.png not found. Get it from Github.") concreteBg = None title = OnscreenText( text=gameTitle, pos=(0, 0.3), scale=0.32, font=Game.fonts["AmericanCaptain"], align=TextNode.ACenter, mayChange=False ) text = OnscreenText( text='Difficulty:', pos=(-0.1, 0), scale=0.1, font=Game.fonts["AmericanCaptain"], bg=(255, 255, 255, 0.1), align=TextNode.ARight, mayChange=False ) menu = DirectOptionMenu( scale=0.12, items=[ "Easy", "Medium", "Hard" ], initialitem=1, highlightColor=(10, 10, 10, 1), pad=(10, 10), pos=(0, 0, 0), popupMenu_pos=(-0.5, 0, 0), command=self.changeLevel, text_scale=0.8 ) startGameButton = DirectButton( text="Start Game", text_font=Game.fonts["AmericanCaptain"], scale=0.15, command=self.startGame, pad=(0.3, 0.3), pos=(0, 0, -0.32) ) spaceShortcut = OnscreenText( text='[Space]', pos=(0, -0.49), scale=0.08, font=Game.fonts["AmericanCaptain"], align=TextNode.ACenter, mayChange=False, bg=(182, 182, 182, 0.5) ) ''' helpButton = DirectButton( text="Help", text_font=Game.fonts["AmericanCaptain"], scale=0.15, command=self.showHelp, pad=(0.3, 0.3), pos=(0, 0, -0.45) ) ''' # Instructions helpText = """\ WASD/Arrow Keys to Drive | Hold Space to drift 1, 2, 3 to change camera | Hold C to look behind Hold V to look around | R to Restart """ OnscreenText( text=helpText, pos=(0, -0.7), scale=0.1, bg=(255,255,255,0.7), wordwrap=20, font=Game.fonts["AmericanCaptain"], align=TextNode.ACenter, mayChange=False ) # Next frame without clicking self.accept("space-up", self.startGame)
def __init__(self, params=None, **kwargs): # Load 3d-Model and parameter super(Panda3dViewer, self).__init__(params=params) self.world_x_range = kwargs.pop("x_range", [-40, 40]) self.world_y_range = kwargs.pop("y_range", [-40, 40]) self.follow_agent_id = kwargs.pop("follow_agent_id", -1) self.screen_dims = kwargs.pop("screen_dims", [1024, 1024]) self.path = os.path.join(os.path.dirname(os.path.abspath(__file__))) # TODO(@fortiss): load into parameter at a earlier stage self.agent_model_path = kwargs.pop("model_path", self.path + "/models/box_car") self.agent_scale = kwargs.pop("model_scale", np.array([3.65, 1.8, 0.8], dtype=float)) self.agent_orientation = \ kwargs.pop("model_orientation",np.array([180, 0,0], dtype=float)) self.agent_translation = kwargs.pop("model_translation", np.array([3.2, 0.9], dtype=float)) self.range_for_zoom = kwargs.pop("is_zoom_range", False) self.line_thicknesses = kwargs.pop("line_thickness", { #Dict of keys cameras and values [line thickness, height] which are needed to calculate the dynamic thickness -2: [0.35, 700], -1: [0.35, 700], 0: [0.1, 70] }) # Parameter for agent camera views # [driving direction offset, height, x-orientation,y-orientation,z-orientation offset to driving direction, LookAt?] self.agent_cam_parameter = kwargs.pop( "agent_view", { "bird_agent": [0, 70, 0, 270, 270, False], "third": [-35, 15, 0, 0, 0, True], "first": [1.2, 2.7, 180, 190, 90, False] }) # Set Window Size self.wp = WindowProperties().getDefault() self.wp.setSize(self.screen_dims[0], self.screen_dims[1]) self.wp.setTitle("BARK Panda3d Viewer") WindowProperties.setDefault(self.wp) ShowBase.__init__(self) # Render Objects Dict self.agent_nodes = {} # Agent Poses Dict self.agent_poses = {} self.setLight() # Creating a plane as floor #TODO parameter from map parameter frame = [ -self.screen_dims[0] / 2, self.screen_dims[0] / 2, -self.screen_dims[1] / 2, self.screen_dims[1] / 2 ] color = VBase4(self.plane_color[0], self.plane_color[1], self.plane_color[2], self.plane_alpha) self.createPlane(frame=frame, color=color) # Set up the camera loop task self.camera_list = [-1] self.initCam() self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") # Set up the line generator self.setDrawer(budget=100000) # -2 : global camera with camera control, -1: transition state for enabling mouse control, 0: agent cameras self.perspectives = { -2: ["birdview", "autozoom"], -1: ["None"], 0: ["bird_agent", "third", "first"] } self.perspective = self.perspectives[self.camIndex( self.follow_agent_id)] self.line_thickness = self.line_thicknesses[self.camIndex( self.follow_agent_id)][0] self.addButtons()
def __init__(self): ShowBase.__init__(self) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "back": 0, "up": 0} # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("EggMod/SandPlan.egg") self.environ.reparentTo(render) self.environ.setScale(20) StartPos = LVector3(0,0,94) self.movint = loader.loadModel("EggMod/HailPar.egg") self.movint.reparentTo(render) self.movint.setScale(2) self.movint.setPos(StartPos + (0, 0, 0.5)) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("arrow_down", self.setKey, ["back", True]) self.accept("f", self.setKey, ["up", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("arrow_down-up", self.setKey, ["back", False]) self.accept("f-up", self.setKey, ["up", False]) self.mopan=Pmango() self.alin = LinearEulerIntegrator() self.mopan.attachLinearIntegrator(self.alin) self.arin = AngularEulerIntegrator() self.mopan.attachAngularIntegrator(self.arin) taskMgr.add(self.move, "moveTask") self.cTrav = CollisionTraverser() #base.cTrav.setRespectPrevTransform(True) self.actMove = NodePath("ActMove") self.actMove.reparentTo(render) self.an = ActorNode("BMova") self.anp = self.actMove.attachNewNode(self.an) self.mopan.attachPhysicalNode(self.an) self.movint.reparentTo(self.anp) self.anp.node().getPhysicsObject().setMass(1) #self.an.getPhysicsObject().setTerminalVelocity(1.0) self.dvi=0 self.grava=ForceNode('GravAll') self.grar=render.attachNewNode(self.grava) self.grdi=LinearVectorForce(0.0,-0.0,-8.0) #self.grdi.setMassDependent(1) self.grava.addForce(self.grdi) #Forces have to be added to force nodes and to # a physics manager self.mopan.addLinearForce(self.grdi) self.BMoveBalance = CollisionSphere(0, 0, -7.0, 1) self.BMoveBalanceNode = CollisionNode('BMove') self.BMoveBalanceNode.addSolid(self.BMoveBalance) self.BMoveBalancePath = self.movint.attachNewNode(self.BMoveBalanceNode) self.DinGro = PhysicsCollisionHandler() self.DinGro.setStaticFrictionCoef(1) self.DinGro.setDynamicFrictionCoef(2) self.DinGro.setAlmostStationarySpeed(0.1) self.DinGro.addCollider(self.BMoveBalancePath,self.anp) #Colliders use nodepaths for collisions instead of nodes self.cTrav.addCollider(self.BMoveBalancePath, self.DinGro) # Uncomment this line to see the collision rays self.BMoveBalancePath.show() # Uncomment this line to show a visual representation of the # collisions occuring self.cTrav.showCollisions(render) # Create some lighting directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) render.setLight(render.attachNewNode(directionalLight))
def __init__(self): ShowBase.__init__(self) self.disableMouse() # sun=DirectionalLight("sun") sun.setColor((0.5, 0.5, 0.5, 1.0)) sunN=self.render.attachNewNode(sun) sunN.setHpr(-45, -45, 0) self.render.setLight(sunN) # self.terreno=self.loader.loadModel("terreno-flattened") self.terreno.reparentTo(self.render) #self.terreno.setClipPlane(plane_nodeN) # point=PointLight("foco") point.setColor((0.7, 0.7, 0.7, 1.0)) pointN=self.render.attachNewNode(point) pointN.setPos(0.0, 0.0, 0.2) self.render.setLight(pointN) # self.horrendo=self.loader.loadModel("horrendo") self.horrendo.reparentTo(self.render) self.horrendo.setPos(0.0, 0.0, 3.0) # self.hombre=self.loader.loadModel("actor.egg") self.hombre.reparentTo(self.render) self.hombre.setPos(0.0, 3.0, -0.5) # self.nivel_agua=-0.7#-0.05 self.agua=self.loader.loadModel("plano-flattened") self.agua.reparentTo(self.render) self.agua.setScale(0.75) self.agua.setTransparency(TransparencyAttrib.MAlpha) self.agua.setZ(self.nivel_agua) # self.rotador=self.render.attachNewNode("rotador") #self.rotador.setZ(self.nivel_agua) self.camera2=None self.camera3=None # self.configurar_reflejo() self.configurar_refraccion() self.configurar_dudv() self.configurar_normal() self.move_factor=0.0 # self.vel_cam=Vec2(0.0, 0.0) # self.camera.reparentTo(self.rotador) self.camera.setPos(self.agua, 10.0, -24.0, 10.0) self.camera.lookAt(self.agua) if self.camera2!=None: self.camera2.reparentTo(self.rotador) self.camera2.setPos(self.agua, 10.0, -24.0, -10.0) self.camera2.lookAt(self.agua) if self.camera3!=None: self.camera3.reparentTo(self.rotador) self.camera3.setPos(self.agua, 10.0, -24.0, 10.0) self.camera3.lookAt(self.agua) # debug info text self.texto1=OnscreenText(text="info?", pos=(0.5, 0.5), scale=0.05, mayChange=True) # shader=Shader.load(Shader.SL_GLSL, vertex="water.v.glsl", fragment="water.f.glsl") self.agua.setShader(shader) self.agua.setShaderInput("light_pos", sunN.getPos()) self.agua.setShaderInput("light_color", sun.getColor()) # self.accept("arrow_left", self.input, ["arrow_left"]) self.accept("arrow_right", self.input, ["arrow_right"]) self.accept("arrow_up", self.input, ["arrow_up"]) self.accept("arrow_down", self.input, ["arrow_down"]) self.accept("arrow_left-up", self.input, ["deactivate"]) self.accept("arrow_right-up", self.input, ["deactivate"]) self.accept("arrow_up-up", self.input, ["deactivate"]) self.accept("arrow_down-up", self.input, ["deactivate"]) # self.taskMgr.add(self.update,"update")
def __init__(self): # Load some configuration variables, its important for this to happen # before the ShowBase is initialized load_prc_file_data( "", """ textures-power-2 none gl-coordinate-system default window-title Panda3D ShaderTerrainMesh Demo # As an optimization, set this to the maximum number of cameras # or lights that will be rendering the terrain at any given time. stm-max-views 8 # Further optimize the performance by reducing this to the max # number of chunks that will be visible at any given time. stm-max-chunk-count 2048 """) # Initialize the showbase ShowBase.__init__(self) # Increase camera FOV as well as the far plane self.camLens.set_fov(90) self.camLens.set_near_far(0.1, 50000) # Construct the terrain self.terrain_node = ShaderTerrainMesh() # Set a heightfield, the heightfield should be a 16-bit png and # have a quadratic size of a power of two. heightfield = self.loader.loadTexture("heightfield.png") heightfield.wrap_u = SamplerState.WM_clamp heightfield.wrap_v = SamplerState.WM_clamp self.terrain_node.heightfield = heightfield # Set the target triangle width. For a value of 10.0 for example, # the terrain will attempt to make every triangle 10 pixels wide on screen. self.terrain_node.target_triangle_width = 10.0 # Generate the terrain self.terrain_node.generate() # Attach the terrain to the main scene and set its scale. With no scale # set, the terrain ranges from (0, 0, 0) to (1, 1, 1) self.terrain = self.render.attach_new_node(self.terrain_node) self.terrain.set_scale(1024, 1024, 100) self.terrain.set_pos(-512, -512, -70.0) # Set a shader on the terrain. The ShaderTerrainMesh only works with # an applied shader. You can use the shaders used here in your own application terrain_shader = Shader.load(Shader.SL_GLSL, "terrain.vert.glsl", "terrain.frag.glsl") self.terrain.set_shader(terrain_shader) self.terrain.set_shader_input("camera", self.camera) # Shortcut to view the wireframe mesh self.accept("f3", self.toggleWireframe) # Set some texture on the terrain grass_tex = self.loader.loadTexture("textures/grass.png") grass_tex.set_minfilter(SamplerState.FT_linear_mipmap_linear) grass_tex.set_anisotropic_degree(16) self.terrain.set_texture(grass_tex) # Load a skybox - you can safely ignore this code skybox = self.loader.loadModel("models/skybox.bam") skybox.reparent_to(self.render) skybox.set_scale(20000) skybox_texture = self.loader.loadTexture("textures/skybox.jpg") skybox_texture.set_minfilter(SamplerState.FT_linear) skybox_texture.set_magfilter(SamplerState.FT_linear) skybox_texture.set_wrap_u(SamplerState.WM_repeat) skybox_texture.set_wrap_v(SamplerState.WM_mirror) skybox_texture.set_anisotropic_degree(16) skybox.set_texture(skybox_texture) skybox_shader = Shader.load(Shader.SL_GLSL, "skybox.vert.glsl", "skybox.frag.glsl") skybox.set_shader(skybox_shader)
def __init__(self): ShowBase.__init__(self) self.mount_multifile() self.current_credits = True self.bg = OnscreenImage('/phase_1/bg.jpg') self.bg.reparentTo(render2d) scale = 0.33 self.gift = OnscreenImage('/phase_1/gift.jpg') self.gift.reparentTo(aspect2d) self.gift.setScale(scale, 1, scale * 1.77) self.gift.setPos(0.8, 0, 0) self.gift.hide() self.title = DirectLabel(self.a2dTopCenter, relief=None, text_align=TextNode.ACenter, color=(0.6, 0.6, 0.6, 0.6), pos=(0, 0, -0.15), scale=0.15, text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1), text='Can you guess the password?') self.title.setTransparency(True) self.label = DirectLabel(aspect2d, relief=None, text_align=TextNode.ACenter, pos=(0, 0, 0.2), scale=0.1, text='') self.label.setTransparency(True) self.entry = DirectEntry(aspect2d, text_align=TextNode.ACenter, scale=0.1, pos=(-0, 0, 0), width=15, focus=1) self.button = DirectButton(self.entry, text_align=TextNode.ACenter, pos=(0, 0, -2), text='Submit', command=self.attempt_decryption) self.credits = DirectButton(base.a2dBottomLeft, relief=None, text_align=TextNode.ALeft, text='C', scale=0.08, text_fg=(1, 1, 1, 1), text_shadow=(0, 0, 0, 1), pos=(0.05, 0, 0.05), command=self.open_credits) self.entry.bind(DGG.ACCEPT, self.attempt_decryption) self.music = self.loader.loadMusic('/phase_1/audio/dweller.ogg') self.playMusic(self.music, looping=True, volume=0.1) self.play_animation()
def __init__(self): # Set up the window, camera, etc. ShowBase.__init__(self) # Set the background color to black self.win.setClearColor((0, 0, 0, 1)) # This is used to store which keys are currently pressed. self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0 } # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.06, "[ESC]: Quit") self.inst2 = addInstructions(0.12, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.18, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.24, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.30, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.36, "[S]: Rotate Camera Right") # Set up the environment # # This environment model contains collision meshes. If you look # in the egg file, you will see the following: # # <Collide> { Polyset keep descend } # # This tag causes the following mesh to be converted to a collision # mesh -- a mesh which is optimized for collision, not rendering. # It also keeps the original mesh, so there are now two copies --- # one optimized for rendering, one for collisions. self.environ = loader.loadModel("models/world") self.environ.reparentTo(render) # Create the main character, Ralph ralphStartPos = self.environ.find("**/start_point").getPos() self.ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) self.ralph.reparentTo(render) self.ralph.setScale(.2) self.ralph.setPos(ralphStartPos + (0, 0, 0.5)) # Create a floater object, which floats 2 units above ralph. We # use this as a target for the camera to look at. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.ralph) self.floater.setZ(2.0) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", True]) self.accept("arrow_right", self.setKey, ["right", True]) self.accept("arrow_up", self.setKey, ["forward", True]) self.accept("a", self.setKey, ["cam-left", True]) self.accept("s", self.setKey, ["cam-right", True]) self.accept("arrow_left-up", self.setKey, ["left", False]) self.accept("arrow_right-up", self.setKey, ["right", False]) self.accept("arrow_up-up", self.setKey, ["forward", False]) self.accept("a-up", self.setKey, ["cam-left", False]) self.accept("s-up", self.setKey, ["cam-right", False]) taskMgr.add(self.move, "moveTask") # Game state variables self.isMoving = False # Set up the camera self.disableMouse() self.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2) # We will detect the height of the terrain by creating a collision # ray and casting it downward toward the terrain. One ray will # start above ralph's head, and the other will start above the camera. # A ray may hit the terrain, or it may hit a rock or a tree. If it # hits the terrain, we can detect the height. If it hits anything # else, we rule that the move is illegal. self.cTrav = CollisionTraverser() self.ralphGroundRay = CollisionRay() self.ralphGroundRay.setOrigin(0, 0, 9) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(CollideMask.bit(0)) self.ralphGroundCol.setIntoCollideMask(CollideMask.allOff()) self.ralphGroundColNp = self.ralph.attachNewNode(self.ralphGroundCol) self.ralphGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.ralphGroundColNp, self.ralphGroundHandler) self.camGroundRay = CollisionRay() self.camGroundRay.setOrigin(0, 0, 9) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(CollideMask.bit(0)) self.camGroundCol.setIntoCollideMask(CollideMask.allOff()) self.camGroundColNp = self.camera.attachNewNode(self.camGroundCol) self.camGroundHandler = CollisionHandlerQueue() self.cTrav.addCollider(self.camGroundColNp, self.camGroundHandler) # Uncomment this line to see the collision rays #self.ralphGroundColNp.show() #self.camGroundColNp.show() # Uncomment this line to show a visual representation of the # collisions occuring #self.cTrav.showCollisions(render) # Create some lighting ambientLight = AmbientLight("ambientLight") ambientLight.setColor((.3, .3, .3, 1)) directionalLight = DirectionalLight("directionalLight") directionalLight.setDirection((-5, -5, -5)) directionalLight.setColor((1, 1, 1, 1)) directionalLight.setSpecularColor((1, 1, 1, 1)) render.setLight(render.attachNewNode(ambientLight)) render.setLight(render.attachNewNode(directionalLight))
def init_EMG(self): ### call init of base class ShowBase ShowBase.__init__(self) ### this if condition includes all the commands that only have to be called when EMG is used ### the commands afterwards, i.e. all the init of Panda, have to be done for only EEG as well, because the taskmanager is used if self.mode == "EMG" or self.mode == "HYBRID": self.EMG_pos_choices = ["fist", "pinch_2", "pinch_3"] ### check inputs, whether the size is acceptable self.num_pos = len(self.EMG_pos_choices) if self.trials_notlive > self.trial_count: raise ValueError( "'trials_notlive' cannot be larger than 'trials'") if self.force_classify == True: # case when force shall be classified as well if self.trial_count % (2 * self.num_pos): raise ValueError("'trials' must be devisable by ", 2 * self.num_pos) if self.trials_notlive % (2 * self.num_pos): raise ValueError("'trials_notlive' must be devisable by ", 2 * self.num_pos) self.EMG_trial_count_for_each_cue_pos = self.trial_count // self.num_pos // 2 self.EMG_trial_count_for_each_cue_pos_notlive = self.trials_notlive // self.num_pos // 2 print("\nFirst, please apply strong force for ", self.trials_notlive // 2, " trials.\n", \ "Afterwards, please apply weak force for ", self.trials_notlive // 2, "trials.\n" ) else: # noone cares about force, only posture if self.trial_count % self.num_pos: raise ValueError("'trials' must be devisable by ", self.num_pos) if self.trials_notlive % self.num_pos: raise ValueError("'trials_notlive' must be devisable by ", self.num_pos) self.EMG_trial_count_for_each_cue_pos = self.trial_count // self.num_pos self.EMG_trial_count_for_each_cue_pos_notlive = self.trials_notlive // self.num_pos ### Generate position lists for both live and notlive trials self.EMG_cue_pos_choices_notlive = [ x for pair in zip(self.EMG_pos_choices * self.EMG_trial_count_for_each_cue_pos_notlive) for x in pair ] self.EMG_cue_pos_choices_live = [ x for pair in zip(self.EMG_pos_choices * (self.EMG_trial_count_for_each_cue_pos - self.EMG_trial_count_for_each_cue_pos_notlive)) for x in pair ] # Randomizing the positions random.shuffle(self.EMG_cue_pos_choices_notlive) random.shuffle(self.EMG_cue_pos_choices_live) if self.force_classify == True: # repeat the exact same testing procedure -->once strong and once weak self.EMG_cue_pos_choices_notlive = self.EMG_cue_pos_choices_notlive + self.EMG_cue_pos_choices_notlive #.append(self.cue_pos_choices_notlive) self.EMG_cue_pos_choices_live = self.EMG_cue_pos_choices_live + self.EMG_cue_pos_choices_live #.append(self.cue_pos_choices_live) self.EMG_trial_count_for_each_cue_pos = self.EMG_trial_count_for_each_cue_pos * 2 self.EMG_trial_count_for_each_cue_pos_notlive = self.EMG_trial_count_for_each_cue_pos_notlive * 2 print("\nNot live trials:") print(self.EMG_cue_pos_choices_notlive) print("\nLive trials:") print(self.EMG_cue_pos_choices_live, '\n') #Add of a position to avoid data loss, because pop(0) is used self.EMG_cue_pos_choices_notlive.append('end') self.EMG_cue_pos_choices_live.append('end') ### initialise the RecordData thread and the RobotHand self.record_data_EMG = RecordData_liveEMG(self.Fs, self.age, self.gender, with_feedback=False) self.record_data_EMG.start_recording() try: self.robothand = RobotHand( port="COM6") #"COM4" on Windows measurement PC self.robothandconnected = 1 except: print('Robothand not connected. Output only to console') self.robothandconnected = 0 ### initialise tasks, including Panda and the run_trial task ### this one is required for only EEG as well, because the taskmanager is used as well # Add the spinCameraTask procedure to the task manager. self.taskMgr.add(self.spinCameraTask, "SpinCameraTask") # Add the run_trial procedure to the task manager self.taskMgr.add(self.run_trial, "run_trial_task") # Load and transform the panda actor. self.pandaActor = Actor("models/Hand") scale = 10 self.pandaActor.setScale(scale, scale, scale) self.pandaActor.reparentTo(self.render) self.pandaActor.setPos(7.9, 1.5, -14.5) ### init variables to be used lateron self.EMG_filename_notlive = "" self.cwd = os.getcwd() self.datapath = self.cwd self.EMG_current_classifier = [] self.EMG_true = 0 self.EMG_false = 0
def __init__(self): # Initialize the ShowBase class from which we inherit, which will # create a window and set up everything we need for rendering into it. ShowBase.__init__(self) # This code puts the standard title and instruction text on screen self.title = OnscreenText( text="Panda3D: Tutorial - Joint Manipulation", fg=(1, 1, 1, 1), parent=base.a2dBottomRight, align=TextNode.ARight, pos=(-0.1, 0.1), shadow=(0, 0, 0, .5), scale=.08) self.onekeyText = genLabelText("ESC: Quit", 1) self.onekeyText = genLabelText("[1]: Teapot", 2) self.twokeyText = genLabelText("[2]: Candy cane", 3) self.threekeyText = genLabelText("[3]: Banana", 4) self.fourkeyText = genLabelText("[4]: Sword", 5) # Set up key input self.accept('escape', sys.exit) self.accept('1', self.switchObject, [0]) self.accept('2', self.switchObject, [1]) self.accept('3', self.switchObject, [2]) self.accept('4', self.switchObject, [3]) base.disableMouse() # Disable mouse-based camera-control camera.setPos(0, -15, 2) # Position the camera self.eve = Actor( "models/eve", # Load our animated charachter {'walk': "models/eve_walk"}) self.eve.reparentTo(render) # Put it in the scene # Now we use controlJoint to get a NodePath that's in control of her neck # This must be done before any animations are played self.eveNeck = self.eve.controlJoint(None, 'modelRoot', 'Neck') # We now play an animation. An animation must be played, or at least posed # for the nodepath we just got from controlJoint to actually effect the # model self.eve.actorInterval("walk", playRate=2).loop() # Now we add a task that will take care of turning the head taskMgr.add(self.turnHead, "turnHead") # Now we will expose the joint the hand joint. ExposeJoint allows us to # get the position of a joint while it is animating. This is different than # controlJonit which stops that joint from animating but lets us move it. # This is particularly usefull for putting an object (like a weapon) in an # actor's hand self.rightHand = self.eve.exposeJoint(None, 'modelRoot', 'RightHand') # This is a table with models, positions, rotations, and scales of objects to # be attached to our exposed joint. These are stock models and so they needed # to be repositioned to look right. positions = [("teapot", (0, -.66, -.95), (90, 0, 90), .4), ("models/candycane", (.15, -.99, -.22), (90, 0, 90), 1), ("models/banana", (.08, -.1, .09), (0, -90, 0), 1.75), ("models/sword", (.11, .19, .06), (0, 0, 90), 1)] self.models = [] # A list that will store our models objects for row in positions: np = loader.loadModel(row[0]) # Load the model np.setPos(row[1][0], row[1][1], row[1][2]) # Position it np.setHpr(row[2][0], row[2][1], row[2][2]) # Rotate it np.setScale(row[3]) # Scale it # Reparent the model to the exposed joint. That way when the joint moves, # the model we just loaded will move with it. np.reparentTo(self.rightHand) self.models.append(np) # Add it to our models list self.switchObject(0) # Make object 0 the first shown self.setupLights() # Put in some default lighting
def __init__(self): DebugObject.__init__(self, "Main") self.debug("Bit System =", 8 * struct.calcsize("P")) # Load engine configuration self.debug("Loading panda3d configuration from configuration.prc ..") loadPrcFile("../../Config/configuration.prc") # Init the showbase ShowBase.__init__(self) # Create the render pipeline self.debug("Creating pipeline") self.renderPipeline = RenderingPipeline(self) # Set a write directory, where the shader cache and so on is stored # self.renderPipeline.getMountManager().setWritePath(writeDirectory) self.renderPipeline.getMountManager().setBasePath("../../") self.renderPipeline.loadSettings("../../Config/pipeline.ini") # Create the pipeline, and enable scattering self.renderPipeline.create() self.renderPipeline.enableDefaultEarthScattering() # Load some demo source self.sceneSource = "Models/SmoothCube/Cube.bam" # Load scene from disk self.debug("Loading Scene '" + self.sceneSource + "'") self.model = self.loader.loadModel(self.sceneSource) self.scene = render.attachNewNode("Scene") self.model.reparentTo(self.scene) self.model.setZ(1.0) # Wheter to use a ground floor self.usePlane = True self.sceneWireframe = False # Flatten scene self.scene.flattenStrong() # Load ground plane if configured if self.usePlane: self.groundPlane = self.loader.loadModel( "Models/Plane/Model.egg.bam") self.groundPlane.setPos(0, 0, 0) self.groundPlane.setScale(2.0) self.groundPlane.setTwoSided(True) self.groundPlane.flattenStrong() self.groundPlane.reparentTo(self.scene) # Prepare textures with SRGB format self.prepareSRGB(self.scene) # Create movement controller (Freecam) self.controller = MovementController(self) self.controller.setInitialPosition(Vec3(0, -5, 5.0), Vec3(0, 0, 5)) self.controller.setup() # Hotkey for wireframe self.accept("f3", self.toggleSceneWireframe) # Hotkey to reload all shaders self.accept("r", self.setShaders) # Create a sun light dPos = Vec3(60, 30, 100) dirLight = DirectionalLight() dirLight.setDirection(dPos) dirLight.setShadowMapResolution(2048) dirLight.setAmbientColor(Vec3(0.0, 0.0, 0.0)) dirLight.setPos(dPos) dirLight.setColor(Vec3(3)) dirLight.setPssmTarget(base.cam, base.camLens) dirLight.setPssmDistance(50.0) dirLight.setCastsShadows(True) self.renderPipeline.addLight(dirLight) self.dirLight = dirLight sunPos = Vec3(56.7587, -31.3601, 189.196) self.dirLight.setPos(sunPos) self.dirLight.setDirection(sunPos) # Tell the GI which light casts the GI self.renderPipeline.setGILightSource(dirLight) # Slider to move the sun if self.renderPipeline.settings.displayOnscreenDebugger: self.renderPipeline.guiManager.demoSlider.node[ "command"] = self.setSunPos self.renderPipeline.guiManager.demoSlider.node["value"] = 20 self.lastSliderValue = 0.0 # Load skyboxn self.skybox = None self.loadSkybox() # Set default object shaders self.setShaders(refreshPipeline=False) self.createGUI()
def __init__(self): ShowBase.__init__(self) self.title = OnscreenText(text="Das Leben")
def __init__(self): ShowBase.__init__(self) ''' concreteBg = OnscreenImage( image="img/startscreen.png", scale=(1.5, 1.5, 1) ) ''' title = OnscreenText( text='Select your Racetrack!', pos=(0, 0.65), scale=0.18, font=Game.fonts["AmericanCaptain"], bg=(255, 255, 255, 1), align=TextNode.ACenter, mayChange=False ) nextButton = DirectButton( text="Next", text_font=Game.fonts["AmericanCaptain"], scale=0.10, command=self.selectCar, pad=(0.3, 0.3), pos=(0, 0, -0.8) ) spaceShortcut = OnscreenText( text='[Space]', pos=(0, -0.93), scale=0.07, font=Game.fonts["AmericanCaptain"], align=TextNode.ACenter, mayChange=False, bg=(182, 182, 182, 0.5), ) # Get List of tracks self.tracks = self.findTracks("racetracks") initialItem = self.tracks.index(Game.selectedTrack) # Minimap! points = Racetrack.parseTrackFile(Game.selectedTrack) self.minimap = Minimap(points, renderer=self.render) self.selectTrack(self.tracks[initialItem]) self.menu = DirectOptionMenu( scale=0.15, items=self.tracks, initialitem=initialItem, highlightColor=(10, 10, 10, 1), pad=(10, 10), pos=(-0.5, 0, 0.35), popupMenu_pos=(-0.5, 0, 0.2), command=self.selectTrack ) helperText = OnscreenText( text='Click and drag anywhere to view the 3D track!', pos=(0, -0.6), scale=0.08, font=Game.fonts["AmericanCaptain"], align=TextNode.ACenter, mayChange=False, bg=(182, 182, 182, 0.5), ) randomiseButton = DirectButton( text="New Random Track", text_font=Game.fonts["AmericanCaptain"], scale=0.10, command=self.randomiseTrack, pad=(0.3, 0.3), pos=(-0.9, 0, 0.35) ) self.randomText = OnscreenText( text='', pos=(-0.9, 0.20), scale=0.07, font=Game.fonts["AmericanCaptain"], align=TextNode.ACenter, mayChange=True, bg=(182, 182, 182, 0.5), ) # Next frame without clicking self.accept("space-up", self.selectCar)
def __init__(self): ShowBase.__init__(self) base.set_background_color(0.1, 0.1, 0.8, 1) base.set_frame_rate_meter(True) base.cam.set_pos_hpr(0, 0, 25, 0, -90, 0) base.disable_mouse() # Input self.accept('escape', self.exitGame) self.accept('f1', base.toggle_wireframe) self.accept('f2', base.toggle_texture) self.accept('f3', self.toggle_debug) self.accept('f5', self.do_screenshot) # Setup scene 1: World self.debugNP = render.attach_new_node(BulletDebugNode('Debug')) self.debugNP.node().show_wireframe(True) self.debugNP.node().show_constraints(True) self.debugNP.node().show_bounding_boxes(True) self.debugNP.node().show_normals(True) self.debugNP.show() self.world = BulletWorld() self.world.set_gravity(LVector3(0, 0, -9.81)) self.world.set_debug_node(self.debugNP.node()) # Setup scene 2: Ball #visNP = loader.load_model('models/ball.egg') visNP = loader.load_model('samples/ball-in-maze/models/ball.egg.pz') visNP.clear_model_nodes() bodyNPs = BulletHelper.from_collision_solids(visNP, True) self.ballNP = bodyNPs[0] self.ballNP.reparent_to(render) self.ballNP.node().set_mass(1.0) self.ballNP.set_pos(4, -4, 1) self.ballNP.node().set_deactivation_enabled(False) visNP.reparent_to(self.ballNP) # Setup scene 3: Maze visNP = loader.load_model('models/maze.egg') #visNP = loader.load_model('samples/ball-in-maze/models/maze.egg.pz') visNP.clear_model_nodes() visNP.reparent_to(render) self.holes = [] self.maze = [] self.mazeNP = visNP bodyNPs = BulletHelper.from_collision_solids(visNP, True); for bodyNP in bodyNPs: bodyNP.reparent_to(render) if isinstance(bodyNP.node(), BulletRigidBodyNode): bodyNP.node().set_mass(0.0) bodyNP.node().set_kinematic(True) self.maze.append(bodyNP) elif isinstance(bodyNP.node(), BulletGhostNode): self.holes.append(bodyNP) # Lighting and material for the ball ambientLight = AmbientLight('ambientLight') ambientLight.set_color(LVector4(0.55, 0.55, 0.55, 1)) directionalLight = DirectionalLight('directionalLight') directionalLight.set_direction(LVector3(0, 0, -1)) directionalLight.set_color(LVector4(0.375, 0.375, 0.375, 1)) directionalLight.set_specular_color(LVector4(1, 1, 1, 1)) self.ballNP.set_light(render.attach_new_node(ambientLight)) self.ballNP.set_light(render.attach_new_node(directionalLight)) m = Material() m.set_specular(LVector4(1,1,1,1)) m.set_shininess(96) self.ballNP.set_material(m, 1) # Startup self.start_game()
def __init__(self): # Load some configuration variables, its important for this to happen # before the ShowBase is initialized load_prc_file_data( "", """ textures-power-2 none window-title Panda3D Shader Terrain Demo """) # Initialize the showbase ShowBase.__init__(self) # Increase camera FOV aswell as the far plane self.camLens.set_fov(90) self.camLens.set_near_far(0.1, 50000) # Construct the terrain self.terrain_node = ShaderTerrainMesh() # Set a heightfield, the heightfield should be a 16-bit png and # have a quadratic size of a power of two. self.terrain_node.heightfield_filename = "heightfield.png" # Set the target triangle width. For a value of 10.0 for example, # the terrain will attempt to make every triangle 10 pixels wide on screen. self.terrain_node.target_triangle_width = 10.0 # Generate the terrain self.terrain_node.generate() # Attach the terrain to the main scene and set its scale self.terrain = self.render.attach_new_node(self.terrain_node) self.terrain.set_scale(1024, 1024, 100) self.terrain.set_pos(-512, -512, -70.0) # Set a shader on the terrain. The ShaderTerrainMesh only works with # an applied shader. You can use the shaders used here in your own shaders terrain_shader = Shader.load(Shader.SL_GLSL, "terrain.vert.glsl", "terrain.frag.glsl") self.terrain.set_shader(terrain_shader) self.terrain.set_shader_input("camera", self.camera) # Set some texture on the terrain grass_tex = self.loader.loadTexture("textures/grass.png") grass_tex.set_minfilter(SamplerState.FT_linear_mipmap_linear) grass_tex.set_anisotropic_degree(16) self.terrain.set_texture(grass_tex) # Load some skybox - you can safely ignore this code skybox = self.loader.loadModel("models/skybox.bam") skybox.reparent_to(self.render) skybox.set_scale(20000) skybox_texture = self.loader.loadTexture("textures/skybox.jpg") skybox_texture.set_minfilter(SamplerState.FT_linear) skybox_texture.set_magfilter(SamplerState.FT_linear) skybox_texture.set_wrap_u(SamplerState.WM_repeat) skybox_texture.set_wrap_v(SamplerState.WM_mirror) skybox_texture.set_anisotropic_degree(16) skybox.set_texture(skybox_texture) skybox_shader = Shader.load(Shader.SL_GLSL, "skybox.vert.glsl", "skybox.frag.glsl") skybox.set_shader(skybox_shader)
def __init__(self): ShowBase.__init__(self) title = OnscreenText( text='Select your Racecar and Passenger!', pos=(0, 0.7), scale=0.18, font=Game.fonts["AmericanCaptain"], bg=(255, 255, 255, 1), align=TextNode.ACenter, mayChange=False ) nextButton = DirectButton( text="Next", text_font=Game.fonts["AmericanCaptain"], scale=0.10, command=self.startGame, pad=(0.3, 0.3), pos=(0, 0, -0.8) ) spaceShortcut = OnscreenText( text='[Space]', pos=(0, -0.93), scale=0.07, font=Game.fonts["AmericanCaptain"], align=TextNode.ACenter, mayChange=False, bg=(182, 182, 182, 0.5), ) # Get List of cars self.cars = self.findCarsOrPassengers("models", "car_") initialCar = self.cars.index(Game.selectedCar) text = OnscreenText( text='Racecar:', pos=(-0.55, 0.4), scale=0.1, font=Game.fonts["AmericanCaptain"], bg=(255, 255, 255, 1), align=TextNode.ARight, mayChange=False ) menu = DirectOptionMenu( scale=0.15, items=self.cars, initialitem=initialCar, highlightColor=(10, 10, 10, 1), pad=(10, 10), pos=(-0.5, 0, 0.4), command=self.selectCar ) # Get List of passengers self.passengers = self.findCarsOrPassengers("models", "passenger_") initialPassenger = self.passengers.index(Game.selectedPassenger) text = OnscreenText( text='Passenger:', pos=(-0.55, 0.2), scale=0.1, font=Game.fonts["AmericanCaptain"], bg=(255, 255, 255, 1), align=TextNode.ARight, mayChange=False ) menu = DirectOptionMenu( scale=0.15, items=self.passengers, initialitem=initialPassenger, highlightColor=(10, 10, 10, 1), pad=(10, 10), pos=(-0.5, 0, 0.2), command=self.selectPassenger ) # If drawing is needed, passenger needs to be selected first self.displayedCar = None self.selectPassenger(self.passengers[initialPassenger]) self.selectCar(self.cars[initialCar]) # Next frame without clicking self.accept("space-up", self.startGame) # Add task to spin camera self.taskMgr.add(self.carShowcase, "CarShowcase")