def saveNewsCache(self): cacheIndexFilename = Filename(self.newsDir, self.CacheIndexFilename) try: file = open(cacheIndexFilename.toOsSpecific(), 'w') except IOError, e: self.notify.warning('error opening news cache file %s: %s' % (cacheIndexFilename, str(e))) return
def readFavIcon(self): vfs = VirtualFileSystem.getGlobalPtr() filename = Filename('favicon.ico') searchPath = DSearchPath() searchPath.appendDirectory(Filename('.')) searchPath.appendDirectory(Filename('etc')) searchPath.appendDirectory(Filename.fromOsSpecific(os.path.expandvars('$DIRECT/src/http'))) searchPath.appendDirectory(Filename.fromOsSpecific(os.path.expandvars('direct/src/http'))) searchPath.appendDirectory(Filename.fromOsSpecific(os.path.expandvars('direct/http'))) searchPath.appendDirectory(Filename('game/resources/http')) searchPath.appendDirectory(Filename('resources/http')) found = vfs.resolveFilename(filename,searchPath) if not found: raise Exception("Couldn't find direct/http/favicon.ico") return vfs.readFile(filename, 1)
def loadParticleConfig(self, file): #Start of the code from steam.ptf self.p.cleanup() self.p = ParticleEffect() self.p.loadConfig(Filename(file)) #Sets particles to birth relative to the teapot, but to render at toplevel self.p.start(self.t) self.p.setPos(3.000, 0.000, 2.250)
def startNotifyLogging(self): self.nout = MultiplexStream() Notify.ptr().setOstreamPtr(self.nout, 0) self.nout.addFile(Filename(self.logfile)) self.nout.addStandardOutput() sys.stdout.console = True sys.stderr.console = True
def __init__(self, pathname, ignoreUsageXml=False): self.pathname = pathname self.filenames = [] self.fileSize = 0 self.nested = [] self.nestedSize = 0 xusage = None if not ignoreUsageXml: # Look for a usage.xml file in this directory. If we find # one, we read it for the file size and then stop here, as # an optimization. usageFilename = Filename(pathname, 'usage.xml') doc = TiXmlDocument(usageFilename.toOsSpecific()) if doc.LoadFile(): xusage = doc.FirstChildElement('usage') if xusage: diskSpace = xusage.Attribute('disk_space') try: diskSpace = int(diskSpace or '') except ValueError: diskSpace = None if diskSpace is not None: self.fileSize = diskSpace return files = vfs.scanDirectory(self.pathname) if files is None: files = [] for vfile in files: if hasattr(vfile, 'getMount'): if not isinstance(vfile.getMount(), VirtualFileMountSystem): # Not a real file; ignore it. continue if vfile.isDirectory(): # A nested directory. subdir = ScanDirectoryNode(vfile.getFilename(), ignoreUsageXml=ignoreUsageXml) self.nested.append(subdir) self.nestedSize += subdir.getTotalSize() elif vfile.isRegularFile(): # A nested file. self.filenames.append(vfile.getFilename()) self.fileSize += vfile.getFileSize() else: # Some other wacky file thing. self.filenames.append(vfile.getFilename()) if xusage: # Now update the usage.xml file with the newly-determined # disk space. xusage.SetAttribute('disk_space', str(self.getTotalSize())) tfile = Filename.temporary(str(pathname), '.xml') if doc.SaveFile(tfile.toOsSpecific()): tfile.renameTo(usageFilename)
def __startIfReady(self): """ Called internally to start the application. """ if self.started: return if self.gotWindow and self.gotP3DFilename: self.started = True # Now we can ignore future calls to startIfReady(). self.ignore('AppRunner_startIfReady') # Hang a hook so we know when the window is actually opened. self.acceptOnce('window-event', self.__windowEvent) # Look for the startup Python file. This might be a magic # filename (like "__main__", or any filename that contains # invalid module characters), so we can't just import it # directly; instead, we go through the low-level importer. # If there's no p3d_info.xml file, we look for "main". moduleName = 'main' if self.p3dPackage: mainName = self.p3dPackage.Attribute('main_module') if mainName: moduleName = mainName # Temporarily set this flag while we import the app, so # that if the app calls run() within its own main.py, it # will properly get ignored by ShowBase. self.initialAppImport = True # Python won't let us import a module named __main__. So, # we have to do that manually, via the VFSImporter. if moduleName == '__main__': dirName = Filename(self.multifileRoot).toOsSpecific() importer = VFSImporter.VFSImporter(dirName) loader = importer.find_module('__main__') if loader is None: raise ImportError('No module named __main__') mainModule = loader.load_module('__main__') else: __import__(moduleName) mainModule = sys.modules[moduleName] # Check if it has a main() function. If so, call it. if hasattr(mainModule, 'main') and hasattr(mainModule.main, '__call__'): mainModule.main(self) # Now clear this flag. self.initialAppImport = False if self.interactiveConsole: # At this point, we have successfully loaded the app. # If the interactive_console flag is enabled, stop the # main loop now and give the user a Python prompt. taskMgr.stop()
def main(argv=None): if argv is None: argv = sys.argv parser = OptionParser() parser.add_option("-n", "--normals", dest="normals", help="regenerate normals with provided degree smoothing") parser.add_option("-b", "--binormals", dest="binormals", default=False, help="make binormals") parser.add_option("-c", "--coordinate-system", dest="coordinate", help="specific coordinate system") parser.add_option("-s", "--show", action="store_false", dest="show", default=False, help="show in pview") (options, args) = parser.parse_args() for infile in args: try: if ".obj" not in infile: print("WARNING", infile, "does not look like a valid obj file") continue obj = ObjFile(infile) egg = obj.toEgg(verbose=False) f, e = os.path.splitext(infile) outfile = f + ".egg" if options.normals is not None: egg.recomputeVertexNormals(float(options.normals)) if options.binormals: egg.recomputeTangentBinormal(GlobPattern("")) if options.coordinate is not None: a = options.coordinate if a == 'z-up' or a == 'z-up-right': coordSys = CSZupRight elif a == 'z-up-left': coordSys = CSZupLeft elif a == 'y-up' or a == 'y-up-right': coordSys = CSYupRight elif a == 'y-up-left': coordSys = CSYupLeft else: raise Exception('Unsupported coordinate system: %s' % (a)) egg.setCoordinateSystem(coordSys) egg.removeUnusedVertices(GlobPattern("")) #egg.triangulatePolygons(EggData.TConvex & EggData.TPolygon) #egg.recomputePolygonNormals() egg.writeEgg(Filename(outfile)) if options.show: os.system("pview " + outfile) except Exception as e: print(e) return 0
def handleFileList(models, fileList): if not fileList: return models for fileName in fileList: if fileName.get_filename().get_fullpath().endswith(('.bam', 'egg', '.pz')): if fileName.get_filename().get_fullpath() not in models: models.append(fileName.get_filename().get_fullpath()) else: handleFileList(models, vfs.scanDirectory(Filename(fileName.get_filename().get_fullpath())))
def initTorchParticles(self): torchTops = self.level.findAllMatches("**/TorchTop*") fxList = ['TorchSmoke.ptf', 'TorchFire.ptf'] for torch in torchTops: for fx in fxList: p = ParticleEffect() p.loadConfig(Filename(fx)) p.setPos(torch.getPos(render)) p.start(self.level)
def findNewsDir(self): if self.NewsOverHttp: return self.NewsStageDir searchPath = DSearchPath() if AppRunnerGlobal.appRunner: searchPath.appendDirectory(Filename.expandFrom('$TT_3_5_ROOT/phase_3.5/models/news')) else: basePath = os.path.expandvars('$TTMODELS') or './ttmodels' searchPath.appendDirectory(Filename.fromOsSpecific(basePath + '/built/' + self.NewsBaseDir)) searchPath.appendDirectory(Filename(self.NewsBaseDir)) pfile = Filename(self.NewsIndexFilename) found = vfs.resolveFilename(pfile, searchPath) if not found: self.notify.warning('findNewsDir - no path: %s' % self.NewsIndexFilename) self.setErrorMessage(TTLocalizer.NewsPageErrorDownloadingFile % self.NewsIndexFilename) return None self.notify.debug('found index file %s' % pfile) realDir = pfile.getDirname() return realDir
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 outputDNA(filename): print('Saving DNA to: ', filename) binaryFilename = Filename(filename) binaryFilename.setBinary() base.le.DNAData.writeDna(binaryFilename, Notify.out(), DNASTORE) base.le.popupNotification( f"Saved to {os.path.basename(binaryFilename)}") if ConfigVariableString("compiler") in ['libpandadna', 'clash']: print(f"Compiling PDNA for {ConfigVariableString('compiler')}") DNASerializer.compileDNA(binaryFilename)
def load_preview_model(self): p_str = "{}/{}_{}_{}.bam".format(self.path, self.name, self.preview_type, self.preview_rec) model_file = Filename(p_str) self.pre_model_np = loader.loadModel(model_file).getChildren()[0] SM.set_planet_shaders(self, self.pre_model_np, self.preview_type) self.pre_model_np.setShaderInput("light_vec", LVector3f(-1, 0, 0)) self.pre_model_np.setShaderInput("atmos_vals", LVector4f(0, 0, 0, 0)) self.pre_model_np.setShaderInput("body_dir", LVector3f(0, 1, 0)) ### return self.pre_model_np
def loadModel(modelPath): loader = Loader.getGlobalPtr() loaderOptions = LoaderOptions() node = loader.loadSync(Filename(modelPath), loaderOptions) if node is not None: nodePath = NodePath(node) nodePath.setTag('model-filename', os.path.abspath(modelPath)) else: raise IOError('Could not load model file: %s' % (modelPath)) return nodePath
def fromFile(self, packageDir, filename, pathname=None, st=None): """ Reads the file information from the indicated file. If st is supplied, it is the result of os.stat on the filename. """ vfs = VirtualFileSystem.getGlobalPtr() filename = Filename(filename) if pathname is None: pathname = Filename(packageDir, filename) self.filename = filename.cStr() self.basename = filename.getBasename() if st is None: st = os.stat(pathname.toOsSpecific()) self.size = st.st_size self.timestamp = st.st_mtime self.readHash(pathname)
def crea_mf(name): name_r = name + "_r" + str(sys.argv[1]) if os.path.exists("arcns_mfs/" + name_r + ".mf"): if os.stat(name).st_mtime <= os.stat("arcns_mfs/" + name_r + ".mf").st_mtime: return else: os.unlink("arcns_mfs/" + name_r + ".mf") mf = Multifile() mf.openWrite("arcns_mfs/" + name_r + ".mf") for root, dirs, files in os.walk(name): for f in files: if f[-1] == "~" or f[-3:] == "pyc" or f[-3:] == "pyo" or f[ -3:] == "bam": pass elif f[-2:] == "py": if os.path.exists(f + "o") and os.stat(f).st_mtime <= os.stat( f + "o").st_mtime: pass else: py_compile.compile(root + "/" + f) fln = Filename(root + "/" + f + "o") fln.set_binary() mf.addSubfile(root + "/" + f + "o", fln, 6) elif f[-3:] == "egg": if os.path.exists(root + "/" + f[:-3] + "bam") and os.stat( root + "/" + f).st_mtime <= os.stat( root + "/" + f[:-3] + "bam").st_mtime: pass else: if os.path.exists(root + "/" + f[:-3] + "bam"): os.unlink(root + "/" + f[:-3] + "bam") os.system("egg2bam -o " + root + "/" + f[:-3] + "bam " + root + "/" + f) fln = Filename(root + "/" + f[:-3] + "bam") fln.set_binary() mf.addSubfile(root + "/" + f[:-3] + "bam", fln, 6) elif f[-3:] == "wav": fln = Filename(root + "/" + f) fln.set_binary() mf.addSubfile(root + "/" + f, fln, 6) mf.close()
def __applyPatch(self, step, patchfile): """ Applies the indicated patching in-place to the current uncompressed archive. The patchfile is removed after the operation. Yields one of stepComplete, stepFailed, restartDownload, or stepContinue. """ self.updated = True origPathname = Filename(self.getPackageDir(), self.uncompressedArchive.filename) patchPathname = Filename(self.getPackageDir(), patchfile.file.filename) result = Filename.temporary('', 'patch_') self.notify.info("Patching %s with %s" % (origPathname, patchPathname)) p = core.Patchfile() # The C++ class ret = p.initiate(patchPathname, origPathname, result) if ret == EUSuccess: ret = p.run() while ret == EUOk: step.bytesDone = step.bytesNeeded * p.getProgress() self.__updateStepProgress(step) if taskMgr.destroyed: # If the task manager has been destroyed, we must # be shutting down. Get out of here. self.notify.warning("Task Manager destroyed, aborting patch %s" % (origPathname)) yield self.stepFailed; return yield self.stepContinue ret = p.run() del p patchPathname.unlink() if ret < 0: self.notify.warning("Patching of %s failed." % (origPathname)) result.unlink() yield self.stepFailed; return if not result.renameTo(origPathname): self.notify.warning("Couldn't rename %s to %s" % (result, origPathname)) yield self.stepFailed; return yield self.stepComplete; return
def _read_code(self): """ Returns the Python compiled code object for this file, if it is available, or None if it is not. May raise IOError, ValueError, SyntaxError, or a number of other errors generated by the low-level system. """ if self.fileType == FTPythonCompiled: # It's a pyc file; just read it directly. pycVfile = vfs.getFile(self.filename, False) if pycVfile: return self._loadPyc(pycVfile, None) raise IOError, 'Could not read %s' % (self.filename) elif self.fileType == FTExtensionModule: return None # It's a .py file (or an __init__.py file; same thing). Read # the .pyc file if it is available and current; otherwise read # the .py file and compile it. t_pyc = None for ext in compiledExtensions: pycFilename = Filename(self.filename) pycFilename.setExtension(ext) pycVfile = vfs.getFile(pycFilename, False) if pycVfile: t_pyc = pycVfile.getTimestamp() break code = None if t_pyc and t_pyc >= self.timestamp: try: code = self._loadPyc(pycVfile, self.timestamp) except ValueError: code = None if not code: source = self._read_source() filename = Filename(self.filename) filename.setExtension('py') code = self._compile(filename, source) return code
def start(self): taskMgr.remove('TT-birds') base.musicManager.stopAllSounds() base.lockMusic() self.musicSequence = Sequence( Func(base.playMusic, self.introMusic, looping=0, volume=1, playLocked=True), Wait(self.introMusic.length()), Func(base.playMusic, self.music, looping=1, volume=1, playLocked=True)) self.musicSequence.start() if __debug__: skyblue2Filename = Filename( '../resources/phase_3.5/maps/skyblue2_invasion.jpg') middayskyBFilename = Filename( '../resources/phase_3.5/maps/middayskyB_invasion.jpg') toontown_central_tutorial_palette_4amla_1Filename = Filename( '../resources/phase_3.5/maps/toontown_central_tutorial_palette_4amla_1_invasion.jpg' ) toontown_central_tutorial_palette_4amla_1_aFilename = Filename( '../resources/phase_3.5/maps/toontown_central_tutorial_palette_4amla_1_a_invasion.rgb' ) else: skyblue2Filename = Filename( '/phase_3.5/maps/skyblue2_invasion.jpg') middayskyBFilename = Filename( '/phase_3.5/maps/middayskyB_invasion.jpg') toontown_central_tutorial_palette_4amla_1Filename = Filename( '/phase_3.5/maps/toontown_central_tutorial_palette_4amla_1_invasion.jpg' ) toontown_central_tutorial_palette_4amla_1_aFilename = Filename( '/phase_3.5/maps/toontown_central_tutorial_palette_4amla_1_a_invasion.rgb' ) self.cr.playGame.hood.sky.findTexture('skyblue2').read( skyblue2Filename) self.cr.playGame.hood.sky.findTexture('middayskyB').read( middayskyBFilename) self.cr.playGame.hood.sky.findTexture( 'toontown_central_tutorial_palette_4amla_1').read( toontown_central_tutorial_palette_4amla_1Filename, toontown_central_tutorial_palette_4amla_1_aFilename, 0, 0) render.setColorScale(Vec4(0.85, 0.65, 0.65, 1)) aspect2d.setColorScale(Vec4(0.85, 0.65, 0.65, 1))
class ParticleEffects: base.enableParticles() p = ParticleEffect() p.cleanup() p = ParticleEffect() p.loadConfig(Filename('bullet_trail.ptf')) p.setH(-90) p.setY(20) def __init__(self, t): ParticleEffects.p.start(t)
def loadModel(modelPath): loader = Loader.getGlobalPtr() # NOTE: disable disk and RAM caching to avoid filling memory when loading multiple scenes loaderOptions = LoaderOptions(LoaderOptions.LF_no_cache) node = loader.loadSync(Filename(modelPath), loaderOptions) if node is not None: nodePath = NodePath(node) nodePath.setTag('model-filename', os.path.abspath(modelPath)) else: raise IOError('Could not load model file: %s' % (modelPath)) return nodePath
def saveNewsCache(self): cacheIndexFilename = Filename(self.newsDir, self.CacheIndexFilename) try: file = open(cacheIndexFilename.toOsSpecific(), 'w') except IOError as e: self.notify.warning('error opening news cache file %s: %s' % (cacheIndexFilename, str(e))) return for filename, (size, date) in self.newsCache.items(): print >> file, '%s\t%s\t%s' % (filename, size, date)
def applyFile(self, filename): mf = Multifile() mf.openReadWrite(Filename(os.path.join(self.packPath, filename))) for subfilename in mf.getSubfileNames(): if os.path.splitext(subfilename)[1] not in SupportedExtensions: mf.removeSubfile(subfilename) print 'Removing a file that is not allowed: %s' % str( subfilename) self.vfSys.mount(mf, self.mountPoint, 0) print 'Successfully Mounted: ' + str(filename)
def parseNewsContent(self): existingSectionIndex = 0 for section, ident in enumerate(self.SectionIdents): subSectionList = [] curSubSection = 0 endSearch = False while not endSearch: justName = self.ContentPattern % (self.dateStr, ident, curSubSection + 1) fullName = Filename(self.newsDir + '/' + justName) if self.strFilenames: if justName in self.strFilenames: subSectionList.append(fullName) self.flatSubsectionList.append( (existingSectionIndex, curSubSection)) curSubSection += 1 else: endSearch = True else: theFile = vfs.getFile(Filename(fullName), status_only=1) if theFile: subSectionList.append(fullName) self.flatSubsectionList.append( (existingSectionIndex, curSubSection)) curSubSection += 1 else: if curSubSection == 0 and self.isSectionInIndex(ident): self.notify.warning('could not find %s' % fullName) subSectionList.append(fullName) self.flatSubsectionList.append( (existingSectionIndex, curSubSection)) endSearch = True if not subSectionList: pass else: self.sectionList.append(subSectionList) existingSectionIndex += 1 self.notify.debug('IssueFrameV2 self.sectionList=%s' % self.sectionList)
def __apply_Textures(self, recipe, tex_dict): for i, ter_dict in enumerate(recipe['terrains']): tex_img = PNMImage() tex_img.read( Filename("{}/tex/{}".format(recipe['planet_path'], ter_dict['texture']))) tex = Texture() tex.load(tex_img) tex.setMinfilter(Texture.FTLinear) ts = TextureStage(str(i)) ts.setSort(i) self.NP.setTexture(ts, tex, i * 10)
def rmtree(self, filename): """ This is like shutil.rmtree(), but it can remove read-only files on Windows. It receives a Filename, the root directory to delete. """ if filename.isDirectory(): for child in filename.scanDirectory(): self.rmtree(Filename(filename, child)) if not filename.rmdir(): print("could not remove directory %s" % (filename)) else: if not filename.unlink(): print("could not delete %s" % (filename))
def _read_source(self): """ Returns the Python source for this file, if it is available, or None if it is not. May raise IOError. """ if self.desc[2] == imp.PY_COMPILED or \ self.desc[2] == imp.C_EXTENSION: return None filename = Filename(self.filename) filename.setExtension('py') filename.setText() return open(self.filename, self.desc[1]).read()
def do_load_texture(self, filename, alpha_filename): tex = Texture() panda_filename = Filename.from_os_specific(filename) if alpha_filename is not None: panda_alpha_filename = Filename.from_os_specific(alpha_filename) else: panda_alpha_filename = Filename('') tex.read(fullpath=panda_filename, alpha_fullpath=panda_alpha_filename, primary_file_num_channels=0, alpha_file_channel=0) return tex
def draw(self): self.model.reparentTo(render) self.p = ParticleEffect() self.p.loadConfig(Filename('data/particles/fireish.ptf')) self.p.setR(180) self.p.setScale(0.25) # Sets particles to birth relative to the teapot, but to render at # toplevel self.p.start(self.model) self.p.setPos(0.000, 0.000, 0.000)
def __init__(self, _cWriter, _cManager, _cReader): DirectObject.__init__(self) # notify self.notify = directNotify.newCategory("level_holder") # so we can send messages self.messager = Messager(_cWriter, _cManager, _cReader, self) # Create stuff we don't want to keep recreating because of their permanence self.players = {} self.day = 0 self.killer = False self.red_room = 0 self.vfs = VirtualFileSystem.getGlobalPtr() # these are used in nearly every level, just keep it loaded self.vfs.mount(Filename("mf/pawns.mf"), ".", VirtualFileSystem.MFReadOnly) self.vfs.mount(Filename("mf/timer.mf"), ".", VirtualFileSystem.MFReadOnly) # console self.console = None self.accept("`", self.pressed_tilda) # Levels self.levels = { MAINMENU: MainMenuLevel(self), LOBBY: LobbyLevel(self), DAY: DayLevel(self), NIGHT: NightLevel(self) } # Set active level self.active_level = MAINMENU self.levels[self.active_level].create() atexit.register(self.exit_game) self.notify.debug("[__init__] Created level_holder")