def init( run_server=False, run_client=False, local_only=False, log_filename=None, log_level='info', window_title='SpaceDrive' ): """Call first. This will set up the initial engine state""" loadPrcFileData("", "notify-level-SpaceDrive " + log_level) if log_level == 'debug': log.setSeverity(2) if log_level == 'info': log.setSeverity(3) if log_level == 'warning': log.setSeverity(4) log.info("Init SpaceDrive") log.debug("Bitness = " + str(8 * struct.calcsize("P"))) universals.run_server = run_server universals.run_client = run_client if log_filename: mstream = MultiplexStream() mstream.addFile(logFilename) mstream.addStandardOutput() Notify.ptr().setOstreamPtr(mstream, False) # Also make Python output go to the same place. sw = StreamWriter(mstream, False) sys.stdout = sw sys.stderr = sw # Since we're writing to a log file, turn on timestamping. loadPrcFileData('', 'notify-timestamp 1') if not run_client: # Don't open a graphics window on the server. (Open a window only # if we're running a normal client, not one of the server # processes.) loadPrcFileData('', 'window-type none\naudio-library-name null') else: loadPrcFile("configuration.prc") loadPrcFileData('', 'frame-rate-meter-scale 0.035') loadPrcFileData('', 'frame-rate-meter-side-margin 0.1') loadPrcFileData('', 'show-frame-rate-meter 1') loadPrcFileData('', 'window-title ' + window_title) loadPrcFileData('', "sync-video 0") loadPrcFileData('', 'task-timer-verbose 1') loadPrcFileData('', 'pstats-tasks 1') loadPrcFileData('', 'want-pstats 1') loadPrcFileData("", "textures-power-2 none") log.info("Loading Sandbox") sandbox.init(log_level=log_level) global base base = sandbox.base
def __init__(self): # Load the default configuration.prc. This is recommended, as it # contains some important panda options loadPrcFile("../../Config/configuration.prc") # Init the showbase ShowBase.__init__(self) # Create a new pipeline instance self.renderPipeline = RenderingPipeline(self) # Set the base path for the pipeline. This is required as we are in # a subdirectory self.renderPipeline.getMountManager().setBasePath("../../") # Also set the write path self.renderPipeline.getMountManager().setWritePath("../../Temp/") # Load the default settings self.renderPipeline.loadSettings("../../Config/pipeline.ini") # Now create the pipeline self.renderPipeline.create() # Enable atmospheric scattering self.renderPipeline.enableDefaultEarthScattering()
def __init__(self): loadPrcFile('config.prc') ShowBase.__init__(self) base.disableMouse() self.render.setShaderAuto() self.accept("escape", sys.exit) # Model model = self.loader.loadModel("twisted") model.reparent_to(self.render) self.model = model # For reference in the rotation task # Light light = Spotlight('light') light_np = self.render.attachNewNode(light) light_np.set_pos(25, 25, 25) light_np.look_at(0, 0, 0) # Model-light interaction light.setShadowCaster(True) light.getLens().setNearFar(1, 50) self.render.setLight(light_np) # Camera self.camera.set_pos(0, -60, 30) self.camera.look_at(0, 0, 0) # Rotating the object self.taskMgr.add(self.rotate_object, 'rotate object') self.render.setAntialias(AntialiasAttrib.MMultisample)
def __init__(self): # Load the default configuration.prc. This is recommended, as it # contains some important panda options loadPrcFile("../../Config/configuration.prc") # Init the showbase ShowBase.__init__(self) # Create a new pipeline instance self.renderPipeline = RenderingPipeline(self) # Set the base path for the pipeline. This is required as we are in # a subdirectory self.renderPipeline.getMountManager().setBasePath("../../") # Also set the write path self.renderPipeline.getMountManager().setWritePath("../../Temp/") # Load the default settings self.renderPipeline.loadSettings("../../Config/pipeline.ini") # Now create the pipeline self.renderPipeline.create() # Load the skybox self.skybox = self.renderPipeline.getDefaultSkybox() self.skybox.reparentTo(render) # At this point we are done with the initialization. Now you want to # load your scene, and create the game logic. # Call this to tell the pipeline that the scene is done loading self.renderPipeline.onSceneInitialized()
def initPanda(self): if hasattr(self, 'panda'): # Allow multiple entry return if self.do is None: self.do = DirectObject() # The undecorated config option can't be changed at runtime, so we need # to set it before the panda object is created. if self.displaySettings.displayMode == NO_BORDER: loadPrcFileData('', 'undecorated 1') # The resolution /can/ be changed at runtime, but there's a split second # flash of the window at the defualt resolution when first opening the # game which looks quite ugly. loadPrcFileData('', 'win-size %d %d' % self.displaySettings.size) loadPrcFile(data.getPandaPath(data, 'config/config.prc')) self.panda = ShowBase.ShowBase() self.pandaScene = None # See https://www.panda3d.org/manual/index.php/Mouse_Support self.panda.disableMouse() # Name is misleading self.displaySettings.applyTimings() self.initPlaque() self.displaySettings.onDetailLevelChanged.addListener(self.setShader) self.setShader()
def panda_config(self): data = [] request_opengl_config(data) self.app_panda_config(data) data.append("text-encoding utf8") data.append("paste-emit-keystrokes #f") #TODO: Still needed ? data.append("bounds-type box") data.append("screenshot-extension png") data.append("screenshot-filename %~p-%Y-%m-%d-%H-%M-%S-%~f.%~e") data.append("fullscreen %d" % settings.win_fullscreen) if settings.win_fullscreen: data.append("win-size %d %d" % (settings.win_fs_width, settings.win_fs_height)) else: data.append("win-size %d %d" % (settings.win_width, settings.win_height)) data.append("lens-far-limit %g" % settings.lens_far_limit) loadPrcFileData("", '\n'.join(data)) if settings.prc_file is not None: config_file = settings.prc_file if not os.path.isabs(config_file): config_file = os.path.join(settings.config_dir, config_file) filename = Filename.from_os_specific(config_file) if filename.exists(): print("Loading panda config", filename) loadPrcFile(filename) else: print("Panda config file", filename)
def __init__(self): loadPrcFile("config/Config.prc") ShowBase.__init__(self) self.debugOnscreenText = OnscreenText( style=1, fg=(1, 1, 1, 1), align=0, pos=(-1, -0.95), scale=0.05, text="Test" ) self.setBackgroundColor(0.0, 0.0, 0.0) self._setupBasicCamera() self._setupKeyboardEvents() self._setupMouseEvents() self._setupCoreTasks()
def __init__(self): self.hasConfig = False # if exist load the config file if os.path.exists(prcFile): loadPrcFile(Filename.fromOsSpecific(prcFile)) self.hasConfig = True # set the variables using the config files content or set a default value self.UDPPORT = ConfigVariableInt('udp-port', '6002').getValue() self.TCPPORT = ConfigVariableInt('tcp-port', '6000').getValue() self.UDPPORTSERVER = ConfigVariableInt('udp-port-server', '6001').getValue() self.SERVERIP = ConfigVariableString('server-ip', '127.0.0.1').getValue() self.TIMEOUT = ConfigVariableInt('timeout-in-ms', '3000').getValue()
def __init__(self): loadPrcFile("config/Config.prc") ShowBase.__init__(self) self.camera = self.makeCamera(self.win) #self.render.setAntialias(AntialiasAttrib.MMultisample) self.setBackgroundColor(0.0,0.0,0.0) #Mouse position text self.posText = OnscreenText(\ style=1, fg=(1,1,1,1), pos=(0.8,-0.95), scale = .07) #self.toggleWireframe() self._setupKeyboardEvents() # Load and transform the panda actor. self.render.setTransparency(TransparencyAttrib.MAlpha) self.tile1 = Tile("tile1",0.0,0.0) node1 = self.render.attachNewNode(self.tile1) self.tile2 = Tile("tile2",0.064,0.032) node2 = self.render.attachNewNode(self.tile2) texture = self.loader.loadTexture('artwork/sample.png') #node.setTwoSided(True) ts = TextureStage('ts') #ts.setMode(TextureStage.MNormal) node1.setTexture(ts, texture, 1) node2.setTexture(ts, texture, 1) myMaterial = Material() myMaterial.setShininess(0.0) #Make this material shiny myMaterial.setAmbient(VBase4(0.0,0.0,0.0,1)) #Make this material blue node1.setMaterial(myMaterial) node2.setMaterial(myMaterial) self.camera.setPos(0, 0, 2) self.camera.setHpr(0, -95, 0) plight = PointLight('plight') plight.setColor(VBase4(0.8, 0.8, 0.2, 1)) plnp = self.render.attachNewNode(plight) plnp.setPos(0.128, 0.064, -0.8) plight.setAttenuation(Point3(0.23, 0.23, 0.25)) self.render.setLight(plnp) self.alight = self.render.attachNewNode(AmbientLight("Ambient")) self.alight.node().setColor(Vec4(0.1, 0.1, 0.1, 1)) self.render.setLight(self.alight) self.render.setShaderAuto()
def __init__(self): # Load the prc file prior to launching showbase in order # to have it affect window related stuff loadPrcFile("Configrc.prc") builtins.userfiles = self.config.GetString('userfiles-directory') if not os.path.exists(userfiles): pathlib.Path(userfiles).mkdir(parents = True, exist_ok = True) # Check for -e or -d launch options parser = argparse.ArgumentParser(description = "Modes") parser.add_argument("--experimental", action = 'store_true', help = "Enables experimental features") parser.add_argument("--debug", action = 'store_true', help = "Enables debugging features") parser.add_argument("--noupdate", action = 'store_true', help = "Disables Auto Updating") parser.add_argument("--server", nargs = "*", help = "Enables features exclusive to various Toontown projects", default = 'online') parser.add_argument("--holiday", nargs = "*", help = "Enables holiday modes. [halloween or winter]") parser.add_argument("--hoods", nargs = "*", help = "Only loads the storage files of the specified hoods", default = ['TT', 'DD', 'BR', 'DG', 'DL', 'MM', 'GS', 'GZ', 'SBHQ', 'LBHQ', 'CBHQ', 'BBHQ', 'OZ', 'PA', 'ES', 'TUT']) args = parser.parse_args() if args.experimental: loadPrcFileData("", "want-experimental true") if args.debug: loadPrcFileData("", "want-debug true") server = SERVER_TO_ID.get(args.server[0].lower(), DEFAULT_SERVER) self.server = server self.hoods = args.hoods # HACK: Check for dnaPath in args.hoods for hood in self.hoods[:]: if hood.endswith('.dna'): args.dnaPath = hood args.hoods.remove(hood) break ShowBase.ShowBase.__init__(self) # Import the main dlls so we don't have to repeatedly import them everywhere builtins.__dict__.update(__import__('panda3d.core', fromlist=['*']).__dict__) builtins.__dict__.update(__import__('libotp', fromlist=['*']).__dict__) builtins.__dict__.update(__import__('libtoontown', fromlist=['*']).__dict__) self.startDirect(1, 1, 0) from toontown.toon import RobotToonManager base.rtm = RobotToonManager.RobotToonManager() base.rtm.popupControls() camera.setPosHpr(0, -60, 5, 0, 0, 0)
def main(): #!/usr/bin/env python # -*- coding: utf-8 -*- # Panda Imports from panda3d.core import loadPrcFile # Load the PRC Configuration FIle loadPrcFile("orbital.prc") t = Simulation() t.run()
def __init__(self): from panda3d.core import loadPrcFile loadPrcFile("cfg/config_client.prc") BSPBase.__init__(self) self.createShaderGenerator() self.createPostProcess() self.loadBSPLevel("maps/example.bsp") self.enableMouse() self.camLens.setMinFov(70.0 / (4. / 3.))
def __init__(self): self.hasConfig = False # if exist load the config file if os.path.exists(prcFile): self.hasConfig = True loadPrcFile(Filename.fromOsSpecific(prcFile)) # set the variables using the config files content or set a default value self.MOTD = ConfigVariableString('motd', 'Welcome to net_core!').getValue() self.HOSTNAME = ConfigVariableString('hostname', '127.0.0.1').getValue() self.TCPPORT = ConfigVariableInt('tcp-port', '6000').getValue() self.BACKLOG = ConfigVariableInt('backlog', '10').getValue() self.UDPPORT = ConfigVariableInt('udp-port', '6001').getValue() self.ISPERSISTENT = ConfigVariableInt('isPersistent', '0').getValue()
def WritePRCFile(self): page = None customConfigVariables = ["", "motd", "hostname", "tcp-port", "backlog", "udp-port", "isPersistent"] if os.path.exists(prcFile): # load the existing config file page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) else: # create a new config file cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("Net Core Pandaconfig") # config declarations page.makeDeclaration("motd", str(self.MOTD)) page.makeDeclaration("hostname", str(self.HOSTNAME)) page.makeDeclaration("tcp-port", str(self.TCPPORT)) page.makeDeclaration("backlog", str(self.BACKLOG)) page.makeDeclaration("udp-port", str(self.UDPPORT)) page.makeDeclaration("isPersistent", str(self.ISPERSISTENT)) # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
def WritePRCFile(self): page = None customConfigVariables = ["", "tcp-port","udp-port", "server-port", "server-ip","timeout-in-ms"] if os.path.exists(prcFile): # load the existing config file page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) else: # create a new config file cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("Grim Net Pandaconfig") # config declarations page.makeDeclaration("udp-port", str(self.UDPPORT)) page.makeDeclaration("tcp-port", str(self.TCPPORT)) page.makeDeclaration("server-port", str(self.UDPPORTSERVER)) page.makeDeclaration("server-ip", str(self.SERVERIP)) page.makeDeclaration("timeout-in-ms", str(self.TIMEOUT)) # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
def __init__(self): self.prc = loadPrcFile(self.CONF_FILE) self.egg = Path(op.dirname(self.CONF_FILE)) / ".." / ".." / "egg" self.tex = Path(op.dirname(self.CONF_FILE)) / ".." / ".." / "tex" self.bam = Path(op.dirname(self.CONF_FILE)) / ".." / ".." / "bam" self.sfx = Path(op.dirname(self.CONF_FILE)) / ".." / ".." / "sfx" self.ass = Path(op.dirname(self.CONF_FILE)) / ".." / ".." / "assets"
def __writeConfig(self): """Save current config in the prc file or if no prc file exists create one. The prc file is set in the prcFile variable""" page = None # These TODO tags are as a reminder for to add any new config # variables that may occur in the future #TODO: get values of configurations here particles = "#f" if not base.particleMgrEnabled else "#t" volume = str(round(base.musicManager.getVolume(), 2)) mute = "#f" if base.AppHasAudioFocus else "#t" #TODO: add any configuration variable name that you have added customConfigVariables = [ "", "particles-enabled", "audio-mute", "audio-volume" ] if os.path.exists(prcFile): # open the config file and change values according to current # application settings page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) # NOTE: particles-enabled and audio-mute are custom variables and # have to be loaded by hand at startup # Particles page.makeDeclaration("particles-enabled", particles) # audio page.makeDeclaration("audio-volume", volume) page.makeDeclaration("audio-mute", mute) else: # Create a config file and set default values cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("{} Pandaconfig".format(appName)) # set OpenGL to be the default page.makeDeclaration("load-display", "pandagl") # get the displays width and height w = self.pipe.getDisplayWidth() h = self.pipe.getDisplayHeight() # set the window size in the config file page.makeDeclaration("win-size", "{} {}".format(w, h)) # set the default to fullscreen in the config file page.makeDeclaration("fullscreen", "1") # particles page.makeDeclaration("particles-enabled", "#t") # audio page.makeDeclaration("audio-volume", volume) page.makeDeclaration("audio-mute", "#f") # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
def config(var, val): """ Make config variables configurable in-game. Args: var (str): the config variable's name. val (str): the config variable's value. Examples: ~config want-game-tables t (enables tables) ~config want-game-tables f (disables tables) """ if CONFIG_FILE: fileSrc = CONFIG_FILE else: pageIndex = CONFIG_MGR.getNumExplicitPages() - 1 fileSrc = CONFIG_MGR.getExplicitPage(pageIndex).getName() found = False hash = "#" if len(val) == 1 and not val.isdigit() else "" val = " {0}{1}\r\n".format(hash, val) newConfig = var + val shutil.move(fileSrc, fileSrc + "~") destination = open(fileSrc, "w") source = open(fileSrc + "~", "r") for line in source: lenLine = 0 lineParts = line.split() if len(lineParts) > 1: lenLine = len(lineParts[0]) if lenLine and var in line and len(var) == lenLine: destination.write(newConfig) found = True else: destination.write(line) source.close() destination.close() if not found: with open(fileSrc, "a") as f: f.write("\n" + newConfig) loadPrcFile(fileSrc) messenger.send(var + " updated") return
def __writeConfig(self): """Save current config in the prc file or if no prc file exists create one. The prc file is set in the prcFile variable""" page = None # These TODO tags are as a reminder for to add any new config # variables that may occur in the future #TODO: get values of configurations here particles = "#f" if not base.particleMgrEnabled else "#t" volume = str(round(base.musicManager.getVolume(), 2)) mute = "#f" if base.AppHasAudioFocus else "#t" #TODO: add any configuration variable name that you have added customConfigVariables = [ "", "particles-enabled", "audio-mute", "audio-volume"] if os.path.exists(prcFile): # open the config file and change values according to current # application settings page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) # NOTE: particles-enabled and audio-mute are custom variables and # have to be loaded by hand at startup # Particles page.makeDeclaration("particles-enabled", particles) # audio page.makeDeclaration("audio-volume", volume) page.makeDeclaration("audio-mute", mute) else: # Create a config file and set default values cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("{} Pandaconfig".format(appName)) # set OpenGL to be the default page.makeDeclaration("load-display", "pandagl") # get the displays width and height w = self.pipe.getDisplayWidth() h = self.pipe.getDisplayHeight() # set the window size in the config file page.makeDeclaration("win-size", "{} {}".format(w, h)) # set the default to fullscreen in the config file page.makeDeclaration("fullscreen", "1") # particles page.makeDeclaration("particles-enabled", "#t") # audio page.makeDeclaration("audio-volume", volume) page.makeDeclaration("audio-mute", "#f") # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
def __init__(self): DirectObject.__init__(self) loadPrcFile("Config.prc") self.showBase = ShowBase() self.accept("escape", self.sendMsgDisconnectReq) self.cManager = QueuedConnectionManager() self.cListener = QueuedConnectionListener(self.cManager, 0) self.cReader = QueuedConnectionReader(self.cManager, 0) self.cWriter = ConnectionWriter(self.cManager,0) self.Connection = self.cManager.openTCPClientConnection(SERVER_IP, SERVER_PORT, 1) self.cReader.addConnection(self.Connection) self.showBase.taskMgr.add(self.readTask, "serverReaderPollTask", -39) self.uiNode = aspect2d.attachNewNode("UI Node") self.gameOutput = GameOutput("../resources/level/maps/test.ppm", self.showBase) def connect(): self.name = self.nameEntry.get() if self.name != "": self.sendMsgAuth() self.loginButton["text"] = "Start!" self.loginButton["command"] = self.sendCompleteSetup def setText(textEntered): self.nameEntry.setText(textEntered) def clearText(): self.nameEntry.enterText('') self.nameEntry = DirectEntry( scale = 0.1, command = setText, focusInCommand = clearText, pos = (-0.5, 0, -0.5), numLines = 1, focus = 1, relief = DGG.SUNKEN) self.loginButton = DirectButton( text = "connect to server", scale = 0.1, command = connect, frameSize = (-4.5, 4.5, -2, 2.5)) self.loginButton.reparentTo(self.uiNode) self.nameEntry.reparentTo(self.uiNode)
def main(): import os import numpy as np from panda3d.core import loadPrcFile assert "CITYSIM3D_DIR" in os.environ loadPrcFile(os.path.expandvars('${CITYSIM3D_DIR}/config.prc')) action_space = TranslationAxisAngleSpace( np.array([-20, -10, -10, -1.5707963267948966]), np.array([20, 10, 10, 1.5707963267948966])) sensor_names = ['image', 'depth_image'] env = SimpleQuadPanda3dEnv(action_space, sensor_names) import time import cv2 start_time = time.time() frames = 0 from visual_dynamics.policies.quad_target_policy import QuadTargetPolicy pol = QuadTargetPolicy(env, (12, 18), (-np.pi / 2, np.pi / 2)) obs = env.reset() pol.reset() image, depth_image = obs while True: try: env.render() image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) cv2.imshow('Image window', image) key = cv2.waitKey(1) key &= 255 if key == 27 or key == ord('q'): print("Pressed ESC or q, exiting") break quad_action = pol.act(obs) obs, _, _, _ = env.step(quad_action) image, depth_image = obs frames += 1 except KeyboardInterrupt: break end_time = time.time() print("average FPS: {}".format(frames / (end_time - start_time)))
def setupLog(editor_name): # check if we have a config file home = os.path.expanduser("~") basePath = os.path.join(home, f".{editor_name}") if not os.path.exists(basePath): os.makedirs(basePath) logPath = os.path.join(basePath, "logs") if not os.path.exists(logPath): os.makedirs(logPath) # Remove log files older than 30 days for f in os.listdir(logPath): fParts = f.split(".") fDate = datetime.now() try: fDate = datetime.strptime(fParts[-1], "%Y-%m-%d_%H") delta = datetime.now() - fDate if delta.days > 30: #print(f"remove {os.path.join(logPath, f)}") os.remove(os.path.join(logPath, f)) except Exception: # this file does not have a date ending pass log_file = os.path.join(logPath, f"{editor_name}.log") handler = TimedRotatingFileHandler(log_file) consoleHandler = StreamHandler() logging.basicConfig(level=logging.DEBUG, handlers=[handler]) #, consoleHandler]) config_file = os.path.join(basePath, f".{editor_name}.prc") if os.path.exists(config_file): loadPrcFile(Filename.fromOsSpecific(config_file)) # make sure to load our custom paths paths_cfg = ConfigVariableSearchPath("custom-model-path", "").getValue() for path in paths_cfg.getDirectories(): line = "model-path {}".format(str(path)) loadPrcFileData("", line) else: with open(config_file, "w") as prcFile: prcFile.write("skip-ask-for-quit #f\n") prcFile.write("create-executable-scripts #f\n") prcFile.write("show-toolbar #t\n")
def __init__(self): # Load the prc file prior to launching showbase in order # to have it affect window related stuff loadPrcFile("Configrc.prc") ShowBase.ShowBase.__init__(self) # Import the main dlls so we don't have to repeatedly import them everywhere builtins.__dict__.update( __import__('panda3d.core', fromlist=['*']).__dict__) builtins.__dict__.update(__import__('libotp', fromlist=['*']).__dict__) builtins.__dict__.update( __import__('libtoontown', fromlist=['*']).__dict__) self.startDirect(1, 1, 0) from toontown.toon import RobotToonManager base.rtm = RobotToonManager.RobotToonManager() base.rtm.popupControls() camera.setPosHpr(0, -60, 5, 0, 0, 0)
def __init__(self): # Load the default configuration.prc. This is recommended, as it # contains some important panda options loadPrcFile("../../Config/configuration.prc") # Init the showbase ShowBase.__init__(self) # Create a new pipeline instance self.renderPipeline = RenderingPipeline(self) # Set the base path for the pipeline. This is required as we are in # a subdirectory self.renderPipeline.getMountManager().setBasePath("../../") # Also set the write path self.renderPipeline.getMountManager().setWritePath("../../Temp/") # Load the default settings self.renderPipeline.loadSettings("../../Config/pipeline.ini") # Now create the pipeline self.renderPipeline.create() # Load the skybox self.skybox = self.renderPipeline.getDefaultSkybox() self.skybox.reparentTo(render) # Create the default movement controler self.controller = MovementController(self) self.controller.setInitialPositionHpr(Vec3(-2.5, -10.5, 7.5), Vec3(0, -14, 0)) self.controller.setup() # At this point we are done with the initialization. Now you want to # load your scene, and create the game logic. # Call this to tell the pipeline that the scene is done loading self.renderPipeline.onSceneInitialized()
def panda_config(self): data = [] request_opengl_config(data) self.app_panda_config(data) data.append("fullscreen %d" % settings.win_fullscreen) if settings.win_fullscreen: data.append("win-size %d %d" % (settings.win_fs_width, settings.win_fs_height)) else: data.append("win-size %d %d" % (settings.win_width, settings.win_height)) data.append("lens-far-limit %g" % settings.lens_far_limit) loadPrcFileData("", '\n'.join(data)) if settings.prc_file is not None: config_file = settings.prc_file if not os.path.isabs(config_file): config_file = os.path.join(settings.config_dir, config_file) filename = Filename.from_os_specific(config_file) if filename.exists(): print("Loading panda config", filename) loadPrcFile(filename) else: print("Panda config file", filename)
def main(): import os import time import numpy as np import cv2 from panda3d.core import loadPrcFile from visual_dynamics import spaces assert "CITYSIM3D_DIR" in os.environ loadPrcFile(os.path.expandvars('${CITYSIM3D_DIR}/config.prc')) action_space = spaces.BoxSpace(np.array([0.0, 0.0]), np.array([0.0, 0.0])) env = GeometricCarPanda3dEnv(action_space) start_time = time.time() frames = 0 image = env.reset() while True: try: env.render() image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) cv2.imshow('Image window', image) key = cv2.waitKey(1) key &= 255 if key == 27 or key == ord('q'): print("Pressed ESC or q, exiting") break image, _, _, _ = env.step(np.array([0.0, 0.0])) frames += 1 except KeyboardInterrupt: break end_time = time.time() print("average FPS: {}".format(frames / (end_time - start_time)))
def __init__(self): loadPrcFile('./config.prc') ShowBase.__init__(self) self.render.setAntialias(AntialiasAttrib.MAuto) # prevents the camera being controlled by the mouse. # necessary because otherwise the camera goes completely mad if # camera.setPos is called intermittently self.disableMouse() # Load the environment model. self.scene = self.loader.loadModel("3dstarnetwork.egg") # Reparent the model to render. self.scene.reparentTo(self.render) # Apply scale and position transforms on the model. self.scene.setScale(0.18, 0.18, 0.18) self.scene.setPos(0.2, 42, 3) self.scene.analyze() self.scene.clearModelNodes() self.scene.flattenStrong() self.scene.analyze() self.pos = {'x': 0., 'y': 0., 'z': 0.} self.ser = serial.Serial('/dev/ttyACM0', 1000000) #self.ser = SerialMock() self.imu = TI_IMU(self.ser) manager = mp.Manager() self.pos = manager.dict({}) self.motion_thread = MotionProcess(self.imu, self.pos) self.motion_thread.start() self.taskMgr.add(self.updateCamera, "updateCameraTask")
def __init__(self): # Load the default configuration.prc. This is recommended, as it # contains some important panda options loadPrcFile("../../Config/configuration.prc") # Init the showbase ShowBase.__init__(self) # Create a new pipeline instance self.renderPipeline = RenderingPipeline(self) # Set the base path for the pipeline. This is required as we are in # a subdirectory self.renderPipeline.getMountManager().setBasePath("../../") # Also set the write path self.renderPipeline.getMountManager().setWritePath("../../Temp/") # Load the default settings self.renderPipeline.loadSettings("../../Config/pipeline.ini") # Now create the pipeline self.renderPipeline.create()
def WritePRCFile(self): page = None customConfigVariables = [ "", "motd", "hostname", "tcp-port", "backlog", "udp-port", "isPersistent" ] if os.path.exists(prcFile): # load the existing config file page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) else: # create a new config file cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("Net Core Pandaconfig") # config declarations page.makeDeclaration("motd", str(self.MOTD)) page.makeDeclaration("hostname", str(self.HOSTNAME)) page.makeDeclaration("tcp-port", str(self.TCPPORT)) page.makeDeclaration("backlog", str(self.BACKLOG)) page.makeDeclaration("udp-port", str(self.UDPPORT)) page.makeDeclaration("isPersistent", str(self.ISPERSISTENT)) # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
def WritePRCFile(self): page = None customConfigVariables = [ "", "tcp-port", "udp-port", "server-port", "server-ip", "timeout-in-ms" ] if os.path.exists(prcFile): # load the existing config file page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) else: # create a new config file cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("Grim Net Pandaconfig") # config declarations page.makeDeclaration("udp-port", str(self.UDPPORT)) page.makeDeclaration("tcp-port", str(self.TCPPORT)) page.makeDeclaration("server-port", str(self.UDPPORTSERVER)) page.makeDeclaration("server-ip", str(self.SERVERIP)) page.makeDeclaration("timeout-in-ms", str(self.TIMEOUT)) # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
from panda3d.core import loadPrcFile loadPrcFile('./config/conf.prc') from tabulate import tabulate import numpy as np import cv2 as cv import panda3d import sys, os import torch import time #Panda 3D Imports from panda3d.core import Filename from panda3d.core import AmbientLight from panda3d.core import DirectionalLight from direct.showbase.ShowBase import ShowBase from scipy.spatial.transform import Rotation as R #Custom Functions from environment.quadrotor_env import quad, sensor from environment.quaternion_euler_utility import deriv_quat from controller.model import ActorCritic from controller.dl_auxiliary import dl_in_gen """ INF209B − TÓPICOS ESPECIAIS EM PROCESSAMENTO DE SINAIS: VISAO COMPUTACIONAL PROJETO
import sys import pman.shim from random import choice from direct.showbase.ShowBase import ShowBase from panda3d.core import loadPrcFile, Filename from panda3d.core import WindowProperties from panda3d.core import NodePath, Camera, DirectionalLight from panda3d.core import CollisionTraverser from road import RoadMan from ship import Ship from hud import Hud loadPrcFile(Filename.expand_from('$MAIN_DIR/settings.prc')) class GameApp(ShowBase): def __init__(self): ShowBase.__init__(self) pman.shim.init(self) #props = WindowProperties() #props.setCursorHidden(True) #props.setMouseMode(WindowProperties.M_relative) #base.win.requestProperties(props) base.disableMouse() self.mouse = [0, 0] self.setFrameRateMeter(True) self.win.setClearColor((0, 0, 0, 1)) self.cTrav = CollisionTraverser() self.cTrav.setRespectPrevTransform(True)
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() # 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) # Create a sun light dPos = Vec3(60, 30, 100) dirLight = DirectionalLight() dirLight.setShadowMapResolution(1024) dirLight.setPos(dPos) dirLight.setColor(Vec3(1)) 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) # Tell the GI which light casts the GI self.renderPipeline.setGILightSource(dirLight) self.renderPipeline.setScatteringSource(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 = self.renderPipeline.getDefaultSkybox() self.skybox.reparentTo(render) self.renderPipeline.setEffect(self.model, "DynamicMaterial.effect") self.renderPipeline.onSceneInitialized() self.createGUI()
from panda3d.core import loadPrcFile loadPrcFile("Config.prc") from panda3d.core import ConfigVariableString import os import Map GAME = ConfigVariableString('game', 'fft').getValue() # Return map list to a client def execute(server, iterator, source): server.playersinlobby.remove(source) mapnames = [m.split('.')[0] for m in os.listdir(GAME+'/maps')] maps = [] for mapname in mapnames: mp = Map.load(mapname) del mp['tiles'] maps.append(mp) server.send.MAP_LIST(maps, source)
import os from panda3d.core import ConfigVariableBool from panda3d.core import ConfigVariableInt from panda3d.core import ConfigVariableDouble from panda3d.core import loadPrcFile from pandac.PandaModules import Filename import logging logging.basicConfig(level=logging.INFO, format='*(%(threadName)-10s) %(filename)s:%(lineno)-4d %(message)s',) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') logging.debug('debug messages working') logging.basicConfig(level=logging.ERROR, format='*(%(threadName)-10s) %(filename)s:%(lineno)-4d %(message)s',) loadPrcFile("config/config.prc") MYDIR = os.path.abspath(sys.path[0]) MYDIR = Filename.fromOsSpecific(MYDIR).getFullpath() logging.info(('running from:' + MYDIR)) if AppRunnerGlobal.appRunner is None: RUNTYPE = 'python' else: logging.info("dom" + str(AppRunnerGlobal.appRunner.dom)) if AppRunnerGlobal.appRunner.dom: RUNTYPE = 'website' else: RUNTYPE = 'local' def getConfigInt(name, default): output = ConfigVariableInt(name, default).getValue()
from panda3d.core import loadPrcFile from pandac.PandaModules import * loadPrcFile("../config.prc") GAME = ConfigVariableString('game', 'fft').getValue() loadPrcFile(GAME+"/config.prc") scale = float( ConfigVariableString('spritescale', '2').getValue() ) from panda3d.core import NodePath, TransparencyAttrib from pandac.PandaModules import Texture, TextureStage import Sprite2d class Sprite: def __init__(self, sheet, realdir=1): self.realdir = realdir self.camdir = 1 self.displaydir = 1 self.animation = 'walk' self.sprite2d = Sprite2d.Sprite2d(sheet, cols=14, rows=4, scale=scale*0.7*256.0/240.0, anchorX='Center') # the main container self.node = NodePath("dummy1") # the billboard container self.node2 = NodePath("dummy2") self.node2.setBillboardPointEye() self.node2.reparentTo( self.node ) self.sprite2d.node.reparentTo( self.node2 ) self.sprite2d.node.setPos( 0, -1.5, -1.5 )
"rotation": 1, "type": "solid", } def toggleSceneWireframe(): base.wireframe = not base.wireframe print("Toggling wireframe:", base.wireframe) if base.wireframe: base.render.setRenderModeWireframe() else: base.render.clearRenderMode() if __name__ == "__main__": loadPrcFile("configuration.prc") loadPrcFileData("", "frame-rate-meter-scale 0.035") loadPrcFileData("", "frame-rate-meter-side-margin 0.1") loadPrcFileData("", "show-frame-rate-meter 1") loadPrcFileData("", "window-title Saturn Test") loadPrcFileData("", "sync-video 0") loadPrcFileData("", "task-timer-verbose 1") loadPrcFileData("", "pstats-tasks 1") loadPrcFileData("", "want-pstats 1") loadPrcFileData("", "textures-power-2 none") loadPrcFileData("", "win-size 1600 960") base = ShowBase() base.setSleep(0.001) base.wireframe = False base.planetframe = False render_pipeline = RenderingPipeline(base)
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 writeConfig(self): """Save current config in the prc file or if no prc file exists create one. The prc file is set in the prcFile variable""" page = None # #TODO: add any configuration variable names that you have added # to the dictionaries in the next lines. Set the current # configurations value as value in this dictionary and it's # name as key. configVariables = { # set the window size in the config file "win-size": ConfigVariableString( "win-size", "{} {}".format(self.dispWidth, self.dispHeight)).getValue(), # set the default to fullscreen in the config file "fullscreen": "#t" if ConfigVariableBool("fullscreen", True).getValue() else "#f", # particles "particles-enabled": "#t" if self.particleMgrEnabled else "#f", # audio "audio-volume": str(round(self.musicManager.getVolume(), 2)), "audio-music-active": "#t" if self.musicActive else "#f", "audio-sfx-active": "#t" if self.sfxActive else "#f", # logging "notify-output": os.path.join(basedir, "game.log"), # window "framebuffer-multisample": "#t" if ConfigVariableBool("framebuffer-multisample").getValue() else "#f", "multisamples": str(ConfigVariableInt("multisamples", 8).getValue()), "texture-anisotropic-degree": str(ConfigVariableInt("texture-anisotropic-degree").getValue()), "textures-auto-power-2": "#t" if ConfigVariableBool("textures-auto-power-2", True).getValue() else "#f", # server connection "server-host": base.serverHost.getValue(), } page = None # Check if we have an existing configuration file if os.path.exists(prcFile): # open the config file and change values according to current # application settings page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base # or other manual config changes by the user if page.getVariableName(dec) in configVariables.keys(): removeDecls.append(page.modifyDeclaration(dec)) for dec in removeDecls: page.deleteDeclaration(dec) else: # Create a config file and set default values cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("Application Config") # always write custom configurations for key, value in configVariables.items(): page.makeDeclaration(key, value) # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
from pandac.PandaModules import Vec3, Vec3D, Vec4, PNMImage from pandac.PandaModules import Shader, Texture, TextureStage from pandac.PandaModules import PointLight, NodePath, PandaNode from pandac.PandaModules import ColorBlendAttrib, WindowProperties from pandac.PandaModules import Point3, Point3D import random, os import sys from direct.filter.CommonFilters import CommonFilters from direct.showbase.ShowBase import ShowBase from panda3d.core import loadPrcFile from direct.gui.OnscreenText import OnscreenText from pandac.PandaModules import TextNode loadPrcFile("init/panda.prc") from strudel.evented import Evented from strudel.inspector import ObjectInspector class StrudelApp(ShowBase, Evented): def __init__(self): ShowBase.__init__(self) self.setBackgroundColor(0, 0, 0) self.disableMouse() self.filters = CommonFilters(self.win, self.cam) self.children = [] self.texts = [] self.want_shell = False
def __writeConfig(self): """Save current config in the prc file or if no prc file exists create one. The prc file is set in the prcFile variable""" page = None particles = str(base.particleMgrEnabled) textSpeed = str(base.textWriteSpeed) volume = str(round(base.musicManager.getVolume(), 2)) mouseSens = str(base.mouseSensitivity) customConfigVariables = [ "", "particles-enabled", "text-write-speed", "audio-mute", "audio-volume", "control-type", "mouse-sensitivity"] if os.path.exists(prcFile): page = loadPrcFile(Filename.fromOsSpecific(prcFile)) removeDecls = [] for dec in range(page.getNumDeclarations()): # Check if our variables are given. # NOTE: This check has to be done to not loose our base or other # manual config changes by the user if page.getVariableName(dec) in customConfigVariables: decl = page.modifyDeclaration(dec) removeDecls.append(decl) for dec in removeDecls: page.deleteDeclaration(dec) # Particles particles = "#f" if not base.particleMgrEnabled else "#t" page.makeDeclaration("particles-enabled", particles) # speed of the textwriter page.makeDeclaration("text-write-speed", textSpeed) # audio page.makeDeclaration("audio-volume", volume) mute = "#f" if base.AppHasAudioFocus else "#t" page.makeDeclaration("audio-mute", mute) # controls page.makeDeclaration("control-type", base.controlType) page.makeDeclaration("mouse-sensitivity", mouseSens) else: cpMgr = ConfigPageManager.getGlobalPtr() page = cpMgr.makeExplicitPage("%s Pandaconfig"%appName) page.makeDeclaration("load-display", "pandagl") # get the displays width and height w = self.pipe.getDisplayWidth() h = self.pipe.getDisplayHeight() # set the window size in the config file page.makeDeclaration("win-size", "%d %d"%(w, h)) # set the default to fullscreen in the config file page.makeDeclaration("fullscreen", "1") # particles page.makeDeclaration("particles-enabled", "#t") # speed of the textwriter page.makeDeclaration("text-write-speed", textSpeed) # audio page.makeDeclaration("audio-volume", volume) page.makeDeclaration("audio-mute", "#f") # player controls page.makeDeclaration("control-type", base.controlType) page.makeDeclaration("mouse-sensitivity", mouseSens) # create a stream to the specified config file configfile = OFileStream(prcFile) # and now write it out page.write(configfile) # close the stream configfile.close()
# # PATHS AND CONFIGS # # set the application Name __builtin__.appName = "Ajaw" __builtin__.versionstring = "15.07" # TODO: use vfs for particle texture (asset) path setup home = os.path.expanduser("~") __builtin__.basedir = os.path.join(home, __builtin__.appName) if not os.path.exists(__builtin__.basedir): os.makedirs(__builtin__.basedir) prcFile = os.path.join(__builtin__.basedir, "%s.prc"%__builtin__.appName) if os.path.exists(prcFile): loadPrcFile(Filename.fromOsSpecific(prcFile)) __builtin__.rootdir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) vfs = VirtualFileSystem.getGlobalPtr() vfs.mount( Filename(os.path.join(__builtin__.rootdir,"assets")), ".", VirtualFileSystem.MFReadOnly ) gettext.bindtextdomain(__builtin__.appName, "localedir") gettext.textdomain(__builtin__.appName) __builtin__._ = gettext.lgettext windowicon = os.path.join(__builtin__.rootdir,"assets","Icon.png") loadPrcFileData("", """ window-title GrimFang OWP - Ajaw cursor-hidden 0
def __init__(self): # Load the default configuration.prc. This is recommended, as it # contains some important panda options loadPrcFile("../../Config/configuration.prc") ShowBase.__init__(self) # Create a new pipeline instance self.renderPipeline = RenderingPipeline(self) # Set the base path for the pipeline. This is required as we are in # a subdirectory self.renderPipeline.getMountManager().setBasePath("../../") # Also set the write path self.renderPipeline.getMountManager().setWritePath("../../Temp/") # Load the default settings self.renderPipeline.loadSettings("../../Config/pipeline.ini") # Now create the pipeline self.renderPipeline.create() # Add a directional light dPos = Vec3(40, 40, 15) dirLight = DirectionalLight() dirLight.setPos(dPos * 1000000.0) dirLight.setShadowMapResolution(1024) dirLight.setCastsShadows(True) dirLight.setColor(Vec3(8)) self.renderPipeline.addLight(dirLight) self.renderPipeline.setScatteringSource(dirLight) self.dirLight = dirLight self.keyMap = { "left": 0, "right": 0, "forward": 0, "cam-left": 0, "cam-right": 0} base.win.setClearColor(Vec4(0, 0, 0, 1)) # Post the instructions self.title = addTitle( "Panda3D Tutorial: Roaming Ralph (Walking on Uneven Terrain)") self.inst1 = addInstructions(0.95, "[ESC]: Quit") self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left") self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right") self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward") self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left") self.inst7 = addInstructions(0.65, "[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) self.environ.setPos(0, 0, 0) self.environ.find("**/wall").removeNode() # 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) self.renderPipeline.setEffect(self.ralph, "Effects/Default/Default.effect", { "dynamic": True }) # Create a floater object. We use the "floater" as a temporary # variable in a variety of calculations. self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(render) # Accept the control keys for movement and rotation self.accept("escape", sys.exit) self.accept("arrow_left", self.setKey, ["left", 1]) self.accept("arrow_right", self.setKey, ["right", 1]) self.accept("arrow_up", self.setKey, ["forward", 1]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("s", self.setKey, ["cam-right", 1]) self.accept("arrow_left-up", self.setKey, ["left", 0]) self.accept("arrow_right-up", self.setKey, ["right", 0]) self.accept("arrow_up-up", self.setKey, ["forward", 0]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("s-up", self.setKey, ["cam-right", 0]) # NOTICE: It is important that your update tasks have a lower priority # than -10000 taskMgr.add(self.move, "moveTask", priority=-20000) self.accept("r", self.reloadShader) # Game state variables self.isMoving = False # Set up the camera base.disableMouse() base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 1.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, 1000) self.ralphGroundRay.setDirection(0, 0, -1) self.ralphGroundCol = CollisionNode('ralphRay') self.ralphGroundCol.addSolid(self.ralphGroundRay) self.ralphGroundCol.setFromCollideMask(BitMask32.bit(0)) self.ralphGroundCol.setIntoCollideMask(BitMask32.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, 1000) self.camGroundRay.setDirection(0, 0, -1) self.camGroundCol = CollisionNode('camRay') self.camGroundCol.addSolid(self.camGroundRay) self.camGroundCol.setFromCollideMask(BitMask32.bit(0)) self.camGroundCol.setIntoCollideMask(BitMask32.allOff()) self.camGroundColNp = base.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 ocean self.water = ProjectedWaterGrid(self.renderPipeline) self.water.setWaterLevel(-4.0) # Create the skybox self.skybox = self.renderPipeline.getDefaultSkybox() self.skybox.reparentTo(render) self.prepareSRGB(render) self.reloadShader() self.renderPipeline.onSceneInitialized() # Add demo slider to move the sun position if self.renderPipeline.settings.displayOnscreenDebugger: self.renderPipeline.guiManager.demoSlider.node[ "command"] = self.setSunPos self.renderPipeline.guiManager.demoSlider.node[ "value"] = 50
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) # Show loading screen self.loadingScreen = PipelineLoadingScreen(self) self.loadingScreen.render() self.loadingScreen.setStatus("Creating pipeline", 10) # Create the render pipeline self.debug("Creating pipeline") self.renderPipeline = RenderingPipeline(self) # Uncomment to use temp directory # writeDirectory = tempfile.mkdtemp(prefix='Shader-tmp') writeDirectory = "Temp/" # Set the pipeline base path self.renderPipeline.getMountManager().setBasePath(".") # Load pipeline settings self.renderPipeline.loadSettings("Config/pipeline.ini") self.loadingScreen.setStatus("Compiling shaders", 20) # Create the pipeline, and enable scattering self.renderPipeline.create() ####### END OF RENDER PIPELINE SETUP ####### # Select demo scene here: # This sources are not included in the repo, for size reasons # self.sceneSource = "Demoscene.ignore/MasterSword/Scene.egg" # self.sceneSource = "Demoscene.ignore/MasterSword/Scene2.egg.bam" # self.sceneSource = "Demoscene.ignore/Couch2/Scene.egg" # self.sceneSource = "Demoscene.ignore/Couch/couch.egg.bam" # self.sceneSource = "Demoscene.ignore/LivingRoom/LivingRoom.egg" # self.sceneSource = "Demoscene.ignore/LivingRoom2/LivingRoom.egg" # self.sceneSource = "Demoscene.ignore/LostEmpire/Model.egg" # self.sceneSource = "Demoscene.ignore/SSLRTest/scene.egg" # self.sceneSource = "Demoscene.ignore/BMW/Bmw.egg" # self.sceneSource = "Demoscene.ignore/Tuscany/Tuscany.egg" # self.sceneSource = "Demoscene.ignore/EiffelTower/Scene.bam" # self.sceneSource = "Demoscene.ignore/HarvesterModel/Model.egg" # self.sceneSource = "Demoscene.ignore/OldHouse/Scene.egg" # self.sceneSource = "Demoscene.ignore/DemoTerrain/Scene.egg" # self.sceneSource = "Demoscene.ignore/TransparencyTest/Scene.egg" # self.sceneSource = "Demoscene.ignore/SanMiguel/Scene.bam" # self.sceneSource = "Demoscene.ignore/DabrovicSponza/Scene.egg" # self.sceneSource = "Demoscene.ignore/Avolition/level5.bam" # self.sceneSource = "Demoscene.ignore/Sphere/Scene.bam" # self.sceneSource = "Demoscene.ignore/Alphatest/alphatest.egg" # self.sceneSource = "Demoscene.ignore/TestScene/Test.bam" # This sources are included in the repo # self.sceneSource = "Models/CornelBox/Model.egg" # self.sceneSource = "Models/HouseSet/Model.egg" # self.sceneSource = "Models/PSSMTest/Model.egg.bam" # self.sceneSource = "Models/PBSTest/Scene.egg.bam" # self.sceneSource = "Models/HDRTest/Scene.egg" # self.sceneSource = "Models/GITestScene/Scene.egg" # self.sceneSource = "Models/VertexPerformanceTest/Scene.egg" # self.sceneSource = "Toolkit/Blender Material Library/MaterialLibrary.egg" self.sceneSource = "panda" # Select surrounding scene here self.sceneSourceSurround = None # self.sceneSourceSurround = "Demoscene.ignore/Couch/Surrounding.egg" # self.sceneSourceSurround = "Demoscene.ignore/LivingRoom/LivingRoom.egg" # self.sceneSourceSurround = "Models/LittleHouse/couch.bam" # Store a list of transparent objects self.transparentObjects = [] # Create a sun light dPos = Vec3(60, 30, 100) if True: dirLight = DirectionalLight() dirLight.setPos(dPos * 100000.0) dirLight.setShadowMapResolution(2048) dirLight.setColor(Vec3(1.1, 1.05, 0.9) * 3.0) dirLight.setCastsShadows(True) dirLight.setPssmDistance(140) self.renderPipeline.addLight(dirLight) self.dirLight = dirLight # Tell the GI which light casts the GI self.renderPipeline.setScatteringSource(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"] = 50 self.lastSliderValue = 0.5 self.movingLights = [] self.demoLights = [] # Create some lights for i in xrange(0): pointLight = PointLight() radius = float(i) / 3.0 * 6.28 + 1.52 xoffs = i * 3.0 yoffs = math.cos(radius) * 0.0 pointLight.setPos(0, 0, 15) pointLight.setColor(Vec3(0.2,0.6,1.0)*6) pointLight.setShadowMapResolution(512) pointLight.setRadius(18) pointLight.setCastsShadows(True) self.renderPipeline.addLight(pointLight) # pointLight.attachDebugNode(render) # self.movingLights.append(pointLight) # Create more lights for i in xrange(0): pointLight = PointLight() radius = float(i) / 12.0 * 6.28 + 5.22 xoffs = math.sin(radius) * 50.0 yoffs = math.cos(radius) * 50.0 pointLight.setPos(Vec3( xoffs, yoffs, 12)) # pointLight.setColor(Vec3(0.2,0.6,1.0) * 0.05) pointLight.setColor(random(), random(), random()) pointLight.setRadius(90) self.renderPipeline.addLight(pointLight) # pointLight.attachDebugNode(render) for x in xrange(0): spotLight = SpotLight() spotLight.setColor(Vec3(0.5, 0.8, 1.0) * 0.3) lightPos = Vec3(math.sin(x/10.0 * 6.28) * 16.0, math.cos(x/10.0 * 6.28) * 16.0, 29.0) spotLight.setPos(lightPos) spotLight.lookAt(lightPos - Vec3(0, 0, 1)) spotLight.setFov(90) spotLight.setShadowMapResolution(1024) spotLight.setCastsShadows(True) spotLight.setNearFar(2.0, 60.0) spotLight.setIESProfile("AreaLight") self.renderPipeline.addLight(spotLight) # spotLight.attachDebugNode(render) # self.movingLights.append(spotLight) # Attach update task self.addTask(self.update, "update") # Update loading screen status self.loadingScreen.setStatus("Loading scene", 55) # Show loading screen a bit if True: self.doMethodLater(0.5, self.loadScene, "Load Scene") else: self.loadScene()
from panda3d.core import loadPrcFile from path import path # The root local path. ROOT_PATH = path(__path__[0]).abspath().split()[0] # Load scenesim-specific Panda3d settings. config_pth = path.joinpath(ROOT_PATH, "cfg/Config.prc") if config_pth.isfile(): loadPrcFile(config_pth)
import sys from panda3d.core import loadPrcFile from panda3d.core import ConfigVariableString loadPrcFile("Config.prc") GAME = ConfigVariableString('game', 'fft').getValue() loadPrcFile(GAME+"/Config.prc") IP = ConfigVariableString('ip', '127.0.0.1').getValue() PORT = int(ConfigVariableString('port', '3001').getValue()) CROSS_BTN = ConfigVariableString('cross-btn', '0').getValue() CIRCLE_BTN = ConfigVariableString('circle-btn', '3').getValue() TRIANGLE_BTN = ConfigVariableString('triangle-btn', '2').getValue() SQUARE_BTN = ConfigVariableString('square-btn', '1').getValue() L1_BTN = ConfigVariableString('l1-btn', '4').getValue() L2_BTN = ConfigVariableString('l2-btn', '7').getValue() R1_BTN = ConfigVariableString('r1-btn', '6').getValue() R2_BTN = ConfigVariableString('r2-btn', '9').getValue() START_BTN = ConfigVariableString('start-btn', '8').getValue() SELECT_BTN = ConfigVariableString('select-btn', '5').getValue() SPRITE_SCALE = float( ConfigVariableString('sprite-scale', '2').getValue() ) THEME = ConfigVariableString('theme', 'default').getValue()
if not os.path.exists('user/'): os.mkdir('user/') if __debug__: try: import wx except: import wxversion wxversion.select('3.0') import wx import sys from direct.stdpy import threading loadPrcFile('dependencies/config/general.prc') loadPrcFile('dependencies/config/release/dev.prc') if os.path.isfile('dependencies/config/local.prc'): loadPrcFile('dependencies/config/local.prc') defaultText = "" def __inject_wx(_): code = textbox.GetValue() exec(code, globals()) def openInjector_wx(): app = wx.App(redirect=False) frame = wx.Frame(None, title="Injector", size=(640, 400), style=wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX) panel = wx.Panel(frame)
# # set company and application details companyName = "Grimfang Studio" appName = "Ankandora" versionstring = "20.04" # build the path from the details we have home = os.path.expanduser("~") basedir = os.path.join(home, companyName, appName) if not os.path.exists(basedir): os.makedirs(basedir) # look for a config file prcFile = os.path.join(basedir, "{}.prc".format(appName)) if os.path.exists(prcFile): mainConfig = loadPrcFile(Filename.fromOsSpecific(prcFile)) # set configurations that should not be changed from a config file loadPrcFileData( "", """ # # Model loading # model-path $MAIN_DIR/assets/ # # Window and graphics # window-title {} #
from panda3d.core import loadPrcFile, loadPrcFileData, Filename, DSearchPath, VBase4 # thread coordination import framework.tickmodule import threading # network support import Queue import SocketServer print "done." print "Applying the engine configuration file/settings..." # load the selected engine configuration (studypath takes precedence over the SNAP root path) config_searchpath = DSearchPath() config_searchpath.appendDirectory(Filename.fromOsSpecific(opts.studypath)) config_searchpath.appendDirectory(Filename.fromOsSpecific('.')) loadPrcFile(config_searchpath.findFile(Filename.fromOsSpecific(opts.engineconfig))) # add a few more media search paths (in particular, media can be in the media directory, or in the studypath) loadPrcFileData('', 'model-path ' + opts.studypath + '/media') loadPrcFileData('', 'model-path ' + opts.studypath) loadPrcFileData('', 'model-path media') # override engine settings according to the command line arguments, if specified if opts.fullscreen is not None: loadPrcFileData('', 'fullscreen ' + opts.fullscreen) if opts.windowsize is not None: loadPrcFileData('', 'win-size ' + opts.windowsize.replace('x',' ')) if opts.windoworigin is not None: loadPrcFileData('', 'win-origin ' + opts.windoworigin.replace('/',' ')) if opts.noborder is not None: loadPrcFileData('', 'undecorated ' + opts.noborder)
help="The control channel of this UD's designated State Server.") parser.add_argument( '--astron-ip', help="The IP address of the Astron Message Director to connect to.") parser.add_argument( '--eventlogger-ip', help="The IP address of the Astron Event Logger to log to.") parser.add_argument('config', nargs='*', default=['config/config_server.prc'], help="PRC file(s) to load.") args = parser.parse_args() __builtins__.args = args for prc in args.config: loadPrcFile(prc) localconfig = '' if args.base_channel: localconfig += 'air-base-channel %s000000\n' % args.base_channel if args.max_channels: localconfig += 'air-channel-allocation %s\n' % args.max_channels if args.stateserver: localconfig += 'air-stateserver %s\n' % args.stateserver if args.astron_ip: localconfig += 'air-connect %s\n' % args.astron_ip if args.eventlogger_ip: localconfig += 'eventlog-host %s\n' % args.eventlogger_ip loadPrcFileData('Command-line', localconfig) from src.coginvasion.base.Metadata import Metadata __builtins__.metadata = Metadata() metadata.PROCESS = 'server'
""" Filename: MusicRecorder.py Created by: blach (26Apr15) """ from sendkeys import SendKeys from panda3d.core import loadPrcFile, loadPrcFileData loadPrcFile('/c/Users/Brian/Documents/panda3d/Panda3D-CI/etc/Config.prc') loadPrcFileData('', 'audio-library-name p3miles_audio') from direct.interval.IntervalGlobal import Sequence, Wait, Func from direct.showbase.ShowBase import ShowBase base = ShowBase() START_KEY = '{F12}' STOP_KEY = '{F12}' print 'Recording start key: ' + START_KEY print 'Recording stop key: ' + STOP_KEY EXTENSION = '.mid' print 'Music extension: ' + EXTENSION BASE = '' PHASES = [ BASE + 'phase_3/audio/bgm/', BASE + 'phase_3.5/audio/bgm/', BASE + 'phase_4/audio/bgm/', BASE + 'phase_6/audio/bgm/', BASE + 'phase_7/audio/bgm/', BASE + 'phase_8/audio/bgm/', BASE + 'phase_9/audio/bgm/', BASE + 'phase_11/audio/bgm/',
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import sys from timeit import default_timer as timer # Disable v-sync import os os.environ['vblank_mode'] = '0' # Load configuration file with CPU backend (TinyPanda software rendering) from panda3d.core import loadPrcFile loadPrcFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), "ConfigCPU.prc")) from benchmark import BenchmarkEnvironment def getFpsAll(nbSteps): # 'acoustics' world temporarily disabled env = BenchmarkEnvironment(activeEngines=['physics', 'render']) start = timer() env.simulate(nbSteps=nbSteps) end = timer() elapsed = (end - start) env.destroy()
from panda3d.core import loadPrcFile loadPrcFile("../config.prc") from pandac.PandaModules import * from direct.showbase import DirectObject from panda3d.core import CollisionTraverser, CollisionNode, CollisionHandlerQueue, CollisionRay, BitMask32, CardMaker, NodePath, Texture, TextureStage from direct.task.Task import Task GAME = ConfigVariableString('game', 'fft').getValue() class Chooser(DirectObject.DirectObject): def __init__(self, charid, sprite, camhandler, callback, cancelcallback): self.charid = charid self.sprite = sprite self.camhandler = camhandler self.callback = callback self.cancelcallback = cancelcallback self.initdir = self.sprite.realdir self.hidir = None # Textures self.readytex = loader.loadTexture(GAME+'/textures/gui/direction.png') self.readytex.setMagfilter(Texture.FTNearest) self.readytex.setMinfilter(Texture.FTNearest) self.hovertex = loader.loadTexture(GAME+'/textures/gui/direction_hover.png') self.hovertex.setMagfilter(Texture.FTNearest) self.hovertex.setMinfilter(Texture.FTNearest) # Sounds self.hover_snd = base.loader.loadSfx(GAME+'/sounds/hover.ogg')
__builtin__.__dict__.update(__import__('pandac.PandaModules', fromlist=['*']).__dict__) from direct.extensions_native import HTTPChannel_extensions from direct.extensions_native import Mat3_extensions from direct.extensions_native import VBase3_extensions from direct.extensions_native import VBase4_extensions from direct.extensions_native import NodePath_extensions from panda3d.core import loadPrcFile if __debug__: loadPrcFile('config/general.prc') loadPrcFile('config/release/dev.prc') from direct.directnotify.DirectNotifyGlobal import directNotify notify = directNotify.newCategory('Toontown Planet Client Start') notify.setInfo(True) from otp.settings.Settings import Settings preferencesFilename = ConfigVariableString( 'preferences-filename', 'preferences.json').getValue()
Left/right arrow turn. Backspace turns around. PgUp/PgDown adjust the view angle up/down. Created on Feb 25, 2015 @author: ejs ''' from math import pi, sin, cos from panda3d.core import loadPrcFile, Vec3, Vec3F, PandaNode,\ KeyboardButton, WindowProperties, Camera from direct.task.TaskManagerGlobal import taskMgr import math loadPrcFile("./myconfig.prc") from direct.task import Task if False: globalClock = 0 DEG_TO_RAD = pi/180 #translates degrees to radians for sin and cos # movement ACCELERATION = 25 JUMP_GRAV = 9.8 JUMP_HEIGHT = 4 JUMP_TIME = 0.5