def loadAnim(self): # bring up file open box to allow selection of an # animation file animFilename = askopenfilename( defaultextension = '.mb', filetypes = (('Maya Models', '*.mb'), ('All files', '*')), initialdir = '/i/beta', title = 'Load Animation', parent = self.component('hull') ) if not animFilename or animFilename == 'None': # no file selected, canceled return # add directory where animation was loaded from to the # current model path so any further searches for the file # can find it fileDirName = os.path.dirname(animFilename) fileBaseName = os.path.basename(animFilename) fileBaseNameBase = os.path.splitext(fileBaseName)[0] fileDirNameFN = Filename(fileDirName) fileDirNameFN.makeCanonical() getModelPath().prependDirectory(fileDirNameFN) for currActor in self['actorList']: # replace all currently loaded anims with specified one # currActor.unloadAnims(None, None, None) currActor.loadAnims({fileBaseNameBase:fileBaseNameBase}) self.clearActorControls() self.createActorControls()
def __init__(self, filename): vfs = VirtualFileSystem.getGlobalPtr() self.material = BSPMaterial.getFromFile(filename) self.filename = filename if self.material.hasKeyvalue("$basetexture"): baseTexturePath = Filename( self.material.getKeyvalue("$basetexture")) if vfs.resolveFilename(baseTexturePath, getModelPath().getValue()): imageData = bytes(VirtualFileSystem.getGlobalPtr().readFile( baseTexturePath, True)) byteArray = QtCore.QByteArray.fromRawData(imageData) image = QtGui.QImage.fromData(byteArray) self.pixmap = QtGui.QPixmap.fromImage(image) self.icon = QtGui.QIcon(self.pixmap) self.size = LVector2i(image.width(), image.height()) else: self.texture = None self.size = LVector2i(64, 64) self.icon = None self.pixmap = None else: self.texture = None self.size = LVector2i(64, 64) self.icon = None self.pixmap = None
def loaderPhaseChecker(self, path, loaderOptions): if 'audio/' in path: return 1 file = Filename(path) if not file.getExtension(): file.setExtension('bam') mp = getModelPath() path = mp.findFile(file).cStr() if not path: return match = re.match('.*phase_([^/]+)/', path) if not match: if 'dmodels' in path: return self.errorAccumulatorBuffer += 'file not in phase (%s, %s)\n' % ( file, path) return basePhase = float(match.groups()[0]) if not launcher.getPhaseComplete(basePhase): self.errorAccumulatorBuffer += 'phase is not loaded for this model %s\n' % path model = loader.loader.loadSync(Filename(path), loaderOptions) if model: model = NodePath(model) for tex in model.findAllTextures(): texPath = tex.getFullpath().cStr() match = re.match('.*phase_([^/]+)/', texPath) if match: texPhase = float(match.groups()[0]) if texPhase > basePhase: self.errorAccumulatorBuffer += 'texture phase is higher than the models (%s, %s)\n' % ( path, texPath)
def __init__(self, name, resource): """Arguments: resource -- name of a directory in assets/skyboxes that contains 6 images. """ ManagedAsset.__init__(self, "sky") self.name = name tex = None for ext in ("png", "jpg", "tga"): f = Filename("skyboxes/{}/0.{}".format(resource, ext)) if f.resolveFilename(getModelPath().getValue()): tex = TexturePool.loadCubeMap("skyboxes/{}/#.{}".format(resource, ext)) break if tex is None: raise ResourceLoadError("assets/skyboxes/%s" % resource, "maybe wrong names or different extensions?") self.node = loader.loadModel("misc/invcube") self.node.clearTexture() self.node.clearMaterial() self.node.setScale(10000) self.node.setTwoSided(True) self.node.setBin('background', 0) self.node.setDepthTest(False) self.node.setDepthWrite(False) self.node.setLightOff() self.node.setTexGen(TextureStage.getDefault(), TexGenAttrib.MWorldPosition) self.node.setTexProjector(TextureStage.getDefault(), render, self.node); self.node.setTexture(tex, 1) self.node.flattenLight() #self.node.setCompass() # not needed with world-space-UVs self.addTask(self.update, "sky repositioning", sort=10, taskChain="world")
def makeBundle(startDir): fstartDir = Filename.fromOsSpecific(startDir) # Search for panda3d_mac along $PATH. path = DSearchPath() if 'PATH' in os.environ: path.appendPath(os.environ['PATH']) path.appendPath(os.defpath) panda3d_mac = path.findFile('panda3d_mac') if not panda3d_mac: raise Exception("Couldn't find panda3d_mac on path.") # Construct a search path to look for the images. search = DSearchPath() # First on the path: an explicit $PLUGIN_IMAGES env var. if ExecutionEnvironment.hasEnvironmentVariable('PLUGIN_IMAGES'): search.appendDirectory(Filename.expandFrom('$PLUGIN_IMAGES')) # Next on the path: the models/plugin_images directory within the # current directory. search.appendDirectory('models/plugin_images') # Finally on the path: models/plugin_images within the model # search path. for dir in getModelPath().getDirectories(): search.appendDirectory(Filename(dir, 'plugin_images')) # Now find the icon file on the above search path. icons = search.findFile('panda3d.icns') if not icons: raise Exception("Couldn't find panda3d.icns on model-path.") # Generate the bundle directory structure rootFilename = Filename(fstartDir) bundleFilename = Filename(rootFilename, 'Panda3D.app') if os.path.exists(bundleFilename.toOsSpecific()): shutil.rmtree(bundleFilename.toOsSpecific()) plistFilename = Filename(bundleFilename, 'Contents/Info.plist') plistFilename.makeDir() exeFilename = Filename(bundleFilename, 'Contents/MacOS/panda3d_mac') exeFilename.makeDir() iconFilename = Filename(bundleFilename, 'Contents/Resources/panda3d.icns') iconFilename.makeDir() # Copy in Info.plist, the icon file, and the compiled executable. shutil.copyfile( Filename(fstartDir, "panda3d_mac.plist").toOsSpecific(), plistFilename.toOsSpecific()) shutil.copyfile(icons.toOsSpecific(), iconFilename.toOsSpecific()) print('%s %s' % (panda3d_mac, exeFilename)) shutil.copyfile(panda3d_mac.toOsSpecific(), exeFilename.toOsSpecific()) os.chmod(exeFilename.toOsSpecific(), 0o755) # All done! bundleFilename.touch() print(bundleFilename.toOsSpecific())
def initPackedAppEnvironment(self): """ This function sets up the Python environment suitably for running a packed app. It should only run once in any given session (and it includes logic to ensure this). """ if self.packedAppEnvironmentInitialized: return self.packedAppEnvironmentInitialized = True vfs = VirtualFileSystem.getGlobalPtr() # Now set up Python to import this stuff. VFSImporter.register() sys.path.append(self.multifileRoot) # Make sure that $MAIN_DIR is set to the p3d root before we # start executing the code in this file. ExecutionEnvironment.setEnvironmentVariable( "MAIN_DIR", Filename(self.multifileRoot).toOsSpecific()) # Put our root directory on the model-path, too. getModelPath().appendDirectory(self.multifileRoot) if not self.trueFileIO: # Replace the builtin open and file symbols so user code will get # our versions by default, which can open and read files out of # the multifile. builtins.open = file.open if sys.version_info < (3, 0): builtins.file = file.open builtins.execfile = file.execfile os.listdir = file.listdir os.walk = file.walk os.path.join = file.join os.path.isfile = file.isfile os.path.isdir = file.isdir os.path.exists = file.exists os.path.lexists = file.lexists os.path.getmtime = file.getmtime os.path.getsize = file.getsize sys.modules['glob'] = glob self.checkDiskUsage()
def qtResolvePath(filename): """ Resolves a filename path using the Panda model-path and returns an OS-specific absolute path. Used to load Qt icons from stuff on model-path. """ filename = Filename.fromOsSpecific(filename) vfs = VirtualFileSystem.getGlobalPtr() vfs.resolveFilename(filename, getModelPath().getValue()) return filename.toOsSpecific()
def makeBundle(startDir): fstartDir = Filename.fromOsSpecific(startDir) # Search for panda3d_mac along $PATH. path = DSearchPath() if 'PATH' in os.environ: path.appendPath(os.environ['PATH']) path.appendPath(os.defpath) panda3d_mac = path.findFile('panda3d_mac') if not panda3d_mac: raise Exception("Couldn't find panda3d_mac on path.") # Construct a search path to look for the images. search = DSearchPath() # First on the path: an explicit $PLUGIN_IMAGES env var. if ExecutionEnvironment.hasEnvironmentVariable('PLUGIN_IMAGES'): search.appendDirectory(Filename.expandFrom('$PLUGIN_IMAGES')) # Next on the path: the models/plugin_images directory within the # current directory. search.appendDirectory('models/plugin_images') # Finally on the path: models/plugin_images within the model # search path. for dir in getModelPath().getDirectories(): search.appendDirectory(Filename(dir, 'plugin_images')) # Now find the icon file on the above search path. icons = search.findFile('panda3d.icns') if not icons: raise Exception("Couldn't find panda3d.icns on model-path.") # Generate the bundle directory structure rootFilename = Filename(fstartDir) bundleFilename = Filename(rootFilename, 'Panda3D.app') if os.path.exists(bundleFilename.toOsSpecific()): shutil.rmtree(bundleFilename.toOsSpecific()) plistFilename = Filename(bundleFilename, 'Contents/Info.plist') plistFilename.makeDir() exeFilename = Filename(bundleFilename, 'Contents/MacOS/panda3d_mac') exeFilename.makeDir() iconFilename = Filename(bundleFilename, 'Contents/Resources/panda3d.icns') iconFilename.makeDir() # Copy in Info.plist, the icon file, and the compiled executable. shutil.copyfile(Filename(fstartDir, "panda3d_mac.plist").toOsSpecific(), plistFilename.toOsSpecific()) shutil.copyfile(icons.toOsSpecific(), iconFilename.toOsSpecific()) print('%s %s' % (panda3d_mac, exeFilename)) shutil.copyfile(panda3d_mac.toOsSpecific(), exeFilename.toOsSpecific()) os.chmod(exeFilename.toOsSpecific(), 0o755) # All done! bundleFilename.touch() print(bundleFilename.toOsSpecific())
def initPackedAppEnvironment(self): """ This function sets up the Python environment suitably for running a packed app. It should only run once in any given session (and it includes logic to ensure this). """ if self.packedAppEnvironmentInitialized: return self.packedAppEnvironmentInitialized = True vfs = VirtualFileSystem.getGlobalPtr() # Now set up Python to import this stuff. VFSImporter.register() sys.path.append(self.multifileRoot) # Make sure that $MAIN_DIR is set to the p3d root before we # start executing the code in this file. ExecutionEnvironment.setEnvironmentVariable("MAIN_DIR", Filename(self.multifileRoot).toOsSpecific()) # Put our root directory on the model-path, too. getModelPath().appendDirectory(self.multifileRoot) if not self.trueFileIO: # Replace the builtin open and file symbols so user code will get # our versions by default, which can open and read files out of # the multifile. builtins.open = file.open if sys.version_info < (3, 0): builtins.file = file.open builtins.execfile = file.execfile os.listdir = file.listdir os.walk = file.walk os.path.join = file.join os.path.isfile = file.isfile os.path.isdir = file.isdir os.path.exists = file.exists os.path.lexists = file.lexists os.path.getmtime = file.getmtime os.path.getsize = file.getsize sys.modules["glob"] = glob self.checkDiskUsage()
def loadTexture(self, texpath, name, exts): tex = None if not texpath: texpath = '.' try: path = filesystem.toPanda(os.path.join(texpath, name + exts)) fname = Filename(path) if fname.resolveFilename(getModelPath().getValue()): tex = self._base.loader.loadTexture(fname) except TypeError: # exts is a list for e in exts: path = filesystem.toPanda(os.path.join(texpath, name + e)) fname = Filename(path) if fname.resolveFilename(getModelPath().getValue()): tex = self._base.loader.loadTexture(fname) break if not tex: raise Exception("did not find any match for "+texpath+"/"+name+" with "+str(exts)) return tex
def FgdParse(filename, search_path=None): """Parse a .fgd file and return a FGD object :param filenames: A path to the .fgd file to be parsed :type filename: list :return: a FGD object :rtype: FGD """ if not search_path: search_path = getModelPath().getValue() vfs = VirtualFileSystem.getGlobalPtr() game_data = Fgd() filename = Filename.fromOsSpecific(filename) if vfs.resolveFilename(filename, search_path): filedir = filename.getDirname() data = vfs.readFile(filename, True).decode("iso-8859-1") try: results = pp_fgd.parseString(data) except Exception as e: raise else: raise FileNotFoundError for i in results: if isinstance(i, FgdEditorData): if i.class_type == 'include': # Append the directory of the current file to the search path inc_search_path = getModelPath().getValue() inc_search_path.appendDirectory(filedir) base_game_data = FgdParse(i.data, inc_search_path) game_data.add_include(base_game_data) game_data.add_editor_data(i) for i in results: if isinstance(i, FgdEntity): game_data.add_entity(i) return game_data
def loadFGDFiles(self): """Reads the .fgd files specified in the config file""" self.fgd = Fgd() numVals = LEConfig.fgd_files.getNumUniqueValues() if numVals == 0: QtWidgets.QMessageBox.critical( None, LEGlobals.AppName, "No FGD files specified in local config!", QtWidgets.QMessageBox.Ok) sys.exit(1) vfs = VirtualFileSystem.getGlobalPtr() searchPath = getModelPath().getValue() for i in range(numVals): fgdFilename = LEConfig.fgd_files.getUniqueValue(i) fgdFilename = ExecutionEnvironment.expandString(fgdFilename) fgdFilename = Filename(fgdFilename) vfs.resolveFilename(fgdFilename, searchPath) fgd = FgdParse(fgdFilename.toOsSpecific()) self.fgd.add_include(fgd)
import logging # load panda configuration ROOT_PATH = path(__path__[0]).joinpath("../../").abspath() p3d.loadPrcFile(path.joinpath(ROOT_PATH, "Config.prc")) def get_path(name): return ROOT_PATH.joinpath(p3d.ConfigVariableString(name, "").get_value()) CPO_PATH = get_path("cpo-path") RENDER_PATH = get_path("render-path") SIM_PATH = get_path("sim-path") SIM_SCRIPT_PATH = get_path("sim-script-path") RENDER_SCRIPT_PATH = get_path("render-script-path") EXP_PATH = get_path("experiment-path") DATA_PATH = get_path("data-path") EGG_PATH = get_path("egg-path") TEXTURE_PATH = get_path("texture-path") BIN_PATH = get_path("bin-path") FIG_PATH = get_path("figures-path") RESULTS_PATH = get_path("results-path") p3d.getModelPath().appendDirectory(EGG_PATH) p3d.getModelPath().appendDirectory(TEXTURE_PATH) LOGLEVEL = p3d.ConfigVariableString("loglevel", "warn").get_value().upper() FORMAT = '%(levelname)s -- %(processName)s/%(filename)s -- %(message)s' logging.basicConfig(level=LOGLEVEL, format=FORMAT)
import re try: import cPickle as pickle except ImportError: import pickle from direct.actor.Actor import Actor from panda3d.core import Filename as pfile, getModelPath import direct.directbase.DirectStart __author__ = "QED" __version__ = "0.0.6" __status__ = "Prototype" MODEL_PATH = getModelPath().getDirectories()[-1].toOsSpecific() cog_dict = { "VP": ["sell", "sell"], "Mr. Hollywood": ["yesman", "A", "A", "sell", "", (7.0 / 6.06)], "The Mingler": ["twoface", "A", "A", "sell", "mingler", (5.75 / 6.06)], "Two-Face": ["twoface", "A", "A", "sell", "", (4.25 / 6.06)], "Mover & Shaker": ["movershaker", "B", "B", "sell", "", (4.375 / 5.29)], "Gladhander": ["gladhander", "C", "C", "sell", "", (4.75 / 4.14)], "Name Dropper": ["numbercruncher", "A", "A", "sell", "name-dropper", (4.35 / 6.06)], "Telemarketer": ["telemarketer", "B", "B", "sell", "", (3.75 / 5.29)], "Cold Caller": ["coldcaller", "C", "C", "sell", "", (3.5 / 4.14)], "CFO": ["cash", "cash"], "Robber Baron": ["yesman", "A", "A", "cash", "robber-baron", (7.0 / 6.06)], "Loan Shark": ["loanshark", "B", "B", "cash", "", (6.5 / 5.29)],
def installPackage(self, appRunner): """ Mounts the package and sets up system paths so it becomes available for use. Returns true on success, false on failure. """ assert self.hasPackage if self.installed: # Already installed. return True assert self not in appRunner.installedPackages mfPathname = Filename(self.getPackageDir(), self.uncompressedArchive.filename) mf = Multifile() if not mf.openRead(mfPathname): self.notify.warning("Couldn't open %s" % (mfPathname)) return False # We mount it under its actual location on disk. root = self.getPackageDir() vfs = VirtualFileSystem.getGlobalPtr() vfs.mount(mf, root, vfs.MFReadOnly) # Add this to the Python search path, if it's not already # there. We have to take a bit of care to check if it's # already there, since there can be some ambiguity in # os-specific path strings. osRoot = self.getPackageDir().toOsSpecific() foundOnPath = False for p in sys.path: if osRoot == p: # Already here, exactly. foundOnPath = True break elif osRoot == Filename.fromOsSpecific(p).toOsSpecific(): # Already here, with some futzing. foundOnPath = True break if not foundOnPath: # Not already here; add it. sys.path.append(osRoot) # Put it on the model-path, too. We do this indiscriminantly, # because the Panda3D runtime won't be adding things to the # model-path, so it shouldn't be already there. getModelPath().appendDirectory(self.getPackageDir()) # Set the environment variable to reference the package root. envvar = '%s_ROOT' % (self.packageName.upper()) ExecutionEnvironment.setEnvironmentVariable(envvar, osRoot) # Add the package root to the system paths. if sys.platform.startswith('win'): path = os.environ.get('PATH', '') os.environ['PATH'] = "%s;%s" % (osRoot, path) else: path = os.environ.get('PATH', '') os.environ['PATH'] = "%s:%s" % (osRoot, path) path = os.environ.get('LD_LIBRARY_PATH', '') os.environ['LD_LIBRARY_PATH'] = "%s:%s" % (osRoot, path) if sys.platform == "darwin": path = os.environ.get('DYLD_LIBRARY_PATH', '') os.environ['DYLD_LIBRARY_PATH'] = "%s:%s" % (osRoot, path) # Now that the environment variable is set, read all of the # prc files in the package. appRunner.loadMultifilePrcFiles(mf, self.getPackageDir()) # Also, find any toplevel Python packages, and add these as # shared packages. This will allow different packages # installed in different directories to share Python files as # if they were all in the same directory. for filename in mf.getSubfileNames(): if filename.endswith('/__init__.pyc') or \ filename.endswith('/__init__.pyo') or \ filename.endswith('/__init__.py'): components = filename.split('/')[:-1] moduleName = '.'.join(components) VFSImporter.sharedPackages[moduleName] = True # Fix up any shared directories so we can load packages from # disparate locations. VFSImporter.reloadSharedPackages() self.installed = True appRunner.installedPackages.append(self) self.markUsed() return True
def findDataFilename(name, extract=False, executable=False): """ Resolve a filename along Panda's model-path. :param name: :return: filename or None """ from panda3d.core import Filename, getModelPath from panda3d.core import VirtualFileSystem logging.debug("findDataFilename: "+ name +" on: \n" + str(getModelPath().getValue())) vfs = VirtualFileSystem.getGlobalPtr() fileName = Filename(name) vfile = vfs.findFile(fileName, getModelPath().getValue()) if not vfile: if extract and name.endswith(".exe"): fileName = Filename(name[:-4]) vfile = vfs.findFile(fileName, getModelPath().getValue()) if not vfile: return None fileName = vfile.getFilename() if extract: # see if the file is embedded in some virtual place OR has the wrong perms from panda3d.core import SubfileInfo info = SubfileInfo() needsCopy = not vfile.getSystemInfo(info) or info.getFilename() != fileName if not needsCopy: if executable: # see if on Linux or OSX and not executable try: stat = os.stat(fileName.toOsSpecific()) if (stat.st_mode & 0111) == 0: logging.error("Found %s locally, but not marked executable!", fileName) needsCopy = True except: needsCopy = True if needsCopy: # virtual file needs to be copied out global _tempDir if not _tempDir: import tempfile _tempDir = os.path.realpath(tempfile.mkdtemp()) #print "Temp dir:",_tempDir xpath = _tempDir + '/' + fileName.getBasename() xTarg = Filename.fromOsSpecific(xpath) # on Windows, case-sensitivity must be honored for the following to work xTarg.makeCanonical() print "extracting",fileName,"to",xTarg if not xTarg.exists(): if not vfs.copyFile(fileName, xTarg): raise IOError("extraction failed when copying " + str(fileName) + " to " + str(xTarg)) fileName = xTarg os.chmod(fileName.toOsSpecific(), 0777) return fileName
if not isdir(self.writePath): self.debug("Creating temp path, as it does not exist yet") try: os.makedirs(self.writePath, 0777) except Exception, msg: self.error("Failed to create temp path:",msg) import sys sys.exit(0) # Mount the pipeline temp path self.debug("Mounting",self.writePath,"as PipelineTemp/") vfs.mountLoop(self.writePath, 'PipelineTemp/', 0) # #pragma include "something" searches in current directory first, # and then on the model-path. Append the Shader directory to the modelpath # to ensure the shader includes can be found. base_path = Filename(self.basePath) getModelPath().appendDirectory(join(base_path.getFullpath(), 'Shader')) # Add the pipeline root directory to the model path aswell getModelPath().appendDirectory(base_path.getFullpath()) # Append the write path to the model directory to make pragma include # find the ShaderAutoConfig.include write_path = Filename(self.writePath) getModelPath().appendDirectory(write_path.getFullpath()) def unmount(self): """ Unmounts the VFS """ raise NotImplementedError()
parser.add_argument('--compress', '-c', action='store_true', help='Compress the output file using ZLib.') parser.add_argument('--verbose', '-v', action='store_true', help='Describe the build process.') parser.add_argument('--logfile', '-l', help='Optional file to write the console output to.') parser.add_argument('--path', '-p', help='Add this path to search path (font loading only).') parser.add_argument('--encoding', '-e', default='latin-1', help='Encoding (useful for latin chars rendering).') parser.add_argument('filenames', nargs='+', help='The raw input file(s). Accepts * as wildcard.') args = parser.parse_args() if args.path: getModelPath().appendDirectory(args.path) reload(sys) sys.setdefaultencoding(args.encoding) class LogAndOutput: def __init__(self, out, filename): self.out = out self.file = open(filename, 'w') def write(self, string): self.file.write(string) self.out.write(string) self.flush()
from path import path # this loads the configuration in Config.prc from panda3d.core import Filename, getModelPath, loadPrcFile config_pth = path("Config.prc") if config_pth.isfile(): cp = Filename.fromOsSpecific(config_pth) cp.makeTrueCase() print "Loading config '%s'" % cp loadPrcFile(cp) getModelPath().appendDirectory("models") getModelPath().appendDirectory("textures") import sys from direct.showbase.ShowBase import ShowBase from panda3d.bullet import BulletBoxShape, BulletRigidBodyNode, BulletWorld from panda3d.bullet import BulletDebugNode class BlockTutorial(ShowBase): def __init__(self): # Step 2: Set up graphics ShowBase.__init__(self) self.setup_camera() self.load_block_model() # Step 3: Set up physics self.create_physics()
from panda3d.core import Filename, getModelPath, loadPrcFile, PandaSystem from path import path import scenesim if PandaSystem.getVersionString() != "1.9.0": import warnings warnings.warn("You are using a version of Panda3D that may not work " "with these demos. If you encounter problems, please try " "version 1.9.0 instead.") # load panda configuration ROOT_PATH = path(__path__[0]).joinpath("..").abspath() config_pth = ROOT_PATH.joinpath("Config.prc") if config_pth.isfile(): cp = Filename.fromOsSpecific(config_pth) cp.makeTrueCase() print "Loading config '%s'" % cp loadPrcFile(cp) getModelPath().appendDirectory(ROOT_PATH.joinpath("models")) getModelPath().appendDirectory(ROOT_PATH.joinpath("textures"))
import re try: import cPickle as pickle except ImportError: import pickle from direct.actor.Actor import Actor from panda3d.core import Filename as pfile, getModelPath import direct.directbase.DirectStart __author__ = "QED" __version__ = "0.0.6" __status__ = "Prototype" MODEL_PATH = getModelPath().getDirectories()[-1].toOsSpecific() cog_dict = { "VP": ["sell", "sell"], "Mr. Hollywood": ["yesman", "A", "A", "sell", "", (7.0 / 6.06)], "The Mingler": ["twoface", "A", "A", "sell", "mingler", (5.75 / 6.06)], "Two-Face": ["twoface", "A", "A", "sell", "", (4.25 / 6.06)], "Mover & Shaker": ["movershaker", "B", "B", "sell", "", (4.375 / 5.29)], "Gladhander": ["gladhander", "C", "C", "sell", "", (4.75 / 4.14)], "Name Dropper":
from path import path # this loads the configuration in Config.prc from panda3d.core import Filename, getModelPath, loadPrcFile config_pth = path("Config.prc") if config_pth.isfile(): cp = Filename.fromOsSpecific(config_pth) cp.makeTrueCase() print "Loading config '%s'" % cp loadPrcFile(cp) getModelPath().appendDirectory("models") getModelPath().appendDirectory("textures") import sys from direct.showbase.ShowBase import ShowBase from panda3d.bullet import BulletBoxShape, BulletRigidBodyNode, BulletWorld from panda3d.bullet import BulletDebugNode class BlockTutorial(ShowBase): def __init__(self): # Step 2: Set up graphics ShowBase.__init__(self) self.setup_camera() self.load_block_model() # Step 3: Set up physics self.create_physics() self.load_block_physics()
internal_prefabs_folder = package_folder / 'prefabs/' internal_scripts_folder = package_folder / 'scripts/' internal_textures_folder = package_folder / 'textures/' internal_fonts_folder = package_folder / 'fonts/' prefabs_folder = asset_folder / 'prefabs/' scenes_folder = asset_folder / 'scenes/' scripts_folder = asset_folder / 'scripts/' textures_folder = asset_folder / 'textures/' fonts_folder = asset_folder / 'fonts/' compressed_textures_folder = asset_folder / 'textures_compressed/' compressed_models_folder = asset_folder / 'models_compressed/' # fonts are loaded py panda3d, so add paths here _model_path = getModelPath() _model_path.append_path(str(internal_fonts_folder.resolve())) _model_path.append_path(str(Path('C:/Windows/Fonts').resolve())) _model_path.append_path(str(asset_folder.resolve())) print('package_folder:', package_folder) print('asset_folder:', asset_folder) print('dev mode:', development_mode) def pause(): global paused paused = True for seq in sequences: seq.pause()
import bee import dragonfly from dragonfly.commandhive import commandhive, commandapp from components.drones.keyboardmove import keyboardmove from components.drones.chessprocessor import chessprocessor from components.drones.chesskeeper import chesskeeper from components.drones.chessboard import chessboard from components.drones.movereporter import movereporter from direct.showbase.ShowBase import taskMgr from panda3d.core import getModelPath import os getModelPath().prependPath(os.getcwd()) from bee import hivemodule class myapp(commandapp): def on_tick(self): taskMgr.step() taskMgr.step() class myhive(commandhive): _hivecontext = hivemodule.appcontext(myapp) keyboardmove("White") keyboardmove("Black")
def readDCFiles(self, dcFileNames = None): dcFile = self.dcFile dcFile.clear() self.dclassesByName = {} self.dclassesByNumber = {} self.hashVal = 0 vfs = VirtualFileSystem.getGlobalPtr() if isinstance(dcFileNames, str): # If we were given a single string, make it a list. dcFileNames = [dcFileNames] dcImports = {} if dcFileNames == None: readResult = dcFile.readAll() if not readResult: self.notify.error("Could not read dc file.") else: searchPath = getModelPath().getValue() for dcFileName in dcFileNames: pathname = Filename(dcFileName) vfs.resolveFilename(pathname, searchPath) readResult = dcFile.read(pathname) if not readResult: self.notify.error("Could not read dc file: %s" % (pathname)) self.hashVal = dcFile.getHash() # Now import all of the modules required by the DC file. for n in range(dcFile.getNumImportModules()): moduleName = dcFile.getImportModule(n)[:] # Maybe the module name is represented as "moduleName/AI". suffix = moduleName.split('/') moduleName = suffix[0] suffix=suffix[1:] if self.dcSuffix in suffix: moduleName += self.dcSuffix importSymbols = [] for i in range(dcFile.getNumImportSymbols(n)): symbolName = dcFile.getImportSymbol(n, i) # Maybe the symbol name is represented as "symbolName/AI". suffix = symbolName.split('/') symbolName = suffix[0] suffix=suffix[1:] if self.dcSuffix in suffix: symbolName += self.dcSuffix importSymbols.append(symbolName) self.importModule(dcImports, moduleName, importSymbols) # Now get the class definition for the classes named in the DC # file. for i in range(dcFile.getNumClasses()): dclass = dcFile.getClass(i) number = dclass.getNumber() className = dclass.getName() + self.dcSuffix # Does the class have a definition defined in the newly # imported namespace? classDef = dcImports.get(className) # Also try it without the dcSuffix. if classDef == None: className = dclass.getName() classDef = dcImports.get(className) if classDef is None: self.notify.debug("No class definition for %s." % (className)) else: if inspect.ismodule(classDef): if not hasattr(classDef, className): self.notify.warning("Module %s does not define class %s." % (className, className)) continue classDef = getattr(classDef, className) if not inspect.isclass(classDef): self.notify.error("Symbol %s is not a class name." % (className)) else: dclass.setClassDef(classDef) self.dclassesByName[className] = dclass if number >= 0: self.dclassesByNumber[number] = dclass # Owner Views if self.hasOwnerView(): ownerDcSuffix = self.dcSuffix + 'OV' # dict of class names (without 'OV') that have owner views ownerImportSymbols = {} # Now import all of the modules required by the DC file. for n in range(dcFile.getNumImportModules()): moduleName = dcFile.getImportModule(n) # Maybe the module name is represented as "moduleName/AI". suffix = moduleName.split('/') moduleName = suffix[0] suffix=suffix[1:] if ownerDcSuffix in suffix: moduleName = moduleName + ownerDcSuffix importSymbols = [] for i in range(dcFile.getNumImportSymbols(n)): symbolName = dcFile.getImportSymbol(n, i) # Check for the OV suffix suffix = symbolName.split('/') symbolName = suffix[0] suffix=suffix[1:] if ownerDcSuffix in suffix: symbolName += ownerDcSuffix importSymbols.append(symbolName) ownerImportSymbols[symbolName] = None self.importModule(dcImports, moduleName, importSymbols) # Now get the class definition for the owner classes named # in the DC file. for i in range(dcFile.getNumClasses()): dclass = dcFile.getClass(i) if ((dclass.getName()+ownerDcSuffix) in ownerImportSymbols): number = dclass.getNumber() className = dclass.getName() + ownerDcSuffix # Does the class have a definition defined in the newly # imported namespace? classDef = dcImports.get(className) if classDef is None: self.notify.error("No class definition for %s." % className) else: if inspect.ismodule(classDef): if not hasattr(classDef, className): self.notify.error("Module %s does not define class %s." % (className, className)) classDef = getattr(classDef, className) dclass.setOwnerClassDef(classDef) self.dclassesByName[className] = dclass
os.makedirs(self.writePath, 0777) except Exception, msg: self.error("Failed to create temp path:", msg) import sys sys.exit(0) # Mount the pipeline temp path self.debug("Mounting", self.writePath, "as PipelineTemp/") vfs.mountLoop(self.writePath, 'PipelineTemp/', 0) # #pragma include "something" searches in current directory first, # and then on the model-path. Append the Shader directory to the modelpath # to ensure the shader includes can be found. base_path = Filename(self.basePath) self.modelPaths.append(join(base_path.getFullpath(), 'Shader')) # Add the pipeline root directory to the model path aswell self.modelPaths.append(base_path.getFullpath()) # Append the write path to the model directory to make pragma include # find the ShaderAutoConfig.include write_path = Filename(self.writePath) self.modelPaths.append(write_path.getFullpath()) for pth in self.modelPaths: getModelPath().appendDirectory(pth) def unmount(self): """ Unmounts the VFS """ raise NotImplementedError()
from menu import DropDownMenu, PopupMenu import direct.directbase.DirectStart from direct.gui.DirectGui import OnscreenText from direct.showbase.DirectObject import DirectObject from panda3d.core import getModelPath, ModifierButtons from panda3d.core import NodePath, Texture, TextureStage from panda3d.core import Vec3 from panda3d.core import RenderModeAttrib, RenderState import os,sys os.chdir(sys.path[0]) modelsPath=filter(lambda p: p.getBasename().find('models')>-1, [getModelPath().getDirectory(i) for i in range(getModelPath().getNumDirectories())]) getModelPath().appendPath(modelsPath[0].getFullpath()+'/maps') thickness=1 gameSlots={} for s in range(4): gameSlots[s]=None TSmode=(TextureStage.MModulate,TextureStage.MBlend,TextureStage.MDecal) def resetModButtons(win=None): if win is not None and not win.getProperties().getForeground(): return origMB=ModifierButtons(base.buttonThrowers[0].node().getModifierButtons()) origMB.allButtonsUp() base.buttonThrowers[0].node().setModifierButtons(origMB)
def readDCFile(self, dcFileNames=None): dcFile = self.getDcFile() dcFile.clear() self.dclassesByName = {} self.dclassesByNumber = {} self.hashVal = 0 if isinstance(dcFileNames, types.StringTypes): dcFileNames = [dcFileNames] dcImports = {} if dcFileNames == None: try: readResult = dcFile.read(dcStream, '__dc__') del __builtin__.dcStream except NameError: readResult = dcFile.readAll() if not readResult: self.notify.error('Could not read dc file.') else: searchPath = getModelPath().getValue() for dcFileName in dcFileNames: pathname = Filename(dcFileName) vfs.resolveFilename(pathname, searchPath) readResult = dcFile.read(pathname) if not readResult: self.notify.error('Could not read dc file: %s' % pathname) self.hashVal = dcFile.getHash() for n in xrange(dcFile.getNumImportModules()): moduleName = dcFile.getImportModule(n)[:] suffix = moduleName.split('/') moduleName = suffix[0] suffix = suffix[1:] if self.dcSuffix in suffix: moduleName += self.dcSuffix else: if self.dcSuffix == 'UD' and 'AI' in suffix: moduleName += 'AI' importSymbols = [] for i in xrange(dcFile.getNumImportSymbols(n)): symbolName = dcFile.getImportSymbol(n, i) suffix = symbolName.split('/') symbolName = suffix[0] suffix = suffix[1:] if self.dcSuffix in suffix: symbolName += self.dcSuffix elif self.dcSuffix == 'UD' and 'AI' in suffix: symbolName += 'AI' importSymbols.append(symbolName) self.importModule(dcImports, moduleName, importSymbols) for i in xrange(dcFile.getNumClasses()): dclass = dcFile.getClass(i) number = dclass.getNumber() className = dclass.getName() + self.dcSuffix classDef = dcImports.get(className) if classDef is None and self.dcSuffix == 'UD': className = dclass.getName() + 'AI' classDef = dcImports.get(className) if classDef == None: className = dclass.getName() classDef = dcImports.get(className) if classDef is None: self.notify.debug('No class definition for %s.' % className) else: if type(classDef) == types.ModuleType: if not hasattr(classDef, className): self.notify.warning( 'Module %s does not define class %s.' % (className, className)) continue classDef = getattr(classDef, className) if type(classDef) != types.ClassType and type( classDef) != types.TypeType: self.notify.error('Symbol %s is not a class name.' % className) else: dclass.setClassDef(classDef) self.dclassesByName[className] = dclass if number >= 0: self.dclassesByNumber[number] = dclass if self.hasOwnerView(): ownerDcSuffix = self.dcSuffix + 'OV' ownerImportSymbols = {} for n in xrange(dcFile.getNumImportModules()): moduleName = dcFile.getImportModule(n) suffix = moduleName.split('/') moduleName = suffix[0] suffix = suffix[1:] if ownerDcSuffix in suffix: moduleName = moduleName + ownerDcSuffix importSymbols = [] for i in xrange(dcFile.getNumImportSymbols(n)): symbolName = dcFile.getImportSymbol(n, i) suffix = symbolName.split('/') symbolName = suffix[0] suffix = suffix[1:] if ownerDcSuffix in suffix: symbolName += ownerDcSuffix importSymbols.append(symbolName) ownerImportSymbols[symbolName] = None self.importModule(dcImports, moduleName, importSymbols) for i in xrange(dcFile.getNumClasses()): dclass = dcFile.getClass(i) if dclass.getName() + ownerDcSuffix in ownerImportSymbols: number = dclass.getNumber() className = dclass.getName() + ownerDcSuffix classDef = dcImports.get(className) if classDef is None: self.notify.error('No class definition for %s.' % className) else: if type(classDef) == types.ModuleType: if not hasattr(classDef, className): self.notify.error( 'Module %s does not define class %s.' % (className, className)) classDef = getattr(classDef, className) dclass.setOwnerClassDef(classDef) self.dclassesByName[className] = dclass return
from panda3d.core import Filename, getModelPath, loadPrcFile, PandaSystem from path import path import scenesim if PandaSystem.getVersionString() != "1.9.0": import warnings warnings.warn( "You are using a version of Panda3D that may not work " "with these demos. If you encounter problems, please try " "version 1.9.0 instead.") # load panda configuration ROOT_PATH = path(__path__[0]).joinpath("..").abspath() config_pth = ROOT_PATH.joinpath("Config.prc") if config_pth.isfile(): cp = Filename.fromOsSpecific(config_pth) cp.makeTrueCase() print "Loading config '%s'" % cp loadPrcFile(cp) getModelPath().appendDirectory(ROOT_PATH.joinpath("models")) getModelPath().appendDirectory(ROOT_PATH.joinpath("textures"))
import os currdir = os.path.split(os.path.abspath(__file__))[0] from panda3d.core import getModelPath getModelPath().prependPath(currdir) from . import TutChessboard from chesskeeper import parse_move def unparse_move(fr, to, p_fr, p_to): if isinstance(p_fr, TutChessboard.Pawn): p = "" elif isinstance(p_fr, TutChessboard.King): p = "K" elif isinstance(p_fr, TutChessboard.Queen): p = "Q" elif isinstance(p_fr, TutChessboard.Rook): p = "R" elif isinstance(p_fr, TutChessboard.Bishop): p = "B" elif isinstance(p_fr, TutChessboard.Knight): p = "N"