Exemplo n.º 1
0
    def loadMultifilePrcFiles(self, mf, root):
        """ Loads any prc files in the root of the indicated
        Multifile, which is presumed to have been mounted already
        under root. """

        # We have to load these prc files explicitly, since the
        # ConfigPageManager can't directly look inside the vfs.  Use
        # the Multifile interface to find the prc files, rather than
        # vfs.scanDirectory(), so we only pick up the files in this
        # particular multifile.
        cpMgr = ConfigPageManager.getGlobalPtr()
        for f in mf.getSubfileNames():
            fn = Filename(f)
            if fn.getDirname() == '' and fn.getExtension() == 'prc':
                pathname = '%s/%s' % (root, f)

                alreadyLoaded = False
                for cpi in range(cpMgr.getNumImplicitPages()):
                    if cpMgr.getImplicitPage(cpi).getName() == pathname:
                        # No need to load this file twice.
                        alreadyLoaded = True
                        break

                if not alreadyLoaded:
                    data = file.open(Filename(pathname), 'r').read()
                    cp = loadPrcFileData(pathname, data)
                    # Set it to sort value 20, behind the implicit pages.
                    cp.setSort(20)
Exemplo n.º 2
0
    def _compile(self, filename, source):
        """ Compiles the Python source code to a code object and
        attempts to write it to an appropriate .pyc file.  May raise
        SyntaxError or other errors generated by the compiler. """
        
        if source and source[-1] != '\n':
            source = source + '\n'
        code = __builtin__.compile(source, filename.toOsSpecific(), 'exec')

        # try to cache the compiled code
        pycFilename = Filename(filename)
        pycFilename.setExtension(compiledExtensions[0])
        try:
            f = open(pycFilename.toOsSpecific(), 'wb')
        except IOError:
            pass
        else:
            f.write('\0\0\0\0')
            f.write(chr(self.timestamp & 0xff) +
                    chr((self.timestamp >> 8) & 0xff) +
                    chr((self.timestamp >> 16) & 0xff) +
                    chr((self.timestamp >> 24) & 0xff))
            f.write(marshal.dumps(code))
            f.flush()
            f.seek(0, 0)
            f.write(imp.get_magic())
            f.close()

        return code
Exemplo n.º 3
0
    def setInstanceInfo(self, rootDir, logDirectory, superMirrorUrl,
                        verifyContents, main, respectPerPlatform):
        """ Called by the browser to set some global information about
        the instance. """

        # rootDir is the root Panda3D install directory on the local
        # machine.
        self.rootDir = Filename.fromOsSpecific(rootDir)

        # logDirectory is the directory name where all log files end
        # up.
        if logDirectory:
            self.logDirectory = Filename.fromOsSpecific(logDirectory)
        else:
            self.logDirectory = Filename(rootDir, 'log')

        # The "super mirror" URL, generally used only by panda3d.exe.
        self.superMirrorUrl = superMirrorUrl

        # How anxious should we be about contacting the server for
        # the latest code?
        self.verifyContents = verifyContents

        # The initial "main" object, if specified.
        if main is not None:
            self.main = main

        self.respectPerPlatform = respectPerPlatform
        #self.notify.info("respectPerPlatform = %s" % (self.respectPerPlatform))

        # Now that we have rootDir, we can read the config file.
        self.readConfigXml()
Exemplo n.º 4
0
 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
Exemplo n.º 5
0
    def _compile(self, filename, source):
        """ Compiles the Python source code to a code object and
        attempts to write it to an appropriate .pyc file.  May raise
        SyntaxError or other errors generated by the compiler. """

        if source and source[-1] != "\n":
            source = source + "\n"
        code = compile(source, filename.toOsSpecific(), "exec")

        # try to cache the compiled code
        pycFilename = Filename(filename)
        pycFilename.setExtension(compiledExtensions[0])
        try:
            f = open(pycFilename.toOsSpecific(), "wb")
        except IOError:
            pass
        else:
            f.write(imp.get_magic())
            if sys.version_info >= (3, 0):
                f.write((self.timestamp & 0xFFFFFFFF).to_bytes(4, "little"))
                f.write(b"\0\0\0\0")
            else:
                f.write(
                    chr(self.timestamp & 0xFF)
                    + chr((self.timestamp >> 8) & 0xFF)
                    + chr((self.timestamp >> 16) & 0xFF)
                    + chr((self.timestamp >> 24) & 0xFF)
                )
            f.write(marshal.dumps(code))
            f.close()

        return code
    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")
Exemplo n.º 7
0
 def mouseTask(self, task):
     j = -1
     if base.mouseWatcherNode.hasMouse():
         mpos = base.mouseWatcherNode.getMouse()
         self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
         self.picker.traverse(self.staticRoot)
         if self.pq.getNumEntries() > 0:
             self.pq.sortEntries()
             for i in range(self.pq.getNumEntries()):
                 if self.pq.getEntry(i).getIntoNode().getTag('car') != "":
                     j = int(self.pq.getEntry(i).getIntoNode().getTag('car'))
                     carpos = self.staticCars[j].getPos()  
                     playerpos = self.player.getPos()
                     dist = math.sqrt( (carpos[0] - playerpos[0])**2 + (carpos[1] - playerpos[1])**2 + (carpos[2] - playerpos[2])**2 )
                     if self.gasList[j] > 0 and dist < DRAIN_DIST:
                         self.winprops.setCursorFilename(Filename.binaryFilename("vamp-icon.ico"))
                         base.win.requestProperties(self.winprops)
                     elif self.gasList[j] > 0:
                         self.winprops.setCursorFilename(Filename.binaryFilename("vamp-off.ico"))
                         base.win.requestProperties(self.winprops)
                     else:
                         self.winprops.setCursorFilename(Filename.binaryFilename("empty-icon.ico"))
                         base.win.requestProperties(self.winprops)
                     break
     if j == -1:
         self.winprops.setCursorFilename(Filename.binaryFilename("question-icon.ico"))
         base.win.requestProperties(self.winprops)
     #print j
     return Task.cont
Exemplo n.º 8
0
 def __init__(self, species, gender, head, features, torso_size, legs_size, path=""):
     """
     Args:
         species (str): "cat", "dog", "duck", "mouse", "pig", "rabbit",
             "bear", "horse" or "monkey".
         gender (str): "m" (male) or "f" (female).
         head (str): "n" (normal) or "l" (long).
         features (str): "n" (normal) or "l" (long).
         torso_size (str): "s" (small), "m" (medium) or "l" (long).
         legs_size (str): "s" (small), "m" (medium) or "l" (long).
         path (str, optional): The file path to the Toontown phase files.
             Defaults to Panda3D's search path.
     """
     global MODEL_PATH
     if path:
         self.path = pfile.fromOsSpecific("%s/" % path).getFullpath()
     else:
         self.path = pfile.fromOsSpecific("%s/" % MODEL_PATH).getFullpath()
     self.species = species
     self.gender = gender
     self.dimensions = torso_size, legs_size
     self.__make_actor(
         species, gender, head, features, torso_size, legs_size
     )
     Actor.__init__(self, self.parts, self.animation)
     self.__initialize_actor()
Exemplo n.º 9
0
    def downloadNextFile(self, task):
        while self.nextNewsFile < len(self.newsFiles) and 'aaver' in self.newsFiles[self.nextNewsFile]:
            self.nextNewsFile += 1

        if self.nextNewsFile >= len(self.newsFiles):
            self.notify.info('Done downloading news.')
            self.percentDownloaded = 1
            del self.newsFiles
            del self.nextNewsFile
            del self.newsUrl
            del self.newsDir
            del self.ch
            del self.url
            if hasattr(self, 'filename'):
                del self.filename
            self.redownloadingNews = False
            if self.active:
                self.parseNewsContent()
            return task.done
        self.percentDownloaded = float(self.nextNewsFile) / float(len(self.newsFiles))
        self.filename = self.newsFiles[self.nextNewsFile]
        self.nextNewsFile += 1
        self.url = self.newsUrl + self.filename
        localFilename = Filename(self.newsDir, self.filename)
        self.notify.info('testing for %s' % localFilename.getFullpath())
        doc = DocumentSpec(self.url)
        if self.filename in self.newsCache:
            size, date = self.newsCache[self.filename]
            if date and localFilename.exists() and (size == 0 or localFilename.getFileSize() == size):
                doc.setDate(date)
                doc.setRequestMode(doc.RMNewer)
        self.ch.beginGetDocument(doc)
        self.ch.downloadToFile(localFilename)
        taskMgr.remove(self.RedownloadTaskName)
        taskMgr.add(self.downloadCurrentFileTask, self.RedownloadTaskName)
Exemplo n.º 10
0
    def downloadIndexTask(self, task):
        if self.ch.run():
            return task.cont
        if not self.ch.isValid():
            self.notify.warning('Unable to download %s' % self.url)
            self.redownloadingNews = False
            return task.done
        self.newsFiles = []
        filename = self.rf.readline()
        while filename:
            filename = filename.strip()
            if filename:
                self.newsFiles.append(filename)
            filename = self.rf.readline()

        del self.rf
        self.newsFiles.sort()
        self.newsIndexEntries = list(self.newsFiles)
        self.notify.info('Server lists %s news files' % len(self.newsFiles))
        self.notify.debug('self.newsIndexEntries=%s' % self.newsIndexEntries)
        self.readNewsCache()
        for basename in os.listdir(self.newsDir.toOsSpecific()):
            if basename != self.CacheIndexFilename and basename not in self.newsCache:
                junk = Filename(self.newsDir, basename)
                self.notify.info('Removing %s' % junk)
                junk.unlink()

        self.nextNewsFile = 0
        return self.downloadNextFile(task)
Exemplo n.º 11
0
    def getLoadedDirname(self, mod):
        """ Returns the directory name that the indicated
        conventionally-loaded module must have been loaded from. """

        fullname = mod.__name__
        dirname = Filename.fromOsSpecific(mod.__file__).getDirname()

        parentname = None
        basename = fullname
        if '.' in fullname:
            parentname, basename = fullname.rsplit('.', 1)

        path = None
        if parentname:
            parent = sys.modules[parentname]
            path = parent.__path__
        if path is None:
            path = sys.path

        for dir in path:
            pdir = Filename.fromOsSpecific(dir).cStr()
            if pdir + '/' + basename == dirname:
                # We found it!
                return dir

        # Couldn't figure it out.
        return None
Exemplo n.º 12
0
    def downloadDescFileGenerator(self, http):
        """ A generator function that implements downloadDescFile()
        one piece at a time.  It yields one of stepComplete,
        stepFailed, or stepContinue. """

        assert self.descFile

        if self.hasDescFile:
            # We've already got one.
            yield self.stepComplete; return

        if not self.host.appRunner or self.host.appRunner.verifyContents != self.host.appRunner.P3DVCNever:
            # We're allowed to download it.
            self.http = http

            func = lambda step, self = self: self.__downloadFile(
                None, self.descFile,
                urlbase = self.descFile.filename,
                filename = self.descFileBasename)
            step = self.InstallStep(func, self.descFile.size, self.downloadFactor, 'downloadDesc')

            for token in step.func():
                if token == self.stepContinue:
                    yield token
                else:
                    break

            while token == self.restartDownload:
                # Try again.
                func = lambda step, self = self: self.__downloadFile(
                    None, self.descFile,
                    urlbase = self.descFile.filename,
                    filename = self.descFileBasename)
                step = self.InstallStep(func, self.descFile.size, self.downloadFactor, 'downloadDesc')
                for token in step.func():
                    if token == self.stepContinue:
                        yield token
                    else:
                        break

            if token == self.stepFailed:
                # Couldn't download the desc file.
                yield self.stepFailed; return

            assert token == self.stepComplete

            filename = Filename(self.getPackageDir(), self.descFileBasename)
            # Now that we've written the desc file, make it read-only.
            os.chmod(filename.toOsSpecific(), 0o444)

        if not self.__readDescFile():
            # Weird, it passed the hash check, but we still can't read
            # it.
            filename = Filename(self.getPackageDir(), self.descFileBasename)
            self.notify.warning("Failure reading %s" % (filename))
            yield self.stepFailed; return

        yield self.stepComplete; return
Exemplo n.º 13
0
    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)
Exemplo n.º 14
0
 def __refresh_Sys_Recipes(self):
     sys_dir_path = Filename("{}/*.shv".format(_path.SYSTEMS))
     sys_files = glob(sys_dir_path.toOsLongName())
     sys_recipes = {}
     for sys_file in sys_files:
         base_name = os_path.basename(sys_file)
         sys_name = os_path.splitext(base_name)[0]
         sys_recipes[sys_name] = SC.compile_sys_recipe(sys_file)
     return sys_recipes
Exemplo n.º 15
0
def dummyAppRunner(tokens = [], argv = None):
    """ This function creates a dummy global AppRunner object, which
    is useful for testing running in a packaged environment without
    actually bothering to package up the application.  Call this at
    the start of your application to enable it.

    It places the current working directory under /mf, as if it were
    mounted from a packed multifile.  It doesn't convert egg files to
    bam files, of course; and there are other minor differences from
    running in an actual packaged environment.  But it can be a useful
    first-look sanity check. """

    if AppRunnerGlobal.appRunner:
        print("Already have AppRunner, not creating a new one.")
        return AppRunnerGlobal.appRunner

    appRunner = AppRunner()
    appRunner.dummy = True
    AppRunnerGlobal.appRunner = appRunner

    platform = PandaSystem.getPlatform()
    version = PandaSystem.getPackageVersionString()
    hostUrl = PandaSystem.getPackageHostUrl()

    if platform.startswith('win'):
        rootDir = Filename(Filename.getUserAppdataDirectory(), 'Panda3D')
    elif platform.startswith('osx'):
        rootDir = Filename(Filename.getHomeDirectory(), 'Library/Caches/Panda3D')
    else:
        rootDir = Filename(Filename.getHomeDirectory(), '.panda3d')

    appRunner.rootDir = rootDir
    appRunner.logDirectory = Filename(rootDir, 'log')

    # Of course we will have the panda3d application loaded.
    appRunner.addPackageInfo('panda3d', platform, version, hostUrl)

    appRunner.tokens = tokens
    appRunner.tokenDict = dict(tokens)
    if argv is None:
        argv = sys.argv
    appRunner.argv = argv
    appRunner.altHost = appRunner.tokenDict.get('alt_host', None)

    appRunner.p3dInfo = None
    appRunner.p3dPackage = None

    # Mount the current directory under the multifileRoot, as if it
    # were coming from a multifile.
    cwd = ExecutionEnvironment.getCwd()
    vfs = VirtualFileSystem.getGlobalPtr()
    vfs.mount(cwd, appRunner.multifileRoot, vfs.MFReadOnly)

    appRunner.initPackedAppEnvironment()

    return appRunner
Exemplo n.º 16
0
    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()
Exemplo n.º 17
0
    def __scanDirectoryRecursively(self, dirname):
        """ Generates a list of Filename objects: all of the files
        (not directories) within and below the indicated dirname. """

        contents = []
        for dirpath, dirnames, filenames in os.walk(dirname.toOsSpecific()):
            dirpath = Filename.fromOsSpecific(dirpath)
            if dirpath == dirname:
                dirpath = Filename('')
            else:
                dirpath.makeRelativeTo(dirname)
            for filename in filenames:
                contents.append(Filename(dirpath, filename))
        return contents
Exemplo n.º 18
0
    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()
        vfile = vfs.getFile(filename)
        if not vfile:
            raise IOError("Could not find '%s'" % (filename))
        return vfile.readFile(True)
Exemplo n.º 19
0
 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.fileType == FTPythonCompiled or \
        self.fileType == FTExtensionModule:
         return None
     
     filename = Filename(self.filename)
     filename.setExtension('py')
     filename.setText()
     vfile = vfs.getFile(filename)
     if not vfile:
         raise IOError
     return vfile.readFile(True)
Exemplo n.º 20
0
    def find_module(self, fullname, path = None):
        if path is None:
            dir_path = self.dir_path
        else:
            dir_path = path
        #print >>sys.stderr, "find_module(%s), dir_path = %s" % (fullname, dir_path)
        basename = fullname.split('.')[-1]
        path = Filename(dir_path, basename)

        # First, look for Python files.
        filename = Filename(path)
        filename.setExtension('py')
        vfile = vfs.getFile(filename, True)
        if vfile:
            return VFSLoader(dir_path, vfile, filename,
                             desc=('.py', 'U', imp.PY_SOURCE))

        # If there's no .py file, but there's a .pyc file, load that
        # anyway.
        for ext in compiledExtensions:
            filename = Filename(path)
            filename.setExtension(ext)
            vfile = vfs.getFile(filename, True)
            if vfile:
                return VFSLoader(dir_path, vfile, filename,
                                 desc=('.'+ext, 'rb', imp.PY_COMPILED))

        # Look for a C/C++ extension module.
        for desc in imp.get_suffixes():
            if desc[2] != imp.C_EXTENSION:
                continue

            filename = Filename(path + desc[0])
            vfile = vfs.getFile(filename, True)
            if vfile:
                return VFSLoader(dir_path, vfile, filename, desc=desc)

        # Finally, consider a package, i.e. a directory containing
        # __init__.py.
        filename = Filename(path, '__init__.py')
        vfile = vfs.getFile(filename, True)
        if vfile:
            return VFSLoader(dir_path, vfile, filename, packagePath=path,
                             desc=('.py', 'U', imp.PY_SOURCE))
        for ext in compiledExtensions:
            filename = Filename(path, '__init__.' + ext)
            vfile = vfs.getFile(filename, True)
            if vfile:
                return VFSLoader(dir_path, vfile, filename, packagePath=path,
                                 desc=('.'+ext, 'rb', imp.PY_COMPILED))

        #print >>sys.stderr, "not found."
        return None
Exemplo n.º 21
0
    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()
Exemplo n.º 22
0
def parseSysArgs():
    """ Handles sys.argv, if there are any local arguments, and
    returns a new argv suitable for passing into the
    application. """

    # We prefix a "+" sign, following the GNU convention, to tell
    # getopt not to parse options following the first non-option
    # parameter.
    opts, args = getopt.getopt(sys.argv[1:], '+h')

    for option, value in opts:
        if option == '-h':
            print __doc__
            sys.exit(1)

    if not args or not args[0]:
        raise ArgumentError, "No Panda app specified.  Use:\nrunp3d.py app.p3d"

    arg0 = args[0]
    p3dFilename = Filename.fromOsSpecific(arg0)
    if p3dFilename.exists():
        p3dFilename.makeAbsolute()
        arg0 = p3dFilename.toOsSpecific()

    return [arg0] + args[1:]
Exemplo n.º 23
0
    def redownloadNews(self):
        if self.redownloadingNews:
            self.notify.warning('averting potential crash redownloadNews called twice, just returning')
            return
        self.percentDownloaded = 0.0
        self.notify.info('starting redownloadNews')
        self.startRedownload = datetime.datetime.now()
        self.redownloadingNews = True
        self.addDownloadingTextTask()
        for issue in self.issues:
            issue.destroy()

        self.issues = []
        self.curIssueIndex = 0
        self.strFilenames = None
        self.needsParseNews = True
        self.newsUrl = self.getInGameNewsUrl()
        self.newsDir = Filename(self.findNewsDir())
        Filename(self.newsDir + '/.').makeDir()
        http = HTTPClient.getGlobalPtr()
        self.url = self.newsUrl + self.NewsIndexFilename
        self.ch = http.makeChannel(True)
        self.ch.beginGetDocument(self.url)
        self.rf = Ramfile()
        self.ch.downloadToRam(self.rf)
        taskMgr.remove(self.RedownloadTaskName)
        taskMgr.add(self.downloadIndexTask, self.RedownloadTaskName)
        return
 def setupBackgroundImage(self):    
   
   image_file = Filename(TestGameBase.__BACKGROUND_IMAGE_PATH__)
   
   # check if image can be loaded
   img_head = PNMImageHeader()
   if not img_head.readHeader(image_file ):
       raise IOError("PNMImageHeader could not read file %s. Try using absolute filepaths"%(image_file.c_str()))
       sys.exit()
       
   # Load the image with a PNMImage
   w = img_head.getXSize()
   h = img_head.getYSize()
   img = PNMImage(w,h)
   #img.alphaFill(0)
   img.read(image_file) 
   
   texture = Texture()        
   texture.setXSize(w)
   texture.setYSize(h)
   texture.setZSize(1)    
   texture.load(img)
   texture.setWrapU(Texture.WM_border_color) # gets rid of odd black edges around image
   texture.setWrapV(Texture.WM_border_color)
   texture.setBorderColor(LColor(0,0,0,0))
   
   # creating CardMaker to hold the texture
   cm = CardMaker('background')
   cm.setFrame(-0.5*w,0.5*w,-0.5*h,0.5*h)  # This configuration places the image's topleft corner at the origin (left, right, bottom, top)
   background_np = NodePath(cm.generate())            
   background_np.setTexture(texture)
   
   background_np.reparentTo(self.render)
   background_np.setPos(TestGameBase.__BACKGROUND_POSITION__)
   background_np.setScale(TestGameBase.__BACKGROUND_SCALE__)
Exemplo n.º 25
0
 def changeMouseCursor(self, cursorFile):
     if self.currIcon != cursorFile:
         self.currIcon = cursorFile
         # winprops.getParentWindow().getXSize()
         # print winprops.getXSize()
         # print "test"
         self.winprops.setCursorFilename(Filename.binaryFilename(cursorFile))
Exemplo n.º 26
0
    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()
Exemplo n.º 27
0
    def load(self, filename):
        """ Loads a profile from a given filename """

        # Make filename unique

        fname = Filename.from_os_specific(filename)
        if not VirtualFileSystem.get_global_ptr().resolve_filename(fname, get_model_path().get_value(), "ies"):
            self.error("Could not resolve", filename)
            return -1
        fname = fname.get_fullpath()

        # Check for cache entries
        if fname in self._entries:
            return self._entries.index(fname)

        # Check for out of bounds
        if len(self._entries) >= self._max_entries:
            # TODO: Could remove unused profiles here or regenerate texture
            self.warn("Cannot load IES Profile, too many loaded! (Maximum: 32)")

        # Try loading the dataset, and see what happes
        try:
            dataset = self._loader.load(fname)
        except IESLoaderException as msg:
            self.warn("Failed to load profile from", filename, ":", msg)
            return -1

        if not dataset:
            return -1

        # Dataset was loaded successfully, now copy it
        dataset.generate_dataset_texture_into(self._storage_tex, len(self._entries))
        self._entries.append(fname)

        return len(self._entries) - 1
Exemplo n.º 28
0
    def create_object(self):
        from panda3d.core import Filename, NodePath, BitMask32
        from direct.actor.Actor import Actor
        from panda3d.bullet import BulletRigidBodyNode, BulletCapsuleShape

        from game_system.resources import ResourceManager
        f = Filename.fromOsSpecific(ResourceManager.get_absolute_path(ResourceManager["TestAI"]["lp_char_bs.egg"]))
        model = Actor(f)

        bullet_node = BulletRigidBodyNode("TestAIBulletNode")
        bullet_nodepath = NodePath(bullet_node)

        bullet_node.set_angular_factor((0, 0, 1))

        shape = BulletCapsuleShape(0.3, 1.4, 2)
        bullet_node.addShape(shape)
        bullet_node.setMass(1.0)

        model.reparentTo(bullet_nodepath)
        model.set_hpr(180, 0, 0)
        model.set_pos(0, 0, -1)

        bullet_nodepath.set_collide_mask(BitMask32.bit(0))
        bullet_nodepath.set_python_tag("actor", model)

        return bullet_nodepath
Exemplo n.º 29
0
    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()
Exemplo n.º 30
0
 def __get_Recipe(self, planet_spec):
     if type(planet_spec) == type(""):
         # Shiva str.
         if "\n" in planet_spec:
             recipe = SC.compile_body_recipe(planet_spec)
         # Planet name.
         else:
             shv_path = Filename("{}/{}/{}.shv".format(_path.BODIES, planet_spec, planet_spec))
             with open(shv_path.toOsLongName()) as shv_file:
                 lines = shv_file.readlines()
             shiva_str = "".join(lines)
             recipe = SC.compile_body_recipe(shiva_str)
     # Recipe given.
     else:
         recipe = planet_spec
     
     return recipe
Exemplo n.º 31
0
    def load(self, filename):
        """ Loads a profile from a given filename and returns the internal
        used index which can be assigned to a light."""

        # Make sure the user can load profiles directly from the ies profile folder
        data_path = join("/$$rp/rpcore/data/ies_profiles/", filename)
        if isfile(data_path):
            filename = data_path

        # Make filename unique
        fname = Filename.from_os_specific(filename)
        if not VirtualFileSystem.get_global_ptr().resolve_filename(
                fname,
                get_model_path().get_value(), "ies"):
            self.error("Could not resolve", filename)
            return -1
        fname = fname.get_fullpath()

        # Check for cache entries
        if fname in self._entries:
            return self._entries.index(fname)

        # Check for out of bounds
        if len(self._entries) >= self._max_entries:
            # TODO: Could remove unused profiles here or regenerate texture
            self.warn(
                "Cannot load IES Profile, too many loaded! (Maximum: 32)")

        # Try loading the dataset, and see what happes
        try:
            dataset = self._load_and_parse_file(fname)
        except InvalidIESProfileException as msg:
            self.warn("Failed to load profile from", filename, ":", msg)
            return -1

        if not dataset:
            return -1

        # Dataset was loaded successfully, now copy it
        dataset.generate_dataset_texture_into(self._storage_tex,
                                              len(self._entries))
        self._entries.append(fname)

        return len(self._entries) - 1
Exemplo n.º 32
0
    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.
            __builtin__.file = file.file
            __builtin__.open = file.open
            __builtin__.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()
Exemplo n.º 33
0
    def __init__(self, model, model_name, asset_type):
        self.model_name = model_name
        fn_p = Filename.expand_from('$MAIN_DIR/assets/{}/{}/{}.toml'.format(
            asset_type,
            model_name,
            model_name,
        ))
        fn = fn_p.to_os_specific()
        self.specs = {}
        file_exists = os.path.isfile(fn)
        if file_exists:
            with open(fn, 'r') as f:
                self.specs = toml.load(f)

        self.read_model(model, model_name, self.specs)

        if not file_exists:
            with open(fn, 'w') as f:
                toml.dump(self.specs, f)
Exemplo n.º 34
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        opts, args = getopt.getopt(argv[1:], "hn:bs",
                                   ["help", "normals", "binormals", "show"])
    except getopt.error as msg:
        print(msg)
        print(__doc__)
        return 2
    show = False
    for o, a in opts:
        if o in ("-h", "--help"):
            print(__doc__)
            return 0
        elif o in ("-s", "--show"):
            show = True
    for infile in args:
        try:
            if ".obj" not in infile:
                print("WARNING", finfile,
                      "does not look like a valid obj file")
                continue
            obj = ObjFile(infile)
            egg = obj.toEgg()
            f, e = os.path.splitext(infile)
            outfile = f + ".egg"
            for o, a in opts:
                if o in ("-n", "--normals"):
                    egg.recomputeVertexNormals(float(a))
                elif o in ("-b", "--binormals"):
                    egg.recomputeTangentBinormal(GlobPattern(""))
            egg.removeUnusedVertices(GlobPattern(""))
            if True:
                egg.triangulatePolygons(EggData.TConvex & EggData.TPolygon)
            if True:
                egg.recomputePolygonNormals()
            egg.writeEgg(Filename(outfile))
            if show:
                os.system("pview " + outfile)
        except Exception as e:
            print(e)
    return 0
Exemplo n.º 35
0
    def __init__(self,
                 file,
                 name=None,
                 pos=(0.0, 0.0, 0.0),
                 scale=(1.0, 1.0, 1.0)):

        self.particleEffect = None
        self.configFile = file
        self.name = name
        self.position = pos
        self.scale = scale

        self.particleEffect = ParticleEffect(name)
        self.particleEffect.loadConfig(Filename(file))

        self.particleEffect.setPos(pos[0], pos[1], pos[2])
        self.particleEffect.setScale(scale[0], scale[1], scale[2])

        base.enableParticles()
Exemplo n.º 36
0
    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
Exemplo n.º 37
0
    def __scanDirectoryRecursively(self, dirname):
        """ Generates a list of Filename objects: all of the files
        (not directories) within and below the indicated dirname. """

        contents = []
        for dirpath, dirnames, filenames in os.walk(dirname.toOsSpecific()):
            dirpath = Filename.fromOsSpecific(dirpath)
            if dirpath == dirname:
                dirpath = Filename('')
            else:
                dirpath.makeRelativeTo(dirname)
            for filename in filenames:
                contents.append(Filename(dirpath, filename))
        return contents
Exemplo n.º 38
0
    def __init__(self, reason):
        Notifier.__init__(self, "alert")
        VirtualFileSystem.getGlobalPtr().mount(Filename("mf/alert.mf"), ".",
                                               VirtualFileSystem.MFReadOnly)
        ok = loader.loadModel("alert.egg")

        if reason not in LOCAL_EN:
            reason = GENERAL

        self.reason = reason

        self.bg_frame = DirectFrame(frameColor=(0, 0, 0, 0),
                                    frameSize=(-1, 1, -1, 1),
                                    suppressMouse=1,
                                    state=DGG.NORMAL,
                                    sortOrder=1000)
        self.frame = DirectFrame(frameSize=(1, 1, 1, 1),
                                 image=ok.find('**/alert'),
                                 image_scale=(1, 0, 0.6),
                                 state=DGG.NORMAL,
                                 parent=self.bg_frame)
        self.text = OnscreenText(text=LOCAL_EN[reason],
                                 fg=(1, 1, 1, 1),
                                 pos=(0, 0.15, 0),
                                 align=TextNode.ACenter,
                                 wordwrap=13,
                                 parent=self.frame)
        self.button = DirectButton(geom=(ok.find('**/ok-ready'),
                                         ok.find('**/ok-click'),
                                         ok.find('**/ok-hover'),
                                         ok.find('**/ok-click')),
                                   relief=None,
                                   geom_scale=(0.3, 0, 0.15),
                                   geom_pos=(0, 0, -0.175),
                                   pressEffect=0,
                                   command=self.destroy,
                                   parent=self.frame)

        self.notify.debug(
            f"[__init__] Created Alert with reason {self.reason}")

        loader.unloadModel(ok)
Exemplo n.º 39
0
    def _import_extension_module(self, fullname):
        """ Loads the binary shared object as a Python module, and
        returns it. """

        vfile = vfs.getFile(self.filename, False)

        # We can only import an extension module if it already exists on
        # disk.  This means if it's a truly virtual file that has no
        # on-disk equivalent, we have to write it to a temporary file
        # first.
        if hasattr(vfile, 'getMount') and \
           isinstance(vfile.getMount(), VirtualFileMountSystem):
            # It's a real file.
            filename = self.filename
        elif self.filename.exists():
            # It's a virtual file, but it's shadowing a real file in
            # the same directory.  Assume they're the same, and load
            # the real one.
            filename = self.filename
        else:
            # It's a virtual file with no real-world existence.  Dump
            # it to disk.  TODO: clean up this filename.
            filename = Filename.temporary(
                '',
                self.filename.getBasenameWoExtension(),
                '.' + self.filename.getExtension(),
                type=Filename.TDso)
            filename.setExtension(self.filename.getExtension())
            filename.setBinary()
            sin = vfile.openReadFile(True)
            sout = OFileStream()
            if not filename.openWrite(sout):
                raise IOError
            if not copyStream(sin, sout):
                raise IOError
            vfile.closeReadFile(sin)
            del sout

        module = imp.load_module(fullname, None, filename.toOsSpecific(),
                                 self.desc)
        module.__file__ = self.filename.toOsSpecific()
        return module
Exemplo n.º 40
0
    def createMap(self):

        height = 10.0
        img = PNMImage(Filename('resources/map1.bmp'))
        shape = BulletHeightfieldShape(img, height, ZUp)
        node = BulletRigidBodyNode('Map')
        node.setMass(99999999)
        node.addShape(shape)
        self.world.attachRigidBody(node)
        offset = img.getXSize() / 2.0 - 0.5
        terrain = GeoMipTerrain('terrain')
        terrain.setHeightfield(img)
        terrainNP = terrain.getRoot()
        terrainNP.setSz(height)
        terrainNP.setPos(-offset, -offset, -height / 2.0)
        #terrain.setColorMap('resources/map1color.bmp')
        terrain.setAutoFlatten(GeoMipTerrain.AFMOff)
        terrain.generate()

        return Map(terrainNP, node)
Exemplo n.º 41
0
    def __init__(self, path):
        if 'Image' in str(type(path)):
            # print('passing pil image!')
            image = path
            self._texture = PandaTexture()
            self._texture.setup2dTexture(image.width, image.height, PandaTexture.TUnsignedByte, PandaTexture.FRgba)
            self._texture.setRamImageAs(image.transpose(Image.FLIP_TOP_BOTTOM).tobytes(), image.mode)
            self._cached_image = image.transpose(Image.FLIP_TOP_BOTTOM)
            self.path = None

        elif type(path) == PandaTexture:
            self._texture = path

        else:
            self.path = Path(path)
            self._texture = loader.loadTexture(Filename.fromOsSpecific(path))

            self._cached_image = None   # for get_pixel() method

        self.filtering = Texture.default_filtering
Exemplo n.º 42
0
    def saveImage(self, path='testImg.png'):
        self.base.graphicsEngine.renderFrame()  # Rendering the frame
        self.base.graphicsEngine.renderFrame()  # Rendering the frame
        image = PNMImage()
        dr = self.base.camNode.getDisplayRegion(0)
        dr.getScreenshot(image)
        image.removeAlpha()
        image.write(Filename(path))

        # pre process for skeltonization
        gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        gray[gray < 150] = 0
        gray[gray >= 150] = 255
        kernel = np.ones((3, 3), np.uint8)
        gray = cv2.erode(gray, kernel)
        #gray = cv2.dilate(gray, kernel)
        #gray = cv2.resize(gray, (gray.shape[1]/2, gray.shape[0]/2))

        cv2.imwrite(path, gray)
        '''
Exemplo n.º 43
0
    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.fileType == FTPythonCompiled or \
           self.fileType == FTExtensionModule:
            return None

        filename = Filename(self.filename)
        filename.setExtension('py')
        filename.setText()
        vfile = vfs.getFile(filename)
        if not vfile:
            raise IOError
        return vfile.readFile(True)
Exemplo n.º 44
0
    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()
        vfile = vfs.getFile(filename)
        if not vfile:
            raise IOError("Could not find '%s'" % (filename))
        return vfile.readFile(True)
Exemplo n.º 45
0
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
Exemplo n.º 46
0
def obj2egg(infile,
            outfile,
            coordinateSystem='z-up',
            recomputeVertexNormals=False,
            recomputeTangentBinormal=False,
            recomputePolygonNormals=False,
            triangulatePolygons=False,
            degreeSmoothing=30.0):

    if coordinateSystem == 'z-up' or coordinateSystem == 'z-up-right':
        coordSys = CSZupRight
    elif coordinateSystem == 'z-up-left':
        coordSys = CSZupLeft
    elif coordinateSystem == 'y-up' or coordinateSystem == 'y-up-right':
        coordSys = CSYupRight
    elif coordinateSystem == 'y-up-left':
        coordSys = CSYupLeft
    else:
        raise Exception('Unsupported coordinate system: %s' %
                        (coordinateSystem))

    os.chdir(os.path.dirname(infile))
    obj = ObjFile(infile)
    egg = obj.toEgg()
    egg.setCoordinateSystem(coordSys)

    egg.removeUnusedVertices(GlobPattern(""))

    if recomputeVertexNormals:
        egg.recomputeVertexNormals(float(degreeSmoothing))

    if recomputeTangentBinormal:
        egg.recomputeTangentBinormal(GlobPattern(""))

    if recomputePolygonNormals:
        egg.recomputePolygonNormals()

    if triangulatePolygons:
        egg.triangulatePolygons(EggData.TConvex & EggData.TPolygon)

    egg.writeEgg(Filename(outfile))
Exemplo n.º 47
0
    def getBlockTex(hightmap, *loc):
        """returns the texture of the block

        given the position and hmap we crate a pandas texture to set the actor to
        this is an indev function and is subject to change

        @param hightmap: the hmap data to get data from
        @type hightmap: higthmap

        @param loc: the position of the block whos tex wer setting
        @type loc: 3 intagers

        @return: a pandas3d texture for the objects
        """
        # get panda path of this files dir
        path = Filename.fromOsSpecific(os.path.dirname(os.path.abspath(__file__)))
        # get witch text to load
        # it top most block make grass else dirt and bottom most wather
        imag = "wather" if loc[-1] == 0 else ("grass" if loc[-1] == hightmap[loc[:-1]] else "dirt")
        tex  = loader.loadTexture(f"{path}/blocks/{imag}.jpg")
        return tex
Exemplo n.º 48
0
    def __init__(self, recorder, trials):
        ShowBase.__init__(self)

        labels = gen_labels(trials)

        self._recorder = recorder
        self._labels = iter(labels)
        self._current_label = None

        cur_dir = os.path.abspath(sys.path[0])
        cur_dir = Filename.fromOsSpecific(cur_dir).getFullpath()

        self.pandaActor = Actor(cur_dir + "/emg/animation/Hand")
        scale = 10
        self.pandaActor.setScale(scale, scale, scale)
        self.pandaActor.reparentTo(self.render)

        self.taskMgr.add(self.spin_camera_task, "spin_camera_task")
        self.taskMgr.add(self.run_trial, "run_trial_task")

        self.pandaActor.setPos(7.9, 1.5, -14.5)
Exemplo n.º 49
0
    def set_obj(self, obj_path):
        obj_node = self.obj_node
        cast_shadow = self.cast_shadow

        if self.obj is not None:
            self.obj.remove_node()

        # Convert that to panda's unix-style notation.
        filepath = Filename.fromOsSpecific(obj_path).getFullpath()
        # load model and add to render root
        obj = base.loader.load_model(filepath, noCache=True)
        obj.reparent_to(obj_node)
        # scale to uinit sphere
        obj_bounds = obj_node.getBounds()
        obj.set_scale(1 / obj_bounds.radius)
        obj_bounds = obj_node.getBounds()
        obj.set_pos(-obj_bounds.center)
        if cast_shadow:
            obj.set_depth_offset(-1)

        self.obj = obj
Exemplo n.º 50
0
    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)
Exemplo n.º 51
0
    def addImage(self, image):
        """ Adds an image to the icon.  Returns False on failure, True on success.
        Only one image per size can be loaded, and the image size must be square. """

        if not isinstance(image, PNMImage):
            fn = image
            if not isinstance(fn, Filename):
                fn = Filename.fromOsSpecific(fn)

            image = PNMImage()
            if not image.read(fn):
                Icon.notify.warning("Image '%s' could not be read" % fn.getBasename())
                return False

        if image.getXSize() != image.getYSize():
            Icon.notify.warning("Ignoring image without square size")
            return False

        self.images[image.getXSize()] = image

        return True
Exemplo n.º 52
0
    def __init__(self, parent, customNodeMap={}, customExporterMap={}):

        DirectObject.__init__(self)

        fn = Filename.fromOsSpecific(os.path.dirname(__file__))
        fn.makeTrueCase()
        self.icon_dir = str(fn) + "/"
        loadPrcFileData("", f"model-path {self.icon_dir}")

        #
        # NODE VIEW
        #
        self.viewNP = aspect2d.attachNewNode("viewNP")
        self.viewNP.setScale(0.5)

        #
        # NODE MANAGER
        #
        self.nodeMgr = NodeManager(self.viewNP, customNodeMap)

        # Drag view
        self.mouseSpeed = 1
        self.mousePos = None
        self.startCameraMovement = False

        # Box select
        # variables to store the start and current pos of the mousepointer
        self.startPos = LPoint2f(0, 0)
        self.lastPos = LPoint2f(0, 0)
        # variables for the to be drawn box
        self.boxCardMaker = CardMaker("SelectionBox")
        self.boxCardMaker.setColor(1, 1, 1, 0.25)
        self.box = None

        #
        # MENU BAR
        #
        self.mainView = MainView(parent, customNodeMap, customExporterMap)

        self.enable_editor()
Exemplo n.º 53
0
    def test_loader_ai(self):
        store = DNAStorage()
        root = self.loader.loadDNAFileAI(store, Filename('test.pdna'))

        self.check_store(store)

        def check_name_class_and_children_count(comp,
                                                klass,
                                                name,
                                                num_children=1):
            self.assertEqual(comp.getName(), name)
            self.assertEqual(comp.__class__, klass)
            self.assertEqual(comp.getNumChildren(), num_children)

        check_name_class_and_children_count(root, DNAData, "root")

        test_group = root.at(0)
        check_name_class_and_children_count(test_group, DNAGroup, "test")

        test_visgroup = test_group.at(0)
        self.assertEqual(store.getDNAVisGroupAI(0), test_visgroup)
        check_name_class_and_children_count(test_visgroup, DNAVisGroup, "1000")

        test_subgroup = test_visgroup.at(0)
        check_name_class_and_children_count(test_subgroup,
                                            DNAGroup,
                                            "subgroup",
                                            num_children=2)

        test_prop = test_subgroup.at(0)
        check_name_class_and_children_count(test_prop,
                                            DNAProp,
                                            "prop_test",
                                            num_children=0)

        test_building = test_subgroup.at(1)
        check_name_class_and_children_count(test_building,
                                            DNALandmarkBuilding,
                                            "tb3:test_block",
                                            num_children=0)
Exemplo n.º 54
0
    def read_texture(self, filename, alpha=False):
        """
        Reads a texture from the model path.
        Throws a PalettizerException if file could not be found.
            :filename: Relative filename pointing to a texture file in the model path.
            :alpha: Do we need an alpha channel?
        """
        img = PNMImage()
        img.read(Filename.from_os_specific(filename))

        if alpha:
            needs_alpha_fill = img.num_channels not in (2, 4)
            img.set_color_type(4)

            if needs_alpha_fill:
                # We need an alpha channel no matter what, so if the image does not have one,
                # it needs to be filled immediately with opaque pixels as it starts out with transparent pixels
                img.alpha_fill(1)
        else:
            img.set_color_type(3)

        return img
Exemplo n.º 55
0
    def write_png(self, new_image, has_alpha, folder, phase_dir, basename):
        """
        Saves a previously palettized image as a PNG file.
            :new_image: The palettized image containing RGB data.
            :has_alpha: Does this image contain alpha data?
            :folder: The folder to save the image in.
            :phase_dir: The name of the phase folder containing the texture, for example: "phase_3"
            :basename: The filename of the image, for example: "avatar_palette_1mla_1"
        """
        # Create the folder if necessary.
        folder = os.path.join(folder, phase_dir, 'maps')

        if not os.path.exists(folder):
            os.makedirs(folder)

        palette_path = os.path.join(folder, basename.strip('.'))

        if not has_alpha:
            # We do not have any alpha pixels, it would be wise to remove the alpha channel
            new_image.remove_alpha()

        new_image.write(Filename.from_os_specific(f'{palette_path}.png'))
Exemplo n.º 56
0
    def checkStatus(self):
        """ Checks the current status of the desc file and the package
        contents on disk. """

        if self.hasPackage:
            return True

        if not self.hasDescFile:
            filename = Filename(self.getPackageDir(), self.descFileBasename)
            if self.descFile.quickVerify(self.getPackageDir(), pathname = filename, notify = self.notify):
                if self.__readDescFile():
                    # Successfully read.  We don't need to call
                    # checkArchiveStatus again, since readDescFile()
                    # has just done it.
                    return self.hasPackage

        if self.hasDescFile:
            if self.__checkArchiveStatus():
                # It's all good.
                self.hasPackage = True

        return self.hasPackage
Exemplo n.º 57
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    try:
        opts, args = getopt.getopt(argv[1:], "hn:bs",
                                   ["help", "normals", "binormals", "show"])
    except getopt.error as msg:
        print(msg)
        print(__doc__)

    show = False
    for (o, a) in opts:
        if o in ("-h", "--help"):
            print(__doc__)
        elif o in ("-s", "--show"):
            show = True

    for infile in args:
        obj = ObjFile(infile)
        egg = obj.toEgg()
        (f, e) = os.path.splitext(infile)
        outfile = f + ".egg"
        for o, a in opts:
            if o in ("-n", "--normals"):
                egg.recomputeVertexNormals(float(a))
            elif o in ("-b", "--binormals"):
                egg.recomputeTangentBinormal(GlobPattern(""))

        egg.removeUnusedVertices(GlobPattern(""))
        if True:
            egg.triangulatePolygons(EggData.TConvex & EggData.TPolygon)

        if True:
            egg.recomputePolygonNormals()

        egg.writeEgg(Filename(outfile))
        if show:
            os.system("pview " + outfile)
Exemplo n.º 58
0
    def loadXml(self, xelement):
        """ Reads the file information from the indicated XML
        element. """

        self.filename = xelement.Attribute('filename')
        self.basename = None
        if self.filename:
            self.basename = Filename(self.filename).getBasename()

        size = xelement.Attribute('size')
        try:
            self.size = int(size)
        except:
            self.size = 0

        timestamp = xelement.Attribute('timestamp')
        try:
            self.timestamp = int(timestamp)
        except:
            self.timestamp = 0

        self.hash = xelement.Attribute('hash')
Exemplo n.º 59
0
    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()

        # Use the tokenize module to detect the encoding.
        import tokenize
        fh = open(self.filename, 'rb')
        encoding, lines = tokenize.detect_encoding(fh.readline)
        return (b''.join(lines) + fh.read()).decode(encoding)
Exemplo n.º 60
0
    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()